repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
audrl1010/EasyMakePhotoPicker | Example/EasyMakePhotoPicker/TextView.swift | 1 | 4044 | //
// TextView.swift
// KaKaoChatInputView
//
// Created by smg on 2017. 5. 13..
// Copyright © 2017년 grutech. All rights reserved.
//
import UIKit
protocol HasPlaceholder {
var placeholderLabel: UILabel { get set }
}
class TextView: UITextView, HasPlaceholder {
// MARK - Properties
var heightDidChange: ((_ newHeight: CGFloat) -> Void)?
lazy var placeholderLabel = UILabel().then {
$0.clipsToBounds = false
$0.numberOfLines = 1
$0.font = self.font
$0.backgroundColor = .clear
$0.textColor = self.placeholderColor
$0.isHidden = true
$0.autoresizesSubviews = false
}
var expectedHeight: CGFloat = 0
var maxNumberOfLines: CGFloat = 0
var minimumHeight: CGFloat {
return ceil(font!.lineHeight) +
textContainerInset.top + textContainerInset.bottom
}
var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
var placeholderColor: UIColor = .gray {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override var font: UIFont? {
didSet { placeholderLabel.font = font }
}
override var contentSize: CGSize {
didSet { updateSize() }
}
// MARK: - View Life Cycle
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
addSubview(placeholderLabel)
isScrollEnabled = false
}
override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.isHidden = isHiddenPlaceholder
if !isHiddenPlaceholder {
placeholderLabel.frame = placeholderRectThatFits(bounds)
sendSubviewToBack(placeholderLabel)
}
}
// MARK - Public Methods
func textViewDidChange() {
placeholderLabel.isHidden = isHiddenPlaceholder
updateSize()
}
// MARK: - Helper Methods
fileprivate var isHiddenPlaceholder:Bool {
return placeholder.lengthOfBytes(using: .utf8) == 0
|| text.lengthOfBytes(using: .utf8) > 0
}
fileprivate func placeholderRectThatFits(_ rect: CGRect) -> CGRect {
var placeholderRect = CGRect.zero
placeholderRect.size = placeholderLabel.sizeThatFits(rect.size)
placeholderRect.origin =
rect.inset(by: textContainerInset).origin
let padding = textContainer.lineFragmentPadding
placeholderRect.origin.x += padding
return placeholderRect
}
fileprivate func ensureCaretDisplaysCorrectly() {
if let s = selectedTextRange {
let rect = caretRect(for: s.end)
UIView.performWithoutAnimation { [weak self] in
guard let `self` = self else { return }
self.scrollRectToVisible(rect, animated: false)
}
}
}
fileprivate func updateSize() {
var maxHeight = CGFloat.infinity
if maxNumberOfLines > 0 {
maxHeight = (ceil(font!.lineHeight) * maxNumberOfLines) +
textContainerInset.top + textContainerInset.bottom
}
let roundedHeight = roundHeight
if roundedHeight >= maxHeight {
expectedHeight = maxHeight
isScrollEnabled = true
}
else {
expectedHeight = roundedHeight
isScrollEnabled = false
}
if let heightDidChange = heightDidChange {
heightDidChange(expectedHeight)
}
ensureCaretDisplaysCorrectly()
}
fileprivate var roundHeight: CGFloat {
var newHeight = CGFloat(0)
if let font = font {
let attributes = [NSAttributedString.Key.font: font]
let boundingSize =
CGSize(width: frame.size.width, height: CGFloat.infinity)
let size =
(text as NSString).boundingRect(
with: boundingSize,
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: attributes, context: nil)
newHeight = ceil(size.height)
}
return newHeight + textContainerInset.top + textContainerInset.bottom
}
}
| mit | ffabf83dcfdc4624bcb66c33fe7ad955 | 23.490909 | 73 | 0.666419 | 4.856971 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Gifting/GiftCurrencyCell.swift | 1 | 3482 | //
// GiftCurrencyCell.swift
// breadwallet
//
// Created by Adrian Corscadden on 2020-12-08.
// Copyright © 2020 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import UIKit
class GiftCurrencyCell: UIView {
private let currency = Currencies.btc.instance!
private let iconContainer = UIView(color: .transparentIconBackground)
private let icon = UIImageView()
private let currencyName = UILabel(font: Theme.body1Accent, color: Theme.primaryText)
private let price = UILabel(font: Theme.body3, color: Theme.secondaryText)
private let fiatBalance = UILabel(font: Theme.body1Accent, color: Theme.primaryText)
private let tokenBalance = UILabel(font: Theme.body3, color: Theme.secondaryText)
private let rate: Double
private let amount: Double
init(rate: Double, amount: Double) {
self.rate = rate
self.amount = amount
super.init(frame: .zero)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
addSubviews()
addConstraints()
setInitialData()
}
private func addSubviews() {
addSubview(iconContainer)
iconContainer.addSubview(icon)
addSubview(currencyName)
addSubview(price)
addSubview(fiatBalance)
addSubview(tokenBalance)
}
private func addConstraints() {
iconContainer.constrain([
iconContainer.leadingAnchor.constraint(equalTo: leadingAnchor, constant: C.padding[1]),
iconContainer.centerYAnchor.constraint(equalTo: centerYAnchor),
iconContainer.heightAnchor.constraint(equalToConstant: 40),
iconContainer.widthAnchor.constraint(equalTo: iconContainer.heightAnchor)])
icon.constrain(toSuperviewEdges: .zero)
price.constrain([
price.leadingAnchor.constraint(equalTo: iconContainer.trailingAnchor, constant: C.padding[1]),
price.bottomAnchor.constraint(equalTo: iconContainer.bottomAnchor)])
currencyName.constrain([
currencyName.leadingAnchor.constraint(equalTo: price.leadingAnchor),
currencyName.bottomAnchor.constraint(equalTo: price.topAnchor, constant: 0.0)])
tokenBalance.constrain([
tokenBalance.bottomAnchor.constraint(equalTo: price.bottomAnchor),
tokenBalance.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -C.padding[2])])
fiatBalance.constrain([
fiatBalance.trailingAnchor.constraint(equalTo: tokenBalance.trailingAnchor),
fiatBalance.bottomAnchor.constraint(equalTo: tokenBalance.topAnchor)])
}
private func setInitialData() {
backgroundColor = currency.colors.0
layer.cornerRadius = 8.0
icon.image = currency.imageNoBackground
iconContainer.layer.cornerRadius = C.Sizes.homeCellCornerRadius
iconContainer.clipsToBounds = true
icon.tintColor = .white
let rateAmount = Amount(tokenString: "1", currency: currency)
price.text = rateAmount.fiatDescription
currencyName.text = "Bitcoin"
let displayAmount = Amount(tokenString: "\(amount)", currency: currency)
fiatBalance.text = displayAmount.fiatDescription
tokenBalance.text = displayAmount.tokenDescription
}
}
| mit | 3b4a06c397cebda6145cfa4d565511bc | 37.252747 | 106 | 0.679402 | 4.923621 | false | false | false | false |
austinzheng/swift | test/PrintAsObjC/imports.swift | 7 | 2045 | // Please keep this file in alphabetical order!
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -emit-module -o %t %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -parse-as-library %t/imports.swiftmodule -typecheck -emit-objc-header-path %t/imports.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/imports.h
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/imports.h
// RUN: %check-in-clang %t/imports.h -I %S/Inputs/custom-modules/ -F %S/Inputs/ -Watimport-in-framework-header
// REQUIRES: objc_interop
// CHECK: @import Base;
// CHECK-NEXT: @import Base.ExplicitSub;
// CHECK-NEXT: @import Base.ExplicitSub.ExSub;
// CHECK-NEXT: @import Base.ImplicitSub.ExSub;
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: @import MostlyPrivate1;
// CHECK-NEXT: @import MostlyPrivate1_Private;
// CHECK-NEXT: @import MostlyPrivate2_Private;
// CHECK-NEXT: @import ctypes.bits;
// NEGATIVE-NOT: ctypes;
// NEGATIVE-NOT: ImSub;
// NEGATIVE-NOT: ImplicitSub;
// NEGATIVE-NOT: MostlyPrivate2;
import ctypes.bits
import Foundation
import Base
import Base.ImplicitSub
import Base.ImplicitSub.ImSub
import Base.ImplicitSub.ExSub
import Base.ExplicitSub
import Base.ExplicitSub.ImSub
import Base.ExplicitSub.ExSub
import MostlyPrivate1
import MostlyPrivate1_Private
// Deliberately not importing MostlyPrivate2
import MostlyPrivate2_Private
@objc class Test {
@objc let word: DWORD = 0
@objc let number: TimeInterval = 0.0
@objc let baseI: BaseI = 0
@objc let baseII: BaseII = 0
@objc let baseIE: BaseIE = 0
@objc let baseE: BaseE = 0
@objc let baseEI: BaseEI = 0
@objc let baseEE: BaseEE = 0
// Deliberately use the private type before the public type.
@objc let mp1priv: MP1PrivateType = 0
@objc let mp1pub: MP1PublicType = 0
@objc let mp2priv: MP2PrivateType = 0
}
| apache-2.0 | 5cbedc45b3c11b3958eb8ac9d404b3df | 33.661017 | 279 | 0.735941 | 3.089124 | false | false | false | false |
vmachiel/swift | Calculator/Calculator/CalculatorBrain.swift | 1 | 6735 | //
// CalculatorBrain.swift
// Calculator
//
// Created by Machiel van Dorst on 25-07-17.
// Copyright © 2017 vmachiel. All rights reserved.
//
import Foundation
// What does this model allow PUBLICLY? What does it allow the controller to do?
// No need for inheritance. Will only be refferenced by one Controller. KISAS
struct CalculatorBrain {
// MARK: - Properties
// This will hold the current number, and the discription of the current operation.
private var accumulator: (acc: Double, des: String)?
// Called by the viewController when operation is pressed to set operand. Set the acc to the
// operand double and string disciption like:
mutating func setOperand(_ operand: Double) {
accumulator = (operand, "\(operand)")
}
// Returns the result to ViewController.
var result: Double? {
get {
if accumulator != nil {
// Return the actual number, force because checked.
return accumulator!.acc
}
return nil
}
}
var description: String? {
get{
if resultIsPending {
return pendingBinaryOperation!.description(pendingBinaryOperation!.firstOperand.1, accumulator?.1 ?? "")
} else {
return accumulator?.des
}
}
}
// MARK: - Basic operation
// What does each operation look like, and what does eacht discription look like.
// They discription functions can be used to build the string.
private enum Operation {
case constant(Double)
case unaryOperation((Double) -> Double, (String) -> String)
case binaryOperation((Double, Double) -> Double, (String, String) -> String)
case nullaryOperation(() -> Double, String)
case equals
}
// Dict built using the Operation enum. Constants can built in functions are used,
// as well as closures to perform the actual operations and build de description
// strings.
// It knows which $ should be doubles and which should be string because you
// defined it in the Operation enum.
// In the description case, the new stuff is constantly added to the existing des-
// cription!!!
private var operations: Dictionary<String, Operation> = [
"π" : Operation.constant(Double.pi),
"e" : Operation.constant(M_E),
"√" : Operation.unaryOperation(sqrt, { "√(" + $0 + ")" }),
"x²" : Operation.unaryOperation({ pow($0, 2) }, { "(" + $0 + ")²" }),
"x³" : Operation.unaryOperation({ pow($0, 3) }, { "(" + $0 + ")³" }),
"eˣ" : Operation.unaryOperation(exp, { "e^(" + $0 + ")" }),
"cos" : Operation.unaryOperation(cos, { "cos(" + $0 + ")" }),
"sin" : Operation.unaryOperation(sin, { "sin(" + $0 + ")" }),
"tan" : Operation.unaryOperation(tan, { "tan(" + $0 + ")" }),
"±" : Operation.unaryOperation({ -$0 }, { "-(" + $0 + ")" }),
"1/x" : Operation.unaryOperation({ 1/$0 }, { "1/(" + $0 + ")" } ),
"ln" : Operation.unaryOperation(log2, { "ln(" + $0 + ")" }),
"log" : Operation.unaryOperation(log10, { "log(" + $0 + ")" }),
"x" : Operation.binaryOperation({ $0 * $1 }, { $0 + "x" + $1 }),
"÷" : Operation.binaryOperation({ $0 / $1 }, { $0 + "÷" + $1 }),
"+" : Operation.binaryOperation({ $0 + $1 }, { $0 + "+" + $1 }),
"-" : Operation.binaryOperation({ $0 - $1 }, { $0 + "-" + $1 }),
"xʸ" : Operation.binaryOperation(pow, { $0 + "^" + $1 }),
"Rand" : Operation.nullaryOperation({ Double(arc4random()) / Double(UInt32.max) }, "rand()"),
"=" : Operation.equals
]
// Gets called when an operator button is pressed.
// Checks the operations dict for a key match, and passes the value to
// operation parameter. Uses its enums ass. value to perform the action and
// add description to the accumulator.
mutating func performOperation(_ symbol: String) {
if let operation = operations[symbol] {
switch operation {
// Constant? set it to the accumulator, so the ViewController can
// get it back to the display. Save the symbol as well.
case .constant(let value):
accumulator = (value, symbol)
case .unaryOperation(let function, let description):
if accumulator != nil {
accumulator = (function(accumulator!.acc), description(accumulator!.des))
// force! already nil checked
}
// Again, the ass values of the enum stored in the dict value can be set to constants.
case .binaryOperation(let function, let description):
if accumulator != nil {
pendingBinaryOperation = PendingBinaryOperation(function: function, description: description, firstOperand: accumulator!)
accumulator = nil
}
case .equals:
performPendingBinaryOperation()
case .nullaryOperation(let function, let description):
accumulator = (function(), description)
}
}
}
// MARK: - Pending operation
// Takes a operation, a description to add to the description string, and a accumulator to
// set to the first operand. Is nil if nothing pending.
private var pendingBinaryOperation: PendingBinaryOperation?
private struct PendingBinaryOperation {
// Store the acutal function, the description and the current (operand, description)
let function: (Double, Double) -> Double // What binary op is being done? (passed by closure)
let description: (String, String) -> String
let firstOperand: (Double, String)
// Called when the second operand is set and equals is passed
func perform(with secondOperand: (Double, String)) -> (Double, String) {
return (function(firstOperand.0, secondOperand.0), description(firstOperand.1, secondOperand.1))
}
}
// Is there a result pending? Checks if the pendingBinaryOperation var has data
var resultIsPending: Bool {
get {
return pendingBinaryOperation != nil
}
}
// If it does have data and equals is pressed and there is a new number in the accumulator,
// call its perform method.
mutating private func performPendingBinaryOperation() {
if pendingBinaryOperation != nil && accumulator != nil {
accumulator = pendingBinaryOperation!.perform(with: accumulator!)
pendingBinaryOperation = nil
}
}
}
| mit | 080768cdb7cb1531f2462bdf0d1602fb | 40.481481 | 141 | 0.589583 | 4.546685 | false | false | false | false |
william86370/fcps-alerts | FCPS Alert/SwiftSpinner.swift | 1 | 15969 | //
// SwiftSpinner.swift
// FCPS Alert
//
// Created by William Wright on 11/16/16.
// Copyright © 2016 A.R.C software and enginering. All rights reserved.
import UIKit
public class SwiftSpinner: UIView {
// MARK: - Singleton
//
// Access the singleton instance
//
public class var sharedInstance: SwiftSpinner {
struct Singleton {
static let instance = SwiftSpinner(frame: CGRect.zero)
}
return Singleton.instance
}
// MARK: - Init
//
// Custom init to build the spinner UI
//
public override init(frame: CGRect) {
super.init(frame: frame)
blurEffect = UIBlurEffect(style: blurEffectStyle)
blurView = UIVisualEffectView(effect: blurEffect)
addSubview(blurView)
vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
addSubview(vibrancyView)
let titleScale: CGFloat = 0.85
titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale)
titleLabel.font = defaultTitleFont
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textColor = UIColor.white
blurView.contentView.addSubview(titleLabel)
blurView.contentView.addSubview(vibrancyView)
outerCircleView.frame.size = frameSize
outerCircle.path = UIBezierPath(ovalIn: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).cgPath
outerCircle.lineWidth = 8.0
outerCircle.strokeStart = 0.0
outerCircle.strokeEnd = 0.45
outerCircle.lineCap = kCALineCapRound
outerCircle.fillColor = UIColor.clear.cgColor
outerCircle.strokeColor = outerCircleDefaultColor
outerCircleView.layer.addSublayer(outerCircle)
outerCircle.strokeStart = 0.0
outerCircle.strokeEnd = 1.0
blurView.contentView.addSubview(outerCircleView)
innerCircleView.frame.size = frameSize
let innerCirclePadding: CGFloat = 12
innerCircle.path = UIBezierPath(ovalIn: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).cgPath
innerCircle.lineWidth = 4.0
innerCircle.strokeStart = 0.5
innerCircle.strokeEnd = 0.9
innerCircle.lineCap = kCALineCapRound
innerCircle.fillColor = UIColor.clear.cgColor
innerCircle.strokeColor = innerCircleDefaultColor
innerCircleView.layer.addSublayer(innerCircle)
innerCircle.strokeStart = 0.0
innerCircle.strokeEnd = 1.0
blurView.contentView.addSubview(innerCircleView)
isUserInteractionEnabled = true
}
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return self
}
// MARK: - Public interface
public lazy var titleLabel = UILabel()
public var subtitleLabel: UILabel?
private let outerCircleDefaultColor = UIColor.white.cgColor
fileprivate var _outerColor: UIColor?
public var outerColor: UIColor? {
get { return _outerColor }
set(newColor) {
_outerColor = newColor
outerCircle.strokeColor = newColor?.cgColor ?? outerCircleDefaultColor
}
}
private let innerCircleDefaultColor = UIColor.gray.cgColor
fileprivate var _innerColor: UIColor?
public var innerColor: UIColor? {
get { return _innerColor }
set(newColor) {
_innerColor = newColor
innerCircle.strokeColor = newColor?.cgColor ?? innerCircleDefaultColor
}
}
//
// Custom superview for the spinner
//
private static weak var customSuperview: UIView? = nil
private static func containerView() -> UIView? {
return customSuperview ?? UIApplication.shared.keyWindow
}
public class func useContainerView(_ sv: UIView?) {
customSuperview = sv
}
//
// Show the spinner activity on screen, if visible only update the title
//
@discardableResult
public class func show(_ title: String, animated: Bool = true) -> SwiftSpinner {
let spinner = SwiftSpinner.sharedInstance
spinner.clearTapHandler()
spinner.updateFrame()
if spinner.superview == nil {
//show the spinner
spinner.alpha = 0.0
guard let containerView = containerView() else {
fatalError("\n`UIApplication.keyWindow` is `nil`. If you're trying to show a spinner from your view controller's `viewDidLoad` method, do that from `viewWillAppear` instead. Alternatively use `useContainerView` to set a view where the spinner should show")
}
containerView.addSubview(spinner)
UIView.animate(withDuration: 0.33, delay: 0.0, options: .curveEaseOut, animations: {
spinner.alpha = 1.0
}, completion: nil)
#if os(iOS)
// Orientation change observer
NotificationCenter.default.addObserver(
spinner,
selector: #selector(SwiftSpinner.updateFrame),
name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation,
object: nil)
#endif
}
spinner.title = title
spinner.animating = animated
return spinner
}
//
// Show the spinner activity on screen with duration, if visible only update the title
//
@discardableResult
public class func show(duration: Double, title: String, animated: Bool = true) -> SwiftSpinner {
let spinner = SwiftSpinner.show(title, animated: animated)
spinner.delay(duration) {
SwiftSpinner.hide()
}
return spinner
}
private static var delayedTokens = [String]()
//
// Show the spinner activity on screen, after delay. If new call to show,
// showWithDelay or hide is maked before execution this call is discarded
//
@discardableResult
public class func show(delay: Double, title: String, animated: Bool = true) {
let token = UUID().uuidString
delayedTokens.append(token)
SwiftSpinner.sharedInstance.delay(delay, completion: {
if let index = delayedTokens.index(of: token) {
delayedTokens.remove(at: index)
_ = SwiftSpinner.show(title, animated: animated)
}
})
}
///
/// Show the spinner with the outer circle representing progress (0 to 1)
///
@discardableResult
public class func show(progress: Double, title: String) -> SwiftSpinner {
let spinner = SwiftSpinner.show(title, animated: false)
spinner.outerCircle.strokeEnd = CGFloat(progress)
return spinner
}
//
// Hide the spinner
//
public static var hideCancelsScheduledSpinners = true
public class func hide(_ completion: (() -> Void)? = nil) {
let spinner = SwiftSpinner.sharedInstance
NotificationCenter.default.removeObserver(spinner)
if hideCancelsScheduledSpinners {
delayedTokens.removeAll()
}
DispatchQueue.main.async(execute: {
spinner.clearTapHandler()
if spinner.superview == nil {
return
}
UIView.animate(withDuration: 0.33, delay: 0.0, options: .curveEaseOut, animations: {
spinner.alpha = 0.0
}, completion: {_ in
spinner.alpha = 1.0
spinner.removeFromSuperview()
spinner.titleLabel.font = spinner.defaultTitleFont
spinner.titleLabel.text = nil
completion?()
})
spinner.animating = false
})
}
//
// Set the default title font
//
public class func setTitleFont(_ font: UIFont?) {
let spinner = SwiftSpinner.sharedInstance
if let font = font {
spinner.titleLabel.font = font
} else {
spinner.titleLabel.font = spinner.defaultTitleFont
}
}
//
// The spinner title
//
public var title: String = "" {
didSet {
let spinner = SwiftSpinner.sharedInstance
guard spinner.animating else {
spinner.titleLabel.transform = CGAffineTransform.identity
spinner.titleLabel.alpha = 1.0
spinner.titleLabel.text = self.title
return
}
UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut, animations: {
spinner.titleLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
spinner.titleLabel.alpha = 0.2
}, completion: {_ in
spinner.titleLabel.text = self.title
UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: [], animations: {
spinner.titleLabel.transform = CGAffineTransform.identity
spinner.titleLabel.alpha = 1.0
}, completion: nil)
})
}
}
//
// observe the view frame and update the subviews layout
//
public override var frame: CGRect {
didSet {
if frame == CGRect.zero {
return
}
blurView.frame = bounds
vibrancyView.frame = blurView.bounds
titleLabel.center = vibrancyView.center
outerCircleView.center = vibrancyView.center
innerCircleView.center = vibrancyView.center
if let subtitle = subtitleLabel {
subtitle.bounds.size = subtitle.sizeThatFits(bounds.insetBy(dx: 20.0, dy: 0.0).size)
subtitle.center = CGPoint(x: bounds.midX, y: bounds.maxY - subtitle.bounds.midY - subtitle.font.pointSize)
}
}
}
//
// Start the spinning animation
//
public var animating: Bool = false {
willSet (shouldAnimate) {
if shouldAnimate && !animating {
spinInner()
spinOuter()
}
}
didSet {
// update UI
if animating {
self.outerCircle.strokeStart = 0.0
self.outerCircle.strokeEnd = 0.45
self.innerCircle.strokeStart = 0.5
self.innerCircle.strokeEnd = 0.9
} else {
self.outerCircle.strokeStart = 0.0
self.outerCircle.strokeEnd = 1.0
self.innerCircle.strokeStart = 0.0
self.innerCircle.strokeEnd = 1.0
}
}
}
//
// Tap handler
//
public func addTapHandler(_ tap: @escaping (()->()), subtitle subtitleText: String? = nil) {
clearTapHandler()
//vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner")))
tapHandler = tap
if subtitleText != nil {
subtitleLabel = UILabel()
if let subtitle = subtitleLabel {
subtitle.text = subtitleText
subtitle.font = UIFont(name: defaultTitleFont.familyName, size: defaultTitleFont.pointSize * 0.8)
subtitle.textColor = UIColor.white
subtitle.numberOfLines = 0
subtitle.textAlignment = .center
subtitle.lineBreakMode = .byWordWrapping
subtitle.bounds.size = subtitle.sizeThatFits(bounds.insetBy(dx: 20.0, dy: 0.0).size)
subtitle.center = CGPoint(x: bounds.midX, y: bounds.maxY - subtitle.bounds.midY - subtitle.font.pointSize)
vibrancyView.contentView.addSubview(subtitle)
}
}
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if tapHandler != nil {
tapHandler?()
tapHandler = nil
}
}
public func clearTapHandler() {
isUserInteractionEnabled = false
subtitleLabel?.removeFromSuperview()
tapHandler = nil
}
// MARK: - Private interface
//
// layout elements
//
private var blurEffectStyle: UIBlurEffectStyle = .dark
private var blurEffect: UIBlurEffect!
private var blurView: UIVisualEffectView!
private var vibrancyView: UIVisualEffectView!
var defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)!
let frameSize = CGSize(width: 200.0, height: 200.0)
private lazy var outerCircleView = UIView()
private lazy var innerCircleView = UIView()
private let outerCircle = CAShapeLayer()
private let innerCircle = CAShapeLayer()
required public init?(coder aDecoder: NSCoder) {
fatalError("Not coder compliant")
}
private var currentOuterRotation: CGFloat = 0.0
private var currentInnerRotation: CGFloat = 0.1
private func spinOuter() {
if superview == nil {
return
}
let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5
let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * M_PI_4 + M_PI_4
//outer circle
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: {
self.currentOuterRotation -= CGFloat(randomRotation)
self.outerCircleView.transform = CGAffineTransform(rotationAngle: self.currentOuterRotation)
}, completion: {_ in
let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0
self.delay(waitDuration, completion: {
if self.animating {
self.spinOuter()
}
})
})
}
private func spinInner() {
if superview == nil {
return
}
//inner circle
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: {
self.currentInnerRotation += CGFloat(M_PI_4)
self.innerCircleView.transform = CGAffineTransform(rotationAngle: self.currentInnerRotation)
}, completion: {_ in
self.delay(0.5, completion: {
if self.animating {
self.spinInner()
}
})
})
}
public func updateFrame() {
if let containerView = SwiftSpinner.containerView() {
SwiftSpinner.sharedInstance.frame = containerView.bounds
}
}
// MARK: - Util methods
func delay(_ seconds: Double, completion:@escaping ()->()) {
let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * seconds )) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime) {
completion()
}
}
override public func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
// MARK: - Tap handler
private var tapHandler: (()->())?
func didTapSpinner() {
tapHandler?()
}
}
| gpl-3.0 | 25405f37e4653cf3da1aa93f0b702a6b | 33.046908 | 272 | 0.585859 | 5.273448 | false | false | false | false |
ansinlee/meteorology | meteorology/BBSReply.swift | 1 | 1144 | //
// BBSReply.swift
// meteorology
//
// Created by LeeAnsin on 15/6/14.
// Copyright (c) 2015年 LeeAnsin. All rights reserved.
//
import Foundation
class Reply {
var Id: Int32?
var TopicId: Int32?
var Time: String?
var Creator: User?
var Content:String?
init(id: Int32?, topicid: Int32?, time:String?, creator:User?, content: String?) {
self.Id = id
self.TopicId = topicid
self.Time = time
self.Creator = creator
self.Content = content
}
init(t: Reply) {
self.Id = t.Id
self.TopicId = t.TopicId
self.Time = t.Time
self.Creator = t.Creator
self.Content = t.Content
}
init(data:AnyObject?) {
if data == nil {
return
}
self.Id = (data?.objectForKey("Id") as! NSNumber).intValue
self.TopicId = (data?.objectForKey("Topicid") as! NSNumber).intValue
self.Time = GetGoDate(data?.objectForKey("Createtime") as! String)
self.Content = data?.objectForKey("Content") as? String
self.Creator = User(data: data?.objectForKey("Creator"))
}
}
| apache-2.0 | fb4f432cf268f5d0479503e77aae8b6b | 24.954545 | 86 | 0.58056 | 3.660256 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/GenderOrText.swift | 1 | 1279 | import Foundation
public enum GenderOrText: Codable, Equatable {
case gender(value: Gender)
case text(value: String)
public init(_ value: Gender) {
self = .gender(value: value)
}
public init(_ value: String) {
self = .text(value: value)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
if let gender = Gender(rawValue: value) {
self = .gender(value: gender)
} else {
self = .text(value: value)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .gender(let value):
try container.encode(value)
case .text(let value):
try container.encode(value)
}
}
public var gender: Gender? {
switch self {
case .gender(let value):
return value
default:
return nil
}
}
public var text: String? {
switch self {
case .text(let value):
return value
default:
return nil
}
}
}
| mit | d38181aa51ccb1be59e6e75096b2ff71 | 22.685185 | 58 | 0.526974 | 4.667883 | false | false | false | false |
thisfin/IconfontPreview | IconfontPreview/TTFDocument.swift | 1 | 1157 | //
// TTFDocument.swift
// IconfontPreview
//
// Created by wenyou on 2017/6/29.
// Copyright © 2017年 wenyou. All rights reserved.
//
import AppKit
class TTFDocument: NSDocument {
private var tempFontManager: FontManager?
override func makeWindowControllers() {
guard let fontManager = tempFontManager else {
return
}
let window = NSWindow(contentRect: .zero, styleMask: [.closable, .resizable, .miniaturizable, .titled], backing: .buffered, defer: false).next {
$0.minSize = NSMakeSize(400, 300)
$0.isRestorable = false
$0.contentViewController = ShowViewController().next {
$0.fontManager = fontManager
}
$0.center()
}
addWindowController(WindowController(window: window).next {
$0.titleName = fontManager.fontName
})
}
// 写文件时用
override func data(ofType typeName: String) throws -> Data {
return Data()
}
// 读文件
override func read(from url: URL, ofType typeName: String) throws {
tempFontManager = FontManager(url: url)
}
}
| mit | 6b9e150564245dc9508b59af85f43633 | 26.095238 | 152 | 0.609842 | 4.262172 | false | false | false | false |
minimoog/filters | filters/ChromaticAbberation.swift | 1 | 3133 | //
// ChromaticAbberation.swift
// filters
//
// Created by Toni Jovanoski on 2/9/17.
// Copyright © 2017 Antonie Jovanoski. All rights reserved.
//
import Foundation
import CoreImage
import CoreGraphics
let tau = CGFloat(M_PI * 2)
class ChromaticAbberation: CIFilter {
var inputImage: CIImage?
var inputAngle: CGFloat = 0
var inputRadius: CGFloat = 2
let rgbChannelCompositing = RGBChannelCompositing()
override func setDefaults() {
inputAngle = 0
inputRadius = 2
}
override var attributes: [String : Any] {
return [
kCIAttributeFilterDisplayName: "Chromatic Abberation",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputAngle": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Angle",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: tau,
kCIAttributeType: kCIAttributeTypeScalar],
"inputRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 25,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
override var outputImage: CIImage? {
guard let inputImage = inputImage else {
return nil
}
let redAngle = inputAngle + tau
let greenAngle = inputAngle + tau * 0.333
let blueAngle = inputAngle + tau * 0.666
let redTransform = CGAffineTransform(translationX: sin(redAngle) * inputRadius, y: cos(redAngle) * inputRadius)
let greenTransform = CGAffineTransform(translationX: sin(greenAngle) * inputRadius, y: cos(greenAngle) * inputRadius)
let blueTransform = CGAffineTransform(translationX: sin(blueAngle) * inputRadius, y: cos(blueAngle) * inputRadius)
let red = inputImage.applyingFilter("CIAffineTransform", withInputParameters: [kCIInputTransformKey: NSValue(cgAffineTransform: redTransform)]).cropping(to: inputImage.extent)
let green = inputImage.applyingFilter("CIAffineTransform", withInputParameters: [kCIInputTransformKey: NSValue(cgAffineTransform: greenTransform)]).cropping(to: inputImage.extent)
let blue = inputImage.applyingFilter("CIAffineTransform", withInputParameters: [kCIInputTransformKey: NSValue(cgAffineTransform: blueTransform)]).cropping(to: inputImage.extent)
rgbChannelCompositing.inputRedImage = red
rgbChannelCompositing.inputGreenImage = green
rgbChannelCompositing.inputBlueImage = blue
return rgbChannelCompositing.outputImage
}
}
| mit | 726f1e8a2cd31f0169b460f993682062 | 37.195122 | 187 | 0.639847 | 5.65343 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/Color.swift | 1 | 1839 | //
// Color.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML Color
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="color" type="kml:colorType" default="ffffffff"/>
public class Color:SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName:String = "color"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as BalloonStyle: v.value.color = self
case let v as IconStyle: v.value.color = self
case let v as LabelStyle: v.value.color = self
case let v as LineStyle: v.value.color = self
case let v as PolyStyle: v.value.color = self
case let v as PhotoOverlay :v.value.color = self
case let v as ScreenOverlay:v.value.color = self
default: break
}
}
}
}
public var value: String = "ffffffff"
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
}
// <simpleType name="colorType">
// <annotation>
// <documentation><![CDATA[
//
// aabbggrr
//
// ffffffff: opaque white
// ff000000: opaque black
//
// ]]></documentation>
// </annotation>
// <restriction base="hexBinary">
// <length value="4"/>
// </restriction>
// </simpleType>
public class colorType {
var value:String!
}
| mit | 859a2067f24741c95b99212b9622bd7b | 27.741935 | 83 | 0.592031 | 3.807692 | false | false | false | false |
vnu/vTweetz | vTweetz/TweetViewController.swift | 1 | 5777 | //
// TweetViewController.swift
// vTweetz
//
// Created by Vinu Charanya on 2/20/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
import ActiveLabel
class TweetViewController: UIViewController {
var tweet: Tweet!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var tweetedAtLabel: UILabel!
@IBOutlet weak var tweetActionImage: UIImageView!
@IBOutlet weak var tweetActionLabel: UILabel!
@IBOutlet weak var tweetTextLabel: ActiveLabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var retweetLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var tweetActionView: UIStackView!
@IBOutlet weak var mediaHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var mediaImage: UIImageView!
let retweetImage = UIImage(named: "retweet-action-on")
let unretweetImage = UIImage(named: "retweet-action")
let likeImage = UIImage(named: "like-action-on")
let unlikeImage = UIImage(named: "like-action")
let replyImage = UIImage(named: "reply-action_0")
let detailComposeSegueId = "tweetDetailComposeSegue"
override func viewDidLoad() {
super.viewDidLoad()
setUpTweet()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTweetAction(){
if let retweetBy = tweet.retweetedBy{
tweetActionView.hidden = false
tweetActionImage.image = unretweetImage
tweetActionLabel.text = "\(retweetBy) Retweeted"
}else if let inReplyto = tweet.inReplyto{
tweetActionView.hidden = false
tweetActionImage.image = replyImage
tweetActionLabel.text = "In reply to @\(inReplyto)"
}
else{
tweetActionView.hidden = true
}
}
func addMediaImage(){
if let mediaUrl = tweet.mediaUrl{
mediaImage.setImageWithURL(NSURL(string: mediaUrl)!)
mediaImage.hidden = false
mediaImage.clipsToBounds = true
mediaHeightConstraint.constant = 240
}else{
mediaImage.hidden = true
mediaHeightConstraint.constant = 0
}
}
func setUpTweet(){
if let tweet = self.tweet{
nameLabel.text = tweet.user!.name!
screenNameLabel.text = "@\(tweet.user!.screenName!)"
tweetedAtLabel.text = tweet.tweetedAt!
retweetLabel.text = "\(tweet.retweetCount!)"
likeLabel.text = "\(tweet.likeCount!)"
profileImage.setImageWithURL(NSURL(string: (tweet.user?.profileImageUrl)!)!)
setTweetText()
setLikeImage(!tweet.liked!)
setRetweetImage(!tweet.retweeted!)
setTweetAction()
addMediaImage()
}
}
func setTweetText(){
tweetTextLabel.URLColor = twitterDarkBlue
tweetTextLabel.hashtagColor = twitterDarkBlue
tweetTextLabel.mentionColor = twitterDarkBlue
tweetTextLabel.text = tweet.text!
tweetTextLabel.handleURLTap { (url: NSURL) -> () in
UIApplication.sharedApplication().openURL(url)
}
}
func setRetweetImage(retweeted: Bool){
if retweeted{
self.retweetButton.setImage(unretweetImage, forState: .Normal)
}else{
self.retweetButton.setImage(retweetImage, forState: .Normal)
}
}
func setLikeImage(liked: Bool){
if liked{
self.likeButton.setImage(unlikeImage, forState: .Normal)
}else{
self.likeButton.setImage(likeImage, forState: .Normal)
}
}
@IBAction func onRetweet(sender: AnyObject) {
if let retweeted = tweet.retweeted{
if retweeted{
self.retweetLabel.text = "\(Int(self.retweetLabel.text!)! - 1)"
}else{
self.retweetLabel.text = "\(Int(self.retweetLabel.text!)! + 1)"
}
setRetweetImage(retweeted)
}
tweet.retweet()
}
@IBAction func onLike(sender: AnyObject) {
if let liked = tweet.liked{
if liked{
self.likeLabel.text = "\(Int(self.likeLabel.text!)! - 1)"
}else{
self.likeLabel.text = "\(Int(self.likeLabel.text!)! + 1)"
}
setLikeImage(liked)
}
tweet.like()
}
@IBAction func onReply(sender: AnyObject) {
self.performSegueWithIdentifier(self.detailComposeSegueId, sender: self)
}
//Segue into Detail View
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == detailComposeSegueId {
if let destination = segue.destinationViewController as? ComposeViewController {
destination.fromTweet = self.tweet
destination.toScreenNames = ["@\(self.tweet.user!.screenName!)"]
destination.hidesBottomBarWhenPushed = true
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 639d358666d7a0fb9c033d3700f05757 | 31.088889 | 106 | 0.612708 | 4.866049 | false | false | false | false |
mak-it/makit-utils-ios | MakitUtils/CLLocationCoordinate2D.swift | 1 | 1088 | //
// location.swift
// viva
//
// Created by Uldis Zingis on 09/02/2017.
// Copyright © 2017 makit. All rights reserved.
//
import UIKit
import CoreLocation
import RxSwift
extension CLLocationCoordinate2D {
public func getLocationAdressString() -> Observable<String?> {
return Observable.create({ (observer) -> Disposable in
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(CLLocation(latitude: self.latitude, longitude: self.longitude)) { (placemarks, err) in
if let error = err {
observer.onError(error)
} else {
let placemark = placemarks?.first
let components = [placemark?.thoroughfare, placemark?.subThoroughfare, placemark?.locality].compactMap{$0}
let locationString = components.joined(separator: ", ")
observer.onNext(locationString)
observer.onCompleted()
}
}
return Disposables.create { }
})
}
}
| mit | b648c8283ee835890a086d689f87075c | 32.96875 | 130 | 0.575897 | 5.151659 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/Views/Title/Thread/ThreadRoomTitleView.swift | 1 | 4378 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Reusable
enum ThreadRoomTitleViewMode {
case allThreads
case specificThread(threadId: String)
}
@objcMembers
class ThreadRoomTitleView: RoomTitleView {
var mode: ThreadRoomTitleViewMode = .allThreads {
didSet {
update()
}
}
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var roomAvatarView: RoomAvatarView!
@IBOutlet private weak var roomEncryptionBadgeView: UIImageView!
@IBOutlet private weak var roomNameLabel: UILabel!
// MARK: - Methods
func configure(withModel model: ThreadRoomTitleModel) {
if let avatarViewData = model.roomAvatar {
roomAvatarView.fill(with: avatarViewData)
} else {
roomAvatarView.avatarImageView.image = nil
}
roomEncryptionBadgeView.image = model.roomEncryptionBadge
roomEncryptionBadgeView.isHidden = model.roomEncryptionBadge == nil
roomNameLabel.text = model.roomDisplayName
}
// MARK: - Overrides
override var mxRoom: MXRoom! {
didSet {
update()
}
}
override class func nib() -> UINib! {
return self.nib
}
override func refreshDisplay() {
guard let room = mxRoom else {
// room not initialized yet
return
}
let avatarViewData = AvatarViewData(matrixItemId: room.matrixItemId,
displayName: room.displayName,
avatarUrl: room.mxContentUri,
mediaManager: room.mxSession.mediaManager,
fallbackImage: AvatarFallbackImage.matrixItem(room.matrixItemId,
room.displayName))
let encrpytionBadge: UIImage?
if let summary = room.summary, summary.isEncrypted, room.mxSession.crypto != nil {
encrpytionBadge = EncryptionTrustLevelBadgeImageHelper.roomBadgeImage(for: summary.roomEncryptionTrustLevel())
} else {
encrpytionBadge = nil
}
let model = ThreadRoomTitleModel(roomAvatar: avatarViewData,
roomEncryptionBadge: encrpytionBadge,
roomDisplayName: room.displayName)
configure(withModel: model)
}
override func awakeFromNib() {
super.awakeFromNib()
update(theme: ThemeService.shared().theme)
registerThemeServiceDidChangeThemeNotification()
}
// MARK: - Private
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self,
selector: #selector(themeDidChange),
name: .themeServiceDidChangeTheme,
object: nil)
}
private func update() {
switch mode {
case .allThreads:
titleLabel.text = VectorL10n.threadsTitle
case .specificThread:
titleLabel.text = VectorL10n.roomThreadTitle
}
}
// MARK: - Actions
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
}
extension ThreadRoomTitleView: NibLoadable {}
extension ThreadRoomTitleView: Themable {
func update(theme: Theme) {
roomAvatarView.backgroundColor = .clear
titleLabel.textColor = theme.colors.primaryContent
roomNameLabel.textColor = theme.colors.secondaryContent
}
}
| apache-2.0 | 4ffdf2dc0982242f5a2da1512b1fdfcc | 31.917293 | 122 | 0.595706 | 5.438509 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/Styles/Bubble/Cells/Poll/Outgoing/PollOutgoingWithoutSenderInfoBubbleCell.swift | 1 | 1603 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class PollOutgoingWithoutSenderInfoBubbleCell: PollBaseBubbleCell, BubbleOutgoingRoomCellProtocol {
override func setupViews() {
super.setupViews()
roomCellContentView?.showSenderInfo = false
let leftMargin: CGFloat = BubbleRoomCellLayoutConstants.outgoingBubbleBackgroundMargins.left + BubbleRoomCellLayoutConstants.pollBubbleBackgroundInsets.left
let rightMargin: CGFloat = BubbleRoomCellLayoutConstants.outgoingBubbleBackgroundMargins.right + BubbleRoomCellLayoutConstants.pollBubbleBackgroundInsets.right
roomCellContentView?.innerContentViewTrailingConstraint.constant = rightMargin
roomCellContentView?.innerContentViewLeadingConstraint.constant = leftMargin
self.setupBubbleDecorations()
}
override func update(theme: Theme) {
super.update(theme: theme)
self.bubbleBackgroundColor = theme.roomCellOutgoingBubbleBackgroundColor
}
}
| apache-2.0 | 73880fba5811500fdc7bd133e42f7cdc | 39.075 | 167 | 0.746725 | 5.187702 | false | false | false | false |
DigitalRogues/FRDLivelyButton-Swift | FRDLivelyButton-Swift/FRDLivelyButtonObject.swift | 1 | 585 | //
// FRDButtonObject.swift
// Last Layer
//
// Created by punk on 11/9/16.
//
//
import UIKit
class FRDLivelyButtonObject: NSObject {
var kFRDLivelyButtonHighlightScale: CGFloat = 0.9
var kFRDLivelyButtonLineWidth: CGFloat = 2.0
var kFRDLivelyButtonColor: CGColor = UIColor.white.cgColor
var kFRDLivelyButtonHighlightedColor: CGColor = UIColor.lightGray.cgColor
var kFRDLivelyButtonHighlightAnimationDuration: Double = 0.1
var kFRDLivelyButtonUnHighlightAnimationDuration: Double = 0.15
var kFRDLivelyButtonStyleChangeAnimationDuration:Double = 0.3
}
| mit | 87ac0feb12ca54c14900106497e72d2b | 29.789474 | 77 | 0.77265 | 3.702532 | false | false | false | false |
mayongl/CS193P | Smashtag/Smashtag/AppDelegate.swift | 1 | 4635 | //
// AppDelegate.swift
// foo
//
// Created by Yonglin Ma on 4/20/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Smash")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | 6563d25e8c45aa30a2f0e11ef694125a | 48.827957 | 285 | 0.6776 | 5.910714 | false | false | false | false |
RobotRebels/SwiftLessons | students_trashspace/Den/HW3.playground/Contents.swift | 1 | 2267 | //: Playground - noun: a place where people can play
import UIKit
protocol GeometryProtocol {
func calcPerimeter() -> Float // метод рассчитывающий периметр фигуры
func calcArea() -> Float // метод рассчитывающий площадь фигуры
}
protocol AxisProtocol {
var centerX: Int {get set} // координата центра фигуры на оси X
var centerY: Int {get set} // координата центра фигуры на оси Y
var rotationAngle: Float {get set} // угол поворота фигуры относительно оси X
func placeIntoAxisCenter() // разместить фигуру в центре координатной оси
}
class Triangle: GeometryProtocol {
private var a: Float = 0.0
private var b: Float = 0.0
private var c: Float = 0.0
func calcPerimeter() -> Float {
return a + b + c
}
func calcArea() -> Float {
return sqrt((a + b + c) * (a + b) * (b + c))
}
}
class Circle : GeometryProtocol, AxisProtocol {
var centerX = 0
var centerY = 0
var rotationAngle: Float = 0.0
var radius: Float = 0.0
func calcPerimeter() -> Float {
return 6.28 * radius
}
func calcArea() -> Float {
return 3.14 * radius * radius
}
func placeIntoAxisCenter() {
centerX = 0
centerY = 0
}
//метод определения пересечения для кругов
func isCross(obj: Circle) -> Bool {
var answer = true
let distance = (self.centerX - obj.centerX) * (self.centerX - obj.centerX) + (self.centerY - obj.centerY) * (self.centerY - obj.centerY)
if sqrt(Double(distance)) > Double(obj.radius + self.radius) {
answer = false
} else{
answer = true
}
return answer
}
init(radius: Float, centerOX: Int, centerOY: Int) {
self.centerX = centerOX
self.centerY = centerOY
self.radius = radius
}
}
var a = Circle(radius: 5, centerOX: 1, centerOY: 0)
var b = Circle(radius: 2, centerOX: 0, centerOY: 2)
print (a.isCross(obj: b))
| mit | 97ba87e1b746d4d70492c8b70db48c1a | 28.157143 | 144 | 0.589417 | 3.549565 | false | false | false | false |
brianpartridge/Life | Life/Board.swift | 1 | 1724 | //
// Board.swift
// Life
//
// Created by Brian Partridge on 10/25/15.
// Copyright © 2015 PearTreeLabs. All rights reserved.
//
import Foundation
/// A two dimensional collection of Cells, representing a point in time in a Game.
public struct Board: CustomStringConvertible, Equatable {
// MARK: - Public Properties
public let size: Size
public let cells: [Cell]
// MARK: - Initializers
public init(size: Size, cells: [Cell]) {
precondition(size.volume == cells.count)
self.size = size
self.cells = cells
}
// MARK: - Public Methods
public func cellAtCoordinate(coordinate: Coordinate) -> Cell {
return cells[cellIndexForCoordinate(coordinate)]
}
public func cellIndexForCoordinate(coordinate: Coordinate) -> Int {
precondition(coordinate.x >= 0 && coordinate.x < size.width)
precondition(coordinate.y >= 0 && coordinate.y < size.height)
return (coordinate.y * size.width) + coordinate.x
}
// MARK: - CustomStringConvertible
public var description: String {
let width = size.width
var row = ""
var rows = [String]()
for (i, cell) in cells.enumerate() {
let columnIndex = i % width
if columnIndex == 0 {
row = ""
}
row.appendContentsOf("\(cell)")
if columnIndex == width-1 {
rows.append(row)
}
}
return rows.joinWithSeparator("\n")
}
}
public func ==(left: Board, right: Board) -> Bool {
return left.size == right.size && left.cells == right.cells
}
| mit | fb59e6bc438afb17235bdb19654e1006 | 24.338235 | 82 | 0.562972 | 4.534211 | false | false | false | false |
Esri/tips-and-tricks-ios | DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/SymbolAlignment/SymbolAlignmentVC.swift | 1 | 3416 | // Copyright 2015 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import ArcGIS
class SymbolAlignmentVC: UIViewController, AGSMapViewLayerDelegate, AGSLayerCalloutDelegate {
@IBOutlet weak var mapView: AGSMapView!
var graphicsLayer: AGSGraphicsLayer!
var pictureSymbol: AGSPictureMarkerSymbol!
override func viewDidLoad() {
super.viewDidLoad()
// set mapView layer delegate
self.mapView.layerDelegate = self
// add base layer to map
let mapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/Canvas/World_Light_Gray_Base/MapServer")
let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl);
self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer")
// add graphics layer to map
self.graphicsLayer = AGSGraphicsLayer.graphicsLayer() as AGSGraphicsLayer
self.graphicsLayer.calloutDelegate = self;
self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
let pointWGS84 = AGSPoint(fromDecimalDegreesString: "34.35815 S, 18.472 E", withSpatialReference: AGSSpatialReference.wgs84SpatialReference())
let pointWebMerc = AGSGeometryEngine.defaultGeometryEngine().projectGeometry(pointWGS84, toSpatialReference: AGSSpatialReference.webMercatorSpatialReference()) as AGSPoint;
let symbol = AGSSimpleMarkerSymbol(color: UIColor.orangeColor())
symbol.style = AGSSimpleMarkerSymbolStyle.Circle
symbol.size = CGSize(width: 10, height: 10)
let graphic = AGSGraphic(geometry: pointWebMerc, symbol: symbol, attributes: nil)
self.graphicsLayer.addGraphic(graphic)
self.mapView.zoomToScale(8000000, withCenterPoint: pointWebMerc, animated: true)
self.pictureSymbol = AGSPictureMarkerSymbol(imageNamed: "BluePushpin")
let graphic2 = AGSGraphic(geometry: pointWebMerc, symbol: self.pictureSymbol, attributes: ["Description":"Cape of Good Hope"])
self.graphicsLayer.addGraphic(graphic2)
}
@IBAction func toggleAlignment(sender: UISwitch) {
if sender.on {
//9 points right, 16 points up
self.pictureSymbol.offset = CGPoint(x: 9, y: 16)
//9 points left, 11 points up
self.pictureSymbol.leaderPoint = CGPoint(x: -9, y: 11)
}else{
self.pictureSymbol.offset = CGPoint(x: 0, y: 0)
self.pictureSymbol.leaderPoint = CGPoint(x: 0, y: 0)
}
}
func callout(callout: AGSCallout!, willShowForFeature feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
let graphic = feature as AGSGraphic
callout.title = graphic.attributeAsStringForKey("Description")
return true
}
}
| apache-2.0 | 8bc5e3a48a147bf0fc7fefc691223849 | 39.188235 | 180 | 0.681499 | 4.653951 | false | false | false | false |
evolutional/flatbuffers | swift/Sources/FlatBuffers/VeriferOptions.swift | 1 | 1866 | /*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// `VerifierOptions` is a set of options to verify a flatbuffer
public struct VerifierOptions {
/// Maximum `Apparent` size if the buffer can be expanded into a DAG tree
internal var _maxApparentSize: UOffset
/// Maximum table count allowed in a buffer
internal var _maxTableCount: UOffset
/// Maximum depth allowed in a buffer
internal var _maxDepth: UOffset
/// Ignoring missing null terminals in strings
internal var _ignoreMissingNullTerminators: Bool
/// initializes the set of options for the verifier
/// - Parameters:
/// - maxDepth: Maximum depth allowed in a buffer
/// - maxTableCount: Maximum table count allowed in a buffer
/// - maxApparentSize: Maximum `Apparent` size if the buffer can be expanded into a DAG tree
/// - ignoreMissingNullTerminators: Ignoring missing null terminals in strings *Currently not supported in swift*
public init(
maxDepth: UOffset = 64,
maxTableCount: UOffset = 1000000,
maxApparentSize: UOffset = 1 << 31,
ignoreMissingNullTerminators: Bool = false)
{
_maxDepth = maxDepth
_maxTableCount = maxTableCount
_maxApparentSize = maxApparentSize
_ignoreMissingNullTerminators = ignoreMissingNullTerminators
}
}
| apache-2.0 | b1a944d4835e6ea5d922d4070d6a9d5a | 34.884615 | 117 | 0.735263 | 4.260274 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/SpriteKit/SpriteKit.swift | 10 | 4292 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import SpriteKit
import simd
// SpriteKit defines SKColor using a macro.
#if os(macOS)
public typealias SKColor = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
public typealias SKColor = UIColor
#endif
// this class only exists to allow AnyObject lookup of _copyImageData
// since that method only exists in a private header in SpriteKit, the lookup
// mechanism by default fails to accept it as a valid AnyObject call
//
// NOTE: older overlays called this _SpriteKitMethodProvider. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@objc class __SpriteKitMethodProvider : NSObject {
override init() { preconditionFailure("don't touch me") }
@objc func _copyImageData() -> NSData! { return nil }
}
@available(iOS, introduced: 10.0)
@available(macOS, introduced: 10.12)
@available(tvOS, introduced: 10.0)
@available(watchOS, introduced: 3.0)
extension SKWarpGeometryGrid {
/// Create a grid of the specified dimensions, source and destination positions.
///
/// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The
/// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1).
///
/// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content.
///
/// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to
/// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and
/// correspond to positions outside of the native undistorted bounds.
///
/// Source and destination positions are provided in row-major order starting from the top-left.
/// For example the indices for a 2x2 grid would be as follows:
///
/// [0]---[1]---[2]
/// | | |
/// [3]---[4]---[5]
/// | | |
/// [6]---[7]---[8]
///
/// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with
/// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with
/// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from
/// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to
public convenience init(columns: Int, rows: Int, sourcePositions: [SIMD2<Float>] = [SIMD2<Float>](), destinationPositions: [SIMD2<Float>] = [SIMD2<Float>]()) {
let requiredElementsCount = (columns + 1) * (rows + 1)
switch (destinationPositions.count, sourcePositions.count) {
case (0, 0):
self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil)
case (let dests, 0):
precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions)
case (0, let sources):
precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil)
case (let dests, let sources):
precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.")
self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions)
}
}
public func replacingBySourcePositions(positions source: [SIMD2<Float>]) -> SKWarpGeometryGrid {
return self.__replacingSourcePositions(source)
}
public func replacingByDestinationPositions(positions destination: [SIMD2<Float>]) -> SKWarpGeometryGrid {
return self.__replacingDestPositions(destination)
}
}
| apache-2.0 | 2ffdddcb44b1664f0cf2b2eff1397bb8 | 47.224719 | 161 | 0.686859 | 4.23692 | false | false | false | false |
JNU-Include/Swift-Study | Learning Swift.playground/Pages/Types.xcplaygroundpage/Contents.swift | 1 | 766 | let country = "South Korea"
let province = "Jejudo"
let city = "Jeju"
let street = "Shinsan"
let streetNumber = 1
//Concatenation '+'
let address = country + ", " + province + ", " + city
print(address)
//String Interpolation
let interpolatedAddress = "\(country), \(province), \(city)"
print(interpolatedAddress)
let interpolatedStreetAddress = "\(streetNumber) \(street)"
//Integers (Int)
let favoriteProgrammingLanguage = "Swift"
let year = 2014
//Floating Point Numbers (Double / Float)
var version = 3.1 //Double
//Boolean
let isFun = true //Bool (true = 1, false = 0)
//Type Safety
var someString = ""
//someString = 12.4
//let bestPlayer: String = "Player1"
//let averageGoalPerGame: Double = 0.99
//let yearOfDebut: Int = 2017
//let mvp: Bool = true
| apache-2.0 | 9ea090d6dab0c01cbca270b40438d35a | 21.529412 | 60 | 0.693211 | 3.374449 | false | false | false | false |
Punch-In/PunchInIOSApp | PunchIn/QuestionTableViewCell.swift | 1 | 1821 | //
// QuestionTableViewCell.swift
// PunchIn
//
// Created by Sumeet Shendrikar on 10/25/15.
// Copyright © 2015 Nilesh Agrawal. All rights reserved.
//
import UIKit
class QuestionTableViewCell: UITableViewCell {
var question:Question! {
didSet {
personNameField.text = question.askedBy
questionTextView.text = question.questionText
questionDateField.text = question.absoluteDateString
if let forClass = question.forClass {
if !forClass.isFinished {
// if class isn't finished, instaed show time since question
questionDateField.text = question.sinceDateString + " ago"
}
}
// if question.isAnswered {
// questionAnsweredImage.hidden = false
// }else{
// questionAnsweredImage.hidden = true
// }
}
}
@IBOutlet weak var questionTextView: UITextView!
@IBOutlet private weak var personNameField: UILabel!
@IBOutlet private weak var questionDateField: UILabel!
@IBOutlet weak var questionAnsweredImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
// Initialization code
}
private func setupUI() {
// configure font colors
personNameField.textColor = ThemeManager.theme().primaryGreyColor()
questionTextView.textColor = ThemeManager.theme().primaryBlueColor()
questionDateField.textColor = ThemeManager.theme().primaryBlueColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | ae14576dee30b379b98af7050dd1cb63 | 28.836066 | 80 | 0.612088 | 5.2149 | false | false | false | false |
sicardf/MyRide | MyRideTests/APIGoogleTests.swift | 1 | 2022 | //
// APIGoogleTests.swift
//
//
// Created by Flavien SICARD on 24/05/2017.
//
//
import XCTest
@testable import SwiftyJSON
@testable import MyRide
class APIGoogleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRequestAutocomplete() {
let apiGoogle = APIGoogle()
let expectedId = "f61ae52b5e603c5052cc1aec9f08768c86090aba"
apiGoogle.getPlaceAutocomplete(address: "12 route de la gare 13570 Barbentane") { (success, data, error) in
if success {
let result = JSON(data!)["predictions"][0]["id"].stringValue
XCTAssert(result == expectedId)
} else {
}
}
}
func testRequestGeocodeAddress() {
let apiGoogle = APIGoogle()
let expectedId = "ChIJh2zX_5fptRIRvOdzzkDCF-M"
apiGoogle.getGeocodeAddress(address: "12 route de la gare 13570 Barbentane") { (success, data, error) in
if success {
let result = JSON(data!)["predictions"][0]["place_id"].stringValue
XCTAssert(result == expectedId)
} else {
}
}
}
func testRequestGeocodeLatlng() {
let apiGoogle = APIGoogle()
let expectedId = "40 Rue Colin, 34000 Montpellier, France"
apiGoogle.getGeocodeLatlng(lat: "43.601461515809419", lng: "3.8783112529422401") { (success, data, error) in
if success {
let result = JSON(data!)["predictions"][0]["formatted_address"].stringValue
XCTAssert(result == expectedId)
} else {
}
}
}
}
| mit | 2865fa14d61623174423402e260a2cfc | 29.179104 | 116 | 0.566766 | 4.186335 | false | true | false | false |
overtake/TelegramSwift | Telegram-Mac/ExportedInvitationRowItem.swift | 1 | 16120 | //
// ExportedInvitationRowItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 13.01.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import TelegramCore
import SwiftSignalKit
private func generate(_ color: NSColor) -> CGImage {
return generateImage(NSMakeSize(40 / System.backingScale, 40 / System.backingScale), contextGenerator: { size, ctx in
let rect: NSRect = .init(origin: .zero, size: size)
ctx.clear(rect)
ctx.setFillColor(color.cgColor)
ctx.fillEllipse(in: rect)
let image = NSImage(named: "Icon_ChatActionsActive")!.precomposed()
ctx.clip(to: rect, mask: image)
ctx.clear(rect)
}, scale: System.backingScale)!
}
private var menuIcon: CGImage {
return generate(theme.colors.grayIcon.darker())
}
private var menuIconActive: CGImage {
return generate(theme.colors.grayIcon.darker().highlighted)
}
class ExportedInvitationRowItem: GeneralRowItem {
enum Mode {
case normal
case short
}
fileprivate let context: AccountContext
fileprivate let exportedLink: _ExportedInvitation?
fileprivate let linkTextLayout: TextViewLayout
private let _menuItems: ()->Signal<[ContextMenuItem], NoError>
fileprivate let shareLink:(String)->Void
fileprivate let usageTextLayout: TextViewLayout
fileprivate let lastPeers: [RenderedPeer]
fileprivate let mode: Mode
fileprivate let open:(_ExportedInvitation)->Void
fileprivate let copyLink:(String)->Void
fileprivate let publicAddress: String?
init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, exportedLink: _ExportedInvitation?, publicAddress: String? = nil, lastPeers: [RenderedPeer], viewType: GeneralViewType, mode: Mode = .normal, menuItems: @escaping()->Signal<[ContextMenuItem], NoError>, share: @escaping(String)->Void, open: @escaping(_ExportedInvitation)->Void = { _ in }, copyLink: @escaping(String)->Void = { _ in }) {
self.context = context
self.exportedLink = exportedLink
self._menuItems = menuItems
self.lastPeers = lastPeers
self.publicAddress = publicAddress
self.shareLink = share
self.open = open
self.mode = enableBetaFeatures ? mode : .short
self.copyLink = copyLink
let text: String
let color: NSColor
let usageText: String
let usageColor: NSColor
if let exportedLink = exportedLink {
text = exportedLink.link.replacingOccurrences(of: "https://", with: "")
color = theme.colors.text
if let count = exportedLink.count {
usageText = strings().inviteLinkJoinedNewCountable(Int(count))
if count > 0 {
usageColor = theme.colors.link
} else {
usageColor = theme.colors.grayText
}
} else {
usageText = strings().inviteLinkJoinedNewZero
usageColor = theme.colors.grayText
}
} else if let publicAddress = publicAddress {
text = "t.me/\(publicAddress)"
color = theme.colors.text
usageText = strings().inviteLinkJoinedNewZero
usageColor = theme.colors.grayText
} else {
text = strings().channelVisibilityLoading
color = theme.colors.grayText
usageText = strings().inviteLinkJoinedNewZero
usageColor = theme.colors.grayText
}
linkTextLayout = TextViewLayout(.initialize(string: text, color: color, font: .normal(.text)), truncationType: .start, alignment: .center)
usageTextLayout = TextViewLayout(.initialize(string: usageText, color: usageColor, font: .normal(.text)))
super.init(initialSize, stableId: stableId, viewType: viewType)
}
override var height: CGFloat {
var height: CGFloat = viewType.innerInset.top + 40 + viewType.innerInset.top
switch mode {
case .normal:
if let link = exportedLink, !link.isExpired && !link.isRevoked {
height += 40 + viewType.innerInset.top
} else if exportedLink == nil && publicAddress == nil {
height += 40
}
height += 30 + viewType.innerInset.bottom
if exportedLink == nil {
height += viewType.innerInset.bottom
}
case .short:
break
}
return height
}
var copyItem: String? {
if let exportedLink = exportedLink {
if !exportedLink.isExpired && !exportedLink.isRevoked {
return exportedLink.link
} else {
return nil
}
} else if let publicAddress = publicAddress {
return publicAddress
} else {
return nil
}
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool {
let result = super.makeSize(width, oldWidth: oldWidth)
linkTextLayout.measure(width: blockWidth - viewType.innerInset.left * 2 + viewType.innerInset.right * 2 - 50)
usageTextLayout.measure(width: blockWidth - viewType.innerInset.left - viewType.innerInset.right)
return result
}
override func menuItems(in location: NSPoint) -> Signal<[ContextMenuItem], NoError> {
return _menuItems()
}
override func viewClass() -> AnyClass {
return ExportedInvitationRowView.self
}
}
private final class ExportedInvitationRowView : GeneralContainableRowView {
struct Avatar : Comparable, Identifiable {
static func < (lhs: Avatar, rhs: Avatar) -> Bool {
return lhs.index < rhs.index
}
var stableId: PeerId {
return peer.id
}
static func == (lhs: Avatar, rhs: Avatar) -> Bool {
if lhs.index != rhs.index {
return false
}
if !lhs.peer.isEqual(rhs.peer) {
return false
}
return true
}
let peer: Peer
let index: Int
}
private let linkContainer: Control = Control()
private let linkView: TextView = TextView()
private let share: TitleButton = TitleButton()
private let copy: TitleButton = TitleButton()
private let actions: ImageButton = ImageButton()
private let usageTextView = TextView()
private let usageContainer = Control()
private var topPeers: [Avatar] = []
private var avatars:[AvatarContentView] = []
private let avatarsContainer = View(frame: NSMakeRect(0, 0, 25 * 3 + 10, 38))
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(linkContainer)
linkContainer.layer?.cornerRadius = 10
linkContainer.addSubview(linkView)
addSubview(share)
share.layer?.cornerRadius = 10
share._thatFit = true
addSubview(copy)
copy.layer?.cornerRadius = 10
copy._thatFit = true
linkView.userInteractionEnabled = false
linkView.isSelectable = false
linkContainer.addSubview(actions)
addSubview(usageContainer)
usageTextView.userInteractionEnabled = false
usageTextView.isSelectable = false
usageTextView.isEventLess = true
avatarsContainer.isEventLess = true
usageContainer.addSubview(usageTextView)
usageContainer.addSubview(avatarsContainer)
linkContainer.scaleOnClick = true
linkContainer.set(handler: { [weak self] _ in
guard let item = self?.item as? ExportedInvitationRowItem else {
return
}
if let link = item.exportedLink {
item.copyLink(link.link)
}
}, for: .Click)
actions.set(handler: { [weak self] control in
guard let event = NSApp.currentEvent else {
return
}
self?.showContextMenu(event)
}, for: .Down)
share.set(handler: { [weak self] _ in
guard let item = self?.item as? ExportedInvitationRowItem else {
return
}
if let link = item.copyItem {
item.shareLink(link)
}
}, for: .Click)
copy.set(handler: { [weak self] _ in
guard let item = self?.item as? ExportedInvitationRowItem else {
return
}
if let link = item.copyItem {
item.copyLink(link)
}
}, for: .Click)
usageContainer.set(handler: { [weak self] _ in
guard let item = self?.item as? ExportedInvitationRowItem else {
return
}
if let exportedLink = item.exportedLink {
item.open(exportedLink)
}
}, for: .Click)
}
override func layout() {
super.layout()
guard let item = item as? ExportedInvitationRowItem else {
return
}
let innerBlockSize = item.blockWidth - item.viewType.innerInset.left - item.viewType.innerInset.right
linkContainer.frame = NSMakeRect(item.viewType.innerInset.left, item.viewType.innerInset.top, innerBlockSize, 40)
linkView.centerY(x: item.viewType.innerInset.left)
copy.frame = NSMakeRect(item.viewType.innerInset.left, linkContainer.frame.maxY + item.viewType.innerInset.top, innerBlockSize / 2 - 10, 40)
share.frame = NSMakeRect(copy.frame.maxX + 20, linkContainer.frame.maxY + item.viewType.innerInset.top, innerBlockSize / 2 - 10, 40)
actions.centerY(x: linkContainer.frame.width - actions.frame.width - item.viewType.innerInset.right)
usageContainer.frame = NSMakeRect(item.viewType.innerInset.left, share.frame.maxY + item.viewType.innerInset.top, innerBlockSize, 30)
let avatarSize: CGFloat = avatarsContainer.subviews.map { $0.frame.maxX }.max() ?? 0
if avatarSize > 0 {
usageTextView.centerY(x: floorToScreenPixels(backingScaleFactor, (frame.width - usageTextView.frame.width - avatarSize - 5) / 2))
avatarsContainer.centerY(x: usageTextView.frame.minX - avatarSize - 5)
} else {
usageTextView.center()
}
}
override func updateColors() {
super.updateColors()
guard let item = item as? ExportedInvitationRowItem else {
return
}
linkContainer.backgroundColor = theme.colors.grayBackground
linkView.backgroundColor = theme.colors.grayBackground
share.set(background: theme.colors.accent, for: .Normal)
share.set(background: theme.colors.accent.highlighted, for: .Highlight)
share.set(color: theme.colors.underSelectedColor, for: .Normal)
copy.set(background: theme.colors.accent, for: .Normal)
copy.set(background: theme.colors.accent.highlighted, for: .Highlight)
copy.set(color: theme.colors.underSelectedColor, for: .Normal)
actions.set(image: menuIcon, for: .Normal)
actions.set(image: menuIconActive, for: .Highlight)
actions.sizeToFit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? ExportedInvitationRowItem else {
return
}
let duration: Double = 0.4
let timingFunction: CAMediaTimingFunctionName = .spring
if item.exportedLink != nil {
var topPeers: [Avatar] = []
if !item.lastPeers.isEmpty {
var index:Int = 0
for participant in item.lastPeers {
if let peer = participant.peer {
topPeers.append(Avatar(peer: peer, index: index))
index += 1
}
}
}
let (removed, inserted, updated) = mergeListsStableWithUpdates(leftList: self.topPeers, rightList: topPeers)
let avatarSize = NSMakeSize(38, 38)
for removed in removed.reversed() {
let control = avatars.remove(at: removed)
let peer = self.topPeers[removed]
let haveNext = topPeers.contains(where: { $0.stableId == peer.stableId })
control.updateLayout(size: avatarSize - NSMakeSize(8, 8), isClipped: false, animated: animated)
control.layer?.opacity = 0
if animated && !haveNext {
control.layer?.animateAlpha(from: 1, to: 0, duration: duration, timingFunction: timingFunction, removeOnCompletion: false, completion: { [weak control] _ in
control?.removeFromSuperview()
})
control.layer?.animateScaleSpring(from: 1.0, to: 0.2, duration: duration, bounce: false)
} else {
control.removeFromSuperview()
}
}
for inserted in inserted {
let control = AvatarContentView(context: item.context, peer: inserted.1.peer, message: nil, synchronousLoad: false, size: avatarSize, inset: 6)
control.updateLayout(size: avatarSize - NSMakeSize(8, 8), isClipped: inserted.0 != 0, animated: animated)
control.userInteractionEnabled = false
control.setFrameSize(avatarSize)
control.setFrameOrigin(NSMakePoint(CGFloat(inserted.0) * (avatarSize.width - 14), 0))
avatars.insert(control, at: inserted.0)
avatarsContainer.subviews.insert(control, at: inserted.0)
if animated {
if let index = inserted.2 {
control.layer?.animatePosition(from: NSMakePoint(CGFloat(index) * (avatarSize.width - 14), 0), to: control.frame.origin, timingFunction: timingFunction)
} else {
control.layer?.animateAlpha(from: 0, to: 1, duration: duration, timingFunction: timingFunction)
control.layer?.animateScaleSpring(from: 0.2, to: 1.0, duration: duration, bounce: false)
}
}
}
for updated in updated {
let control = avatars[updated.0]
control.updateLayout(size: avatarSize - NSMakeSize(8, 8), isClipped: updated.0 != 0, animated: animated)
let updatedPoint = NSMakePoint(CGFloat(updated.0) * (avatarSize.width - 14), 0)
if animated {
control.layer?.animatePosition(from: control.frame.origin - updatedPoint, to: .zero, duration: duration, timingFunction: timingFunction, additive: true)
}
control.setFrameOrigin(updatedPoint)
}
var index: CGFloat = 10
for control in avatarsContainer.subviews.compactMap({ $0 as? AvatarContentView }) {
control.layer?.zPosition = index
index -= 1
}
}
share.set(font: .medium(.text), for: .Normal)
share.set(text: strings().manageLinksContextShare, for: .Normal)
share.userInteractionEnabled = item.copyItem != nil
copy.set(font: .medium(.text), for: .Normal)
copy.set(text: strings().manageLinksContextCopy, for: .Normal)
copy.userInteractionEnabled = item.copyItem != nil
linkView.update(item.linkTextLayout)
usageTextView.update(item.usageTextLayout)
needsLayout = true
}
}
| gpl-2.0 | cea0fe3aab0c431b4fd409b64776fc93 | 37.470167 | 416 | 0.590235 | 4.921832 | false | false | false | false |
AuspiciousApps/matchingFlags | newFlag/GameViewController.swift | 1 | 3667 | //
// ViewController.swift
// newFlag
//
// Created by MAD Student on 7/17/17.
// Copyright © 2017 MAD Student. All rights reserved.
//
import UIKit
import LTMorphingLabel
import MZTimerLabel
class GameViewController: UIViewController, MatchingGameDelegate {
@IBOutlet weak var burnLabel: LTMorphingLabel!
@IBOutlet weak var cardButton: UIButton!
@IBOutlet weak var timerLabel: LTMorphingLabel!
var stopWatch: MZTimerLabel!
var game = Game()//instanciating a struct..(make a object)
var gameNum = 1
override func viewDidLoad() {
super.viewDidLoad()
game.gameDelegate = self
burnLabel.morphingEffect = .burn
timerLabel.morphingEffect = .burn
//game.newGame()
stopWatch = MZTimerLabel.init(label: timerLabel)
stopWatch.timeFormat = "mm:ss"
stopWatch.start()
}
@IBAction func cardTapped(_ sender: UIButton) {
let tagNum = sender.tag
if game.flipCard(atIndexNumber: tagNum - 1){
let thisImage = UIImage(named: game.deckOfCards.deltCards[tagNum - 1])
//sender.setImage(thisImage, for: .normal)
UIView.transition(with: sender, duration: 0.4, options: .transitionFlipFromRight, animations: { sender.setImage(thisImage, for: .normal)}, completion: nil)
// game.speakCard(number: tagNum - 1)
displayGameOver()
}
}
@IBAction func newGame(_ sender: UIButton) {
for tagNum in 1...12{
if let thisButton = self.view.viewWithTag(tagNum) as? UIButton {
//thisButton.setImage(#imageLiteral(resourceName: "cardBack"), for: .normal)
UIView.transition(with: thisButton, duration: 0.2, options: [.transitionFlipFromTop, .repeat] , animations: { thisButton.setImage(#imageLiteral(resourceName: "cardBack"), for: .normal)}, completion: nil)
let delayTime = DispatchTime.now() + 0.5
DispatchQueue.main.asyncAfter(deadline: delayTime) {
thisButton.layer.removeAllAnimations()
}
}
}
gameNum += 1
burnLabel.text = "Game #\(gameNum)"
game.newGame()
stopWatch.reset()
stopWatch.start()
//sender.setImage(thisImage, for: .normal)
}
func game(_ game: Game, hideCards cards: [Int]) {
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime){
for cardIndex in cards {
if let thisButton = self.view.viewWithTag(cardIndex + 1) as? UIButton {
UIView.transition(with: thisButton, duration: 0.2, options: .transitionFlipFromTop, animations: { thisButton.setImage(#imageLiteral(resourceName: "cardBack"), for: .normal)}, completion: nil)
}
}
self.game.noFlipWhileWait = false
}
}
func displayGameOver() {
if game.matchArray.isEmpty {
burnLabel.text = "GAME OVER WINNER"
stopWatch.pause()
}
}
// let thisImage = UIImage(named: nameList[tagNum - 1])
// thisButton.setBackgroundImage(thisImage, for: .normal)
//
// func drawCards() {
// deltCards = nameList
// //nameList = shuffle(nameList)
// deltCards.shuffle()
//
// }
//highlight then command /
}
| mit | 98464303e208635fa039429949a008bd | 32.027027 | 219 | 0.574741 | 4.56538 | false | false | false | false |
irace/Objchecklist | Objchecklist/AppDelegate.swift | 1 | 1862 | //
// AppDelegate.swift
// Objchecklist
//
// Created by Bryan Irace on 11/15/14.
// Copyright (c) 2014 Bryan Irace. All rights reserved.
//
import UIKit
// Alternative name: `Cocoamplete`?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
// MARK: - UIApplicationDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
let splitViewController = UISplitViewController()
splitViewController.viewControllers = [UINavigationController(rootViewController: MasterViewController())/*, IssueViewController(issue: Issue(title: "", permalink: NSURL(), articles: []))*/]
splitViewController.delegate = self
window?.rootViewController = splitViewController
window?.makeKeyAndVisible();
return true
}
// MARK: - Split view
// func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
// if let secondaryAsNavController = secondaryViewController as? UINavigationController {
// if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
// if topAsDetailController.detailItem == nil {
// // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
// return true
// }
// }
// }
// return false
// }
}
| mit | 6e924845042e3d66f090985cc914308c | 37.791667 | 226 | 0.690118 | 5.987138 | false | false | false | false |
sihekuang/SKUIComponents | SKUIComponents/Classes/SKRoundedGradientFilledButton.swift | 1 | 1004 | //
// RoundedGradientFilledButton.swift
// Pods
//
// Created by Daniel Lee on 12/28/16.
//
//
import Foundation
@IBDesignable
open class SKRoundedGradientFilledButton: SKRoundedFilledButton{
@IBInspectable
open var endColor: UIColor?
@IBInspectable
open var isGradientHorizontal: Bool = true
override open func draw(_ rect: CGRect) {
let startColor = self.fillColor ?? UIColor.white
let endColor = self.endColor ?? startColor
let radius = self.cornerRadius
guard let path = SKUIHelper.drawRectGradient(rect: rect, startColor: startColor, endColor: endColor, cornerRadius: radius, isHorizontal: isGradientHorizontal) else{
return
}
if showShadow{
SKUIHelper.drawShadow(view: self, bezierPath: path, cornerRadius: cornerRadius, shadowOffsetX: shadowOffsetX, shadowOffsetY: shadowOffsetY, shadowRadius: shadowRadius, color: outlineShadowColor)
}
}
}
| mit | fc0199f41733eeb7d09bf7439790f233 | 27.685714 | 206 | 0.674303 | 4.897561 | false | false | false | false |
pidjay/SideMenu | Example/SideMenu/MainViewController.swift | 2 | 4335 | //
// MainViewController.swift
//
// Created by Jon Kent on 11/12/15.
// Copyright © 2015 Jon Kent. All rights reserved.
//
import SideMenu
class MainViewController: UIViewController {
@IBOutlet fileprivate weak var presentModeSegmentedControl:UISegmentedControl!
@IBOutlet fileprivate weak var blurSegmentControl:UISegmentedControl!
@IBOutlet fileprivate weak var darknessSlider:UISlider!
@IBOutlet fileprivate weak var shadowOpacitySlider:UISlider!
@IBOutlet fileprivate weak var screenWidthSlider:UISlider!
@IBOutlet fileprivate weak var shrinkFactorSlider:UISlider!
@IBOutlet fileprivate weak var blackOutStatusBar:UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
setupSideMenu()
setDefaults()
}
fileprivate func setupSideMenu() {
// Define the menus
SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController
SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController
// Enable gestures. The left and/or right menus must be set up above for these to work.
// Note that these continue to work on the Navigation Controller independent of the View Controller it displays!
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
// Set up a cool background image for demo purposes
SideMenuManager.menuAnimationBackgroundColor = UIColor(patternImage: UIImage(named: "background")!)
}
fileprivate func setDefaults() {
let modes:[SideMenuManager.MenuPresentMode] = [.menuSlideIn, .viewSlideOut, .menuDissolveIn]
presentModeSegmentedControl.selectedSegmentIndex = modes.index(of: SideMenuManager.menuPresentMode)!
let styles:[UIBlurEffectStyle] = [.dark, .light, .extraLight]
if let menuBlurEffectStyle = SideMenuManager.menuBlurEffectStyle {
blurSegmentControl.selectedSegmentIndex = styles.index(of: menuBlurEffectStyle) ?? 0
} else {
blurSegmentControl.selectedSegmentIndex = 0
}
darknessSlider.value = Float(SideMenuManager.menuAnimationFadeStrength)
shadowOpacitySlider.value = Float(SideMenuManager.menuShadowOpacity)
shrinkFactorSlider.value = Float(SideMenuManager.menuAnimationTransformScaleFactor)
screenWidthSlider.value = Float(SideMenuManager.menuWidth / view.frame.width)
blackOutStatusBar.isOn = SideMenuManager.menuFadeStatusBar
}
@IBAction fileprivate func changeSegment(_ segmentControl: UISegmentedControl) {
switch segmentControl {
case presentModeSegmentedControl:
let modes:[SideMenuManager.MenuPresentMode] = [.menuSlideIn, .viewSlideOut, .viewSlideInOut, .menuDissolveIn]
SideMenuManager.menuPresentMode = modes[segmentControl.selectedSegmentIndex]
case blurSegmentControl:
if segmentControl.selectedSegmentIndex == 0 {
SideMenuManager.menuBlurEffectStyle = nil
} else {
let styles:[UIBlurEffectStyle] = [.dark, .light, .extraLight]
SideMenuManager.menuBlurEffectStyle = styles[segmentControl.selectedSegmentIndex - 1]
}
default: break;
}
}
@IBAction fileprivate func changeSlider(_ slider: UISlider) {
switch slider {
case darknessSlider:
SideMenuManager.menuAnimationFadeStrength = CGFloat(slider.value)
case shadowOpacitySlider:
SideMenuManager.menuShadowOpacity = slider.value
case shrinkFactorSlider:
SideMenuManager.menuAnimationTransformScaleFactor = CGFloat(slider.value)
case screenWidthSlider:
SideMenuManager.menuWidth = view.frame.width * CGFloat(slider.value)
default: break;
}
}
@IBAction fileprivate func changeSwitch(_ switchControl: UISwitch) {
SideMenuManager.menuFadeStatusBar = switchControl.isOn
}
}
| mit | f6b45178efb55d9ea1dd0d4449138948 | 46.108696 | 177 | 0.71712 | 5.84097 | false | false | false | false |
matsprea/omim | iphone/Maps/Core/Theme/GlobalStyleSheet.swift | 1 | 11372 | import Foundation
class GlobalStyleSheet: IStyleSheet {
static func register(theme: Theme, colors: IColors, fonts: IFonts) {
//MARK: Defaults
theme.add(styleName: "TableView") { (s) -> (Void) in
s.backgroundColor = colors.white
s.separatorColor = colors.blackDividers
s.exclusions = [String(describing: UIDatePicker.self)]
}
theme.add(styleName: "TableCell") { (s) -> (Void) in
s.backgroundColor = colors.white
s.fontColor = colors.blackPrimaryText
s.tintColor = colors.linkBlue
s.fontColorDetailed = colors.blackSecondaryText
s.backgroundColorSelected = colors.pressBackground
s.exclusions = [String(describing: UIDatePicker.self),
"_UIActivityUserDefaultsActivityCell"]
}
theme.add(styleName: "MWMTableViewCell", from: "TableCell") { (s) -> (Void) in
}
theme.add(styleName: "TableViewHeaderFooterView") { (s) -> (Void) in
s.font = fonts.medium14
s.fontColor = colors.blackSecondaryText
}
theme.add(styleName: "SearchBar") { (s) -> (Void) in
s.backgroundColor = colors.white
s.barTintColor = colors.primary
s.tintColor = UIColor.white
s.fontColor = colors.blackSecondaryText
}
theme.add(styleName: "NavigationBar") { (s) -> (Void) in
s.barTintColor = colors.primary
s.tintColor = colors.whitePrimaryText
s.backgroundImage = UIImage()
s.shadowImage = UIImage()
s.font = fonts.regular18
s.fontColor = colors.whitePrimaryText
}
theme.add(styleName: "NavigationBarItem") { (s) -> (Void) in
s.font = fonts.regular18
s.fontColor = colors.whitePrimaryText
s.fontColorDisabled = UIColor.lightGray
s.fontColorHighlighted = colors.whitePrimaryTextHighlighted
s.tintColor = colors.whitePrimaryText
}
theme.add(styleName: "Checkmark") { (s) -> (Void) in
s.onTintColor = colors.linkBlue
s.offTintColor = colors.blackHintText
}
theme.add(styleName: "Switch") { (s) -> (Void) in
s.onTintColor = colors.linkBlue
}
theme.add(styleName: "PageControl") { (s) -> (Void) in
s.pageIndicatorTintColor = colors.blackHintText
s.currentPageIndicatorTintColor = colors.blackSecondaryText
s.backgroundColor = colors.white
}
theme.add(styleName: "StarRatingView") { (s) -> (Void) in
s.onTintColor = colors.ratingYellow
s.offTintColor = colors.blackDividers
}
theme.add(styleName: "DifficultyView") { (s) -> (Void) in
s.colors = [colors.blackSecondaryText, colors.ratingGreen, colors.ratingYellow, colors.ratingRed]
s.offTintColor = colors.blackSecondaryText
s.backgroundColor = colors.clear
}
//MARK: Global styles
theme.add(styleName: "Divider") { (s) -> (Void) in
s.backgroundColor = colors.blackDividers
}
theme.add(styleName: "SolidDivider") { (s) -> (Void) in
s.backgroundColor = colors.solidDividers
}
theme.add(styleName: "Background") { (s) -> (Void) in
s.backgroundColor = colors.white
}
theme.add(styleName: "PressBackground") { (s) -> (Void) in
s.backgroundColor = colors.pressBackground
}
theme.add(styleName: "PrimaryBackground") { (s) -> (Void) in
s.backgroundColor = colors.primary
}
theme.add(styleName: "SecondaryBackground") { (s) -> (Void) in
s.backgroundColor = colors.secondary
}
theme.add(styleName: "MenuBackground") { (s) -> (Void) in
s.backgroundColor = colors.menuBackground
}
theme.add(styleName: "BlackOpaqueBackground") { (s) -> (Void) in
s.backgroundColor = colors.blackOpaque
}
theme.add(styleName: "BlueBackground") { (s) -> (Void) in
s.backgroundColor = colors.linkBlue
}
theme.add(styleName: "ToastBackground") { (s) -> (Void) in
s.backgroundColor = colors.toastBackground
}
theme.add(styleName: "FadeBackground") { (s) -> (Void) in
s.backgroundColor = colors.fadeBackground
}
theme.add(styleName: "ErrorBackground") { (s) -> (Void) in
s.backgroundColor = colors.errorPink
}
theme.add(styleName: "BlackStatusBarBackground") { (s) -> (Void) in
s.backgroundColor = colors.blackStatusBarBackground
}
theme.add(styleName: "PresentationBackground") { (s) -> (Void) in
s.backgroundColor = UIColor.black.withAlphaComponent(alpha40)
}
theme.add(styleName: "ClearBackground") { (s) -> (Void) in
s.backgroundColor = colors.clear
}
theme.add(styleName: "TabView") { (s) -> (Void) in
s.backgroundColor = colors.pressBackground
s.barTintColor = colors.primary
s.tintColor = colors.white
s.fontColor = colors.whitePrimaryText
s.font = fonts.medium14
}
theme.add(styleName: "DialogView") { (s) -> (Void) in
s.cornerRadius = 8
s.shadowRadius = 2
s.shadowColor = UIColor(0,0,0,alpha26)
s.shadowOpacity = 1
s.shadowOffset = CGSize(width: 0, height: 1)
s.backgroundColor = colors.white
s.clip = true
}
theme.add(styleName: "AlertView") { (s) -> (Void) in
s.cornerRadius = 12
s.shadowRadius = 6
s.shadowColor = UIColor(0,0,0,alpha20)
s.shadowOpacity = 1
s.shadowOffset = CGSize(width: 0, height: 3)
s.backgroundColor = colors.alertBackground
s.clip = true
}
theme.add(styleName: "AlertViewTextField") { (s) -> (Void) in
s.borderColor = colors.blackDividers
s.borderWidth = 0.5
s.backgroundColor = colors.white
}
theme.add(styleName: "SearchStatusBarView") { (s) -> (Void) in
s.backgroundColor = colors.primary
s.shadowRadius = 2
s.shadowColor = colors.blackDividers
s.shadowOpacity = 1
s.shadowOffset = CGSize(width: 0, height: 0)
}
theme.add(styleName: "RatingView12") { (s) -> (Void) in
var settings = RatingViewSettings()
settings.filledColor = colors.ratingYellow
settings.emptyColor = colors.blackDividers
settings.textFonts[.top] = fonts.regular10
settings.textColors[.top] = colors.blackSecondaryText
settings.starSize = 12
settings.starsCount = 5
s.ratingViewSettings = settings
s.borderWidth = 0
}
theme.add(styleName: "RatingView20") { (s) -> (Void) in
var settings = RatingViewSettings()
settings.filledColor = colors.ratingYellow
settings.emptyColor = colors.blackDividers
settings.textFonts[.top] = fonts.regular10
settings.textColors[.top] = colors.blackSecondaryText
settings.starSize = 20
settings.starsCount = 5
s.ratingViewSettings = settings
s.borderWidth = 0
}
//MARK: Buttons
theme.add(styleName: "FlatNormalButton") { (s) -> (Void) in
s.font = fonts.medium14
s.cornerRadius = 8
s.clip = true
s.fontColor = colors.whitePrimaryText
s.backgroundColor = colors.linkBlue
s.fontColorHighlighted = colors.whitePrimaryTextHighlighted
s.fontColorDisabled = colors.whitePrimaryTextHighlighted
s.backgroundColorHighlighted = colors.linkBlueHighlighted
}
theme.add(styleName: "FlatNormalButtonBig", from: "FlatNormalButton") { (s) -> (Void) in
s.font = fonts.regular17
}
theme.add(styleName: "FlatNormalTransButton") { (s) -> (Void) in
s.font = fonts.medium14
s.cornerRadius = 8
s.clip = true
s.fontColor = colors.linkBlue
s.backgroundColor = colors.clear
s.fontColorHighlighted = colors.linkBlueHighlighted
s.fontColorDisabled = colors.blackHintText
s.backgroundColorHighlighted = colors.clear
}
theme.add(styleName: "FlatNormalTransButtonBig", from: "FlatNormalTransButton") { (s) -> (Void) in
s.font = fonts.regular17
}
theme.add(styleName: "FlatGrayTransButton") { (s) -> (Void) in
s.font = fonts.medium14
s.fontColor = colors.blackSecondaryText
s.backgroundColor = colors.clear
s.fontColorHighlighted = colors.linkBlueHighlighted
}
theme.add(styleName: "FlatRedTransButton") { (s) -> (Void) in
s.font = fonts.medium14
s.fontColor = colors.red
s.backgroundColor = colors.clear
s.fontColorHighlighted = colors.red
}
theme.add(styleName: "FlatRedTransButtonBig") { (s) -> (Void) in
s.font = fonts.regular17
s.fontColor = colors.red
s.backgroundColor = colors.clear
s.fontColorHighlighted = colors.red
}
theme.add(styleName: "FlatRedButton") { (s) -> (Void) in
s.font = fonts.medium14
s.cornerRadius = 8
s.fontColor = colors.whitePrimaryText
s.backgroundColor = colors.buttonRed
s.fontColorHighlighted = colors.buttonRedHighlighted
}
theme.add(styleName: "MoreButton") { (s) -> (Void) in
s.fontColor = colors.linkBlue
s.fontColorHighlighted = colors.linkBlueHighlighted
s.backgroundColor = colors.clear
s.font = fonts.regular16
}
theme.add(styleName: "EditButton") { (s) -> (Void) in
s.font = fonts.regular14
s.fontColor = colors.linkBlue
s.cornerRadius = 8
s.borderColor = colors.linkBlue
s.borderWidth = 1
s.fontColorHighlighted = colors.linkBlueHighlighted
s.backgroundColor = colors.clear
}
theme.add(styleName: "RateAppButton") { (s) -> (Void) in
s.font = fonts.medium17
s.fontColor = colors.linkBlue
s.fontColorHighlighted = colors.white
s.borderColor = colors.linkBlue
s.cornerRadius = 8
s.borderWidth = 1
s.backgroundColor = colors.clear
s.backgroundColorHighlighted = colors.linkBlue
}
theme.add(styleName: "TermsOfUseLinkText") { (s) -> (Void) in
s.font = fonts.regular16
s.fontColor = colors.blackPrimaryText
s.linkAttributes = [NSAttributedString.Key.font: fonts.regular16,
NSAttributedString.Key.foregroundColor: colors.linkBlue,
NSAttributedString.Key.underlineColor: UIColor.clear]
s.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
theme.add(styleName: "TermsOfUseGrayButton") { (s) -> (Void) in
s.font = fonts.medium10
s.fontColor = colors.blackSecondaryText
s.fontColorHighlighted = colors.blackHintText
}
theme.add(styleName: "Badge") { (s) -> (Void) in
s.round = true
s.backgroundColor = colors.downloadBadgeBackground
}
//MARK: coloring
theme.add(styleName: "MWMBlue") { (s) -> (Void) in
s.tintColor = colors.linkBlue
s.coloring = MWMButtonColoring.blue
}
theme.add(styleName: "MWMBlack") { (s) -> (Void) in
s.tintColor = colors.blackSecondaryText
s.coloring = MWMButtonColoring.black
}
theme.add(styleName: "MWMOther") { (s) -> (Void) in
s.tintColor = colors.white
s.coloring = MWMButtonColoring.other
}
theme.add(styleName: "MWMGray") { (s) -> (Void) in
s.tintColor = colors.blackHintText
s.coloring = MWMButtonColoring.gray
}
theme.add(styleName: "MWMSeparator") { (s) -> (Void) in
s.tintColor = colors.blackDividers
s.coloring = MWMButtonColoring.black
}
theme.add(styleName: "MWMWhite") { (s) -> (Void) in
s.tintColor = colors.white
s.coloring = MWMButtonColoring.white
}
}
}
| apache-2.0 | 3e5142079d462f9aff85fba1bddc61a6 | 31.772334 | 103 | 0.646588 | 3.972057 | false | false | false | false |
CSullivan102/LearnApp | LearnKit/ChooseTopic/ChooseTopicViewController.swift | 1 | 7568 | //
// ChooseTopicViewController.swift
// Learn
//
// Created by Christopher Sullivan on 9/11/15.
// Copyright © 2015 Christopher Sullivan. All rights reserved.
//
import UIKit
import CoreData
public protocol ChooseTopicDelegate {
func didChooseTopic(topic: Topic?)
}
public class ChooseTopicViewController: UIViewController, UICollectionViewDelegate, ManagedObjectContextSettable, TopicCollectionControllable {
public var managedObjectContext: NSManagedObjectContext!
public var parentTopic: Topic?
public var topicViewState: TopicViewState = .BaseTopic
public var chooseTopicDelegate: ChooseTopicDelegate?
private var selectedTopic: Topic?
private var selectedSubtopic: Topic? {
didSet {
chooseTopicDelegate?.didChooseTopic(selectedSubtopic)
}
}
private var currentDataSource: UICollectionViewDataSource?
private var topicPickingState: TopicPickingState = .None
private let createTopicTransitioningDelegate = SmallModalTransitioningDelegate()
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var chooseTopicButton: UIButton!
@IBOutlet weak var chooseSubTopicButton: UIButton!
@IBOutlet weak var stackView: UIStackView!
override public func viewDidLoad() {
super.viewDidLoad()
setupParentTopic {
self.setupInitialFetchedResultsController()
}
collectionView.delegate = self
preferredContentSize = stackView.bounds.size
}
private func setupInitialFetchedResultsController() {
guard let topic = self.parentTopic else {
fatalError("Tried to set up choose topic controller without parent")
}
setupDataSourceForTopic(topic)
}
private func setupDataSourceForTopic(topic: Topic) {
let frc = getFetchedResultsControllerForTopic(topic)
currentDataSource = AddableFetchedResultsCollectionDataSource(collectionView: collectionView, fetchedResultsController: frc, delegate: self)
collectionView.dataSource = currentDataSource
collectionView.reloadData()
}
@IBAction func chooseTopicButtonPressed(sender: UIButton) {
selectedTopic = nil
selectedSubtopic = nil
let prevTopicPickingState = topicPickingState
topicPickingState = .Topic
if prevTopicPickingState != topicPickingState {
setupInitialFetchedResultsController()
updateUIForState()
}
}
@IBAction func chooseSubtopicButtonPressed(sender: UIButton) {
selectedSubtopic = nil
let prevTopicPickingState = topicPickingState
topicPickingState = .Subtopic
if prevTopicPickingState != topicPickingState {
updateUIForState()
}
}
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier,
segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Invalid segue identifier \(segue.identifier)")
}
switch segueIdentifier {
case .ShowCreateTopic:
guard let vc = segue.destinationViewController as? CreateTopicViewController else {
fatalError("Unexpected view controller for \(identifier) segue")
}
switch topicPickingState {
case .Subtopic:
vc.parentTopic = selectedTopic
default:
vc.parentTopic = parentTopic
}
vc.managedObjectContext = managedObjectContext
vc.modalPresentationStyle = .Custom
vc.transitioningDelegate = createTopicTransitioningDelegate
vc.createTopicDelegate = self
}
}
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? Cell else {
return
}
if cell.addableCell {
performSegueWithIdentifier(SegueIdentifier.ShowCreateTopic.rawValue, sender: nil)
} else {
guard let topic = cell.topic else {
return
}
switch topicPickingState {
case .Topic:
didPickTopic(topic)
case .Subtopic:
didPickSubtopic(topic)
case .None:
return
}
}
}
private func didPickTopic(topic: Topic) {
selectedTopic = topic
topicPickingState = .Subtopic
setupDataSourceForTopic(topic)
updateUIForState()
}
public override func viewDidLayoutSubviews() {
preferredContentSize = stackView.bounds.size
}
private func didPickSubtopic(subtopic: Topic) {
selectedSubtopic = subtopic
topicPickingState = .None
updateUIForState()
}
private func updateUIForState() {
updateButtonTitlesForCurrentState()
updateModalLayoutForCurrentState()
}
private func updateButtonTitlesForCurrentState() {
var topicButtonTitle: String
var subTopicButtonTitle: String
if let topic = selectedTopic {
topicButtonTitle = topic.iconAndName
} else {
topicButtonTitle = "Choose Topic"
}
if let subTopic = selectedSubtopic {
subTopicButtonTitle = subTopic.iconAndName
} else {
subTopicButtonTitle = "Choose Subtopic"
}
chooseTopicButton.setTitle(topicButtonTitle, forState: .Normal)
chooseSubTopicButton.setTitle(subTopicButtonTitle, forState: .Normal)
}
private func updateModalLayoutForCurrentState() {
var subTopicButtonHidden: Bool
var collectionViewHidden: Bool
subTopicButtonHidden = (selectedTopic == nil)
switch topicPickingState {
case .Subtopic, .Topic:
collectionViewHidden = false
case .None:
collectionViewHidden = true
}
chooseSubTopicButton.hidden = subTopicButtonHidden
collectionView.hidden = collectionViewHidden
}
private enum SegueIdentifier: String {
case ShowCreateTopic = "ShowCreateTopic"
}
private enum TopicPickingState {
case None
case Topic
case Subtopic
}
}
extension ChooseTopicViewController: CreateTopicDelegate {
public func didCreateTopic(topic: Topic) {
switch topicPickingState {
case .Topic:
didPickTopic(topic)
case .Subtopic:
didPickSubtopic(topic)
case .None:
return
}
}
}
extension ChooseTopicViewController: AddableFetchedResultsCollectionDataSourceDelegate {
public typealias Cell = TopicCollectionViewCell
public typealias Object = Topic
public typealias AddableCell = TopicCollectionViewCell
public func cellIdentifierForObject(object: Object) -> String {
return "TopicShareCell"
}
public func cellIdentifierForAddable() -> String {
return "TopicShareCell"
}
public func configureCell(cell: Cell, object: Object) {
cell.topic = object
cell.addableCell = false
}
public func configureAddableCell(cell: AddableCell) {
cell.addableCell = true
}
} | mit | ddb0856054d5ae3b5a603803c626caf9 | 30.798319 | 148 | 0.645831 | 5.76753 | false | false | false | false |
Geor9eLau/WorkHelper | WorkoutHelper/HomePageViewController.swift | 1 | 3314 | //
// HomePageViewController.swift
// WorkoutHelper
//
// Created by George on 2016/12/26.
// Copyright © 2016年 George. All rights reserved.
//
import UIKit
class HomePageViewController: BaseViewController, iCarouselDataSource, iCarouselDelegate {
@IBOutlet weak var carousel: iCarousel!
// private lazy var colltectionView: UICollectionView = {
// let layout = UICollectionViewFlowLayout()
// layout.itemSize = CGSize(width: 70, height:90.0)
// layout.minimumLineSpacing = 5.0;
//
// layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20)
// let tmpCollectionView = UICollectionView(frame: CGRect(x: 0, y: 100, width: SCREEN_WIDTH , height: SCREEN_HEIGHT - 250), collectionViewLayout: layout)
// tmpCollectionView.delegate = self
// tmpCollectionView.dataSource = self
// tmpCollectionView.register(UINib.init(nibName: "ChooseCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
// tmpCollectionView.collectionViewLayout = layout
// tmpCollectionView.backgroundColor = UIColor.clear
// return tmpCollectionView
// }()
private var recordTf: UITextField = {
let tmp = UITextField(frame: CGRect(x: 20, y: SCREEN_HEIGHT - 200, width: SCREEN_WIDTH - 40, height: 150))
tmp.allowsEditingTextAttributes = false
tmp.isEnabled = false
return tmp
}()
private var dataSource: [BodyPart] = ALL_BODY_PART_CHOICES
override func viewDidLoad() {
super.viewDidLoad()
title = "Home Page"
carousel.type = .coverFlow
carousel.bounces = false
carousel.currentItemIndex = 1
// Do any additional setup after loading the view.
}
// MARK: - Private
private func setupUI() {
}
// MARK: - Event Handler
@IBAction func workoutBtnDidClicked(_ sender: UIButton) {
let motionVC = MotionViewController(part: dataSource[carousel.currentItemIndex])
motionVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(motionVC, animated: true)
}
// MARK: - iCarouselDataSource
func numberOfItems(in carousel: iCarousel) -> Int {
return dataSource.count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var itemView: CarouselItemView
let part = dataSource[index]
if (view as? CarouselItemView) != nil{
itemView = view as! CarouselItemView
} else {
//don't do anything specific to the index within
//this `if ... else` statement because the view will be
//recycled and used with other index values later
itemView = CarouselItemView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
}
itemView.imgView.image = UIImage(named: part.rawValue)
itemView.titleLbl.text = part.rawValue
return itemView
}
// MARK: - iCarouselDelegate
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if (option == .spacing) {
return value * 1.1
}
return value
}
}
| mit | f698d587efeeda51cd660f774e0ea931 | 32.11 | 160 | 0.631833 | 4.743553 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Calling/CallCenterSupport.swift | 1 | 3263 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
/// An opaque OTR calling message.
public typealias WireCallMessageToken = UnsafeMutableRawPointer
/// The possible types of call.
public enum AVSCallType: Int32 {
case normal = 0
case video = 1
case audioOnly = 2
}
/// Possible types of conversation in which calls can be initiated.
public enum AVSConversationType: Int32 {
case oneToOne = 0
case group = 1
case conference = 2
}
/// An object that represents a calling event.
public struct CallEvent {
let data: Data
let currentTimestamp: Date
let serverTimestamp: Date
let conversationId: AVSIdentifier
let userId: AVSIdentifier
let clientId: String
}
// MARK: - Call center transport
/// A block of code executed when the config request finishes.
public typealias CallConfigRequestCompletion = (String?, Int) -> Void
/// An object that can perform requests on behalf of the call center.
public protocol WireCallCenterTransport: AnyObject {
/// Sends a calling message.
///
/// - Parameters:
/// - data: The message payload.
/// - conversationId: The conversation in which the message is sent.
/// - targets: Exact recipients of the message. If `nil`, all conversation participants are recipients.
/// - completionHandler: A handler when the network request completes with http status code.
func send(data: Data, conversationId: AVSIdentifier, targets: [AVSClient]?, completionHandler: @escaping ((_ status: Int) -> Void))
/// Send a calling message to the SFT server (for conference calling).
///
/// - Parameters:
/// - data: The message payload.
/// - url: The url of the server.
/// - completionHandler: A handler when the network request completes with the response payload.
func sendSFT(data: Data, url: URL, completionHandler: @escaping ((Result<Data>) -> Void))
/// Request the call configuration from the backend.
///
/// - Parameters:
/// - completionHandler: A handler when the network request completes with the response payload.
func requestCallConfig(completionHandler: @escaping CallConfigRequestCompletion)
/// Request the client list for a conversation.
///
/// - Parameters:
/// - conversationId: A conversation from which the client list is queried.
/// - completionHandler: A handler when the network request completes with the list of clients.
func requestClientsList(conversationId: AVSIdentifier, completionHandler: @escaping ([AVSClient]) -> Void)
}
| gpl-3.0 | ccdc6d51d82e8b3663d486f3834c43af | 30.990196 | 135 | 0.703034 | 4.641536 | false | false | false | false |
isRaining/Swift30days | 1_day/008-字符串/008-字符串/ViewController.swift | 1 | 2123 | import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
demo()
demo1()
demo2()
demo3()
demo4()
}
//MARK: - 字符串的遍历
/**
String 是一个结构体
* 可以直接遍历
*
*/
func demo() -> () {
let str = "我要跑打破哦死女卡是"
for c in str.characters{
print(c)
}
}
//MARK: - 字符串长度
func demo1() -> () {
let str = "hello world"
//使用utf-8编码,每个汉字三个字节
//输出制定编码对应的字节数量
print(str.lengthOfBytes(using: .utf8))
//输出字符串字符个数
print(str.characters.count)
//使用NSString中转
let ocStr = str as NSString
print(ocStr.length)
}
//MARK: - 字符串拼接
func demo2() -> () {
let name = "laowang"
let age = 89
let title:String? = "BOSS"
let str = "\(name) \(age) \(title ?? "员工")"
print(str)
}
//MARK: - 格式化字符串
func demo3() -> () {
let h = 8
let m = 7
let s = 6
let dateStr = "\(h):\(m):\(s)"
print(dateStr)
let dateStr1 = String(format: "%02d:%02d:%02d:",h,m,s)
print(dateStr1)
}
//MARK: - 字符串的子串
//一般拿NSString作为中转,因为swift取子串的方法一直在优化
func demo4() -> () {
let str = "挨饿也不反对和健康 v 和部分的时间出现"
let ocStr = str as NSString
let s1 = ocStr.substring(to: 3)
let s2 = ocStr.substring(with: NSMakeRange(2, 3))
let s3 = ocStr.substring(from: 4)
print("\(s1) : \(s2) : \(s3)")
print(str.startIndex)
print(str.endIndex)
print(str.substring(from: "ye".startIndex))
}
}
| mit | 1e0275d04c9f75c313faed5ad7927fdf | 20.941176 | 80 | 0.464343 | 3.572797 | false | false | false | false |
okerivy/Coursera | Coursera/Coursera/Classes/Module/Main/MainViewController.swift | 1 | 3087 | //
// MainViewController.swift
// Coursera
//
// Created by okerivy on 15/9/30.
// Copyright © 2015年 okerivy. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// 先用 kvc 替换 tabbar
let tb = MainTabBar()
setValue(tb, forKeyPath: "tabBar")
tb.composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
addChildViewControllers()
}
/// 点击中间按钮 按钮点击方法必须公开
func composeButtonClick() {
print(__FUNCTION__)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print(tabBar.items)
}
/// 添加所有的子控制器
private func addChildViewControllers() {
//加载 json
let path = NSBundle.mainBundle().pathForResource("MainVCSetting.json", ofType: nil)!
let data = NSData(contentsOfFile: path)!
// 反序列化
do {
let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
// 在遍历数组的时候,必须指明数组中包含对象的类型,包括字典的格式
for dict in array as! [[String: String]]{
print(dict)
addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
}
} catch(_) {
}
}
/// 添加子控制器
///
/// - parameter vc: 子控制器
/// - parameter title: 标题
/// - parameter imageName: 图片名称
private func addChildViewController(vcName: String, title: String, imageName: String) {
tabBar.tintColor = UIColor.orangeColor()
// Swift 中的类名是包含命名空间的,如果希望用字符串动态创建并且实例化类,需要按照以下代码格式
// Swift 设定对象的类型 写在右侧 as! String as? String
// 自动推导, 右侧指定好, 左侧变量类型自然 ok
let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
// 将字符串转成类
let anyobjecType: AnyObject.Type = NSClassFromString(ns + "." + vcName)!
if anyobjecType is UIViewController.Type {
let vc = (anyobjecType as! UIViewController.Type).init()
vc.title = title
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
let nav = UINavigationController(rootViewController: vc)
addChildViewController(nav)
print(vc)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | ae981e2e42090e0d4c5222dcda9b11ff | 27.265306 | 119 | 0.58556 | 4.809028 | false | false | false | false |
18775134221/SwiftBase | SwiftTest/SwiftTest/Classes/tools/Extention/UIImage-Extension.swift | 2 | 978 | //
// UIImage-Extension.swift
// SwiftTest
//
// Created by MAC on 2016/12/28.
// Copyright © 2016年 MAC. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
// MARK: - 根据颜色创建Image
class func createImage(color: UIColor) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
// MARK: 拉伸图片做背景
class func getStretchableImage(imageName: String) -> UIImage {
var image = UIImage(named: imageName)
image = image?.stretchableImage(withLeftCapWidth: Int((image?.size.width)! * 0.5), topCapHeight: Int((image?.size.height)! * 0.5))
return image!
}
}
| apache-2.0 | 8020a011efa6b14e56ad383945d93770 | 28.65625 | 138 | 0.649104 | 4.236607 | false | false | false | false |
IBM-Swift/BluePic | BluePic-CloudFunctions/actions/VisualRecognition.swift | 1 | 1934 | /**
* Run Watson Visual Recognition image analysis
*/
import KituraNet
import Dispatch
import Foundation
import SwiftyJSON
func main(args: [String:Any]) -> [String:Any] {
var str = ""
var result: [String:Any] = [
"visualRecognition": str
]
guard let visualRecognitionKey = args["visualRecognitionKey"] as? String,
let imageURL = args["imageURL"] as? String else {
return result
}
let requestOptions: [ClientRequest.Options] = [ .method("GET"),
.schema("https://"),
.hostname("gateway-a.watsonplatform.net"),
.port(443),
.path("/visual-recognition/api/v3/classify?api_key=\(visualRecognitionKey)&url=\(imageURL)&version=2016-05-20")
]
let req = HTTP.request(requestOptions) { response in
do {
if let response = response, let responseStr = try response.readString(),
let dataResponse = responseStr.data(using: String.Encoding.utf8, allowLossyConversion: true) {
let jsonObj = JSON(data: dataResponse)
if let imageClasses = jsonObj["images"][0]["classifiers"][0]["classes"].array {
for imageClass in imageClasses {
if let label = imageClass["class"].string, let confidence = imageClass["score"].double {
if (str.characters.count > 0) {
str = str + ","
}
str += "{\"label\":\"\(label)\",\"confidence\":\(confidence)}"
}
}
}
}
} catch {
print("Error: \(error)")
}
}
req.end()
str = "[\(str)]"
result = [
"visualRecognition": str
]
return result
}
| apache-2.0 | e61c0906f2e859831fb4392e70004df9 | 31.233333 | 163 | 0.489659 | 4.908629 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK | Evrythng-iOS/CompositeEncoding.swift | 1 | 998 | //
// CompositeEncoding.swift
// EvrythngiOS
//
// Created by JD Castro on 26/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
import Moya
import Alamofire
struct CompositeEncoding: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard let parameters = parameters else {
return try urlRequest.asURLRequest()
}
let queryParameters = (parameters["query"] as! Parameters)
let queryRequest = try URLEncoding(destination: .queryString).encode(urlRequest, with: queryParameters)
if let body = parameters["body"] {
let bodyParameters = (body as! Parameters)
var bodyRequest = try JSONEncoding().encode(urlRequest, with: bodyParameters)
bodyRequest.url = queryRequest.url
return bodyRequest
} else {
return queryRequest
}
}
}
| apache-2.0 | cf1ef5eaf03649bf3c167615067929ce | 30.15625 | 112 | 0.641926 | 5.01005 | false | false | false | false |
JohnEstropia/CoreStore | Sources/DiffableDataSourceSnapshotProtocol.swift | 1 | 4407 | //
// DiffableDataSourceSnapshotProtocol.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
// MARK: - DiffableDataSourceSnapshotProtocol
internal protocol DiffableDataSourceSnapshotProtocol {
init()
var numberOfItems: Int { get }
var numberOfSections: Int { get }
var sectionIdentifiers: [String] { get }
var itemIdentifiers: [NSManagedObjectID] { get }
func numberOfItems(inSection identifier: String) -> Int
func itemIdentifiers(inSection identifier: String) -> [NSManagedObjectID]
func sectionIdentifier(containingItem identifier: NSManagedObjectID) -> String?
func indexOfItem(_ identifier: NSManagedObjectID) -> Int?
func indexOfSection(_ identifier: String) -> Int?
mutating func appendItems<C: Collection>(_ identifiers: C, toSection sectionIdentifier: String?) where C.Element == NSManagedObjectID
mutating func insertItems<C: Collection>(_ identifiers: C, beforeItem beforeIdentifier: NSManagedObjectID) where C.Element == NSManagedObjectID
mutating func insertItems<C: Collection>(_ identifiers: C, afterItem afterIdentifier: NSManagedObjectID) where C.Element == NSManagedObjectID
mutating func deleteItems<C: Collection>(_ identifiers: C) where C.Element == NSManagedObjectID
mutating func deleteAllItems()
mutating func moveItem(_ identifier: NSManagedObjectID, beforeItem toIdentifier: NSManagedObjectID)
mutating func moveItem(_ identifier: NSManagedObjectID, afterItem toIdentifier: NSManagedObjectID)
mutating func reloadItems<C: Collection>(_ identifiers: C) where C.Element == NSManagedObjectID
mutating func appendSections<C: Collection>(_ identifiers: C) where C.Element == String
mutating func insertSections<C: Collection>(_ identifiers: C, beforeSection toIdentifier: String) where C.Element == String
mutating func insertSections<C: Collection>(_ identifiers: C, afterSection toIdentifier: String) where C.Element == String
mutating func deleteSections<C: Collection>(_ identifiers: C) where C.Element == String
mutating func moveSection(_ identifier: String, beforeSection toIdentifier: String)
mutating func moveSection(_ identifier: String, afterSection toIdentifier: String)
mutating func reloadSections<C: Collection>(_ identifiers: C) where C.Element == String
mutating func unsafeAppendItems<C: Collection>(_ identifiers: C, toSectionAt sectionIndex: Int) where C.Element == NSManagedObjectID
mutating func unsafeInsertItems<C: Collection>(_ identifiers: C, at indexPath: IndexPath) where C.Element == NSManagedObjectID
mutating func unsafeDeleteItems<C: Collection>(at indexPaths: C) where C.Element == IndexPath
mutating func unsafeMoveItem(at indexPath: IndexPath, to newIndexPath: IndexPath)
mutating func unsafeReloadItems<C: Collection>(at indexPaths: C) where C.Element == IndexPath
mutating func unsafeInsertSections<C: Collection>(_ identifiers: C, at sectionIndex: Int) where C.Element == String
mutating func unsafeDeleteSections<C: Collection>(at sectionIndices: C) where C.Element == Int
mutating func unsafeMoveSection(at sectionIndex: Int, to newSectionIndex: Int)
mutating func unsafeReloadSections<C: Collection>(at sectionIndices: C) where C.Element == Int
}
| mit | 93f5df251c04b193981b74db9eaf5cfa | 59.356164 | 147 | 0.764639 | 4.901001 | false | false | false | false |
alexktchen/ExchangeRate | ExchangeRate/TodaySettingViewController.swift | 1 | 3043 | //
// TodayViewController.swift
// ExchangeRate
//
// Created by Alex Chen on 2015/10/3.
// Copyright © 2015 AlexChen. All rights reserved.
//
import UIKit
import Core
class TodaySettingViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CountryPassValueDelegate {
@IBOutlet weak var tableView: UITableView!
var isMajor = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "today_view_title".localized
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.backgroundColor = UIColor.whiteColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func currenctSelected(aCurrency: Currency) {
if isMajor {
UserDefaultDataService.sharedInstance.setMajorCurrencysData(aCurrency)
} else {
UserDefaultDataService.sharedInstance.setMinorCurrencysData(aCurrency)
}
self.tableView.reloadData()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
if indexPath.row == 0{
if let item = UserDefaultDataService.sharedInstance.getMajorCurrencysData() {
cell.textLabel?.text = "today_view_detail_major_currency".localized
cell.detailTextLabel?.text = item.displayName
} else {
cell.textLabel?.text = "today_view_detail_no_selected".localized
cell.detailTextLabel?.text = ""
}
} else {
if let item = UserDefaultDataService.sharedInstance.getMinorCurrencysData() {
cell.textLabel?.text = "today_view_detail_minor_currency".localized
cell.detailTextLabel?.text = item.displayName
} else {
cell.textLabel?.text = "today_view_detail_no_selected".localized
cell.detailTextLabel?.text = ""
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
isMajor = true
} else {
isMajor = false
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginWebView = storyboard.instantiateViewControllerWithIdentifier("CountryFetchTableView") as! CountryFetchTableView
loginWebView.delegate = self
self.navigationController!.pushViewController(loginWebView, animated: true)
}
}
| mit | b23aec77f595fc10bb5c2f6cc019270d | 33.568182 | 128 | 0.657462 | 5.253886 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Exercise1.playgroundpage/Sources/SetUp.swift | 1 | 3686 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
let world = loadGridWorld(named: "5.1")
public let actor = Actor()
let switchCoordinates = [
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 2),
Coordinate(column: 2, row: 2)
]
public func playgroundPrologue() {
placeActor()
placeRandomNodes()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomItems()
}
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeActor() {
world.place(actor, facing: west, at: Coordinate(column: 4, row: 2))
}
func placeRandomNodes() {
let switchItem = Switch()
for coord in switchCoordinates {
world.place(RandomNode(resembling: switchItem), at: coord)
}
}
func realizeRandomItems() {
let switchNodes = world.place(nodeOfType: Switch.self, at: switchCoordinates)
for switchNode in switchNodes {
switchNode.isOn = randomBool()
}
// Ensure at least one Switch is off.
let switchNode = switchNodes.randomElement
switchNode?.isOn = false
}
func placeBlocks() {
let obstacles = [
Coordinate(column: 1, row: 0),
Coordinate(column: 1, row: 1),
Coordinate(column: 1, row: 3),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 1),
Coordinate(column: 3, row: 1),
Coordinate(column: 2, row: 3),
Coordinate(column: 3, row: 3),
]
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
let tiers = [
Coordinate(column: 2, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 4, row: 0),
Coordinate(column: 4, row: 0),
Coordinate(column: 4, row: 0),
Coordinate(column: 5, row: 0),
Coordinate(column: 5, row: 0),
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 2),
Coordinate(column: 2, row: 2),
Coordinate(column: 2, row: 4),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 4),
Coordinate(column: 4, row: 4),
Coordinate(column: 4, row: 4),
Coordinate(column: 4, row: 4),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 4),
]
world.placeBlocks(at: tiers)
world.place(Stair(), at: Coordinate(column: 0, row: 1))
world.place(Stair(), facing: north, at: Coordinate(column: 0, row: 3))
world.place(Stair(), facing: east, at: Coordinate(column: 3, row: 2))
}
| mit | c3d4d8b83203245662b9f78159a20a46 | 28.725806 | 89 | 0.495931 | 4.550617 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/NluEnrichmentEntities.swift | 1 | 3885 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
An object speficying the Entities enrichment and related parameters.
*/
public struct NluEnrichmentEntities: Codable, Equatable {
/**
When `true`, sentiment analysis of entities will be performed on the specified field.
*/
public var sentiment: Bool?
/**
When `true`, emotion detection of entities will be performed on the specified field.
*/
public var emotion: Bool?
/**
The maximum number of entities to extract for each instance of the specified field.
*/
public var limit: Int?
/**
When `true`, the number of mentions of each identified entity is recorded. The default is `false`.
*/
public var mentions: Bool?
/**
When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`.
*/
public var mentionTypes: Bool?
/**
When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is
`false`.
*/
public var sentenceLocations: Bool?
/**
The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, or
the default public model `alchemy`.
*/
public var model: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case sentiment = "sentiment"
case emotion = "emotion"
case limit = "limit"
case mentions = "mentions"
case mentionTypes = "mention_types"
case sentenceLocations = "sentence_locations"
case model = "model"
}
/**
Initialize a `NluEnrichmentEntities` with member variables.
- parameter sentiment: When `true`, sentiment analysis of entities will be performed on the specified field.
- parameter emotion: When `true`, emotion detection of entities will be performed on the specified field.
- parameter limit: The maximum number of entities to extract for each instance of the specified field.
- parameter mentions: When `true`, the number of mentions of each identified entity is recorded. The default is
`false`.
- parameter mentionTypes: When `true`, the types of mentions for each idetifieid entity is recorded. The default
is `false`.
- parameter sentenceLocations: When `true`, a list of sentence locations for each instance of each identified
entity is recorded. The default is `false`.
- parameter model: The enrichement model to use with entity extraction. May be a custom model provided by Watson
Knowledge Studio, or the default public model `alchemy`.
- returns: An initialized `NluEnrichmentEntities`.
*/
public init(
sentiment: Bool? = nil,
emotion: Bool? = nil,
limit: Int? = nil,
mentions: Bool? = nil,
mentionTypes: Bool? = nil,
sentenceLocations: Bool? = nil,
model: String? = nil
)
{
self.sentiment = sentiment
self.emotion = emotion
self.limit = limit
self.mentions = mentions
self.mentionTypes = mentionTypes
self.sentenceLocations = sentenceLocations
self.model = model
}
}
| apache-2.0 | fb1aade80b31966d1a21d20bac9c7400 | 34.972222 | 119 | 0.673874 | 4.592199 | false | false | false | false |
DAloG/BlueCap | BlueCap/Central/PeripheralServicesViewController.swift | 1 | 4310 | //
// PeripheralServicesViewController.swift
// BlueCap
//
// Created by Troy Stribling on 6/22/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class PeripheralServicesViewController : UITableViewController {
weak var peripheral : Peripheral!
var peripheralViewController : PeripheralViewController!
var progressView = ProgressView()
struct MainStoryboard {
static let peripheralServiceCell = "PeripheralServiceCell"
static let peripheralServicesCharacteritics = "PeripheralServicesCharacteritics"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Plain, target:nil, action:nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.updateWhenActive()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"peripheralDisconnected", name:BlueCapNotification.peripheralDisconnected, object:self.peripheral!)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) {
if segue.identifier == MainStoryboard.peripheralServicesCharacteritics {
if let peripheral = self.peripheral {
if let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell) {
let viewController = segue.destinationViewController as! PeripheralServiceCharacteristicsViewController
viewController.service = peripheral.services[selectedIndex.row]
viewController.peripheralViewController = self.peripheralViewController
}
}
}
}
override func shouldPerformSegueWithIdentifier(identifier:String?, sender:AnyObject?) -> Bool {
return true
}
func peripheralDisconnected() {
Logger.debug()
if self.peripheralViewController.peripehealConnected {
self.presentViewController(UIAlertController.alertWithMessage("Peripheral disconnected"), animated:true, completion:nil)
self.peripheralViewController.peripehealConnected = false
self.updateWhenActive()
}
}
func didResignActive() {
Logger.debug()
self.navigationController?.popToRootViewControllerAnimated(false)
}
func didBecomeActive() {
Logger.debug()
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int {
if let peripheral = self.peripheral {
return peripheral.services.count
} else {
return 0;
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralServiceCell, forIndexPath: indexPath) as! NameUUIDCell
let service = peripheral.services[indexPath.row]
cell.nameLabel.text = service.name
cell.uuidLabel.text = service.uuid.UUIDString
if let peripheralViewController = self.peripheralViewController {
if peripheralViewController.peripehealConnected {
cell.nameLabel.textColor = UIColor.blackColor()
} else {
cell.nameLabel.textColor = UIColor.lightGrayColor()
}
} else {
cell.nameLabel.textColor = UIColor.blackColor()
}
return cell
}
// UITableViewDelegate
}
| mit | 80cb706ac5769e35eb5629342c038936 | 37.141593 | 171 | 0.679582 | 6.011158 | false | false | false | false |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift闭包/main.swift | 1 | 2855 |
func add(a: Float, b : Float) -> Float {
return a + b
}
func addFunc(a: Float, b : Float , fun: ( Float, Float ) -> Float ) -> Float {
return fun(a, b)
}
//addFunc(2, b: 3) { (c, d) -> Float in
// return c + d
//}
//
//let add0 = addFunc(3, b: 4, fun: add)
//print("\(__FUNCTION__) \(add0)")
//
//func square(a:Float) -> Float {
// return a * a
//}
//
//func cube(a:Float) -> Float {
// return a * a * a
//}
//
//func averageSumOfSquares(a:Float,b:Float) -> Float {
// return (square(a) + square(b)) / 2.0
//}
//
//func averageSumOfCubes(a:Float,b:Float) -> Float {
// return (cube(a) + cube(b)) / 2.0
//}
//
//
//print(averageSumOfCubes(4, b: 5))
//
//func averageOfFunction(a:Float,b:Float, fun:Float->Float) -> Float {
// return (fun(a) + fun(b))/2
//}
//func averageOfFunction(a:Float,b:Float, fun:(Float -> Float)) -> Float {
// return (fun(a) + fun(b))/2
//}
//
//
////
//print("\(__FUNCTION__) \(averageOfFunction(4, b: 3, fun: square))")
//
////averageOfFunction(4, b: 3, fun: square)
////
////averageOfFunction(4, b: 3, fun: square)
//
//print("\(__FUNCTION__) \(averageOfFunction(3, b: 4, fun: {(x: Float) -> Float in return x * x}))")
//
//print("\(__FUNCTION__) \(averageOfFunction(3, b: 4, fun: {x in return x * x}))")
//
//print("\(__FUNCTION__) \(averageOfFunction(3, b: 4, fun: {x in x * x}))")
//
//print("\(__FUNCTION__) \(averageOfFunction(3, b: 4, fun: {$0 * $0}))")
//
//
////Map
////map用于将每个数组元素通过某个方法进行转换。
//
//let array = [4, 5]
//
//func intToString(a: Int) -> String{
// return String(a) + "?"
//}
//
//let arrayString = array.map{intToString($0)}
//let arrayString = array.map(intToString)
//
//print("\(__FUNCTION__) \(arrayString)")
//
//
//print("\(__FUNCTION__) \(array.map{"\($0)" + "?"})")
//print("\(__FUNCTION__) \(array.map{"\($0)?"})")
//filter用于选择数组元素中满足某种条件的元素。
let moneyArray = [23, 45, 78]
//var filteredArray : [Int] = []
//for money in moneyArray {
// if (money > 30) {
// filteredArray += [money]
// }
//}
//
//print("\(__FUNCTION__) \(filteredArray)")
//print("\(__FUNCTION__) \(moneyArray.filter({$0 > 30}))")
//let arrayBool = moneyArray.filter{$0 > 30}
//
//print("\(__FUNCTION__) \(arrayBool)")
//
////Reduce
////
////reduce方法把数组元素组合计算为一个值。
var sum = 0
for money in moneyArray {
sum = sum + money
}
//
print("\(__FUNCTION__) \(sum)")
//moneyArray.reduce(4, combine: +)
//
////reduce(initial: U, combine: (U, T) -> U) -> U
////
////接收两个参数,一个为类型U的初始值,另一个为把类型为U的元素和类型为T的元素组合成一个类型为U的值的函数。最终结果整个数组就变成了一个类型为U的值。
//
//
//
//print("\(__FUNCTION__) \(moneyArray.reduce(0, combine: +))")
| mit | 42f3a066f7a587bd326b4acb5894852a | 18.75 | 100 | 0.550825 | 2.712799 | false | false | false | false |
AZaps/Scribe-Swift | Scribe/QuestLogViewController.swift | 1 | 5648 | //
// QuestLogViewController.swift
// Scribe
//
// Created by Anthony Zaprzalka on 9/13/16.
// Copyright © 2016 Anthony Zaprzalka. All rights reserved.
//
// Displays all quests in a table
// Quests can be added, deleted, and completed
import UIKit
import CoreData
class QuestLogViewController: UITableViewController,NSFetchedResultsControllerDelegate {
var quests = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Update the array to show on the UITableView
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let sortDescription = NSSortDescriptor(key: "date", ascending: true)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Quest")
fetchRequest.sortDescriptors = [sortDescription]
do {
let results = try managedContext.fetch(fetchRequest)
/*
Using
quests = results as! [NSManagedObject]
causes a memory leak on every appearance of this viewController
I fixed the memory leak by updating the array in the following 3 line.
This may not be a long term solution as it empties and assignes values after each time the view appears, that could cause major slowdown with larger arrays.
Some array parsing might need to be added to insert a new element instead. Since reappending each time will make duplicates on the fetch
*/
quests.removeAll()
for item in results {
quests.append(item as! NSManagedObject)
}
} catch let error as NSError {
print("ERROR \(error)")
}
// Reload the table
reloadTable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Override Table Views
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestCell")
let quest = quests[(indexPath as NSIndexPath).row]
cell!.textLabel!.text = quest.value(forKey: "title") as? String
return cell!
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
// Delete core data entry
let selectedCell = tableView.cellForRow(at: indexPath)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Quest")
let referenceString: String = (selectedCell!.value(forKey: "text"))! as! String
let searchPredicate = NSPredicate(format: "title == %@", referenceString)
fetchRequest.predicate = searchPredicate
do {
let fetchResults = try managedContext.fetch(fetchRequest) as? [NSManagedObject]
for item in fetchResults! {
managedContext.delete(item)
if managedContext.hasChanges {
do {
try managedContext.save()
} catch let error as NSError {
print("ERROR: \(error)")
}
}
}
} catch let error as NSError {
print("ERROR: \(error)")
}
// Delete array entry
quests.remove(at: (indexPath as NSIndexPath).row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
reloadTable()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quests.count
}
// MARK: - Prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CellDetailViewSegue" {
// Delegate to ViewController
let cellDetailViewController = segue.destination as! QuestDetailViewController
// Get the index path from the selected cell
let selectedIndex = self.tableView.indexPath(for: sender as! UITableViewCell)
// Get the cell from the selected index row
let selectedCell = quests[(selectedIndex! as NSIndexPath).row]
// Get properties of the cell to send
cellDetailViewController.selectedQuest.title = selectedCell.value(forKey: "title") as! String
cellDetailViewController.selectedQuest.givenBy = selectedCell.value(forKey: "givenBy") as? String
cellDetailViewController.selectedQuest.notes = selectedCell.value(forKey: "notes") as? String
cellDetailViewController.selectedQuest.date = selectedCell.value(forKey: "date") as! Date
}
}
@IBOutlet var questLogDataTable: UITableView!
@IBAction func viewQuestLogViewController(_ segue: UIStoryboardSegue) {
}
@IBAction func saveQuestToQuestLogViewController(_ segue: UIStoryboardSegue) {
}
func reloadTable() {
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.reloadData()
})
}
}
| mit | a0801e8a403eac9d589331b0616c8679 | 41.458647 | 169 | 0.627767 | 5.63011 | false | false | false | false |
kevinhankens/runalysis | Runalysis/RouteView.swift | 1 | 10274 | //
// RouteView.swift
// Runalysis
//
// Created by Kevin Hankens on 8/18/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
/*!
* Displays a route.
*/
class RouteView: UIView {
// The core data storage of routes.
var routeStore: RouteStore?
// The currently viewed route ID.
var routeId: NSNumber = 0
// Provides a summary of the array of RoutePoint objects.
var summary: RouteSummary?
// The minimum x value of the route points.
var gridMinX = 0.0
// The maximum x value of the route points.
var gridMaxX = 0.0
// The minimum y value of the route points.
var gridMinY = 0.0
// The maximum y value of the route points.
var gridMaxY = 0.0
// The scale between the grid points and the canvas points.
var gridRatio = 0.0
// The width of the course drawing.
var lineWidth = CGFloat(5.0)
/*!
* Factory method to create a RouteView object.
*
* @param CGFloat x
* @param CGFloat y
* @param CGFloat width
* @param CGFloat height
* @param NSNumber routeId
* @param RouteStore routeStore
* @param RouteSummary routeSummary
*
* @return RouteView
*/
class func createRouteView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, routeId: NSNumber, routeStore: RouteStore, routeSummary: RouteSummary)->RouteView {
let route = RouteView(frame: CGRectMake(x, y, width, width))
route.summary = routeSummary
route.routeStore = routeStore
route.updateRoute()
route.sizeToFit()
return route
}
/*!
* Updates the currently viewed route.
*
* @return void
*/
func updateRoute() {
self.displayLatest()
}
/*!
*
*/
func displayLatest() {
self.determineGrid()
self.setNeedsDisplay()
}
/*!
* Determines the scale of the route in terms of the current canvas.
*
* @return void
*/
func determineGrid() {
if self.summary!.points?.count > 0 {
if let zp = self.summary!.points![0] as? Route {
self.gridMinX = zp.longitude_raw
self.gridMaxX = zp.longitude_raw
self.gridMinY = zp.latitude_raw
self.gridMaxY = zp.latitude_raw
}
for point in self.summary!.points! {
if let p = point as? Route {
if p.longitude_raw > self.gridMaxX {
self.gridMaxX = p.longitude_raw
}
else if p.longitude_raw < self.gridMinX {
self.gridMinX = p.longitude_raw
}
if p.latitude_raw > self.gridMaxY {
self.gridMaxY = p.latitude_raw
}
else if p.latitude_raw < self.gridMinY {
self.gridMinY = p.latitude_raw
}
}
}
}
let diffX = fabs(self.gridMaxX - self.gridMinX)
let diffY = fabs(self.gridMaxY - self.gridMinY)
if (diffX > diffY) {
if diffX > 0 {
self.gridRatio = Double(self.bounds.width - 20) / diffX
}
else {
self.gridRatio = 1
}
}
else {
if diffY > 0 {
self.gridRatio = Double(self.bounds.width - 20) / diffY
}
else {
self.gridRatio = 1
}
}
//println("\(self.bounds)")
//println("\(self.gridMinX) \(self.gridMaxX) \(self.gridMinY) \(self.gridMaxY)")
}
/*!
* Overrides UIView::drawRect()
*
* Draws the currently viewed route and information.
*
* @param CGRect rect
*
* @return void
*/
override func drawRect(rect: CGRect) {
// Let the line width scale for the screen size.
self.lineWidth = ceil(1.2 * self.bounds.width/100)
if self.lineWidth < 5 {
self.lineWidth = 5
} else if self.lineWidth > 8 {
self.lineWidth = 8
}
var unitCounter = 0
var unitTest = 0
var total = Double(0)
let ctx = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(ctx, GlobalTheme.getBackgroundColor().CGColor);
CGContextFillRect(ctx, self.bounds)
var px: CGFloat = 0.0
var py: CGFloat = 0.0
var ppx: CGFloat = 0.0
var ppy: CGFloat = 0.0
var cx: CGFloat = 0.0
var cy: CGFloat = 0.0
var dx: CGFloat = 0.0
var dy: CGFloat = 0.0
var wx: CGFloat = 0.0
var wy: CGFloat = 0.0
var bx: CGFloat = 0.0
var by: CGFloat = 0.0
var dhyp: CGFloat = 0.0
var dratio: CGFloat = 0.0
var q: Int = 0
var d: CGFloat = 0.0
//var ptime: NSNumber = 0.0
var start = true
var speedColor: CGColor
var animation_steps = 0
if self.summary!.points?.count > 0 {
for point in self.summary!.points! {
if let p = point as? Route {
cx = CGFloat((p.longitude_raw - self.gridMinX) * self.gridRatio) + 10.0
cy = CGFloat(self.frame.height) - CGFloat((p.latitude_raw - self.gridMinY) * self.gridRatio) - 10.0
animation_steps++
if animation_steps > self.summary!.animation_length {
break
}
if start || p.velocity.doubleValue > 0.0 {
if start {
start = false
}
else {
speedColor = GlobalTheme.getSpeedColor(p.relVelMovingAvg, setAlpha: 1.0).CGColor
CGContextSetStrokeColorWithColor(ctx, speedColor)
// Calculate the change in x/y.
dx = fabs(cx - px)
dy = fabs(cy - py)
// Find the ratio of change vs perpendicular line
// to create a box.
dhyp = sqrt(pow(dx, 2) + pow(dy, 2))
dratio = dhyp/self.lineWidth
if dratio == 0.0 {
wx = 0.0
wy = 0.0
}
else {
wx = dy/dratio
wy = dx/dratio
}
// Back everything up a tiny amount so that we
// don't have lines separating the boxes
bx = 0.1 * wx
by = 0.1 * wy
if cx > px && cy > py {
// Moving SE
q = 0
wx *= -1
px -= by
py -= bx
}
else if cx > px && cy < py {
// Moving NE
q = 1
px -= by
py += bx
}
else if cx < px && cy < py {
// Moving NW
q = 2
wy *= -1
px += by
py += bx
}
else { // cx < px && cy > py
// Moving SW or not moving
q = 3
wx *= -1
wy *= -1
px += by
py -= bx
}
// Create a box path.
var path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, px, py)
CGPathAddLineToPoint(path, nil, cx, cy)
CGPathAddLineToPoint(path, nil, cx + wx, cy + wy)
CGPathAddLineToPoint(path, nil, px + wx, py + wy)
CGPathAddLineToPoint(path, nil, ppx, ppy)
CGPathAddLineToPoint(path, nil, px, py)
CGContextSetFillColorWithColor(ctx, speedColor)
CGContextAddPath(ctx, path)
CGContextDrawPath(ctx, kCGPathFill)
// Draw a unit (mi/km) marker
total += RunalysisUnits.convertMetersToUnits(p.distance.doubleValue)
unitTest = Int(total)
if unitTest > unitCounter {
unitCounter = unitTest
var center = CGPointMake(cx, cy)
CGContextSetLineWidth(ctx, 1.0)
CGContextAddArc(ctx, center.x, center.y, CGFloat(12.0), CGFloat(0), CGFloat(2*M_PI), Int32(0))
CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor)
CGContextStrokePath(ctx);
}
}
}
px = cx
py = cy
ppx = cx + wx
ppy = cy + wy
}
}
}
}
}
| mit | 8058ad7005736f7e9d0ead1b57737bb2 | 33.827119 | 171 | 0.408215 | 5.271421 | false | false | false | false |
sugar2010/SwiftOptimizer | swix/math.swift | 2 | 796 | //
// math.swift
// swix
//
// Created by Scott Sievert on 7/11/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
// fft, ifft, dot product, haar wavelet
func dot(x: matrix2d, y: matrix2d) -> matrix2d{
var (Mx, Nx) = x.shape
var (My, Ny) = y.shape
assert(Nx == My, "Matrix sizes not compatible for dot product")
var z = zeros((Mx, Ny))
dot_objc(!x, !y, !z, Mx.cint, Ny.cint, Nx.cint)
return z
}
func fft(x: matrix) -> (matrix, matrix){
var N:CInt = x.n.cint
var yr = zeros(N.int)
var yi = zeros(N.int)
fft_objc(!x, N, !yr, !yi);
return (yr, yi)
}
func ifft(yr: matrix, yi: matrix) -> matrix{
var N = yr.n
var x = zeros(N)
ifft_objc(!yr, !yi, N.cint, !x);
return x
} | mit | 90e58efeb4a79a948936bd639df63ad5 | 19.435897 | 67 | 0.574121 | 2.707483 | false | false | false | false |
yoha/Thoughtless | Pods/HidingNavigationBar/HidingNavigationBar/HidingViewController.swift | 2 | 4481 | //
// HidingViewController.swift
// Optimus
//
// Created by Tristan Himmelman on 2015-03-17.
// Copyright (c) 2015 Hearst TV. All rights reserved.
//
import UIKit
class HidingViewController {
var child: HidingViewController?
var navSubviews: [UIView]?
var view: UIView
var expandedCenter: ((UIView) -> CGPoint)?
var alphaFadeEnabled = false
var contractsUpwards = true
init(view: UIView) {
self.view = view
}
init() {
view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
view.backgroundColor = UIColor.clear
view.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
}
func expandedCenterValue() -> CGPoint {
if let expandedCenter = expandedCenter {
return expandedCenter(view)
}
return CGPoint(x: 0, y: 0)
}
func contractionAmountValue() -> CGFloat {
return view.bounds.height
}
func contractedCenterValue() -> CGPoint {
if contractsUpwards {
return CGPoint(x: expandedCenterValue().x, y: expandedCenterValue().y - contractionAmountValue())
} else {
return CGPoint(x: expandedCenterValue().x, y: expandedCenterValue().y + contractionAmountValue())
}
}
func isContracted() -> Bool {
return Float(fabs(view.center.y - contractedCenterValue().y)) < FLT_EPSILON
}
func isExpanded() -> Bool {
return Float(fabs(view.center.y - expandedCenterValue().y)) < FLT_EPSILON
}
func totalHeight() -> CGFloat {
let height = expandedCenterValue().y - contractedCenterValue().y
if let child = child {
return child.totalHeight() + height
}
return height
}
func setAlphaFadeEnabled(_ alphaFadeEnabled: Bool) {
self.alphaFadeEnabled = alphaFadeEnabled
if !alphaFadeEnabled {
updateSubviewsToAlpha(1.0)
}
}
func updateYOffset(_ delta: CGFloat) -> CGFloat {
var deltaY = delta
if child != nil && deltaY < 0 {
deltaY = child!.updateYOffset(deltaY)
child!.view.isHidden = (deltaY) < 0;
}
var newYOffset = view.center.y + deltaY
var newYCenter = max(min(expandedCenterValue().y, newYOffset), contractedCenterValue().y)
if contractsUpwards == false {
newYOffset = view.center.y - deltaY
newYCenter = min(max(expandedCenterValue().y, newYOffset), contractedCenterValue().y)
}
view.center = CGPoint(x: view.center.x, y: newYCenter)
if alphaFadeEnabled {
var newAlpha: CGFloat = 1.0 - (expandedCenterValue().y - view.center.y) * 2 / contractionAmountValue()
newAlpha = CGFloat(min(max(FLT_EPSILON, Float(newAlpha)), 1.0))
updateSubviewsToAlpha(newAlpha)
}
var residual = newYOffset - newYCenter
if (child != nil && deltaY > 0 && residual > 0) {
residual = child!.updateYOffset(residual)
child!.view.isHidden = residual - (newYOffset - newYCenter) > 0
}
return residual;
}
func snap(_ contract: Bool, completion:((Void) -> Void)!) -> CGFloat {
var deltaY: CGFloat = 0
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
if let child = self.child {
if contract && child.isContracted() {
deltaY = self.contract()
} else {
deltaY = self.expand()
}
} else {
if contract {
deltaY = self.contract()
} else {
deltaY = self.expand()
}
}
}) { (success: Bool) -> Void in
if completion != nil{
completion();
}
}
return deltaY;
}
func expand() -> CGFloat {
view.isHidden = false
if alphaFadeEnabled {
updateSubviewsToAlpha(1)
navSubviews = nil
}
var amountToMove = expandedCenterValue().y - view.center.y
view.center = expandedCenterValue()
if let child = child {
amountToMove += child.expand()
}
return amountToMove;
}
func contract() -> CGFloat {
if alphaFadeEnabled {
updateSubviewsToAlpha(0)
}
let amountToMove = contractedCenterValue().y - view.center.y
view.center = contractedCenterValue()
return amountToMove;
}
// MARK: - Private methods
fileprivate func updateSubviewsToAlpha(_ alpha: CGFloat) {
if navSubviews == nil {
navSubviews = []
// loops through and subview and save the visible ones in navSubviews array
for subView in view.subviews {
let isBackgroundView = subView === view.subviews[0]
let isViewHidden = subView.isHidden || Float(subView.alpha) < FLT_EPSILON
if isBackgroundView == false && isViewHidden == false {
navSubviews?.append(subView)
}
}
}
if let subViews = navSubviews {
for subView in subViews {
subView.alpha = alpha
}
}
}
}
| mit | 3da0b96c4d705fbcffd1a542ac2d15a1 | 22.962567 | 105 | 0.668378 | 3.407605 | false | false | false | false |
Beaver/BeaverCodeGen | Pods/Beaver/Beaver/Type/ChildStore.swift | 1 | 2244 | public final class ChildStore<StateType: State, ParentStateType: State> {
public typealias Extract = (ParentStateType) -> StateType?
let extract: Extract
let store: Store<ParentStateType>
public init(store: Store<ParentStateType>,
extract: @escaping Extract) {
self.store = store
self.extract = extract
}
}
// MARK: - State
extension ChildStore {
public var state: StateType {
guard let extractedState = extract(store.state) else {
fatalError("Could not extract state from parentState")
}
return extractedState
}
}
// MARK: - Dispatching
extension ChildStore {
public func dispatch(_ envelop: ActionEnvelop) {
store.dispatch(envelop)
}
}
// MARK: - Subscribing
extension ChildStore {
private func subscriberName(with name: String) -> String {
return String(describing: self) + "_" + name
}
public func subscribe(_ subscriber: Store<StateType>.Subscriber) {
let store = self.store
let name = subscriberName(with: subscriber.name)
let parentSubscriber = Store<ParentStateType>.Subscriber(name: name) { [weak self] oldState, newState, completion in
if let weakSelf = self {
let oldChildState = oldState.flatMap(weakSelf.extract)
if let childState = weakSelf.extract(newState), oldChildState != childState {
subscriber.stateDidUpdate(oldChildState, childState, completion)
} else {
completion()
}
} else {
store.unsubscribe(name)
completion()
}
}
store.subscribe(parentSubscriber)
}
public func subscribe(name: String, stateDidUpdate: @escaping Store<StateType>.Subscriber.StateDidUpdate) {
subscribe(Store<StateType>.Subscriber(name: name, stateDidUpdate: stateDidUpdate))
}
public func unsubscribe(_ name: String) {
store.unsubscribe(subscriberName(with: name))
}
}
public protocol ChildStoring {
associatedtype StateType: State
associatedtype ParentStateType: State
var store: ChildStore<StateType, ParentStateType> { get }
}
| mit | 1e2da7243679bda80731cd362782b9ee | 27.405063 | 124 | 0.633244 | 4.754237 | false | false | false | false |
testpress/ios-app | ios-app/UI/TimeAnalyticsTableViewController.swift | 1 | 9377 | //
// TimeAnalyticsTableViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. 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.
//
import LUExpandableTableView
import UIKit
import WebKit
class TimeAnalyticsTableViewController: UIViewController {
@IBOutlet var tableView: LUExpandableTableView!
@IBOutlet weak var contentView: UIView!
var attempt: Attempt!
var attemptItems = [AttemptItem]()
var showingProgress: Bool = false
var emptyView: EmptyView!
let loadingDialogController = UIUtils.initProgressDialog(message:
Strings.LOADING_QUESTIONS + "\n\n")
var webViewHeight: [CGFloat]!
var selectedIndexPath: IndexPath!
override func viewDidLoad() {
self.setStatusBarColor()
emptyView = EmptyView.getInstance(parentView: contentView)
emptyView.parentView = view
tableView.tableFooterView = UIView(frame: .zero)
tableView.reloadData()
tableView.expandableTableViewDataSource = self
tableView.expandableTableViewDelegate = self
tableView.sectionFooterHeight = 2.0;
UIUtils.setTableViewSeperatorInset(tableView, size: 0)
tableView.register(
UINib(nibName: Constants.TIME_ANALYTICS_HEADER_VIEW_CELL, bundle: Bundle.main),
forHeaderFooterViewReuseIdentifier: Constants.TIME_ANALYTICS_HEADER_VIEW_CELL
)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
present(loadingDialogController, animated: false, completion: nil)
loadQuestions(url: attempt.reviewUrl!)
}
func loadQuestions(url: String) {
TPApiClient.getQuestions(
endpointProvider: TPEndpointProvider(.getQuestions, url: url),
completion: {
testpressResponse, error in
if let error = error {
debugPrint(error.message ?? "No error message found")
debugPrint(error.kind)
self.loadingDialogController.dismiss(animated: true, completion: {
var retryHandler: (() -> Void)?
if error.kind == .network {
retryHandler = {
self.emptyView.hide()
self.present(self.loadingDialogController, animated: false)
self.loadQuestions(url: url)
}
}
let (image, title, description) = error.getDisplayInfo()
self.emptyView.show(image: image, title: title, description: description,
retryHandler: retryHandler)
})
return
}
self.attemptItems.append(contentsOf: testpressResponse!.results)
if !(testpressResponse!.next.isEmpty) {
self.loadQuestions(url: testpressResponse!.next)
} else {
if self.attemptItems.isEmpty {
// Handled empty questions
self.loadingDialogController.dismiss(animated: true, completion: {
UIUtils.showSimpleAlert(
title: Strings.NO_QUESTIONS,
message: Strings.NO_QUESTIONS_DESCRIPTION,
viewController: self,
completion: { action in
self.back()
})
})
return
}
self.webViewHeight = [CGFloat](repeating: 0, count: self.attemptItems.count)
self.loadingDialogController.dismiss(animated: false, completion: nil)
self.tableView.reloadData()
}
})
}
@IBAction func back() {
dismiss(animated: true, completion: nil)
}
}
extension TimeAnalyticsTableViewController: LUExpandableTableViewDataSource {
func numberOfSections(in expandableTableView: LUExpandableTableView) -> Int {
return attemptItems.count
}
func expandableTableView(_ expandableTableView: LUExpandableTableView,
numberOfRowsInSection section: Int) -> Int {
return 1
}
func expandableTableView(_ expandableTableView: LUExpandableTableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if attemptItems.count <= indexPath.section {
// Needed to prevent index out of bound execption when dismiss view controller while
// table view is scrolling
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(
withIdentifier: Constants.TIME_ANALYTICS_QUESTION_CELL, for: indexPath)
as! TimeAnalyticsQuestionCell
let attemptItem = attemptItems[indexPath.section]
cell.initCell(attemptItem: attemptItem, parentViewController: self)
return cell
}
func expandableTableView(_ expandableTableView: LUExpandableTableView, sectionHeaderOfSection
section: Int) -> LUExpandableTableViewSectionHeader {
if attemptItems.count <= section {
// Needed to prevent index out of bound execption when dismiss view controller while
// table view is scrolling
return LUExpandableTableViewSectionHeader()
}
let cell = expandableTableView.dequeueReusableHeaderFooterView(
withIdentifier: Constants.TIME_ANALYTICS_HEADER_VIEW_CELL)
as! TimeAnalyticsHeaderViewCell
let attemptItem = attemptItems[section]
if attemptItem.index == nil {
attemptItem.index = section + 1
}
cell.initCell(attemptItem: attemptItem, parentViewController: self)
return cell
}
}
extension TimeAnalyticsTableViewController: LUExpandableTableViewDelegate {
func expandableTableView(_ expandableTableView: LUExpandableTableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return webViewHeight[indexPath.section]
}
func expandableTableView(_ expandableTableView: LUExpandableTableView,
heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
}
extension TimeAnalyticsTableViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
if (message.name == "callbackHandler") {
let body = message.body
if let dict = body as? Dictionary<String, AnyObject> {
let index = dict["index"] as! Int
webViewHeight[index] = dict["height"] as! CGFloat + 20
tableView.expandSections(at: [index])
tableView.beginUpdates()
let indexPath = IndexPath(item: 0, section: index)
tableView.reloadRows(at: [indexPath], with: .none)
tableView.endUpdates()
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
}
}
}
}
extension TimeAnalyticsTableViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(getJavascript(webView)) { (result, error) in
if error != nil {
debugPrint(error ?? "no error")
}
}
}
func getJavascript(_ webView: WKWebView) -> String {
var js: String = ""
if webViewHeight[webView.tag] == 0.0 {
js += "var message = {'height': document.body.offsetHeight, 'index': \(webView.tag)};"
js += "webkit.messageHandlers.callbackHandler.postMessage(message);"
}
do {
return js
} catch let error as NSError {
debugPrint(error.localizedDescription)
}
return ""
}
}
| mit | e44fcdb1bc0ba31a7f2bde64ada8adec | 39.588745 | 98 | 0.605589 | 5.49912 | false | false | false | false |
Estimote/iOS-SDK | LegacyExamples/Nearables/MonitoringExample-Swift/MonitoringExample-Swift/ViewController.swift | 1 | 4375 | //
// ViewController.swift
// MonitoringExample-Swift
//
// Created by Marcin Klimek on 09/01/15.
// Copyright (c) 2015 Estimote. All rights reserved.
//
import UIKit
class ESTTableViewCell: UITableViewCell
{
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController,
UITableViewDelegate,
UITableViewDataSource,
ESTNearableManagerDelegate
{
var nearables:Array<ESTNearable>!
var nearableManager:ESTNearableManager!
var tableView:UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Pick Nearable to monitor for:";
tableView = UITableView(frame: self.view.frame)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.registerClass(ESTTableViewCell.classForCoder(), forCellReuseIdentifier: "CellIdentifier")
nearables = []
nearableManager = ESTNearableManager()
nearableManager.delegate = self
nearableManager .startRangingForType(ESTNearableType.All)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return nearables.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! ESTTableViewCell
let nearable = nearables[indexPath.row] as ESTNearable
let details = "Type: \(ESTNearableDefinitions.nameForType(nearable.type)) RSSI: \(nearable.rssi)"
cell.textLabel?.text = "Identifier: \(nearable.identifier)"
cell.detailTextLabel?.text = details;
let imageView = UIImageView(frame: CGRectMake(self.view.frame.size.width - 60, 30, 30, 30))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.image = self.imageForNearableType(nearable.type)
cell.contentView.addSubview(imageView)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 80
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("details", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if(segue.identifier == "details")
{
let monitVC:MonitoringDetailsViewController = segue.destinationViewController as! MonitoringDetailsViewController
monitVC.nearable = self.nearables[(sender as! NSIndexPath).row]
}
}
// MARK: - ESTNearableManager delegate
func nearableManager(manager: ESTNearableManager, didRangeNearables nearables: [ESTNearable], withType type: ESTNearableType) {
self.nearables = nearables
self.tableView.reloadData()
}
func imageForNearableType(type: ESTNearableType) -> UIImage?
{
switch (type)
{
case ESTNearableType.Bag:
return UIImage(named: "sticker_bag")
case ESTNearableType.Bike:
return UIImage(named: "sticker_bike")
case ESTNearableType.Car:
return UIImage(named: "sticker_car")
case ESTNearableType.Fridge:
return UIImage(named: "sticker_fridge")
case ESTNearableType.Bed:
return UIImage(named: "sticker_bed")
case ESTNearableType.Chair:
return UIImage(named: "sticker_chair")
case ESTNearableType.Shoe:
return UIImage(named: "sticker_shoe")
case ESTNearableType.Door:
return UIImage(named: "sticker_door")
case ESTNearableType.Dog:
return UIImage(named: "sticker_dog")
default:
return UIImage(named: "sticker_grey")
}
}
}
| mit | 191ed915e9059efc86c7d709ebfb9536 | 31.407407 | 131 | 0.660343 | 5.110981 | false | false | false | false |
Tomikes/eidolon | Kiosk/Bid Fulfillment/ConfirmYourBidViewController.swift | 6 | 4400 | import UIKit
import ECPhoneNumberFormatter
import Moya
import ReactiveCocoa
import Swift_RAC_Macros
class ConfirmYourBidViewController: UIViewController {
private dynamic var number: String = ""
let phoneNumberFormatter = ECPhoneNumberFormatter()
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
@IBOutlet var numberAmountTextField: TextField!
@IBOutlet var cursor: CursorView!
@IBOutlet var keypadContainer: KeypadContainerView!
@IBOutlet var enterButton: UIButton!
@IBOutlet var useArtsyLoginButton: UIButton!
lazy var numberSignal: RACSignal = { self.keypadContainer.stringValueSignal }()
lazy var provider: ArtsyProvider<ArtsyAPI> = Provider.sharedProvider
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidViewController {
return storyboard.viewControllerWithID(.ConfirmYourBid) as! ConfirmYourBidViewController
}
override func viewDidLoad() {
super.viewDidLoad()
let titleString = useArtsyLoginButton.titleForState(useArtsyLoginButton.state)! ?? ""
let attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
NSFontAttributeName: useArtsyLoginButton.titleLabel!.font];
let attrTitle = NSAttributedString(string: titleString, attributes:attributes)
useArtsyLoginButton.setAttributedTitle(attrTitle, forState:useArtsyLoginButton.state)
RAC(self, "number") <~ numberSignal
let numberStringSignal = RACObserve(self, "number")
RAC(numberAmountTextField, "text") <~ numberStringSignal.map(toPhoneNumberString)
let nav = self.fulfillmentNav()
RAC(nav.bidDetails.newUser, "phoneNumber") <~ numberStringSignal
RAC(nav.bidDetails, "paddleNumber") <~ numberStringSignal
bidDetailsPreviewView.bidDetails = nav.bidDetails
// Does a bidder exist for this phone number?
// if so forward to PIN input VC
// else send to enter email
if let nav = self.navigationController as? FulfillmentNavigationController {
let numberIsZeroLengthSignal = numberStringSignal.map(isZeroLengthString)
enterButton.rac_command = RACCommand(enabled: numberIsZeroLengthSignal.not()) { [weak self] _ in
if (self == nil) {
return RACSignal.empty()
}
let endpoint: ArtsyAPI = ArtsyAPI.FindBidderRegistration(auctionID: nav.auctionID!, phone: String(self!.number))
return XAppRequest(endpoint, provider:self!.provider).filterStatusCode(400).doError { (error) -> Void in
// Due to AlamoFire restrictions we can't stop HTTP redirects
// so to figure out if we got 302'd we have to introspect the
// error to see if it's the original URL to know if the
// request suceedded
let moyaResponse = error.userInfo["data"] as? MoyaResponse
let responseURL = moyaResponse?.response?.URL?.absoluteString
if let responseURL = responseURL {
if (responseURL as NSString).containsString("v1/bidder/") {
self?.performSegue(.ConfirmyourBidBidderFound)
return
}
}
self?.performSegue(.ConfirmyourBidBidderNotFound)
return
}
}
}
}
func toOpeningBidString(cents:AnyObject!) -> AnyObject! {
if let dollars = NSNumberFormatter.currencyStringForCents(cents as? Int) {
return "Enter \(dollars) or more"
}
return ""
}
func toPhoneNumberString(number:AnyObject!) -> AnyObject! {
let numberString = number as! String
if numberString.characters.count >= 7 {
return self.phoneNumberFormatter.stringForObjectValue(numberString)
} else {
return numberString
}
}
}
private extension ConfirmYourBidViewController {
@IBAction func dev_noPhoneNumberFoundTapped(sender: AnyObject) {
self.performSegue(.ConfirmyourBidArtsyLogin )
}
@IBAction func dev_phoneNumberFoundTapped(sender: AnyObject) {
self.performSegue(.ConfirmyourBidBidderFound)
}
}
| mit | 6ee82d0d4a8dc801f911caa669571064 | 37.596491 | 128 | 0.652727 | 5.5 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/ToolKit/JSToolKit/JSBridge/JSSwiftyBeaver.swift | 1 | 908 | //
// JSSwiftyBeaverBridge.swift
// LoveYou
//
// Created by WengHengcong on 2016/10/30.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import UIKit
import SwiftyBeaver
let JSLog = SwiftyBeaver.self
class JSSwiftyBeaver: NSObject {
public class func bridgeInit() {
// add log destinations. at least one is needed!
let console = ConsoleDestination() // log to Xcode Console
//let file = FileDestination() // log to default swiftybeaver.log file
//let cloud = SBPlatformDestination(appID: "foo", appSecret: "bar", encryptionKey: "123") // to cloud
// use custom format and set console output to short time, log level & message
// console.format = "$DHH:mm:ss$d $L $M"
// add the destinations to SwiftyBeaver
JSLog.addDestination(console)
//log.addDestination(file)
//log.addDestination(cloud)
}
}
| mit | cbfb442618550b9f34453b8b40acd7a4 | 28.193548 | 109 | 0.661878 | 4.095023 | false | false | false | false |
Incipia/Conduction | Conduction/Classes/ConductionSequence.swift | 1 | 3651 | //
// ConductionSequence.swift
// Bindable
//
// Created by Leif Meyer on 1/16/18.
//
import Foundation
public protocol ConductionSequenceState: ConductionState {
associatedtype Step: Equatable
var step: Step? { get set }
}
public struct ConductionSequenceLayer<Step: Equatable> {
// MARK: - Public Properties
let step: Step
let conductor: Conductor?
}
open class ConductionSequence<State: ConductionSequenceState>: ConductionStateObserver<State>, ConductionContext {
// MARK: - Private Properties
private var _oldStateContext: Any?
// MARK: - Public Properties
open var context: Any? { return state }
public var contextuals: [ConductionContextual] { return layers.flatMap { $0.conductor as? ConductionContextual } }
public let navigationContext: UINavigationController
public private(set) var layers: [ConductionSequenceLayer<State.Step>] = []
// MARK: - Init
public init(navigationContext: UINavigationController) {
self.navigationContext = navigationContext
super.init()
}
// MARK: - Subclass Hooks
open func didContextChangeWithState(oldContext: Any?, oldState: State?) -> Bool { return true }
open func conductor(step: State.Step) -> Conductor? { return nil }
// MARK: - Public
public func set(step: State.Step?) { state.step = step }
public func addStateLayers(steps: [State.Step], atIndex index: Int, animated: Bool) {
guard !steps.isEmpty else { return }
layers.insert(contentsOf: steps.map { ConductionSequenceLayer<State.Step>(step: $0, conductor: conductor(step: $0)) }, at: index)
if state.step != layers.last?.step {
state.step = layers.last?.step
}
layers[index..<index+steps.count].forEach {
if let contextualConductor = $0.conductor as? ConductionContextual {
added(contextual: contextualConductor)
}
$0.conductor?.show(with: navigationContext, animated: animated)
}
}
public func removeLayers(inRange range: Range<Int>) {
var newLayers = layers
newLayers.removeSubrange(range)
if state.step != newLayers.last?.step {
state.step = layers.last?.step
}
let removedContext = context
layers[range].reversed().forEach {
if let removedContext = removedContext, let contextualConductor = $0.conductor as? ConductionContextual {
$0.conductor?.dismissWithCompletion {
contextualConductor.leave(context: removedContext)
}
} else {
$0.conductor?.dismiss()
}
layers = newLayers
}
}
// MARK: - Overridden
open override func stateWillChange(nextState: State) {
_oldStateContext = context
}
open override func stateChanged(oldState: State? = nil) {
defer {
_stateChangeBlocks.forEach { $0.value(oldState ?? state, state) }
}
let oldContext = _oldStateContext
_oldStateContext = nil
if didContextChangeWithState(oldContext: oldContext, oldState: oldState) {
contextChanged(oldContext: oldContext)
}
guard layers.last?.step != state.step else { return }
guard let step = state.step else {
removeLayers(inRange: 0..<layers.count)
return
}
guard let reversedIndex = (layers.reversed().map { $0.step }.index(of: step)) else {
addStateLayers(steps: [step], atIndex: layers.count, animated: true)
return
}
let index = layers.count - reversedIndex - 1
if index + 1 < layers.count {
removeLayers(inRange: index+1..<layers.count)
}
}
}
| mit | 2226e89412a3ef1033807d15df547e5d | 32.190909 | 135 | 0.651055 | 4.34126 | false | false | false | false |
Asura19/My30DaysOfSwift | SlideOutMenu/SlideOutMenu/MenuController.swift | 1 | 1667 | //
// MenuController.swift
// SlideOutMenu
//
// Created by Phoenix on 2017/4/22.
// Copyright © 2017年 Phoenix. All rights reserved.
//
import UIKit
class MenuController: UITableViewController {
var TableArrary = [String]()
override func viewDidLoad() {
TableArrary = ["Blue", "Orange", "Pink"]
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
self.tableView.separatorColor = UIColor(red:0.159, green:0.156, blue:0.181, alpha:1)
self.view.backgroundColor = UIColor.black
UIApplication.shared.isStatusBarHidden = true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableArrary.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableArrary[indexPath.row], for: indexPath) as UITableViewCell
cell.textLabel?.text = TableArrary[indexPath.row]
cell.backgroundColor = UIColor.clear
cell.textLabel?.textColor = UIColor.white
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor(red:0.245, green:0.247, blue:0.272, alpha:0.817)
}
}
| mit | 4b331df59e96050c77a6f7f8d90f828f | 30.396226 | 127 | 0.660457 | 4.837209 | false | false | false | false |
Ge3kXm/MXWB | MXWB/Classes/NewFeature/NewFeatureVC.swift | 1 | 1050 | //
// NewFeatureVC.swift
// MXWB
//
// Created by maRk on 2017/4/20.
// Copyright © 2017年 maRk. All rights reserved.
//
import UIKit
class NewFeatureVC: UIViewController {
lazy var bgImageView: UIImageView = {
let bgView = UIImageView(frame: UIScreen.main.bounds)
bgView.image = UIImage(named: "new_feature_1")
return bgView
}()
lazy var button: UIButton = {
let button = UIButton(type: UIButtonType.contactAdd)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.addTarget(self, action: #selector(NewFeatureVC.startClick), for: UIControlEvents.touchUpInside)
return button
}()
@objc func startClick()
{
NotificationCenter.default.post(name: NSNotification.Name(MXWB_NOTIFICATION_SWITCHROOTVC_KEY), object: true)
}
override func viewDidLoad()
{
super.viewDidLoad()
initUI()
}
private func initUI()
{
view.addSubview(bgImageView)
view.addSubview(button)
}
}
| apache-2.0 | 7a600eac269802210f65c90cc148a640 | 23.348837 | 116 | 0.631328 | 4.07393 | false | false | false | false |
qutheory/vapor | Sources/Vapor/Sessions/Session.swift | 2 | 1522 | /// Sessions are a method for associating data with a client accessing your app.
///
/// Each session has a unique identifier that is used to look it up with each request
/// to your app. This is usually done via HTTP cookies.
///
/// See `Request.session()` and `SessionsMiddleware` for more information.
public final class Session {
/// This session's unique identifier. Usually a cookie value.
public var id: SessionID?
/// This session's data.
public var data: SessionData
/// `true` if this session is still valid.
var isValid: Bool
/// Create a new `Session`.
///
/// Normally you will use `Request.session()` to do this.
public init(id: SessionID? = nil, data: SessionData = .init()) {
self.id = id
self.data = data
self.isValid = true
}
/// Invalidates the current session, removing persisted data from the session driver
/// and invalidating the cookie.
public func destroy() {
self.isValid = false
}
}
public struct SessionID: Equatable, Hashable {
public let string: String
public init(string: String) {
self.string = string
}
}
extension SessionID: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
try self.init(string: container.decode(String.self))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.string)
}
}
| mit | 14bcfc20aa874d35bafe72199e7b9c37 | 29.44 | 88 | 0.659658 | 4.463343 | false | false | false | false |
Erickson0806/AVPlayer-with-Swift | AVPlayerSwift/AVPlayerSwift/PlayerManager.swift | 1 | 1857 | //
// PlayerManager.swift
// AVPlayerSwift
//
// Created by Erickson on 16/1/22.
// Copyright © 2016年 paiyipai. All rights reserved.
//
import UIKit
import AVFoundation
let kStatusKeyPath = "status"
class PlayerManager: NSObject {
// private(set) internal var view: UIView
var asset:AVAsset?
var playerItem:AVPlayerItem?
var player:AVPlayer?
var transport:DKTransport?
init(url:NSURL) {
super.init()
asset = AVAsset(URL: url)
self.perpareToPlay()
}
func perpareToPlay(){
let keys = [
"tracks",
"duration",
"commonMetadata",
"availableMediaCharacteristicsWithMediaSelectionOptions"
]
self.playerItem = AVPlayerItem(asset: asset!, automaticallyLoadedAssetKeys: keys)
self.playerItem!.addObserver(self, forKeyPath: kStatusKeyPath, options: .New, context: nil)
self.player = AVPlayer(playerItem: self.playerItem!)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
dispatch_async(dispatch_get_main_queue()) {
self.playerItem!.removeObserver(self, forKeyPath: kStatusKeyPath)
if self.playerItem?.status == .ReadyToPlay {
self.addPlayerItemTimeObserver()
self.addItemEndObserverForPlayerItem()
// let duration = self.playerItem!.duration
//
self.player?.play()
}
}
}
func addPlayerItemTimeObserver(){
}
func addItemEndObserverForPlayerItem(){
}
}
| apache-2.0 | 71755c7fcade13fdb723b6b51418e0e8 | 22.468354 | 157 | 0.564725 | 5.121547 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/SiteVerticalsService.swift | 1 | 3721 | import AutomatticTracks
// MARK: - SiteVerticalsService
/// Advises the caller of results related to requests for a specific site vertical.
///
/// - success: the site vertical request succeeded with the accompanying result.
/// - failure: the site vertical request failed due to the accompanying error.
///
public enum SiteVerticalRequestResult {
case success(SiteVertical)
case failure(SiteVerticalsError)
}
typealias SiteVerticalRequestCompletion = (SiteVerticalRequestResult) -> ()
/// Abstracts retrieval of site verticals.
///
protocol SiteVerticalsService {
func retrieveVertical(named verticalName: String, completion: @escaping SiteVerticalRequestCompletion)
func retrieveVerticals(request: SiteVerticalsRequest, completion: @escaping SiteVerticalsServiceCompletion)
}
// MARK: - MockSiteVerticalsService
/// Mock implementation of the SiteVerticalsService
///
final class MockSiteVerticalsService: SiteVerticalsService {
func retrieveVertical(named verticalName: String, completion: @escaping SiteVerticalRequestCompletion) {
let vertical = SiteVertical(identifier: "SV 1", title: "Vertical 1", isNew: false)
completion(.success(vertical))
}
func retrieveVerticals(request: SiteVerticalsRequest, completion: @escaping SiteVerticalsServiceCompletion) {
let result = SiteVerticalsResult.success(mockVerticals())
completion(result)
}
private func mockVerticals() -> [SiteVertical] {
return [ SiteVertical(identifier: "SV 1", title: "Vertical 1", isNew: false),
SiteVertical(identifier: "SV 2", title: "Vertical 2", isNew: false),
SiteVertical(identifier: "SV 3", title: "Landscap", isNew: true) ]
}
}
// MARK: - SiteCreationVerticalsService
/// Retrieves candidate Site Verticals used to create a new site.
///
final class SiteCreationVerticalsService: LocalCoreDataService, SiteVerticalsService {
// MARK: Properties
/// A facade for WPCOM services.
private let remoteService: WordPressComServiceRemote
// MARK: LocalCoreDataService
override init(managedObjectContext context: NSManagedObjectContext) {
let api: WordPressComRestApi
if let account = try? WPAccount.lookupDefaultWordPressComAccount(in: context) {
api = account.wordPressComRestV2Api
} else {
api = WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress(), localeKey: WordPressComRestApi.LocaleKeyV2)
}
self.remoteService = WordPressComServiceRemote(wordPressComRestApi: api)
super.init(managedObjectContext: context)
}
// MARK: SiteVerticalsService
func retrieveVertical(named verticalName: String, completion: @escaping SiteVerticalRequestCompletion) {
let request = SiteVerticalsRequest(search: verticalName, limit: 1)
remoteService.retrieveVerticals(request: request) { result in
switch result {
case .success(let verticals):
guard let vertical = verticals.first else {
WordPressAppDelegate.crashLogging?.logMessage("The verticals service should always return at least 1 match for the precise term queried.", level: .error)
completion(.failure(.serviceFailure))
return
}
completion(.success(vertical))
case .failure(let error):
completion(.failure(error))
}
}
}
func retrieveVerticals(request: SiteVerticalsRequest, completion: @escaping SiteVerticalsServiceCompletion) {
remoteService.retrieveVerticals(request: request) { result in
completion(result)
}
}
}
| gpl-2.0 | 91bef1b8356aa76949490a95a4496172 | 36.969388 | 173 | 0.703843 | 5.021592 | false | false | false | false |
sudeepunnikrishnan/ios-sdk | Instamojo/Wallet.swift | 1 | 552 | //
// Wallet.swift
// Instamojo
//
// Created by Sukanya Raj on 15/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
public class Wallet: NSObject {
public var name: String
public var imageUrl: String
public var walletID: String
override init() {
self.name = ""
self.imageUrl = ""
self.walletID = ""
}
public init(name: String, imageUrl: String, walletID: String) {
self.name = name
self.imageUrl = imageUrl
self.walletID = walletID
}
}
| lgpl-3.0 | adda3f72bdada63b89a833fce70c5db8 | 18 | 67 | 0.602541 | 3.935714 | false | false | false | false |
adad184/XXPlaceHolder | XXPlaceHolder/XXPlaceHolder/XXViewController.swift | 1 | 3019 | //
// XXViewController.swift
// XXPlaceHolder
//
// Created by Ralph Li on 10/19/15.
// Copyright © 2015 LJC. All rights reserved.
//
import UIKit
class XXViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let iv1 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
let iv2 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
let iv3 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
let iv4 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
let iv5 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
let iv6 = UIImageView.init(image: UIImage.init(named: "1.jpeg"))
self.view.addSubview(iv1)
self.view.addSubview(iv2)
self.view.addSubview(iv3)
self.view.addSubview(iv4)
self.view.addSubview(iv5)
self.view.addSubview(iv6)
iv2.showPlaceHolder()
iv3.showPlaceHolderWith(UIColor.greenColor())
iv4.showPlaceHolderWith(UIColor.yellowColor(), backColor: UIColor.init(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.5))
iv5.showPlaceHolderWith(UIColor.whiteColor(), backColor: UIColor.init(red: 1.0, green: 0.5, blue: 0, alpha: 0.8), arrowSize: 12)
iv6.showPlaceHolderWith(UIColor.whiteColor(), backColor: UIColor.blackColor(), arrowSize: 25, lineWidth: 3, frameWidth: 5, frameColor: UIColor.redColor())
let imgSize = CGSizeMake(130, 130)
let windowWidth = UIScreen.mainScreen().bounds.width
let padding = imgSize.height+20;
iv1.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv2.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv3.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv4.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv5.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv6.frame = CGRectMake(0,0, imgSize.width, imgSize.height)
iv1.center = CGPointMake(windowWidth*0.25, 64+padding*0.5)
iv2.center = CGPointMake(windowWidth*0.75, 64+padding*0.5)
iv3.center = CGPointMake(windowWidth*0.25, 64+padding*1.5)
iv4.center = CGPointMake(windowWidth*0.75, 64+padding*1.5)
iv5.center = CGPointMake(windowWidth*0.25, 64+padding*2.5)
iv6.center = CGPointMake(windowWidth*0.75, 64+padding*2.5)
}
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.
}
*/
}
| mit | 907012269e4b8e39705014651410deee | 40.342466 | 162 | 0.656395 | 3.753731 | false | false | false | false |
pauldardeau/tataille-swift | tataille-swift/ControlInfo.swift | 1 | 3726 | //
// ControlInfo.swift
// tataille-swift
//
// Created by Paul Dardeau on 8/1/14.
// Copyright (c) 2014 SwampBits. All rights reserved.
// BSD license
import Foundation
public class ControlInfo {
// font
// audio clip
var controlType: CocoaDisplayEngine.ControlType
public var cid: ControlId
public var controlName: String?
public var groupName: String?
public var text: String?
public var helpCaption: String?
public var values: String?
public var valuesDelimiter: String?
public var foregroundColor: String?
public var backgroundColor: String?
public var rect: NSRect
public var isSelected = false // only for checkbox? if so, probably remove
public var isVisible = true
public var isEnabled = true
//**************************************************************************
public init(cid: ControlId) {
self.controlType = CocoaDisplayEngine.ControlType.Unknown
self.cid = cid
self.rect = CGRectZero
}
//**************************************************************************
func isValid() -> Bool {
return self.cid.isValid()
}
//**************************************************************************
func haveParent() -> Bool {
return self.cid.haveParent()
}
//**************************************************************************
func getValues(defaultDelimiter: String) -> [String]? {
if let unWrappedValues = self.values {
if let unWrappedDelimiter = self.valuesDelimiter {
return unWrappedValues.componentsSeparatedByString(unWrappedDelimiter)
} else {
return unWrappedValues.componentsSeparatedByString(defaultDelimiter)
}
}
return nil
}
//**************************************************************************
class func haveStringValue(s: String?) -> Bool {
if let sUnwrapped = s {
if countElements(sUnwrapped) > 0 {
return true
}
}
return false
}
//**************************************************************************
func haveForegroundColor() -> Bool {
return ControlInfo.haveStringValue(self.foregroundColor)
}
//**************************************************************************
func haveBackgroundColor() -> Bool {
return ControlInfo.haveStringValue(self.backgroundColor)
}
//**************************************************************************
func haveGroupName() -> Bool {
return ControlInfo.haveStringValue(self.groupName)
}
//**************************************************************************
func haveControlName() -> Bool {
return ControlInfo.haveStringValue(self.controlName)
}
//**************************************************************************
func haveHelpCaption() -> Bool {
return ControlInfo.haveStringValue(self.helpCaption)
}
//**************************************************************************
func haveText() -> Bool {
return ControlInfo.haveStringValue(self.text)
}
//**************************************************************************
func haveValues() -> Bool {
return ControlInfo.haveStringValue(self.values)
}
//**************************************************************************
func haveValuesDelimiter() -> Bool {
return ControlInfo.haveStringValue(self.valuesDelimiter)
}
//**************************************************************************
}
| bsd-3-clause | ec312efcba3ec41df3e60e5e85f3aaaa | 28.109375 | 86 | 0.438272 | 6.241206 | false | false | false | false |
blocktree/BitcoinSwift | BitcoinSwift/Sources/network/BTCCommand.swift | 1 | 4012 | //
// BTCCommand.swift
// BitcoinSwift
//
// Created by Chance on 2017/5/21.
//
//
import Foundation
/// 比特币网络协议指令集
///
/// - version: 一个节点收到连接请求时,它立即宣告其版本。在通信双方都得到对方版本之前,不会有其他通信
/// - verack: 版本不低于209的客户端在应答version消息时发送verack消息。这个消息仅包含一个command为"verack"的消息头
/// - addr: 提供网络上已知节点的信息。一般来说3小时不进行宣告(advertise)的节点会被网络遗忘
/// - inv: 节点通过此消息可以宣告(advertise)它又拥有的对象信息。这个消息可以主动发送,也可以用于应答getbloks消息
/// - getdata: getdata用于应答inv消息来获取指定对象,它通常在接收到inv包并滤去已知元素后发送
/// - getblocks: 发送此消息以期返回一个包含编号从hash_start到hash_stop的block列表的inv消息。若hash_start到hash_stop的block数超过500,则在500处截止。欲获取后面的block散列,需要重新发送getblocks消息。
/// - getheaders: 获取包含编号hash_star到hash_stop的至多2000个block的header包。要获取之后的block散列,需要重新发送getheaders消息。这个消息用于快速下载不包含相关交易的blockchain。
/// - tx: tx消息描述一笔比特币交易,用于应答getdata消息
/// - block: block消息用于响应请求交易信息的getdata消息
/// - headers: headers消息返回block的头部以应答getheaders
/// - getaddr: getaddr消息向一个节点发送获取已知活动端的请求,以识别网络中的节点。回应这个消息的方法是发送包含已知活动端信息的addr消息。一般的,一个3小时内发送过消息的节点被认为是活动的。
/// - checkorder: 此消息用于IP Transactions,以询问对方是否接受交易并允许查看order内容。
/// - submitorder: 确认一个order已经被提交
/// - reply: IP Transactions的一般应答
/// - ping: ping消息主要用于确认TCP/IP连接的可用性。
/// - alert: alert消息用于在节点间发送通知使其传遍整个网络。如果签名验证这个alert来自Bitcoin的核心开发组,建议将这条消息显示给终端用户。交易尝试,尤其是客户端间的自动交易则建议停止。消息文字应当记入记录文件并传到每个用户。
public enum BTCCommand: String {
case version = "version"
case verack = "verack"
case addr = "addr"
case inv = "inv"
case getdata = "getdata"
case getblocks = "getblocks"
case getheaders = "getheaders"
case tx = "tx"
case block = "block"
case headers = "headers"
case getaddr = "getaddr"
case checkorder = "checkorder"
case submitorder = "submitorder"
case reply = "reply"
case ping = "ping"
case alert = "alert"
/// 是否需要校验完整性
public var isChecksum: Bool {
// version和verack消息不包含checksum,payload的起始位置提前4个字节
switch self {
case .version, .verack:
return false
default:
return true
}
}
public func encode(value: [String: Any]) -> Data {
var msg = Data()
switch self {
case .version:
//一个节点收到连接请求时,它立即宣告其版本。在通信双方都得到对方版本之前,不会有其他通信
msg.appendVarInt(value: 0)
// case .verack:
// case .addr:
// case .inv:
// case .getdata:
// case .getblocks:
// case .getheaders:
// case .tx:
// case .block:
// case .headers:
// case .getaddr:
// case .checkorder:
// case .submitorder:
// case .reply:
// case .ping:
// case .alert:
default:break
}
return msg
}
public static func sendVersionMessage() {
}
}
| mit | b3b34c1aa62540853b539cec87f44a92 | 28.311828 | 143 | 0.653705 | 2.704365 | false | false | false | false |
myandy/shi_ios | shishi/DB/DBManager.swift | 1 | 1747 | //
// DB.swift
// shishi
//
// Created by andymao on 2016/12/18.
// Copyright © 2016年 andymao. All rights reserved.
//
import Foundation
import UIKit
import FMDB
public class DBManager: NSObject {
//创建单例对象
public static let shared: DBManager = DBManager()
//数据库文件名,这并不是一定要作为属性,但是方便重用。
let databaseFileName = "shishi.db"
//数据库文件的路径
var pathToDatabase: String!
//FMDatabase对象用于访问和操作实际的数据库
var database: FMDatabase!
let dbPath = NSHomeDirectory() + "/Documents/shishi.db"
override init() {
super.init()
//创建数据库文件路径
// let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
// pathToDatabase = documentDirectory.appending("/\(databaseFileName)")
}
//这里添加后续代码
//打开数据库
public func openDatabase() -> Bool{
//确认database对象是否被初始化,如果为nil,那么判断路径是否存在并创建
if database == nil{
if FileManager.default.fileExists(atPath: dbPath){
database = FMDatabase(path: dbPath)
NSLog("open from file ")
}
}
//如果database对象存在,打开数据库,返回真,表示打开成功,否则数据库文件不存在或者发生了其它错误
if database != nil{
if database.open(){
NSLog("Success")
return true
}
}
return false
}
public func getDatabase()-> FMDatabase{
return database
}
}
| apache-2.0 | 5658cc8c2f0d6be99ae96fe41a49a1ff | 23.965517 | 125 | 0.599448 | 4.172911 | false | false | false | false |
mactive/rw-courses-note | AdvancedSwift3/Dictionary101.playground/Contents.swift | 1 | 722 | //: Playground - noun: a place where people can play
import UIKit
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
for item in namesOfIntegers {
print(item)
}
var airports: [String: String] = ["YYZ": "Tornoto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London"
airports["LHR"] = "London Heathrow"
if let oldValue = airports.updateValue("Dubin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue)")
}
airports["APL"] = "Apple Internation"
airports["APL"] = nil
airports.removeValue(forKey: "APL")
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys.sorted() {
print("\(airportCode)")
}
| mit | c866564aa057b970a28b5ace4c6a9c0b | 20.878788 | 76 | 0.680055 | 3.327189 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift | 8 | 1875 | //
// AnonymousDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an Action-based disposable.
///
/// When dispose method is called, disposal action will be dereferenced.
private final class AnonymousDisposable : DisposeBase, Cancelable {
public typealias DisposeAction = () -> Void
private let disposed = AtomicInt(0)
private var disposeAction: DisposeAction?
/// - returns: Was resource disposed.
public var isDisposed: Bool {
isFlagSet(self.disposed, 1)
}
/// Constructs a new disposable with the given action used for disposal.
///
/// - parameter disposeAction: Disposal action which will be run upon calling `dispose`.
private init(_ disposeAction: @escaping DisposeAction) {
self.disposeAction = disposeAction
super.init()
}
// Non-deprecated version of the constructor, used by `Disposables.create(with:)`
fileprivate init(disposeAction: @escaping DisposeAction) {
self.disposeAction = disposeAction
super.init()
}
/// Calls the disposal action if and only if the current instance hasn't been disposed yet.
///
/// After invoking disposal action, disposal action will be dereferenced.
fileprivate func dispose() {
if fetchOr(self.disposed, 1) == 0 {
if let action = self.disposeAction {
self.disposeAction = nil
action()
}
}
}
}
extension Disposables {
/// Constructs a new disposable with the given action used for disposal.
///
/// - parameter dispose: Disposal action which will be run upon calling `dispose`.
public static func create(with dispose: @escaping () -> Void) -> Cancelable {
AnonymousDisposable(disposeAction: dispose)
}
}
| mit | 9b4bd3813f7d86fcf2e47ae0effb8bf1 | 30.762712 | 95 | 0.66222 | 4.854922 | false | false | false | false |
zhangzichen/Pontus | Pontus/Swift+Pontus/CollectionType+Pontus.swift | 1 | 862 |
import Foundation
public extension RangeReplaceableCollection {
/// mutating func insert(newElement: Self.Generator.Element, atIndex i: Self.Index)
func pontus_insert(_ newElement: Self.Iterator.Element, atIndex i: Self.Index) -> Self {
var newCollection = self
newCollection.insert(newElement, at: i)
return newCollection
}
func pontus_appendFirst(_ x: Self.Iterator.Element?) -> Self {
var newCollection = self
if x != nil {
newCollection.insert(x!, at: self.startIndex)
}
return newCollection
}
/// mutating func append(x: Self.Generator.Element)
func pontus_append(_ x: Self.Iterator.Element?) -> Self {
var newCollection = self
if x != nil {
newCollection.append(x!)
}
return self
}
}
| mit | 77ad05e4f682f9cf2cacfecb29b58618 | 25.9375 | 92 | 0.603248 | 4.560847 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Model/CGSSLive.swift | 1 | 7840 | //
// CGSSLive.swift
// DereGuide
//
// Created by zzk on 16/7/23.
// Copyright © 2016年 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
enum CGSSLiveSimulatorType: String, CustomStringConvertible, ColorRepresentable {
case normal = "常规模式" //!!!无法被本地化 注意使用时本地化
case vocal = "Vocal Burst"
case dance = "Dance Burst"
case visual = "Visual Burst"
case parade = "LIVE Parade"
static let all: [CGSSLiveSimulatorType] = [.normal, .vocal, .dance, .visual, .parade]
var color: UIColor {
switch self {
case .normal:
return Color.parade
case .vocal:
return Color.vocal
case .dance:
return Color.dance
case .visual:
return Color.passion
case .parade:
return Color.parade
}
}
var description: String {
switch self {
case .normal:
return NSLocalizedString("常规模式", comment: "")
default:
return self.rawValue
}
}
}
enum CGSSGrooveType: String, CustomStringConvertible, ColorRepresentable {
case cute = "Cute Groove"
case cool = "Cool Groove"
case passion = "Passion Groove"
static let all: [CGSSGrooveType] = [.cute, .cool, .passion]
var description: String {
return self.rawValue
}
var color: UIColor {
switch self {
case .cute:
return Color.cute
case .cool:
return Color.cool
case .passion:
return Color.passion
}
}
init? (cardType: CGSSCardTypes) {
switch cardType {
case CGSSCardTypes.cute:
self = .cute
case CGSSCardTypes.cool:
self = .cool
case CGSSCardTypes.passion:
self = .passion
default:
return nil
}
}
}
// MARK: 用于排序的属性
extension CGSSLive {
@objc dynamic var updateId: Int {
return details.map { $0.id }.max() ?? 0
}
@objc dynamic var maxDiffStars: Int {
return selectedLiveDetails.map { $0.stars }.max() ?? 0
}
@objc dynamic var maxNumberOfNotes: Int {
return selectedLiveDetails.map {
if $0.numberOfNotes != 0 {
return $0.numberOfNotes
} else {
return getBeatmap(of: $0.difficulty)?.numberOfNotes ?? 0
}
}.max() ?? 0
// this method takes very long time, because it read each beatmap files
// return self.getBeatmap(of: selectableMaxDifficulty)?.numberOfNotes ?? 0
}
@objc dynamic var sLength: Float {
return getBeatmap(of: .debut)?.totalSeconds ?? 0
}
}
extension CGSSLive {
// 每beat占用的秒数
var barSecond: Double {
return 1 / Double(bpm) * 60
}
var color: UIColor {
switch type {
case 1:
return Color.cute
case 2:
return Color.cool
case 3:
return Color.passion
default:
return UIColor.darkText
}
}
var icon: UIImage {
switch type {
case 1:
return #imageLiteral(resourceName: "song-cute")
case 2:
return #imageLiteral(resourceName: "song-cool")
case 3:
return #imageLiteral(resourceName: "song-passion")
default:
return #imageLiteral(resourceName: "song-all")
}
}
var filterType: CGSSLiveTypes {
switch type {
case 1:
return .cute
case 2:
return .cool
case 3:
return .passion
default:
return .office
}
}
var eventFilterType: CGSSLiveEventTypes {
return CGSSLiveEventTypes.init(eventType: eventType)
}
func getBeatmap(of difficulty: CGSSLiveDifficulty) -> CGSSBeatmap? {
return beatmaps.first { $0.difficulty == difficulty }
}
func getLiveDetail(of difficulty: CGSSLiveDifficulty) -> CGSSLiveDetail? {
return details.first { $0.difficulty == difficulty }
}
var jacketURL: URL {
return URL.images.appendingPathComponent("/jacket/\(musicDataId).png")
}
var selectedLiveDetails: [CGSSLiveDetail] {
return details.filter {
self.difficultyTypes.contains($0.difficultyTypes)
}
}
// var title: String {
// if eventType == 0 {
// return name
// } else {
// return name + "(" + NSLocalizedString("活动", comment: "") + ")"
// }
// }
subscript (difficulty: CGSSLiveDifficulty) -> CGSSLiveDetail? {
get {
return getLiveDetail(of: difficulty)
}
}
func merge(anotherLive live: CGSSLive) {
eventType = max(live.eventType, eventType)
startDate = min(live.startDate, startDate)
musicDataId = max(live.musicDataId, musicDataId)
let eventLive: CGSSLive
let normalLive: CGSSLive
if self.eventType > live.eventType {
eventLive = self
normalLive = live
} else {
eventLive = live
normalLive = self
}
if !normalLive.details.contains { $0.difficulty == .masterPlus } {
var liveDetails = normalLive.details
if let masterPlus = eventLive.details.first(where: { $0.difficulty == .masterPlus }) {
liveDetails.append(masterPlus)
id = eventLive.id
}
liveDetails.sort { $0.difficulty.rawValue < $1.difficulty.rawValue }
self.details = liveDetails
}
}
}
class CGSSLive: NSObject {
@objc dynamic var bpm : Int
var eventType : Int
var id : Int
var musicDataId : Int
var name : String
@objc dynamic var startDate : String
var type : Int
var details = [CGSSLiveDetail]()
lazy var beatmapCount: Int = {
let semaphore = DispatchSemaphore.init(value: 0)
var result = 0
let path = String.init(format: DataPath.beatmap, self.id)
let fm = FileManager.default
if fm.fileExists(atPath: path) {
let dbQueue = MusicScoreDBQueue.init(path: path)
dbQueue.getBeatmapCount(callback: { (count) in
result = count
semaphore.signal()
})
} else {
semaphore.signal()
}
semaphore.wait()
return result
}()
lazy var vocalists: [Int] = {
let semaphore = DispatchSemaphore(value: 0)
var result = [Int]()
CGSSGameResource.shared.master.getVocalistsBy(musicDataId: self.musicDataId, callback: { (list) in
result = list
semaphore.signal()
})
semaphore.wait()
return result
}()
lazy var beatmaps: [CGSSBeatmap] = {
guard let beatmaps = CGSSGameResource.shared.getBeatmaps(liveId: self.id) else {
return [CGSSBeatmap]()
}
return beatmaps
}()
/// used in filter
var difficultyTypes: CGSSLiveDifficultyTypes = .all
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init? (fromJson json: JSON){
if json.isEmpty {
return nil
}
bpm = json["bpm"].intValue
eventType = json["event_type"].intValue
id = json["id"].intValue
musicDataId = json["music_data_id"].intValue
name = json["name"].stringValue.replacingOccurrences(of: "\\n", with: "")
startDate = json["start_date"].stringValue
type = json["type"].intValue
super.init()
}
}
| mit | 14e9d40d636e072e35f69d8e074b5ff9 | 25.861592 | 106 | 0.553265 | 4.413303 | false | false | false | false |
vbudhram/firefox-ios | XCUITests/DragAndDropTests.swift | 1 | 6720 | /* 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 XCTest
let firstWebsite = ["url": "www.youtube.com", "tabName": "Home - YouTube"]
let secondWebsite = ["url": "www.twitter.com", "tabName": "Twitter"]
let homeTab = ["tabName": "home"]
let websiteWithSearchField = ["url": "https://developer.mozilla.org/en-US/search", "urlSearchField": "Search the docs"]
class DragAndDropTests: BaseTestCase {
override func tearDown() {
XCUIDevice.shared().orientation = UIDeviceOrientation.portrait
super.tearDown()
}
private func openTwoWebsites() {
// Open two tabs
navigator.openURL(firstWebsite["url"]!)
navigator.goto(TabTray)
navigator.openURL(secondWebsite["url"]!)
waitUntilPageLoad()
}
private func dragAndDrop(dragElement: XCUIElement, dropOnElement: XCUIElement) {
dragElement.press(forDuration: 2, thenDragTo: dropOnElement)
}
private func checkTabsOrder(dragAndDropTab: Bool, firstTab: String, secondTab: String) {
let firstTabCell = app.collectionViews.cells.element(boundBy: 0).label
let secondTabCell = app.collectionViews.cells.element(boundBy: 1).label
if (dragAndDropTab) {
XCTAssertEqual(firstTabCell, firstTab, "first tab after is not correct")
XCTAssertEqual(secondTabCell, secondTab, "second tab after is not correct")
} else {
XCTAssertEqual(firstTabCell, firstTab, "first tab before is not correct")
XCTAssertEqual(secondTabCell, secondTab, "second tab before is not correct")
}
}
// This feature is working only on iPad so far and so tests enabled only on that schema
func testRearrangeTabs() {
openTwoWebsites()
checkTabsOrder(dragAndDropTab: false, firstTab: firstWebsite["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Drag first tab on the second one
dragAndDrop(dragElement: app.collectionViews.cells[firstWebsite["tabName"]!], dropOnElement: app.collectionViews.cells[secondWebsite["tabName"]!])
checkTabsOrder(dragAndDropTab: true, firstTab: secondWebsite["tabName"]!, secondTab: firstWebsite["tabName"]!)
// Check that focus is kept on last website open
XCTAssertEqual(app.textFields["url"].value! as? String, "mobile.twitter.com/", "The tab has not been dropped correctly")
}
func testRearrangeTabsLandscape() {
// Set the device in landscape mode
XCUIDevice.shared().orientation = UIDeviceOrientation.landscapeLeft
openTwoWebsites()
checkTabsOrder(dragAndDropTab: false, firstTab: firstWebsite["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Rearrange the tabs via drag home tab and drop it on twitter tab
dragAndDrop(dragElement: app.collectionViews.cells[firstWebsite["tabName"]!], dropOnElement: app.collectionViews.cells[secondWebsite["tabName"]!])
checkTabsOrder(dragAndDropTab: true, firstTab: secondWebsite["tabName"]!, secondTab: firstWebsite["tabName"]!)
// Check that focus is kept on last website open
XCTAssertEqual(app.textFields["url"].value! as? String, "mobile.twitter.com/", "The tab has not been dropped correctly")
}
func testDragDropToInvalidArea() {
openTwoWebsites()
checkTabsOrder(dragAndDropTab: false, firstTab: firstWebsite["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Rearrange the tabs via drag home tab and drop it to the tabs button
dragAndDrop(dragElement: app.collectionViews.cells[firstWebsite["tabName"]!], dropOnElement: app.buttons["TopTabsViewController.tabsButton"])
// Check that the order of the tabs have not changed
checkTabsOrder(dragAndDropTab: false, firstTab: firstWebsite["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Check that focus on the website does not change either
XCTAssertEqual(app.textFields["url"].value! as? String, "mobile.twitter.com/", "The tab has not been dropped correctly")
}
func testDragAndDropHomeTab() {
// Home tab is open and then a new website
navigator.openNewURL(urlString: secondWebsite["url"]!)
waitUntilPageLoad()
waitforExistence(app.collectionViews.cells.element(boundBy: 1))
checkTabsOrder(dragAndDropTab: false, firstTab: homeTab["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Drag and drop home tab from the second position to the first one
dragAndDrop(dragElement: app.collectionViews.cells["home"], dropOnElement: app.collectionViews.cells[secondWebsite["tabName"]!])
checkTabsOrder(dragAndDropTab: true, firstTab: secondWebsite["tabName"]! , secondTab: homeTab["tabName"]!)
// Check that focus is kept on last website open
XCTAssertEqual(app.textFields["url"].value! as? String, "mobile.twitter.com/", "The tab has not been dropped correctly")
}
func testRearrangeTabsPrivateMode() {
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
openTwoWebsites()
checkTabsOrder(dragAndDropTab: false, firstTab: firstWebsite["tabName"]!, secondTab: secondWebsite["tabName"]!)
// Drag first tab on the second one
dragAndDrop(dragElement: app.collectionViews.cells[firstWebsite["tabName"]!], dropOnElement: app.collectionViews.cells[secondWebsite["tabName"]!])
checkTabsOrder(dragAndDropTab: true, firstTab: secondWebsite["tabName"]!, secondTab: firstWebsite["tabName"]!)
// Check that focus is kept on last website open
XCTAssertEqual(app.textFields["url"].value! as? String, "mobile.twitter.com/", "The tab has not been dropped correctly")
}
// This test drags the address bar and since it is not possible to drop it on another app, lets do it in a search box
func testDragAddressBarIntoSearchBox() {
navigator.openURL("developer.mozilla.org/en-US/search")
waitUntilPageLoad()
// Check the text in the search field before dragging and dropping the url text field
XCTAssertEqual(app.webViews.searchFields[websiteWithSearchField["urlSearchField"]!].placeholderValue, "Search the docs")
dragAndDrop(dragElement: app.textFields["url"], dropOnElement: app.webViews.searchFields[websiteWithSearchField["urlSearchField"]!])
// Verify that the text in the search field is the same as the text in the url text field
XCTAssertEqual(app.webViews.searchFields[websiteWithSearchField["urlSearchField"]!].value as? String, websiteWithSearchField["url"]!)
}
}
| mpl-2.0 | ae5deded6019f4799f323c79823493b6 | 55.949153 | 154 | 0.708036 | 4.543611 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Buttons/SmallSecondaryButton.swift | 1 | 1619 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
/// Syntactic suguar on SecondaryButton to render it in a small size
///
/// # Usage
/// ```
/// SmallSecondaryButton(title: "OK") { print("Tapped") }
/// ```
///
/// # Figma
/// [Buttons](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=6%3A2955)
public struct SmallSecondaryButton: View {
private let title: String
private let isLoading: Bool
private let action: () -> Void
public init(
title: String,
isLoading: Bool = false,
action: @escaping () -> Void
) {
self.title = title
self.isLoading = isLoading
self.action = action
}
public var body: some View {
SecondaryButton(title: title, isLoading: isLoading, action: action)
.pillButtonSize(.small)
}
}
struct SmallSecondaryButton_Previews: PreviewProvider {
static var previews: some View {
Group {
SmallSecondaryButton(title: "OK", isLoading: false) {
print("Tapped")
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Enabled")
SmallSecondaryButton(title: "OK", isLoading: false) {
print("Tapped")
}
.disabled(true)
.previewLayout(.sizeThatFits)
.previewDisplayName("Disabled")
SmallSecondaryButton(title: "OK", isLoading: true) {
print("Tapped")
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Loading")
}
}
}
| lgpl-3.0 | 7b1bc55757d908f8ed8592c80e5e0e0e | 26.423729 | 102 | 0.580346 | 4.361186 | false | false | false | false |
jonathanhogan/receptionkit | ReceptionKit/View Controllers/Received Messages/SupportKitConversationDelegate.swift | 3 | 3450 | //
// SupportKitConversationDelegate.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-24.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import Foundation
import UIKit
class ConversationDelegate: NSObject, SKTConversationDelegate {
var isPresentingMessage = false
// Display the message modal when a message arrives
// Only displays the last message
func conversation(conversation: SKTConversation!, didReceiveMessages messages: [AnyObject]!) {
// May be a bug here where messages are ignored if the messages are batched
// and multiple messages are sent at once
let lastMessage: SKTMessage = messages.last! as! SKTMessage
// This method is also called when the user sends a message
// (ex. when a delivery method is tapped)
if (!lastMessage.isFromCurrentUser) {
let topVC = getTopViewController()
let receivedMessageView = ReceivedMessageViewController(nibName: "ReceivedMessageViewController", bundle: nil)
receivedMessageView.name = lastMessage.name
receivedMessageView.message = lastMessage.text
receivedMessageView.picture = lastMessage.avatarUrl
receivedMessageView.modalPresentationStyle = UIModalPresentationStyle.FormSheet
receivedMessageView.preferredContentSize = CGSize(width: 600.0, height: 500.0)
// Check that there is no presentation already before presenting
if (isPresentingMessage) {
topVC.dismissViewControllerAnimated(true) { () -> Void in
self.isPresentingMessage = false
self.presentMessageView(receivedMessageView)
}
} else {
self.presentMessageView(receivedMessageView)
}
// Dismiss the message after 10 seconds
let timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "dismissMessageView:", userInfo: nil, repeats: false)
}
}
// Present the message
func presentMessageView(viewController: UIViewController) {
getTopViewController().presentViewController(viewController, animated: true) { () -> Void in
self.isPresentingMessage = true
}
}
// Dismiss the message
func dismissMessageView(timer: NSTimer!) {
if (isPresentingMessage) {
getTopViewController().dismissViewControllerAnimated(true) { () -> Void in
self.isPresentingMessage = false
}
}
}
// Don't show the default SupportKit conversation
func conversation(conversation: SKTConversation!, shouldShowForAction action: SKTAction) -> Bool {
return false
}
// Don't show the default SupportKit notification
func conversation(conversation: SKTConversation!, shouldShowInAppNotificationForMessage message: SKTMessage!) -> Bool {
return false
}
// Don't do anything when reading messages
func conversation(conversation: SKTConversation!, unreadCountDidChange unreadCount: UInt) {
// Do nothing
}
// Get the view controller that's currently being presented
// This is where the notification will show
func getTopViewController() -> UIViewController {
return UIApplication.sharedApplication().keyWindow!.rootViewController!
}
}
| mit | c1e4be14d6cffb5b59931cc7ef05ba69 | 39.116279 | 146 | 0.662029 | 5.769231 | false | false | false | false |
kiwitechnologies/ServiceClientiOS | ServiceClient/ServiceClient/TSGServiceClient/Helper/RequestModel.swift | 1 | 1735 | //
// RequestModel.swift
// TSGServiceClient
//
// Created by Yogesh Bhatt on 15/06/16.
// Copyright © 2016 kiwitech. All rights reserved.
//
import Foundation
class RequestModel:NSObject {
var url:String!
var bodyParam:NSDictionary?=nil
var queryParam:NSDictionary?=nil
var type:RequestType
var isRunning:Bool
var apiTag:String!
var priority:Bool
var actionType:ActionType
var apiTime:String
var dataKeyName:String?
var mimeType:MimeType?
var imageQuality:ImageQuality?
var progressValue:(percentage:Float)->()? //= { percent in}
var successBlock:(response:AnyObject)->()? //= { response in}
var failureBlock:(error:NSError)->()? //= { error in}
var requestObj:Request?
init(url:String!, bodyParam:NSDictionary?=nil,queryParam:NSDictionary?=nil, type:RequestType, state:Bool = false, apiTag:String!, priority:Bool,actionType:ActionType,apiTime:String,requestObj:Request?=nil,dataKeyName:String?=nil,mimeType:MimeType?=nil,imageQuality:ImageQuality?=nil,progressBlock:(percentage:Float)->()?,successBlock:(response:AnyObject)->()?,
failureBlock:(error:NSError)->()?){
self.url = url
self.bodyParam = bodyParam
self.type = type
self.isRunning = state
self.apiTag = apiTag
self.priority = priority
self.actionType = actionType
self.queryParam = queryParam
self.apiTime = apiTime
self.dataKeyName = dataKeyName
self.mimeType = mimeType
self.imageQuality = imageQuality
self.progressValue = progressBlock
self.successBlock = successBlock
self.failureBlock = failureBlock
self.requestObj = requestObj
}
} | mit | 60b9165e222a1375a62acb696c8b4d3a | 33.019608 | 364 | 0.677624 | 4.401015 | false | false | false | false |
matrixs/SmartTableView | SmartTableView/SmartTestCell.swift | 1 | 1536 | //
// SmartTestCell.swift
// SmartTableView
//
// Created by matrixs on 16/7/24.
// Copyright © 2016年 matrixs. All rights reserved.
//
import UIKit
import SnapKit
class SmartTestCell: UITableViewCell {
let contentLabel = UILabel()
let smartImageView = UIImageView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
smartImageView.image = UIImage(named: "test")
contentView.addSubview(smartImageView)
smartImageView.contentMode = .top
smartImageView.snp.makeConstraints { (make) in
make.left.top.equalTo(self.contentView).offset(10)
make.width.equalTo(70)
make.bottom.equalTo(-20).priority(100)
}
contentLabel.textColor = UIColor.blue
contentLabel.font = UIFont.systemFont(ofSize: 20)
contentLabel.numberOfLines = 0
contentView.addSubview(contentLabel)
contentLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.contentView).offset(10)
make.left.equalTo(smartImageView.snp_right).offset(10)
make.right.equalTo(self.contentView).offset(-10)
make.bottom.equalTo(-60).priority(100)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func fillData(data: NSObject) {
contentLabel.text = (data as! NSDictionary)["txt"] as? String
}
}
| mit | a28ddcefe31c0e706a35ee26ca8c635e | 31.617021 | 74 | 0.651663 | 4.417867 | false | true | false | false |
iamyuiwong/swift-sqlite | sqlite/SQLiteHelper.swift | 1 | 15892 | /*
* NAME - SQLiteHelper.swift - SQLiteHelper for OSX and iOS
*
* DESC
* - Terrible "bind" (?) -- removed ??
* - For OSX test needed
*
* C. 15/10/11. Xcode 7.0.1 Swift 2.0
*
* V
* - 1.0.0.0_201510121854050800:
* . + init / reopen
* . + closeDB
* . + deinitialize / dropDB
* . + DB version and upgrade (TODO more)
* . + create
* . + insert
* . + query (select ...)
*
* - 1.0.0.1_201510131531490800
* . - init
* . - move out DB
* . + count
* . ... more ...
*/
import Foundation
public class SQLiteHelper {
/*
* ======================================================================
* - reopen: open / re-open DB
* - closeDB: close DB
* ======================================================================
*/
/*
* NAME reopen - re-open SQLiteDB
*
* RETURN
* - success: code is 0
*/
public static func reopen (byDBName dbName: String,
DBVersion dbv: Int = 0,
gid: String? = nil,
fmt: NSDateFormatter? = nil) -> (code: Int32, sd: SQLiteDB?) {
Log.trace()
var curDBV: Int = 0
/* get inst if has to close first */
if let inst = SQLiteDB.Static.instance {
/* get current DB version */
curDBV = inst.dbVersion
SQLiteHelper.closeDB(db: inst)
} else {
curDBV = dbv
}
let dbvK = SQLiteUtil.makeDBVerionKey(byDBName: dbName)
let savedDBVersion = AppUtil.getAppIntValue(byKey: dbvK)
if (curDBV > savedDBVersion) {
/* FIXME: to add callback to do real upgrade */
SQLiteHelper.dropDB(byDBName: dbName)
AppUtil.setAppIntValue(value: curDBV,
forKey: dbvK)
}
/* get path for db in documents directory */
var docPath: String?
if ((nil == gid) || gid!.isEmpty) {
docPath = AppUtil.appDocPath
} else {
docPath = AppUtil.getAppGourpPath(group: gid!)
}
var dbPath: String = ""
var retval: Int32 = 0
var dp = String()
if (nil != docPath) {
dp = docPath!
}
var finalInst: SQLiteDB?
if (!dp.isEmpty) {
dbPath = dp + "/db/" + dbName
Log.v(tag: SQLiteDB.TAG, items: "dbPath:", dbPath)
/* check if copy of db is there in documents directory */
if (!FileUtil.isExists(ofPath: dbPath)) {
/*
* the database does not exist
* so copy to documents directory
*/
let _resPath = AppUtil.appResPath
if (nil == _resPath) {
Log.e(tag: SQLiteDB.TAG,
items: "get path of resources fail")
retval = -1
} else {
let resPath = _resPath!
Log.v(tag: SQLiteDB.TAG, items: "resPath:", resPath)
let from = resPath + "/" + dbName
FileUtil.Mkdir(dir: dp + "/db", parent: true)
let ret = FileIO.cp(fileFromPath: from,
toPath: dbPath)
if (!ret) {
Log.e(tag: SQLiteDB.TAG,
items:
"failed to copy writable version of db")
retval = -2
}
}
} else {
FileUtil.Mkdir(dir: dp + "/db", parent: true)
}
/* open the db */
let cpath = StringUtil.toCString(fromString: dbPath,
encoding: NSUTF8StringEncoding)
finalInst = SQLiteDB()
let ret = sqlite3_open(cpath!,
&(finalInst!.__SQLiteHelper_db))
if (SQLITE_OK != ret) {
/* open failed, close db and fail */
if let d = finalInst!.db {
sqlite3_close(d)
}
Log.e(tag: SQLiteDB.TAG,
items: "sqlite3_open fail: \(ret)")
retval = -3
finalInst = nil
}
} else {
Log.e(tag: SQLiteDB.TAG,
items: "get path of documents directory for db fail")
retval = -4
}
if (0 == retval) {
if let inst = finalInst {
/* set fmt */
if let f = fmt {
inst.__SQLiteHelper_fmt = f
} else {
inst.__SQLiteHelper_fmt.timeZone
= NSTimeZone(name: "CST")
inst.__SQLiteHelper_fmt.dateFormat
= "YYYY-MM-dd HH:mm:ss"
}
/* set q */
/* final all success set queue */
SQLiteDB.Static.__SQLiteHelper_queue
= dispatch_queue_create(
SQLiteUtil.makeDBQueueLabel(byDBName: dbName), nil)
/* set dbV */
inst.__SQLiteHelper_dbVersion = curDBV
/* set dbName */
inst.__SQLiteHelper_dbName = dbName
/* set dpPathPrefix */
inst.__SQLiteHelper_dbPathPrefix = dp + "/db/"
Log.v(tag: SQLiteDB.TAG, items: "dbPathPrefix: ",
inst.__SQLiteHelper_dbPathPrefix)
/* set instance */
SQLiteDB.Static.__SQLiteHelper_instance = inst
}
}
return (retval, finalInst)
}
/*
* NAME closeDB - just close
*/
public static func closeDB (db sd: SQLiteDB) {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.__SQLiteHelper_instance != nil
if (!hasInst) {
return
}
/* get and check DB name */
let dbn = sd.dbName
if (dbn.isEmpty) {
return
}
/* get and check DB */
let db = sd.db
if (nil == db) {
return
}
/* opt value */
let dboptK = SQLiteUtil.makeDBOptimizeKey(byDBName: dbn)
var dboptV = AppUtil.getAppIntValue(byKey: dboptK)
--dboptV
Log.v(tag: SQLiteDB.TAG, items: "dboptv \(dboptV)")
var clean: Bool?
if (dboptV <= 0) {
clean = true
dboptV = 500
} else {
clean = false
}
AppUtil.setAppIntValue(value: dboptV, forKey: dboptK)
if (clean!) {
/* clean db now is new ! */
Log.v(tag: SQLiteDB.TAG, items: "optimize db")
let sql = "VACUUM; ANALYZE"
let ret = SQLiteHelper.run(sql: sql, useDB: db!)
if (ret < 0) {
Log.w(tag: SQLiteDB.TAG,
items: "optimize db fail: ignore: \(ret)")
}
}
sqlite3_close(db!)
sd.__SQLiteHelper_db = nil
sd.__SQLiteHelper_dbName = ""
sd.__SQLiteHelper_dbPathPrefix = nil
sd.__SQLiteHelper_fmt = NSDateFormatter()
SQLiteDB.Static.__SQLiteHelper_instance = nil
}
/*
* ======================================================================
* - dropDB byDBName
* - run sql useDB
* - query bySql useDB
* - count itemsInTable useDB withSqlLimit
* ======================================================================
*/
public static func dropDB (byDBName dbn: String) {
Log.trace()
/* check arg */
if (dbn.isEmpty) {
return
}
/* close DB */
if let inst = SQLiteDB.Static.instance {
SQLiteHelper.closeDB(db: inst)
}
/* remove env conf */
let dboptK = SQLiteUtil.makeDBOptimizeKey(byDBName: dbn)
AppUtil.removeAppObject(byKey: dboptK)
let dbvK = SQLiteUtil.makeDBVerionKey(byDBName: dbn)
AppUtil.removeAppObject(byKey: dbvK)
if let docPath = AppUtil.appDocPath {
let dbAtDoc = docPath + "/db/" + dbn
var ret = FileUtil.rm(fileByPath: dbAtDoc)
Log.i(tag: SQLiteDB.TAG, items: dbAtDoc, "rm ret: \(ret)")
let ed = FileUtil.isExistedEmptyDir(ofPath: docPath + "/db")
if (ed.yes) {
ret = FileUtil.Rmdir(ofPath: docPath + "/db")
Log.i(tag: SQLiteDB.TAG, items: docPath + "/db",
"Rmdir ret: \(ret)")
} else {
Log.w(tag: SQLiteDB.TAG, items: "not empty: \(ed.code)")
}
}
}
/*
* NAME run - run sql useDB
*
* DESC
* - will block
* - thread safe
* - no lock
*
* RETURN
* - success: >= 0
* - fail: < 0
*/
public static func run (sql s: String, useDB dbo: COpaquePointer?) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if (s.isEmpty || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
var retval: Int32 = -10000
if let q = SQLiteDB.Static.queue {
dispatch_sync(q) {
let ret = SQLiteUtil.prepare(sql: s, useDB: dbo)
if (0 == ret.code && nil != ret.stmt) {
retval = SQLiteUtil.execute(sql: s,
useStmt: ret.stmt, useDB: dbo)
} else {
retval = ret.code
Log.e(tag: SQLiteDB.TAG,
items: "execute fail: \(retval)")
}
}
}
return retval
}
/*
* NAME query - by sql (has results)
*
* DESC
* - e.x.
* . SELECT ...
* . SELECT COUNT(*) ...
*/
public static func query (bySql sql: String, useDB dbo: COpaquePointer?)
-> (code: Int32, rows: array<SQLRow>?) {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return (-ENODEV, nil)
}
/* check arg */
if (sql.isEmpty || (nil == dbo) || (nil == dbo!)) {
return (-EINVAL, nil)
}
var rows: [SQLRow]?
var retcode: Int32 = 0
if let q = SQLiteDB.Static.queue {
dispatch_sync(q) {
let ret = SQLiteUtil.prepare(sql: sql, useDB: dbo!)
if (ret.stmt != nil) {
rows = SQLiteUtil.query(theStmt: ret.stmt, sql: sql)
} else {
retcode = ret.code
}
}
if (nil != rows) {
return (Int32(rows!.count),
array<SQLRow>(values: rows!)) /* success */
} else {
return (retcode, nil)
}
} else {
return (-ENODEV, nil)
}
}
public static func count (itemsInTable tab: String,
useDB dbo: COpaquePointer?,
withSqlLimit: String = "")
-> Int32 {
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if (tab.isEmpty || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
var cntsql = "SELECT COUNT(*) AS c FROM `"
cntsql += tab + "`"
cntsql += " " + withSqlLimit
let qret = SQLiteHelper.query(bySql: cntsql, useDB: dbo!)
if (qret.code <= 0) {
Log.e(tag: SQLiteDB.TAG, items: "query fail")
return qret.code
} else {
let crowo = qret.rows![0]!["c"]
if let crow = crowo {
let co = crow.intValue
if let c = co {
return Int32(c)
}
}
}
return 0
}
/*
* ======================================================================
* - create tableBySql
* - create tablesBySqls
* - drop tableByName
* - drop tablesByNames
* ======================================================================
*/
public static func create (tableBySql sql: String,
useDB dbo: COpaquePointer?) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if (sql.isEmpty || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
var ret: Int32 = 0
let lsql = sql.lowercaseString
if (lsql.isEmpty || (!lsql.hasPrefix("create"))) {
ret = -EINVAL
} else {
ret = SQLiteHelper.run(sql: sql, useDB: dbo!)
}
return ret
}
public static func create (tablesBySqls sqls: array<String>,
useDB d: COpaquePointer) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if ((sqls.count <= 0) || (nil == d)) {
return -EINVAL
}
var succ: Int32 = 0
for sql in sqls {
let lsql = sql.lowercaseString
if (lsql.isEmpty || (!lsql.hasPrefix("create"))) {
Log.w(tag: SQLiteDB.TAG,
items: "invalid arg found: skip")
} else {
let ret = SQLiteHelper.run(sql: sql, useDB: d)
if (ret <= 0) {
Log.w(tag: SQLiteDB.TAG,
items: sql, "execute fail: \(ret): skip")
} else {
++succ
}
}
}
return succ
}
public static func drop (tableByName n: String,
useDB dbo: COpaquePointer?) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if (n.isEmpty || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
let sql = "DROP TABLE IF EXISTS `" + n + "`;"
return SQLiteHelper.run(sql: sql, useDB: dbo!)
}
public static func drop (tablesByNames ns: array<String>,
useDB dbo: COpaquePointer?) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if ((ns.count <= 0) || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
var ret: Int32 = 0
var ret2: Int32 = -1
for n in ns {
let sql = "DROP TABLE IF EXISTS `" + n + "`;"
ret2 = SQLiteHelper.run(sql: sql, useDB: dbo!)
if (ret2 < 0) {
Log.w(tag: SQLiteDB.TAG, items: "run sql fail:",
"\(ret2)", sql)
} else {
ret += ret2
}
}
return ret
}
/*
* ======================================================================
* - insert bySql
* - insert bySqls
* - insert valuesList intoTab withKeyList useDB
* ======================================================================
*/
public static func insert (bySql sql: String, useDB dbo: COpaquePointer?)
-> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
let lsql = sql.lowercaseString
if ((nil == dbo) || (nil == dbo!) || lsql.isEmpty
|| (!lsql.hasPrefix("insert"))) {
return -EINVAL
}
Log.v(tag: SQLiteDB.TAG, items: sql)
return SQLiteHelper.run(sql: sql, useDB: dbo!)
}
public static func insert (bySqls sqls: array<String>,
useDB dbo: COpaquePointer?) -> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if ((sqls.count <= 0) || (nil == dbo) || (nil == dbo!)) {
return -EINVAL
}
var ret: Int32 = 0
for sql in sqls {
let lsql = sql.lowercaseString
if (lsql.isEmpty || (!lsql.hasPrefix("insert"))) {
Log.w(tag: SQLiteDB.TAG, items: "argument error: skip")
} else {
let ret2 = SQLiteHelper.run(sql: sql, useDB: dbo!)
if (ret2 <= 0) {
Log.w(tag: SQLiteDB.TAG,
items: "run sql fail: \(ret2):", sql)
} else {
ret += ret2
}
}
}
return ret
}
public static func insert (let valuesList vsl:
array<Dictionary<String, String>>,
intoTab tab: String, let withKeyList kl: array<String>,
useDB dbo: COpaquePointer?) -> Int32 {
/* OK no lock need here */
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
if ((nil == dbo) || (nil == dbo!) || (vsl.count <= 0) || tab.isEmpty
|| (kl.count <= 0)) {
return -EINVAL
}
var sqlPrefix = "INSERT INTO "
sqlPrefix += tab + " ("
let c = kl.count
var tot = 0
for k in kl {
++tot
if (tot < c) {
sqlPrefix += k + ", "
} else {
sqlPrefix += k
}
}
sqlPrefix += ") VALUES ("
var sql: String = ""
var retval: Int32 = 0
for vs in vsl {
sql = sqlPrefix
let c = kl.count
var tot = 0
for k in kl {
++tot
if (tot < c) {
sql += vs[k]! + ", "
} else {
sql += vs[k]!
}
}
sql += ");"
let ret = self.insert(bySql: sql, useDB: dbo!)
if (ret <= 0) {
Log.w(tag: SQLiteDB.TAG, items: "insert error: ignore")
} else {
++retval
}
}
return retval
}
public static func update (columns cos: array<String>,
toValues vs: array<String>,
toTab t: String,
useDB dbo: COpaquePointer?,
limitSql: String = "")
-> Int32 {
Log.trace()
/* get hasInst and check inst */
let hasInst = SQLiteDB.Static.instance != nil
if (!hasInst) {
return -ENODEV
}
/* check arg */
let cosc = cos.count
let vsc = vs.count
if ((nil == dbo) || (nil == dbo!)
|| (t.isEmpty)
|| (cosc <= 0) || (vsc <= 0)
|| (cosc != vsc)) {
return -EINVAL
}
/* make sql */
var sql = "UPDATE `"
sql += t
sql += "` SET "
for i in 0..<(cosc - 1) {
sql += "`"
if let k = cos[i] {
sql += k
} else {
return -EINVAL
}
sql += "` = "
if let v = vs[i] {
sql += v
} else {
return -EINVAL
}
sql += ", "
}
sql += "`"
if let k = cos[cosc - 1] {
sql += k
} else {
return -EINVAL
}
sql += "` = "
if let v = vs[cosc - 1] {
sql += v
} else {
return -EINVAL
}
sql += " " + limitSql
sql += ";"
Log.v(tag: SQLiteDB.TAG, items: sql)
return SQLiteHelper.run(sql: sql, useDB: dbo!)
}
}
| lgpl-3.0 | 7fa5c7933feddf835906411364a79240 | 18.644005 | 78 | 0.548955 | 2.940785 | false | false | false | false |
GianniCarlo/Audiobook-Player | BookPlayer/Library/Views/AddButton.swift | 1 | 1098 | //
// AddButton.swift
// BookPlayer
//
// Created by Florian Pichler on 03.06.18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import Themeable
import UIKit
class AddButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
setUpTheming()
}
private func setup() {
let add = UIImageView(image: #imageLiteral(resourceName: "listAdd"))
let distance: CGFloat = 15.0
add.tintColor = UIColor.tintColor
self.setImage(add.image, for: .normal)
self.imageEdgeInsets.right = distance
self.titleEdgeInsets.left = distance
}
@IBInspectable var localizedKey: String? {
didSet {
guard let key = localizedKey else { return }
UIView.performWithoutAnimation {
setTitle(key.localized, for: .normal)
layoutIfNeeded()
}
}
}
}
extension AddButton: Themeable {
func applyTheme(_ theme: Theme) {
self.setTitleColor(theme.linkColor, for: .normal)
}
}
| gpl-3.0 | 1ed72ede7aa79131acfda44ecd37d209 | 21.387755 | 76 | 0.61258 | 4.45935 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/InsertMediaSearchResultCollectionViewCell.swift | 1 | 4099 | import UIKit
final class InsertMediaSearchResultCollectionViewCell: CollectionViewCell {
let imageView = UIImageView()
private let captionLabel = UILabel()
private var imageURL: URL?
private var spacing: CGFloat = 8
private let selectedImageView = UIImageView()
private var selectedImage = UIImage(named: "selected")
override func setup() {
super.setup()
isAccessibilityElement = true
imageView.accessibilityIgnoresInvertColors = true
imageView.contentMode = .scaleAspectFit
contentView.addSubview(imageView)
selectedImageView.contentMode = .scaleAspectFit
contentView.addSubview(selectedImageView)
captionLabel.numberOfLines = 1
contentView.addSubview(captionLabel)
captionLabel.isAccessibilityElement = true
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
captionLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
}
override func reset() {
super.reset()
imageView.wmf_reset()
captionLabel.text = nil
}
func configure(imageURL: URL?, caption: String?) {
self.imageURL = imageURL
captionLabel.text = caption
accessibilityValue = caption
setNeedsLayout()
}
override var isSelected: Bool {
didSet {
updateSelectedOrHighlighted()
selectedImageView.isHidden = !isSelected
}
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
guard let imageURL = imageURL else {
return super.sizeThatFits(size, apply: apply)
}
let imageViewDimension = size.width
let selectedImageViewDimension = min(35, imageViewDimension * 0.2)
guard let scaledImageURL = WMFParseSizePrefixFromSourceURL(imageURL) < Int(imageViewDimension) ? URL(string: WMFChangeImageSourceURLSizePrefix(imageURL.absoluteString, Int(imageViewDimension))) : imageURL else {
return super.sizeThatFits(size, apply: apply)
}
let size = super.sizeThatFits(size, apply: apply)
var origin = CGPoint(x: 0, y: 0)
let minHeight = imageViewDimension + layoutMargins.top + layoutMargins.bottom
let height = max(origin.y, minHeight)
if apply {
imageView.frame = CGRect(x: origin.x, y: origin.y, width: imageViewDimension, height: imageViewDimension)
imageView.wmf_setImage(with: scaledImageURL, detectFaces: false, onGPU: true, failure: {_ in }, success: {
self.imageView.backgroundColor = .clear
})
selectedImageView.frame = CGRect(x: imageView.frame.maxX - selectedImageViewDimension, y: imageView.frame.maxY - selectedImageViewDimension, width: selectedImageViewDimension, height: selectedImageViewDimension)
selectedImageView.image = selectedImage
origin.y += imageView.frame.layoutHeight(with: spacing)
}
selectedImageView.isHidden = !isSelected
let semanticContentAttribute: UISemanticContentAttribute = traitCollection.layoutDirection == .rightToLeft ? .forceRightToLeft : .forceLeftToRight
if captionLabel.wmf_hasAnyNonWhitespaceText {
let captionLabelFrame = captionLabel.wmf_preferredFrame(at: origin, maximumWidth: imageViewDimension, alignedBy: semanticContentAttribute, apply: apply)
origin.y += captionLabelFrame.height
}
captionLabel.isHidden = !captionLabel.wmf_hasAnyNonWhitespaceText
return CGSize(width: size.width, height: height)
}
}
extension InsertMediaSearchResultCollectionViewCell: Themeable {
func apply(theme: Theme) {
backgroundColor = theme.colors.paperBackground
imageView.backgroundColor = .clear
selectedImage = theme.isDark ? UIImage(named: "selected-dark") : UIImage(named: "selected")
selectedImageView.tintColor = theme.colors.link
captionLabel.textColor = theme.colors.primaryText
}
}
| mit | 6c5a47a1a0314a82827aa7935556e46c | 38.796117 | 223 | 0.6909 | 5.393421 | false | false | false | false |
Minitour/WWDC-Collaborators | Macintosh.playground/Sources/Special/Picasso.swift | 1 | 12718 | import Foundation
import UIKit
public class Picasso: MacApp{
/// The application main view
public var container: UIView? = PaintView()
public var desktopIcon: UIImage?
public var identifier: String? = "picasso"
public var windowTitle: String? = "Picasso"
public var menuActions: [MenuAction]? = nil
public var contentMode: ContentStyle = .default
lazy public var uniqueIdentifier: String = {
return UUID().uuidString
}()
/// Data Source function, returns the size of the container.
public func sizeForWindow() -> CGSize {
return CGSize(width: 364, height: 205)
}
public func clear(){
(container as? PaintView)?.clear()
}
public func undo(){
let paintView = (container as? PaintView)
paintView?.didSelectUndo(sender: (paintView?.undoButton)!)
}
public init(){
desktopIcon = UIImage.withBezierPath(pathForIcon(), size: CGSize(width: 65, height: 65))
}
func pathForIcon()->[SpecificBezierPath]{
var sbpa = [SpecificBezierPath]()
let size = MacAppDesktopView.width
let radius = size/2.5
let path = UIBezierPath(arcCenter: CGPoint(x: size/2,y: size/2), radius: radius, startAngle: 0.523599, endAngle: 5.75959, clockwise: true)
let length: CGFloat = sin(1.0472) * radius
path.addQuadCurve(to: CGPoint(x: path.currentPoint.x, y: path.currentPoint.y + length), controlPoint: CGPoint(x: size/2 + size / 8, y: size/2))
path.close()
sbpa.append(SpecificBezierPath(path: path, stroke: true, fill: true, strokeColor: .black, fillColor: .black))
let objectSize = size/7
let object1 = UIBezierPath(roundedRect: CGRect(x: size/2 + size / 10, y: size/4.2, width: objectSize, height: objectSize), cornerRadius: objectSize/2)
sbpa.append(SpecificBezierPath(path: object1, stroke: false, fill: true, strokeColor: .clear, fillColor: .white))
let object2 = UIBezierPath(roundedRect: CGRect(x: size/2 - size / 8, y: size/2 - size / 3, width: objectSize, height: objectSize), cornerRadius: objectSize/2)
sbpa.append(SpecificBezierPath(path: object2, stroke: false, fill: true, strokeColor: .clear, fillColor: .white))
let object3 = UIBezierPath(roundedRect: CGRect(x: size/2 - size / 3, y: size/2 - size / 8, width: objectSize, height: objectSize), cornerRadius: objectSize/2)
sbpa.append(SpecificBezierPath(path: object3, stroke: false, fill: true, strokeColor: .clear, fillColor: .white))
let object4 = UIBezierPath(roundedRect: CGRect(x: size/2 - size / 4, y: size/2 + size/7, width: objectSize, height: objectSize), cornerRadius: objectSize/2)
sbpa.append(SpecificBezierPath(path: object4, stroke: false, fill: true, strokeColor: .clear, fillColor: .white))
let object5 = UIBezierPath(roundedRect: CGRect(x: size/2 + size / 10, y: size/2 + size/10, width: objectSize, height: objectSize), cornerRadius: objectSize/2)
sbpa.append(SpecificBezierPath(path: object5, stroke: false, fill: true, strokeColor: .clear, fillColor: .white))
return sbpa
}
}
public class PaintView: UIView{
var canvas: CanvasView!
var colorsView: UIStackView!
var colors: [UIColor] = [#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),#colorLiteral(red: 0.6642242074, green: 0.6642400622, blue: 0.6642315388, alpha: 1),#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0),#colorLiteral(red: 1, green: 0.3005838394, blue: 0.2565174997, alpha: 1),#colorLiteral(red: 1, green: 0.4863265157, blue: 0, alpha: 1),#colorLiteral(red: 1, green: 0.8288275599, blue: 0, alpha: 1),#colorLiteral(red: 0.4497856498, green: 0.9784941077, blue: 0, alpha: 1),#colorLiteral(red: 0, green: 0.8252056837, blue: 0.664467752, alpha: 1),#colorLiteral(red: 0, green: 0.8362106681, blue: 1, alpha: 1),#colorLiteral(red: 0, green: 0.3225687146, blue: 1, alpha: 1),#colorLiteral(red: 0.482165277, green: 0.1738786995, blue: 0.8384277225, alpha: 1),#colorLiteral(red: 0.8474548459, green: 0.2363488376, blue: 1, alpha: 1)]
var undoButton: UIButton!
var brushSizeStackView: UIStackView!
open func clear(){
canvas?.clear()
undoButton?.isEnabled = false
}
convenience public init(){
self.init(frame: CGRect.zero)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
let settingsView = UIView()
undoButton = UIButton(type: .system)
undoButton.tintColor = .black
undoButton.setTitle("Undo", for: [])
undoButton.titleLabel?.font = SystemSettings.normalSizeFont
undoButton.addTarget(self, action: #selector(didSelectUndo(sender:)), for: .touchUpInside)
undoButton.isEnabled = false
canvas = CanvasView()
canvas.delegate = self
canvas.backgroundColor = .clear
colorsView = UIStackView()
colorsView.axis = .vertical
colorsView.distribution = .fillEqually
brushSizeStackView = UIStackView()
brushSizeStackView.axis = .horizontal
brushSizeStackView.distribution = .fillEqually
addSubview(canvas)
addSubview(colorsView)
addSubview(settingsView)
colorsView.translatesAutoresizingMaskIntoConstraints = false
colorsView.topAnchor.constraint(equalTo: topAnchor).isActive = true
colorsView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
colorsView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
colorsView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.05).isActive = true
settingsView.translatesAutoresizingMaskIntoConstraints = false
settingsView.heightAnchor.constraint(equalTo: colorsView.widthAnchor, multiplier: 1.0).isActive = true
settingsView.rightAnchor.constraint(equalTo: colorsView.leftAnchor).isActive = true
settingsView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
settingsView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
settingsView.addSubview(undoButton)
settingsView.addSubview(brushSizeStackView)
undoButton.translatesAutoresizingMaskIntoConstraints = false
undoButton.topAnchor.constraint(equalTo: settingsView.topAnchor,constant: 4).isActive = true
undoButton.leftAnchor.constraint(equalTo: settingsView.leftAnchor).isActive = true
undoButton.bottomAnchor.constraint(equalTo: settingsView.bottomAnchor,constant: -4).isActive = true
undoButton.widthAnchor.constraint(equalTo: settingsView.widthAnchor, multiplier: 0.5).isActive = true
brushSizeStackView.translatesAutoresizingMaskIntoConstraints = false
brushSizeStackView.leftAnchor.constraint(equalTo: undoButton.rightAnchor).isActive = true
brushSizeStackView.topAnchor.constraint(equalTo: settingsView.topAnchor).isActive = true
brushSizeStackView.rightAnchor.constraint(equalTo: settingsView.rightAnchor).isActive = true
brushSizeStackView.bottomAnchor.constraint(equalTo: settingsView.bottomAnchor).isActive = true
canvas.translatesAutoresizingMaskIntoConstraints = false
canvas.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
canvas.topAnchor.constraint(equalTo: topAnchor).isActive = true
canvas.bottomAnchor.constraint(equalTo: settingsView.topAnchor).isActive = true
canvas.rightAnchor.constraint(equalTo: colorsView.leftAnchor).isActive = true
for i in 0..<colors.count{
let button = createColorButton(withColor: colors[i])
button.tag = i
button.addTarget(self, action: #selector(didSelectColor(sender:)), for: .touchUpInside)
colorsView.addArrangedSubview(button)
}
let sizes: [CGFloat] = [2,3,4,5]
let actualSizes = [3,5,8,12]
for i in 0..<4{
let button = createBrushSizeButton(withSize: sizes[i])
button.addTarget(self, action: #selector(didSelectBrushSize(sender:)), for: .touchUpInside)
button.tag = actualSizes[i]
brushSizeStackView.addArrangedSubview(button)
}
(colorsView.arrangedSubviews.first as? UIButton)?.isSelected = true
(brushSizeStackView.arrangedSubviews.first as? UIButton)?.isSelected = true
}
func didSelectBrushSize(sender: UIButton){
brushSizeStackView.arrangedSubviews.forEach {
if $0 is UIButton{
let button = $0 as! UIButton
button.isSelected = false
}
}
sender.isSelected = true
let size = CGFloat(sender.tag)
canvas.lineWidth = size
}
func didSelectColor(sender: UIButton){
colorsView.arrangedSubviews.forEach {
if $0 is UIButton{
let button = $0 as! UIButton
button.isSelected = false
}
}
sender.isSelected = true
canvas.currentColor = colors[sender.tag]
}
func didSelectUndo(sender: UIButton){
canvas.undo()
if !canvas.canUndo{
sender.isEnabled = false
}
}
func createColorButton(withColor color: UIColor)->UIButton{
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 10, height: 10), cornerRadius: 2)
path.lineWidth = 0.4
let sbp = SpecificBezierPath(path: path, stroke: true, fill: true, strokeColor: .black, fillColor: color)
let image = UIImage.withBezierPath([sbp], size: CGSize(width: 10, height: 10))
let button = UIButton(type: .custom)
button.setImage(image, for: [])
button.setBackgroundImage(UIImage(color: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.1996291893)), for: .selected)
return button
}
func createBrushSizeButton(withSize size: CGFloat)-> UIButton{
//2,3,4,5
let path = UIBezierPath(roundedRect: CGRect(x: (10-size)/2, y: (10-size)/2, width: size, height: size), cornerRadius: size/2)
let sbp = SpecificBezierPath(path: path, stroke: false, fill: true, strokeColor: .black, fillColor: .black)
let image = UIImage.withBezierPath([sbp], size: CGSize(width: 10, height: 10))
let button = UIButton(type: .custom)
button.setImage(image, for: [])
button.setBackgroundImage(UIImage(color: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.1996291893)), for: .selected)
return button
}
}
extension PaintView: CanvasDelegate{
public func didDrawIn(_ canvasView: CanvasView){
undoButton?.isEnabled = true
}
}
public protocol CanvasDelegate{
func didDrawIn(_ canvasView: CanvasView)
}
public class CanvasView: UIView{
struct CustomPath{
var color: UIColor
var width: CGFloat
var path: UIBezierPath
}
open var currentColor: UIColor = .black
open var lineWidth: CGFloat = 3
open var delegate: CanvasDelegate?
open var canUndo: Bool{
return paths.count > 0
}
open func clear(){
paths.removeAll()
setNeedsDisplay()
}
open func undo(){
if paths.count > 0 {
paths.removeLast()
setNeedsDisplay()
}
}
private var currentPath: UIBezierPath!
private var paths = [CustomPath]()
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
currentPath = UIBezierPath()
currentPath.lineWidth = lineWidth
currentPath.move(to: touches.first!.location(in: self))
paths.append(CustomPath(color: currentColor, width: lineWidth, path: currentPath))
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
currentPath.addLine(to: touches.first!.location(in: self))
setNeedsDisplay()
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.didDrawIn(self)
}
public override func draw(_ rect: CGRect) {
for customPath in paths{
customPath.color.setStroke()
customPath.path.stroke()
}
}
}
| mit | 06f16acd996a96ac5781b18447bb9aec | 39.893891 | 845 | 0.647979 | 4.409847 | false | false | false | false |
santosli/100-Days-of-Swift-3 | Project 12/Project 12/SLTableViewController.swift | 1 | 3761 | //
// SLTableViewController.swift
// Project 12
//
// Created by Santos on 02/11/2016.
// Copyright © 2016 santos. All rights reserved.
//
import UIKit
class SLTableViewController: UITableViewController, PassingDataProtocol {
var heroes : [String] = ["EARTHSHAKER", "TINY", "SVEN", "JUGGERNAUT"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
self.navigationItem.leftBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addNewHero))
self.navigationItem.title = "DOTA"
}
func addNewHero() {
let addHeroViewController = storyboard?.instantiateViewController(withIdentifier: "addHero") as! SLAddHeroViewController
addHeroViewController.delegate = self
self.navigationController?.pushViewController(addHeroViewController, animated: true)
}
func passingData(_ data: String) {
heroes.append(data)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return heroes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = heroes[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 041fcfe1319237ffe98a31b60f12b69a | 33.495413 | 141 | 0.670479 | 5.229485 | false | false | false | false |
martinjakubik/war | batanimal/lib/ButtonNode.swift | 1 | 1211 | //
// Button.swift
// batanimal
//
// Created by Marcin Jakubik on 13/01/2019.
// Copyright © 2019 martin jakubik. All rights reserved.
//
import Foundation
import SpriteKit
class ButtonNode:SKSpriteNode {
var labelText:String = ""
var controller:GamePlay?
init(withText labelText: String, position: CGPoint) {
let buttonTexture:SKTexture = SKTexture(imageNamed: "button.png")
super.init(texture: buttonTexture, color: UIColor.clear, size: buttonTexture.size())
self.position = position
self.labelText = labelText
self.isUserInteractionEnabled = true
let labelNode = SKLabelNode(fontNamed: "Avenir-Medium")
labelNode.text = self.labelText
labelNode.fontColor = UIColor.darkGray
labelNode.fontSize = 28.0
labelNode.verticalAlignmentMode = .center
self.addChild(labelNode)
labelNode.zPosition = 51
self.zPosition = 50
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
}
}
| apache-2.0 | cc7dec89e21cd5b650a299f030cd6bb0 | 23.693878 | 92 | 0.665289 | 4.336918 | false | false | false | false |
akuraru/RandomSwift | Tests/RandomSetStringTest.swift | 1 | 1574 | //
// RandomSetString.swift
// RandomSwift
//
// Created by akuraru on 2015/05/16.
// Copyright (c) 2015年 akuraru. All rights reserved.
//
import Foundation
import XCTest
class RandomSetStringTest : XCTestCase {
func testJapaneseFirst() {
let words = Japanese()
XCTAssertEqual(words[0], "ぁ")
}
func testJapaneseLength() {
let words = Japanese()
XCTAssertEqual(words.length, 21066)
}
func testJapaneseLast() {
let words = Japanese()
XCTAssertEqual(words[words.length - 1], "龠")
}
func testAlphabetFirst() {
let words = Alphabet()
XCTAssertEqual(words[0], "A")
}
func testAlphabetLength() {
let words = Alphabet()
XCTAssertEqual(words.length, 52)
}
func testAlphabetLast() {
let words = Alphabet()
XCTAssertEqual(words[words.length - 1], "z")
}
func testWordsFirst() {
let words = Words()
XCTAssertEqual(words[0], "A")
}
func testWordsLength() {
let words = Words()
XCTAssertEqual(words.length, 63)
}
func testWordsLast() {
let words = Words()
XCTAssertEqual(words[words.length - 1], "_")
}
func testSpaseSetFirst() {
let words = SpaseSet()
XCTAssertEqual(words[0], " ")
}
func testSpaseSetLength() {
let words = SpaseSet()
XCTAssertEqual(words.length, 5)
}
func testSpaseSetLast() {
let words = SpaseSet()
XCTAssertEqual(words[words.length - 1], "\u{0C}")
}
}
| mit | 3e9a6c2110d230f2a6256021d4fd2f14 | 23.5 | 57 | 0.577806 | 4 | false | true | false | false |
noppefoxwolf/RxQueue | RxQueue/Classes/Service.swift | 1 | 628 | //
// Service.swift
// Pods
//
// Created by Tomoya Hirano on 2017/06/14.
//
//
import RxSwift
enum ServiceState {
case working
case idle
}
final class Service {
let state = Variable<ServiceState>(.idle)
var isWorking: Bool {
return state.value == .working
}
private(set) var element: Queueable? = nil
func start(_ element: Queueable) {
self.element = element
let duration: DispatchTime = .now() + element.duration
state.value = .working
DispatchQueue.main.asyncAfter(deadline: duration, execute: { [weak self] in
self?.state.value = .idle
self?.element = nil
})
}
}
| mit | f2ad2fb0468fb8d26f299b25f6522d6b | 18.625 | 79 | 0.649682 | 3.609195 | false | false | false | false |
bhajian/raspi-remote | Carthage/Checkouts/ios-sdk/Source/TextToSpeechV1/Models/CustomVoiceUpdate.swift | 1 | 1738 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** A custom voice model used by the Text to Speech service. */
public struct CustomVoiceUpdate: JSONEncodable {
/// The new name for the custom voice model.
private let name: String?
/// The new description for the custom voice model.
private let description: String?
/// A list of words and their translations from the custom voice model.
private let words: [Word]
/// Used to initialize a `CustomVoiceUpdate` model.
public init(name: String? = nil, description: String? = nil, words: [Word] = []) {
self.name = name
self.description = description
self.words = words
}
/// Used internally to serialize a `CustomVoiceUpdate` model to JSON.
public func toJSON() -> JSON {
var json = [String: JSON]()
if let name = name {
json["name"] = .String(name)
}
if let description = description {
json["description"] = .String(description)
}
json["words"] = .Array(words.map { word in word.toJSON() })
return .Dictionary(json)
}
}
| mit | 6b6dca8266b302d3635210dbb6adf40a | 32.423077 | 86 | 0.651323 | 4.411168 | false | false | false | false |
SwiftFMI/iOS_2017_2018 | Upr/21.10.17/LoginApp-final-3/LoginApp-final-3/SuccessViewController.swift | 1 | 1514 | //
// SuccessViewController.swift
// SwiftFmi
//
// Created by Petko Haydushki on 24.10.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
class SuccessViewController: UIViewController {
var labelText = "Empty"
var username = "Empty"
@IBOutlet weak var successLabel: UILabel!
@IBOutlet weak var logOutButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.logOutButton.layer.borderColor = UIColor.white.cgColor
self.logOutButton.layer.borderWidth = 2
self.logOutButton.layer.cornerRadius = 8.0;
self.successLabel.text = labelText;
}
@IBAction func logOutAction(_ sender: Any) {
let controller = self.presentingViewController as! ViewController
controller.usernameTextField.text = ""
controller.passwordTextField.text = ""
self.dismiss(animated: true)
}
@IBAction func deleteAccount(_ sender: Any) {
if (UserDefaults.standard.object(forKey: "userData") != nil)
{
var userData = UserDefaults.standard.object(forKey: "userData") as! [String : String]
userData.removeValue(forKey: username)
let controller = self.presentingViewController as! ViewController
controller.userData = userData
UserDefaults.standard.set(userData, forKey: "userData")
self.dismiss(animated: true)
}
}
}
| apache-2.0 | c348e5d9eb6137695a902a8eb866d53c | 28.666667 | 97 | 0.630535 | 4.772871 | false | false | false | false |
galv/reddift | reddift/Model/Comment.swift | 1 | 7353 | //
// Comment.swift
// reddift
//
// Created by generator.rb via from https://github.com/reddit/reddit/wiki/JSON
// Created at 2015-04-15 11:23:32 +0900
//
import Foundation
/**
Expand child comments which are included in Comment objects, recursively.
- parameter comment: Comment object will be expanded.
- returns: Array contains Comment objects which are expaned from specified Comment object.
*/
public func extendAllReplies(comment:Thing) -> [Thing] {
var comments:[Thing] = [comment]
if let comment = comment as? Comment {
for obj in comment.replies.children {
comments.appendContentsOf(extendAllReplies(obj))
}
}
return comments
}
/**
Comment object.
*/
public struct Comment : Thing {
/// identifier of Thing like 15bfi0.
public var id:String
/// name of Thing, that is fullname, like t3_15bfi0.
public var name:String
/// type of Thing, like t3.
static public let kind = "t1"
/**
the id of the subreddit in which the thing is located
example: t5_2qizd
*/
public let subredditId:String
/**
example:
*/
public let bannedBy:String
/**
example: t3_32wnhw
*/
public let linkId:String
/**
how the logged-in user has voted on the link - True = upvoted, False = downvoted, null = no vote
example:
*/
public let likes:String
/**
example: {"kind"=>"Listing", "data"=>{"modhash"=>nil, "children"=>[{"kind"=>"more", "data"=>{"count"=>0, "parent_id"=>"t1_cqfhkcb", "children"=>["cqfmmpp"], "name"=>"t1_cqfmmpp", "id"=>"cqfmmpp"}}], "after"=>nil, "before"=>nil}}
*/
public let replies:Listing
/**
example: []
*/
public let userReports:[AnyObject]
/**
true if this post is saved by the logged in user
example: false
*/
public let saved:Bool
/**
example: 0
*/
public let gilded:Int
/**
example: false
*/
public let archived:Bool
/**
example:
*/
public let reportReasons:[AnyObject]
/**
the account name of the poster. null if this is a promotional link
example: Icnoyotl
*/
public let author:String
/**
example: t1_cqfh5kz
*/
public let parentId:String
/**
the net-score of the link. note: A submission's score is simply the number of upvotes minus the number of downvotes. If five users like the submission and three users don't it will have a score of 2. Please note that the vote numbers are not "real" numbers, they have been "fuzzed" to prevent spam bots etc. So taking the above example, if five users upvoted the submission, and three users downvote it, the upvote/downvote numbers may say 23 upvotes and 21 downvotes, or 12 upvotes, and 10 downvotes. The points score is correct, but the vote totals are "fuzzed".
example: 1
*/
public let score:Int
/**
example:
*/
public let approvedBy:String
/**
example: 0
*/
public let controversiality:Int
/**
example: The bot has been having this problem for awhile, there have been thousands of new comments since it last worked properly, so it seems like this must be something recurring? Could it have something to do with our AutoModerator?
*/
public let body:String
/**
example: false
*/
public let edited:Bool
/**
the CSS class of the author's flair. subreddit specific
example:
*/
public let authorFlairCssClass:String
/**
example: 0
*/
public let downs:Int
/**
example: <div class="md"><p>The bot has been having this problem for awhile, there have been thousands of new comments since it last worked properly, so it seems like this must be something recurring? Could it have something to do with our AutoModerator?</p>
</div>
*/
public let bodyHtml:String
/**
subreddit of thing excluding the /r/ prefix. "pics"
example: redditdev
*/
public let subreddit:String
/**
example: false
*/
public let scoreHidden:Bool
/**
example: 1429284845
*/
public let created:Int
/**
the text of the author's flair. subreddit specific
example:
*/
public let authorFlairText:String
/**
example: 1429281245
*/
public let createdUtc:Int
/**
example:
*/
public let distinguished:Bool
/**
example: []
*/
public let modReports:[AnyObject]
/**
example:
*/
public let numReports:Int
/**
example: 1
*/
public let ups:Int
public init(id:String) {
self.id = id
self.name = "\(Comment.kind)_\(self.id)"
subredditId = ""
bannedBy = ""
linkId = ""
likes = ""
replies = Listing()
userReports = []
saved = false
gilded = 0
archived = false
reportReasons = []
author = ""
parentId = ""
score = 0
approvedBy = ""
controversiality = 0
body = ""
edited = false
authorFlairCssClass = ""
downs = 0
bodyHtml = ""
subreddit = ""
scoreHidden = false
created = 0
authorFlairText = ""
createdUtc = 0
distinguished = false
modReports = []
numReports = 0
ups = 0
}
/**
Parse t1 Thing.
- parameter data: Dictionary, must be generated parsing t1 Thing.
- returns: Comment object as Thing.
*/
public init(data:JSONDictionary) {
id = data["id"] as? String ?? ""
subredditId = data["subreddit_id"] as? String ?? ""
bannedBy = data["banned_by"] as? String ?? ""
linkId = data["link_id"] as? String ?? ""
likes = data["likes"] as? String ?? ""
userReports = []
saved = data["saved"] as? Bool ?? false
gilded = data["gilded"] as? Int ?? 0
archived = data["archived"] as? Bool ?? false
reportReasons = []
author = data["author"] as? String ?? ""
parentId = data["parent_id"] as? String ?? ""
score = data["score"] as? Int ?? 0
approvedBy = data["approved_by"] as? String ?? ""
controversiality = data["controversiality"] as? Int ?? 0
body = data["body"] as? String ?? ""
edited = data["edited"] as? Bool ?? false
authorFlairCssClass = data["author_flair_css_class"] as? String ?? ""
downs = data["downs"] as? Int ?? 0
bodyHtml = data["body_html"] as? String ?? ""
subreddit = data["subreddit"] as? String ?? ""
scoreHidden = data["score_hidden"] as? Bool ?? false
name = data["name"] as? String ?? ""
created = data["created"] as? Int ?? 0
authorFlairText = data["author_flair_text"] as? String ?? ""
createdUtc = data["created_utc"] as? Int ?? 0
distinguished = data["distinguished"] as? Bool ?? false
modReports = []
numReports = data["num_reports"] as? Int ?? 0
ups = data["ups"] as? Int ?? 0
if let temp = data["replies"] as? JSONDictionary {
if let obj = Parser.parseJSON(temp) as? Listing {
replies = obj
}
else {
replies = Listing()
}
}
else {
replies = Listing()
}
}
}
| mit | a2d5552083958ae03d0ba7e6287a9cea | 28.294821 | 569 | 0.582891 | 4.103237 | false | false | false | false |
haibtdt/Assetracker | Assetracker/BuiltInApplicationAssetTracker.swift | 1 | 1647 | //
// BuiltInApplicationAssetTracker.swift
// Assetracker
//
// Created by SB 8 on 10/20/15.
// Copyright © 2015 vn.haibui. All rights reserved.
//
import UIKit
public enum BuiltInAssetClass : String {
case AppImages
case UserSpecifics
}
public class BuiltInApplicationAssetTracker: NSObject {
var assetTracker_ : AssetTracker! = nil
public var assetTracker : AssetTracker {
if assetTracker_ == nil {
let defaultFileManager = NSFileManager.defaultManager()
let appSupportDir = try! defaultFileManager.URLForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
let assetDirURL = appSupportDir.URLByAppendingPathComponent("asset_files")
try! defaultFileManager.createDirectoryAtURL(assetDirURL, withIntermediateDirectories: true, attributes: nil)
assetTracker_ = AssetTracker(assetDirectoryURL: assetDirURL)
prepopulateDefaultAssetClasses()
}
return assetTracker_
}
func prepopulateDefaultAssetClasses () {
if assetTracker_.getAssetClass(BuiltInAssetClass.AppImages.rawValue) == nil {
assetTracker_.addAssetClass(BuiltInAssetClass.AppImages.rawValue)
}
if assetTracker_.getAssetClass(BuiltInAssetClass.UserSpecifics.rawValue) == nil {
assetTracker_.addAssetClass(BuiltInAssetClass.UserSpecifics.rawValue)
}
}
}
| epl-1.0 | 780da64123b456bd4bfd1ac726ba71bc | 27.37931 | 187 | 0.640948 | 5.242038 | false | false | false | false |
gottsohn/ios-swift-boiler | IOSSwiftBoiler/SettingsViewController.swift | 1 | 5421 | //
// SettingsViewController.swift
// ios-swift-boiler
//
// Created by Godson Ukpere on 3/15/16.
// Copyright © 2016 Godson Ukpere. All rights reserved.
//
import UIKit
import CoreData
class SettingsTableViewController: UITableViewController {
let SONG_COUNT:Int = 30
let url:String = "http://blog.godson.com.ng/terms-and-conditions/"
let labelText:String = NSLocalizedString("TNC", comment: "TNC")
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if Helpers.currentUser != nil, let loginCell:UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) {
(loginCell.viewWithTag(1) as! UILabel).text = NSLocalizedString("LOGOUT", comment: "Logout")
let name:String = Helpers.currentUser[Const.KEY_USERNAME].string ?? Helpers.currentUser[Const.KEY_NAME].stringValue
(loginCell.viewWithTag(2) as! UILabel).text = name.characters.count > 0 ? name : NSLocalizedString("USERNAME", comment: "Username")
}
if let versionCell:UITableViewCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1)) {
(versionCell.viewWithTag(1) as! UILabel).text = Helpers.appVersion
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewController:WebViewController = segue.destinationViewController as? WebViewController {
viewController.url = url
viewController.labelText = labelText
}
}
@IBAction func close (sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return 3
}
return 0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let alertMessage:String = NSLocalizedString("ARE_YOU_SURE", comment: "Are you sure")
let alertTitle:String = NSLocalizedString("CONFIRM", comment: "Confirm")
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
if Helpers.currentUser != nil {
Helpers.showDialog(self, message: alertMessage, title: alertTitle, callbackOk: {
action in
Helpers.currentUser = nil
Users.deleteData()
NSNotificationCenter.defaultCenter().postNotificationName(Const.NOTIFICATION_USER_AUTH, object: nil)
self.close(tableView)
})
} else {
close(tableView)
}
default:
break
}
case 1:
switch indexPath.row {
case 1:
// Open Web View
break
case 2:
Helpers.showDialog(self, message: "About this app goes in here", title: "IOS Swift Boiler")
default:
break
}
default:
break
}
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
}
| mit | c47959e5e5739d09ffbd9f6d065264e5 | 35.621622 | 157 | 0.626384 | 5.366337 | false | false | false | false |
ACChe/eidolon | Kiosk/Bid Fulfillment/BidCheckingNetworkModel.swift | 1 | 5538 | import UIKit
import ReactiveCocoa
import Moya
class BidCheckingNetworkModel: NSObject {
private var pollInterval = NSTimeInterval(1)
private var maxPollRequests = 20
private var pollRequests = 0
// inputs
unowned let fulfillmentController: FulfillmentController
// outputs
dynamic var bidIsResolved = false
dynamic var isHighestBidder = false
dynamic var reserveNotMet = false
private var mostRecentSaleArtwork: SaleArtwork?
init(fulfillmentController: FulfillmentController) {
self.fulfillmentController = fulfillmentController
}
func waitForBidResolution (bidderPositionId: String) -> RACSignal {
return self.pollForUpdatedBidderPosition(bidderPositionId).then { [weak self] in
guard let me = self else { return RACSignal.empty() }
return me.getUpdatedSaleArtwork().flattenMap { [weak self] (saleObject) -> RACStream! in
guard let me = self else { return RACSignal.empty() }
// This is an updated model – hooray!
if let saleArtwork = saleObject as? SaleArtwork {
me.mostRecentSaleArtwork = saleArtwork
me.fulfillmentController.bidDetails.saleArtwork?.updateWithValues(saleArtwork)
me.reserveNotMet = ReserveStatus.initOrDefault(saleArtwork.reserveStatus).reserveNotMet
return RACSignal.`return`(saleArtwork)
} else {
logger.log("Bidder position was processed but corresponding saleArtwork was not found")
return RACSignal.empty()
}
}.flattenMap { [weak self] mostRecentSaleArtwork in
// TODO: adjust logic to use parameter instead of instance variable
guard let me = self else { return RACSignal.empty() }
return me.checkForMaxBid()
}
} .doNext { _ in
self.bidIsResolved = true
return
// If polling fails, we can still show bid confirmation. Do not error.
} .catchTo( RACSignal.empty() )
}
private func pollForUpdatedBidderPosition(bidderPositionId: String) -> RACSignal {
let updatedBidderPosition = getUpdatedBidderPosition(bidderPositionId).flattenMap { [weak self] bidderPositionObject in
self?.pollRequests++
logger.log("Polling \(self?.pollRequests) of \(self?.maxPollRequests) for updated sale artwork")
// TODO: handle the case where the user was already the highest bidder
if let processedAt = (bidderPositionObject as? BidderPosition)?.processedAt {
logger.log("BidPosition finished processing at \(processedAt), proceeding...")
return RACSignal.`return`(processedAt)
} else {
// The backend hasn't finished processing the bid yet
if (self?.pollRequests ?? 0) >= (self?.maxPollRequests ?? 0) {
// We have exceeded our max number of polls, fail.
return RACSignal.error(nil)
} else {
// We didn't get an updated value, so let's try again.
return RACSignal.empty().delay(self?.pollInterval ?? 1).then({ () -> RACSignal! in
return self?.pollForUpdatedBidderPosition(bidderPositionId)
})
}
}
}
return RACSignal.empty().delay(pollInterval).then { updatedBidderPosition }
}
private func checkForMaxBid() -> RACSignal {
return self.getMyBidderPositions().doNext { [weak self] (newBidderPositions) -> Void in
let newBidderPositions = newBidderPositions as? [BidderPosition]
if let topBidID = self?.mostRecentSaleArtwork?.saleHighestBid?.id {
for position in newBidderPositions! {
if position.highestBid?.id == topBidID {
self?.isHighestBidder = true
}
}
} else {
RACSignal.error(nil)
}
}
}
private func getMyBidderPositions() -> RACSignal {
let artworkID = fulfillmentController.bidDetails.saleArtwork!.artwork.id;
let auctionID = fulfillmentController.bidDetails.saleArtwork!.auctionID!
let endpoint: ArtsyAPI = ArtsyAPI.MyBidPositionsForAuctionArtwork(auctionID: auctionID, artworkID: artworkID)
return fulfillmentController.loggedInProvider!.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(BidderPosition.self)
}
private func getUpdatedSaleArtwork() -> RACSignal {
let artworkID = fulfillmentController.bidDetails.saleArtwork!.artwork.id;
let auctionID = fulfillmentController.bidDetails.saleArtwork!.auctionID!
let endpoint: ArtsyAPI = ArtsyAPI.AuctionInfoForArtwork(auctionID: auctionID, artworkID: artworkID)
return fulfillmentController.loggedInProvider!.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObject(SaleArtwork.self)
}
private func getUpdatedBidderPosition(bidderPositionId: String) -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.MyBidPosition(id: bidderPositionId)
return fulfillmentController.loggedInProvider!.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObject(BidderPosition.self)
}
}
| mit | 5b066291fb1846f774953335de662085 | 43.645161 | 150 | 0.63349 | 5.643221 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Settings/CellDescriptors/SettingsShareDatabaseCellDescriptor.swift | 1 | 2796 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import ZipArchive
import WireSyncEngine
class DocumentDelegate: NSObject, UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return UIApplication.shared.topmostViewController(onlyFullScreen: false)!
}
}
class SettingsShareDatabaseCellDescriptor: SettingsButtonCellDescriptor {
let documentDelegate: DocumentDelegate
init() {
let documentDelegate = DocumentDelegate()
self.documentDelegate = documentDelegate
super.init(title: "Share Database", isDestructive: false) { _ in
let fileURL = ZMUserSession.shared()!.managedObjectContext.zm_storeURL!
let archiveURL = fileURL.appendingPathExtension("zip")
SSZipArchive.createZipFile(atPath: archiveURL.path, withFilesAtPaths: [fileURL.path])
let shareDatabaseDocumentController = UIDocumentInteractionController(url: archiveURL)
shareDatabaseDocumentController.delegate = documentDelegate
shareDatabaseDocumentController.presentPreview(animated: true)
}
}
}
class SettingsShareCryptoboxCellDescriptor: SettingsButtonCellDescriptor {
let documentDelegate: DocumentDelegate
init() {
let documentDelegate = DocumentDelegate()
self.documentDelegate = documentDelegate
super.init(title: "Share Cryptobox", isDestructive: false) { _ in
let fileURL = ZMUserSession.shared()!.managedObjectContext.zm_storeURL!.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("otr")
let archiveURL = fileURL.appendingPathExtension("zip")
SSZipArchive.createZipFile(atPath: archiveURL.path, withContentsOfDirectory: fileURL.path)
let shareDatabaseDocumentController = UIDocumentInteractionController(url: archiveURL)
shareDatabaseDocumentController.delegate = documentDelegate
shareDatabaseDocumentController.presentPreview(animated: true)
}
}
}
| gpl-3.0 | 940c28639532c78aac655e6a4d0ed1be | 36.28 | 169 | 0.744635 | 5.356322 | false | false | false | false |
benlangmuir/swift | test/Interop/SwiftToCxx/properties/getter-in-cxx.swift | 2 | 7805 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Properties -clang-header-expose-public-decls -emit-clang-header-path %t/properties.h
// RUN: %FileCheck %s < %t/properties.h
// RUN: %check-interop-cxx-header-in-clang(%t/properties.h)
public struct FirstSmallStruct {
public let x: UInt32
}
// CHECK: class FirstSmallStruct final {
// CHECK: public:
// CHECK: inline FirstSmallStruct(FirstSmallStruct &&) = default;
// CHECK-NEXT: inline uint32_t getX() const;
// CHECK-NEXT: private:
public struct LargeStruct {
public let x1, x2, x3, x4, x5, x6: Int
public var anotherLargeStruct: LargeStruct {
return LargeStruct(x1: 11, x2: 42, x3: -0xFFF, x4: 0xbad, x5: 5, x6: 0)
}
public var firstSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 65)
}
}
// CHECK: class LargeStruct final {
// CHECK: public:
// CHECK: inline LargeStruct(LargeStruct &&) = default;
// CHECK-NEXT: inline swift::Int getX1() const;
// CHECK-NEXT: inline swift::Int getX2() const;
// CHECK-NEXT: inline swift::Int getX3() const;
// CHECK-NEXT: inline swift::Int getX4() const;
// CHECK-NEXT: inline swift::Int getX5() const;
// CHECK-NEXT: inline swift::Int getX6() const;
// CHECK-NEXT: inline LargeStruct getAnotherLargeStruct() const;
// CHECK-NEXT: inline FirstSmallStruct getFirstSmallStruct() const;
// CHECK-NEXT: private:
public final class PropertiesInClass {
public let storedInt: Int32
init(_ x: Int32) {
storedInt = x
}
public var computedInt: Int {
return Int(storedInt) - 1
}
public var smallStruct: FirstSmallStruct {
return FirstSmallStruct(x: UInt32(-storedInt));
}
}
// CHECK: class PropertiesInClass final : public swift::_impl::RefCountedClass {
// CHECK: using RefCountedClass::operator=;
// CHECK-NEXT: inline int32_t getStoredInt();
// CHECK-NEXT: inline swift::Int getComputedInt();
// CHECK-NEXT: inline FirstSmallStruct getSmallStruct();
public func createPropsInClass(_ x: Int32) -> PropertiesInClass {
return PropertiesInClass(x)
}
public struct SmallStructWithGetters {
public let storedInt: UInt32
public var computedInt: Int {
return Int(storedInt) + 2
}
public var largeStruct: LargeStruct {
return LargeStruct(x1: computedInt * 2, x2: 1, x3: 2, x4: 3, x5: 4, x6: 5)
}
public var smallStruct: SmallStructWithGetters {
return SmallStructWithGetters(storedInt: 0xFAE);
}
}
// CHECK: class SmallStructWithGetters final {
// CHECK: public:
// CHECK: inline SmallStructWithGetters(SmallStructWithGetters &&) = default;
// CHECK-NEXT: inline uint32_t getStoredInt() const;
// CHECK-NEXT: inline swift::Int getComputedInt() const;
// CHECK-NEXT: inline LargeStruct getLargeStruct() const;
// CHECK-NEXT: inline SmallStructWithGetters getSmallStruct() const;
// CHECK-NEXT: private:
public func createSmallStructWithGetter() -> SmallStructWithGetters {
return SmallStructWithGetters(storedInt: 21)
}
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
internal init(x: Int) {
storedRef = RefCountedClass(x: x)
}
public var another: StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 1)
}
}
public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 0)
}
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX2() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x2Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX3() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x3Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX4() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x4Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX5() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x5Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int LargeStruct::getX6() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x6Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::getAnotherLargeStruct() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties11LargeStructV07anotherbC0ACvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties11LargeStructV010firstSmallC0AA05FirsteC0Vvg(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline int32_t PropertiesInClass::getStoredInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int PropertiesInClass::getComputedInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct PropertiesInClass::getSmallStruct() {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties0A7InClassC11smallStructAA010FirstSmallE0Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this)));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline uint32_t SmallStructWithGetters::getStoredInt() const {
// CHECK-NEXT: return _impl::$s10Properties22SmallStructWithGettersV9storedInts6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int SmallStructWithGetters::getComputedInt() const {
// CHECK-NEXT: return _impl::$s10Properties22SmallStructWithGettersV11computedIntSivg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct SmallStructWithGetters::getLargeStruct() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties22SmallStructWithGettersV05largeC0AA05LargeC0Vvg(result, _impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline SmallStructWithGetters SmallStructWithGetters::getSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_SmallStructWithGetters::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties22SmallStructWithGettersV05smallC0ACvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer())));
// CHECK-NEXT: });
// CHECK-NEXT: }
| apache-2.0 | b68fb53c0c29e026b3a61bb62c10b7de | 41.418478 | 222 | 0.725817 | 3.881154 | false | false | false | false |
benlangmuir/swift | test/SILGen/guaranteed_closure_context.swift | 4 | 3588 | // RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s
func use<T>(_: T) {}
func escape(_ f: () -> ()) {}
protocol P {}
class C: P {}
struct S {}
// CHECK-LABEL: sil hidden [ossa] @$s26guaranteed_closure_context0A9_capturesyyF
func guaranteed_captures() {
// CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S }
var mutableTrivial = S()
// CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C }
// CHECK: [[MUTABLE_RETAINABLE_BOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MUTABLE_RETAINABLE_BOX]]
var mutableRetainable = C()
// CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var any P }
// CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MUTABLE_ADDRESS_ONLY_BOX]]
var mutableAddressOnly: P = C()
// CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S
let immutableTrivial = S()
// CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C
// CHECK: [[B_IMMUTABLE_RETAINABLE:%.*]] = begin_borrow [lexical] [[IMMUTABLE_RETAINABLE]] : $C
let immutableRetainable = C()
// CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack [lexical] $any P
let immutableAddressOnly: P = C()
func captureEverything() {
use((mutableTrivial, mutableRetainable, mutableAddressOnly,
immutableTrivial, immutableRetainable, immutableAddressOnly))
}
// CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]]
// CHECK: [[MUTABLE_TRIVIAL_BOX_BORROW:%[^,]+]] = begin_borrow [[MUTABLE_TRIVIAL_BOX]]
// CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@\$s26guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]]
// CHECK: apply [[FN]]([[MUTABLE_TRIVIAL_BOX_BORROW]], [[MUTABLE_RETAINABLE_BOX_LIFETIME]], [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME]], [[IMMUTABLE_TRIVIAL]], [[B_IMMUTABLE_RETAINABLE]], [[IMMUTABLE_ADDRESS_ONLY]])
captureEverything()
// CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]]
// -- partial_apply still takes ownership of its arguments.
// CHECK: [[FN:%.*]] = function_ref [[FN_NAME]]
// CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]]
// CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX_LIFETIME]]
// CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME]]
// CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[B_IMMUTABLE_RETAINABLE]]
// CHECK: [[IMMUTABLE_ADDRESS:%.*]] = alloc_stack $any P
// CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_ADDRESS]])
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]]
// CHECK: apply {{.*}}[[CONVERT]]
// CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX_LIFETIME]]
// CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]]
escape(captureEverything)
}
// CHECK: sil private [ossa] [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var any P }, S, @guaranteed C, @in_guaranteed any P)
| apache-2.0 | ecaaa66c4922c5239ffaa564c602d453 | 51 | 225 | 0.657191 | 3.624242 | false | false | false | false |
JeffESchmitz/RideNiceRide | RideNiceRide/ViewControllers/PullUp/ContentViewController.swift | 1 | 9948 | //
// ContentViewController.swift
// RideNiceRide
//
// Created by Jeff Schmitz on 11/14/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import UIKit
import MapKit
import ISHPullUp
import Willow
import DATAStack
import CoreData
import PKHUD
/**
* This protocol allows you to set the height of the bottom ISHPullUpController.
* This is useful for adjusting the height from outside of PullUpController or user interact.
* i.e. in the event the main viewcontroller (or any other view controller) wants to set the height.
*/
protocol PullUpViewDelegate {
func setPullUpViewHeight(bottomHeight: CGFloat, animated: Bool)
}
class ContentViewController: UIViewController {
// MARK: - Properties (public)
@IBOutlet weak var rootView: UIView!
@IBOutlet weak var layoutAnnotationLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
lazy var hubwayAPI: HubwayAPI = HubwayAPI(dataStack: self.dataStack)
unowned var dataStack: DATAStack
var viewModel: ContentViewModel? {
didSet {
updateView()
}
}
var pullUpViewDelegate: PullUpViewDelegate?
var panoramaViewDelegate: PanoramaViewDelegate?
var selectedStationViewModel: StationViewModel?
var selectedAnnotationView: AnnotationView? {
didSet {
// Ideally, update the pin image or Annotation (View?) size to be larger than the others to signify to the user this one is selected
// V2 functionality maybe?
let annotation = selectedAnnotationView?.annotation as? CustomAnnotation
//swiftlint:disable opening_brace
let stationViewModel = viewModel?.hubwayData.first{ $0.stationId == annotation?.stationId }
//swiftlint:enable opening_brace
log.info("stationViewModel: \(stationViewModel)")
selectedStationViewModel = stationViewModel
}
}
// MARK: - View Life Cycle
required init?(coder aDecoder: NSCoder) {
//swiftlint:disable force_cast
let appdelegate = UIApplication.shared.delegate as! AppDelegate
self.dataStack = appdelegate.dataStack
//swiftlint:enable force_cast
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
centerMapOnLastLocation()
}
override func viewWillAppear(_ animated: Bool) {
reloadStationsOnMapView()
}
func reloadStationsOnMapView() {
HUD.show(.progress)
hubwayAPI.getStations { (stations, error) in
if let error = error {
log.error("Error occured retreiving Stations from HubwayAPI. '\(error.localizedDescription)'")
// Really wanted to use the labeled error as it shows the buzzed X with the message.
// Alas, if the message gets too long it is set in an amazingly small font.
// HUD.flash(.labeledError(title: "", subtitle: error.localizedDescription), delay: 2.5)
HUD.flash(.label(error.localizedDescription), delay: 2.5)
} else if let stations = stations {
log.info("stations returned from HubwayAPI: \(stations.count)")
let stationViewModels = self.convertStationDataModelsToViewModels(stationDataModels: stations)
self.viewModel = ContentViewModel(hubwayData: stationViewModels)
self.makeAnnotationsAndPlot()
HUD.hide(animated: true)
}
}
}
// MARK: - View Methods
private func setupView() {
self.mapView.delegate = self
layoutAnnotationLabel.layer.cornerRadius = 2
// the mapView should use the rootView's layout margins to correctly update the legal label and coordinate region
mapView.preservesSuperviewLayoutMargins = true
}
private func makeAnnotationsAndPlot() {
let annotations = self.makeAnnotationsFromStations()
for annotation in annotations {
self.mapView.addAnnotation(annotation)
}
}
private func updateView() {
if let viewModel = viewModel {
// just for test debugging of viewmodel - replace by populating an Annotation here
log.info("There are \(viewModel.hubwayData.count) number of Stations in Hubway.")
}
}
// MARK: - Helper methods
private func convertStationDataModelsToViewModels(stationDataModels: [Station]) -> [StationViewModel] {
var result = [StationViewModel]()
for stationDataModel in stationDataModels {
result.append(StationViewModel(station: stationDataModel))
}
return result
}
private func makeAnnotationsFromStations() -> [CustomAnnotation] {
var result = [CustomAnnotation]()
if let stations = self.viewModel?.hubwayData {
if !stations.isEmpty {
if let hubwayData = self.viewModel?.hubwayData {
for station in hubwayData {
let stationLat = CLLocationDegrees(station.station.latitude!)
let stationLong = CLLocationDegrees(station.station.longitude!)
let location = CLLocationCoordinate2D(latitude: stationLat!, longitude: stationLong!)
let annotation = CustomAnnotation(coordinate: location)
annotation.stationId = station.stationId
annotation.availableBikes = Int(station.availableBikes)!
annotation.title = station.stationName
annotation.stationName = station.stationName
annotation.availableDocks = Int(station.availableDocks)!
result.append(annotation)
}
}
}
}
return result
}
private func centerMapOnLastLocation() {
let userDefaults = UserDefaults.standard
guard userDefaults.object(forKey: K.Map.Latitude) != nil
&& userDefaults.object(forKey: K.Map.Longitude) != nil else {
// If code execution reached this point,
// no region has been set (likely first run of app after install),
// so default the location to center of Boston.
let location = CLLocationCoordinate2D(latitude: 42.360083, longitude: -71.05888)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
return
}
let latitude = userDefaults.double(forKey: K.Map.Latitude)
let longitude = userDefaults.double(forKey: K.Map.Longitude)
let latitudeDelta = userDefaults.double(forKey: K.Map.LatitudeDelta)
let longitudeDelta = userDefaults.double(forKey: K.Map.LongitudeDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let coordinateSpan = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)
let coordinateRegion = MKCoordinateRegionMake(location, coordinateSpan)
mapView.setRegion(coordinateRegion, animated: true)
}
}
// MARK: - ISHPullUpContentDelegate
extension ContentViewController: ISHPullUpContentDelegate {
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, update edgeInsets: UIEdgeInsets, forContentViewController contentVC: UIViewController) {
// update edgeInsets
rootView.layoutMargins = edgeInsets
// call layoutIfNeeded right away to participate in animations.
// This method may be called from within animation blocks
rootView.layoutIfNeeded()
}
}
// MARK: - MKMapViewDelegate
extension ContentViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
log.debug("Inside \(#function)")
if annotation is MKUserLocation {
return nil
}
var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationView.identifier)
if annotationView == nil {
annotationView = AnnotationView(annotation: annotation, reuseIdentifier: AnnotationView.identifier)
annotationView?.canShowCallout = false
} else {
annotationView?.annotation = annotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
log.debug("Inside \(#function)")
guard let annotationView = view as? AnnotationView else {
log.error("Error trying to unwrap AnnotationView while selecting a pin on the MKMap")
return
}
selectedAnnotationView = annotationView
let annotation = annotationView.annotation as? CustomAnnotation
pullUpViewDelegate?.setPullUpViewHeight(bottomHeight: 70, animated: true)
if let moveToCoordinate = annotation?.coordinate {
panoramaViewDelegate?.moveNearCoordinate(coordinate: moveToCoordinate)
}
if let stationViewModel = selectedStationViewModel {
panoramaViewDelegate?.didSelect(StationViewModel: stationViewModel)
}
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
log.debug("Inside \(#function)")
panoramaViewDelegate?.didDeselect()
self.selectedStationViewModel = nil
self.selectedAnnotationView = nil
pullUpViewDelegate?.setPullUpViewHeight(bottomHeight: 0, animated: true)
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let userDefaults = UserDefaults.standard
userDefaults.set(mapView.region.center.latitude, forKey: K.Map.Latitude)
userDefaults.set(mapView.region.center.longitude, forKey: K.Map.Longitude)
userDefaults.set(mapView.region.span.latitudeDelta, forKey: K.Map.LatitudeDelta)
userDefaults.set(mapView.region.span.longitudeDelta, forKey: K.Map.LongitudeDelta)
userDefaults.synchronize()
}
}
// MARK: - ManageFavoriteDelegate
extension ContentViewController: ManageFavoriteDelegate {
func addFavoriteStation() {
log.debug("Inside \(#function)")
if let stationViewModel = selectedStationViewModel {
_ = hubwayAPI.insertFavorite(forStation: stationViewModel.station)
}
}
func removeFavoriteStation() {
log.debug("Inside \(#function)")
if let stationViewModel = selectedStationViewModel {
dataStack.performInNewBackgroundContext({ (backgroundContext) in
self.hubwayAPI.removeFavorite(forStationId: stationViewModel.stationId, in: backgroundContext)
})
}
}
}
| mit | aade5c5fffd0f9cc6c51e4ffdf9aa57c | 35.977695 | 165 | 0.72635 | 4.800676 | false | false | false | false |
nasser0099/Express | Express/Functional.swift | 1 | 3995 | //===--- Functional.swift -------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express 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 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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 Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
func toMap<A : Hashable, B>(array:Array<(A, B)>) -> Dictionary<A, B> {
var dict = Dictionary<A, B>()
for (k, v) in array {
dict[k] = v
}
return dict
}
extension SequenceType {
func fold<B>(initial:B, f:(B,Generator.Element)->B) -> B {
var b:B = initial
forEach { e in
b = f(b, e)
}
return b
}
func findFirst(f:(Generator.Element)->Bool) -> Generator.Element? {
for e in self {
if(f(e)) {
return e
}
}
return nil
}
func mapFirst<B>(f:(Generator.Element)->B?) -> B? {
for e in self {
let b = f(e)
if b != nil {
return b
}
}
return nil
}
}
/*Just an example
let arr = [1, 2, 4]
let folded = arr.fold(1) { b, e in
return b+e
}
print("B: ", folded)*/
extension Optional : SequenceType {
public typealias Generator = AnyGenerator<Wrapped>
/// A type that represents a subsequence of some of the elements.
public func generate() -> Generator {
var done:Bool = false
return anyGenerator {
if(done) {
return None
}
done = true
return self
}
}
}
public extension Optional {
func getOrElse(@autoclosure el:() -> Wrapped) -> Wrapped {
switch self {
case .Some(let value): return value
default: return el()
}
}
func getOrElse(el:() -> Wrapped) -> Wrapped {
switch self {
case .Some(let value): return value
default: return el()
}
}
}
public extension Dictionary {
mutating func getOrInsert(key:Key, @autoclosure f:()->Value) -> Value {
return getOrInsert(key, f: f)
}
mutating func getOrInsert(key:Key, f:()->Value) -> Value {
guard let stored = self[key] else {
let value = f()
self[key] = value
return value
}
return stored
}
mutating func getOrInsert(key:Key, @autoclosure f:() throws ->Value) throws -> Value {
return try getOrInsert(key, f: f)
}
mutating func getOrInsert(key:Key, f:() throws -> Value) throws -> Value {
guard let stored = self[key] else {
let value = try f()
self[key] = value
return value
}
return stored
}
}
public extension Dictionary {
func map<K : Hashable, V>(@noescape transform: ((Key, Value)) throws -> (K, V)) rethrows -> Dictionary<K, V> {
var result = Dictionary<K, V>()
for it in self {
let (k, v) = try transform(it)
result[k] = v
}
return result
}
}
infix operator ++ { associativity left precedence 160 }
public func ++ <Key: Hashable, Value>(left:Dictionary<Key, Value>, right:Dictionary<Key, Value>) -> Dictionary<Key, Value> {
var new = left
for (k, v) in right {
new[k] = v
}
return new
} | gpl-3.0 | 297c55f85ed59dc502beed3e3c9dddd2 | 25.64 | 124 | 0.541677 | 4.174504 | false | false | false | false |
habr/ChatTaskAPI | IQKeyboardManager/Demo/Swift_Demo/ViewController/ExampleTableViewController.swift | 3 | 2174 | //
// ExampleTableViewController.swift
// IQKeyboardManager
//
// Created by InfoEnum02 on 20/04/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
class ExampleTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if ((indexPath.row % 2) == 0) {
return 40
} else {
return 160
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "\(indexPath.section) \(indexPath.row)"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell?.backgroundColor = UIColor.clearColor()
cell?.selectionStyle = UITableViewCellSelectionStyle.None
let contentView : UIView! = cell?.contentView
if ((indexPath.row % 2) == 0) {
let textField = UITextField(frame: CGRectMake(5,5,contentView.frame.size.width-10,30))
textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth]
textField.placeholder = identifier
textField.backgroundColor = UIColor.clearColor()
textField.borderStyle = UITextBorderStyle.RoundedRect
cell?.contentView.addSubview(textField)
} else {
let textView = UITextView(frame: CGRectInset(contentView.bounds, 5, 5))
textView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
textView.text = "Sample Text"
cell?.contentView.addSubview(textView)
}
}
return cell!
}
}
| mit | d5409d0e6562179a5e49d5d317171b81 | 35.847458 | 158 | 0.635695 | 5.891599 | false | false | false | false |
tensorflow/swift-apis | Sources/TensorFlow/Optimizers/MomentumBased.swift | 1 | 26628 | // 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 _Differentiation
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
import Numerics
#endif
/// A RMSProp optimizer.
///
/// Implements the RMSProp optimization algorithm. RMSProp is a form of stochastic gradient descent
/// where the gradients are divided by a running average of their recent magnitude. RMSProp keeps a
/// moving average of the squared gradient for each weight.
///
/// References:
/// - ["Lecture 6.5 - rmsprop: Divide the gradient by a running average
/// of its recent magnitude"](
/// http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
/// (Tieleman and Hinton, 2012)
/// - ["Generating Sequences With Recurrent Neural Networks"](
/// https://arxiv.org/abs/1308.0850) (Graves, 2013)
public class RMSProp<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// The gradient moving average decay factor.
public var rho: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The step count.
public var step: Float = 0
/// The alpha values for all model differentiable variables.
public var alpha: Model.TangentVector = .zero
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - rho: The gradient moving average decay factor. The default value is `0.9`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-8`.
/// - decay: The learning rate decay. The default value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
rho: Float = 0.9,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(rho >= 0, "Rho must be non-negative")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.rho = rho
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let learningRate = self.learningRate * 1 / (1 + decay * Float(step))
alpha = alpha.scaled(by: rho) + (direction .* direction).scaled(by: 1 - rho)
let denominator = Model.TangentVector.sqrt(alpha).adding(epsilon)
model.move(along: (direction ./ denominator).scaled(by: -learningRate))
}
public required init(copying other: RMSProp, to device: Device) {
learningRate = other.learningRate
rho = other.rho
epsilon = other.epsilon
decay = other.decay
step = other.step
alpha = .init(copying: other.alpha, to: device)
}
}
/// An AdaGrad optimizer.
///
/// Implements the AdaGrad (adaptive gradient) optimization algorithm. AdaGrad has
/// parameter-specific learning rates, which are adapted relative to how frequently parameters
/// gets updated during training. Parameters that receive more updates have smaller learning rates.
///
/// AdaGrad individually adapts the learning rates of all model parameters by scaling them inversely
/// proportional to the square root of the running sum of squares of gradient norms.
///
/// Reference: ["Adaptive Subgradient Methods for Online Learning and Stochastic
/// Optimization"](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
/// (Duchi et al, 2011)
public class AdaGrad<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The running sum of squares of gradient norms.
public var accumulator: Model.TangentVector
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - initialAccumulatorValue: The starting value for the running sum of squares of gradient
/// norms. The default value is `0.1`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-8`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
initialAccumulatorValue: Float = 0.1,
epsilon: Float = 1e-8
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(
initialAccumulatorValue >= 0, "The initial accumulator value must be non-negative.")
self.learningRate = learningRate
self.epsilon = epsilon
self.accumulator = Model.TangentVector.one.scaled(by: initialAccumulatorValue)
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
accumulator = accumulator + (direction .* direction)
let denominator = Model.TangentVector.sqrt(accumulator).adding(epsilon)
model.move(along: (direction ./ denominator).scaled(by: -learningRate))
}
public required init(copying other: AdaGrad, to device: Device) {
learningRate = other.learningRate
epsilon = other.epsilon
accumulator = .init(copying: other.accumulator, to: device)
}
}
/// An AdaDelta optimizer.
///
/// Implements the AdaDelta optimization algorithm. AdaDelta is a stochastic
/// gradient descent method based on the first order information. It adapts
/// learning rates based on a moving window of gradient updates, instead of
/// accumulating all past gradients. Thus, AdaDelta continues learning even
/// when many updates have been done. It adapts faster to changing dynamics of
/// the optimization problem space.
///
/// Reference: ["ADADELTA: An Adaptive Learning Rate Method"](
/// https://arxiv.org/abs/1212.5701) (Zeiler, 2012)
public class AdaDelta<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// The decay factor, corresponding to the fraction of gradient to keep at each time step.
public var rho: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The accumulated, exponentially decaying average of squared gradients.
public var averageSquared: Model.TangentVector = .zero
/// The accumulated parameter updates.
public var accumulatedDelta: Model.TangentVector = .zero
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1`.
/// - rho: The decay factor. The default value is `0.95`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-6`.
/// - decay: The learning rate decay. The defalut value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1,
rho: Float = 0.95,
epsilon: Float = 1e-6,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= rho && rho <= 1, "Rho parameter must be between 0 and 1")
precondition(0 <= epsilon, "Epsilon parameter must be non-negative")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.rho = rho
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let learningRate = self.learningRate / (1 + decay * Float(step))
averageSquared =
averageSquared.scaled(by: rho) + (direction .* direction).scaled(by: 1 - rho)
var stepSize = direction .* Model.TangentVector.sqrt(accumulatedDelta.adding(epsilon))
stepSize ./= Model.TangentVector.sqrt(averageSquared.adding(epsilon))
model.move(along: stepSize.scaled(by: -learningRate))
accumulatedDelta =
accumulatedDelta.scaled(by: rho) + (stepSize .* stepSize).scaled(by: 1 - rho)
}
public required init(copying other: AdaDelta, to device: Device) {
learningRate = other.learningRate
rho = other.rho
epsilon = other.epsilon
decay = other.decay
step = other.step
averageSquared = .init(copying: other.averageSquared, to: device)
accumulatedDelta = .init(copying: other.accumulatedDelta, to: device)
}
}
/// Adam optimizer.
///
/// Implements the Adam optimization algorithm. Adam is a stochastic gradient descent method that
/// computes individual adaptive learning rates for different parameters from estimates of first-
/// and second-order moments of the gradients.
///
/// Reference: ["Adam: A Method for Stochastic Optimization"](https://arxiv.org/abs/1412.6980v8)
/// (Kingma and Ba, 2014).
///
/// ### Examples: ###
///
/// - Train a simple reinforcement learning agent:
///
/// ````
/// ...
/// // Instantiate an agent's policy - approximated by the neural network (`net`) after defining it
/// in advance.
/// var net = Net(observationSize: Int(observationSize), hiddenSize: hiddenSize, actionCount: actionCount)
/// // Define the Adam optimizer for the network with a learning rate set to 0.01.
/// let optimizer = Adam(for: net, learningRate: 0.01)
/// ...
/// // Begin training the agent (over a certain number of episodes).
/// while true {
/// ...
/// // Implementing the gradient descent with the Adam optimizer:
/// // Define the gradients (use withLearningPhase to call a closure under a learning phase).
/// let gradients = withLearningPhase(.training) {
/// TensorFlow.gradient(at: net) { net -> Tensor<Float> in
/// // Return a softmax (loss) function
/// return loss = softmaxCrossEntropy(logits: net(input), probabilities: target)
/// }
/// }
/// // Update the differentiable variables of the network (`net`) along the gradients with the Adam
/// optimizer.
/// optimizer.update(&net, along: gradients)
/// ...
/// }
/// }
/// ````
///
/// - Train a generative adversarial network (GAN):
///
/// ````
/// ...
/// // Instantiate the generator and the discriminator networks after defining them.
/// var generator = Generator()
/// var discriminator = Discriminator()
/// // Define the Adam optimizers for each network with a learning rate set to 2e-4 and beta1 - to 0.5.
/// let adamOptimizerG = Adam(for: generator, learningRate: 2e-4, beta1: 0.5)
/// let adamOptimizerD = Adam(for: discriminator, learningRate: 2e-4, beta1: 0.5)
/// ...
/// Start the training loop over a certain number of epochs (`epochCount`).
/// for epoch in 1...epochCount {
/// // Start the training phase.
/// ...
/// for batch in trainingShuffled.batched(batchSize) {
/// // Implementing the gradient descent with the Adam optimizer:
/// // 1) Update the generator.
/// ...
/// let 𝛁generator = TensorFlow.gradient(at: generator) { generator -> Tensor<Float> in
/// ...
/// return loss
/// }
/// // Update the differentiable variables of the generator along the gradients (`𝛁generator`)
/// // with the Adam optimizer.
/// adamOptimizerG.update(&generator, along: 𝛁generator)
///
/// // 2) Update the discriminator.
/// ...
/// let 𝛁discriminator = TensorFlow.gradient(at: discriminator) { discriminator -> Tensor<Float> in
/// ...
/// return loss
/// }
/// // Update the differentiable variables of the discriminator along the gradients (`𝛁discriminator`)
/// // with the Adam optimizer.
/// adamOptimizerD.update(&discriminator, along: 𝛁discriminator)
/// }
/// }
/// ````
public class Adam<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - beta1: The exponential decay rate for the 1st moment estimates. The default value is `0.9`.
/// - beta2: The exponential decay rate for the 2nd moment estimates. The default value is `0.999`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability.
/// The default value is `1e-8`.
/// - decay: The learning rate decay. The default value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
// Note: `stepSize` is split into two lines to avoid the "compiler is unable to type-check
// this expression in reasonable time" error.
var stepSize = learningRate * sqrtf(1 - powf(beta2, step))
stepSize = stepSize / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
let denominator = Model.TangentVector.sqrt(secondMoments).adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: Adam, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
}
}
/// AdaMax optimizer.
///
/// A variant of Adam based on the infinity-norm.
///
/// Reference: Section 7 of ["Adam - A Method for Stochastic Optimization"](
/// https://arxiv.org/abs/1412.6980v8)
public class AdaMax<Model: Differentiable & KeyPathIterable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// Decay rate used to estimate the first moment (mean) of gradients.
public var beta1: Float
/// Decay rate used to estimate the exponentially weighted infinity norm.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The step count.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The exponentially weighted infinity norm of the weights.
public var infinityNorm: Model.TangentVector = .zero
/// Note: The default parameters follow those provided in the paper.
public init(
for model: __shared Model,
learningRate: Float = 0.002,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative.")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1.")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1.")
precondition(decay >= 0, "Learning rate decay must be non-negative.")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
let stepSize = learningRate / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
// Update `infinityNorm` using a key path approach because `max(_:_:)` cannot be
// currently applied in a simpler manner.
for kp in infinityNorm.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) {
infinityNorm[keyPath: kp] = max(
beta2 * infinityNorm[keyPath: kp], abs(direction[keyPath: kp]))
}
for kp in infinityNorm.recursivelyAllWritableKeyPaths(to: Tensor<Double>.self) {
infinityNorm[keyPath: kp] = max(
Double(beta2) * infinityNorm[keyPath: kp], abs(direction[keyPath: kp]))
}
let denominator = infinityNorm.adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: AdaMax, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
infinityNorm = .init(copying: other.infinityNorm, to: device)
}
}
/// AMSGrad optimizer.
///
/// This algorithm is a modification of Adam with better convergence properties when close to local
/// optima.
///
/// Reference: ["On the Convergence of Adam and Beyond"](
/// https://openreview.net/pdf?id=ryQu7f-RZ)
public class AMSGrad<Model: Differentiable & KeyPathIterable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
/// The maximum of the second moments of the weights.
public var secondMomentsMax: Model.TangentVector = .zero
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
// Note: `stepSize` is split into two lines to avoid the "compiler is unable to type-check
// this expression in reasonable time" error.
var stepSize = learningRate * sqrtf(1 - powf(beta2, step))
stepSize = stepSize / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
// Update `secondMomentsMax` using a key path approach because `max(_:_:)` cannot be
// currently applied in a simpler manner.
for kp in secondMomentsMax.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) {
secondMomentsMax[keyPath: kp] = max(
secondMomentsMax[keyPath: kp], secondMoments[keyPath: kp])
}
for kp in secondMomentsMax.recursivelyAllWritableKeyPaths(to: Tensor<Double>.self) {
secondMomentsMax[keyPath: kp] = max(
secondMomentsMax[keyPath: kp], secondMoments[keyPath: kp])
}
let denominator = Model.TangentVector.sqrt(secondMomentsMax).adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: AMSGrad, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
secondMomentsMax = .init(copying: other.secondMomentsMax, to: device)
}
}
/// RAdam optimizer.
///
/// Rectified Adam, a variant of Adam that introduces a term to rectify the adaptive learning rate
/// variance.
///
/// Reference: ["On the Variance of the Adaptive Learning Rate and Beyond"](
/// https://arxiv.org/pdf/1908.03265.pdf)
public class RAdam<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable,
Model.TangentVector.VectorSpaceScalar == Float
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let beta1Power = powf(beta1, step)
let beta2Power = powf(beta2, step)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
// Compute maximum length SMA, bias-corrected moving average and approximate length.
let N_sma_inf = 2 / (1 - beta2) - 1
let N_sma_t = N_sma_inf - 2 * step * beta2Power / (1 - beta2Power)
if N_sma_t >= 5 {
// Compute bias-corrected second moments, rectification and adapted momentum.
let secondMoments_h = Model.TangentVector.sqrt(secondMoments).adding(epsilon)
let stepSize =
sqrtf(
(N_sma_t - 4) * (N_sma_t - 2) * N_sma_inf
/ ((N_sma_inf - 4) * (N_sma_inf - 2) * (N_sma_t))) * learningRate / (1 - beta1Power)
model.move(
along: (firstMoments ./ secondMoments_h).scaled(by: -stepSize * sqrtf(1 - beta2Power)))
} else {
// Update with un-adapted momentum.
let stepSize = learningRate / (1 - beta1Power)
model.move(along: firstMoments.scaled(by: -stepSize))
}
}
public required init(copying other: RAdam, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
}
}
| apache-2.0 | 9364a1115848d99cba2930bc6809188e | 39.075301 | 111 | 0.689929 | 4.043458 | false | false | false | false |
hejunbinlan/Watchdog | Classes/Watchdog.swift | 4 | 2164 | import Foundation
public class Watchdog {
/*
The number of seconds that must pass to consider the main thread blocked
*/
private var threshold: Double
private var runLoop: CFRunLoopRef = CFRunLoopGetMain()
private var observer: CFRunLoopObserverRef!
private var startTime: UInt64 = 0;
public init(threshold: Double = 0.2) {
self.threshold = threshold
var timebase: mach_timebase_info_data_t = mach_timebase_info(numer: 0, denom: 0)
mach_timebase_info(&timebase)
let secondsPerMachine: NSTimeInterval = NSTimeInterval(Double(timebase.numer) / Double(timebase.denom) / Double(1e9))
observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault,
CFRunLoopActivity.AllActivities.rawValue,
true,
0) { [weak self] (observer, activity) in
guard let weakSelf = self else {
return
}
switch(activity) {
case CFRunLoopActivity.Entry, CFRunLoopActivity.BeforeTimers,
CFRunLoopActivity.AfterWaiting, CFRunLoopActivity.BeforeSources:
if weakSelf.startTime == 0 {
weakSelf.startTime = mach_absolute_time()
}
case CFRunLoopActivity.BeforeWaiting, CFRunLoopActivity.Exit:
let elapsed = mach_absolute_time() - weakSelf.startTime
let duration: NSTimeInterval = NSTimeInterval(elapsed) * secondsPerMachine
if duration > weakSelf.threshold {
print("👮 Main thread was blocked for " + String(format:"%.2f", duration) + "s 👮");
}
weakSelf.startTime = 0
default: ()
}
}
CFRunLoopAddObserver(CFRunLoopGetMain(), observer!, kCFRunLoopCommonModes)
}
deinit {
CFRunLoopObserverInvalidate(observer!)
}
}
| mit | b463e34a070a549e2c81401deadedc96 | 35.576271 | 125 | 0.541242 | 5.880109 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/SignalUtils.swift | 1 | 2066 | //
// SignalUtils.swift
// TelegramMac
//
// Created by keepcoder on 27/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
func countdown(_ count:Double, delay:Double) -> Signal<Double,Void> {
return Signal { subscriber in
var value:Double = count
subscriber.putNext(value)
var timer:SwiftSignalKit.Timer? = nil
timer = SwiftSignalKit.Timer(timeout: delay, repeat: true, completion: {
value -= delay
subscriber.putNext(max(value,0))
if value <= 0 {
subscriber.putCompletion()
timer?.invalidate()
timer = nil
}
}, queue: Queue.mainQueue())
timer?.start()
return ActionDisposable(action: {
timer?.invalidate()
})
}
}
public func `repeat`<T, E>(_ delay:Double, onQueue:Queue) -> (Signal<T, E>) -> Signal<T, E> {
return { signal in
return Signal { subscriber in
// let disposable:MEtadi = DisposableSet()
var timer:SwiftSignalKit.Timer? = nil
timer = SwiftSignalKit.Timer(timeout: delay, repeat: true, completion: {
_ = signal.start(next: { (next) in
subscriber.putNext(next)
})
}, queue: onQueue)
timer?.start()
return ActionDisposable {
timer?.invalidate()
}
}
}
}
/*
+(SSignal *)countdownSignal:(int)count delay:(int)delay {
return [[SSignal alloc] initWithGenerator:^id<SDisposable>(SSubscriber *subscriber) {
__block int value = count;
[subscriber putNext:@(value)];
STimer *timer = [[STimer alloc] initWithTimeout:delay repeat:true completion:^{
value -= delay;
[subscriber putNext:@(MAX(value, 0))];
if (value <= 0) {
[subscriber putCompletion];
}
} queue:[ASQueue mainQueue]];
[timer start];
return [[SBlockDisposable alloc] initWithBlock:^{
[timer invalidate];
}];
}];
}
*/
| gpl-2.0 | 256b96d2eacb8126d0cbed8e686eef79 | 26.171053 | 93 | 0.566102 | 4.257732 | false | false | false | false |
ello/ello-ios | Sources/Utilities/InterfaceString.swift | 1 | 47975 | ////
/// InterfaceString.swift
//
struct InterfaceString {
// Adding type information to the strings reduced the overall compile time considerably
struct Tab {
struct PopupTitle {
static let Discover: String = NSLocalizedString(
"Discover",
comment: "Discover pop up title"
)
static let Notifications: String = NSLocalizedString(
"Notifications",
comment: "Notifications pop up title"
)
static let Following: String = NSLocalizedString(
"Following",
comment: "Stream pop up title"
)
static let Profile: String = NSLocalizedString(
"Your Profile",
comment: "Profile pop up title"
)
static let Omnibar: String = NSLocalizedString("Post", comment: "Omnibar pop up title")
}
struct PopupText {
static let Discover: String = NSLocalizedString(
"What's next in art, design, fashion, web culture & more.",
comment: "Discover pop up text"
)
static let Notifications: String = NSLocalizedString(
"Stay hyped with real-time alerts.",
comment: "Notifications pop up text"
)
static let Following: String = NSLocalizedString(
"Follow the people, work & ideas that you think are most rad.",
comment: "Stream pop up text"
)
static let Profile: String = NSLocalizedString(
"Your deets & posts in one place. All your settings too.",
comment: "Profile pop up text"
)
static let Omnibar: String = NSLocalizedString(
"Publish images, GIFs, text, links and more.",
comment: "Omnibar pop up text"
)
}
}
struct Followers {
static let Title: String = NSLocalizedString("Followers", comment: "Followers title")
}
struct Following {
static let Title: String = NSLocalizedString("Following", comment: "Following title")
static let NewPosts: String = NSLocalizedString("New Posts", comment: "New posts title")
}
struct Editorials {
static let Title: String = NSLocalizedString("Editorials", comment: "")
static let NavbarTitle: String = NSLocalizedString("Editorial", comment: "")
static let Join: String = NSLocalizedString("Join The Creators Network.", comment: "")
static let JoinCaption: String = NSLocalizedString(
"Be part of what’s next in art, design, fasion, web, culture & more.",
comment: ""
)
static let SubmitJoin: String = NSLocalizedString("Create Account", comment: "")
static let Invite: String = NSLocalizedString("Invite some cool people.", comment: "")
static let InviteCaption: String = NSLocalizedString("Help Ello grow.", comment: "")
static let InviteInstructions: String = NSLocalizedString(
"Invite as many people as you want, just separate their email addresses with commas.",
comment: ""
)
static let InvitePlaceholder: String = NSLocalizedString(
"Enter email addresses",
comment: ""
)
static let InviteSent: String = NSLocalizedString("✅ Invitations sent.", comment: "")
static let SubmitInvite: String = NSLocalizedString("Invite", comment: "")
static let EmailPlaceholder: String = NSLocalizedString("Email", comment: "")
static let UsernamePlaceholder: String = NSLocalizedString("Username", comment: "")
static let PasswordPlaceholder: String = NSLocalizedString("Password", comment: "")
static let Advertising: String = NSLocalizedString("#advertising", comment: "")
}
struct ArtistInvites {
static let Title: String = NSLocalizedString("Creative Briefs", comment: "")
static let Submissions: String = NSLocalizedString("Submissions", comment: "")
static let Selections: String = NSLocalizedString("Selections", comment: "")
static let PostSubmissionHeader: String = NSLocalizedString(
"Invite Submission",
comment: ""
)
static let SubmissionsError: String = NSLocalizedString(
"Error while loading submissions",
comment: ""
)
static let SeeSubmissions: String = NSLocalizedString("↓ See Submissions", comment: "")
static let Submit: String = NSLocalizedString("SUBMIT", comment: "")
static let PreviewStatus: String = NSLocalizedString("Preview", comment: "")
static let UpcomingStatus: String = NSLocalizedString("Coming Soon", comment: "")
static let OpenStatus: String = NSLocalizedString("Open For Submissions", comment: "")
static let SelectingStatus: String = NSLocalizedString(
"Selections In Progress",
comment: ""
)
static let ClosedStatus: String = NSLocalizedString("Invite Closed", comment: "")
static let SubmissionJoinPrompt: String = NSLocalizedString(
"To submit to an Invite you first need to create an Ello account.",
comment: ""
)
static let SubmissionSuccessTitle: String = NSLocalizedString(
"Submission received!",
comment: ""
)
static let SubmissionSuccessDescription: String = NSLocalizedString(
"Our team of curators will review your submission and you’ll recieve a notification when it is accepted.",
comment: ""
)
static let AdminTitle: String = NSLocalizedString("Submissions", comment: "")
static let AdminEmpty: String = NSLocalizedString("No submissions", comment: "")
static let AdminUnapprovedStream: String = NSLocalizedString("Pending review", comment: "")
static let AdminApprovedStream: String = NSLocalizedString(
"Accepted submissions",
comment: ""
)
static let AdminSelectedStream: String = NSLocalizedString(
"Selected submissions",
comment: ""
)
static let AdminDeclinedStream: String = NSLocalizedString(
"Declined submissions",
comment: ""
)
static let AdminUnapprovedTab: String = NSLocalizedString("To Review", comment: "")
static let AdminApprovedTab: String = NSLocalizedString("Accepted", comment: "")
static let AdminSelectedTab: String = NSLocalizedString("Selected", comment: "")
static let AdminDeclinedTab: String = NSLocalizedString("Declined", comment: "")
static let AdminUnapproveAction: String = NSLocalizedString("Accepted", comment: "")
static let AdminUnselectAction: String = NSLocalizedString("Selected", comment: "")
static let AdminApproveAction: String = NSLocalizedString("Accept", comment: "")
static let AdminSelectAction: String = NSLocalizedString("Select", comment: "")
static let AdminDeclineAction: String = NSLocalizedString("Decline", comment: "")
static let Selecting: String = NSLocalizedString("Hold Tight", comment: "")
static func Opens(_ dateStr: String) -> String {
return String.localizedStringWithFormat("Opens %@", dateStr)
}
static func Ends(_ dateStr: String) -> String {
return String.localizedStringWithFormat("Ends %@", dateStr)
}
static func Ended(_ dateStr: String) -> String {
return String.localizedStringWithFormat("Ended %@", dateStr)
}
static func DaysRemaining(_ days: Int) -> String {
return String.localizedStringWithFormat("%lu Days Remaining", days)
}
static func Countdown(_ totalSeconds: Int) -> String {
var remainingSeconds = totalSeconds
let seconds = totalSeconds % 60
remainingSeconds -= seconds
let minutes: Int = remainingSeconds / 60 % 60
remainingSeconds -= minutes * 60
let hours: Int = remainingSeconds / 3600 % 60
return String.localizedStringWithFormat(
"%02d:%02d:%02d Remaining",
hours,
minutes,
seconds
)
}
}
struct Notifications {
static let Title: String = NSLocalizedString(
"Notifications",
comment: "Notifications title"
)
static let Reply: String = NSLocalizedString("Reply", comment: "Reply button title")
}
struct Discover {
static let Title: String = NSLocalizedString("Discover", comment: "")
static let Categories: String = NSLocalizedString("Categories", comment: "")
static let AllCategories: String = NSLocalizedString("All", comment: "All Categories title")
static let Subscriptions: String = NSLocalizedString("Subscriptions", comment: "")
static let Subscribed: String = NSLocalizedString(
"Subscribed",
comment: "Subscribed Categories title"
)
static let Subscribe: String = NSLocalizedString(
"Subscribe",
comment: "Subscribe Categories title"
)
static let ZeroState: String = NSLocalizedString(
"Choose communities to subscribe to here.",
comment: ""
)
static let ZeroState1: String = NSLocalizedString(
"Choose communities to subscribe to ",
comment: ""
)
static let ZeroState2: String = NSLocalizedString("here", comment: "")
static let ZeroState3: String = NSLocalizedString(".", comment: "")
static let Featured: String = NSLocalizedString("Featured", comment: "")
static let Trending: String = NSLocalizedString("Trending", comment: "")
static let Recent: String = NSLocalizedString("Recent", comment: "")
static let Shop: String = NSLocalizedString("Shop", comment: "")
}
struct Search {
static let Prompt: String = NSLocalizedString("Search Ello", comment: "search ello prompt")
static let Posts: String = NSLocalizedString("Posts", comment: "Posts search toggle")
static let People: String = NSLocalizedString("People", comment: "People search toggle")
static let FindFriendsPrompt: String = NSLocalizedString(
"Help grow the Ello community.",
comment: "Search zero state button title"
)
static let NoMatches: String = NSLocalizedString(
"We couldn't find any matches.",
comment: "No search results found title"
)
static let TryAgain: String = NSLocalizedString(
"Try another search?",
comment: "No search results found body"
)
}
struct Drawer {
static let Invite: String = NSLocalizedString("Invite", comment: "")
static let Giveaways: String = NSLocalizedString("Giveaways", comment: "")
static let Twitter: String = NSLocalizedString("Twitter", comment: "")
static let Instagram: String = NSLocalizedString("Instagram", comment: "")
static let Facebook: String = NSLocalizedString("Facebook", comment: "")
static let Pinterest: String = NSLocalizedString("Pinterest", comment: "")
static let Tumblr: String = NSLocalizedString("Tumblr", comment: "")
static let Medium: String = NSLocalizedString("Medium", comment: "")
static let Magazine: String = NSLocalizedString("Magazine", comment: "")
static let Store: String = NSLocalizedString("Store", comment: "")
static let Help: String = NSLocalizedString("Help", comment: "")
static let Resources: String = NSLocalizedString("Resources", comment: "")
static let About: String = NSLocalizedString("About", comment: "")
static let Logout: String = NSLocalizedString("Logout", comment: "")
static let Version: String = {
let marketingVersion: String
let buildVersion: String
if Globals.isTesting {
marketingVersion = "SPECS"
buildVersion = "specs"
}
else {
marketingVersion = (
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
) ?? "???"
buildVersion = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String) ?? "???"
}
return NSLocalizedString(
"Ello v\(marketingVersion) b\(buildVersion)",
comment: "version number"
)
}()
}
struct Community {
static let Choose: String = NSLocalizedString("Choose Category", comment: "")
static let Search: String = NSLocalizedString("Search Categories", comment: "")
}
struct Category {
static let Moderator: String = NSLocalizedString("Moderator", comment: "")
static let Moderators: String = NSLocalizedString("Moderators", comment: "")
static let Curator: String = NSLocalizedString("Curator", comment: "")
static let Curators: String = NSLocalizedString("Curators", comment: "")
static let FeaturedUser: String = NSLocalizedString("Featured User", comment: "")
static let NoRoles: String = NSLocalizedString("No existing roles", comment: "")
static let SponsoredBy: String = NSLocalizedString("Sponsored by", comment: "")
static let PostedBy: String = NSLocalizedString("Posted by", comment: "")
static let HeaderBy: String = NSLocalizedString("Header by", comment: "")
static let RoleAdmin: String = NSLocalizedString("Community Roles", comment: "")
}
struct Settings {
static let EditProfile: String = NSLocalizedString("Edit Profile", comment: "")
static let EditCredentials: String = NSLocalizedString("Edit Credentials", comment: "")
static let CredentialsSettings: String = NSLocalizedString(
"To change your username, email, or password, please verify your current password",
comment: ""
)
static let TapToEdit: String = NSLocalizedString("(tap to edit)", comment: "")
static let AbortChanges: String = NSLocalizedString("Discard changes?", comment: "")
static let Logout: String = NSLocalizedString("Logout", comment: "")
static let Profile: String = NSLocalizedString("Profile", comment: "")
static let ProfileDescription: String = NSLocalizedString(
"Your name, username, bio and links appear on your public profile. Your email address remains private.",
comment: "Profile Privacy Description"
)
static let CommunityInfo: String = NSLocalizedString("Community Info", comment: "")
static let Username: String = NSLocalizedString("Username", comment: "")
static let Email: String = NSLocalizedString("Email", comment: "")
static let OldPassword: String = NSLocalizedString("Current Password", comment: "")
static let OldPasswordRequired: String = NSLocalizedString(
"You must enter your current password to change your username, email, or password.",
comment: ""
)
static let Password: String = NSLocalizedString("Password", comment: "")
static let Name: String = NSLocalizedString("Name", comment: "")
static let Bio: String = NSLocalizedString("Bio", comment: "")
static let Links: String = NSLocalizedString("Links", comment: "")
static let Location: String = NSLocalizedString("Location", comment: "")
static let AvatarUploaded: String = NSLocalizedString(
"You’ve updated your Avatar.\n\nIt may take a few minutes for your new avatar to appear on Ello, so please be patient. It’ll be live soon!",
comment: "Avatar updated copy"
)
static let CoverImageUploaded: String = NSLocalizedString(
"You’ve updated your Header.\n\nIt may take a few minutes for your new header to appear on Ello, so please be patient. It’ll be live soon!",
comment: "Cover Image updated copy"
)
static let CreatorType: String = NSLocalizedString("Creator Type", comment: "")
static let BlockedTitle: String = NSLocalizedString("Blocked", comment: "")
static let MutedTitle: String = NSLocalizedString("Muted", comment: "")
static let DeleteAccountTitle: String = NSLocalizedString("Account Deletion", comment: "")
static let DeleteAccount: String = NSLocalizedString("Delete Account", comment: "")
static let DeleteAccountExplanation: String = NSLocalizedString(
"By deleting your account you remove your personal information from Ello. Your account cannot be restored.",
comment: ""
)
static let DeleteAccountConfirm: String = NSLocalizedString(
"Delete Account?",
comment: "delete account question"
)
static let AccountIsBeingDeleted: String = NSLocalizedString(
"Your account is in the process of being deleted.",
comment: ""
)
static func RedirectedCountdown(_ count: Int) -> String {
return String.localizedStringWithFormat("You will be redirected in %lu...", count)
}
}
struct Profile {
static let Title: String = NSLocalizedString("Profile", comment: "Profile Title")
static let Mention: String = NSLocalizedString("@ Mention", comment: "Mention button title")
static let Collaborate: String = NSLocalizedString(
"Collab",
comment: "Collaborate button title"
)
static let Hire: String = NSLocalizedString("Hire", comment: "Hire button title")
static let Invite: String = NSLocalizedString("Invite", comment: "Invite button title")
static let EditProfile: String = NSLocalizedString(
"Edit Profile",
comment: "Edit Profile button title"
)
static let PostsCount: String = NSLocalizedString("Posts", comment: "Posts count header")
static let FollowingCount: String = NSLocalizedString(
"Following",
comment: "Following count header"
)
static let FollowersCount: String = NSLocalizedString(
"Followers",
comment: "Followers count header"
)
static let LovesCount: String = NSLocalizedString("Loves", comment: "Loves count header")
static let CurrentUserNoResultsTitle: String = NSLocalizedString(
"Welcome to your Profile",
comment: ""
)
static let CurrentUserNoResultsBody: String = NSLocalizedString(
"Everything you post lives here!\n\nThis is the place to find everyone you’re following and everyone that’s following you. You’ll find your Loves here too!",
comment: ""
)
static let NoResultsTitle: String = NSLocalizedString(
"This person hasn't posted yet.",
comment: ""
)
static let NoResultsBody: String = NSLocalizedString(
"Follow or mention them to help them get started!",
comment: ""
)
static let FeaturedIn: String = NSLocalizedString(
"Featured in",
comment: "Featurd in label"
)
static let TotalViews: String = NSLocalizedString("Views", comment: "Total views label")
static let Badges: String = NSLocalizedString("Badges", comment: "")
}
struct Badges {
static let Featured = NSLocalizedString("Featured", comment: "")
static let Community = NSLocalizedString("Community Profile", comment: "")
static let Experimental = NSLocalizedString("Experimental Group", comment: "")
static let Staff = NSLocalizedString("Ello Staff Member", comment: "")
static let StaffLink = NSLocalizedString("Meet the Staff", comment: "")
static let Spam = NSLocalizedString("Spam, Eggs, and Spam", comment: "")
static let Nsfw = NSLocalizedString("NSFW", comment: "")
static let LearnMore: String = NSLocalizedString("Learn More", comment: "")
}
struct Post {
static let DefaultTitle: String = NSLocalizedString(
"Post Detail",
comment: "Default post title"
)
static let LovedByList: String = NSLocalizedString(
"Loved by",
comment: "Loved by list title"
)
static let RepostedByList: String = NSLocalizedString(
"Reposted by",
comment: "Reposted by list title"
)
static let RelatedPosts: String = NSLocalizedString(
"Related Posts",
comment: "Related posts title"
)
static let LoadMoreComments: String = NSLocalizedString(
"Load More",
comment: "Load More Comments title"
)
static let Feature: String = NSLocalizedString("Feature", comment: "")
static let Featured: String = NSLocalizedString("Featured", comment: "")
static let FeaturedBy: String = NSLocalizedString("Featured by", comment: "")
static let AddedTo: String = NSLocalizedString("Added to", comment: "")
static let PostedInto: String = NSLocalizedString("Posted into", comment: "")
static let CreateComment: String = NSLocalizedString(
"Comment...",
comment: "Create Comment Button Prompt"
)
static let DeletePostConfirm: String = NSLocalizedString(
"Delete Post?",
comment: "Delete Post confirmation"
)
static let DeleteCommentConfirm: String = NSLocalizedString(
"Delete Comment?",
comment: "Delete Comment confirmation"
)
static let RepostConfirm: String = NSLocalizedString(
"Repost?",
comment: "Repost confirmation"
)
static let RepostSuccess: String = NSLocalizedString(
"Success!",
comment: "Successful repost alert"
)
static let RepostError: String = NSLocalizedString(
"Could not create repost",
comment: "Could not create repost message"
)
static let CannotEditPost: String = NSLocalizedString(
"Looks like this post was created on the web!\n\nThe videos and embedded content it contains are not YET editable on our iOS app. We’ll add this feature soon!",
comment: "Uneditable post error message"
)
static let CannotEditComment: String = NSLocalizedString(
"Looks like this comment was created on the web!\n\nThe videos and embedded content it contains are not YET editable on our iOS app. We’ll add this feature soon!",
comment: "Uneditable comment error message"
)
}
struct Omnibar {
static let SayEllo: String = NSLocalizedString("Say Ello...", comment: "Say Ello prompt")
static let AddMoreText: String = NSLocalizedString(
"Add more text...",
comment: "Add more text prompt"
)
static let EnterURL: String = NSLocalizedString("Enter the URL", comment: "")
static let CreatePostTitle: String = NSLocalizedString("Post", comment: "Create a post")
static func CreateArtistInviteSubmission(title: String) -> String {
return String.localizedStringWithFormat("Submit to %@", title)
}
static let CreatePostButton: String = NSLocalizedString("Post", comment: "")
static let ChooseCommunity: String = NSLocalizedString("Choose Category", comment: "")
static let EditPostTitle: String = NSLocalizedString("Edit this post", comment: "")
static let EditPostButton: String = NSLocalizedString("Edit Post", comment: "")
static let EditCommentTitle: String = NSLocalizedString("Edit this comment", comment: "")
static let EditCommentButton: String = NSLocalizedString("Edit Comment", comment: "")
static let CreateCommentTitle: String = NSLocalizedString("Leave a comment", comment: "")
static let CreateCommentButton: String = NSLocalizedString("Comment", comment: "")
static let CannotComment: String = NSLocalizedString(
"This user has disabled comments.",
comment: ""
)
static let TooLongError: String = NSLocalizedString(
"Your text is too long.\n\nThe character limit is 5,000.",
comment: "Post too long (maximum characters is 5000) error message"
)
static func LoadingImageError(url: URL) -> String {
return String.localizedStringWithFormat(
"There was a problem loading the image\n%@",
url.absoluteString
)
}
static let UpdatingPost: String = NSLocalizedString("Updating your post…", comment: "")
static let UpdatingComment: String = NSLocalizedString(
"Updating your comment…",
comment: ""
)
static let CreatingPost: String = NSLocalizedString("Creating your post…", comment: "")
static let CreatingComment: String = NSLocalizedString(
"Creating your comment…",
comment: ""
)
static let CreatedPost: String = NSLocalizedString(
"Post successfully created!",
comment: ""
)
static let CreatedComment: String = NSLocalizedString(
"Comment successfully created!",
comment: ""
)
static let SellYourWorkTitle: String = NSLocalizedString(
"Sell your work",
comment: "Sell your work title"
)
static let ProductLinkPlaceholder: String = NSLocalizedString(
"Product detail URL",
comment: "Product detail URL prompt"
)
}
struct Hire {
static func HireTitle(atName: String) -> String {
return String.localizedStringWithFormat("Hire %@", atName)
}
static func CollaborateTitle(atName: String) -> String {
return String.localizedStringWithFormat("Collaborate with %@", atName)
}
}
struct Loves {
static let Title: String = NSLocalizedString("Loves", comment: "love stream")
}
struct Relationship {
static let Follow: String = NSLocalizedString("Follow", comment: "Follow relationship")
static let Following: String = NSLocalizedString(
"Following",
comment: "Following relationship"
)
static let Muted: String = NSLocalizedString("Muted", comment: "Muted relationship")
static let Blocked: String = NSLocalizedString("Blocked", comment: "Blocked relationship")
static let MuteButton: String = NSLocalizedString("Mute", comment: "Mute button title")
static let UnmuteButton: String = NSLocalizedString(
"Unmute",
comment: "Unmute button title"
)
static let BlockButton: String = NSLocalizedString("Block", comment: "Block button title")
static let UnblockButton: String = NSLocalizedString(
"Unblock",
comment: "Unblock button title"
)
static let FlagButton: String = NSLocalizedString("Flag", comment: "Flag button title")
static func UnmuteAlert(atName: String) -> String {
return String.localizedStringWithFormat(
"Would you like to \nunmute or block %@?",
atName
)
}
static func UnblockAlert(atName: String) -> String {
return String.localizedStringWithFormat(
"Would you like to \nmute or unblock %@?",
atName
)
}
static func MuteAlert(atName: String) -> String {
return String.localizedStringWithFormat("Would you like to \nmute or block %@?", atName)
}
static func MuteWarning(atName: String) -> String {
return String.localizedStringWithFormat(
"%@ will not be able to comment on your posts. If %@ mentions you, you will not be notified.",
atName,
atName
)
}
static func BlockWarning(atName: String) -> String {
return String.localizedStringWithFormat(
"%@ will not be able to follow you or view your profile, posts or find you in search.",
atName
)
}
static func FlagWarning(atName: String) -> String {
return String.localizedStringWithFormat("%@ will be investigated by our staff.", atName)
}
}
struct PushNotifications {
static let PermissionPrompt: String = NSLocalizedString(
"Ello would like to send you push notifications.\n\nWe will let you know when you have new notifications. You can make changes in your settings.\n",
comment: "Turn on Push Notifications prompt"
)
static let PermissionYes: String = NSLocalizedString("Yes please", comment: "Allow")
static let PermissionNo: String = NSLocalizedString("No thanks", comment: "Disallow")
static let CommentReply: String = NSLocalizedString("Reply", comment: "")
static let MessageUser: String = NSLocalizedString("Mention", comment: "")
static let PostComment: String = NSLocalizedString("Comment", comment: "")
static let LovePost: String = NSLocalizedString("Love", comment: "")
static let FollowUser: String = NSLocalizedString("Follow", comment: "")
static let View: String = NSLocalizedString("View", comment: "")
}
struct Friends {
static let ImportPermissionTitle: String = NSLocalizedString(
"Invite some cool people",
comment: ""
)
static let ImportPermissionSubtitle: String = NSLocalizedString(
"Help Ello grow.",
comment: ""
)
static let ImportPermissionPrompt: String = NSLocalizedString(
"Ello does not sell user data, and will never contact anyone without your permission.",
comment: ""
)
static let ImportSMS: String = NSLocalizedString("Send Invite", comment: "")
static let SMSMessage: String = NSLocalizedString(
"Check out Ello, the Creators Network. https://itunes.apple.com/us/app/ello/id953614327",
comment: ""
)
static let ImportAllow: String = NSLocalizedString("Import my contacts", comment: "")
static let ImportNotNow: String = NSLocalizedString("Not now", comment: "")
static func ImportError(_ message: String) -> String {
return String.localizedStringWithFormat(
"We were unable to access your address book\n%@",
message
)
}
static let AccessDenied: String = NSLocalizedString(
"Access to your contacts has been denied. If you want to search for friends, you will need to grant access from Settings.",
comment: "Access to contacts denied by user"
)
static let AccessRestricted: String = NSLocalizedString(
"Access to your contacts has been denied by the system.",
comment: "Access to contacts denied by system"
)
static let FindAndInvite: String = NSLocalizedString(
"Find & invite your contacts",
comment: "Find & invite"
)
static let Resend: String = NSLocalizedString(
"Re-send",
comment: "invite friends cell re-send"
)
static let Invite: String = NSLocalizedString(
"Invite",
comment: "invite friends cell invite"
)
}
struct NSFW {
static let Show: String = NSLocalizedString("Tap to View.", comment: "")
static let Hide: String = NSLocalizedString("Tap to Hide.", comment: "")
}
struct ImagePicker {
static let ChooseSource: String = NSLocalizedString(
"Choose a photo source",
comment: "choose photo source (camera or library)"
)
static let Camera: String = NSLocalizedString("Camera", comment: "camera button")
static let Library: String = NSLocalizedString("Library", comment: "library button")
static let NoSourceAvailable: String = NSLocalizedString(
"Sorry, but your device doesn’t have a photo library!",
comment: "device doesn't support photo library"
)
static let TakePhoto: String = NSLocalizedString("Take Photo", comment: "Camera button")
static let PhotoLibrary: String = NSLocalizedString(
"Photo Library",
comment: "Library button"
)
static func AddImages(_ count: Int) -> String {
return String.localizedStringWithFormat("Add %lu Image(s)", count)
}
static let ChooseImage: String = NSLocalizedString("Choose Image", comment: "")
}
struct WebBrowser {
static let TermsAndConditions: String = NSLocalizedString(
"Terms and Conditions",
comment: "terms and conditions title"
)
}
struct Startup {
static let SignUp: String = NSLocalizedString("Sign Up", comment: "sign up button")
static let Login: String = NSLocalizedString("Login", comment: "login button")
static let Join: String = NSLocalizedString("Join The Creators Network.", comment: "")
static let Reset: String = NSLocalizedString("Reset", comment: "Reset button label")
static let ForgotPasswordEnter: String = NSLocalizedString(
"Enter your email",
comment: "Enter your email label"
)
static let ForgotPasswordEnterSuccess: String = NSLocalizedString(
"If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.",
comment: "Enter your email success description"
)
static let ForgotPasswordReset: String = NSLocalizedString(
"Reset your password.",
comment: "Reset your password label"
)
static let ForgotPasswordResetError: String = NSLocalizedString(
"The password reset token you used is no longer valid. This may be because you requested more than one token, or that too much time has elapsed.",
comment: "Reset your password long error reason."
)
static let Tagline: String = NSLocalizedString(
"Be part of what’s next in art, design, fashion, web culture & more.",
comment: "Be part of what's next tag line label"
)
}
struct Login {
static let Continue: String = NSLocalizedString("Continue", comment: "continue button")
static let LoadUserError: String = NSLocalizedString(
"Unable to load user.",
comment: "Unable to load user message"
)
static let ForgotPassword: String = NSLocalizedString(
"Forgot Password",
comment: "forgot password title"
)
static let UsernamePlaceholder: String = NSLocalizedString(
"Username or Email",
comment: "username or email field"
)
static let PasswordPlaceholder: String = NSLocalizedString(
"Password",
comment: "password field"
)
}
struct Join {
static let Discover: String = NSLocalizedString(
"Discover Ello",
comment: "discover ello button"
)
static let Email: String = NSLocalizedString("Email", comment: "email key")
static let EmailPlaceholder: String = NSLocalizedString(
"Enter email",
comment: "sign up email field"
)
static let UsernamePlaceholder: String = NSLocalizedString(
"Create username",
comment: "sign up username field"
)
static let Username: String = NSLocalizedString("Username", comment: "username key")
static let Password: String = NSLocalizedString("Password", comment: "password key")
static let PasswordPlaceholder: String = NSLocalizedString(
"Set password",
comment: "sign up password field"
)
static let LoginAfterJoinError: String = NSLocalizedString(
"Your account has been created, but there was an error logging in, please try again",
comment: "After successfully joining, there was an error signing in"
)
static let UsernameUnavailable: String = NSLocalizedString(
"Username already exists.\nPlease try a new one.",
comment: ""
)
static let UsernameSuggestionPrefix: String = NSLocalizedString(
"Here are some available usernames:\n",
comment: ""
)
static func Terms(textAttrs: [NSAttributedString.Key: Any]) -> NSAttributedString {
let linkAttrs = textAttrs + [
.underlineStyle: NSUnderlineStyle.single.rawValue,
]
let format = NSLocalizedString(
"I have read and accept Ello's {Terms} and {Privacy Policy}.",
comment: ""
)
let termsTitle = NSLocalizedString("Terms", comment: "")
let privacyTitle = NSLocalizedString("Privacy Policy", comment: "")
let replace: [String: NSAttributedString] = [
"Terms": NSAttributedString(
string: termsTitle,
attributes: linkAttrs + [
ElloAttributedText.Link: "url",
ElloAttributedText.Object: (
termsTitle, URL(string: "\(ElloURI.baseURL)/wtf/policies/terms/")
),
]
),
"Privacy Policy": NSAttributedString(
string: privacyTitle,
attributes: linkAttrs + [
ElloAttributedText.Link: "url",
ElloAttributedText.Object: (
privacyTitle, URL(string: "\(ElloURI.baseURL)/wtf/policies/privacy/")
),
]
),
]
let attributedBuffer = NSMutableAttributedString()
var buffer = ""
var key = ""
var inReplacement = false
for c in format {
if !inReplacement, c == "{" {
key = ""
inReplacement = true
}
else if inReplacement, key.isEmpty, c == "{" {
buffer += "{"
inReplacement = false
}
else if inReplacement, c == "}" {
if let replacement = replace[key] {
attributedBuffer.append(replacement)
}
inReplacement = false
}
else if inReplacement {
if !buffer.isEmpty {
attributedBuffer.append(
NSAttributedString(
string: buffer,
attributes: textAttrs
)
)
buffer = ""
}
key += "\(c)"
}
else {
buffer += "\(c)"
}
}
if !buffer.isEmpty {
attributedBuffer.append(
NSAttributedString(
string: buffer,
attributes: textAttrs
)
)
}
return attributedBuffer
}
}
struct Validator {
static let EmailRequired: String = NSLocalizedString("Email is required.", comment: "")
static let UsernameRequired: String = NSLocalizedString(
"Username is required.",
comment: ""
)
static let PasswordRequired: String = NSLocalizedString(
"Password is required.",
comment: ""
)
static let TermsRequired: String = NSLocalizedString(
"Accepting the Terms and Privacy Policy is required.",
comment: ""
)
static let SignInInvalid: String = NSLocalizedString(
"Invalid email or username",
comment: ""
)
static let CredentialsInvalid: String = NSLocalizedString(
"Invalid credentials",
comment: ""
)
static let EmailInvalid: String = NSLocalizedString(
"That email is invalid.",
comment: ""
)
static let UsernameInvalid: String = NSLocalizedString(
"That username is invalid.",
comment: ""
)
static let PasswordInvalid: String = NSLocalizedString(
"Password must be at least 8 characters long.",
comment: ""
)
}
struct Onboard {
static let PickCategoriesPrimary: String = NSLocalizedString(
"Pick what you’re into.",
comment: ""
)
static let PickCategoriesSecondary: String = NSLocalizedString(
"Slow down & check out some cool ass shit.",
comment: ""
)
static let CreateProfilePrimary: String = NSLocalizedString(
"Grow your creative influence.",
comment: ""
)
static let CreateProfileSecondary: String = NSLocalizedString(
"Completed profiles get way more views.",
comment: ""
)
static let InviteFriendsPrimary: String = NSLocalizedString(
"Invite some cool people.",
comment: ""
)
static let InviteFriendsSecondary: String = NSLocalizedString(
"Make Ello better.",
comment: ""
)
static let CreatorTypeHeader: String = NSLocalizedString(
"We’re doing a quick survey to find out a little more about the artistic composition of the Ello community. You can always update your selection(s) in settings. Thank you!",
comment: ""
)
static let HereAs: String = NSLocalizedString("I am here as:", comment: "")
static let Interests: String = NSLocalizedString("I make:", comment: "")
static let Artist: String = NSLocalizedString("An Artist", comment: "")
static let Fan: String = NSLocalizedString("A Fan", comment: "")
static let CreateAccount: String = NSLocalizedString("Create Account", comment: "")
static let CreateProfile: String = NSLocalizedString("Create Your Profile", comment: "")
static let InvitePeople: String = NSLocalizedString("Invite Cool People", comment: "")
static let ImDone: String = NSLocalizedString("I’m done", comment: "")
static func Pick(_ count: Int) -> String {
return String.localizedStringWithFormat("Pick %lu", count)
}
static let UploadCoverButton: String = NSLocalizedString("Upload Header", comment: "")
static let UploadCoverImagePrompt: String = NSLocalizedString(
"2560 x 1440\nAnimated Gifs work, too",
comment: ""
)
static let UploadAvatarButton: String = NSLocalizedString("Upload Avatar", comment: "")
static let UploadAvatarPrompt: String = NSLocalizedString(
"360 x 360\nAnimated Gifs work, too",
comment: ""
)
static let NamePlaceholder: String = NSLocalizedString("Name", comment: "")
static let BioPlaceholder: String = NSLocalizedString("Bio", comment: "")
static let LinksPlaceholder: String = NSLocalizedString("Links", comment: "")
static let Search: String = NSLocalizedString("Name or email", comment: "")
static let UploadFailed: String = NSLocalizedString(
"Oh no! Something went wrong.\n\nTry that again maybe?",
comment: "image upload failed during onboarding message"
)
static let RelationshipFailed: String = NSLocalizedString(
"Oh no! Something went wrong.\n\nTry that again maybe?",
comment: "relationship status update failed during onboarding message"
)
}
struct Share {
static let FailedToPost: String = NSLocalizedString(
"Uh oh, failed to post to Ello.",
comment: "Failed to post to Ello"
)
static let PleaseLogin: String = NSLocalizedString(
"Please login to the Ello app first to use this feature.",
comment: "Not logged in message."
)
}
struct App {
static let OpenInSafari: String = NSLocalizedString("Open in Safari", comment: "")
static let LoggedOut: String = NSLocalizedString(
"You have been automatically logged out",
comment: "Automatically logged out message"
)
static let LoginAndView: String = NSLocalizedString(
"Login and view",
comment: "Login and view prompt"
)
static let OldVersion: String = NSLocalizedString(
"The version of the app you’re using is too old, and is no longer compatible with our API.\n\nPlease update the app to the latest version, using the “Updates” tab in the App Store.",
comment: "App out of date message"
)
static let LoggedOutError: String = NSLocalizedString("You must be logged in", comment: "")
}
struct Error {
static let JPEGCompress: String = NSLocalizedString(
"Could not compress image as JPEG",
comment: ""
)
}
static let GenericError: String = NSLocalizedString(
"Something went wrong. Thank you for your patience with Ello!",
comment: "Generic error message"
)
static let UnknownError: String = NSLocalizedString(
"Unknown error",
comment: "Unknown error message"
)
static let EmptyStreamText: String = NSLocalizedString("Nothing To See Here", comment: "")
static let Ello: String = NSLocalizedString("Ello", comment: "")
static let OK: String = NSLocalizedString("OK", comment: "")
static let Yes: String = NSLocalizedString("Yes", comment: "")
static let No: String = NSLocalizedString("No", comment: "")
static let Nevermind: String = NSLocalizedString("Nevermind", comment: "")
static let Cancel: String = NSLocalizedString("Cancel", comment: "")
static let Submit: String = NSLocalizedString("Submit", comment: "")
static let Retry: String = NSLocalizedString("Retry", comment: "")
static let AreYouSure: String = NSLocalizedString("Are You Sure?", comment: "")
static let ThatIsOK: String = NSLocalizedString("It’s OK, I understand!", comment: "")
static let Delete: String = NSLocalizedString("Delete", comment: "")
static let Remove: String = NSLocalizedString("Remove", comment: "")
static let Next: String = NSLocalizedString("Next", comment: "")
static let Done: String = NSLocalizedString("Done", comment: "")
static let Skip: String = NSLocalizedString("Skip", comment: "")
static let SeeAll: String = NSLocalizedString("See All", comment: "")
static let Send: String = NSLocalizedString("Send", comment: "")
static let Save: String = NSLocalizedString("Save", comment: "")
static let Edit: String = NSLocalizedString("Edit", comment: "")
static let Info: String = NSLocalizedString("Info", comment: "")
static let Add: String = NSLocalizedString("Add", comment: "")
}
| mit | ec8f570ce69519b6f92598f138192725 | 45.437016 | 194 | 0.607767 | 5.510925 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/MaxProfit.swift | 1 | 781 | //
// MaxProfit.swift
// LeetCode
//
// Created by xiAo_Ju on 2020/3/23.
// Copyright © 2020 伯驹 黄. All rights reserved.
//
import Foundation
func maxProfit(_ prices: [Int]) -> Int {
if prices.isEmpty { return 0 }
var minPrice = prices[0]
var maxProfit = 0
for price in prices {
let profit = price - minPrice
if profit > maxProfit {
maxProfit = profit
}
minPrice = min(minPrice, price)
}
return maxProfit
}
func maxProfitII(_ prices: [Int]) -> Int {
guard prices.count > 1 else { return 0 }
var maxProfit = 0
for i in 1 ..< prices.count {
let profit = prices[i] - prices[i - 1]
if profit > 0 {
maxProfit += profit
}
}
return maxProfit
}
| mit | 2c96f72f9c9805d846ae94e1f1d8b5d6 | 17.428571 | 47 | 0.556848 | 3.633803 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIKitExtensions/QMUISlider.swift | 1 | 3608 | //
// QMUISlider.swift
// QMUI.swift
//
// Created by xnxin on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
/**
* 相比系统的 UISlider,支持:
* 1. 修改背后导轨的高度
* 2. 修改圆点的大小
* 3. 修改圆点的阴影样式
*/
class QMUISlider: UISlider {
/// 背后导轨的高度,默认为 0,表示使用系统默认的高度。
@IBInspectable public var trackHeight: CGFloat = 0
/// 中间圆球的大小,默认为 .zero
/// @warning 注意若设置了 thumbSize 但没设置 thumbColor,则圆点的颜色会使用 self.tintColor 的颜色(但系统 UISlider 默认的圆点颜色是白色带阴影)
@IBInspectable public var thumbSize: CGSize = .zero {
didSet {
updateThumbImage()
}
}
/// 中间圆球的颜色,默认为 nil。
/// @warning 注意请勿使用系统的 thumbTintColor,因为 thumbTintColor 和 thumbImage 是互斥的,设置一个会导致另一个被清空,从而导致样式错误。
@IBInspectable public var thumbColor: UIColor? {
didSet {
updateThumbImage()
}
}
/// 中间圆球的阴影颜色,默认为 nil
@IBInspectable public var thumbShadowColor: UIColor? {
didSet {
if let thumbView = thumbViewIfExist() {
thumbView.layer.shadowColor = thumbShadowColor?.cgColor
thumbView.layer.shadowOpacity = (thumbShadowColor != nil) ? 1 : 0
}
}
}
/// 中间圆球的阴影偏移值,默认为 .zero
@IBInspectable public var thumbShadowOffset: CGSize = .zero {
didSet {
if let thumbView = thumbViewIfExist() {
thumbView.layer.shadowOffset = thumbShadowOffset
}
}
}
/// 中间圆球的阴影扩散度,默认为 0
@IBInspectable public var thumbShadowRadius: CGFloat = 0 {
didSet {
if let thumbView = thumbViewIfExist() {
thumbView.layer.shadowRadius = thumbShadowRadius
}
}
}
private func updateThumbImage() {
if thumbSize.isEmpty { return }
if let thumbColor = self.thumbColor ?? tintColor {
let thumbImage = UIImage.qmui_image(shape: .oval, size: thumbSize, tintColor: thumbColor)
setThumbImage(thumbImage, for: .normal)
setThumbImage(thumbImage, for: .highlighted)
}
}
private func thumbViewIfExist() -> UIView? {
// thumbView 并非在一开始就存在,而是在某个时机才生成的,所以可能返回 nil
if let thumbView = value(forKey: "thumbView") {
return thumbView as? UIView
} else {
return nil
}
}
// MARK: Override
override func trackRect(forBounds bounds: CGRect) -> CGRect {
var result = super.trackRect(forBounds: bounds)
if trackHeight == 0 {
return result
}
result = result.setHeight(trackHeight)
result = result.setY(bounds.height.center(result.height))
return result
}
override func didAddSubview(_ subview: UIView) {
super.didAddSubview(subview)
guard subview == thumbViewIfExist() else {
return
}
let thumbView = subview
thumbView.layer.shadowColor = thumbShadowColor?.cgColor
thumbView.layer.shadowOpacity = (thumbShadowColor != nil) ? 1 : 0
thumbView.layer.shadowOffset = thumbShadowOffset
thumbView.layer.shadowRadius = thumbShadowRadius
}
}
| mit | 189457acddd1473e4945a9a77b4f9675 | 28.027778 | 106 | 0.60638 | 4.141347 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0363-swift-scopeinfo-addtoscope.swift | 13 | 741 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
}
class i {
func d((h: (Any, AnyObject)) {
}
}
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
}
class i: d{ class func f {}
enum A : String {
}
struct d<f : e, g: e where g.h == f.h> {
}
}
extension d) {
}
func a() {
c a(b: Int = 0) {
}
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
o.m == o> (m: o) {
}
st.C == E> {s func c() { }
}
}
st> {
}
func prefix(with: Strin-> <r>(() -> r) -> h {
n { u o "\(v): \(u()" }
| apache-2.0 | da4c632824f33b0784885011ba5a7703 | 14.122449 | 87 | 0.518219 | 2.315625 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.