repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/ScrollableEducationPanelViewController.swift | mit | 1 | import UIKit
typealias ScrollableEducationPanelButtonTapHandler = ((_ sender: Any) -> ())
typealias ScrollableEducationPanelDismissHandler = (() -> ())
/*
Education panels typically have the following items, from top to bottom:
== Close button ==
== Image ==
== Heading text ==
== Subheading text ==
== Primary button ==
== Secondary button ==
== Footer text ==
This class pairs with a xib with roughly the following structure:
view
scroll view
stack view
close button
image view
heading label
subheading label
primary button
secondary button
footer label
- Stackview management of its subviews makes it easy to collapse space for unneeded items.
- Scrollview containment makes long translations or landscape on small phones scrollable when needed.
*/
class ScrollableEducationPanelViewController: UIViewController, Themeable {
@IBOutlet fileprivate weak var closeButton: UIButton!
@IBOutlet fileprivate weak var imageView: UIImageView!
@IBOutlet fileprivate weak var headingLabel: UILabel!
@IBOutlet fileprivate weak var subheadingLabel: UILabel!
@IBOutlet fileprivate weak var primaryButton: AutoLayoutSafeMultiLineButton!
@IBOutlet fileprivate weak var secondaryButton: AutoLayoutSafeMultiLineButton!
@IBOutlet fileprivate weak var footerLabel: UILabel!
@IBOutlet fileprivate weak var scrollViewContainer: UIView!
@IBOutlet fileprivate weak var stackView: UIStackView!
@IBOutlet fileprivate weak var roundedCornerContainer: UIView!
@IBOutlet fileprivate weak var effectsView: UIVisualEffectView!
fileprivate var primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?
fileprivate var secondaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?
fileprivate var dismissHandler: ScrollableEducationPanelDismissHandler?
fileprivate var showCloseButton = true
private var discardDismissHandlerOnPrimaryButtonTap = false
private var primaryButtonTapped = false
private var theme: Theme = Theme.standard
var image:UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
view.setNeedsLayout() // Ensures stackview will collapse if image is set to nil.
}
}
var heading:String? {
get {
return headingLabel.text
}
set {
headingLabel.text = newValue
view.setNeedsLayout()
}
}
var subheading:String? {
get {
return subheadingLabel.text
}
set {
subheadingLabel.text = newValue
view.setNeedsLayout()
}
}
var primaryButtonTitle:String? {
get {
return primaryButton.title(for: .normal)
}
set {
primaryButton.setTitle(newValue, for: .normal)
view.setNeedsLayout()
}
}
var secondaryButtonTitle:String? {
get {
return secondaryButton.title(for: .normal)
}
set {
secondaryButton.setTitle(newValue, for: .normal)
view.setNeedsLayout()
}
}
var footer:String? {
get {
return footerLabel.text
}
set {
footerLabel.text = newValue
view.setNeedsLayout()
}
}
init(showCloseButton: Bool, primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?, secondaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler?, dismissHandler: ScrollableEducationPanelDismissHandler?, discardDismissHandlerOnPrimaryButtonTap: Bool = false, theme: Theme) {
super.init(nibName: "ScrollableEducationPanelView", bundle: nil)
self.modalPresentationStyle = .overFullScreen
self.modalTransitionStyle = .crossDissolve
self.theme = theme
self.showCloseButton = showCloseButton
self.primaryButtonTapHandler = primaryButtonTapHandler
self.secondaryButtonTapHandler = secondaryButtonTapHandler
self.dismissHandler = dismissHandler
self.discardDismissHandlerOnPrimaryButtonTap = discardDismissHandlerOnPrimaryButtonTap
}
required public init?(coder aDecoder: NSCoder) {
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
assert(stackView.wmf_firstArrangedSubviewWithRequiredNonZeroHeightConstraint() == nil, stackView.wmf_anArrangedSubviewHasRequiredNonZeroHeightConstraintAssertString())
reset()
primaryButton.titleLabel?.textAlignment = .center
secondaryButton.titleLabel?.textAlignment = .center
closeButton.isHidden = !showCloseButton
[self.view, self.roundedCornerContainer].forEach {view in
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.overlayTapped(_:))))
}
closeButton.setImage(UIImage(named:"places-auth-close")?.withRenderingMode(.alwaysTemplate), for: .normal)
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
apply(theme: theme)
}
@IBAction func overlayTapped(_ sender: UITapGestureRecognizer) {
if (showCloseButton && sender.view == view) {
dismiss(animated: true, completion: nil)
}
}
// Clear out xib defaults. Needed because we check these for nil to conditionally collapse stackview subviews.
fileprivate func reset() {
imageView.image = nil
headingLabel.text = nil
subheadingLabel.text = nil
primaryButton.setTitle(nil, for: .normal)
secondaryButton.setTitle(nil, for: .normal)
footerLabel.text = nil
}
override func viewWillAppear(_ animated: Bool) {
adjustStackViewSubviewsVisibility()
super.viewWillAppear(animated)
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
adjustImageViewVisibility(for: newCollection.verticalSizeClass)
// Call to 'layoutIfNeeded' is required to ensure changes made in 'adjustImageViewVisibility' are
// reflected correctly on rotation.
view.layoutIfNeeded()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
secondaryButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
}
fileprivate func adjustImageViewVisibility(for verticalSizeClass: UIUserInterfaceSizeClass) {
imageView.isHidden = (imageView.image == nil || verticalSizeClass == .compact)
}
fileprivate func adjustStackViewSubviewsVisibility() {
// Collapse stack view cell for image if no image or compact vertical size class.
adjustImageViewVisibility(for: traitCollection.verticalSizeClass)
// Collapse stack view cells for labels/buttons if no text.
headingLabel.isHidden = !headingLabel.wmf_hasAnyNonWhitespaceText
subheadingLabel.isHidden = !subheadingLabel.wmf_hasAnyNonWhitespaceText
footerLabel.isHidden = !footerLabel.wmf_hasAnyNonWhitespaceText
primaryButton.isHidden = !primaryButton.wmf_hasAnyNonWhitespaceText
secondaryButton.isHidden = !secondaryButton.wmf_hasAnyNonWhitespaceText
}
@IBAction fileprivate func close(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction fileprivate func primaryButtonTapped(_ sender: Any) {
guard let primaryButtonTapHandler = primaryButtonTapHandler else {
return
}
primaryButtonTapped = true
primaryButtonTapHandler(sender)
}
@IBAction fileprivate func secondaryButtonTapped(_ sender: Any) {
guard let secondaryButtonTapHandler = secondaryButtonTapHandler else {
return
}
secondaryButtonTapHandler(sender)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard let dismissHandler = dismissHandler else {
return
}
guard !(discardDismissHandlerOnPrimaryButtonTap && primaryButtonTapped) else {
return
}
dismissHandler()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
primaryButtonTapped = false
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
headingLabel?.textColor = theme.colors.primaryText
subheadingLabel?.textColor = theme.colors.primaryText
footerLabel?.textColor = theme.colors.primaryText
closeButton.tintColor = theme.colors.primaryText
primaryButton?.tintColor = theme.colors.link
secondaryButton?.tintColor = theme.colors.link
primaryButton?.layer.borderColor = theme.colors.link.cgColor
effectsView.effect = UIBlurEffect(style: theme.colors.blurEffectStyle)
effectsView.backgroundColor = theme.colors.blurEffectBackground
}
}
| 851b209fb4fa639074f46bb2a6630179 | 37.084677 | 297 | 0.68036 | false | false | false | false |
ilyahal/VKMusic | refs/heads/master | Pods/SwiftyVK/Source/API/Account.swift | apache-2.0 | 2 | extension _VKAPI {
///Methods for working with User Account. More - https://vk.com/dev/account
public struct Account {
///Returns non-null values of user counters. More - https://vk.com/dev/account.getCounters
public static func getCounters(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getCounters", parameters: parameters)
}
///Sets an application screen name (up to 17 characters), that is shown to the user in the left menu. More - https://vk.com/dev/account.setNameInMenu
public static func setNameInMenu(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setNameInMenu", parameters: parameters)
}
///Marks the current user as online for 15 minutes. More - https://vk.com/dev/account.setOnline
public static func setOnline(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setOnline", parameters: parameters)
}
///Marks a current user as Offline. More - https://vk.com/dev/account.setOffline
public static func setOffline(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setOffline", parameters: parameters)
}
///Allows to search the VK users using phone nubmers, e-mail addresses and user IDs on other services. More - https://vk.com/dev/account.lookupContacts
public static func lookupContacts(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.lookupContacts", parameters: parameters)
}
///Subscribes an iOS/Android-based device to receive push notifications. More - https://vk.com/dev/account.registerDevice
public static func registerDevice(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.registerDevice", parameters: parameters)
}
///Unsubscribes a device from push notifications. More - https://vk.com/dev/account.unregisterDevice
public static func unregisterDevice(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.unregisterDevice", parameters: parameters)
}
///Mutes in parameters of sent push notifications for the set period of time. More - https://vk.com/dev/account.setSilenceMode
public static func setSilenceMode(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setSilenceMode", parameters: parameters)
}
///Gets settings of push notifications. More - https://vk.com/dev/account.getPushSettings
public static func getPushSettings(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getPushSettings", parameters: parameters)
}
///Sets settings of push notifications. More - https://vk.com/dev/account.getPushSettings
public static func setPushSettings(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setPushSettings", parameters: parameters)
}
///Gets settings of the current user in this application. More - https://vk.com/dev/account.getAppPermissions
public static func getAppPermissions(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getAppPermissions", parameters: parameters)
}
///Returns a list of active ads (offers) which executed by the user will bring him/her respective number of votes to his balance in the application. More - https://vk.com/dev/account.getActiveOffers
public static func getActiveOffers(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getActiveOffers", parameters: parameters)
}
///Adds user to the banlist. More - https://vk.com/dev/account.banUser
public static func banUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.banUser", parameters: parameters)
}
///Deletes user from the banlist. More - https://vk.com/dev/account.unbanUser
public static func unbanUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.unbanUser", parameters: parameters)
}
///Returns a user's blacklist, находящихся в черном списке. More - https://vk.com/dev/account.getBanned
public static func getBanned(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getBanned", parameters: parameters)
}
///Returns current account info. More - https://vk.com/dev/account.getInfo
public static func getInfo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getInfo", parameters: parameters)
}
///Allows to edit the current account info. More - https://vk.com/dev/account.setInfo
public static func setInfo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.setInfo", parameters: parameters)
}
///Changes a user password after access is successfully restored with the auth.restore method. More - https://vk.com/dev/account.changePassword
public static func changePassword(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.changePassword", parameters: parameters)
}
///Returns the current account info. More - https://vk.com/dev/account.getProfileInfo
public static func getProfileInfo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.getProfileInfo", parameters: parameters)
}
///Edits current profile info. More - https://vk.com/dev/account.saveProfileInfo
public static func saveProfileInfo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "account.saveProfileInfo", parameters: parameters)
}
}
}
| f31775d38c5a94ac6883d01252078c87 | 40.606897 | 202 | 0.666335 | false | false | false | false |
mactive/rw-courses-note | refs/heads/master | advanced-swift-types-and-operations/TypesAndOps.playground/Pages/invalid-state-challenge.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
import struct CoreGraphics.CGFloat
import struct CoreGraphics.CGPoint
import struct CoreGraphics.CGSize
import struct CoreGraphics.CGRect
struct CGAngle {
var radians: CGFloat
}
extension CGAngle {
@inlinable init(degrees: CGFloat) {
radians = degrees / 180.0 * CGFloat.pi
}
@inlinable var degrees: CGFloat {
get {
return radians / CGFloat.pi * 180.0
}
set {
radians = newValue / 180.0
}
}
}
extension CGAngle: CustomStringConvertible {
var description: String {
return String(format: "%0.2f.C", degrees)
}
}
let angle = CGAngle(radians: .pi)
let angle2 = CGAngle(degrees: 90)
//: enum 写法
// 这样不同的形状不同的入参 就比各种init方法更好
enum ShapeKind {
case circle(center: CGPoint, radius: CGFloat)
case square(origin: CGPoint, size: CGFloat)
case rotatedSquare(origin: CGPoint, size: CGFloat, angle: CGAngle)
case rect(CGRect)
case rotatedRect(CGRect, CGAngle)
case ellipse(CGRect)
case rotatedEllipse(CGRect, CGAngle)
}
let circleItem = ShapeKind.circle(center: CGPoint.zero, radius: 10)
let rotatedSquare = ShapeKind.rotatedSquare(origin: .zero,
size: 19.21,
angle: CGAngle(degrees: 90))
//: 传统写法
// struct
struct Shape {
enum `Type` {
case circle
case square
case rotatedSquare
case rect
case rotatedRect
case ellipse
case rotetedEllipse
}
var shareType: Type
var rect: CGRect
var angle: CGFloat
}
let center = CGPoint.zero
let radius: CGFloat = 10
let circle = Shape(shareType: .circle,
rect: CGRect(x: center.x - radius,
y: center.y - radius,
width: radius * 2,
height: radius * 2),
angle: 0)
circle.angle
//: [Next](@next)
| eabfa26ec7e7805ccbc0dd8a3c6a492c | 22.857143 | 72 | 0.584331 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Money/Sources/MoneyKit/CurrencyRepresentation/Currency/LocalizationConstants+Fiat.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import Localization
extension LocalizationConstants {
public enum Fiat {
static let usd = NSLocalizedString(
"US Dollar",
comment: "Name of the USD (US Dollar) fiat currency."
)
static let gbp = NSLocalizedString(
"British Pound",
comment: "Name of the GBP (British Pound) fiat currency."
)
static let eur = NSLocalizedString(
"Euro",
comment: "Name of the EUR (Euro) fiat currency."
)
static let ars = NSLocalizedString(
"Argentinian Peso",
comment: "Name of the ARS (Argentinian Peso) fiat currency."
)
static let brl = NSLocalizedString(
"Brazilian Real",
comment: "Name of the BRL (Brazilian Real) fiat currency."
)
}
}
| be1350108c53f914c66ce3f916aac3fe | 29.533333 | 72 | 0.578603 | false | false | false | false |
DavadDi/flatbuffers | refs/heads/master | swift/Sources/FlatBuffers/Table.swift | apache-2.0 | 1 | /*
* 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
public struct Table {
public private(set) var bb: ByteBuffer
public private(set) var postion: Int32
public init(bb: ByteBuffer, position: Int32 = 0) {
guard isLitteEndian else {
fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
}
self.bb = bb
postion = position
}
public func offset(_ o: Int32) -> Int32 {
let vtable = postion - bb.read(def: Int32.self, position: Int(postion))
return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(
def: Int16.self,
position: Int(vtable + o))) : 0
}
public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) }
/// String reads from the buffer with respect to position of the current table.
/// - Parameter offset: Offset of the string
public func string(at offset: Int32) -> String? {
directString(at: offset + postion)
}
/// Direct string reads from the buffer disregarding the position of the table.
/// It would be preferable to use string unless the current position of the table is not needed
/// - Parameter offset: Offset of the string
public func directString(at offset: Int32) -> String? {
var offset = offset
offset += bb.read(def: Int32.self, position: Int(offset))
let count = bb.read(def: Int32.self, position: Int(offset))
let position = offset + Int32(MemoryLayout<Int32>.size)
return bb.readString(at: position, count: count)
}
/// Reads from the buffer with respect to the position in the table.
/// - Parameters:
/// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
public func readBuffer<T>(of type: T.Type, at o: Int32) -> T {
directRead(of: T.self, offset: o + postion)
}
/// Reads from the buffer disregarding the position of the table.
/// It would be used when reading from an
/// ```
/// let offset = __t.offset(10)
/// //Only used when the we already know what is the
/// // position in the table since __t.vector(at:)
/// // returns the index with respect to the position
/// __t.directRead(of: Byte.self,
/// offset: __t.vector(at: offset) + index * 1)
/// ```
/// - Parameters:
/// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
public func directRead<T>(of type: T.Type, offset o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o))
return r
}
public func union<T: FlatBufferObject>(_ o: Int32) -> T {
let o = o + postion
return directUnion(o)
}
public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T {
T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
}
public func getVector<T>(at off: Int32) -> [T]? {
let o = offset(off)
guard o != 0 else { return nil }
return bb.readSlice(index: vector(at: o), count: vector(count: o))
}
/// Vector count gets the count of Elements within the array
/// - Parameter o: start offset of the vector
/// - returns: Count of elements
public func vector(count o: Int32) -> Int32 {
var o = o
o += postion
o += bb.read(def: Int32.self, position: Int(o))
return bb.read(def: Int32.self, position: Int(o))
}
/// Vector start index in the buffer
/// - Parameter o:start offset of the vector
/// - returns: the start index of the vector
public func vector(at o: Int32) -> Int32 {
var o = o
o += postion
return o + bb.read(def: Int32.self, position: Int(o)) + 4
}
}
extension Table {
static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read(
def: Int32.self,
position: Int(o)) }
static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 {
let vTable = Int32(fbb.capacity) - o
return vTable + Int32(fbb.read(
def: Int16.self,
position: Int(vTable + vOffset - fbb.read(def: Int32.self, position: Int(vTable)))))
}
static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = fbb.read(def: Int32.self, position: Int(_off2))
let startPos1 = _off1 + memorySize
let startPos2 = _off2 + memorySize
let minValue = min(len1, len2)
for i in 0...minValue {
let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1))
let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2))
if b1 != b2 {
return Int32(b2 - b1)
}
}
return len1 - len2
}
static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = Int32(key.count)
let startPos1 = _off1 + memorySize
let minValue = min(len1, len2)
for i in 0..<minValue {
let b = fbb.read(def: Int8.self, position: Int(i + startPos1))
let byte = key[Int(i)]
if b != byte {
return Int32(b - Int8(byte))
}
}
return len1 - len2
}
}
| 29d55a7293e8b03863d80ad0e5fba98b | 35.180723 | 97 | 0.641525 | false | false | false | false |
koba-uy/chivia-app-ios | refs/heads/master | src/Pods/MapboxNavigation/MapboxNavigation/RouteTableViewController.swift | lgpl-3.0 | 1 | import UIKit
import Pulley
import MapboxCoreNavigation
import MapboxDirections
class RouteTableViewController: UIViewController {
let RouteTableViewCellIdentifier = "RouteTableViewCellId"
let dateFormatter = DateFormatter()
let dateComponentsFormatter = DateComponentsFormatter()
let distanceFormatter = DistanceFormatter(approximate: true)
let routeStepFormatter = RouteStepFormatter()
weak var routeController: RouteController!
@IBOutlet var headerView: RouteTableViewHeaderView!
@IBOutlet weak var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
distanceFormatter.numberFormatter.locale = .nationalizedCurrent
dateFormatter.timeStyle = .short
dateComponentsFormatter.allowedUnits = [.hour, .minute]
dateComponentsFormatter.unitsStyle = .abbreviated
tableView.tableHeaderView = headerView
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 80
}
func updateETA(routeProgress: RouteProgress) {
let arrivalDate = NSCalendar.current.date(byAdding: .second, value: Int(routeProgress.durationRemaining), to: Date())
headerView.arrivalTimeLabel.text = dateFormatter.string(from: arrivalDate!)
if routeProgress.durationRemaining < 5 {
headerView.distanceRemainingLabel.text = nil
} else {
headerView.distanceRemainingLabel.text = distanceFormatter.string(from: routeProgress.distanceRemaining)
}
dateComponentsFormatter.unitsStyle = routeProgress.durationRemaining < 3600 ? .short : .abbreviated
if routeProgress.durationRemaining < 60 {
headerView.timeRemainingLabel.text = String.localizedStringWithFormat(NSLocalizedString("LESS_THAN", bundle: .mapboxNavigation, value: "<%@", comment: "Format string for a short distance or time less than a minimum threshold; 1 = duration remaining"), dateComponentsFormatter.string(from: 61)!)
} else {
headerView.timeRemainingLabel.text = dateComponentsFormatter.string(from: routeProgress.durationRemaining)
}
let coordinatesLeftOnStepCount = Int(floor((Double(routeProgress.currentLegProgress.currentStepProgress.step.coordinateCount)) * routeProgress.currentLegProgress.currentStepProgress.fractionTraveled))
guard coordinatesLeftOnStepCount >= 0 else {
headerView.timeRemainingLabel.textColor = TimeRemainingLabel.appearance(for: traitCollection).textColor
return
}
guard routeProgress.legIndex < routeProgress.congestionTravelTimesSegmentsByStep.count,
routeProgress.currentLegProgress.stepIndex < routeProgress.congestionTravelTimesSegmentsByStep[routeProgress.legIndex].count else { return }
let congestionTimesForStep = routeProgress.congestionTravelTimesSegmentsByStep[routeProgress.legIndex][routeProgress.currentLegProgress.stepIndex]
guard coordinatesLeftOnStepCount <= congestionTimesForStep.count else { return }
let remainingCongestionTimesForStep = congestionTimesForStep.suffix(from: coordinatesLeftOnStepCount)
let remainingCongestionTimesForRoute = routeProgress.congestionTimesPerStep[routeProgress.legIndex].suffix(from: routeProgress.currentLegProgress.stepIndex + 1)
var remainingStepCongestionTotals: [CongestionLevel: TimeInterval] = [:]
for stepValues in remainingCongestionTimesForRoute {
for (key, value) in stepValues {
remainingStepCongestionTotals[key] = (remainingStepCongestionTotals[key] ?? 0) + value
}
}
for (segmentCongestion, segmentTime) in remainingCongestionTimesForStep {
remainingStepCongestionTotals[segmentCongestion] = (remainingStepCongestionTotals[segmentCongestion] ?? 0) + segmentTime
}
// Update text color on time remaining based on congestion level
if routeProgress.durationRemaining < 60 {
headerView.congestionLevel = .unknown
} else {
if let max = remainingStepCongestionTotals.max(by: { a, b in a.value < b.value }) {
headerView.congestionLevel = max.key
} else {
headerView.congestionLevel = .unknown
}
}
}
func notifyAlertLevelDidChange() {
if let visibleIndexPaths = tableView.indexPathsForVisibleRows {
tableView.reloadRows(at: visibleIndexPaths, with: .fade)
}
}
}
extension RouteTableViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return routeController.routeProgress.route.legs.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Don't display section header if there is only one step
guard routeController.routeProgress.route.legs.count > 1 else {
return nil
}
let leg = routeController.routeProgress.route.legs[section]
let sourceName = leg.source.name
let destinationName = leg.destination.name
let majorWays = leg.name.components(separatedBy: ", ")
if let destinationName = destinationName?.nonEmptyString, majorWays.count > 1 {
let summary = String.localizedStringWithFormat(NSLocalizedString("LEG_MAJOR_WAYS_FORMAT", bundle: .mapboxNavigation, value: "%@ and %@", comment: "Format for displaying the first two major ways"), majorWays[0], majorWays[1])
return String.localizedStringWithFormat(NSLocalizedString("WAYPOINT_DESTINATION_VIA_WAYPOINTS_FORMAT", bundle: .mapboxNavigation, value: "%@, via %@", comment: "Format for displaying destination and intermediate waypoints; 1 = source ; 2 = destinations"), destinationName, summary)
} else if let sourceName = sourceName?.nonEmptyString, let destinationName = destinationName?.nonEmptyString {
return String.localizedStringWithFormat(NSLocalizedString("WAYPOINT_SOURCE_DESTINATION_FORMAT", bundle: .mapboxNavigation, value: "%@ and %@", comment: "Format for displaying start and endpoint for leg; 1 = source ; 2 = destination"), sourceName, destinationName)
} else {
return leg.name
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routeController.routeProgress.route.legs[section].steps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: RouteTableViewCellIdentifier, for: indexPath) as! RouteTableViewCell
let legs = routeController.routeProgress.route.legs
cell.step = legs[indexPath.section].steps[indexPath.row]
if indexPath.section < routeController.routeProgress.legIndex || (indexPath.section == routeController.routeProgress.legIndex && indexPath.row <= routeController.routeProgress.currentLegProgress.stepIndex) {
cell.contentView.alpha = 0.4
}
return cell
}
}
extension RouteTableViewController: PulleyDrawerViewControllerDelegate {
/**
Returns an array of `PulleyPosition`. The array contains the view positions the bottom bar supports.
*/
public func supportedDrawerPositions() -> [PulleyPosition] {
return [
.collapsed,
.partiallyRevealed,
.open,
.closed
]
}
func collapsedDrawerHeight() -> CGFloat {
return headerView.intrinsicContentSize.height
}
func partialRevealDrawerHeight() -> CGFloat {
return UIScreen.main.bounds.height * 0.60
}
}
| 6a6f35518b84f6e2f07c3b25b58b2e16 | 48.04321 | 306 | 0.701196 | false | false | false | false |
iot-spotted/spotted | refs/heads/master | AppMessage/AppMessage/Controlers/MainViewController.swift | bsd-3-clause | 1 | //
// MainViewController.swift
// AppMessage
//
// Created by Jake Weiss on 2/21/17.
// Copyright © 2017 mirabeau. All rights reserved.
//
import UIKit
import EVCloudKitDao
import CloudKit
import Async
class MainViewController: UIViewController {
@IBOutlet var scrollView: UIScrollView!
var cameraViewController: CameraViewController!
var chatViewController: ChatViewController!
var profileViewController: ProfileViewController!
var gameController: GameController!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"loadChat"),
object:nil, queue:nil,
using:loadChat)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"loadCamera"),
object:nil, queue:nil,
using:loadCamera)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"loadProfile"),
object:nil, queue:nil,
using:loadProfile)
self.profileViewController = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "profileViewController") as! ProfileViewController
self.cameraViewController = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "cameraViewController") as! CameraViewController
self.chatViewController = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(withIdentifier: "chatViewController") as! ChatViewController
self.createGameUserIfNotExists()
self.gameController = GameController(parentView: self)
self.cameraViewController.gameController = self.gameController
self.chatViewController.gameController = self.gameController
self.profileViewController.gameController = self.gameController
self.chatViewController.setContact("", fakeGroupChatName: "lol")
self.addChildViewController(self.cameraViewController)
self.scrollView.addSubview(self.cameraViewController.view)
self.cameraViewController.didMove(toParentViewController: self)
self.addChildViewController(self.profileViewController)
self.scrollView!.addSubview(self.profileViewController.view)
self.profileViewController.didMove(toParentViewController: self)
self.addChildViewController(self.chatViewController)
self.scrollView!.addSubview(self.chatViewController.view)
self.chatViewController.didMove(toParentViewController: self)
var profileFrame :CGRect = self.profileViewController.view.frame
profileFrame.origin.x = profileFrame.width
self.cameraViewController.view.frame = profileFrame
var cameraFrame :CGRect = self.cameraViewController.view.frame
cameraFrame.origin.x = 2*cameraFrame.width;
self.chatViewController.view.frame = cameraFrame;
let scrollWidth: CGFloat = 3 * self.view.frame.width
let scrollHeight: CGFloat = self.view.frame.height
self.scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight);
self.scrollView.keyboardDismissMode = .onDrag
self.scrollView.contentOffset = CGPoint(x:self.view.frame.width,y:0)
self.registerForMessageNotifications()
self.registerForVoteNotifications()
self.registerForItNotifications()
}
func createGameUserIfNotExists() {
let recordIdMe = getMyRecordID()
EVCloudData.publicDB.dao.query(GameUser(), predicate: NSPredicate(format: "User_ID == '\(recordIdMe)'"),
completionHandler: { results, stats in
EVLog("query : result count = \(results.count)")
if (results.count == 0) {
print("creating user...")
let user = GameUser()
user.User_ID = recordIdMe
user.Name = getMyName()
EVCloudData.publicDB.saveItem(user, completionHandler: {user in
print("Created user")
print(user)
}, errorHandler: {error in
Helper.showError("Could not create group! \(error.localizedDescription)")
})
}
return true
}, errorHandler: { error in
EVLog("<--- ERROR query User")
})
EVCloudData.publicDB.dao.query(GroupState(), predicate: NSPredicate(format: "Group_ID == '\(GLOBAL_GROUP_ID)'"),
completionHandler: { results, stats in
EVLog("query : result count = \(results.count)")
if (results.count == 0) {
print("group does not exist")
let group = GroupState()
group.Group_ID = GLOBAL_GROUP_ID
group.It_User_ID = recordIdMe
group.It_User_Name = getMyName()
EVCloudData.publicDB.saveItem(group, completionHandler: {group in
print("Created group")
print(group)
}, errorHandler: { error in
Helper.showError("Could not create group! \(error.localizedDescription)")
})
} else {
print("group already exists");
}
return true
}
);
}
func registerForMessageNotifications(_ retryCount: Double = 1) {
EVCloudData.publicDB.connect(Message(), predicate: NSPredicate(format: "To_ID = %@", GLOBAL_GROUP_ID), filterId: "Message_ToGroup", configureNotificationInfo: { notificationInfo in
notificationInfo.alertLocalizationKey = "%1$@ %2$@ : %3$@"
notificationInfo.alertLocalizationArgs = ["FromFirstName", "FromLastName", "Text"]
}, completionHandler: { results, status in
EVLog("Message to group results = \(results.count)")
return status == CompletionStatus.partialResult && results.count < 200 // Continue reading if we have less than 200 records and if there are more.
}, insertedHandler: { item in
EVLog("Message to group inserted \(item)")
//self.startChat(item.From_ID, firstName: item.ToFirstName, lastName: item.ToLastName)
//self.createGameUserIfNotExists()
//self.scrollView!.contentOffset = CGPoint(x:self.view.frame.width*2,y:0)
}, updatedHandler: { item, dataIndex in
EVLog("Message to group updated \(item)")
}, deletedHandler: { recordId, dataIndex in
EVLog("Message to group deleted : \(recordId)")
}, errorHandler: { error in
switch EVCloudKitDao.handleCloudKitErrorAs(error, retryAttempt: retryCount) {
case .retry(let timeToWait):
Helper.showError("Could not load messages: \(error.localizedDescription)")
Async.background(after: timeToWait) {
self.registerForMessageNotifications(retryCount + 1)
}
case .fail:
Helper.showError("Could not load messages: \(error.localizedDescription)")
default: // For here there is no need to handle the .Success and .RecoverableError
break
}
})
}
func registerForVoteNotifications(_ retryCount: Double = 1) {
EVCloudData.publicDB.connect(Vote(), predicate: NSPredicate(format: "Group_ID = %@ AND Status == 'I'", GLOBAL_GROUP_ID), filterId: "Vote_ToGroup", configureNotificationInfo: { notificationInfo in
notificationInfo.alertLocalizationKey = "Verify %1$@'s photo of %2$@!"
notificationInfo.alertLocalizationArgs = ["Sender_Name", "It_User_Name"]
}, completionHandler: { results, status in
EVLog("Vote to group results = \(results.count)")
return status == CompletionStatus.partialResult && results.count < 200 // Continue reading if we have less than 200 records and if there are more.
}, insertedHandler: { item in
EVLog("Vote to group inserted \(item)")
}, updatedHandler: { item, dataIndex in
EVLog("Vote to group updated \(item)")
}, deletedHandler: { recordId, dataIndex in
EVLog("Vote to group deleted : \(recordId)")
}, errorHandler: { error in
switch EVCloudKitDao.handleCloudKitErrorAs(error, retryAttempt: retryCount) {
case .retry(let timeToWait):
Helper.showError("Could not load vote: \(error.localizedDescription)")
Async.background(after: timeToWait) {
self.registerForVoteNotifications(retryCount + 1)
}
case .fail:
Helper.showError("Could not load vote: \(error.localizedDescription)")
default: // For here there is no need to handle the .Success and .RecoverableError
break
}
})
}
func registerForItNotifications(_ retryCount: Double = 1) {
EVCloudData.publicDB.connect(GroupState(), predicate: NSPredicate(format: "Group_ID = %@", GLOBAL_GROUP_ID), filterId: "It_Changed", configureNotificationInfo: { notificationInfo in
notificationInfo.alertLocalizationKey = "%1$@ is now It!"
notificationInfo.alertLocalizationArgs = ["It_User_Name"]
}, completionHandler: { results, status in
EVLog("It results = \(results.count)")
return status == CompletionStatus.partialResult && results.count < 200 // Continue reading if we have less than 200 records and if there are more.
}, insertedHandler: { item in
EVLog("It inserted \(item)")
}, updatedHandler: { item, dataIndex in
EVLog("It updated \(item)")
}, deletedHandler: { recordId, dataIndex in
EVLog("It deleted : \(recordId)")
}, errorHandler: { error in
switch EVCloudKitDao.handleCloudKitErrorAs(error, retryAttempt: retryCount) {
case .retry(let timeToWait):
Helper.showError("Could not load it change: \(error.localizedDescription)")
Async.background(after: timeToWait) {
self.registerForItNotifications(retryCount + 1)
}
case .fail:
Helper.showError("Could not load it change: \(error.localizedDescription)")
default: // For here there is no need to handle the .Success and .RecoverableError
break
}
})
}
override func viewDidLayoutSubviews() {
profileViewController.view.frame = self.view.frame
}
func loadChat(notification: Notification) {
self.scrollView.scrollRectToVisible(CGRect(x:self.chatViewController.view.frame.origin.x,y:0,width:self.chatViewController.view.frame.width,height:self.chatViewController.view.frame.height), animated: true)
}
func loadCamera(notification: Notification) {
self.scrollView.scrollRectToVisible(CGRect(x:self.cameraViewController.view.frame.origin.x,y:0,width:self.cameraViewController.view.frame.origin.x,height:self.cameraViewController.view.frame.height), animated: true)
}
func loadProfile(notification: Notification) {
self.scrollView.scrollRectToVisible(CGRect(x:0,y:0,width:self.profileViewController.view.frame.width,height:self.profileViewController.view.frame.height), animated: true)
}
}
| 6eebe806e336e1a59b37f50d83f8e22c | 48.606695 | 223 | 0.622048 | false | false | false | false |
flexih/CorePlayer.Swift | refs/heads/master | OSXDemo/OSXDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// OSXDemo
//
// Created by flexih on 12/8/15.
// Copyright © 2015 flexih. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
let corePlayer = CorePlayer()
override func viewDidLoad() {
super.viewDidLoad()
corePlayer.moduleManager().initModules([EventModule.self])
corePlayer.view().translatesAutoresizingMaskIntoConstraints = false
view.addSubview(corePlayer.view())
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0).active = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0).active = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0).active = true
NSLayoutConstraint.init(item: corePlayer.view(), attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0).active = true
corePlayer.playURL(NSURL(string: "http://devimages.apple.com/samplecode/adDemo/ad.m3u8")!)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
deinit {
corePlayer.stop()
}
}
| 7bce1ec743b9624a1e3cb860ee8186a2 | 34.658537 | 175 | 0.675103 | false | false | false | false |
vojto/NiceKit | refs/heads/master | NiceKit/SwiftHexColors.swift | mit | 1 | //
// SwiftHexColors.swift
// Median
//
// Created by Vojtech Rinik on 29/10/2016.
// Copyright © 2016 Vojtech Rinik. All rights reserved.
//
import Foundation
// SwiftHEXColors.swift
//
// Copyright (c) 2014 Doan Truong Thi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
typealias SWColor = UIColor
#else
import Cocoa
typealias SWColor = NSColor
#endif
private extension Int {
func duplicate4bits() -> Int {
return (self << 4) + self
}
}
/// An extension of UIColor (on iOS) or NSColor (on OSX) providing HEX color handling.
public extension SWColor {
/**
Create non-autoreleased color with in the given hex string. Alpha will be set as 1 by default.
- parameter hexString: The hex string, with or without the hash character.
- returns: A color with the given hex string.
*/
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
fileprivate convenience init?(hex3: Int, alpha: Float) {
self.init(red: CGFloat( ((hex3 & 0xF00) >> 8).duplicate4bits() ) / 255.0,
green: CGFloat( ((hex3 & 0x0F0) >> 4).duplicate4bits() ) / 255.0,
blue: CGFloat( ((hex3 & 0x00F) >> 0).duplicate4bits() ) / 255.0, alpha: CGFloat(alpha))
}
fileprivate convenience init?(hex6: Int, alpha: Float) {
self.init(red: CGFloat( (hex6 & 0xFF0000) >> 16 ) / 255.0,
green: CGFloat( (hex6 & 0x00FF00) >> 8 ) / 255.0,
blue: CGFloat( (hex6 & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(alpha))
}
/**
Create non-autoreleased color with in the given hex string and alpha.
- parameter hexString: The hex string, with or without the hash character.
- parameter alpha: The alpha value, a floating value between 0 and 1.
- returns: A color with the given hex string and alpha.
*/
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
}
guard let hexVal = Int(hex, radix: 16) else {
self.init()
return nil
}
switch hex.characters.count {
case 3:
self.init(hex3: hexVal, alpha: alpha)
case 6:
self.init(hex6: hexVal, alpha: alpha)
default:
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases, not a feature. -- Apple Forum
self.init()
return nil
}
}
/**
Create non-autoreleased color with in the given hex value. Alpha will be set as 1 by default.
- parameter hex: The hex value. For example: 0xff8942 (no quotation).
- returns: A color with the given hex value
*/
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex value and alpha
- parameter hex: The hex value. For example: 0xff8942 (no quotation).
- parameter alpha: The alpha value, a floating value between 0 and 1.
- returns: color with the given hex value and alpha
*/
public convenience init?(hex: Int, alpha: Float) {
if (0x000000 ... 0xFFFFFF) ~= hex {
self.init(hex6: hex , alpha: alpha)
} else {
self.init()
return nil
}
}
}
| 0aad26dba457c86c1944786f25bf5405 | 35.793893 | 115 | 0.628631 | false | false | false | false |
codefellows/pdx-c11-iOS | refs/heads/master | sampleCode/day2.playground/Contents.swift | mit | 1 | // Day 2 iOS F2 Portland
import UIKit
// ----------------------------------------
// DEMO 2.2: ARC & Strong & Weak References
// ----------------------------------------
var objectExists: Bool = false
func objectStatus() -> String {
println("objectExists = \(objectExists)")
return objectExists ? "Exists" : "Does NOT exist"
}
class Person {
var firstName : String = ""
var lastName : String = ""
init(_ firstname:String, _ lastname:String) {
self.firstName = firstname
self.lastName = lastname
objectExists = true
}
deinit {
objectExists = false;
}
}
objectStatus() // Starting point - no objects exist yet
var brook: Person?
var cofounder: Person?
objectStatus() // Optional does not trigger object instantiation
// "Normal" create & destroy
brook = Person("Brook", "Riggio") // Object & ref created
objectStatus()
brook!.firstName
brook!.lastName
brook = nil // ref removed
objectStatus() // No more refs, object de-alloc'd
// "Normal" create, multiple refs
brook = Person("Brook", "Riggio")
objectStatus()
brook!.firstName
brook!.lastName
cofounder = brook // 2nd ref created
objectStatus()
brook = nil // 1st ref removed...
objectStatus() // ...but cofounder ref keeps object alive
// Weak
weak var foo: Person?
foo = cofounder
cofounder = nil
objectStatus() // foo wasn't strong enough to save the object
foo // foo reverts to nil
// ----------------
// DEMO 2.2: Arrays
// ----------------
var dogNames = ["Fido", "Juniper", "Lucky"]
var catNames: [String] = ["Fido", "Juniper", "Lucky"]
dogNames[0]
dogNames[2]
dogNames.append("Old Yeller")
dogNames.count
dogNames.reverse()
var prices: [Float32] = [100, -9, 0, 9.99]
var temp: [Int] = [100, -9, 0, 1]
var people = [Person]()
people.append(Person("Will", "Little"))
people.append(Person("Jordana", "Gustafson")) | f13626186fc89f1234909b41aae7f0e7 | 24.630137 | 66 | 0.62139 | false | false | false | false |
BenziAhamed/Tracery | refs/heads/master | Common/Parser.swift | mit | 1 | //
// Parser.swift
// Tracery
//
// Created by Benzi on 10/03/17.
// Copyright © 2017 Benzi Ahamed. All rights reserved.
//
import Foundation
// MARK:- Parsing
struct Modifier : CustomStringConvertible {
var name: String
var parameters: [ValueCandidate]
var description: String {
return ".\(name)(\(parameters.map { $0.description }.joined(separator: ", ")))"
}
}
protocol ValueCandidateProtocol {
var nodes: [ParserNode] { get }
var hasWeight: Bool { get }
var weight: Int { get }
}
struct ValueCandidate: ValueCandidateProtocol, CustomStringConvertible {
var nodes: [ParserNode]
var hasWeight: Bool {
if let last = nodes.last, case .weight = last { return true }
return false
}
var weight: Int {
if let last = nodes.last, case let .weight(value) = last { return value }
return 1
}
var description: String {
return "<" + nodes.map { "\($0)" }.joined(separator: ",") + ">"
}
}
enum ParserConditionOperator {
case equalTo
case notEqualTo
case valueIn
case valueNotIn
}
struct ParserCondition: CustomStringConvertible {
let lhs: [ParserNode]
let rhs: [ParserNode]
let op: ParserConditionOperator
var description: String {
return "\(lhs) \(op) \(rhs)"
}
}
enum ParserNode : CustomStringConvertible {
// input nodes
case text(String)
case rule(name:String, mods:[Modifier])
case any(values:[ValueCandidate], selector:RuleCandidateSelector, mods:[Modifier])
case tag(name:String, values:[ValueCandidate])
case weight(value: Int)
case createRule(name:String, values:[ValueCandidate])
// control flow
indirect case ifBlock(condition:ParserCondition, thenBlock:[ParserNode], elseBlock:[ParserNode]?)
indirect case whileBlock(condition:ParserCondition, doBlock:[ParserNode])
// procedures
case runMod(name: String)
case createTag(name: String, selector: RuleCandidateSelector)
// args handling
indirect case evaluateArg(nodes: [ParserNode])
// low level flow control
indirect case branch(check:ParserConditionOperator, thenBlock:[ParserNode], elseBlock:[ParserNode]?)
public var description: String {
switch self {
case let .rule(name, mods):
if mods.count > 0 {
let mods = mods.reduce("") { $0 + $1.description }
return "⌽#\(name)\(mods)#"
}
return "⌽#\(name)#"
case let .createRule(name, values):
if values.count == 1 { return "⌽+#\(name)=\(values[0])#" }
return "⌽+#\(name)=\(values)#"
case let .tag(name, values):
if values.count == 1 { return "⌽t:\(name)=\(values[0])" }
return "⌽t:\(name)=(\(values))"
case let .text(text):
return "⌽`\(text)`"
case let .any(values, _, mods):
if mods.count > 0 {
return "⌽any\(values)+\(mods)"
}
return "⌽any\(values)"
case let .weight(value):
return "⌽weight(\(value))"
case let .runMod(name):
return "⌽run(\(name))"
case let .createTag(name, _):
return "⌽+t:\(name)"
case let .evaluateArg(nodes):
return "⌽eval<\(nodes)>"
case let .ifBlock(condition, thenBlock, elseBlock):
if let elseBlock = elseBlock {
return "⌽if(\(condition) then \(thenBlock) else \(elseBlock))"
}
return "⌽if(\(condition) then \(thenBlock))"
case let .branch(check, thenBlock, elseBlock):
if let elseBlock = elseBlock {
return "⌽jump(args \(check) then \(thenBlock) else \(elseBlock))"
}
return "⌽jump(args \(check) then \(thenBlock))"
case let .whileBlock(condition, doBlock):
return "⌽while(\(condition) then \(doBlock))"
}
}
}
enum ParserError : Error, CustomStringConvertible {
case error(String)
var description: String {
switch self {
case let .error(msg): return msg
}
}
}
struct Parser { }
extension Array where Element: ValueCandidateProtocol {
func selector() -> RuleCandidateSelector {
if count < 2 {
return PickFirstContentSelector.shared
}
func hasWeights() -> Bool {
for i in self {
if i.hasWeight { return true }
}
return false
}
if hasWeights() {
var weights = [Int]()
for i in self {
weights.append(i.weight)
}
return WeightedSelector(weights)
}
return DefaultContentSelector(count)
}
}
| af4ff201ef3ae6647afa9e32178640c7 | 26.032787 | 104 | 0.551445 | false | false | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/TopRightHeight.Individual.swift | apache-2.0 | 1 | //
// TopRightHeight.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct TopRightHeight {
let topRight: LayoutElement.Point
let height: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.TopRightHeight {
private func makeFrame(topRight: Point, height: Float, width: Float) -> Rect {
let x = topRight.x - width
let y = topRight.y
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.TopRightHeight: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let topRight = self.topRight.evaluated(from: parameters)
let height = self.height.evaluated(from: parameters, withTheOtherAxis: .width(0))
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(topRight: topRight, height: height, width: width)
}
}
| d5b2ebb6a8c48e895c7cfd90a42b6a6d | 21.692308 | 115 | 0.723729 | false | false | false | false |
julienbodet/wikipedia-ios | refs/heads/develop | Wikipedia/Code/WMFTwoFactorPasswordViewController.swift | mit | 1 |
import UIKit
fileprivate enum WMFTwoFactorNextFirstResponderDirection: Int {
case forward = 1
case reverse = -1
}
fileprivate enum WMFTwoFactorTokenDisplayMode {
case shortNumeric
case longAlphaNumeric
}
class WMFTwoFactorPasswordViewController: WMFScrollViewController, UITextFieldDelegate, WMFDeleteBackwardReportingTextFieldDelegate, Themeable {
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var subTitleLabel: UILabel!
@IBOutlet fileprivate var tokenLabel: UILabel!
@IBOutlet fileprivate var tokenAlertLabel: UILabel!
@IBOutlet fileprivate var oathTokenFields: [ThemeableTextField]!
@IBOutlet fileprivate var oathTokenFieldsStackView: UIStackView!
@IBOutlet fileprivate var displayModeToggle: UILabel!
@IBOutlet fileprivate var backupOathTokenField: ThemeableTextField!
@IBOutlet fileprivate var loginButton: WMFAuthButton!
fileprivate var theme = Theme.standard
public var funnel: WMFLoginFunnel?
public var userName:String?
public var password:String?
public var captchaID:String?
public var captchaWord:String?
@objc func displayModeToggleTapped(_ recognizer: UITapGestureRecognizer) {
guard recognizer.state == .ended else {
return
}
switch displayMode {
case .longAlphaNumeric:
displayMode = .shortNumeric
case .shortNumeric:
displayMode = .longAlphaNumeric
}
}
fileprivate var displayMode: WMFTwoFactorTokenDisplayMode = .shortNumeric {
didSet {
switch displayMode {
case .longAlphaNumeric:
backupOathTokenField.isHidden = false
oathTokenFieldsStackView.isHidden = true
tokenLabel.text = WMFLocalizedString("field-backup-token-title", value:"Backup code", comment:"Title for backup token field")
displayModeToggle.text = WMFLocalizedString("two-factor-login-with-regular-code", value:"Use verification code", comment:"Button text for showing text fields for normal two factor login")
case .shortNumeric:
backupOathTokenField.isHidden = true
oathTokenFieldsStackView.isHidden = false
tokenLabel.text = WMFLocalizedString("field-token-title", value:"Verification code", comment:"Title for token field")
displayModeToggle.text = WMFLocalizedString("two-factor-login-with-backup-code", value:"Use one of your backup codes", comment:"Button text for showing text field for backup code two factor login")
}
oathTokenFields.forEach {$0.text = nil}
backupOathTokenField.text = nil
if isViewLoaded && (view.window != nil) {
makeAppropriateFieldFirstResponder()
}
}
}
fileprivate func makeAppropriateFieldFirstResponder() {
switch displayMode {
case .longAlphaNumeric:
backupOathTokenField?.becomeFirstResponder()
case .shortNumeric:
oathTokenFields.first?.becomeFirstResponder()
}
}
@IBAction fileprivate func loginButtonTapped(withSender sender: UIButton) {
save()
}
fileprivate func areRequiredFieldsPopulated() -> Bool {
switch displayMode {
case .longAlphaNumeric:
guard backupOathTokenField.text.wmf_safeCharacterCount > 0 else {
return false
}
return true
case .shortNumeric:
return oathTokenFields.first(where:{ $0.text.wmf_safeCharacterCount == 0 }) == nil
}
}
@IBAction func textFieldDidChange(_ sender: ThemeableTextField) {
enableProgressiveButton(areRequiredFieldsPopulated())
guard
displayMode == .shortNumeric,
sender.text.wmf_safeCharacterCount > 0
else {
return
}
makeNextTextFieldFirstResponder(currentTextField: sender, direction: .forward)
}
fileprivate func makeNextTextFieldFirstResponder(currentTextField: ThemeableTextField, direction: WMFTwoFactorNextFirstResponderDirection) {
guard let index = oathTokenFields.index(of: currentTextField) else {
return
}
let nextIndex = index + direction.rawValue
guard
nextIndex > -1,
nextIndex < oathTokenFields.count
else {
return
}
oathTokenFields[nextIndex].becomeFirstResponder()
}
func wmf_deleteBackward(_ sender: WMFDeleteBackwardReportingTextField) {
guard
displayMode == .shortNumeric,
sender.text.wmf_safeCharacterCount == 0
else {
return
}
makeNextTextFieldFirstResponder(currentTextField: sender, direction: .reverse)
}
func enableProgressiveButton(_ highlight: Bool) {
loginButton.isEnabled = highlight
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
enableProgressiveButton(false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
makeAppropriateFieldFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
enableProgressiveButton(false)
}
fileprivate func allowedCharacterSet() -> CharacterSet {
switch displayMode {
case .longAlphaNumeric:
return CharacterSet.init(charactersIn: " ").union(CharacterSet.alphanumerics)
case .shortNumeric:
return CharacterSet.decimalDigits
}
}
fileprivate func maxTextFieldCharacterCount() -> Int {
// Presently backup tokens are 16 digit, but may contain spaces and their length
// may change in future, so for now just set a sensible upper limit.
switch displayMode {
case .longAlphaNumeric:
return 24
case .shortNumeric:
return 1
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Disallow invalid characters.
guard (string.rangeOfCharacter(from: allowedCharacterSet().inverted) == nil) else {
return false
}
// Always allow backspace.
guard string != "" else {
return true
}
// Support numeric code pasting when showing individual digit UITextFields - i.e. when displayMode == .shortNumeric.
// If displayMode == .shortNumeric 'string' has been verified to be comprised of decimal digits by this point.
// Backup code (when displayMode == .longAlphaNumeric) pasting already works as-is because it uses a single UITextField.
if displayMode == .shortNumeric && string.count == oathTokenFields.count{
for (field, char) in zip(oathTokenFields, string) {
field.text = String(char)
}
enableProgressiveButton(areRequiredFieldsPopulated())
return false
}
// Enforce max count.
let countIfAllowed = textField.text.wmf_safeCharacterCount + string.count
return (countIfAllowed <= maxTextFieldCharacterCount())
}
func textFieldDidBeginEditing(_ textField: UITextField) {
tokenAlertLabel.isHidden = true
// In the storyboard we've set the text fields' to "Clear when editing begins", but
// the "Editing changed" handler "textFieldDidChange" isn't called when this clearing
// happens, so update progressive buttons' enabled state here too.
enableProgressiveButton(areRequiredFieldsPopulated())
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard displayMode == .longAlphaNumeric else {
return true
}
save()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
oathTokenFields.sort { $0.tag < $1.tag }
oathTokenFields.forEach {
$0.rightViewMode = .never
$0.textAlignment = .center
}
// Cast fields once here to set 'deleteBackwardDelegate' rather than casting everywhere else UITextField is expected.
if let fields = oathTokenFields as? [WMFDeleteBackwardReportingTextField] {
fields.forEach {$0.deleteBackwardDelegate = self}
}else{
assertionFailure("Underlying oathTokenFields from storyboard were expected to be of type 'WMFDeleteBackwardReportingTextField'.")
}
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
loginButton.setTitle(WMFLocalizedString("two-factor-login-continue", value:"Continue log in", comment:"Button text for finishing two factor login"), for: .normal)
titleLabel.text = WMFLocalizedString("two-factor-login-title", value:"Log in to your account", comment:"Title for two factor login interface")
subTitleLabel.text = WMFLocalizedString("two-factor-login-instructions", value:"Please enter two factor verification code", comment:"Instructions for two factor login interface")
displayMode = .shortNumeric
displayModeToggle.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(displayModeToggleTapped(_:))))
view.wmf_configureSubviewsForDynamicType()
apply(theme: theme)
}
@objc func closeButtonPushed(_ : UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
fileprivate func token() -> String {
switch displayMode {
case .longAlphaNumeric:
return backupOathTokenField.text!
case .shortNumeric:
return oathTokenFields.reduce("", { $0 + ($1.text ?? "") })
}
}
fileprivate func save() {
wmf_hideKeyboard()
tokenAlertLabel.isHidden = true
enableProgressiveButton(false)
guard
let userName = userName,
let password = password
else {
return
}
WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically.\n{{Identical|Logging in}}"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
WMFAuthenticationManager.sharedInstance
.login(username: userName,
password: password,
retypePassword: nil,
oathToken: token(),
captchaID: captchaID,
captchaWord: captchaWord,
success: { _ in
let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName)
WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
let presenter = self.presentingViewController
self.dismiss(animated: true, completion: {
presenter?.wmf_showEnableReadingListSyncPanel(theme: self.theme, oncePerLogin: true)
})
self.funnel?.logSuccess()
}, failure: { error in
if let error = error as? WMFAccountLoginError {
switch error {
case .temporaryPasswordNeedsChange:
WMFAlertManager.sharedInstance.dismissAlert()
self.showChangeTempPasswordViewController()
return
case .wrongToken:
self.tokenAlertLabel.text = error.localizedDescription
self.tokenAlertLabel.isHidden = false
self.funnel?.logError(error.localizedDescription)
WMFAlertManager.sharedInstance.dismissAlert()
return
default: break
}
}
self.enableProgressiveButton(true)
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
self.oathTokenFields.forEach {$0.text = nil}
self.backupOathTokenField.text = nil
self.makeAppropriateFieldFirstResponder()
})
}
func showChangeTempPasswordViewController() {
guard
let presenter = presentingViewController,
let changePasswordVC = WMFChangePasswordViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
changePasswordVC.apply(theme: theme)
dismiss(animated: true, completion: {
changePasswordVC.userName = self.userName
let navigationController = WMFThemeableNavigationController(rootViewController: changePasswordVC, theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
view.tintColor = theme.colors.link
tokenAlertLabel.textColor = theme.colors.error
var fields = oathTokenFields ?? []
fields.append(backupOathTokenField)
for textField in fields {
textField.apply(theme: theme)
}
titleLabel.textColor = theme.colors.primaryText
tokenLabel.textColor = theme.colors.secondaryText
displayModeToggle.textColor = theme.colors.link
subTitleLabel.textColor = theme.colors.secondaryText
}
}
| 876771bd1e1b8f4224bcada9da83e04c | 40.335227 | 314 | 0.638282 | false | false | false | false |
melsomino/unified-ios | refs/heads/master | Unified/Implementation/Cloud/DefaultCloudFilesCache.swift | mit | 1 | //
// Created by Власов М.Ю. on 25.05.16.
//
import Foundation
public class DefaultCloudFilesCache: CloudFileCache {
init(cloudConnector: CloudConnector, localPath: String) {
self.cloudConnector = cloudConnector
self.localPath = localPath
}
// MARK: - CloudFilesCache
public func getFile(relativeUrl: String, forceExtension: String?) -> CloudFile {
lock.lock()
defer {
lock.unlock()
}
let relativeUrlHash = calcHash(relativeUrl)
if let existing = fileFromRelativeUrlHash[relativeUrlHash] {
return existing
}
let localFilePath = localPath + "/" + relativeUrlHash + (forceExtension ?? "")
let newFile = DefaultCloudFile(url: cloudConnector.makeUrl(relativeUrl), localPath: localFilePath)
fileFromRelativeUrlHash[relativeUrlHash] = newFile
return newFile
}
// MARK: - Internals
private var cloudConnector: CloudConnector
private var localPath: String
private var fileFromRelativeUrlHash = [String: DefaultCloudFile]()
private var lock = NSLock()
private func calcHash(url: String) -> String {
return StringHashes.getHash(url)
}
}
| 944880695660bfcce5a09865915fd051 | 22.565217 | 100 | 0.741697 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Generics/conditional_conformances.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -warn-redundant-requirements > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
protocol P1 {}
protocol P2 {}
protocol P3 {}
protocol P4: P1 {}
protocol P5: P2 {}
protocol P6: P2 {}
protocol Assoc { associatedtype AT }
func takes_P2<X: P2>(_: X) {}
func takes_P5<X: P5>(_: X) {}
// Skip the first generic signature declcontext dump
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Free
struct Free<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Free
// CHECK-NEXT: (normal_conformance type=Free<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension Free: P2 where T: P1 {}
// expected-note@-1 {{requirement from conditional conformance of 'Free<U>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'Free<T>' to 'P2'}}
func free_good<U: P1>(_: U) {
takes_P2(Free<U>())
}
func free_bad<U>(_: U) {
takes_P2(Free<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
}
struct Constrained<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Constrained
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Constrained
// CHECK-NEXT: (normal_conformance type=Constrained<T> protocol=P2
// CHECK-NEXT: conforms_to: T P3)
extension Constrained: P2 where T: P3 {} // expected-note {{requirement from conditional conformance of 'Constrained<U>' to 'P2'}}
func constrained_good<U: P1 & P3>(_: U) {
takes_P2(Constrained<U>())
}
func constrained_bad<U: P1>(_: U) {
takes_P2(Constrained<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P3'}}
}
struct RedundantSame<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSame
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSame
// CHECK-NEXT: (normal_conformance type=RedundantSame<T> protocol=P2)
extension RedundantSame: P2 where T: P1 {}
// expected-warning@-1 {{redundant conformance constraint 'T' : 'P1'}}
struct RedundantSuper<T: P4> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSuper
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSuper
// CHECK-NEXT: (normal_conformance type=RedundantSuper<T> protocol=P2)
extension RedundantSuper: P2 where T: P1 {}
// expected-warning@-1 {{redundant conformance constraint 'T' : 'P1'}}
struct OverlappingSub<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=OverlappingSub
// CHECK-LABEL: ExtensionDecl line={{.*}} base=OverlappingSub
// CHECK-NEXT: (normal_conformance type=OverlappingSub<T> protocol=P2
// CHECK-NEXT: conforms_to: T P4)
extension OverlappingSub: P2 where T: P4 {} // expected-note {{requirement from conditional conformance of 'OverlappingSub<U>' to 'P2'}}
func overlapping_sub_good<U: P4>(_: U) {
takes_P2(OverlappingSub<U>())
}
func overlapping_sub_bad<U: P1>(_: U) {
takes_P2(OverlappingSub<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P4'}}
}
struct SameType<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameType
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameType
// CHECK-NEXT: (normal_conformance type=SameType<T> protocol=P2
// CHECK-NEXT: same_type: T Int)
extension SameType: P2 where T == Int {}
// expected-note@-1 {{requirement from conditional conformance of 'SameType<U>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'SameType<Float>' to 'P2'}}
func same_type_good() {
takes_P2(SameType<Int>())
}
func same_type_bad<U>(_: U) {
takes_P2(SameType<U>()) // expected-error{{global function 'takes_P2' requires the types 'U' and 'Int' be equivalent}}
takes_P2(SameType<Float>()) // expected-error{{global function 'takes_P2' requires the types 'Float' and 'Int' be equivalent}}
}
struct SameTypeGeneric<T, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameTypeGeneric
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameTypeGeneric
// CHECK-NEXT: (normal_conformance type=SameTypeGeneric<T, U> protocol=P2
// CHECK-NEXT: same_type: T U)
extension SameTypeGeneric: P2 where T == U {}
// expected-note@-1 {{requirement from conditional conformance of 'SameTypeGeneric<U, Int>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'SameTypeGeneric<Int, Float>' to 'P2'}}
// expected-note@-3 {{requirement from conditional conformance of 'SameTypeGeneric<U, V>' to 'P2'}}
func same_type_generic_good<U, V>(_: U, _: V)
where U: Assoc, V: Assoc, U.AT == V.AT
{
takes_P2(SameTypeGeneric<Int, Int>())
takes_P2(SameTypeGeneric<U, U>())
takes_P2(SameTypeGeneric<U.AT, V.AT>())
}
func same_type_bad<U, V>(_: U, _: V) {
takes_P2(SameTypeGeneric<U, V>())
// expected-error@-1{{global function 'takes_P2' requires the types 'U' and 'V' be equivalent}}
takes_P2(SameTypeGeneric<U, Int>())
// expected-error@-1{{global function 'takes_P2' requires the types 'U' and 'Int' be equivalent}}
takes_P2(SameTypeGeneric<Int, Float>())
// expected-error@-1{{global function 'takes_P2' requires the types 'Int' and 'Float' be equivalent}}
}
struct Infer<T, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Infer
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Infer
// CHECK-NEXT: (normal_conformance type=Infer<T, U> protocol=P2
// CHECK-NEXT: same_type: T Constrained<U>
// CHECK-NEXT: conforms_to: U P1)
extension Infer: P2 where T == Constrained<U> {}
// expected-note@-1 2 {{requirement from conditional conformance of 'Infer<Constrained<U>, V>' to 'P2'}}
func infer_good<U: P1>(_: U) {
takes_P2(Infer<Constrained<U>, U>())
}
func infer_bad<U: P1, V>(_: U, _: V) {
takes_P2(Infer<Constrained<U>, V>())
// expected-error@-1{{global function 'takes_P2' requires the types 'Constrained<U>' and 'Constrained<V>' be equivalent}}
// expected-error@-2{{global function 'takes_P2' requires that 'V' conform to 'P1'}}
takes_P2(Infer<Constrained<V>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
}
struct InferRedundant<T, U: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InferRedundant
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InferRedundant
// CHECK-NEXT: (normal_conformance type=InferRedundant<T, U> protocol=P2
// CHECK-NEXT: same_type: T Constrained<U>)
extension InferRedundant: P2 where T == Constrained<U> {}
func infer_redundant_good<U: P1>(_: U) {
takes_P2(InferRedundant<Constrained<U>, U>())
}
func infer_redundant_bad<U: P1, V>(_: U, _: V) {
takes_P2(InferRedundant<Constrained<U>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
takes_P2(InferRedundant<Constrained<V>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
}
class C1 {}
class C2: C1 {}
class C3: C2 {}
struct ClassFree<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassFree
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassFree
// CHECK-NEXT: (normal_conformance type=ClassFree<T> protocol=P2
// CHECK-NEXT: superclass: T C1)
extension ClassFree: P2 where T: C1 {} // expected-note {{requirement from conditional conformance of 'ClassFree<U>' to 'P2'}}
func class_free_good<U: C1>(_: U) {
takes_P2(ClassFree<U>())
}
func class_free_bad<U>(_: U) {
takes_P2(ClassFree<U>())
// expected-error@-1{{global function 'takes_P2' requires that 'U' inherit from 'C1'}}
}
struct ClassMoreSpecific<T: C1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassMoreSpecific
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassMoreSpecific
// CHECK-NEXT: (normal_conformance type=ClassMoreSpecific<T> protocol=P2
// CHECK-NEXT: superclass: T C3)
extension ClassMoreSpecific: P2 where T: C3 {} // expected-note {{requirement from conditional conformance of 'ClassMoreSpecific<U>' to 'P2'}}
func class_more_specific_good<U: C3>(_: U) {
takes_P2(ClassMoreSpecific<U>())
}
func class_more_specific_bad<U: C1>(_: U) {
takes_P2(ClassMoreSpecific<U>())
// expected-error@-1{{global function 'takes_P2' requires that 'U' inherit from 'C3'}}
}
struct ClassLessSpecific<T: C3> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassLessSpecific
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassLessSpecific
// CHECK-NEXT: (normal_conformance type=ClassLessSpecific<T> protocol=P2)
extension ClassLessSpecific: P2 where T: C1 {}
// expected-warning@-1 {{redundant superclass constraint 'T' : 'C1'}}
// Inherited conformances:
class Base<T> {}
extension Base: P2 where T: C1 {}
class SubclassGood: Base<C1> {}
func subclass_good() {
takes_P2(SubclassGood())
}
class SubclassBad: Base<Int> {} // expected-note {{requirement from conditional conformance of 'SubclassBad' to 'P2'}}
func subclass_bad() {
takes_P2(SubclassBad())
// expected-error@-1{{global function 'takes_P2' requires that 'Int' inherit from 'C1'}}
}
// Inheriting conformances:
struct InheritEqual<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension InheritEqual: P2 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritEqual<U>' to 'P2'}}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P5
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
// CHECK-NEXT: conforms_to: T P1)
extension InheritEqual: P5 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritEqual<U>' to 'P5'}}
func inheritequal_good<U: P1>(_: U) {
takes_P2(InheritEqual<U>())
takes_P5(InheritEqual<U>())
}
func inheritequal_bad<U>(_: U) {
takes_P2(InheritEqual<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
takes_P5(InheritEqual<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P1'}}
}
struct InheritLess<T> {}
extension InheritLess: P2 where T: P1 {}
extension InheritLess: P5 {}
// expected-error@-1 {{type 'InheritLess<T>' does not conform to protocol 'P5'}}
// expected-error@-2 {{type 'T' does not conform to protocol 'P1'}}
// expected-error@-3 {{'P5' requires that 'T' conform to 'P1'}}
// expected-note@-4 {{requirement specified as 'T' : 'P1'}}
// expected-note@-5 {{requirement from conditional conformance of 'InheritLess<T>' to 'P2'}}
struct InheritMore<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension InheritMore: P2 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritMore<U>' to 'P2'}}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P5
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
// CHECK-NEXT: conforms_to: T P4)
extension InheritMore: P5 where T: P4 {} // expected-note 2 {{requirement from conditional conformance of 'InheritMore<U>' to 'P5'}}
func inheritequal_good_good<U: P4>(_: U) {
takes_P2(InheritMore<U>())
takes_P5(InheritMore<U>())
}
func inheritequal_good_bad<U: P1>(_: U) {
takes_P2(InheritMore<U>())
takes_P5(InheritMore<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P4'}}
}
func inheritequal_bad_bad<U>(_: U) {
takes_P2(InheritMore<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
takes_P5(InheritMore<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P4'}}
}
struct InheritImplicitOne<T> {}
// This shouldn't give anything implicit since we disallow implication for
// conditional conformances (in many cases, the implied bounds are
// incorrect/insufficiently general).
extension InheritImplicitOne: P5 where T: P1 {}
// expected-error@-1{{conditional conformance of type 'InheritImplicitOne<T>' to protocol 'P5' does not imply conformance to inherited protocol 'P2'}}
// expected-note@-2{{did you mean to explicitly state the conformance like 'extension InheritImplicitOne: P2 where ...'?}}
struct InheritImplicitTwo<T> {}
// Even if we relax the rule about implication, this double-up should still be
// an error, because either conformance could imply InheritImplicitTwo: P2.
extension InheritImplicitTwo: P5 where T: P1 {}
// expected-error@-1{{conditional conformance of type 'InheritImplicitTwo<T>' to protocol 'P5' does not imply conformance to inherited protocol 'P2'}}
// expected-note@-2{{did you mean to explicitly state the conformance like 'extension InheritImplicitTwo: P2 where ...'?}}
extension InheritImplicitTwo: P6 where T: P1 {}
// However, if there's a non-conditional conformance that implies something, we
// can imply from that one.
struct InheritImplicitGood1<T> {}
extension InheritImplicitGood1: P5 {}
extension InheritImplicitGood1: P6 where T: P1 {}
func inheritimplicitgood1<T>(_ : T) {
takes_P2(InheritImplicitGood1<T>()) // unconstrained!
takes_P2(InheritImplicitGood1<Int>())
}
struct InheritImplicitGood2<T> {}
extension InheritImplicitGood2: P6 where T: P1 {}
extension InheritImplicitGood2: P5 {}
func inheritimplicitgood2<T>(_: T) {
takes_P2(InheritImplicitGood2<T>()) // unconstrained!
takes_P2(InheritImplicitGood2<Int>())
}
struct InheritImplicitGood3<T>: P5 {}
extension InheritImplicitGood3: P6 where T: P1 {}
func inheritimplicitgood3<T>(_: T) {
takes_P2(InheritImplicitGood3<T>()) // unconstrained!
takes_P2(InheritImplicitGood3<Int>())
}
// "Multiple conformances" from SE0143
struct TwoConformances<T> {}
extension TwoConformances: P2 where T: P1 {}
// expected-note@-1{{'TwoConformances<T>' declares conformance to protocol 'P2' here}}
extension TwoConformances: P2 where T: P3 {}
// expected-error@-1{{conflicting conformance of 'TwoConformances<T>' to protocol 'P2'; there cannot be more than one conformance, even with different conditional bounds}}
struct TwoDisjointConformances<T> {}
extension TwoDisjointConformances: P2 where T == Int {}
// expected-note@-1{{'TwoDisjointConformances<T>' declares conformance to protocol 'P2' here}}
extension TwoDisjointConformances: P2 where T == String {}
// expected-error@-1{{conflicting conformance of 'TwoDisjointConformances<T>' to protocol 'P2'; there cannot be more than one conformance, even with different conditional bounds}}
// FIXME: these cases should be equivalent (and both with the same output as the
// first), but the second one choses T as the representative of the
// equivalence class containing both T and U in the extension's generic
// signature, meaning the stored conditional requirement is T: P1, which isn't
// true in the original type's generic signature.
struct RedundancyOrderDependenceGood<T: P1, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood
// CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceGood<T, U> protocol=P2
// CHECK-NEXT: same_type: T U)
extension RedundancyOrderDependenceGood: P2 where U: P1, T == U {}
// expected-warning@-1 {{redundant conformance constraint 'U' : 'P1'}}
struct RedundancyOrderDependenceBad<T, U: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad
// CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceBad<T, U> protocol=P2
// CHECK-NEXT: conforms_to: T P1
// CHECK-NEXT: same_type: T U)
extension RedundancyOrderDependenceBad: P2 where T: P1, T == U {}
// Checking of conditional requirements for existential conversions.
func existential_good<T: P1>(_: T.Type) {
_ = Free<T>() as P2
}
func existential_bad<T>(_: T.Type) {
_ = Free<T>() as P2 // expected-error{{protocol 'P2' requires that 'T' conform to 'P1'}}
}
// rdar://problem/35837054
protocol P7 { }
protocol P8 {
associatedtype A
}
struct X0 { }
struct X1 { }
extension X1: P8 {
typealias A = X0
}
struct X2<T> { }
extension X2: P7 where T: P8, T.A: P7 { } // expected-note {{requirement from conditional conformance of 'X2<X1>' to 'P7'}}
func takesF7<T: P7>(_: T) { }
func passesConditionallyNotF7(x21: X2<X1>) {
takesF7(x21) // expected-error{{global function 'takesF7' requires that 'X1.A' (aka 'X0') conform to 'P7'}}
}
public struct SR6990<T, U> {}
extension SR6990: Sequence where T == Int {
public typealias Element = Float
public typealias Iterator = IndexingIterator<[Float]>
public func makeIterator() -> Iterator { fatalError() }
}
// SR-8324
protocol ElementProtocol {
associatedtype BaseElement: BaseElementProtocol = Self
}
protocol BaseElementProtocol: ElementProtocol where BaseElement == Self {}
protocol ArrayProtocol {
associatedtype Element: ElementProtocol
}
protocol NestedArrayProtocol: ArrayProtocol where Element: ArrayProtocol, Element.Element.BaseElement == Element.BaseElement {
associatedtype BaseElement = Element.BaseElement
}
extension Array: ArrayProtocol where Element: ElementProtocol {}
extension Array: NestedArrayProtocol where Element: ElementProtocol, Element: ArrayProtocol, Element.Element.BaseElement == Element.BaseElement {
// with the typealias uncommented you do not get a crash.
// typealias BaseElement = Element.BaseElement
}
// SR-8337
struct Foo<Bar> {}
protocol P {
associatedtype A
var foo: Foo<A> { get }
}
extension Foo: P where Bar: P {
var foo: Foo { return self }
}
// rdar://problem/47871590
extension BinaryInteger {
var foo: Self {
return self <= 1
? 1
: (2...self).reduce(1, *)
// expected-error@-1 {{referencing instance method 'reduce' on 'ClosedRange' requires that 'Self.Stride' conform to 'SignedInteger'}}
}
}
// SR-10992
protocol SR_10992_P {}
struct SR_10992_S<T> {}
extension SR_10992_S: SR_10992_P where T: SR_10992_P {} // expected-note {{requirement from conditional conformance of 'SR_10992_S<String>' to 'SR_10992_P'}}
func sr_10992_foo(_ fn: (SR_10992_S<String>) -> Void) {}
func sr_10992_bar(_ fn: (SR_10992_P) -> Void) {
sr_10992_foo(fn) // expected-error {{global function 'sr_10992_foo' requires that 'String' conform to 'SR_10992_P'}}
}
| a6d7e80de2e477fb9682dcae95e574d6 | 41.392694 | 179 | 0.707346 | false | false | false | false |
UsrNameu1/VIPER-SWIFT | refs/heads/master | VIPER-SWIFT/Classes/Modules/List/Application Logic/Interactor/ListInteractor.swift | mit | 3 | //
// ListInteractor.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
class ListInteractor : NSObject, ListInteractorInput {
var output : ListInteractorOutput?
let clock : Clock
let dataManager : ListDataManager
init(dataManager: ListDataManager, clock: Clock) {
self.dataManager = dataManager
self.clock = clock
}
func findUpcomingItems() {
let today = clock.today()
let endOfNextWeek = NSCalendar.currentCalendar().dateForEndOfFollowingWeekWithDate(today)
dataManager.todoItemsBetweenStartDate(today,
endDate: endOfNextWeek,
completion: { todoItems in
let upcomingItems = self.upcomingItemsFromToDoItems(todoItems)
self.output?.foundUpcomingItems(upcomingItems)
})
}
func upcomingItemsFromToDoItems(todoItems: [TodoItem]) -> [UpcomingItem] {
let calendar = NSCalendar.autoupdatingCurrentCalendar()
var upcomingItems : [UpcomingItem] = []
for todoItem in todoItems {
var dateRelation = calendar.nearTermRelationForDate(todoItem.dueDate, relativeToToday: clock.today())
let upcomingItem = UpcomingItem(title: todoItem.name, dueDate: todoItem.dueDate, dateRelation: dateRelation)
upcomingItems.insert(upcomingItem, atIndex: upcomingItems.endIndex)
}
return upcomingItems
}
} | 5c89542e2ed63ce818f690acad5c070e | 31.851064 | 120 | 0.659754 | false | false | false | false |
necrowman/CRLAlamofireFuture | refs/heads/master | Carthage/Checkouts/ExecutionContext/ExecutionContext/CustomExecutionContext.swift | mit | 111 | //===--- CustomExecutionContext.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 Foundation3
import Boilerplate
public class CustomExecutionContext : ExecutionContextBase, ExecutionContextType {
let id = NSUUID()
let executor:Executor
public init(executor:Executor) {
self.executor = executor
}
public func async(task:SafeTask) {
executor {
let context = currentContext.value
defer {
currentContext.value = context
}
currentContext.value = self
task()
}
}
public func async(after:Timeout, task:SafeTask) {
async {
Thread.sleep(after)
task()
}
}
public func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType {
return try syncThroughAsync(task)
}
public func isEqualTo(other: NonStrictEquatable) -> Bool {
guard let other = other as? CustomExecutionContext else {
return false
}
return id.isEqual(other.id)
}
} | 614dbc8cac3fb7936f51cedd2c4d8c95 | 30.293103 | 97 | 0.594267 | false | false | false | false |
CodaFi/swift | refs/heads/main | stdlib/public/core/ContiguouslyStored.swift | apache-2.0 | 15 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// NOTE: The below is necessary for fast String initialization from untyped
// memory. When we add Collection.withContiguousRawStorageIfAvailabe(), we can
// deprecate this functionality.
@usableFromInline
internal protocol _HasContiguousBytes {
func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R
var _providesContiguousBytesNoCopy: Bool { get }
}
extension _HasContiguousBytes {
@inlinable
var _providesContiguousBytesNoCopy: Bool {
@inline(__always) get { return true }
}
}
extension Array: _HasContiguousBytes {
@inlinable
var _providesContiguousBytesNoCopy: Bool {
@inline(__always) get {
#if _runtime(_ObjC)
return _buffer._isNative
#else
return true
#endif
}
}
}
extension ContiguousArray: _HasContiguousBytes {}
extension UnsafeBufferPointer: _HasContiguousBytes {
@inlinable @inline(__always)
func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
let ptr = UnsafeRawPointer(self.baseAddress)
let len = self.count &* MemoryLayout<Element>.stride
return try body(UnsafeRawBufferPointer(start: ptr, count: len))
}
}
extension UnsafeMutableBufferPointer: _HasContiguousBytes {
@inlinable @inline(__always)
func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
let ptr = UnsafeRawPointer(self.baseAddress)
let len = self.count &* MemoryLayout<Element>.stride
return try body(UnsafeRawBufferPointer(start: ptr, count: len))
}
}
extension UnsafeRawBufferPointer: _HasContiguousBytes {
@inlinable @inline(__always)
func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
return try body(self)
}
}
extension UnsafeMutableRawBufferPointer: _HasContiguousBytes {
@inlinable @inline(__always)
func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
return try body(UnsafeRawBufferPointer(self))
}
}
extension String: _HasContiguousBytes {
@inlinable
internal var _providesContiguousBytesNoCopy: Bool {
@inline(__always) get { return self._guts.isFastUTF8 }
}
@inlinable @inline(__always)
internal func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
var copy = self
return try copy.withUTF8 { return try body(UnsafeRawBufferPointer($0)) }
}
}
extension Substring: _HasContiguousBytes {
@inlinable
internal var _providesContiguousBytesNoCopy: Bool {
@inline(__always) get { return self._wholeGuts.isFastUTF8 }
}
@inlinable @inline(__always)
internal func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
var copy = self
return try copy.withUTF8 { return try body(UnsafeRawBufferPointer($0)) }
}
}
| 9fd801618bdeb03582db8ddaca3af83b | 30.196262 | 80 | 0.681546 | false | false | false | false |
niekang/WeiBo | refs/heads/master | WeiBo/Class/View/Home/TitleView/WBTitleButton.swift | apache-2.0 | 1 | //
// WBTitleView.swift
// WeiBo
//
// Created by 聂康 on 2017/6/24.
// Copyright © 2017年 com.nk. All rights reserved.
//
import UIKit
class WBTitleButton: UIButton {
init(title:String?) {
super.init(frame: CGRect())
if title == nil {
setTitle("首页", for: .normal)
}else {
setImage(UIImage(named: "navigationbar_arrow_down"), for: .normal)
setImage(UIImage(named:"navigationbar_arrow_up"), for: .selected)
setTitle(title! + " ", for: .normal)
setTitleColor(UIColor.darkGray, for: .normal)
titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
}
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let _ = titleLabel?.text,
let _ = imageView?.image else {
return
}
titleLabel?.frame.origin.x = 0
imageView?.frame.origin.x = titleLabel!.bounds.width
}
}
| eb68a8e2d30a49d33b8d79d2e3db5ebc | 25.756098 | 78 | 0.569736 | false | false | false | false |
HariniMurali/TestDemoPodSDK | refs/heads/master | DropDown/helpers/DPDKeyboardListener.swift | mit | 6 | //
// KeyboardListener.swift
// DropDown
//
// Created by Kevin Hirsch on 30/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
internal final class KeyboardListener {
static let sharedInstance = KeyboardListener()
fileprivate(set) var isVisible = false
fileprivate(set) var keyboardFrame = CGRect.zero
fileprivate var isListening = false
deinit {
stopListeningToKeyboard()
}
}
//MARK: - Notifications
extension KeyboardListener {
func startListeningToKeyboard() {
if isListening {
return
}
isListening = true
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow(_:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(_:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
}
func stopListeningToKeyboard() {
NotificationCenter.default.removeObserver(self)
}
@objc
fileprivate func keyboardWillShow(_ notification: Notification) {
isVisible = true
keyboardFrame = keyboardFrame(fromNotification: notification)
}
@objc
fileprivate func keyboardWillHide(_ notification: Notification) {
isVisible = false
keyboardFrame = keyboardFrame(fromNotification: notification)
}
fileprivate func keyboardFrame(fromNotification notification: Notification) -> CGRect {
return ((notification as NSNotification).userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero
}
}
| 627f4f7bd72b87ddd5e9a6e2a79a9f91 | 21.720588 | 124 | 0.748867 | false | false | false | false |
Liqiankun/DLSwift | refs/heads/master | Swift/Swift字典.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//key不能重复
var dic : Dictionary<String,String> = ["Swift" : "快速","Python" : "大蟒"]
var dictionaryOne : Dictionary<String,Int> = [:]
var dictionaryTwo : [String:Int] = [:]
var dictionaryThree = [String:String]()
var dictionaryFour = Dictionary<String,String>()
print(dic["Swift"])
if let swift = dic["Swift"] {
print(swift)
}
dic.isEmpty
dic.count
Array(dic.keys)
Array(dic.values)
for key in dic.keys{
print(key)
}
//比较的是元素
dictionaryOne == dictionaryTwo
/** --------------------增删改查---------------------*/
dic["Paython"] = "大蛇"
//返回值为旧的value
dic.updateValue("雨燕", forKey: "Swift")
//如果没有就是添加
dic["PHP"] = "php"
dic.updateValue("C", forKey: "C")
print(dic)
dic["C"] = nil
dic.removeValueForKey("Paython")
| 1e70027b1de7b9f8359c95ebda770564 | 12.704918 | 70 | 0.626794 | false | false | false | false |
wayfair/brickkit-ios | refs/heads/master | Example/Source/Examples/Sticking/StickingFooterBaseViewController.swift | apache-2.0 | 1 | //
// StickingFooterBaseViewController.swift
// BrickKit
//
// Created by Ruben Cagnie on 6/3/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import BrickKit
private let StickySection = "Sticky Section"
private let FooterTitle = "FooterTitle"
class StickingFooterBaseViewController: BrickApp.BaseBrickController, HasTitle {
class var brickTitle: String {
return "Sticking Footer"
}
class var subTitle: String {
return "Example of Sticking Footers"
}
let numberOfLabels = 50
var repeatLabel: LabelBrick!
override func viewDidLoad() {
super.viewDidLoad()
let layout = self.brickCollectionView.layout
layout.zIndexBehavior = .bottomUp
self.brickCollectionView.registerBrickClass(LabelBrick.self)
let behavior = StickyFooterLayoutBehavior(dataSource: self)
self.brickCollectionView.layout.behaviors.insert(behavior)
let footerSection = BrickSection(StickySection, backgroundColor: UIColor.white, bricks: [
LabelBrick(FooterTitle, backgroundColor: .brickGray1, dataSource: LabelBrickCellModel(text: "Footer Title")),
LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: UIColor.lightGray, dataSource: LabelBrickCellModel(text: "Footer Label 1")),
LabelBrick(width: .ratio(ratio: 0.5), backgroundColor: UIColor.lightGray, dataSource: LabelBrickCellModel(text: "Footer Label 2")),
], inset: 5, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
let section = BrickSection(backgroundColor: UIColor.white, bricks: [
LabelBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 0.5), height: .auto(estimate: .fixed(size: 38)), backgroundColor: .brickGray1, dataSource: self),
footerSection
])
section.repeatCountDataSource = self
self.setSection(section)
}
}
extension StickingFooterBaseViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == BrickIdentifiers.repeatLabel {
return numberOfLabels
} else {
return 1
}
}
}
extension StickingFooterBaseViewController: LabelBrickCellDataSource {
func configureLabelBrickCell(_ cell: LabelBrickCell) {
cell.label.text = "BRICK \(cell.index + 1)"
cell.configure()
}
}
extension StickingFooterBaseViewController: StickyLayoutBehaviorDataSource {
func stickyLayoutBehavior(_ stickyLayoutBehavior: StickyLayoutBehavior, shouldStickItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool {
return identifier == StickySection
}
}
| 97a646c1ce9665b17451e0367af300ab | 35.217949 | 238 | 0.71115 | false | false | false | false |
EZ-NET/ESSwim | refs/heads/swift-2.2 | Sources/State/Cache.swift | mit | 1 | //
// Cache.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/06/15.
//
//
public protocol CacheType : CacheDataType {
mutating func release()
}
public protocol CacheDataType {
associatedtype Value
var value:Value? { get }
var cached:Bool { get }
func cache(value:Value)
}
extension CacheDataType {
func value(@autoclosure predicate:()->Value) -> Value {
return value(predicate: predicate)
}
public func value(@noescape predicate predicate:()->Value) -> Value {
if !self.cached {
self.cache(predicate())
}
return self.value!
}
}
public struct Cache<T> {
var _data:_CacheData<T>
public init() {
self._data = _CacheData()
}
}
extension Cache : CacheType {
public var cached:Bool {
return self._data.cached
}
public var value:T? {
return self._data.value
}
public mutating func release() {
self._data = _CacheData()
}
public func cache(value: T) {
guard !self.cached else {
fatalError("Aready cached.")
}
self._data.cache(value)
}
}
final class _CacheData<T> : CacheDataType {
private(set) var _value:T? = nil
var cached:Bool {
return self._value != nil
}
var value:T? {
return self._value
}
func cache(value:T) {
self._value = value
}
}
| c1dc3877c6ece0a010c983dacf9c7107 | 12.081633 | 70 | 0.629485 | false | false | false | false |
atrick/swift | refs/heads/main | test/Generics/sr13850.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// https://bugs.swift.org/browse/SR-13850
// CHECK: Requirement signature: <Self where Self.[P1]A : P2>
protocol P1 {
associatedtype A: P2
}
// CHECK: Requirement signature: <Self>
protocol P2 {
associatedtype A
}
// Neither one of 'P3', 'P4' or 'f()' should have diagnosed
// redundant conformance requirements.
// CHECK: Requirement signature: <Self where Self : P2, Self == Self.[P2]A.[P1]A, Self.[P2]A : P1>
protocol P3 : P2 where Self.A: P1, Self.A.A == Self { }
// CHECK: Requirement signature: <Self where Self.[P4]X : P2, Self.[P4]X == Self.[P4]X.[P2]A.[P1]A, Self.[P4]X.[P2]A : P1>
protocol P4 {
associatedtype X where X : P2, X.A: P1, X.A.A == X
}
// CHECK: Generic signature: <T where T : P2, T == T.[P2]A.[P1]A, T.[P2]A : P1>
func f<T : P2>(_: T) where T.A : P1, T.A.A == T { }
| 2f421fa6e93748e8a4773635fe0ce73a | 33.555556 | 129 | 0.647374 | false | false | false | false |
Syject/MyLessPass-iOS | refs/heads/master | LessPass/Libraries/BigInteger/SMP Bignum Extensions.swift | gpl-3.0 | 2 | //
// SMP Bignum Extensions.swift
// BigInteger
//
// This module contains convenience extensions for SMP that are
// largely compatible with the (OpenSSL-based) Bignum Swift module.
//
import Foundation
/// Bignum compatibility alias for BInt
public typealias Bignum = BInt
public extension Bignum
{
/// Representation as Data
public var data: Data {
let n = limbs.count
var data = Data(count: n * 8)
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
var p = ptr
for i in (0..<n).reversed() {
for j in (0..<8).reversed() {
p.pointee = UInt8((limbs[i] >> UInt64(j*8)) & 0xff)
p += 1
}
}
}
return data
}
/// Decimal string representation
public var dec: String { return description }
/// Hexadecimal string representation
public var hex: String { return data.hexString }
///
/// Initialise a BInt from a hexadecimal string
///
/// - Parameter hex: the hexadecimal string to convert to a big integer
public init(hex: String) {
self.init(number: hex.lowercased(), withBase: 16)
}
/// Initialise from an unsigned, 64 bit integer
///
/// - Parameter n: the 64 bit unsigned integer to convert to a BInt
public init(_ n: UInt64) {
self.init(limbs: [n])
}
/// Initialise from big-endian data
///
/// - Parameter data: the data to convert to a Bignum
public init(data: Data) {
let n = data.count
guard n > 0 else {
self.init(0)
return
}
let m = (n + 7) / 8
var limbs = Limbs(repeating: 0, count: m)
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
var p = ptr
let r = n % 8
let k = r == 0 ? 8 : r
for j in (0..<k).reversed() {
limbs[m-1] += UInt64(p.pointee) << UInt64(j*8)
p += 1
}
guard m > 1 else { return }
for i in (0..<(m-1)).reversed() {
for j in (0..<8).reversed() {
limbs[i] += UInt64(p.pointee) << UInt64(j*8)
p += 1
}
}
}
self.init(limbs: limbs)
}
}
/// Extension for Data to interoperate with Bignum
extension Data {
/// Hexadecimal string representation of the underlying data
var hexString: String {
return withUnsafeBytes { (buf: UnsafePointer<UInt8>) -> String in
let charA = UInt8(UnicodeScalar("a").value)
let char0 = UInt8(UnicodeScalar("0").value)
func itoh(_ value: UInt8) -> UInt8 {
return (value > 9) ? (charA + value - 10) : (char0 + value)
}
let ptr = UnsafeMutablePointer<UInt8>.allocate(capacity: count * 2)
for i in 0 ..< count {
ptr[i*2] = itoh((buf[i] >> 4) & 0xF)
ptr[i*2+1] = itoh(buf[i] & 0xF)
}
return String(bytesNoCopy: ptr, length: count*2, encoding: .utf8, freeWhenDone: true)!
}
}
}
| 4bfcbb853e1402b1a5c899e170fd6948 | 25.046296 | 98 | 0.591184 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/ViewControllers/Chat/CellNodes/ChatBaseCellNode.swift | mit | 1 | //
// ChatBaseCellNode.swift
// Yep
//
// Created by NIX on 16/7/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import RealmSwift
import AsyncDisplayKit
class ChatBaseCellNode: ASCellNode {
static let avatarSize = CGSize(width: 40, height: 40)
static let topPadding: CGFloat = 0
static let bottomPadding: CGFloat = 10
static var verticalPadding: CGFloat {
return topPadding + bottomPadding
}
var tapAvatarAction: ((user: User) -> Void)?
var user: User? {
didSet {
if let user = user {
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageNode.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
}
}
}
private lazy var nameNode = ASTextNode()
lazy var avatarImageNode: ASImageNode = {
let node = ASImageNode()
let tapAvatar = UITapGestureRecognizer(target: self, action: #selector(ChatBaseCellNode.tapAvatar(_:)))
node.userInteractionEnabled = true
node.view.addGestureRecognizer(tapAvatar)
return node
}()
override init() {
super.init()
selectionStyle = .None
//addSubnode(nameNode)
addSubnode(avatarImageNode)
}
@objc private func tapAvatar(sender: UITapGestureRecognizer) {
println("tapAvatar")
if let user = user {
tapAvatarAction?(user: user)
}
}
func deleteMessage(object: AnyObject?) {
println("TODO deleteMessage")
}
func reportMessage(object: AnyObject?) {
println("TODO reportMessage")
}
}
| da0a0bdfe5f5d542fc9b1977860b89a1 | 24.661765 | 133 | 0.64298 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/data types/enumerable/XGInteractionPoint.swift | gpl-2.0 | 1 | //
// XGWarp.swift
// GoD Tool
//
// Created by The Steez on 29/10/2017.
//
//
import Foundation
let kSizeOfInteractionPoint = 0x1C
// some of the offsets overlap because the values at that offset play different roles depending on the type of interaction point
let kIPInteractionMethodOffset = 0x0
let kIPRoomIDOffset = 0x2
let kIPRegionIndexOffset = 0x7
let kIPScriptValueOffset = 0x8
let kIPScriptIndexOffset = 0xa
let kIPScriptParameter1Offset = 0xc
let kIPScriptParameter2Offset = 0x10
let kIPScriptParameter3Offset = 0x14
let kIPScriptParameter4Offset = 0x18
let kIPWarpTargetRoomIDOffset = 0xe
let kIPWarpTargetEntryPointIDOffset = 0x13
let kIPWarpSoundEffectOffset = 0x17
let kIPStringIDOffset = 0xe
let kIPDoorIDOffset = 0xe
let kIPElevatorIDOffset = 0xe
let kIPElevatorTargetRoomIDOffset = 0x12
let kIPTargetElevatorIDOffset = 0x16
let kIPElevatorDirectionOffset = 0x1B
let kIPCutsceneIDOffset = 0x16
let kIPCameraIDOffset = 0x18
let kIPPCRoomIDOffset = 0xe
let kIPPCUnknownOffset = 0x13
// These are the indexes of that script function in common.rel's script
let kIPWarpValue = 0x4
let kIPDoorValue = 0x5
let kIPElevatorValue = 0x6
let kIPTextValue = game == .XD ? 0xC : 0xB
let kIPCutsceneValue = game == .XD ? 0xD : 0xC
let kIPPCValue = game == .XD ? 0xE : 0xD
enum XGInteractionMethods : Int, Codable {
case None = 0
case WalkThrough = 1
case WalkInFront = 2
case PressAButton = 3
case PressAButton2 = 4 // colosseum only
var name: String {
switch self {
case .None:
return "None"
case .WalkThrough:
return "Walk Through"
case .WalkInFront:
return "Walk In Front Of"
case .PressAButton:
return "Press A"
case .PressAButton2:
return "Press A 2"
}
}
}
enum XGElevatorDirections : Int, Codable {
case up = 0
case down = 1
var string : String {
return self.rawValue == 0 ? "Up" : "Down"
}
}
enum XGInteractionPointInfo {
case None
// These are all just script indexes in common.rel's script
case Warp(targetRoom: Int, targetEntryID: Int, sound: Bool)
case Door(id: Int)
case Text(stringID: Int)
case Elevator(elevatorID: Int, targetRoomID: Int, targetElevatorID: Int, direction: XGElevatorDirections)
case CutsceneWarp(targetRoom: Int, targetEntryID: Int, cutsceneID: Int, cameraFSYSID: Int)
case PC(roomID: Int, unknown: Int) // parameters are unused
case CurrentScript(scriptIndex: Int, parameter1: Int, parameter2: Int, parameter3: Int, parameter4: Int) // index into current map's script
case CommonScript(scriptIndex: Int, parameter1: Int, parameter2: Int, parameter3: Int, parameter4: Int) // for any other function in common.rel
var scriptIndex: Int {
switch self {
case .None: return 0
case .Warp:
return kIPWarpValue
case .Door:
return kIPDoorValue
case .Text:
return kIPTextValue
case .Elevator:
return kIPElevatorValue
case .CutsceneWarp:
return kIPCutsceneValue
case .PC:
return kIPPCValue
case .CurrentScript(let scriptIndex, _, _, _, _):
return scriptIndex
case .CommonScript(let scriptIndex, _, _, _, _):
return scriptIndex
}
}
}
fileprivate var IPData = [XGInteractionPointData]()
fileprivate func getIPData() {
if IPData.isEmpty {
for i in 0 ..< CommonIndexes.NumberOfInteractionPoints.value {
IPData.append(XGInteractionPointData(index: i))
}
}
}
var allInteractionPointData : [XGInteractionPointData] {
getIPData()
return IPData
}
final class XGInteractionPointData: NSObject {
// Each entry is actually a script function call
// if the script value is 0x596 then the script function is from common.scd
// if the script value is 0x100 then the script function is from the map's scd
// the IP type is actually the index of the script function to call
// e.g. @floor_link (warp 0x4) or @elevator (0x6)
// the rest of the parameters are the arguments to the function
var index = 0
var startOffset = 0
var roomID = 0
var interactionMethod = XGInteractionMethods.None
var interactionPointIndex = 0
var info = XGInteractionPointInfo.None
var room: XGRoom? {
return XGRoom.roomWithID(roomID)
}
override var description: String {
var desc = "Interaction Point: \(index) - offset: \(startOffset.hexString())"
var roomName = "-"
if let room = XGRoom.roomWithID(roomID) {
roomName = room.name
}
desc += " Room: \(roomName) (\(roomID.hexString()))\n"
switch interactionMethod {
case .WalkInFront:
desc += "Walk in front of Interaction Region: \(interactionPointIndex)\n"
case .WalkThrough:
desc += "Walk through Interaction Region: \(interactionPointIndex)\n"
case .PressAButton:
desc += "Press A on Interaction Region: \(interactionPointIndex)\n"
case .PressAButton2:
desc += "Press A (2) on Interaction Region: \(interactionPointIndex)\n"
default:
break
}
switch info {
case .None:
break
case .Warp(let targetRoom, let targetEntryID, let sound):
var roomName = "-"
if let room = XGRoom.roomWithID(targetRoom) {
roomName = room.name
}
desc += "Warp to \(roomName) at Entry point: \(targetEntryID) \(sound ? "with" : "without") sound effect\n"
case .Door(let id):
desc += "Open door with id: \(id)\n"
case .Text(let stringID):
desc += "Display text: \"\(getStringSafelyWithID(id: stringID))\"\n"
case .CurrentScript(let scriptIndex, let parameter1, let parameter2, let parameter3, let parameter4):
desc += "Call script function with id: \(scriptIndex)"
if game == .XD {
if let room = XGRoom.roomWithID(roomID) {
if let script = room.script?.scriptData {
if scriptIndex < script.ftbl.count {
desc += " @\(script.ftbl[scriptIndex].name)"
}
}
}
} else {
desc += " with parameter 1: \(parameter1)\n"
desc += " with parameter 2: \(parameter2)\n"
desc += " with parameter 3: \(parameter3)\n"
desc += " with parameter 4: \(parameter4)\n"
}
desc += "\n"
case .CommonScript(let scriptIndex, let parameter1, let parameter2, let parameter3, let parameter4):
desc += "Call common script function with id: \(scriptIndex)"
if game == .XD {
if let room = XGRoom.roomWithID(roomID) {
if let script = room.script?.scriptData {
if scriptIndex < script.ftbl.count {
desc += " @\(script.ftbl[scriptIndex].name)"
}
}
}
} else {
desc += " with parameter 1: \(parameter1)\n"
desc += " with parameter 2: \(parameter2)\n"
desc += " with parameter 3: \(parameter3)\n"
desc += " with parameter 4: \(parameter4)\n"
}
desc += "\n"
case .Elevator(let elevatorID, let targetRoomID, let targetElevatorID, let direction):
desc += "Use Elevator with id \(elevatorID) to go \(direction == .up ? "up" : "down")\n"
var roomName = "-"
if let room = XGRoom.roomWithID(targetRoomID) {
roomName = room.name
}
desc += "to room \(roomName) elevator with id: \(targetElevatorID)\n"
case .PC(let roomID, let unknown):
desc += "Use PC roomID: \(roomID.hexString()) unknown: \(unknown)\n"
case .CutsceneWarp(let targetRoom, let targetEntryID, let cutsceneID, let cameraFSYSID):
var roomName = "-"
if let room = XGRoom.roomWithID(targetRoom) {
roomName = room.name
}
desc += "Cutscene warp \(cutsceneID.hexString()) to \(roomName) at Entry point: \(targetEntryID) with camera file \(cameraFSYSID.hexString())\n"
}
return desc
}
init(index: Int) {
super.init()
self.index = index
self.startOffset = CommonIndexes.InteractionPoints.startOffset + (index * kSizeOfInteractionPoint)
let rel = XGFiles.common_rel.data!
self.roomID = rel.get2BytesAtOffset(startOffset + kIPRoomIDOffset)
self.interactionPointIndex = rel.getByteAtOffset(startOffset + kIPRegionIndexOffset)
let methodID = rel.getByteAtOffset(startOffset + kIPInteractionMethodOffset)
if let method = XGInteractionMethods(rawValue: methodID) {
self.interactionMethod = method
} else {
printg("Unknown interaction method: \(methodID) for point with index: \(index)")
}
let scriptIdentifier = rel.get2BytesAtOffset(startOffset + kIPScriptValueOffset)
let scriptID = rel.get2BytesAtOffset(startOffset + kIPScriptIndexOffset)
if scriptIdentifier == 0x100 { // current script
let parameter1 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter1Offset)
let parameter2 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter2Offset)
let parameter3 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter3Offset)
let parameter4 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter4Offset)
self.info = .CurrentScript(scriptIndex: scriptID, parameter1: parameter1, parameter2: parameter2, parameter3: parameter3, parameter4: parameter4)
} else if scriptIdentifier == 0x596 { // common.rel
switch scriptID {
// These are the function indexes within common.rel's script
case kIPWarpValue:
let targetRoom = rel.get2BytesAtOffset(startOffset + kIPWarpTargetRoomIDOffset)
let entryID = rel.getByteAtOffset(startOffset + kIPWarpTargetEntryPointIDOffset)
let sound = rel.getByteAtOffset(startOffset + kIPWarpSoundEffectOffset) == 1
self.info = .Warp(targetRoom: targetRoom, targetEntryID: entryID, sound: sound)
case kIPDoorValue:
self.info = .Door(id: rel.get2BytesAtOffset(startOffset + kIPDoorIDOffset))
case kIPElevatorValue:
let elevID = rel.get2BytesAtOffset(startOffset + kIPElevatorIDOffset)
let targetRoom = rel.get2BytesAtOffset(startOffset + kIPElevatorTargetRoomIDOffset)
let targetElevID = rel.get2BytesAtOffset(startOffset + kIPTargetElevatorIDOffset)
let direction = XGElevatorDirections(rawValue: rel.getByteAtOffset(startOffset + kIPElevatorDirectionOffset)) ?? .up
self.info = .Elevator(elevatorID: elevID, targetRoomID: targetRoom, targetElevatorID: targetElevID, direction: direction)
case kIPTextValue:
self.info = .Text(stringID: rel.get2BytesAtOffset(startOffset + kIPStringIDOffset))
case kIPCutsceneValue:
let targetRoom = rel.get2BytesAtOffset(startOffset + kIPWarpTargetRoomIDOffset)
let entryID = rel.getByteAtOffset(startOffset + kIPWarpTargetEntryPointIDOffset)
let cutsceneID = rel.get2BytesAtOffset(startOffset + kIPCutsceneIDOffset)
let camera = rel.get2BytesAtOffset(startOffset + kIPCameraIDOffset)
self.info = .CutsceneWarp(targetRoom: targetRoom, targetEntryID: entryID, cutsceneID: cutsceneID, cameraFSYSID: camera)
case kIPPCValue:
let roomID = rel.get2BytesAtOffset(startOffset + kIPPCRoomIDOffset)
let unknown = rel.getByteAtOffset(startOffset + kIPPCUnknownOffset)
self.info = .PC(roomID: roomID, unknown: unknown)
default:
let parameter1 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter1Offset)
let parameter2 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter2Offset)
let parameter3 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter3Offset)
let parameter4 = rel.get4BytesAtOffset(startOffset + kIPScriptParameter4Offset)
self.info = .CommonScript(scriptIndex: scriptID, parameter1: parameter1, parameter2: parameter2, parameter3: parameter3, parameter4: parameter4)
}
} else if scriptIdentifier == 0 {
self.info = .None
} else {
printg("Unknown variable value: \(scriptIdentifier) for point with index: \(index)")
}
}
func save() {
let rel = XGFiles.common_rel.data!
// first clear all data as different IP types use different offsets
rel.replaceBytesFromOffset(startOffset, withByteStream: [Int](repeating: 0, count: kSizeOfInteractionPoint))
rel.replaceByteAtOffset(startOffset + kIPInteractionMethodOffset, withByte: self.interactionMethod.rawValue)
rel.replace2BytesAtOffset(startOffset + kIPRoomIDOffset, withBytes: self.roomID)
rel.replaceByteAtOffset(startOffset + kIPRegionIndexOffset, withByte: self.interactionPointIndex)
switch self.info {
case .None: break
case .CurrentScript: rel.replace2BytesAtOffset(startOffset + kIPScriptValueOffset, withBytes: 0x100)
default: rel.replace2BytesAtOffset(startOffset + kIPScriptValueOffset, withBytes: 0x596)
}
rel.replace2BytesAtOffset(startOffset + kIPScriptIndexOffset, withBytes: info.scriptIndex)
switch self.info {
case .None:
break
case .Warp(let targetRoom, let targetEntryID, let sound):
rel.replace2BytesAtOffset(startOffset + kIPWarpTargetRoomIDOffset, withBytes: targetRoom)
rel.replaceByteAtOffset(startOffset + kIPWarpTargetEntryPointIDOffset, withByte: targetEntryID)
rel.replaceByteAtOffset(startOffset + kIPWarpSoundEffectOffset, withByte: sound ? 1 : 0)
case .Door(let id):
rel.replace2BytesAtOffset(startOffset + kIPDoorIDOffset, withBytes: id)
case .Elevator(let elevatorID, let targetRoomID, let targetElevatorID, let direction):
rel.replace2BytesAtOffset(startOffset + kIPElevatorIDOffset, withBytes: elevatorID)
rel.replace2BytesAtOffset(startOffset + kIPElevatorTargetRoomIDOffset, withBytes: targetRoomID)
rel.replace2BytesAtOffset(startOffset + kIPTargetElevatorIDOffset, withBytes: targetElevatorID)
rel.replaceByteAtOffset(startOffset + kIPElevatorDirectionOffset, withByte: direction.rawValue)
case .Text(let stringID):
rel.replace2BytesAtOffset(startOffset + kIPStringIDOffset, withBytes: stringID)
case .CurrentScript(_, let parameter1, let parameter2, let parameter3, let parameter4),
.CommonScript(_, let parameter1, let parameter2, let parameter3, let parameter4):
rel.replace4BytesAtOffset(startOffset + kIPScriptParameter1Offset, withBytes: parameter1)
rel.replace4BytesAtOffset(startOffset + kIPScriptParameter2Offset, withBytes: parameter2)
rel.replace4BytesAtOffset(startOffset + kIPScriptParameter3Offset, withBytes: parameter3)
rel.replace4BytesAtOffset(startOffset + kIPScriptParameter4Offset, withBytes: parameter4)
case .CutsceneWarp(let targetRoom, let targetEntryID, let cutsceneID, let cameraFSYSID):
rel.replace2BytesAtOffset(startOffset + kIPWarpTargetRoomIDOffset, withBytes: targetRoom)
rel.replaceByteAtOffset(startOffset + kIPWarpTargetEntryPointIDOffset, withByte: targetEntryID)
rel.replace2BytesAtOffset(startOffset + kIPCutsceneIDOffset, withBytes: cutsceneID)
rel.replace2BytesAtOffset(startOffset + kIPCameraIDOffset, withBytes: cameraFSYSID)
rel.replaceByteAtOffset(startOffset + kIPCameraIDOffset + 1, withByte: 0x18) // .cam filetype
case .PC(let roomID, let unknown):
rel.replace2BytesAtOffset(startOffset + kIPPCRoomIDOffset, withBytes: roomID)
rel.replaceByteAtOffset(startOffset + kIPPCUnknownOffset, withByte: unknown)
}
rel.save()
}
}
let kSizeOfMapEntryLocation = 0x10
let kIPAngleOffset = 0x0
let kILXOffset = 0x4
let kILYOffset = 0x8
let kILZOffset = 0xC
class XGMapEntryLocation : NSObject {
var index = 0
var startOffset = 0
var xCoordinate : Float = 0
var yCoordinate : Float = 0
var zCoordinate : Float = 0
var angle = 0
var room : XGRoom {
return XGRoom.roomWithName(self.file.fileName.removeFileExtensions())!
}
var file : XGFiles!
init(file: XGFiles, index: Int, startOffset: Int) {
super.init()
self.index = index
self.startOffset = startOffset
self.file = file
let data = file.data!
self.xCoordinate = data.getWordAtOffset(startOffset + kILXOffset).hexToSignedFloat()
self.yCoordinate = data.getWordAtOffset(startOffset + kILYOffset).hexToSignedFloat()
self.zCoordinate = data.getWordAtOffset(startOffset + kILZOffset).hexToSignedFloat()
self.angle = data.get2BytesAtOffset(startOffset + kIPAngleOffset)
}
func save() {
let data = file.data!
data.replace2BytesAtOffset(startOffset + kIPAngleOffset, withBytes: self.angle)
data.replaceWordAtOffset(startOffset + kILXOffset, withBytes: self.xCoordinate.bitPattern)
data.replaceWordAtOffset(startOffset + kILYOffset, withBytes: self.yCoordinate.bitPattern)
data.replaceWordAtOffset(startOffset + kILZOffset, withBytes: self.zCoordinate.bitPattern)
data.save()
}
}
extension XGInteractionPointData: XGEnumerable {
var enumerableName: String {
return "Interaction Point " + String(format: "%03d", index)
}
var enumerableValue: String? {
return nil
}
static var className: String {
return "Interaction Points"
}
static var allValues: [XGInteractionPointData] {
var values = [XGInteractionPointData]()
for i in 0 ..< CommonIndexes.NumberOfInteractionPoints.value {
values.append(XGInteractionPointData(index: i))
}
return values
}
}
extension XGElevatorDirections: XGEnumerable {
var enumerableName: String {
return string
}
var enumerableValue: String? {
return rawValue.string
}
static var className: String {
return "Elevator Directions"
}
static var allValues: [XGElevatorDirections] {
return [.up, .down]
}
}
| 32e574e82b09a8570e818c687a62f20d | 34.89485 | 148 | 0.742333 | false | false | false | false |
dehesa/Utilities | refs/heads/master | Sources/Apple/Visuals/Views/AnimatableView.swift | mit | 2 | #if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
#if os(iOS) || os(tvOS)
open class AnimatableView<Layer:CALayer>: UIView where Layer:Animatable {
open override static var layerClass : AnyClass {
return Layer.self
}
open override func willMove(toWindow newWindow: UIWindow?) {
guard let screen = newWindow?.screen else { return }
layer.contentsScale = screen.scale
layer.setNeedsLayout()
}
}
#elseif os(macOS)
open class AnimatableView<Layer:CALayer>: NSView where Layer:Animatable {
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.layer = self.makeBackingLayer()
self.wantsLayer = true
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.layer = self.makeBackingLayer()
self.wantsLayer = true
}
open override func makeBackingLayer() -> CALayer {
return Layer()
}
open override func viewDidChangeBackingProperties() {
guard let scale = self.window?.backingScaleFactor,
let layer = self.layer else { return }
layer.contentsScale = scale
layer.setNeedsLayout()
}
}
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension AnimatableView: Animatable {
public var isAnimating: Bool {
return (self.layer as! Animatable).isAnimating
}
public func startAnimating(withDuration duration: TimeInterval?) {
(self.layer as! Animatable).startAnimating(withDuration: duration)
}
public func stopAnimating() {
(self.layer as! Animatable).stopAnimating()
}
}
#endif
| af3e75aae0223ef870dc9553c43c5bfb | 26.639344 | 74 | 0.648873 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/Root/Service/ZSShelfWebService.swift | mit | 1 | //
// ZSShelfWebService.swift
// zhuishushenqi
//
// Created by yung on 2018/7/31.
// Copyright © 2018年 QS. All rights reserved.
//
import Foundation
import ZSAPI
class ZSShelfWebService: ZSBaseService {
func fetchShelvesUpdate(for ids:[String],completion:@escaping ZSBaseCallback<[BookShelf]>) {
let id = (ids as NSArray).componentsJoined(by: ",")
let api = ZSAPI.update(id: id)
zs_get(api.path, parameters: api.parameters).responseJSON { (response) in
if let data = response.data {
if let obj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [Any] {
if let models = [BookShelf].deserialize(from: obj) {
if let arr = models as? [BookShelf]{
completion(arr)
}
}
}
}
}
}
func fetchShelfMsg(_ completion:ZSBaseCallback<ZSShelfMessage>?) {
let shelfApi = ZSAPI.shelfMSG("" as AnyObject)
zs_get(shelfApi.path, parameters: shelfApi.parameters).responseJSON { (response) in
if let data = response.data {
if let obj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:Any] {
if let message = ZSShelfMessage.deserialize(from: obj["message"] as? [String:Any]) {
completion?(message)
} else {
completion?(nil)
}
} else {
completion?(nil)
}
} else {
completion?(nil)
}
}
}
func fetchShelvesUpdate(for books:[BookDetail],completion:ZSBaseCallback<Void>?) {
let id = getIDSOf(books: books)
let api = ZSAPI.update(id: id)
zs_get(api.path, parameters: api.parameters).responseJSON { (response) in
if let data = response.data {
if let obj = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [Any] {
}
}
}
}
func fetchBookshelf(token:String, completion:@escaping ZSBaseCallback<[ZSUserBookshelf]>) {
let api = ZSAPI.bookshelf(token: token)
zs_get(api.path, parameters: api.parameters) { (json) in
if let models = [ZSUserBookshelf].deserialize(from: json?["books"] as? [Any]) as? [ZSUserBookshelf] {
completion(models)
}
}
}
func fetchShelfDelete(urlString:String, param:[String:Any]? ,completion:@escaping ZSBaseCallback<[String:Any]>) {
zs_delete(urlString, parameters: param) { (json) in
completion(json)
}
}
func fetchShelfAdd(urlString:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[String:Any]>) {
zs_put(urlString, parameters: param) { (json) in
completion(json)
}
}
func fetchBookInfo(id:String, completion:@escaping ZSBaseCallback<BookDetail>) {
let api = ZSAPI.book(key: id)
zs_get(api.path, parameters: api.parameters) { (json) in
if let book = BookDetail.deserialize(from: json) {
completion(book)
}
}
}
func fetchBlessingBag(urlString:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[String:Any]>) {
zs_get(urlString, parameters: param) { (json) in
completion(json)
}
}
func fetchJudgeIn(urlString:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[String:Any]>) {
zs_get(urlString, parameters: param) { (json) in
completion(json)
}
}
func fetchSignIn(urlString:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[String:Any]>) {
zs_get(urlString, parameters: param) { (json) in
completion(json)
}
}
private func getIDSOf(books:[BookDetail]) ->String{
var id = ""
for book in books {
if (book._id != "") {
if id != "" {
id.append(",")
}
id.append(book._id)
}
}
return id
}
}
| 5da5a783f2a90f905e9363c61beed3ec | 35.5 | 151 | 0.55064 | false | false | false | false |
edouardjamin/30daysSwift | refs/heads/master | Day 07 - PullToRefresh/PullToRefresh/ViewController.swift | mit | 1 | //
// ViewController.swift
// PullToRefresh
//
// Created by Edouard Jamin on 29/02/16.
// Copyright © 2016 Edouard Jamin. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Interface
@IBOutlet weak var tableView: UITableView!
// Prototypes
let emojis = ["😋", "😑", "❤️", "🎉", "😇", "🙈", "😂", "✈️", "☺️", "😘", "😛", "😍", "😎", "😀", "😌", "💩"]
var lastRefresh = NSDate()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.addSubview(self.refreshControl)
// Set up attributes for refresh
// Custom last refresh
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.Hour.union(NSCalendarUnit.Minute), fromDate: lastRefresh)
let attributes = [NSBackgroundColorAttributeName: UIColor(red:0.13, green:0.15, blue:0.16, alpha:1), NSForegroundColorAttributeName: UIColor.blackColor()]
self.refreshControl.attributedTitle = NSAttributedString(string: "Last refresh at \(components.hour):\(components.minute)", attributes: attributes)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Table Views Configs
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emojis.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! CustomCell
let random_emoji = emojis[Int(floor(drand48() * Double(emojis.count)))]
cell.titleLabel.text = "\(random_emoji)\(random_emoji)\(random_emoji)\(random_emoji)\(random_emoji)"
return cell
}
// Pull to refresh
func handleRefresh(refresh :AnyObject) {
self.tableView.reloadData()
lastRefresh = NSDate()
refreshControl.endRefreshing()
}
// Pull-to-refresh
lazy var refreshControl :UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
return refreshControl
}()
// Black Selection set up
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell :UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor.blackColor()
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let selectedCell :UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor.blackColor()
return indexPath
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell :UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor(red:0.13, green:0.15, blue:0.16, alpha:1)
}
// Status bar
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| 3c177649a16345f6bafda911a2668217 | 33.967033 | 156 | 0.7489 | false | false | false | false |
SquidKit/SquidKit | refs/heads/master | SquidKit/EmbossedText.swift | mit | 1 | //
// EmbossedText.swift
// SquidKit
//
// Created by Mike Leavy on 10/26/18.
// Copyright © 2018-2019 Squid Store, LLC. All rights reserved.
//
import UIKit
public struct EmbossedText {
public static func emboss(_ text: String, font: UIFont, color: UIColor, texture: UIImage, useHeightMap: Bool) -> UIImage? {
let styled = StyledString().pushFont(font).pushColor(color).pushString(text)
return emboss(styled.attributedString, texture: texture, useHeightMap: useHeightMap)
}
public static func emboss(_ text: NSAttributedString, texture: UIImage, useHeightMap: Bool) -> UIImage? {
let image = UIImage
.image(from: text)?
.applyEmboss(shadingImage: texture, useHeightMap: useHeightMap)
return image
}
}
public extension UIImage {
class func image(from string: String, attributes: [NSAttributedString.Key: Any]?, size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
string.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func image(from string: NSAttributedString) -> UIImage? {
let size = string.size()
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
string.draw(with: rect, options: .usesLineFragmentOrigin, context: nil)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func applyEmboss(shadingImage: UIImage, useHeightMap: Bool = true) -> UIImage {
// Create filters
guard let shadedMaterialFilter = CIFilter(name: "CIShadedMaterial") else { return self }
if useHeightMap {
guard let heightMapFilter = CIFilter(name: "CIHeightFieldFromMask") else { return self }
heightMapFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
guard let heightMapFilterOutput = heightMapFilter.outputImage else { return self }
shadedMaterialFilter.setValue(heightMapFilterOutput, forKey: kCIInputImageKey)
}
else {
shadedMaterialFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
}
shadedMaterialFilter.setValue(CIImage(image: shadingImage), forKey: "inputShadingImage")
// Output
guard let filteredImage = shadedMaterialFilter.outputImage else { return self }
return UIImage(ciImage: filteredImage)
}
}
| 2ebbfac72489f1e7c98082748e7a7fc6 | 41.6 | 127 | 0.676417 | false | false | false | false |
JGiola/swift | refs/heads/main | SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift | apache-2.0 | 4 | //===--- SubstitutionMap.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct SubstitutionMap {
public let bridged: BridgedSubstitutionMap
public init(_ bridged: BridgedSubstitutionMap) {
self.bridged = bridged
}
public init() {
self.bridged = SubstitutionMap_getEmpty();
}
}
| b3c35a2e980e40f4dfcf79509efca6c0 | 29.96 | 80 | 0.605943 | false | false | false | false |
catloafsoft/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Filters/Tone Filter/AKToneFilter.swift | mit | 1 | //
// AKToneFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// A first-order recursive low-pass filter with variable frequency response.
///
/// - parameter input: Input node to process
/// - parameter halfPowerPoint: The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2.
///
public class AKToneFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKToneFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var halfPowerPointParameter: AUParameter?
/// The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2.
public var halfPowerPoint: Double = 1000 {
willSet(newValue) {
if halfPowerPoint != newValue {
halfPowerPointParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter halfPowerPoint: The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2.
///
public init(
_ input: AKNode,
halfPowerPoint: Double = 1000) {
self.halfPowerPoint = halfPowerPoint
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x746f6e65 /*'tone'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKToneFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKToneFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKToneFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
halfPowerPointParameter = tree.valueForKey("halfPowerPoint") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.halfPowerPointParameter!.address {
self.halfPowerPoint = Double(value)
}
}
}
halfPowerPointParameter?.setValue(Float(halfPowerPoint), originator: token!)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| c932ab80080fc70f1209da75ce2da6ef | 31.45283 | 130 | 0.644767 | false | false | false | false |
VoIPGRID/vialer-ios | refs/heads/master | Vialer/Helpers/SegueHandler.swift | gpl-3.0 | 1 | //
// UIViewController.swift
// Copyright © 2017 VoIPGRID. All rights reserved.
//
import Foundation
protocol SegueHandler {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandler where Self : UIViewController, SegueIdentifier.RawValue == String {
func performSegue(segueIdentifier: SegueIdentifier, sender: Any? = nil) {
DispatchQueue.main.async {
self.performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
}
func segueIdentifier(segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier)
else { fatalError("Unknown segue: \(segue))") }
return segueIdentifier
}
}
| a81ff92ffdf88e2e1d429a2ea1cf77eb | 30.44 | 90 | 0.70229 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/Generics/superclass_constraint.swift | apache-2.0 | 8 | // RUN: %target-parse-verify-swift
// RUN: %target-parse-verify-swift -parse -debug-generic-signatures %s > %t.dump 2>&1
// RUN: FileCheck %s < %t.dump
class A {
func foo() { }
}
class B : A {
func bar() { }
}
class Other { }
func f1<T : A where T : Other>(_: T) { } // expected-error{{generic parameter 'T' cannot be a subclass of both 'A' and 'Other'}}
func f2<T : A where T : B>(_: T) { }
class GA<T> {}
class GB<T> : GA<T> {}
protocol P {}
func f3<T, U where U : GA<T>>(_: T, _: U) {}
func f4<T, U where U : GA<T>>(_: T, _: U) {}
func f5<T, U : GA<T>>(_: T, _: U) {}
func f6<U : GA<T>, T : P>(_: T, _: U) {}
func f7<U, T where U : GA<T>, T : P>(_: T, _: U) {}
func f8<T : GA<A> where T : GA<B>>(_: T) { } // expected-error{{generic parameter 'T' cannot be a subclass of both 'GA<A>' and 'GA<B>'}}
func f9<T : GA<A> where T : GB<A>>(_: T) { }
func f10<T : GB<A> where T : GA<A>>(_: T) { }
func f11<T : GA<T>>(_: T) { } // expected-error{{superclass constraint 'GA<T>' is recursive}}
func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } // expected-error{{superclass constraint 'GA<U>' is recursive}}
func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{inheritance from non-protocol, non-class type 'U'}}
// rdar://problem/24730536
// Superclass constraints can be used to resolve nested types to concrete types.
protocol P3 {
associatedtype T
}
protocol P2 {
associatedtype T : P3
}
class C : P3 {
typealias T = Int
}
class S : P2 {
typealias T = C
}
extension P2 where Self.T : C {
// CHECK: superclass_constraint.(file).P2.concreteTypeWitnessViaSuperclass1
// CHECK: Generic signature: <Self where Self : P2, Self.T : C, Self.T : P3, Self.T.T == T>
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P2, τ_0_0.T : C, τ_0_0.T : P3, τ_0_0.T.T == Int>
func concreteTypeWitnessViaSuperclass1(x: Self.T.T) {}
}
// CHECK: superclassConformance1
// CHECK: Requirements:
// CHECK-NEXT: T witness marker
// CHECK-NEXT: T : C [explicit @
// CHECK-NEXT: T : P3 [redundant @
// CHECK-NEXT: T[.P3].T == T [protocol]
// CHECK: Canonical generic signature for mangling: <τ_0_0 where τ_0_0 : C>
func superclassConformance1<T where T : C, T : P3>(t: T) { }
// CHECK: superclassConformance2
// CHECK: Requirements:
// CHECK-NEXT: T witness marker
// CHECK-NEXT: T : C [explicit @
// CHECK-NEXT: T : P3 [redundant @
// CHECK-NEXT: T[.P3].T == T [protocol]
// CHECK: Canonical generic signature for mangling: <τ_0_0 where τ_0_0 : C>
func superclassConformance2<T where T : C, T : P3>(t: T) { }
protocol P4 { }
class C2 : C, P4 { }
// CHECK: superclassConformance3
// CHECK: Requirements:
// CHECK-NEXT: T witness marker
// CHECK-NEXT: T : C2 [explicit @
// CHECK-NEXT: T : P4 [redundant @
// CHECK: Canonical generic signature for mangling: <τ_0_0 where τ_0_0 : C2>
func superclassConformance3<T where T : C, T : P4, T : C2>(t: T) { }
| a0b6e89e30c5063982a982591c6d5b88 | 29.924731 | 136 | 0.610223 | false | false | false | false |
peaks-cc/iOS11_samplecode | refs/heads/master | chapter_12/HomeKitSample/App/Code/Controller/HomesViewController.swift | mit | 1 | //
// HomesViewController.swift
//
// Created by ToKoRo on 2017-08-18.
//
import UIKit
import HomeKit
class HomesViewController: UITableViewController {
lazy var homeManager: HMHomeManager = HMHomeManager.shared
var homes: [HMHome] { return homeManager.homes }
var selectedHome: HMHome?
override func viewDidLoad() {
super.viewDidLoad()
homeManager.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "Home"?:
sendContext(selectedHome, to: segue.destination)
default:
break
}
}
func refresh() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func home(at indexPath: IndexPath) -> HMHome? {
return homes.safe[indexPath.row]
}
@IBAction func addButtonDidTap(sender: AnyObject) {
let alert = UIAlertController(title: nil, message: "追加するHomeの名前を入力してください", preferredStyle: .alert)
alert.addTextField()
alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
guard
let name = alert.textFields?.first?.text,
name.count > 0
else {
return
}
self?.handleNewHome(withName: name)
})
alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel))
present(alert, animated: true)
}
func handleNewHome(withName name: String) {
homeManager.addHome(withName: name) { home, error in
if let home = home {
print("# added: \(home)")
self.refresh()
}
if let error = error {
print("# error: \(error)")
}
}
}
}
// MARK: - HomeActionHandler
extension HomesViewController: HomeActionHandler {
func handleRemove(_ home: HMHome) {
homeManager.removeHome(home) { [weak self] error in
if let error = error {
print("# error: \(error)")
}
self?.refresh()
}
}
func handleMakePrimary(_ home: HMHome) {
homeManager.updatePrimaryHome(home) { [weak self] error in
if let error = error {
print("# error: \(error)")
}
self?.refresh()
}
}
}
// MARK: - UITableViewDataSource
extension HomesViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Home", for: indexPath)
if let home = home(at: indexPath) {
cell.textLabel?.text = home.name
cell.detailTextLabel?.text = home.isPrimary ? "primary" : nil
}
return cell
}
}
// MARK: - UITableViewDelegate
extension HomesViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer { tableView.deselectRow(at: indexPath, animated: true) }
self.selectedHome = home(at: indexPath)
performSegue(withIdentifier: "Home", sender: nil)
}
}
// MARK: - HMHomeManagerDelegate
extension HomesViewController: HMHomeManagerDelegate {
func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {
print("# homeManagerDidUpdateHomes")
// 起動直後?に一度呼ばれた
// これが呼ばれるまでhomeManager.primaryHomeはnil
// 1つめのHomeをaddした時には呼ばれなかった
// 2つめのHomeをaddした時には呼ばれなかった
refresh()
}
func homeManagerDidUpdatePrimaryHome(_ manager: HMHomeManager) {
print("# homeManagerDidUpdatePrimaryHome")
// 1つめのHomeをaddした時に呼ばれた
// primaryなHomeを削除した時に呼ばれた
}
func homeManager(_ manager: HMHomeManager, didAdd home: HMHome) {
print("# homeManager didAdd home")
// Homeを追加しても呼ばれない?
}
func homeManager(_ manager: HMHomeManager, didRemove home: HMHome) {
print("# homeManager didRemove home")
}
}
| 8483cccd357eefe01a401d6d69e6fc4c | 26.018868 | 109 | 0.605912 | false | false | false | false |
mthud/MorphingLabel | refs/heads/master | MorphingLabel+Anvil.swift | mit | 1 | //
// MorphingLabel+Anvil.swift
// https://github.com/mthud/MorphingLabel
//
import UIKit
extension MorphingLabel {
func AnvilLoad() {
startClosures["Anvil\(MorphingPhases.start)"] = {
self.emitterView.removeAllEmitters()
guard self.newRects.count > 0 else { return }
let centerRect = self.newRects[Int(self.newRects.count / 2)]
_ = self.emitterView.createEmitter (
"leftSmoke",
particleName: "Smoke",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: 1, height: 1)
layer.emitterPosition = CGPoint(x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3)
layer.renderMode = kCAEmitterLayerSurface
cell.emissionLongitude = CGFloat(Double.pi / 2)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 130
cell.birthRate = 60
cell.velocity = CGFloat(80 + Int(arc4random_uniform(60)))
cell.velocityRange = 100
cell.yAcceleration = -40
cell.xAcceleration = 70
cell.emissionLongitude = CGFloat(-Double.pi / 2)
cell.emissionRange = CGFloat(Double.pi / 4) / 5.0
cell.lifetime = self.morphingDuration * 2.0
cell.spin = 10
cell.alphaSpeed = -0.5 / self.morphingDuration
}
_ = self.emitterView.createEmitter (
"rightSmoke",
particleName: "Smoke",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: 1, height: 1)
layer.emitterPosition = CGPoint(x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3)
layer.renderMode = kCAEmitterLayerSurface
cell.emissionLongitude = CGFloat(Double.pi / 2)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 130
cell.birthRate = 60
cell.velocity = CGFloat(80 + Int(arc4random_uniform(60)))
cell.velocityRange = 100
cell.yAcceleration = -40
cell.xAcceleration = -70
cell.emissionLongitude = CGFloat(Double.pi / 2)
cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0
cell.lifetime = self.morphingDuration * 2.0
cell.spin = -10
cell.alphaSpeed = -0.5 / self.morphingDuration
}
_ = self.emitterView.createEmitter(
"leftFragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: self.font.pointSize, height: 1)
layer.emitterPosition = CGPoint(x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.cgColor
cell.birthRate = 60
cell.velocity = 350
cell.yAcceleration = 0
cell.xAcceleration = CGFloat(10 * Int(arc4random_uniform(10)))
cell.emissionLongitude = CGFloat(-Double.pi / 2)
cell.emissionRange = CGFloat(Double.pi / 4) / 5.0
cell.alphaSpeed = -2
cell.lifetime = self.morphingDuration
}
_ = self.emitterView.createEmitter (
"rightFragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: self.font.pointSize, height: 1)
layer.emitterPosition = CGPoint(x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.cgColor
cell.birthRate = 60
cell.velocity = 350
cell.yAcceleration = 0
cell.xAcceleration = CGFloat(-10 * Int(arc4random_uniform(10)))
cell.emissionLongitude = CGFloat(Double.pi / 2)
cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0
cell.alphaSpeed = -2
cell.lifetime = self.morphingDuration
}
_ = self.emitterView.createEmitter(
"fragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: self.font.pointSize, height: 1)
layer.emitterPosition = CGPoint(x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.cgColor
cell.birthRate = 60
cell.velocity = 250
cell.velocityRange = CGFloat(Int(arc4random_uniform(20)) + 30)
cell.yAcceleration = 500
cell.emissionLongitude = 0
cell.emissionRange = CGFloat(Double.pi / 2)
cell.alphaSpeed = -1
cell.lifetime = self.morphingDuration
}
}
progressClosures["Anvil\(MorphingPhases.progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if (!isNewChar) {
return min(1.0, max(0.0, progress))
}
let j = Float(sin(Float(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j))
}
effectClosures["Anvil\(MorphingPhases.disappear)"] = {
char, index, progress in
return CharacterLimbo (
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
effectClosures["Anvil\(MorphingPhases.appear)"] = {
char, index, progress in
var rect = self.newRects[index]
if (progress < 1.0) {
let easingValue = Easing.easeOutBounce(progress, 0.0, 1.0)
rect.origin.y = CGFloat(Float(rect.origin.y) * easingValue)
}
if (progress > self.morphingDuration * 0.5)
{
let end = self.morphingDuration * 0.55
self.emitterView.createEmitter (
"fragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update { (layer, _) in
if (progress > end) {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter (
"leftFragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update { (layer, _) in
if (progress > end) {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter (
"rightFragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update { (layer, _) in
if (progress > end) {
layer.birthRate = 0
}
}.play()
}
if (progress > self.morphingDuration * 0.63)
{
let end = self.morphingDuration * 0.7
self.emitterView.createEmitter (
"leftSmoke",
particleName: "Smoke",
duration: 0.6
) {_ in}.update { (layer, _) in
if (progress > end) {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter (
"rightSmoke",
particleName: "Smoke",
duration: 0.6
) {_ in}.update { (layer, _) in
if (progress > end) {
layer.birthRate = 0
}
}.play()
}
return CharacterLimbo (
char: char,
rect: rect,
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress)
)
}
}
}
| 419cf9ba9231ad8841f87b50d9d1e74f | 40.159292 | 126 | 0.470114 | false | false | false | false |
quadro5/swift3_L | refs/heads/master | swift_question.playground/Pages/Let91 Decode ways.xcplaygroundpage/Contents.swift | unlicense | 1 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
/// Version 1, roll array
class Solution {
func numDecodings(_ s: String) -> Int {
if s.isEmpty {
return 0
}
let base = String("0").utf8.map { Int($0) }
let strs = s.utf8.map { Int($0) - base[0] }
let len = strs.count
var cur = 1
var prev = 0
var i = 0
while i < len {
// for 0
if strs[i] == 0 {
cur = 0
}
// for 11--26
if i > 0 && ((strs[i-1] != 0 && strs[i-1] < 2) || (strs[i-1] == 2 && strs[i] < 7)) {
cur = prev + cur
prev = cur - prev
// other single num
} else {
prev = cur
}
i += 1
}
return cur
}
}
/// Version 2 DP
class Solution2 {
func numDecodings(_ s: String) -> Int {
if s.isEmpty {
return 0
}
let base = String("0").utf8.map { Int($0) }
let strs = s.utf8.map { Int($0) - base[0] }
let len = strs.count
var dp = Array<Int>(repeating: 0, count: len+1)
dp[0] = 1
var i = 1
while i < len + 1 {
// for 0
if strs[i-1] == 0 {
dp[i-1] = 0
}
// for 11--26
if i > 1 && ((strs[i-2] != 0 && strs[i-2] < 2) || (strs[i-2] == 2 && strs[i-1] < 7)) {
//cur = prev + cur
//prev = cur - prev
dp[i] = dp[i-2] + dp[i-1]
// other single num
} else {
//prev = cur
dp[i] = dp[i-1]
}
i += 1
}
return dp[len]
}
}
| b8b9f415ea2f7f8e7c11fe095358c3e4 | 22.141026 | 98 | 0.362327 | false | false | false | false |
stomp1128/TIY-Assignments | refs/heads/master | 22-Dude-Where's-My-Car?/22-Dude-Where's-My-Car?/MapViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// 22-Dude-Where's-My-Car?
//
// Created by Chris Stomp on 11/3/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
let kLocationsKey = "locations"
protocol LocationPopoverViewControllerDelegate //step 31
{
func locationWasChosen(location: Location)
}
class MapViewController: UIViewController, CLLocationManagerDelegate, UIPopoverPresentationControllerDelegate, LocationPopoverViewControllerDelegate
{
var locations = Array<Location>()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "showPopoverSegue"
{
let destinationViewController = segue.destinationViewController as!LocationPopoverViewController
destinationViewController.popoverPresentationController?.delegate = self
destinationViewController.delegate = self //step 33
destinationViewController.preferredContentSize = CGSizeMake(200.0, 100.0)
}
}
func locationWasChosen(location: Location)
{
navigationController?.dismissViewControllerAnimated(true, completion: nil)
locations.append(location)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return .None
}
//MARK: - Misc.
func loadLocationData() //step 15
{
if let data = NSUserDefaults.standardUserDefaults().objectForKey(kLocationsKey) as? NSData
{
if let savedLocations = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Location]
{
locations = savedLocations
//reloadData()
}
}
}
func saveLocationData() //step 13
{
let locationData = NSKeyedArchiver.archivedDataWithRootObject(locations)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: kLocationsKey)
}
}
| 693e8db8c987fcf6c9ddc4ecea5ac814 | 26.568182 | 148 | 0.674361 | false | false | false | false |
marwen86/NHtest | refs/heads/master | NHTest/NHTest/Model/NHImageModel.swift | mit | 1 | //
// NHImageModel.swift
// NHTest
//
// Created by Mohamed Marouane YOUSSEF on 07/10/2017.
// Copyright © 2017 Mohamed Marouane YOUSSEF. All rights reserved.
//
import UIKit
public struct NHImageModel {
var comments : Int
var downloads : Int
var favorites : Int
var id : Int
var imageHeight : Int
var imageWidth : Int
var likes : Int
var pageURL : String
var previewHeight : Int
var previewURL : String
var previewWidth : Int
var type : String
var user : String
var userImageURL : String
var tags : String
var user_id : Int
var views : Int
var webformatHeight : Int
var webformatURL : String
var webformatWidth : Int
}
extension NHImageModel: Equatable {
public /// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func ==(lhs: NHImageModel, rhs: NHImageModel) -> Bool {
return true
}
}
| fd3c10608871b3ad63745193310e83ea | 22.42 | 79 | 0.624253 | false | false | false | false |
qingtianbuyu/Mono | refs/heads/master | Moon/Classes/Main/Model/MNModEntityList.swift | mit | 1 | //
// MNModEntityList.swift
// Moon
//
// Created by YKing on 16/6/4.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNModEntityList {
var start: String?
var top_banner: MNBannerEntity?
var mod_list: [MNModEntity]?
func loadModData() {
mod_list = [MNModEntity]()
loadWithPlist("new-explore1.plist")
loadWithPlist("new-explore2.plist")
loadWithPlist("new-explore3.plist")
loadWithPlist("new-explore4.plist")
loadWithPlist("new-explore5.plist")
}
func loadWithPlist(_ path: String) {
var modArray = [MNModEntity]()
let path = Bundle.main.path(forResource: path, ofType: nil)
let modEntityListDict = NSDictionary(contentsOfFile:path!) as! [String: AnyObject]
let modDictArray = modEntityListDict["mod_list"] as! NSArray
for modEntityDict in modDictArray {
let mod = (modEntityDict as! [String: AnyObject])
modArray.append(MNModEntity(dict:mod))
}
mod_list?.append(contentsOf: modArray)
guard let bannerDict = (modEntityListDict["top_banner"] as? [String: AnyObject]) else {
return
}
top_banner = MNBannerEntity(dict: bannerDict)
}
}
| 01aa2f2caa1fa0b300f2d3da6f274dcb | 26.4 | 94 | 0.64558 | false | false | false | false |
criticalmaps/criticalmaps-ios | refs/heads/main | CriticalMapsKit/Sources/SettingsFeature/RideEventSettingsCore.swift | mit | 1 | import ComposableArchitecture
import Helpers
import SharedModels
public struct RideEventsSettingsFeature: ReducerProtocol {
public init() {}
public typealias State = SharedModels.RideEventSettings
// MARK: Actions
public enum Action: Equatable {
case setRideEventsEnabled(Bool)
case setRideEventTypeEnabled(RideEventSettings.RideEventTypeSetting)
case setRideEventRadius(EventDistance)
}
public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> {
switch action {
case let .setRideEventsEnabled(value):
state.isEnabled = value
return .none
case let .setRideEventTypeEnabled(type):
guard let index = state.typeSettings.firstIndex(where: { $0.type == type.type }) else {
return .none
}
state.typeSettings[index].isEnabled = type.isEnabled
return .none
case let .setRideEventRadius(distance):
state.eventDistance = distance
return .none
}
}
}
| dce33f8bf19bf6c5759481afdb81c4e2 | 26.111111 | 93 | 0.716189 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | packages/TGUIKit/Sources/System.swift | gpl-2.0 | 1 | //
// System.swift
// TGUIKit
//
// Created by keepcoder on 08/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import AVFoundation
public weak var mw:Window?
public var mainWindow:Window {
if let window = NSApp.keyWindow as? Window {
return window
} else if let window = NSApp.mainWindow as? Window {
return window
} else if let mw = mw {
return mw
}
fatalError("window not found")
}
public struct System {
public static var legacyMenu: Bool = true
private static var scaleFactor: Atomic<CGFloat> = Atomic(value: 2.0)
private static var safeScaleFactor: CGFloat = 2.0
public static func updateScaleFactor(_ value: CGFloat) {
_ = scaleFactor.modify { _ in
safeScaleFactor = value
return value
}
}
public static var isRetina:Bool {
get {
return safeScaleFactor >= 2.0
}
}
public static var backingScale:CGFloat {
return safeScaleFactor
}
public static var aspectRatio: CGFloat {
let frame = NSScreen.main?.frame ?? .zero
let preferredAspectRatio = CGFloat(frame.width / frame.height)
return preferredAspectRatio
}
public static var cameraAspectRatio: CGFloat {
let device = AVCaptureDevice.default(for: .video)
let description = device?.activeFormat.formatDescription
if let description = description {
let dimension = CMVideoFormatDescriptionGetDimensions(description)
return CGFloat(dimension.width) / CGFloat(dimension.height)
}
return aspectRatio
}
public static var drawAsync:Bool {
return false
}
public static var isScrollInverted: Bool {
if UserDefaults.standard.value(forKey: "com.apple.swipescrolldirection") != nil {
return UserDefaults.standard.bool(forKey: "com.apple.swipescrolldirection")
} else {
return true
}
}
public static var supportsTransparentFontDrawing: Bool {
if #available(OSX 10.15, *) {
return true
} else {
return System.backingScale > 1.0
}
}
}
public var uiLocalizationFunc:((String)->String)?
public func localizedString(_ key:String) -> String {
if let uiLocalizationFunc = uiLocalizationFunc {
return uiLocalizationFunc(key)
} else {
return NSLocalizedString(key, comment: "")
}
}
//public func localizedString(_ key:String, countable:Int = 0, apply:Bool = true) -> String {
// let suffix:String
// if countable == 1 {
// suffix = ".singular"
// } else if countable > 1 {
// suffix = ".pluar"
// } else {
// suffix = ".zero"
// }
// if apply {
// return String(format: localizedString(key + suffix), countable)
// } else {
// return localizedString(key + suffix)
// }
//}
public func reverseIndexList<T>(_ list:[(Int,T,Int?)], _ previousCount:Int, _ updateCount:Int) -> [(Int,T,Int?)] {
var reversed:[(Int,T,Int?)] = []
for (int1,obj,int2) in list.reversed() {
if let s = int2 {
reversed.append((updateCount - int1 - 1,obj, previousCount - s - 1))
} else {
reversed.append((updateCount - int1 - 1,obj, nil))
}
}
return reversed
}
public func reverseIndexList<T>(_ list:[(Int,T)], _ previousCount:Int, _ updateCount:Int) -> [(Int,T)] {
var reversed:[(Int,T)] = []
for (int1,obj) in list.reversed() {
reversed.append((updateCount - int1 - 1,obj))
}
return reversed
}
public func reverseIndexList<T>(_ list:[(Int,T,Int)], _ previousCount:Int, _ updateCount:Int) -> [(Int,T,Int)] {
var reversed:[(Int,T,Int)] = []
for (int1,obj,int2) in list.reversed() {
reversed.append((updateCount - int1 - 1,obj, previousCount - int2 - 1))
}
return reversed
}
public func reverseIndexList(_ list:[Int], _ count:Int) -> [Int] {
var reversed:[(Int)] = []
for int1 in list.reversed() {
reversed.append(count - int1 - 1)
}
return reversed
}
public func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
public func delay(_ delay:Double, onQueue queue: DispatchQueue, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
queue.asyncAfter(deadline: when, execute: closure)
}
public func delaySignal(_ value:Double) -> Signal<NoValue, NoError> {
return .complete() |> delay(value, queue: .mainQueue())
}
| 927af9c7f9a33ff9749187da762a87d0 | 27.161677 | 114 | 0.609398 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/UnsafeBufferPointer+Shims.swift | apache-2.0 | 3 | // Sources/SwiftProtobuf/UnsafeBufferPointer+Shims.swift - Shims for UnsafeBufferPointer
//
// Copyright (c) 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Shims for UnsafeBufferPointer
///
// -----------------------------------------------------------------------------
extension UnsafeMutableBufferPointer {
#if !swift(>=4.2)
internal static func allocate(capacity: Int) -> UnsafeMutableBufferPointer<Element> {
let pointer = UnsafeMutablePointer<Element>.allocate(capacity: capacity)
return UnsafeMutableBufferPointer(start: pointer, count: capacity)
}
#endif
#if !swift(>=4.1)
internal func deallocate() {
self.baseAddress?.deallocate(capacity: self.count)
}
#endif
}
extension UnsafeMutableRawBufferPointer {
#if !swift(>=4.1)
internal func copyMemory<C: Collection>(from source: C) where C.Element == UInt8 {
self.copyBytes(from: source)
}
#endif
}
| 69e2b463c15ad64f2be04176ba8d860b | 31.621622 | 89 | 0.612262 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/type/infer/instance_variables.swift | apache-2.0 | 6 | // RUN: %target-parse-verify-swift
struct X {
var b = true, i = 17
var d : Dictionary = [0 : "Zero", 1 : "One", 2 : "Two" ]
}
func testX(inout x: X) {
x.b = false
x.i = 5
x.d[3] = "Three"
}
struct Broken {
var b = True // expected-error{{use of unresolved identifier 'True'}}
}
| 839e2be2e6c1f0eea267c9504a6d547a | 15.5 | 72 | 0.558923 | false | true | false | false |
BrandonMA/SwifterUI | refs/heads/master | SwifterUI/SwifterUI/UILibrary/Views/SFTextView.swift | mit | 1 | //
// SFTextView.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 06/02/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
open class SFTextView: UITextView, SFViewColorStyle {
// MARK: - Instance Properties
open var automaticallyAdjustsColorStyle: Bool = false
open var useAlternativeColors: Bool = false
// MARK: - Initializers
public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero) {
self.automaticallyAdjustsColorStyle = automaticallyAdjustsColorStyle
self.useAlternativeColors = useAlternativeColors
super.init(frame: frame, textContainer: nil)
if automaticallyAdjustsColorStyle {
updateColors()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open func updateColors() {
backgroundColor = useAlternativeColors ? colorStyle.contrastColor : colorStyle.alternativeColor
textColor = colorStyle.textColor
keyboardAppearance = colorStyle.keyboardStyle
updateSubviewsColors()
}
}
| 5c6837d8b8b9d70fb19617ff6271f669 | 27.931818 | 121 | 0.67557 | false | false | false | false |
fancymax/12306ForMac | refs/heads/master | 12306ForMac/Model/MainModel.swift | mit | 1 | //
// MainModel.swift
// 12306ForMac
//
// Created by fancymax on 15/10/6.
// Copyright © 2015年 fancy. All rights reserved.
//
import Foundation
class MainModel{
static var realName = ""
static var userName = ""
static var isGetUserInfo = false
static var passengers = [PassengerDTO]()
static var selectPassengers = [PassengerDTO]()
static var isGetPassengersInfo = false
static var selectedTicket:QueryLeftNewDTO?
static var orderId:String?
static var globalRepeatSubmitToken:String = ""
static var key_check_isChange:String?
static var train_location:String?
static var trainDate:String?
static var historyOrderList:[OrderDTO] = []
static var noCompleteOrderList:[OrderDTO] = []
}
| 731ee932c4fac5cfc5cfd073da3a0495 | 22.515152 | 50 | 0.679124 | false | false | false | false |
Antondomashnev/Sourcery | refs/heads/master | SourceryTests/Generating/StencilTemplateSpec.swift | mit | 1 | import Quick
import Nimble
import PathKit
import Stencil
@testable import Sourcery
@testable import SourceryRuntime
class StencilTemplateSpec: QuickSpec {
override func spec() {
describe("StencilTemplate") {
func generate(_ template: String) -> String {
let arrayAnnotations = Variable(name: "annotated", typeName: TypeName("MyClass"))
arrayAnnotations.annotations = ["Foo": ["Hello", "World"] as NSArray]
let singleAnnotation = Variable(name: "annotated", typeName: TypeName("MyClass"))
singleAnnotation.annotations = ["Foo": "HelloWorld" as NSString]
return (try? Generator.generate(Types(types: [
Class(name: "MyClass", variables: [
Variable(name: "lowerFirst", typeName: TypeName("myClass")),
Variable(name: "upperFirst", typeName: TypeName("MyClass")),
arrayAnnotations,
singleAnnotation
])
]), template: StencilTemplate(templateString: template))) ?? ""
}
describe("toArray") {
context("given array") {
it("doesnt modify the value") {
let result = generate("{% for key,value in type.MyClass.variables.2.annotations %}{{ value | toArray }}{% endfor %}")
expect(result).to(equal("(\n Hello,\n World\n)"))
}
}
context("given something") {
it("transforms it into array") {
let result = generate("{% for key,value in type.MyClass.variables.3.annotations %}{{ value | toArray }}{% endfor %}")
expect(result).to(equal("[HelloWorld]"))
}
}
}
context("given string") {
it("generates upperFirst") {
expect(generate("{{\"helloWorld\" | upperFirst }}")).to(equal("HelloWorld"))
}
it("generates lowerFirst") {
expect(generate("{{\"HelloWorld\" | lowerFirst }}")).to(equal("helloWorld"))
}
it("generates uppercase") {
expect(generate("{{ \"HelloWorld\" | uppercase }}")).to(equal("HELLOWORLD"))
}
it("generates lowercase") {
expect(generate("{{ \"HelloWorld\" | lowercase }}")).to(equal("helloworld"))
}
it("generates capitalise") {
expect(generate("{{ \"helloWorld\" | capitalise }}")).to(equal("Helloworld"))
}
it("checks for string in name") {
expect(generate("{{ \"FooBar\" | contains:\"oo\" }}")).to(equal("true"))
expect(generate("{{ \"FooBar\" | contains:\"xx\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !contains:\"oo\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !contains:\"xx\" }}")).to(equal("true"))
}
it("checks for string in prefix") {
expect(generate("{{ \"FooBar\" | hasPrefix:\"Foo\" }}")).to(equal("true"))
expect(generate("{{ \"FooBar\" | hasPrefix:\"Bar\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !hasPrefix:\"Foo\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !hasPrefix:\"Bar\" }}")).to(equal("true"))
}
it("checks for string in suffix") {
expect(generate("{{ \"FooBar\" | hasSuffix:\"Bar\" }}")).to(equal("true"))
expect(generate("{{ \"FooBar\" | hasSuffix:\"Foo\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !hasSuffix:\"Bar\" }}")).to(equal("false"))
expect(generate("{{ \"FooBar\" | !hasSuffix:\"Foo\" }}")).to(equal("true"))
}
it("removes instances of a substring") {
expect(generate("{{\"helloWorld\" | replace:\"he\",\"bo\" | replace:\"llo\",\"la\" }}")).to(equal("bolaWorld"))
expect(generate("{{\"helloWorldhelloWorld\" | replace:\"hello\",\"hola\" }}")).to(equal("holaWorldholaWorld"))
expect(generate("{{\"helloWorld\" | replace:\"hello\",\"\" }}")).to(equal("World"))
expect(generate("{{\"helloWorld\" | replace:\"foo\",\"bar\" }}")).to(equal("helloWorld"))
}
}
context("given TypeName") {
it("generates upperFirst") {
expect(generate("{{ type.MyClass.variables.0.typeName | upperFirst }}")).to(equal("MyClass"))
}
it("generates lowerFirst") {
expect(generate("{{ type.MyClass.variables.1.typeName | lowerFirst }}")).to(equal("myClass"))
}
it("generates uppercase") {
expect(generate("{{ type.MyClass.variables.0.typeName | uppercase }}")).to(equal("MYCLASS"))
}
it("generates lowercase") {
expect(generate("{{ type.MyClass.variables.1.typeName | lowercase }}")).to(equal("myclass"))
}
it("generates capitalise") {
expect(generate("{{ type.MyClass.variables.1.typeName | capitalise }}")).to(equal("Myclass"))
}
it("checks for string in name") {
expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"my\" }}")).to(equal("true"))
expect(generate("{{ type.MyClass.variables.0.typeName | contains:\"xx\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"my\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !contains:\"xx\" }}")).to(equal("true"))
}
it("checks for string in prefix") {
expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"my\" }}")).to(equal("true"))
expect(generate("{{ type.MyClass.variables.0.typeName | hasPrefix:\"My\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"my\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !hasPrefix:\"My\" }}")).to(equal("true"))
}
it("checks for string in suffix") {
expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"Class\" }}")).to(equal("true"))
expect(generate("{{ type.MyClass.variables.0.typeName | hasSuffix:\"class\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"Class\" }}")).to(equal("false"))
expect(generate("{{ type.MyClass.variables.0.typeName | !hasSuffix:\"class\" }}")).to(equal("true"))
}
it("removes instances of a substring") {
expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"My\" | replace:\"Class\",\"Struct\" }}")).to(equal("MyStruct"))
expect(generate("{{type.MyClass.variables.0.typeName | replace:\"s\",\"z\" }}")).to(equal("myClazz"))
expect(generate("{{type.MyClass.variables.0.typeName | replace:\"my\",\"\" }}")).to(equal("Class"))
expect(generate("{{type.MyClass.variables.0.typeName | replace:\"foo\",\"bar\" }}")).to(equal("myClass"))
}
}
it("rethrows template parsing errors") {
expect {
try Generator.generate(Types(types: []), template: StencilTemplate(templateString: "{% tag %}"))
}
.to(throwError(closure: { (error) in
expect("\(error)").to(equal(": Unknown template tag 'tag'"))
}))
}
it("includes partial templates") {
var outputDir = Path("/tmp")
outputDir = Stubs.cleanTemporarySourceryDir()
let templatePath = Stubs.templateDirectory + Path("Include.stencil")
let expectedResult = "// Generated using Sourcery Major.Minor.Patch — https://github.com/krzysztofzablocki/Sourcery\n" +
"// DO NOT EDIT\n\n" +
"partial template content\n"
expect { try Sourcery(cacheDisabled: true).processFiles(.sources(Paths(include: [Stubs.sourceDirectory])), usingTemplates: Paths(include: [templatePath]), output: outputDir) }.toNot(throwError())
let result = (try? (outputDir + Sourcery().generatedPath(for: templatePath)).read(.utf8))
expect(result).to(equal(expectedResult))
}
}
}
}
| d597e28600f2875ce3b7615baad9ecf4 | 52.245614 | 211 | 0.498298 | false | false | false | false |
1000copy/fin | refs/heads/master | Controller/NodeTopicListViewController.swift | mit | 1 | import UIKit
class NodeTopicListViewController: UIViewController {
fileprivate weak var _loadView:V2LoadingView?
func showLoadingView (){
self._loadView = V2LoadingView(view)
}
func hideLoadingView() {
self._loadView?.hideLoadingView()
}
var node:NodeModel?
var favorited:Bool = false
var favoriteUrl:String? {
didSet{
// print(favoriteUrl)
// let startIndex = favoriteUrl?.range(of: "/", options: .backwards, range: nil, locale: nil)
// let endIndex = favoriteUrl?.range(of: "?")
// let nodeId = favoriteUrl?.substring(with: Range<String.Index>( startIndex!.upperBound ..< endIndex!.lowerBound ))
// if let _ = nodeId , let favoriteUrl = favoriteUrl {
// favorited = !favoriteUrl.hasPrefix("/favorite")
// followButton.refreshButtonImage()
// }
favorited = isFavorite(favoriteUrl)
followButton.refreshButtonImage()
}
}
func isFavorite(_ favoriteUrl:String?) -> Bool{
let startIndex = favoriteUrl?.range(of: "/", options: .backwards, range: nil, locale: nil)
let endIndex = favoriteUrl?.range(of: "?")
let nodeId = favoriteUrl?.substring(with: Range<String.Index>( startIndex!.upperBound ..< endIndex!.lowerBound ))
if let _ = nodeId , let favoriteUrl = favoriteUrl {
return !favoriteUrl.hasPrefix("/favorite")
}
return false
}
var followButton:FollowButton!
fileprivate var _tableView :NodeTable!
fileprivate var tableView: NodeTable {
get{
if(_tableView != nil){
return _tableView!;
}
_tableView = NodeTable();
return _tableView!
}
}
override func viewDidLoad() {
super.viewDidLoad()
if self.node?.nodeId == nil {
return;
}
followButton = FollowButton(frame:CGRect(x: 0, y: 0, width: 26, height: 26))
followButton.nodeId = node?.nodeId
let followItem = UIBarButtonItem(customView: followButton)
//处理间距
let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpaceItem.width = -5
self.navigationItem.rightBarButtonItems = [fixedSpaceItem,followItem]
self.title = self.node?.nodeName
self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(self.view);
}
self.showLoadingView()
self.tableView.scrollUp = refresh
self.tableView.scrollDown = getNextPage
self.tableView.beginScrollUp()
}
var currentPage = 1
func refresh(_ cb : @escaping Callback){
TopicListModelHTTP.getTopicList(self.node!.nodeId!, page: 1){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
self?._tableView.topicList = response.value?.0
self?.favoriteUrl = response.value?.1
self?.tableView.reloadData()
}
self?.hideLoadingView()
cb()
}
}
func getNextPage(_ cb : @escaping CallbackMore){
if let count = self.tableView.topicList?.count, count <= 0{
return;
}
self.currentPage += 1
TopicListModelHTTP.getTopicList(self.node!.nodeId!, page: self.currentPage){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
if let weakSelf = self , let value = response.value {
weakSelf.tableView.topicList! += value.0
weakSelf.tableView.reloadData()
}
else{
self?.currentPage -= 1
}
}
cb(true)
}
}
}
fileprivate class NodeTable : TableBase{
fileprivate var topicList:Array<TopicListModel>?
var currentPage = 1
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
backgroundColor = V2EXColor.colors.v2_backgroundColor
separatorStyle = .none
regClass(self, cell: HomeTopicListTableViewCell.self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override fileprivate func rowCount(_ section: Int) -> Int {
if let list = self.topicList {
return list.count;
}
return 0;
}
override fileprivate func rowHeight(_ indexPath: IndexPath) -> CGFloat {
let item = self.topicList![indexPath.row]
let titleHeight = item.getHeight() ?? 0
// 上间隔 头像高度 头像下间隔 标题高度 标题下间隔 cell间隔
let height = 12 + 35 + 12 + titleHeight + 12 + 8
return height
}
override fileprivate func cellAt(_ indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(self, cell: HomeTopicListTableViewCell.self, indexPath: indexPath);
cell.bindNodeModel(self.topicList![indexPath.row]);
return cell;
}
override fileprivate func didSelectRowAt(_ indexPath: IndexPath) {
let item = self.topicList![indexPath.row]
if let id = item.topicId {
Msg.send("openTopicDetail1", [id])
self.deselectRow(at: indexPath, animated: true)
}
}
}
class FollowButton : ButtonBase{
override init(frame: CGRect) {
super.init(frame: frame)
tap = toggleFavoriteState
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var favorited:Bool = false
var nodeId:String?
func refreshButtonImage() {
let followImage = self.favorited == true ? UIImage(named: "ic_favorite")! : UIImage(named: "ic_favorite_border")!
self.setImage(followImage.withRenderingMode(.alwaysTemplate), for: UIControlState())
}
func toggleFavoriteState(){
if(self.favorited){
TopicListModelHTTP.favorite(self.nodeId!, type: 0)
self.favorited = false
V2Success("取消收藏了~")
}
else{
TopicListModelHTTP.favorite(self.nodeId!, type: 1)
self.favorited = true
V2Success("收藏成功")
}
refreshButtonImage()
}
}
| 366b6feaaa176c881496f5d643e8f723 | 37 | 127 | 0.594615 | false | false | false | false |
Codezerker/RyCooder | refs/heads/master | Sources/Extensions.swift | mit | 1 | import Foundation
import Leonid
internal extension FileManager {
internal func filteredMusicFileURLs(inDirectory directory: String) -> [URL] {
guard let enumerator = enumerator(at: URL(fileURLWithPath: directory), includingPropertiesForKeys: nil, options: [], errorHandler: nil) else {
return []
}
var musicFiles = [URL]()
let enumeration: () -> Bool = {
guard let fileURL = enumerator.nextObject() as? URL else {
return false
}
if fileURL.isMusicFile {
musicFiles.append(fileURL)
}
return true
}
while enumeration() {}
return musicFiles
}
}
internal extension URL {
private enum MusicFileExtension: String {
case mp3 = "mp3"
case m4a = "m4a"
case m4p = "m4p"
}
internal var isMusicFile: Bool {
return MusicFileExtension(rawValue: pathExtension) != nil
}
}
internal extension String {
internal static let arrow = "=====>".addingBash(color: .blue, style: .dim)
internal var tinted: String {
return addingBash(color: .blue, style: .none)
}
internal var turnedOn: String {
return addingBash(color: .green, style: .none)
}
internal var turnedOff: String {
return addingBash(color: .red, style: .dim)
}
internal var highlighted: String {
return addingBash(color: .white, style: .bold)
}
internal var underlined: String {
return addingBash(color: .white, style: .underline)
}
}
internal extension Collection {
internal func shuffled() -> [Generator.Element] {
var array = Array(self)
array.shuffle()
return array
}
}
internal extension MutableCollection where Index == Int, IndexDistance == Int {
internal mutating func shuffle() {
guard count > 1 else { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
| aab616625ebd279920cb2df7e722a047 | 21.576471 | 146 | 0.647733 | false | false | false | false |
wolfposd/DynamicFeedback | refs/heads/master | DynamicFeedbackSheets/DynamicFeedbackSheets/View/TextFieldCell.swift | gpl-2.0 | 1 | //
// TextFieldModuleCell.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class TextFieldCell: ModuleCell, UITextFieldDelegate {
// MARK: Properties
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var textField: UITextField!
@IBOutlet var charactersLabel: UILabel!
override var module: FeedbackSheetModule? {
willSet {
if let textModule = newValue as? TextModule {
descriptionLabel.text = textModule.text
textField.text = nil
charactersLabel.text = "Remaining characters: \(textModule.characterLimit)"
}
}
}
// FIXME: Testing, current Bug in Xcode (Ambiguous use of module)
func setModule(module: FeedbackSheetModule) {
self.module = module
}
// MARK: View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
textField.layer.borderColor = UIColor.grayColor().CGColor
textField.layer.borderWidth = 1.5
textField.layer.cornerRadius = 5
textField.delegate = self
}
// MARK: Actions
override func reloadWithResponseData(responseData: AnyObject) {
let text = responseData as String
let textLength = countElements(text)
var shouldChange = true
textField.text = text
if let textModule = module as? TextModule {
shouldChange = (textLength <= textModule.characterLimit) ? true : false
if shouldChange {
charactersLabel.text = "Remaining characters: \(textModule.characterLimit - textLength)"
}
}
}
// MARK: UITextFieldDelegate
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let newLength = countElements(textField.text!) + countElements(string!) - range.length
var shouldChange = true
if let textModule = module as? TextModule {
shouldChange = (newLength <= textModule.characterLimit) ? true : false
if shouldChange {
charactersLabel.text = "Remaining characters: \(textModule.characterLimit - newLength)"
}
}
return shouldChange
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField!) {
if let textModule = module as? TextModule {
textModule.responseData = textField.text
delegate?.moduleCell(self, didGetResponse: textModule.responseData, forID: textModule.ID)
}
}
} | df11e4aedda9f7d9482d4de509c2fbf7 | 30.852273 | 134 | 0.633833 | false | false | false | false |
cemolcay/MusicTheory | refs/heads/master | Sources/MusicTheory/Accidental.swift | mit | 1 | //
// Enharmonics.swift
// MusicTheory
//
// Created by Cem Olcay on 21.06.2018.
// Copyright © 2018 cemolcay. All rights reserved.
//
// https://github.com/cemolcay/MusicTheory
//
import Foundation
/// Returns a new accidental by adding up two accidentals in the equation.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns the sum of two accidentals.
public func + (lhs: Accidental, rhs: Accidental) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue + rhs.rawValue)
}
/// Returns a new accidental by substracting two accidentals in the equation.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns the difference of two accidentals.
public func - (lhs: Accidental, rhs: Accidental) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue - rhs.rawValue)
}
/// Returns a new accidental by adding up an int to the accidental in the equation.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns the sum of two accidentals.
public func + (lhs: Accidental, rhs: Int) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue + rhs)
}
/// Returns a new accidental by substracting an int from the accidental in the equation.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns the difference of two accidentals.
public func - (lhs: Accidental, rhs: Int) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue - rhs)
}
/// Multiples an accidental with a multiplier.
///
/// - Parameters:
/// - lhs: Accidental you want to multiply.
/// - rhs: Multiplier.
/// - Returns: Returns a multiplied acceident.
public func * (lhs: Accidental, rhs: Int) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue * rhs)
}
/// Divides an accidental with a multiplier
///
/// - Parameters:
/// - lhs: Accidental you want to divide.
/// - rhs: Multiplier.
/// - Returns: Returns a divided accidental.
public func / (lhs: Accidental, rhs: Int) -> Accidental {
return Accidental(integerLiteral: lhs.rawValue / rhs)
}
/// Checks if the two accidental is identical in terms of their halfstep values.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns true if two accidentalals is identical.
public func == (lhs: Accidental, rhs: Accidental) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// Checks if the two accidental is exactly identical.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Returns true if two accidentalals is identical.
public func === (lhs: Accidental, rhs: Accidental) -> Bool {
switch (lhs, rhs) {
case (.natural, .natural):
return true
case let (.sharps(a), .sharps(b)):
return a == b
case let (.flats(a), .flats(b)):
return a == b
default:
return false
}
}
/// The enum used for calculating values of the `Key`s and `Pitche`s.
public enum Accidental: Codable, Equatable, Hashable, RawRepresentable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral, CustomStringConvertible {
/// No accidental.
case natural
/// Reduces the `Key` or `Pitch` value amount of halfsteps.
case flats(amount: Int)
/// Increases the `Key` or `Pitch` value amount of halfsteps.
case sharps(amount: Int)
/// Reduces the `Key` or `Pitch` value one halfstep below.
public static let flat: Accidental = .flats(amount: 1)
/// Increases the `Key` or `Pitch` value one halfstep above.
public static let sharp: Accidental = .sharps(amount: 1)
/// Reduces the `Key` or `Pitch` value amount two halfsteps below.
public static let doubleFlat: Accidental = .flats(amount: 2)
/// Increases the `Key` or `Pitch` value two halfsteps above.
public static let doubleSharp: Accidental = .sharps(amount: 2)
/// A flag for `description` function that determines if it should use double sharp and double flat symbols.
/// It's useful to set it false where the fonts do not support that symbols. Defaults true.
public static var shouldUseDoubleFlatAndDoubleSharpNotation = true
// MARK: RawRepresentable
public typealias RawValue = Int
/// Value of the accidental in terms of halfsteps.
public var rawValue: Int {
switch self {
case .natural:
return 0
case let .flats(amount):
return -amount
case let .sharps(amount):
return amount
}
}
/// Initilizes the accidental with an integer that represents the halfstep amount.
///
/// - Parameter rawValue: Halfstep value of the accidental. Zero if natural, above zero if sharp, below zero if flat.
public init?(rawValue: Accidental.RawValue) {
if rawValue == 0 {
self = .natural
} else if rawValue > 0 {
self = .sharps(amount: rawValue)
} else {
self = .flats(amount: -rawValue)
}
}
// MARK: ExpressibleByIntegerLiteral
public typealias IntegerLiteralType = Int
/// Initilizes the accidental with an integer literal value.
///
/// - Parameter value: Halfstep value of the accidental. Zero if natural, above zero if sharp, below zero if flat.
public init(integerLiteral value: Accidental.IntegerLiteralType) {
self = Accidental(rawValue: value) ?? .natural
}
// MARK: ExpressibleByStringLiteral
public typealias StringLiteralType = String
public init(stringLiteral value: Accidental.StringLiteralType) {
var sum = 0
for i in 0 ..< value.count {
switch value[value.index(value.startIndex, offsetBy: i)] {
case "#", "♯":
sum += 1
case "b", "♭":
sum -= 1
default:
break
}
}
self = Accidental(rawValue: sum) ?? .natural
}
// MARK: CustomStringConvertible
/// Returns the notation string of the accidental.
public var notation: String {
if case .natural = self {
return "♮"
}
return description
}
/// Returns the notation string of the accidental. Returns empty string if accidental is natural.
public var description: String {
switch self {
case .natural:
return ""
case let .flats(amount):
switch amount {
case 0: return Accidental.natural.description
case 1: return "♭"
case 2 where Accidental.shouldUseDoubleFlatAndDoubleSharpNotation: return "𝄫"
default: return amount > 0 ? (0 ..< amount).map({ _ in Accidental.flats(amount: 1).description }).joined() : ""
}
case let .sharps(amount):
switch amount {
case 0: return Accidental.natural.description
case 1: return "♯"
case 2 where Accidental.shouldUseDoubleFlatAndDoubleSharpNotation: return "𝄪"
default: return amount > 0 ? (0 ..< amount).map({ _ in Accidental.sharps(amount: 1).description }).joined() : ""
}
}
}
}
| 851dfe84e88d1c4c30d1b5e5bd0adae9 | 31.901869 | 154 | 0.676324 | false | false | false | false |
rxwei/cuda-swift | refs/heads/master | Sources/Warp/ArrayBuffer.swift | mit | 1 | //
// Buffer.swift
// Warp
//
// Created by Richard Wei on 10/26/16.
//
//
import CUDARuntime
protocol DeviceArrayBufferProtocol : DeviceBufferProtocol, MutableCollection, RandomAccessCollection {
typealias Index = Int
typealias Indices = CountableRange<Int>
var baseAddress: UnsafeMutableDevicePointer<Element> { get }
var capacity: Int { get }
init(capacity: Int)
init(device: Device, capacity: Int)
init(viewing other: Self, in range: Range<Int>)
var startAddress: UnsafeMutableDevicePointer<Element> { get }
var endAddress: UnsafeMutableDevicePointer<Element> { get }
subscript(i: Int) -> DeviceValueBuffer<Element> { get set }
}
extension DeviceArrayBufferProtocol where Index == Int {
init() {
self.init(capacity: 0)
}
var startAddress: UnsafeMutableDevicePointer<Element> {
return baseAddress.advanced(by: startIndex)
}
var endAddress: UnsafeMutableDevicePointer<Element> {
return baseAddress.advanced(by: endIndex)
}
var count: Int {
return endIndex - startIndex
}
func index(after i: Int) -> Int {
return i + 1
}
func index(before i: Int) -> Int {
return i - 1
}
}
class LifetimeKeeper<Kept> {
let retainee: Kept
init(keeping retainee: Kept) {
self.retainee = retainee
}
}
final class DeviceArrayBuffer<Element> : DeviceArrayBufferProtocol {
typealias SubSequence = DeviceArrayBuffer<Element>
let device: Device
var baseAddress: UnsafeMutableDevicePointer<Element>
let capacity: Int
let startIndex: Int, endIndex: Int
var owner: AnyObject?
private var lifetimeKeeper: LifetimeKeeper<[Element]>?
private var valueRetainees: [DeviceValueBuffer<Element>?]
init(capacity: Int) {
device = Device.current
self.capacity = capacity
baseAddress = UnsafeMutableDevicePointer<Element>.allocate(capacity: capacity)
startIndex = 0
endIndex = capacity
owner = nil
valueRetainees = Array(repeating: nil, count: capacity)
}
convenience init(device: Device) {
self.init(device: device, capacity: 0)
}
convenience init(device: Device, capacity: Int) {
let contextualDevice = Device.current
if device == contextualDevice {
self.init(capacity: capacity)
} else {
Device.current = device
self.init(capacity: capacity)
Device.current = contextualDevice
}
}
init(viewing other: DeviceArrayBuffer<Element>) {
device = other.device
capacity = other.capacity
baseAddress = other.baseAddress
startIndex = other.startIndex
endIndex = other.endIndex
owner = other
lifetimeKeeper = other.lifetimeKeeper
valueRetainees = other.valueRetainees
}
init(viewing other: DeviceArrayBuffer<Element>, in range: Range<Int>) {
device = other.device
capacity = other.capacity
baseAddress = other.baseAddress
precondition(other.startIndex <= range.lowerBound && other.endIndex >= range.upperBound,
"Array index out of bounds")
startIndex = range.lowerBound
endIndex = range.upperBound
owner = other
lifetimeKeeper = other.lifetimeKeeper
valueRetainees = other.valueRetainees
}
convenience init<C: Collection>(_ elements: C, device: Device) where
C.Iterator.Element == Element, C.IndexDistance == Int
{
self.init(device: device, capacity: elements.count)
var elements = Array(elements)
baseAddress.assign(fromHost: &elements, count: elements.count)
lifetimeKeeper = LifetimeKeeper<[Element]>(keeping: elements)
}
convenience init(repeating repeatedValue: Element, count: Int, device: Device) {
self.init(device: device, capacity: count)
baseAddress.assign(repeatedValue, count: count)
}
convenience init(_ other: DeviceArrayBuffer<Element>) {
self.init(device: other.device, capacity: other.count)
lifetimeKeeper = other.lifetimeKeeper
baseAddress.assign(from: other.startAddress, count: other.count)
}
deinit {
if owner == nil {
baseAddress.deallocate()
}
}
var indices: CountableRange<Int> {
return startIndex..<endIndex
}
/// Replaces the specified subrange of elements with the given collection.
public func replaceSubrange<C : Collection>
(_ subrange: Range<Int>, with newElements: C) where C.Iterator.Element == DeviceValueBuffer<Element> {
let subrange = CountableRange(subrange)
for (index, element) in zip(subrange, newElements) {
self[index] = element
}
}
public func replaceSubrange
(_ subrange: Range<Int>, with newElements: DeviceArrayBuffer<Element>) {
precondition(subrange.lowerBound >= startIndex && subrange.upperBound <= endIndex,
"Array index out of subrange")
for (i, valueBuf) in zip(CountableRange(subrange), newElements) {
valueRetainees[i] = valueBuf
}
baseAddress.advanced(by: subrange.lowerBound)
.assign(from: newElements.startAddress,
count: Swift.min(subrange.count, count))
}
/// Accesses the subsequence bounded by the given range.
///
/// - Parameter bounds: A range of the collection's indices. The upper and
/// lower bounds of the `bounds` range must be valid indices of the
/// collection.
subscript(bounds: Range<Int>) -> DeviceArrayBuffer<Element> {
get {
return DeviceArrayBuffer(viewing: self, in: bounds)
}
set {
replaceSubrange(bounds, with: newValue)
}
}
subscript(i: Int) -> DeviceValueBuffer<Element> {
get {
return DeviceValueBuffer(viewing: self, offsetBy: i)
}
set {
valueRetainees[i] = newValue
baseAddress.advanced(by: i).assign(from: newValue.baseAddress)
}
}
}
| 3cb18cb22160c65ad3c70f07e30a2929 | 30.050505 | 110 | 0.640046 | false | false | false | false |
GarenChen/SunshineAlbum | refs/heads/master | SunshineAlbum/Classes/ImageCropperViewController.swift | mit | 1 | //
// ImageCropperViewController.swift
// Pods
//
// Created by Garen on 2017/9/18.
//
//
import UIKit
class ImageCropperViewController: UIViewController {
var didCanceled: (() -> Void)?
var didCropped: ((UIImage?) -> Void)?
private var assetModel: AssetModel?
private var imageCropFrame: CGRect = .zero
private var originalImage: UIImage? {
didSet {
guard let image = originalImage else { return }
let oldWidth = imageCropFrame.size.width
let oldHeight = image.size.height * (oldWidth / image.size.width)
let oldX = imageCropFrame.origin.x + (imageCropFrame.width - oldWidth) / 2
let oldY = imageCropFrame.origin.y + (imageCropFrame.size.height - oldHeight) / 2
oldFrame = CGRect(x: oldX, y: oldY, width: oldWidth, height: oldHeight)
latestFrame = oldFrame
largeFrame = CGRect(x: 0, y: 0, width: limitRatio * oldWidth, height: limitRatio * oldHeight)
imageView.frame = oldFrame
}
}
private var oldFrame: CGRect = .zero
private var largeFrame: CGRect = .zero
private var limitRatio: CGFloat = 0
private var latestFrame: CGRect = .zero
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.frame = UIScreen.main.bounds
imageView.isUserInteractionEnabled = true
imageView.isMultipleTouchEnabled = true
return imageView
}()
private lazy var overlayView: UIView = { [unowned self] in
let overLayView = UIView(frame: self.view.bounds)
overLayView.alpha = 0.5
overLayView.backgroundColor = .black
overLayView.isUserInteractionEnabled = false
return overLayView
}()
private lazy var ratioView: UIView = { [unowned self] in
let ratioView = UIView(frame: self.imageCropFrame)
ratioView.layer.borderColor = UIColor(white: 1.0, alpha: 0.5).cgColor
ratioView.layer.borderWidth = 1
return ratioView
}()
private lazy var bottomBar: UIView = { [unowned self] in
let bottomBar = UIView(frame: CGRect(x: 0, y: UIScreen.ScreenHeight - 72, width: UIScreen.ScreenWidth, height: 72))
bottomBar.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
let cancelButton = UIButton(frame: CGRect(x: 12, y: 0, width: 80, height: 72))
cancelButton.contentHorizontalAlignment = .left
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(.white, for: .normal)
cancelButton.addTarget(self, action: #selector(didClickCancel(_:)), for: .touchUpInside)
bottomBar.addSubview(cancelButton)
let confirmButton = UIButton(frame: CGRect(x: UIScreen.ScreenWidth - 92, y: 0, width: 80, height: 72))
confirmButton.contentHorizontalAlignment = .right
confirmButton.setTitle("确定", for: .normal)
confirmButton.setTitleColor(.white, for: .normal)
confirmButton.addTarget(self, action: #selector(didClickConfirm(_:)), for: .touchUpInside)
bottomBar.addSubview(confirmButton)
return bottomBar
}()
convenience init(assetModel: AssetModel,
imageCropFrame: CGRect = SASelectionManager.shared.imageCropFrame,
limitRatio: CGFloat = SASelectionManager.shared.limitRatio) {
self.init()
self.assetModel = assetModel
self.imageCropFrame = imageCropFrame
self.limitRatio = limitRatio
AssetsManager.shared.fetchPreviewImage(asset: assetModel.asset) { [weak self] (image) in
guard let `self` = self else { return }
self.originalImage = image
self.imageView.image = image
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
// Do any additional setup after loading the view.
}
private func setupViews() {
view.backgroundColor = .black
view.addSubview(imageView)
addGestureRecognizer()
view.addSubview(overlayView)
view.addSubview(ratioView)
view.addSubview(bottomBar)
overlayClipping()
}
private func addGestureRecognizer() {
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(didPinch(_:)))
let pan = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
view.addGestureRecognizer(pinch)
view.addGestureRecognizer(pan)
}
private func overlayClipping() {
let maskLayer = CAShapeLayer()
let path = CGMutablePath()
/// left
path.addRect(CGRect(x: 0, y: 0, width: ratioView.frame.origin.x, height: overlayView.frame.size.height))
/// right
path.addRect(CGRect(x: ratioView.frame.origin.x + ratioView.frame.size.width, y: 0, width: overlayView.frame.size.width - ratioView.frame.origin.x - ratioView.frame.size.width, height: overlayView.frame.size.height))
/// top
path.addRect(CGRect(x: 0, y: 0, width: overlayView.frame.size.width, height: ratioView.frame.origin.y))
/// bottom
path.addRect(CGRect(x: 0, y: ratioView.frame.origin.y + ratioView.frame.size.height, width: overlayView.frame.size.width, height: overlayView.frame.size.height - ratioView.frame.origin.y + ratioView.frame.size.height))
maskLayer.path = path
overlayView.layer.mask = maskLayer
}
@objc private func didPinch(_ sender: UIPinchGestureRecognizer) {
if sender.state == .began || sender.state == .changed {
imageView.transform = imageView.transform.scaledBy(x: sender.scale, y: sender.scale)
sender.scale = 1
} else if sender.state == .ended {
var newFrame = imageView.frame
newFrame = handleScaleOverflow(frame: newFrame)
newFrame = handleBorderOverflow(frame: newFrame)
UIView.animate(withDuration: 0.3, animations: {
self.imageView.frame = newFrame
self.latestFrame = newFrame
})
}
}
@objc private func didPan(_ sender: UIPanGestureRecognizer) {
if sender.state == .began || sender.state == .changed {
let absCenterX = imageCropFrame.origin.x + imageCropFrame.size.width / 2
let absCenterY = imageCropFrame.origin.y + imageCropFrame.size.height / 2
let scaleRatio = imageView.frame.size.width / imageCropFrame.size.width
let acceleratorX = 1 - CGFloat(fabs(Double(absCenterX - imageView.center.x))) / (scaleRatio * absCenterX)
let acceleratorY = 1 - CGFloat(fabs(Double(absCenterY - imageView.center.y))) / (scaleRatio * absCenterY)
let translation = sender.translation(in: imageView.superview)
imageView.center = CGPoint(x: imageView.center.x + translation.x * acceleratorX,
y: imageView.center.y + translation.y * acceleratorY)
sender.setTranslation(.zero, in: imageView.superview)
} else if sender.state == .ended {
var newFrame = imageView.frame
newFrame = handleBorderOverflow(frame: newFrame)
UIView.animate(withDuration: 0.3, animations: {
self.imageView.frame = newFrame
self.latestFrame = newFrame
})
}
}
@objc private func didClickCancel(_ sender: UIButton) {
didCanceled?()
}
@objc private func didClickConfirm(_ sender: UIButton) {
didCropped?(getCroppedImage())
}
private func handleScaleOverflow(frame: CGRect) -> CGRect {
var newFrame = frame
let originCenter = CGPoint(x: newFrame.origin.x + newFrame.size.width/2, y: newFrame.origin.y + newFrame.size.height / 2)
if newFrame.size.width < oldFrame.size.width {
newFrame = oldFrame
}
if newFrame.size.width > largeFrame.size.width {
newFrame = largeFrame
}
newFrame.origin = CGPoint(x: originCenter.x - newFrame.size.width / 2,
y: originCenter.y - newFrame.size.height / 2)
return newFrame
}
private func handleBorderOverflow(frame: CGRect) -> CGRect {
var newFrame = frame
if newFrame.origin.x > imageCropFrame.origin.x {
newFrame.origin.x = imageCropFrame.origin.x
}
if newFrame.maxX < imageCropFrame.size.width {
newFrame.origin.x = imageCropFrame.size.width - newFrame.size.width
}
if newFrame.origin.y > imageCropFrame.origin.y {
newFrame.origin.y = imageCropFrame.origin.y
}
if newFrame.maxY < imageCropFrame.origin.y + imageCropFrame.size.height {
newFrame.origin.y = imageCropFrame.origin.y + imageCropFrame.size.height - newFrame.size.height
}
if imageView.frame.size.width > imageView.frame.size.height && newFrame.size.height <= imageCropFrame.size.height {
newFrame.origin.y = imageCropFrame.origin.y + (imageCropFrame.size.height - newFrame.size.height) / 2
}
return newFrame
}
private func getCroppedImage() -> UIImage? {
guard let originalImage = originalImage else { return nil }
let squareFrame = imageCropFrame
let scaleRatio = latestFrame.size.width / originalImage.size.width
var x = (squareFrame.origin.x - latestFrame.origin.x) / scaleRatio
var y = (squareFrame.origin.y - latestFrame.origin.y) / scaleRatio
var w = squareFrame.size.width / scaleRatio
var h = squareFrame.size.height / scaleRatio
if latestFrame.size.width < imageCropFrame.size.width {
let newW = originalImage.size.width
let newH = newW * (imageCropFrame.size.height / imageCropFrame.size.width)
x = 0
y = y + (h - newH) / 2
w = newW
h = newH
}
if latestFrame.size.height < imageCropFrame.size.height {
let newH = originalImage.size.height
let newW = newH * (imageCropFrame.size.width / imageCropFrame.size.height)
x = x + (w - newW) / 2
y = 0
w = newW
h = newH
}
let newImageRect = CGRect(x: x, y: y, width: w, height: h)
guard let newImage = originalImage.cgImage?.cropping(to: newImageRect) else {
return nil
}
UIGraphicsBeginImageContext(newImageRect.size)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.draw(newImage, in: newImageRect)
let resultImage = UIImage(cgImage: newImage)
UIGraphicsEndImageContext()
return resultImage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| d085d21d5708361a8580baee4f218e52 | 32.153846 | 220 | 0.711086 | false | false | false | false |
dvidlui/iOS8-day-by-day | refs/heads/master | 35-coremotion/LocoMotion/LocoMotion/MotionActivityCell.swift | apache-2.0 | 1 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import CoreMotion
class MotionActivityCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var pedometerLabel: UILabel!
var activity: Activity? {
didSet {
prepareCellForActivity(activity)
}
}
var dateFormatter: NSDateFormatter?
var lengthFormatter: NSLengthFormatter?
var pedometer: CMPedometer?
// MARK:- Utility methods
private func prepareCellForActivity(activity: Activity?) {
if let activity = activity {
var imageName = ""
switch activity.type {
case .Cycling:
imageName = "cycle"
pedometerLabel.text = ""
case .Running:
imageName = "run"
requestPedometerData()
case .Walking:
imageName = "walk"
requestPedometerData()
default:
imageName = ""
pedometerLabel.text = ""
}
iconImageView.image = UIImage(named: imageName)
titleLabel.text = "\(dateFormatter!.stringFromDate(activity.startDate)) - \(dateFormatter!.stringFromDate(activity.endDate))"
}
}
private func requestPedometerData() {
pedometer?.queryPedometerDataFromDate(activity?.startDate, toDate: activity?.endDate) {
(data, error) -> Void in
if error != nil {
println("There was an error requesting data from the pedometer: \(error)")
} else {
dispatch_async(dispatch_get_main_queue()) {
self.pedometerLabel.text = self.constructPedometerString(data)
}
}
}
}
private func constructPedometerString(data: CMPedometerData) -> String {
var pedometerString = ""
if CMPedometer.isStepCountingAvailable() {
pedometerString += "\(data.numberOfSteps) steps | "
}
if CMPedometer.isDistanceAvailable() {
pedometerString += "\(lengthFormatter!.stringFromMeters(data.distance)) | "
}
if CMPedometer.isFloorCountingAvailable() {
pedometerString += "\(data.floorsAscended) floors"
}
return pedometerString
}
}
| b4dac8f4ce0b9d473e9a59cc0cffb8a7 | 28.433333 | 131 | 0.676104 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Pods/SimpleImageViewer/ImageViewer/AnimatableImageView.swift | mit | 1 | import UIKit
final class AnimatableImageView: UIView {
fileprivate let imageView = UIImageView()
override var contentMode: UIViewContentMode {
didSet { update() }
}
override var frame: CGRect {
didSet { update() }
}
var image: UIImage? {
didSet {
imageView.image = image
update()
}
}
init() {
super.init(frame: .zero)
clipsToBounds = true
addSubview(imageView)
imageView.contentMode = .scaleToFill
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension AnimatableImageView {
func update() {
guard let image = image else { return }
switch contentMode {
case .scaleToFill:
imageView.bounds = Utilities.rect(forSize: bounds.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFit:
imageView.bounds = Utilities.aspectFitRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFill:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .redraw:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .center:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .top:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerTop(forSize: image.size, insideSize: bounds.size)
case .bottom:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerBottom(forSize: image.size, insideSize: bounds.size)
case .left:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerLeft(forSize: image.size, insideSize: bounds.size)
case .right:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerRight(forSize: image.size, insideSize: bounds.size)
case .topLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topLeft(forSize: image.size, insideSize: bounds.size)
case .topRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topRight(forSize: image.size, insideSize: bounds.size)
case .bottomLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomLeft(forSize: image.size, insideSize: bounds.size)
case .bottomRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomRight(forSize: image.size, insideSize: bounds.size)
}
}
}
| c6306d6cad9d2950945d426f9b637e5c | 39.962025 | 99 | 0.637515 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/CallNavigationHeaderView.swift | gpl-2.0 | 1 | //
// CallNavigationHeaderView.swift
// Telegram
//
// Created by keepcoder on 05/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
private let blue = NSColor(rgb: 0x0078ff)
private let lightBlue = NSColor(rgb: 0x59c7f8)
private let green = NSColor(rgb: 0x33c659)
private let purple = NSColor(rgb: 0x766EE9)
private let lightPurple = NSColor(rgb: 0xF05459)
class CallStatusBarBackgroundViewLegacy : View, CallStatusBarBackground {
var audioLevel: Float = 0
var speaking:(Bool, Bool, Bool)? = nil {
didSet {
if let speaking = self.speaking, (speaking.0 != oldValue?.0 || speaking.1 != oldValue?.1 || speaking.2 != oldValue?.2) {
let targetColors: [NSColor]
if speaking.1 {
if speaking.2 {
if speaking.0 {
targetColors = [green, blue]
} else {
targetColors = [blue, lightBlue]
}
} else {
targetColors = [purple, lightPurple]
}
} else {
targetColors = [theme.colors.grayIcon, theme.colors.grayIcon.lighter()]
}
self.backgroundColor = targetColors.first ?? theme.colors.accent
}
}
}
}
class CallStatusBarBackgroundView: View, CallStatusBarBackground {
private let foregroundView: View
private let foregroundGradientLayer: CAGradientLayer
private let maskCurveLayer: VoiceCurveLayer
var audioLevel: Float = 0.0 {
didSet {
self.maskCurveLayer.updateLevel(CGFloat(audioLevel))
}
}
var speaking:(Bool, Bool, Bool)? = nil {
didSet {
if let speaking = self.speaking, (speaking.0 != oldValue?.0 || speaking.1 != oldValue?.1 || speaking.2 != oldValue?.2) {
let initialColors = self.foregroundGradientLayer.colors
let targetColors: [CGColor]
if speaking.1 {
if speaking.2 {
if speaking.0 {
targetColors = [green.cgColor, blue.cgColor]
} else {
targetColors = [blue.cgColor, lightBlue.cgColor]
}
} else {
targetColors = [purple.cgColor, lightPurple.cgColor]
}
} else {
targetColors = [theme.colors.grayIcon.cgColor, theme.colors.grayIcon.lighter().cgColor]
}
self.foregroundGradientLayer.colors = targetColors
self.foregroundGradientLayer.animate(from: initialColors as AnyObject, to: targetColors as AnyObject, keyPath: "colors", timingFunction: .linear, duration: 0.3)
}
}
}
override init() {
self.foregroundView = View()
self.foregroundGradientLayer = CAGradientLayer()
self.maskCurveLayer = VoiceCurveLayer(frame: CGRect(), maxLevel: 2.5, smallCurveRange: (0.0, 0.0), mediumCurveRange: (0.1, 0.55), bigCurveRange: (0.1, 1.0))
self.maskCurveLayer.setColor(NSColor(rgb: 0xffffff))
super.init()
self.addSubview(self.foregroundView)
self.foregroundView.layer?.addSublayer(self.foregroundGradientLayer)
self.foregroundGradientLayer.colors = [theme.colors.grayIcon.cgColor, theme.colors.grayIcon.lighter().cgColor]
self.foregroundGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
self.foregroundGradientLayer.endPoint = CGPoint(x: 2.0, y: 0.5)
self.foregroundView.layer?.mask = maskCurveLayer
//layer?.addSublayer(maskCurveLayer)
self.updateAnimations()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
override func layout() {
super.layout()
CATransaction.begin()
CATransaction.setDisableActions(true)
self.foregroundView.frame = NSMakeRect(0, 0, frame.width, frame.height)
self.foregroundGradientLayer.frame = foregroundView.bounds
self.maskCurveLayer.frame = NSMakeRect(0, 0, frame.width, frame.height)
CATransaction.commit()
}
private let occlusionDisposable = MetaDisposable()
private var isCurrentlyInHierarchy: Bool = false {
didSet {
updateAnimations()
}
}
deinit {
occlusionDisposable.dispose()
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window = window as? Window {
occlusionDisposable.set(window.takeOcclusionState.start(next: { [weak self] value in
self?.isCurrentlyInHierarchy = value.contains(.visible)
}))
} else {
occlusionDisposable.set(nil)
isCurrentlyInHierarchy = false
}
}
func updateAnimations() {
if !isCurrentlyInHierarchy {
self.foregroundGradientLayer.removeAllAnimations()
self.maskCurveLayer.stopAnimating()
return
}
self.maskCurveLayer.startAnimating()
}
}
private final class VoiceCurveLayer: SimpleLayer {
private let smallCurve: CurveLayer
private let mediumCurve: CurveLayer
private let bigCurve: CurveLayer
private let maxLevel: CGFloat
private var displayLinkAnimator: ConstantDisplayLinkAnimator?
private var audioLevel: CGFloat = 0.0
var presentationAudioLevel: CGFloat = 0.0
private(set) var isAnimating = false
public typealias CurveRange = (min: CGFloat, max: CGFloat)
public init(
frame: CGRect,
maxLevel: CGFloat,
smallCurveRange: CurveRange,
mediumCurveRange: CurveRange,
bigCurveRange: CurveRange
) {
self.maxLevel = maxLevel
self.smallCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1,
maxRandomness: 1.3,
minSpeed: 0.9,
maxSpeed: 3.2,
minOffset: smallCurveRange.min,
maxOffset: smallCurveRange.max
)
self.mediumCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1.2,
maxRandomness: 1.5,
minSpeed: 1.0,
maxSpeed: 4.4,
minOffset: mediumCurveRange.min,
maxOffset: mediumCurveRange.max
)
self.bigCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1.2,
maxRandomness: 1.7,
minSpeed: 1.0,
maxSpeed: 5.8,
minOffset: bigCurveRange.min,
maxOffset: bigCurveRange.max
)
super.init()
self.addSublayer(bigCurve)
self.addSublayer(mediumCurve)
self.addSublayer(smallCurve)
displayLinkAnimator = ConstantDisplayLinkAnimator() { [weak self] in
guard let strongSelf = self else { return }
strongSelf.presentationAudioLevel = strongSelf.presentationAudioLevel * 0.9 + strongSelf.audioLevel * 0.1
strongSelf.smallCurve.level = strongSelf.presentationAudioLevel
strongSelf.mediumCurve.level = strongSelf.presentationAudioLevel
strongSelf.bigCurve.level = strongSelf.presentationAudioLevel
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setColor(_ color: NSColor) {
smallCurve.setColor(color.withAlphaComponent(1.0))
mediumCurve.setColor(color.withAlphaComponent(0.55))
bigCurve.setColor(color.withAlphaComponent(0.35))
}
public func updateLevel(_ level: CGFloat) {
let normalizedLevel = min(1, max(level / maxLevel, 0))
smallCurve.updateSpeedLevel(to: normalizedLevel)
mediumCurve.updateSpeedLevel(to: normalizedLevel)
bigCurve.updateSpeedLevel(to: normalizedLevel)
audioLevel = normalizedLevel
}
public func startAnimating() {
guard !isAnimating else { return }
isAnimating = true
updateCurvesState()
displayLinkAnimator?.isPaused = false
}
public func stopAnimating() {
self.stopAnimating(duration: 0.15)
}
public func stopAnimating(duration: Double) {
guard isAnimating else { return }
isAnimating = false
updateCurvesState()
displayLinkAnimator?.isPaused = true
}
private func updateCurvesState() {
if isAnimating {
if smallCurve.frame.size != .zero {
smallCurve.startAnimating()
mediumCurve.startAnimating()
bigCurve.startAnimating()
}
} else {
smallCurve.stopAnimating()
mediumCurve.stopAnimating()
bigCurve.stopAnimating()
}
}
override var frame: NSRect {
didSet {
if oldValue != frame {
smallCurve.frame = bounds
mediumCurve.frame = bounds
bigCurve.frame = bounds
updateCurvesState()
}
}
}
}
final class CurveLayer: CAShapeLayer {
let pointsCount: Int
let smoothness: CGFloat
let minRandomness: CGFloat
let maxRandomness: CGFloat
let minSpeed: CGFloat
let maxSpeed: CGFloat
let minOffset: CGFloat
let maxOffset: CGFloat
var level: CGFloat = 0 {
didSet {
guard self.minOffset > 0.0 else {
return
}
CATransaction.begin()
CATransaction.setDisableActions(true)
let lv = minOffset + (maxOffset - minOffset) * level
self.transform = CATransform3DMakeTranslation(0.0, lv * 16.0, 0.0)
CATransaction.commit()
}
}
private var curveAnimation: DisplayLinkAnimator?
private var speedLevel: CGFloat = 0
private var lastSpeedLevel: CGFloat = 0
private var transition: CGFloat = 0 {
didSet {
guard let currentPoints = currentPoints else { return }
let width = self.bounds.width
let smoothness = self.smoothness
let signal: Signal<CGPath, NoError> = Signal { subscriber in
subscriber.putNext(.smoothCurve(through: currentPoints, length: width, smoothness: smoothness, curve: true))
subscriber.putCompletion()
return EmptyDisposable
}
|> runOn(resourcesQueue)
|> deliverOnMainQueue
_ = signal.start(next: { [weak self] path in
self?.path = path
})
}
}
override var frame: CGRect {
didSet {
if oldValue != frame {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.position = CGPoint(x: self.bounds.width / 2.0, y: self.bounds.height / 2.0)
self.bounds = self.bounds
CATransaction.commit()
}
if self.frame.size != oldValue.size {
self.fromPoints = nil
self.toPoints = nil
self.curveAnimation = nil
self.animateToNewShape()
}
}
}
private var fromPoints: [CGPoint]?
private var toPoints: [CGPoint]?
private var currentPoints: [CGPoint]? {
guard let fromPoints = fromPoints, let toPoints = toPoints else { return nil }
return fromPoints.enumerated().map { offset, fromPoint in
let toPoint = toPoints[offset]
return CGPoint(
x: fromPoint.x + (toPoint.x - fromPoint.x) * transition,
y: fromPoint.y + (toPoint.y - fromPoint.y) * transition
)
}
}
init(
pointsCount: Int,
minRandomness: CGFloat,
maxRandomness: CGFloat,
minSpeed: CGFloat,
maxSpeed: CGFloat,
minOffset: CGFloat,
maxOffset: CGFloat
) {
self.pointsCount = pointsCount
self.minRandomness = minRandomness
self.maxRandomness = maxRandomness
self.minSpeed = minSpeed
self.maxSpeed = maxSpeed
self.minOffset = minOffset
self.maxOffset = maxOffset
self.smoothness = 0.35
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func setColor(_ color: NSColor) {
self.fillColor = color.cgColor
}
func updateSpeedLevel(to newSpeedLevel: CGFloat) {
speedLevel = max(speedLevel, newSpeedLevel)
}
func startAnimating() {
animateToNewShape()
}
func stopAnimating() {
fromPoints = currentPoints
toPoints = nil
self.curveAnimation?.invalidate()
curveAnimation = nil
}
private func animateToNewShape() {
if curveAnimation != nil {
fromPoints = currentPoints
toPoints = nil
curveAnimation = nil
}
if fromPoints == nil {
fromPoints = generateNextCurve(for: bounds.size)
}
if toPoints == nil {
toPoints = generateNextCurve(for: bounds.size)
}
let duration = CGFloat(1 / (minSpeed + (maxSpeed - minSpeed) * speedLevel))
let fromValue: CGFloat = 0
let toValue: CGFloat = 1
let animation = DisplayLinkAnimator(duration: Double(duration), from: fromValue, to: toValue, update: { [weak self] value in
self?.transition = value
}, completion: { [weak self] in
guard let `self` = self else {
return
}
self.fromPoints = self.currentPoints
self.toPoints = nil
self.curveAnimation = nil
self.animateToNewShape()
})
self.curveAnimation = animation
lastSpeedLevel = speedLevel
speedLevel = 0
}
private func generateNextCurve(for size: CGSize) -> [CGPoint] {
let randomness = minRandomness + (maxRandomness - minRandomness) * speedLevel
return curve(pointsCount: pointsCount, randomness: randomness).map {
return CGPoint(x: $0.x * CGFloat(size.width), y: size.height - 18.0 + $0.y * 12.0)
}
}
private func curve(pointsCount: Int, randomness: CGFloat) -> [CGPoint] {
let segment = 1.0 / CGFloat(pointsCount - 1)
let rgen = { () -> CGFloat in
let accuracy: UInt32 = 1000
let random = arc4random_uniform(accuracy)
return CGFloat(random) / CGFloat(accuracy)
}
let rangeStart: CGFloat = 1.0 / (1.0 + randomness / 10.0)
let points = (0 ..< pointsCount).map { i -> CGPoint in
let randPointOffset = (rangeStart + CGFloat(rgen()) * (1 - rangeStart)) / 2
let segmentRandomness: CGFloat = randomness
let pointX: CGFloat
let pointY: CGFloat
let randomXDelta: CGFloat
if i == 0 {
pointX = 0.0
pointY = 0.0
randomXDelta = 0.0
} else if i == pointsCount - 1 {
pointX = 1.0
pointY = 0.0
randomXDelta = 0.0
} else {
pointX = segment * CGFloat(i)
pointY = ((segmentRandomness * CGFloat(arc4random_uniform(100)) / CGFloat(100)) - segmentRandomness * 0.5) * randPointOffset
randomXDelta = segment - segment * randPointOffset
}
return CGPoint(x: pointX + randomXDelta, y: pointY)
}
return points
}
}
protocol CallStatusBarBackground : View {
var audioLevel: Float { get set }
var speaking:(Bool, Bool, Bool)? { get set }
}
class CallHeaderBasicView : NavigationHeaderView {
private let _backgroundView: CallStatusBarBackground
var backgroundView: CallStatusBarBackground {
return _backgroundView
}
private let container = View()
fileprivate let callInfo:TitleButton = TitleButton()
fileprivate let endCall:ImageButton = ImageButton()
fileprivate let statusTextView:TextView = TextView()
fileprivate let muteControl:ImageButton = ImageButton()
fileprivate let capView = View()
let disposable = MetaDisposable()
let hideDisposable = MetaDisposable()
override func hide(_ animated: Bool) {
super.hide(true)
disposable.set(nil)
hideDisposable.set(nil)
}
private var statusTimer: SwiftSignalKit.Timer?
var status: CallControllerStatusValue = .text("", nil) {
didSet {
if self.status != oldValue {
self.statusTimer?.invalidate()
if self.status.hasTimer == true {
self.statusTimer = SwiftSignalKit.Timer(timeout: 0.5, repeat: true, completion: { [weak self] in
self?.updateStatus()
}, queue: Queue.mainQueue())
self.statusTimer?.start()
self.updateStatus()
} else {
self.updateStatus()
}
}
}
}
private func updateStatus(animated: Bool = true) {
var statusText: String = ""
switch self.status {
case let .text(text, _):
statusText = text
case let .timer(referenceTime, _):
let duration = Int32(CFAbsoluteTimeGetCurrent() - referenceTime)
let durationString: String
if duration > 60 * 60 {
durationString = String(format: "%02d:%02d:%02d", arguments: [duration / 3600, (duration / 60) % 60, duration % 60])
} else {
durationString = String(format: "%02d:%02d", arguments: [(duration / 60) % 60, duration % 60])
}
statusText = durationString
case let .startsIn(time):
statusText = strings().chatHeaderVoiceChatStartsIn(timerText(time - Int(Date().timeIntervalSince1970)))
}
let layout = TextViewLayout.init(.initialize(string: statusText, color: .white, font: .normal(13)))
layout.measure(width: .greatestFiniteMagnitude)
self.statusTextView.update(layout)
needsLayout = true
}
deinit {
disposable.dispose()
hideDisposable.dispose()
}
override init(_ header: NavigationHeader) {
if #available(OSX 10.12, *) {
self._backgroundView = CallStatusBarBackgroundView()
} else {
self._backgroundView = CallStatusBarBackgroundViewLegacy()
}
super.init(header)
backgroundView.frame = bounds
backgroundView.wantsLayer = true
addSubview(capView)
addSubview(backgroundView)
addSubview(container)
statusTextView.backgroundColor = .clear
statusTextView.userInteractionEnabled = false
statusTextView.isSelectable = false
callInfo.set(font: .medium(.text), for: .Normal)
callInfo.disableActions()
container.addSubview(callInfo)
callInfo.userInteractionEnabled = false
endCall.disableActions()
container.addSubview(endCall)
endCall.scaleOnClick = true
muteControl.scaleOnClick = true
container.addSubview(statusTextView)
callInfo.set(handler: { [weak self] _ in
self?.showInfoWindow()
}, for: .Click)
endCall.set(handler: { [weak self] _ in
self?.hangUp()
}, for: .Click)
muteControl.autohighlight = false
container.addSubview(muteControl)
muteControl.set(handler: { [weak self] _ in
self?.toggleMute()
}, for: .Click)
updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func toggleMute() {
}
func showInfoWindow() {
}
func hangUp() {
}
func setInfo(_ text: String) {
self.callInfo.set(text: text, for: .Normal)
}
func setMicroIcon(_ image: CGImage) {
muteControl.set(image: image, for: .Normal)
_ = muteControl.sizeToFit()
}
override func mouseUp(with event: NSEvent) {
super.mouseUp(with: event)
let point = self.convert(event.locationInWindow, from: nil)
if let header = header, point.y <= header.height {
showInfoWindow()
}
}
var blueColor:NSColor {
return theme.colors.accentSelect
}
var grayColor:NSColor {
return theme.colors.grayText
}
func getEndText() -> String {
return strings().callHeaderEndCall
}
override func layout() {
super.layout()
capView.frame = NSMakeRect(0, 0, frame.width, height)
backgroundView.frame = bounds
container.frame = NSMakeRect(0, 0, frame.width, height)
muteControl.centerY(x:18)
statusTextView.centerY(x: muteControl.frame.maxX + 6)
endCall.centerY(x: frame.width - endCall.frame.width - 20)
_ = callInfo.sizeToFit(NSZeroSize, NSMakeSize(frame.width - statusTextView.frame.width - 60 - 20 - endCall.frame.width - 10, callInfo.frame.height), thatFit: false)
let rect = container.focus(callInfo.frame.size)
callInfo.setFrameOrigin(NSMakePoint(max(statusTextView.frame.maxX + 10, min(rect.minX, endCall.frame.minX - 10 - callInfo.frame.width)), rect.minY))
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = (theme as! TelegramPresentationTheme)
self.capView.backgroundColor = backgroundView.backgroundColor
endCall.set(image: theme.icons.callInlineDecline, for: .Normal)
endCall.set(image: theme.icons.callInlineDecline, for: .Highlight)
_ = endCall.sizeToFit(NSMakeSize(10, 10), thatFit: false)
callInfo.set(color: .white, for: .Normal)
needsLayout = true
}
}
class CallNavigationHeaderView: CallHeaderBasicView {
var session: PCallSession? {
get {
self.header?.contextObject as? PCallSession
}
}
private let audioLevelDisposable = MetaDisposable()
deinit {
audioLevelDisposable.dispose()
}
fileprivate weak var accountPeer: Peer?
fileprivate var state: CallState?
override func showInfoWindow() {
if let session = self.session {
showCallWindow(session)
}
}
override func hangUp() {
self.session?.hangUpCurrentCall()
}
override func toggleMute() {
session?.toggleMute()
}
override func update(with contextObject: Any) {
super.update(with: contextObject)
let session = contextObject as! PCallSession
let account = session.account
let signal = Signal<Peer?, NoError>.single(session.peer) |> then(session.account.postbox.loadedPeerWithId(session.peerId) |> map(Optional.init) |> deliverOnMainQueue)
let accountPeer: Signal<Peer?, NoError> = session.accountContext.sharedContext.activeAccounts |> mapToSignal { accounts in
if accounts.accounts.count == 1 {
return .single(nil)
} else {
return account.postbox.loadedPeerWithId(account.peerId) |> map(Optional.init)
}
}
disposable.set(combineLatest(queue: .mainQueue(), session.state, signal, accountPeer).start(next: { [weak self] state, peer, accountPeer in
if let peer = peer {
self?.setInfo(peer.displayTitle)
}
self?.updateState(state, accountPeer: accountPeer, animated: false)
self?.needsLayout = true
self?.ready.set(.single(true))
}))
audioLevelDisposable.set((session.audioLevel |> deliverOnMainQueue).start(next: { [weak self] value in
self?.backgroundView.audioLevel = value
}))
hideDisposable.set((session.canBeRemoved |> deliverOnMainQueue).start(next: { [weak self] value in
if value {
self?.hide(true)
}
}))
}
private func updateState(_ state:CallState, accountPeer: Peer?, animated: Bool) {
self.state = state
self.status = state.state.statusText(accountPeer, state.videoState)
var isConnected: Bool = false
let isMuted = state.isMuted
switch state.state {
case .active:
isConnected = true
default:
isConnected = false
}
self.backgroundView.speaking = (isConnected && !isMuted, isConnected, true)
if animated {
backgroundView.layer?.animateBackground()
}
setMicroIcon(!state.isMuted ? theme.icons.callInlineUnmuted : theme.icons.callInlineMuted)
needsLayout = true
switch state.state {
case let .terminated(_, reason, _):
if let reason = reason, reason.recall {
} else {
muteControl.removeAllHandlers()
endCall.removeAllHandlers()
callInfo.removeAllHandlers()
muteControl.change(opacity: 0.8, animated: animated)
endCall.change(opacity: 0.8, animated: animated)
statusTextView._change(opacity: 0.8, animated: animated)
callInfo._change(opacity: 0.8, animated: animated)
}
default:
break
}
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
if let state = state {
self.updateState(state, accountPeer: accountPeer, animated: false)
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(_ header: NavigationHeader) {
super.init(header)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
}
| e6d1e23389f849658d4f432cea101ed1 | 30.058486 | 176 | 0.583724 | false | false | false | false |
icepy/APNGKit | refs/heads/master | APNGKit/APNGImageCache.swift | mit | 1 | //
// APNGImageCache.swift
// APNGKit
//
// Created by Wei Wang on 15/8/30.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Cache for APNGKit. It will hold apng images initialized from specified init methods.
/// If the same file is requested later, APNGKit will look it up in this cache first to improve performance.
public class APNGCache {
private static let defaultCacheInstance = APNGCache()
/// The default cache object. It is used internal in APNGKit.
/// You should always use this object to interact with APNG cache as well.
public class var defaultCache: APNGCache {
return defaultCacheInstance
}
let cacheObject = NSCache()
init() {
cacheObject.totalCostLimit = 0
cacheObject.name = "com.onevcat.APNGKit.cache"
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache",
name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache",
name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
Cache an APNG image with specified key.
- parameter image: The image should be cached.
- parameter key: The key of that image
*/
public func setImage(image: APNGImage, forKey key: String) {
cacheObject.setObject(image, forKey: key, cost: image.cost)
}
/**
Remove an APNG image from cache with specified key.
- parameter key: The key of that image
*/
public func removeImageForKey(key: String) {
cacheObject.removeObjectForKey(key)
}
func imageForKey(key: String) -> APNGImage? {
return cacheObject.objectForKey(key) as? APNGImage
}
/**
Clear the memory cache.
- note: Generally speaking you could just use APNGKit without worrying the memory and cache.
The cached images will be removed when a memory warning is received or your app is switched to background.
However, there is a chance that you want to do an operation requiring huge amount of memory, which may cause
your app OOM directly without receiving a memory warning. In this situation, you could call this method first
to release the APNG cache for your memory costing operation.
*/
@objc public func clearMemoryCache() {
// The cache will not work once it receives a memory warning from iOS 8.
// It seems an intended behaviours to reduce memory pressure.
// See http://stackoverflow.com/questions/27289360/nscache-objectforkey-always-return-nil-after-memory-warning-on-ios-8
// The solution in that post does not work on iOS 9. I guess just follow the system behavior would be good.
cacheObject.removeAllObjects()
}
}
extension APNGImage {
var cost: Int {
var s = 0
for f in frames {
if let image = f.image {
s += Int(image.size.height * image.size.width * image.scale * image.scale * CGFloat(self.bitDepth))
}
}
return s
}
} | a5105b0d1c0570b3549d38b90d084cbc | 40.803738 | 135 | 0.672182 | false | false | false | false |
alblue/swift | refs/heads/master | test/IRGen/partial_apply_generic.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
//
// Type parameters
//
infix operator ~>
func ~> <Target, Args, Result> (
target: Target,
method: (Target) -> (Args) -> Result)
-> (Args) -> Result
{
return method(target)
}
protocol Runcible {
associatedtype Element
}
struct Mince {}
struct Spoon: Runcible {
typealias Element = Mince
}
func split<Seq: Runcible>(_ seq: Seq) -> ((Seq.Element) -> Bool) -> () {
return {(isSeparator: (Seq.Element) -> Bool) in
return ()
}
}
var seq = Spoon()
var x = seq ~> split
//
// Indirect return
//
// CHECK-LABEL: define internal swiftcc { i8*, %swift.refcounted* } @"$s21partial_apply_generic5split{{[_0-9a-zA-Z]*}}FTA"(%T21partial_apply_generic5SpoonV* noalias nocapture, %swift.refcounted* swiftself)
// CHECK: [[REABSTRACT:%.*]] = bitcast %T21partial_apply_generic5SpoonV* %0 to %swift.opaque*
// CHECK: tail call swiftcc { i8*, %swift.refcounted* } @"$s21partial_apply_generic5split{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture [[REABSTRACT]],
struct HugeStruct { var a, b, c, d: Int }
struct S {
func hugeStructReturn(_ h: HugeStruct) -> HugeStruct { return h }
}
let s = S()
var y = s.hugeStructReturn
// CHECK-LABEL: define internal swiftcc { i64, i64, i64, i64 } @"$s21partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFFTA"(i64, i64, i64, i64, %swift.refcounted* swiftself) #0 {
// CHECK: entry:
// CHECK: %5 = tail call swiftcc { i64, i64, i64, i64 } @"$s21partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFF"(i64 %0, i64 %1, i64 %2, i64 %3)
// CHECK: ret { i64, i64, i64, i64 } %5
// CHECK: }
//
// Witness method
//
protocol Protein {
static func veganOrNothing() -> Protein?
static func paleoDiet() throws -> Protein
}
enum CarbOverdose : Error {
case Mild
case Severe
}
class Chicken : Protein {
static func veganOrNothing() -> Protein? {
return nil
}
static func paleoDiet() throws -> Protein {
throw CarbOverdose.Severe
}
}
func healthyLunch<T: Protein>(_ t: T) -> () -> Protein? {
return T.veganOrNothing
}
let f = healthyLunch(Chicken())
func dietaryFad<T: Protein>(_ t: T) -> () throws -> Protein {
return T.paleoDiet
}
let g = dietaryFad(Chicken())
do {
try g()
} catch {}
| 815c3afabec77286169d66416143d876 | 23.935484 | 205 | 0.658905 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/collection_cast_crash.swift | apache-2.0 | 14 | // RUN: %target-swift-frontend -O -Xllvm -sil-inline-generics=false -Xllvm -sil-partial-specialization=false -primary-file %s -emit-sil -o - | %FileCheck %s
// check if the compiler does not crash if a function is specialized
// which contains a collection cast
class MyClass {}
class KeyClass : Hashable {
var hashValue : Int { return 0 }
}
func ==(lhs: KeyClass, rhs: KeyClass) -> Bool { return true }
// CHECK-LABEL: sil{{.*}}@{{.*}}arrayUpCast{{.*}} <Ct where Ct : MyClass>
func arrayUpCast<Ct: MyClass>(_ arr: [Ct]) -> [MyClass] {
// CHECK: apply %{{[0-9]*}}<Ct{{.*}}>(%{{[0-9]*}})
return arr
// CHECK: return
}
// CHECK-LABEL: sil{{.*}}@{{.*}}arrayDownCast{{.*}} <Ct where Ct : MyClass>
func arrayDownCast<Ct: MyClass>(_ arr: [MyClass]) -> [Ct] {
// CHECK: apply %{{[0-9]*}}<{{.*}}Ct>(%{{[0-9]*}})
return arr as! [Ct]
// CHECK: return
}
// CHECK-LABEL: sil{{.*}}@{{.*}}dictUpCast{{.*}} <Ct where Ct : MyClass>
func dictUpCast<Ct: MyClass>(_ dict: [KeyClass:Ct]) -> [KeyClass:MyClass] {
// CHECK: apply %{{[0-9]*}}<{{.*}}Ct{{.*}}>(%{{[0-9]*}})
return dict as [KeyClass:MyClass]
// CHECK: return
}
// CHECK-LABEL: sil{{.*}}@{{.*}}dictDownCast{{.*}} <Ct where Ct : MyClass>
func dictDownCast<Ct: MyClass>(_ dict: [KeyClass:MyClass]) -> [KeyClass:Ct] {
// CHECK: apply %{{[0-9]*}}<KeyClass, MyClass, KeyClass, Ct>(%{{[0-9]*}})
return dict as! [KeyClass:Ct]
// CHECK: return
}
func setUpCast<Ct: KeyClass>(_ s: Set<Ct>) -> Set<KeyClass> {
// CHECK: apply %{{[0-9]*}}<Ct, KeyClass>(%{{[0-9]*}})
return s as Set<KeyClass>
// CHECK: return
}
func setDownCast<Ct : KeyClass>(_ s : Set<KeyClass>) -> Set<Ct> {
// CHECK: apply %{{[0-9]*}}<KeyClass, Ct>(%{{[0-9]*}})
return s as! Set<Ct>
// CHECK: return
}
let arr: [MyClass] = [MyClass()]
arrayUpCast(arr)
arrayDownCast(arr)
let dict: [KeyClass:MyClass] = [KeyClass() : MyClass()]
dictUpCast(dict)
dictDownCast(dict)
let s: Set<KeyClass> = Set()
setUpCast(s)
setDownCast(s)
| c46765d3c13912d53e96aa5187d26928 | 29.151515 | 157 | 0.59196 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Vender/LFTwitterProfile/TwitterProfileViewController.swift | mit | 1 | //
// TwitterProfileViewController.swift
// TwitterProfileViewController
//
// Created by Roy Tang on 30/9/2016.
// Copyright © 2016 NA. All rights reserved.
//
import UIKit
import SnapKit
open class TwitterProfileViewController: UIViewController {
// Global tint
open static var globalTint: UIColor = UIColor(red: 42.0/255.0, green: 163.0/255.0, blue: 239.0/255.0, alpha: 1)
// Constants
open let stickyheaderContainerViewHeight: CGFloat = 125
open let bouncingThreshold: CGFloat = 100
open let scrollToScaleDownProfileIconDistance: CGFloat = 60
open var profileHeaderViewHeight: CGFloat = 160 {
didSet {
//self.view.setNeedsLayout()
//self.view.layoutIfNeeded()
}
}
open let segmentedControlContainerHeight: CGFloat = 46
open var username: String? {
didSet {
self.profileHeaderView?.titleLabel?.text = username
self.navigationTitleLabel?.text = username
}
}
open var profileImage: UIImage? {
didSet {
self.profileHeaderView?.iconImageView?.image = profileImage
}
}
open var locationString: String? {
didSet {
self.profileHeaderView?.locationLabel?.text = locationString
}
}
open var descriptionString: String? {
didSet {
self.profileHeaderView?.descriptionLabel?.text = descriptionString
}
}
open var coverImage: UIImage? {
didSet {
self.headerCoverView?.image = coverImage
}
}
// Properties
var currentIndex: Int = 0 {
didSet {
self.updateTableViewContent()
}
}
var scrollViews: [UIScrollView] = []
var currentScrollView: UIScrollView {
return scrollViews[currentIndex]
}
fileprivate var mainScrollView: UIScrollView!
var headerCoverView: UIImageView!
var profileHeaderView: TwitterProfileHeaderView!
var stickyHeaderContainerView: UIView!
var blurEffectView: UIVisualEffectView!
var segmentedControl: UISegmentedControl!
var segmentedControlContainer: UIView!
var navigationTitleLabel: UILabel!
var navigationDetailLabel: UILabel!
var debugTextView: UILabel!
var shouldUpdateScrollViewContentFrame = false
deinit {
self.scrollViews.forEach { (scrollView) in
scrollView.removeFromSuperview()
}
self.scrollViews.removeAll()
print("[TwitterProfileViewController] memeory leak check passed")
}
override open func viewDidLoad() {
super.viewDidLoad()
self.prepareForLayout()
setNeedsStatusBarAppearanceUpdate()
self.prepareViews()
shouldUpdateScrollViewContentFrame = true
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(profileHeaderView.sizeThatFits(self.mainScrollView.bounds.size))
self.profileHeaderViewHeight = profileHeaderView.sizeThatFits(self.mainScrollView.bounds.size).height
if self.shouldUpdateScrollViewContentFrame {
// configure layout frames
self.stickyHeaderContainerView.frame = self.computeStickyHeaderContainerViewFrame()
self.profileHeaderView.frame = self.computeProfileHeaderViewFrame()
self.segmentedControlContainer.frame = self.computeSegmentedControlContainerFrame()
self.scrollViews.forEach({ (scrollView) in
scrollView.frame = self.computeTableViewFrame(tableView: scrollView)
})
self.updateMainScrollViewFrame()
self.mainScrollView.scrollIndicatorInsets = computeMainScrollViewIndicatorInsets()
self.shouldUpdateScrollViewContentFrame = false
}
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension TwitterProfileViewController {
func prepareViews() {
let _mainScrollView = TouchRespondScrollView(frame: self.view.bounds)
_mainScrollView.delegate = self
_mainScrollView.showsHorizontalScrollIndicator = false
self.mainScrollView = _mainScrollView
self.view.addSubview(_mainScrollView)
_mainScrollView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
// sticker header Container view
let _stickyHeaderContainer = UIView()
_stickyHeaderContainer.clipsToBounds = true
_mainScrollView.addSubview(_stickyHeaderContainer)
self.stickyHeaderContainerView = _stickyHeaderContainer
// Cover Image View
let coverImageView = UIImageView()
coverImageView.clipsToBounds = true
_stickyHeaderContainer.addSubview(coverImageView)
coverImageView.snp.makeConstraints { (make) in
make.edges.equalTo(_stickyHeaderContainer)
}
coverImageView.image = UIImage(named: "background.png")
coverImageView.contentMode = .scaleAspectFill
coverImageView.clipsToBounds = true
self.headerCoverView = coverImageView
// blur effect on top of coverImageView
let blurEffect = UIBlurEffect(style: .dark)
let _blurEffectView = UIVisualEffectView(effect: blurEffect)
_blurEffectView.alpha = 0
self.blurEffectView = _blurEffectView
_stickyHeaderContainer.addSubview(_blurEffectView)
_blurEffectView.snp.makeConstraints { (make) in
make.edges.equalTo(_stickyHeaderContainer)
}
// Detail Title
let _navigationDetailLabel = UILabel()
_navigationDetailLabel.text = "121 Tweets"
_navigationDetailLabel.textColor = UIColor.white
_navigationDetailLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
_stickyHeaderContainer.addSubview(_navigationDetailLabel)
_navigationDetailLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(_stickyHeaderContainer.snp.centerX)
make.bottom.equalTo(_stickyHeaderContainer.snp.bottom).inset(8)
}
self.navigationDetailLabel = _navigationDetailLabel
// Navigation Title
let _navigationTitleLabel = UILabel()
_navigationTitleLabel.text = self.username ?? "{username}"
_navigationTitleLabel.textColor = UIColor.white
_navigationTitleLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
_stickyHeaderContainer.addSubview(_navigationTitleLabel)
_navigationTitleLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(_stickyHeaderContainer.snp.centerX)
make.bottom.equalTo(_navigationDetailLabel.snp.top).offset(4)
}
self.navigationTitleLabel = _navigationTitleLabel
// preset the navigation title and detail at progress=0 position
animateNaivationTitleAt(progress: 0)
// ProfileHeaderView
if let _profileHeaderView = Bundle.bundleFromPod()?.loadNibNamed("TwitterProfileHeaderView", owner: self, options: nil)?.first as? TwitterProfileHeaderView {
_mainScrollView.addSubview(_profileHeaderView)
self.profileHeaderView = _profileHeaderView
self.profileHeaderView.usernameLabel.text = self.username
self.profileHeaderView.locationLabel.text = self.locationString
self.profileHeaderView.iconImageView.image = self.profileImage
}
// Segmented Control Container
let _segmentedControlContainer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: mainScrollView.bounds.width, height: 100))
_segmentedControlContainer.backgroundColor = UIColor.white
_mainScrollView.addSubview(_segmentedControlContainer)
self.segmentedControlContainer = _segmentedControlContainer
// Segmented Control
let _segmentedControl = UISegmentedControl()
_segmentedControl.addTarget(self, action: #selector(self.segmentedControlValueDidChange(sender:)), for: .valueChanged)
_segmentedControl.backgroundColor = UIColor.white
for index in 0..<numberOfSegments() {
let segmentTitle = self.segmentTitle(forSegment: index)
_segmentedControl.insertSegment(withTitle: segmentTitle, at: index, animated: false)
}
_segmentedControl.selectedSegmentIndex = 0
_segmentedControlContainer.addSubview(_segmentedControl)
self.segmentedControl = _segmentedControl
_segmentedControl.snp.makeConstraints { (make) in
// make.edges.equalTo(_segmentedControlContainer).inset(UIEdgeInsetsMake(8, 16, 8, 16))
make.width.equalToSuperview().offset(-16)
make.centerX.equalToSuperview()
make.centerY.equalTo(_segmentedControlContainer.snp.centerY)
}
self.scrollViews = []
for index in 0..<numberOfSegments() {
let scrollView = self.scrollView(forSegment: index)
self.scrollViews.append(scrollView)
scrollView.isHidden = (index > 0)
_mainScrollView.addSubview(scrollView)
}
self.showDebugInfo()
}
func computeStickyHeaderContainerViewFrame() -> CGRect {
return CGRect(x: 0, y: 0, width: mainScrollView.bounds.width, height: stickyheaderContainerViewHeight)
}
func computeProfileHeaderViewFrame() -> CGRect {
return CGRect(x: 0, y: computeStickyHeaderContainerViewFrame().origin.y + stickyheaderContainerViewHeight, width: mainScrollView.bounds.width, height: profileHeaderViewHeight)
}
func computeTableViewFrame(tableView: UIScrollView) -> CGRect {
let upperViewFrame = computeSegmentedControlContainerFrame()
return CGRect(x: 0, y: upperViewFrame.origin.y + upperViewFrame.height , width: mainScrollView.bounds.width, height: tableView.contentSize.height)
}
func computeMainScrollViewIndicatorInsets() -> UIEdgeInsets {
return UIEdgeInsetsMake(self.computeSegmentedControlContainerFrame().lf_originBottom, 0, 0, 0)
}
func computeNavigationFrame() -> CGRect {
return headerCoverView.convert(headerCoverView.bounds, to: self.view)
}
func computeSegmentedControlContainerFrame() -> CGRect {
let rect = computeProfileHeaderViewFrame()
return CGRect(x: 0, y: rect.origin.y + rect.height, width: mainScrollView.bounds.width, height: segmentedControlContainerHeight)
}
func updateMainScrollViewFrame() {
let bottomHeight = max(currentScrollView.bounds.height, 800)
self.mainScrollView.contentSize = CGSize(
width: view.bounds.width,
height: stickyheaderContainerViewHeight + profileHeaderViewHeight + segmentedControlContainer.bounds.height + bottomHeight)
}
}
extension TwitterProfileViewController: UIScrollViewDelegate {
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffset = scrollView.contentOffset
self.debugContentOffset(contentOffset: contentOffset)
// sticky headerCover
if contentOffset.y <= 0 {
let bounceProgress = min(1, abs(contentOffset.y) / bouncingThreshold)
let newHeight = abs(contentOffset.y) + self.stickyheaderContainerViewHeight
// adjust stickyHeader frame
self.stickyHeaderContainerView.frame = CGRect(
x: 0,
y: contentOffset.y,
width: mainScrollView.bounds.width,
height: newHeight)
// blurring effect amplitude
self.blurEffectView.alpha = min(1, bounceProgress * 2)
// scaling effect
let scalingFactor = 1 + min((bounceProgress + 1), 2)
// print(scalingFactor)
self.headerCoverView.transform = CGAffineTransform(scaleX: scalingFactor, y: scalingFactor)
// adjust mainScrollView indicator insets
var baseInset = computeMainScrollViewIndicatorInsets()
baseInset.top += abs(contentOffset.y)
self.mainScrollView.scrollIndicatorInsets = baseInset
self.mainScrollView.bringSubview(toFront: self.profileHeaderView)
} else {
// anything to be set if contentOffset.y is positive
self.blurEffectView.alpha = 0
self.mainScrollView.scrollIndicatorInsets = computeMainScrollViewIndicatorInsets()
}
// Universal
// applied to every contentOffset.y
let scaleProgress = max(0, min(1, contentOffset.y / self.scrollToScaleDownProfileIconDistance))
self.profileHeaderView.animator(t: scaleProgress)
if contentOffset.y > 0 {
// When scroll View reached the threshold
if contentOffset.y >= scrollToScaleDownProfileIconDistance {
self.stickyHeaderContainerView.frame = CGRect(x: 0, y: contentOffset.y - scrollToScaleDownProfileIconDistance, width: mainScrollView.bounds.width, height: stickyheaderContainerViewHeight)
// bring stickyHeader to the front
self.mainScrollView.bringSubview(toFront: self.stickyHeaderContainerView)
} else {
self.mainScrollView.bringSubview(toFront: self.profileHeaderView)
self.stickyHeaderContainerView.frame = computeStickyHeaderContainerViewFrame()
}
// Sticky Segmented Control
let navigationLocation = CGRect(x: 0, y: 0, width: stickyHeaderContainerView.bounds.width, height: stickyHeaderContainerView.frame.origin.y - contentOffset.y + stickyHeaderContainerView.bounds.height)
let navigationHeight = navigationLocation.height - abs(navigationLocation.origin.y)
let segmentedControlContainerLocationY = stickyheaderContainerViewHeight + profileHeaderViewHeight - navigationHeight
if contentOffset.y > 0 && contentOffset.y >= segmentedControlContainerLocationY {
// if segmentedControlLocation.origin.y <= navigationHeight {
segmentedControlContainer.frame = CGRect(x: 0, y: contentOffset.y + navigationHeight, width: segmentedControlContainer.bounds.width, height: segmentedControlContainer.bounds.height)
} else {
segmentedControlContainer.frame = computeSegmentedControlContainerFrame()
}
// Override
// When scroll View reached the top edge of Title label
if let titleLabel = profileHeaderView.titleLabel, let usernameLabel = profileHeaderView.usernameLabel {
// titleLabel location relative to self.view
let titleLabelLocationY = stickyheaderContainerViewHeight - 35
let totalHeight = titleLabel.bounds.height + usernameLabel.bounds.height + 35
let detailProgress = max(0, min((contentOffset.y - titleLabelLocationY) / totalHeight, 1))
blurEffectView.alpha = detailProgress
animateNaivationTitleAt(progress: detailProgress)
}
}
// Segmented control is always on top in any situations
self.mainScrollView.bringSubview(toFront: segmentedControlContainer)
}
}
// MARK: Animators
extension TwitterProfileViewController {
func animateNaivationTitleAt(progress: CGFloat) {
guard let superview = self.navigationDetailLabel?.superview else {
return
}
let totalDistance: CGFloat = 75
if progress >= 0 {
let distance = (1 - progress) * totalDistance
self.navigationDetailLabel.snp.updateConstraints({ (make) in
make.bottom.equalTo(superview.snp.bottom).inset(8 - distance)
})
}
}
}
// status bar style override
extension TwitterProfileViewController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
// Table View Switching
extension TwitterProfileViewController {
func updateTableViewContent() {
print("currentIndex did changed \(self.currentIndex)")
}
internal func segmentedControlValueDidChange(sender: AnyObject?) {
self.currentIndex = self.segmentedControl.selectedSegmentIndex
let scrollViewToBeShown: UIScrollView! = self.currentScrollView
self.scrollViews.forEach { (scrollView) in
scrollView?.isHidden = scrollView != scrollViewToBeShown
}
scrollViewToBeShown.frame = self.computeTableViewFrame(tableView: scrollViewToBeShown)
self.updateMainScrollViewFrame()
// auto scroll to top if mainScrollView.contentOffset > navigationHeight + segmentedControl.height
let navigationHeight = self.scrollToScaleDownProfileIconDistance
let threshold = self.computeProfileHeaderViewFrame().lf_originBottom - navigationHeight
if mainScrollView.contentOffset.y > threshold {
self.mainScrollView.setContentOffset(CGPoint(x: 0, y: threshold), animated: false)
}
}
}
extension TwitterProfileViewController {
var debugMode: Bool {
return false
}
func showDebugInfo() {
if debugMode {
self.debugTextView = UILabel()
debugTextView.text = "debug mode: on"
debugTextView.backgroundColor = UIColor.white
debugTextView.sizeToFit()
self.view.addSubview(debugTextView)
debugTextView.snp.makeConstraints({ (make) in
make.right.equalTo(self.view.snp.right).inset(16)
make.top.equalTo(self.view.snp.top).inset(16)
})
}
}
func debugContentOffset(contentOffset: CGPoint) {
self.debugTextView?.text = "\(contentOffset)"
}
}
extension CGRect {
var lf_originBottom: CGFloat {
return self.origin.y + self.height
}
}
// MARK: Public interfaces
extension TwitterProfileViewController {
open func numberOfSegments() -> Int {
return 0
}
open func segmentTitle(forSegment index: Int) -> String {
return ""
}
open func prepareForLayout() {
/* to be override */
}
open func scrollView(forSegment index: Int) -> UIScrollView {
return UITableView.init(frame: CGRect.zero, style: .grouped)
}
}
| 2c38e4b04a723b2a87a88f26fcb74862 | 32.658153 | 206 | 0.72064 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/views/SLV917MyPageNoticeCell.swift | mit | 1 | //
// SLV917MyPageNoticeCell.swift
// selluv-ios
//
// Created by 김택수 on 2017. 2. 9..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV917MyPageNoticeCell: UITableViewCell {
@IBOutlet weak var noticeTitleLabel:UILabel!
@IBOutlet weak var dateLabel:UILabel!
@IBOutlet weak var contentLabel:UILabel!
@IBOutlet weak var contentLabelTop:NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
self.initUI()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initUI() {
self.noticeTitleLabel.backgroundColor = UIColor.clear
self.dateLabel.backgroundColor = UIColor.clear
self.contentLabel.backgroundColor = UIColor.clear
self.noticeTitleLabel.text = ""
self.dateLabel.text = ""
self.contentLabel.text = ""
}
func toggledCellHeight() -> CGFloat {
if self.frame.size.height == myPageNoticeCellNormalHeight {
return self.contentLabel.frame.size.height + self.contentLabelTop.constant + 20
} else {
return myPageNoticeCellNormalHeight
}
}
}
| 3d1efcc21b3f14ad424ac31cbea81faa | 26.87234 | 91 | 0.653435 | false | false | false | false |
arsonik/AKTrakt | refs/heads/master | Source/shared/Enums/TraktCrewPosition.swift | mit | 1 | //
// TraktCrewPosition.swift
// Pods
//
// Created by Florian Morello on 01/06/16.
//
//
import Foundation
/**
Represent a crew position
- Production: Production description
- Art: Art description
- Crew: Crew description
- CostumeMakeUp: CostumeMakeUp description
- Directing: Directing description
- Writing: Writing description
- Sound: Sound description
- Camera: Camera description
*/
public enum TraktCrewPosition: String {
case Production = "production"
case Art = "art"
case Crew = "crew"
case CostumeMakeUp = "costume & make-up"
case Directing = "directing"
case Writing = "writing"
case Sound = "sound"
case Camera = "camera"
}
| 1bbc13e8236fea84870c0cfc348e62cb | 21.9375 | 44 | 0.648501 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAddressSearch/Sources/FeatureAddressSearchDomain/Models/AddressSearchResult.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct AddressSearchResult: Codable, Equatable {
public enum AddressType: String {
case address = "Address"
}
enum CodingKeys: String, CodingKey {
case addressId = "id"
case text
case type
case highlight
case description
}
public let addressId: String?
public let text: String?
public let type: String?
public let highlight: String?
public let description: String?
public init(
addressId: String?,
text: String?,
type: String?,
highlight: String?,
description: String?
) {
self.addressId = addressId
self.text = text
self.type = type
self.highlight = highlight
self.description = description
}
}
extension AddressSearchResult {
public var isAddressType: Bool { type == AddressSearchResult.AddressType.address.rawValue }
}
| a480263f29f1342c43a8131d663b0287 | 22.738095 | 95 | 0.631896 | false | false | false | false |
mvader/advent-of-code | refs/heads/master | 2020/04/02.swift | mit | 1 | import Foundation
func parsePassport(_ p: String) -> [String: String] {
return [String: String](
uniqueKeysWithValues: p.components(separatedBy: "\n")
.flatMap { s in s.components(separatedBy: " ") }
.map { s in
let kv = s.components(separatedBy: ":")
return (kv[0], kv[1])
})
}
func numberBetween(_ n: String, min: Int, max: Int) -> Bool {
if let n = Int(n) {
return (min...max).contains(n)
}
return false
}
func matches(_ value: String, pattern: String) -> Bool {
return value.range(of: pattern, options: .regularExpression) != nil
}
let requiredFields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
let validEyeColors = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
func isFieldValid(key: String, value: String) -> Bool {
switch key {
case "byr": return numberBetween(value, min: 1920, max: 2002)
case "iyr": return numberBetween(value, min: 2010, max: 2020)
case "eyr": return numberBetween(value, min: 2020, max: 2030)
case "hgt":
if matches(value, pattern: #"^\d+(cm|in)"#) {
let num = String(value.prefix(value.count - 2))
if value.hasSuffix("cm") {
return numberBetween(num, min: 150, max: 193)
} else {
return numberBetween(num, min: 59, max: 76)
}
}
case "hcl": return matches(value, pattern: #"^#[a-f0-9]{6}$"#)
case "ecl": return validEyeColors.contains(value)
case "pid": return matches(value, pattern: #"^[0-9]{9}$"#)
default: return true
}
return false
}
func isValid(passport: [String: String]) -> Bool {
return requiredFields.allSatisfy { f in passport[f] != nil } && passport.allSatisfy(isFieldValid)
}
let passports = (try String(contentsOfFile: "./input.txt", encoding: .utf8))
.components(separatedBy: "\n\n")
.map(parsePassport)
print(passports.filter(isValid).count)
| b83c1c53f25575dec4511a738b31d824 | 31.192982 | 99 | 0.628883 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode/Linked List/206_Reverse Linked List.swift | mit | 1 | // 206_Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/submissions/
//
// Created by Honghao Zhang on 9/5/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Reverse a singly linked list.
//
//Example:
//
//Input: 1->2->3->4->5->NULL
//Output: 5->4->3->2->1->NULL
//Follow up:
//
//A linked list can be reversed either iteratively or recursively. Could you implement both?
//
import Foundation
//public class ListNode {
// public var val: Int
// public var next: ListNode?
// public init(_ val: Int) {
// self.val = val
// self.next = nil
// }
//}
class Num206 {
// Iteration
func reverseList_Iteration(_ head: ListNode?) -> ListNode? {
let root: ListNode? = nil
var i: ListNode? = root
var j: ListNode? = head
var k: ListNode? = head?.next
while j != nil {
j?.next = i
i = j
j = k
k = k?.next
}
return i
}
// Recursive
func reverseList_Recursive(_ head: ListNode?) -> ListNode? {
if head?.next == nil {
return head
}
let subHead: ListNode? = head?.next
let newHead = reverseList_Recursive(subHead)
subHead?.next = head
head?.next = nil
return newHead
}
func reverseList(_ head: ListNode?) -> ListNode? {
var i: ListNode? = head
var j: ListNode? = i?.next
var k: ListNode? = j?.next
i?.next = nil
while j != nil {
j?.next = i
i = j
j = k
k = k?.next
}
return i
// nil
// 1
// i j k
// 1->2
// i j k
// 1->2->3
// 1->2->3->4->nil
// i j k
// 1 2->3->4->nil
// 1<-2 3->4->nil
// 1<-2 3->4->nil
// i j k
// 1<-2<-3 4->nil
// 1<-2<-3 4->nil
// i j k
// 1<-2<-3<-4
// i j k
}
}
| 49d9ae7d2439a28e9833a8f8b8af3911 | 17.222222 | 92 | 0.521619 | false | false | false | false |
ljshj/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorApp/AppDelegate.swift | agpl-3.0 | 2 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import ActorSDK
@objc public class AppDelegate : ActorApplicationDelegate {
override init() {
super.init()
ActorSDK.sharedActor().inviteUrlHost = "quit.email"
ActorSDK.sharedActor().inviteUrlScheme = "actor"
ActorSDK.sharedActor().style.searchStatusBarStyle = .Default
// Enabling experimental features
ActorSDK.sharedActor().enableExperimentalFeatures = true
// Setting Development Push Id
ActorSDK.sharedActor().apiPushId = 868547
ActorSDK.sharedActor().authStrategy = .PhoneEmail
// Creating Actor
ActorSDK.sharedActor().createActor()
}
public override func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
super.application(application, didFinishLaunchingWithOptions: launchOptions)
ActorSDK.sharedActor().presentMessengerInNewWindow()
return true;
}
} | 713942cbf64d12c73d23ef509ca9baa4 | 28.025641 | 144 | 0.645447 | false | false | false | false |
blinksh/blink | refs/heads/raw | BlinkConfig/BKSSHHost.swift | gpl-3.0 | 1 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import SSH
public struct BKSSHHost {
private let content: [String:Any]
public var bindAddress: String?
public var ciphers: String?
public var compression: Bool?
public var compressionLevel: Int?
//public var connectionAttempts: Int?
public var connectionTimeout: Int?
public var controlMaster: ControlMasterOption?
public var dynamicForward: [OptionalBindAddressInfo]?
public var exitOnForwardFailure: Bool?
public var forwardAgent: Bool?
//public var hostKeyAlias: String?
public var hostbasedAuthentication: Bool?
public var hostKeyAlgorithms: String?
public var hostName: String?
public var identityFile: [String]?
//public var identitiesOnly: Bool?
public var kbdInteractiveAuthentication: Bool?
public var kexAlgorithms: String?
public var localForward: [PortForwardInfo]?
public var logLevel: SSHLogLevel?
public var macs: String?
public var password: String?
//public var numberOfPasswordPrompts: Int?
public var passwordAuthentication: Bool?
public var port: String?
//public var preferredAuthentications: String?
public var proxyCommand: String?
public var proxyJump: String?
public var pubKeyAuthentication: Bool?
public var rekeyLimit: BytesNumber?
public var remoteCommand: String?
public var remoteForward: [PortForwardInfo]?
public var requestTty: TTYBool?
public var sendEnv: [String]?
public var strictHostKeyChecking: Bool?
public var user: String?
public struct ValidationError: Error {
let message: String
public var description: String { message }
}
public init(content: [String: Any]) throws {
self.content = content
func castValue<T: SSHValue>(_ value: Any) throws -> T {
// Values must be mapped to a String
let value = value as! String
return try T(castSSHValue: value)
}
func castList<T: SSHValue>(_ value: Any) throws -> [T] {
if let list = value as? [String] {
return try list.map { try T(castSSHValue: $0) }
} else {
return try (value as! String)
.split(separator: " ")
.map { try T(castSSHValue: String($0)) }
}
}
for (key, value) in content {
do {
let key = key.lowercased()
switch key {
case "bindaddress": self.bindAddress = try castValue(value)
case "ciphers": self.ciphers = try castValue(value)
case "compression": self.compression = try castValue(value)
case "compressionlevel": self.compressionLevel = try castValue(value)
case "connectiontimeout": self.connectionTimeout = try castValue(value)
case "controlmaster": self.controlMaster = try castValue(value)
case "dynamicforward": self.dynamicForward = try castList(value)
case "exitonforwardfailure": self.exitOnForwardFailure = try castValue(value)
case "forwardagent": self.forwardAgent = try castValue(value)
case "kbdinteractiveauthentication": self.kbdInteractiveAuthentication = try castValue(value)
case "hostbasedauthentication": self.hostbasedAuthentication = try castValue(value)
case "hostkeyalgorithms": self.hostKeyAlgorithms = try castValue(value)
case "hostname": self.hostName = try castValue(value)
case "identityfile": self.identityFile = try castList(value)
//case "identitiesonly": self.identitiesOnly = try castValue(value)
case "kexalgorithms": self.kexAlgorithms = try castValue(value)
case "localforward": self.localForward = try castList(value)
case "loglevel": self.logLevel = try castValue(value)
case "macs": self.macs = try castValue(value)
//case "numberofpasswordprompts": self.numberOfPasswordPrompts= try castValue(value)
case "password": self.password = try castValue(value)
case "passwordauthentication": self.passwordAuthentication = try castValue(value)
case "port": self.port = try castValue(value)
//case "preferredAuthentications":self.preferredAuthentications=try castValue(value)
case "proxycommand": self.proxyCommand = try castValue(value)
case "proxyjump": self.proxyJump = try castValue(value)
case "pubkeyauthentication": self.pubKeyAuthentication = try castValue(value)
case "rekeylimit": self.rekeyLimit = try castValue(value)
case "remotecommand": self.remoteCommand = try castValue(value)
case "remoteforward": self.remoteForward = try castList(value)
case "requesttty": self.requestTty = try castValue(value)
case "sendenv": self.sendEnv = try castList(value)
case "stricthostkeychecking": self.strictHostKeyChecking = try castValue(value)
case "user": self.user = try castValue(value)
default:
// Skip unknown
break
}
} catch let error as ValidationError {
throw ValidationError(message: "\(key) \(value) - \(error.message)")
}
}
}
public func merge(_ host: BKSSHHost) throws -> BKSSHHost {
var configDict = content
configDict.mergeWithSSHConfigRules(host.content)
return try BKSSHHost(content: configDict)
}
public func sshClientConfig(authMethods: [SSH.AuthMethod]?,
verifyHostCallback: SSHClientConfig.RequestVerifyHostCallback? = nil,
agent: SSHAgent? = nil,
logger: SSHLogPublisher? = nil) -> SSHClientConfig {
SSHClientConfig(
user: user ?? "root",
port: port,
proxyJump: proxyJump,
proxyCommand: proxyCommand,
authMethods: authMethods,
agent: agent,
loggingVerbosity: logLevel,
verifyHostCallback: verifyHostCallback,
connectionTimeout: connectionTimeout,
sshDirectory: BlinkPaths.ssh()!,
logger: logger,
compression: compression,
compressionLevel: compressionLevel,
ciphers: ciphers,
macs: macs,
bindAddress: bindAddress,
hostKeyAlgorithms: hostKeyAlgorithms,
rekeyDataLimit: rekeyLimit?.rawValue,
kexAlgorithms: kexAlgorithms,
kbdInteractiveAuthentication: kbdInteractiveAuthentication,
passwordAuthentication: passwordAuthentication,
pubKeyAuthentication: pubKeyAuthentication,
hostbasedAuthentication: hostbasedAuthentication
)
}
}
fileprivate protocol SSHValue {
init(castSSHValue val: String) throws
}
extension Bool: SSHValue {
fileprivate init(castSSHValue val: String) throws {
switch val.lowercased() {
case "yes":
self.init(true)
case "no":
self.init(false)
default:
throw BKSSHHost.ValidationError(message: "Value must be yes/no")
}
}
}
extension Int: SSHValue {
fileprivate init(castSSHValue val: String) throws {
guard let _ = Int(val) else {
throw BKSSHHost.ValidationError(message: "Value must be a number")
}
self.init(val)!
}
}
extension UInt: SSHValue {
fileprivate init(castSSHValue val: String) throws {
guard let _ = UInt(val) else {
throw BKSSHHost.ValidationError(message: "Value must be a positive integer.")
}
self.init(val)!
}
}
extension String: SSHValue {
fileprivate init(castSSHValue val: String) throws {
self.init(val)
}
}
extension SSHLogLevel: SSHValue {
fileprivate init(castSSHValue val: String) throws {
guard let _ = SSHLogLevel(val) else {
throw BKSSHHost.ValidationError(message: "Value must be QUIET, etc...")
}
self.init(val)!
}
}
public enum TTYBool: String, SSHValue {
case auto = "auto"
case force = "force"
case yes = "yes"
case no = "no"
fileprivate init(castSSHValue val: String) throws {
guard let _ = TTYBool(rawValue: val) else {
throw BKSSHHost.ValidationError(message: "Value must be auto, force, yes or no")
}
self.init(rawValue: val)!
}
}
public enum ControlMasterOption: String, SSHValue {
case auto = "auto"
case ask = "ask"
case autoask = "autoask"
case yes = "yes"
case no = "no"
fileprivate init(castSSHValue val: String) throws {
guard let _ = ControlMasterOption(rawValue: val) else {
throw BKSSHHost.ValidationError(message: "Value must be auto, ask, autoask, yes or no")
}
self.init(rawValue: val)!
}
}
fileprivate let AddressPattern = #"^((?<localPort>\d+)(:|\s))?(?<bindAddress>\[([\w:.]+)\]|([\w.][\w.-]*)):(?<remotePort>\d+)$"#
public struct PortForwardInfo: Equatable, SSHValue {
public let remotePort: UInt16
public let bindAddress: String
public let localPort: UInt16
fileprivate init(castSSHValue val: String) throws {
try self.init(val)
}
public init(_ info: String) throws {
let regex = try! NSRegularExpression(pattern: AddressPattern)
guard let match = regex.firstMatch(in: info,
range: NSRange(location: 0, length: info.count))
else {
throw BKSSHHost.ValidationError(message: "Missing <localport>:<bind_address>:<remoteport> for port forwarding.")
}
guard let r = Range(match.range(withName: "localPort"), in: info),
let localPort = UInt16(info[r])
else {
throw BKSSHHost.ValidationError(message: "Invalid local port.")
}
self.localPort = localPort
guard let r = Range(match.range(withName: "remotePort"), in: info),
let remotePort = UInt16(info[r])
else {
throw BKSSHHost.ValidationError(message: "Invalid remote port.")
}
self.remotePort = remotePort
guard let r = Range(match.range(withName: "bindAddress"), in: info)
else {
throw BKSSHHost.ValidationError(message: "Invalid bind address.")
}
var bindAddress = String(info[r])
bindAddress.removeAll(where: { $0 == "[" || $0 == "]" })
self.bindAddress = bindAddress
}
}
public struct BindAddressInfo: Equatable, SSHValue {
public let port: UInt16
public let bindAddress: String
fileprivate init(castSSHValue val: String) throws {
try self.init(val)
}
public init(_ info: String) throws {
let addr = try OptionalBindAddressInfo(info)
guard let bindAddress = addr.bindAddress else {
throw BKSSHHost.ValidationError(message: "Invalid bind address.")
}
self.bindAddress = bindAddress
self.port = addr.port
}
}
public struct OptionalBindAddressInfo: Equatable, SSHValue {
public let port: UInt16
public let bindAddress: String?
fileprivate init(castSSHValue val: String) throws {
try self.init(val)
}
public init(_ info: String) throws {
if let port = UInt16(info) {
self.port = port
self.bindAddress = nil
return
}
let regex = try! NSRegularExpression(pattern: AddressPattern)
guard let match = regex.firstMatch(in: info,
range: NSRange(location: 0, length: info.count))
else {
throw BKSSHHost.ValidationError(message: "Missing <bind_address>:<remoteport>.")
}
guard let r = Range(match.range(withName: "remotePort"), in: info),
let port = UInt16(info[r])
else {
throw BKSSHHost.ValidationError(message: "Invalid remote port.")
}
self.port = port
if let r = Range(match.range(withName: "bindAddress"), in: info) {
var bindAddress = String(info[r])
bindAddress.removeAll(where: { $0 == "[" || $0 == "]" })
self.bindAddress = bindAddress
} else {
throw BKSSHHost.ValidationError(message: "Invalid bind address.")
}
}
}
public struct BytesNumber: SSHValue {
let rawValue: UInt
fileprivate init(castSSHValue val: String) throws {
guard let lastChar = val.last else {
throw BKSSHHost.ValidationError(message: "Missing string")
}
if lastChar.isNumber {
self.rawValue = try UInt(castSSHValue: val)
return
}
var number = try UInt(castSSHValue: String(val.dropLast()))
switch lastChar {
case "G":
number = number * 1024
fallthrough
case "M":
number = number * 1024
fallthrough
case "K":
number = number * 1024
default:
throw BKSSHHost.ValidationError(message: "Invalid bytes number.")
}
self.rawValue = number
}
}
| e9174a579f332cbd01c430d832425ee5 | 34.699752 | 128 | 0.621394 | false | false | false | false |
yyny1789/KrMediumKit | refs/heads/master | Source/Utils/Extensions/UIColor+BFKit.swift | mit | 1 | //
// UIColorExtension.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. 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 Foundation
import UIKit
// MARK: - Global functions
/// Create an UIColor in format RGBA.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - alpha: Alpha value.
/// - Returns: Returns the created UIColor.
public func RGBA(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Float) -> UIColor {
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha))
}
/// Create an UIColor in format ARGB.
///
/// - Parameters:
/// - alpha: Alpha value.
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor.
public func ARGB( _ alpha: Float, _ red: Int, _ green: Int, _ blue: Int) -> UIColor {
return RGBA(red, green, blue, alpha)
}
/// Create an UIColor in format RGB.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor.
public func RGB(_ red: Int, _ green: Int, _ blue: Int) -> UIColor {
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
// MARK: - UIColor extension
/// This extesion adds some useful functions to UIColor.
public extension UIColor {
// MARK: - Variables
/// RGB properties: red.
public var redComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
return component![0]
}
return 0.0
}
/// RGB properties: green.
public var greenComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
return component![0]
}
return component![1]
}
return 0.0
}
/// RGB properties: blue.
public var blueComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
return component![0]
}
return component![2]
}
return 0.0
}
/// RGB properties: white.
public var whiteComponent: CGFloat {
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
let component = self.cgColor.__unsafeComponents
return component![0]
}
return 0.0
}
/// RGB properties: luminance.
public var luminance: CGFloat {
if self.canProvideRGBComponents() {
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
if !self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return 0.0
}
return red * 0.2126 + green * 0.7152 + blue * 0.0722
}
return 0.0
}
/// RGBA properties: alpha.
public var alpha: CGFloat {
return self.cgColor.alpha
}
/// HSB properties: hue.
public var hue: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return hue
}
}
return 0.0
}
/// HSB properties: saturation.
public var saturation: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return saturation
}
}
return 0.0
}
/// HSB properties: brightness.
public var brightness: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return brightness
}
}
return 0.0
}
/// Returns the HEX string from UIColor.
public var hex: String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let rgb: Int = (Int)(red * 255) << 16 | (Int)(green * 255) << 8 | (Int)(blue * 255) << 0
return String(format:"#%06x", rgb)
}
// MARK: - Functions
/// Create a color from HEX with alpha.
///
/// - Parameters:
/// - hex: HEX value.
/// - alpha: Alpha value.
public convenience init(hex: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha)
}
/// Create a color from a HEX string.
/// It supports the following type:
/// - #ARGB, ARGB if irstIsAlpha is true. #RGBA, RGBA if firstIsAlpha is false.
/// - #ARGB.
/// - #RRGGBB.
/// - #AARRGGBB, AARRGGBB if irstIsAlpha is true. #RRGGBBAA, RRGGBBAA if firstIsAlpha is false.
///
/// - Parameters:
/// - hexString: HEX string.
/// - alphaFirst: Set it to true if alpha value is the first in the HEX string. If alpha value is the last one, set it to false. Default is false.
public convenience init(hex: String, alphaFirst: Bool = false) {
let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased()
var alpha: CGFloat = 0.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0
switch colorString.length {
case 3: // #RGB
alpha = 1.0
red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1)
green = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1)
blue = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1)
case 4: // #ARGB
alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1)
red = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1)
green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1)
blue = UIColor.colorComponentFrom(colorString, start: 3, lenght: 1)
case 6: // #RRGGBB
alpha = 1.0
red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2)
green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2)
blue = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2)
case 8: // #AARRGGBB
alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2)
red = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2)
green = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2)
blue = UIColor.colorComponentFrom(colorString, start: 6, lenght: 2)
default:
break
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
/// A good contrasting color, it will be either black or white.
///
/// - Returns: Returns the color.
public func contrasting() -> UIColor {
return self.luminance > 0.5 ? UIColor.black : UIColor.white
}
/// A complementary color that should look good.
///
/// - Returns: Returns the color.
public func complementary() -> UIColor? {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if !self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return nil
}
hue += 180
if hue > 360 {
hue -= 360
}
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
/// Check if the color is in RGB format.
///
/// - Returns: Returns if the color is in RGB format.
public func canProvideRGBComponents() -> Bool {
guard let colorSpace = self.cgColor.colorSpace else {
return false
}
switch colorSpace.model {
case CGColorSpaceModel.rgb, CGColorSpaceModel.monochrome:
return true
default:
return false
}
}
/// Returns the color component from the string.
///
/// - Parameters:
/// - fromString: String to convert.
/// - start: Component start index.
/// - lenght: Component lenght.
/// - Returns: Returns the color component from the string.
fileprivate static func colorComponentFrom(_ string: String, start: Int, lenght: Int) -> CGFloat {
var substring: NSString = string as NSString
substring = substring.substring(with: NSMakeRange(start, lenght)) as NSString
let fullHex = lenght == 2 ? substring as String : "\(substring)\(substring)"
var hexComponent: CUnsignedInt = 0
Scanner(string: fullHex).scanHexInt32(&hexComponent)
return CGFloat(hexComponent) / 255.0
}
/// Create a random color.
///
/// - Parameter alpha: Alpha value.
/// - Returns: Returns the UIColor instance.
public static func random(alpha: CGFloat = 1.0) -> UIColor {
let red: UInt32 = arc4random_uniform(255)
let green: UInt32 = arc4random_uniform(255)
let blue: UInt32 = arc4random_uniform(255)
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
/// Create an UIColor from a given string. Example: "blue" or hex string.
///
/// - Parameter color: String with color.
/// - Returns: Returns the created UIColor.
public static func color(string color: String) -> UIColor {
if color.length >= 3 {
if UIColor.responds(to: Selector(color.lowercased() + "Color")) {
return self.convertColor(string: color)
} else {
return UIColor(hex: color)
}
} else {
return UIColor.black
}
}
/// Create an UIColor from a given string like "blue" or an hex string.
///
/// - Parameter color: String with color.
public convenience init(string color: String) {
if UIColor.responds(to: Selector(color.lowercased() + "Color")) {
self.init(cgColor: UIColor.convertColor(string: color).cgColor)
} else {
self.init(hex: color)
}
}
/// Used the retrive the color from the string color ("blue" or "red").
///
/// - Parameter color: String with the color.
/// - Returns: Returns the created UIColor.
private static func convertColor(string color: String) -> UIColor {
let color = color.lowercased()
switch color {
case "black":
return UIColor.black
case "darkgray":
return UIColor.darkGray
case "lightgray":
return UIColor.lightGray
case "white":
return UIColor.white
case "gray":
return UIColor.gray
case "red":
return UIColor.red
case "green":
return UIColor.green
case "blue":
return UIColor.blue
case "cyan":
return UIColor.cyan
case "yellow":
return UIColor.yellow
case "magenta":
return UIColor.magenta
case "orange":
return UIColor.orange
case "purple":
return UIColor.purple
case "brown":
return UIColor.brown
case "clear":
return UIColor.clear
default:
return UIColor.clear
}
}
/// Creates and returns a color object that has the same color space and component values as the given color, but has the specified alpha component.
///
/// - Parameters:
/// - color: UIColor value.
/// - alpha: Alpha value.
/// - Returns: Returns an UIColor instance.
public static func color(color: UIColor, alpha: CGFloat) -> UIColor {
return color.withAlphaComponent(alpha)
}
}
| fa25f882e812445875a375f2940bcaff | 35.033592 | 163 | 0.58702 | false | false | false | false |
cotkjaer/Silverback | refs/heads/master | Silverback/Interpolation.swift | mit | 1 | //
// Interpolation.swift
// Silverback
//
// Created by Christian Otkjær on 30/11/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
import Foundation
import UIKit
func cubicSplineFunction(points: [CGPoint]) -> (Int, CGFloat) -> CGFloat
{
let len = points.count
var x = points.map{$0.x}
var y = points.map{$0.y}
var h = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var u = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var lam = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
for i in 0..<len-1
{
h[i] = x[i+1] - x[i]
}
for i in 1..<len - 1
{
u[i] = h[i-1]/(h[i] + h[i-1])
lam[i] = h[i]/(h[i] + h[i-1])
}
var a = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var b = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var c = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var m = Array<Array<CGFloat>>()
for i in 0..<len
{
m.append(Array<CGFloat>(count: len, repeatedValue: CGFloatZero))
for j in 0..<len
{
m[i][j] = 0
}
if (i == 0)
{
m[i][0] = 2;
m[i][1] = 1;
b[0] = 2;
c[0] = 1;
}
else if (i == (len - 1))
{
m[i][len - 2] = 1;
m[i][len - 1] = 2;
a[len-1] = 1;
b[len-1] = 2;
}
else
{
m[i][i-1] = lam[i];
m[i][i] = 2;
m[i][i+1] = u[i];
a[i] = lam[i];
b[i] = 2;
c[i] = u[i];
}
}
var g = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
g[0] = 3 * (y[1] - y[0])/h[0]
g[len-1] = 3 * (y[len - 1] - y[len - 2])/h[len - 2]
for i in 1..<len - 1
{
let s = u[i] * (y[i+1] - y[i])/h[i]
let t = lam[i] * (y[i] - y[i-1])/h[i-1]
g[i] = 3 * ( t + s )
}
//< Solve the Equations
var p = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var q = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
p[0] = b[0]
for i in 0..<len - 1
{
q[i] = c[i]/p[i]
}
for i in 1..<len
{
p[i] = b[i] - a[i]*q[i-1]
}
var su = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var sq = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
var sx = Array<CGFloat>(count: len, repeatedValue: CGFloatZero)
su[0] = c[0]/b[0]
sq[0] = g[0]/b[0]
for i in 1..<len - 1
{
su[i] = c[i]/(b[i] - su[i-1]*a[i])
}
for i in 1..<len
{
sq[i] = (g[i] - sq[i-1]*a[i])/(b[i] - su[i-1]*a[i]);
}
sx[len-1] = sq[len-1];
for i in Array(0..<len - 1).reverse()
{
sx[i] = sq[i] - su[i]*sx[i+1];
}
let ph = h;
let px = x;
let psx = sx;
let py = y;
let f = { (k: Int, vX: CGFloat) -> CGFloat in
let vX_pXk = vX - px[k]
let vX_pXk1 = vX - px[k+1]
let pow_vX_pXk = vX_pXk * vX_pXk
let pow_vX_pXk1 = vX_pXk1 * vX_pXk1
let phk2 = ph[k] * ph[k]
let phk3 = phk2 * ph[k]
let p1 = (ph[k] + 2 * vX_pXk) * (pow_vX_pXk1) * py[k] / phk3
let p2 = (ph[k] - 2 * vX_pXk1) * pow_vX_pXk * py[k+1] / phk3
let p3 = vX_pXk * pow_vX_pXk1 * psx[k] / phk2
let p4 = vX_pXk1 * pow_vX_pXk * psx[k+1] / phk2
return p1 + p2 + p3 + p4
}
return f
}
func drawCubicSplineInRect(rect: CGRect, points: [CGPoint], inContext context: CGContextRef)
{
let path = UIBezierPath()
let f = cubicSplineFunction(points)
for (i, pt) in points.enumerate()
{
if (i == 0)
{
path.moveToPoint(pt)
}
else
{
let curP = points[i-1]
let delta = CGFloat(1)
for var pointX = curP.x; abs(pointX - pt.x) > 1e-5; pointX += delta
{
let pointY = f(i-1, pointX)
path.addLineToPoint(CGPoint(x: pointX, y: pointY))
}
}
}
path.lineWidth = 1
UIColor.blackColor().setStroke()
path.stroke()
} | 2f6a9d067aa8bae1821fbc281903f263 | 22.747253 | 92 | 0.448507 | false | false | false | false |
magistral-io/MagistralSwift | refs/heads/master | Carthage/Checkouts/CocoaMQTT/Source/CocoaMQTTFrame.swift | mit | 1 | //
// CocoaMQTTFrame.swift
// CocoaMQTT
//
// Created by Feng Lee<[email protected]> on 14/8/3.
// Copyright (c) 2015 emqtt.io. All rights reserved.
//
import Foundation
/**
* Encode and Decode big-endian UInt16
*/
extension UInt16 {
// Most Significant Byte (MSB)
private var highByte: UInt8 {
return UInt8( (self & 0xFF00) >> 8)
}
// Least Significant Byte (LSB)
private var lowByte: UInt8 {
return UInt8(self & 0x00FF)
}
fileprivate var hlBytes: [UInt8] {
return [highByte, lowByte]
}
}
/**
* String with two bytes length
*/
extension String {
// ok?
var bytesWithLength: [UInt8] {
return UInt16(utf8.count).hlBytes + utf8
}
}
/**
* Bool to bit
*/
extension Bool {
fileprivate var bit: UInt8 {
return self ? 1 : 0
}
fileprivate init(bit: UInt8) {
self = (bit == 0) ? false : true
}
}
/**
* read bit
*/
extension UInt8 {
fileprivate func bitAt(_ offset: UInt8) -> UInt8 {
return (self >> offset) & 0x01
}
}
/**
* MQTT Frame Type
*/
enum CocoaMQTTFrameType: UInt8 {
case reserved = 0x00
case connect = 0x10
case connack = 0x20
case publish = 0x30
case puback = 0x40
case pubrec = 0x50
case pubrel = 0x60
case pubcomp = 0x70
case subscribe = 0x80
case suback = 0x90
case unsubscribe = 0xA0
case unsuback = 0xB0
case pingreq = 0xC0
case pingresp = 0xD0
case disconnect = 0xE0
}
/**
* MQTT Frame
*/
open class CocoaMQTTFrame {
/**
* |--------------------------------------
* | 7 6 5 4 | 3 | 2 1 | 0 |
* | Type | DUP flag | QoS | RETAIN |
* |--------------------------------------
*/
var header: UInt8 = 0
var type: UInt8 {
return UInt8(header & 0xF0)
}
var dup: Bool {
get {
return ((header & 0x08) >> 3) == 0 ? false : true
}
set {
header |= (newValue.bit << 3)
}
}
var qos: UInt8 {
// #define GETQOS(HDR) ((HDR & 0x06) >> 1)
get {
return (header & 0x06) >> 1
}
// #define SETQOS(HDR, Q) (HDR | ((Q) << 1))
set {
header |= (newValue << 1)
}
}
var retained: Bool {
get {
return (header & 0x01) == 0 ? false : true
}
set {
header |= newValue.bit
}
}
var variableHeader: [UInt8] = []
var payload: [UInt8] = []
init(header: UInt8) {
self.header = header
}
init(type: CocoaMQTTFrameType, payload: [UInt8] = []) {
self.header = type.rawValue
self.payload = payload
}
func data() -> [UInt8] {
self.pack()
return [UInt8]([header]) + encodeLength() + variableHeader + payload
}
func encodeLength() -> [UInt8] {
var bytes: [UInt8] = []
var digit: UInt8 = 0
var len: UInt32 = UInt32(variableHeader.count+payload.count)
repeat {
digit = UInt8(len % 128)
len = len / 128
// if there are more digits to encode, set the top bit of this digit
if len > 0 {
digit = digit | 0x80
}
bytes.append(digit)
} while len > 0
return bytes
}
// do nothing
func pack() { return; }
}
/**
* MQTT CONNECT Frame
*/
class CocoaMQTTFrameConnect: CocoaMQTTFrame {
let PROTOCOL_LEVEL = UInt8(4)
let PROTOCOL_VERSION: String = "MQTT/3.1.1"
let PROTOCOL_MAGIC: String = "MQTT"
/**
* |----------------------------------------------------------------------------------
* | 7 | 6 | 5 | 4 3 | 2 | 1 | 0 |
* | username | password | willretain | willqos | willflag | cleansession | reserved |
* |----------------------------------------------------------------------------------
*/
var flags: UInt8 = 0
var flagUsername: Bool {
// #define FLAG_USERNAME(F, U) (F | ((U) << 7))
get {
return Bool(bit: (flags >> 7) & 0x01)
}
set {
flags |= (newValue.bit << 7)
}
}
var flagPassword: Bool {
// #define FLAG_PASSWD(F, P) (F | ((P) << 6))
get {
return Bool(bit:(flags >> 6) & 0x01)
}
set {
flags |= (newValue.bit << 6)
}
}
var flagWillRetain: Bool {
// #define FLAG_WILLRETAIN(F, R) (F | ((R) << 5))
get {
return Bool(bit: (flags >> 5) & 0x01)
}
set {
flags |= (newValue.bit << 5)
}
}
var flagWillQOS: UInt8 {
// #define FLAG_WILLQOS(F, Q) (F | ((Q) << 3))
get {
return (flags >> 3) & 0x03
}
set {
flags |= (newValue << 3)
}
}
var flagWill: Bool {
// #define FLAG_WILL(F, W) (F | ((W) << 2))
get {
return Bool(bit:(flags >> 2) & 0x01)
}
set {
flags |= ((newValue.bit) << 2)
}
}
var flagCleanSession: Bool {
// #define FLAG_CLEANSESS(F, C) (F | ((C) << 1))
get {
return Bool(bit: (flags >> 1) & 0x01)
}
set {
flags |= ((newValue.bit) << 1)
}
}
var client: CocoaMQTTClient
init(client: CocoaMQTT) {
self.client = client
super.init(type: CocoaMQTTFrameType.connect)
}
override func pack() {
// variable header
variableHeader += PROTOCOL_MAGIC.bytesWithLength
variableHeader.append(PROTOCOL_LEVEL)
// payload
payload += client.clientID.bytesWithLength
if let will = client.willMessage {
flagWill = true
flagWillQOS = will.qos.rawValue
flagWillRetain = will.retained
payload += will.topic.bytesWithLength
payload += will.payload
}
if let username = client.username {
flagUsername = true
payload += username.bytesWithLength
}
if let password = client.password {
flagPassword = true
payload += password.bytesWithLength
}
// flags
flagCleanSession = client.cleanSession
variableHeader.append(flags)
variableHeader += client.keepAlive.hlBytes
}
}
/**
* MQTT PUBLISH Frame
*/
open class CocoaMQTTFramePublish: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
var data: [UInt8]?
init(msgid: UInt16, topic: String, payload: [UInt8]) {
super.init(type: CocoaMQTTFrameType.publish, payload: payload)
self.msgid = msgid
self.topic = topic
}
init(header: UInt8, data: [UInt8]) {
super.init(header: header)
self.data = data
}
func unpack() {
// topic
if data!.count < 2 {
printWarning("Invalid format of rescived message.")
return
}
var msb = data![0]
var lsb = data![1]
let len = UInt16(msb) << 8 + UInt16(lsb)
var pos = 2 + Int(len)
if data!.count < pos {
printWarning("Invalid format of rescived message.")
return
}
topic = NSString(bytes: [UInt8](data![2...(pos-1)]), length: Int(len), encoding: String.Encoding.utf8.rawValue) as String?
// msgid
if qos == 0 {
msgid = 0
} else {
if data!.count < pos + 2 {
printWarning("Invalid format of rescived message.")
return
}
msb = data![pos]
lsb = data![pos+1]
pos += 2
msgid = UInt16(msb) << 8 + UInt16(lsb)
}
// payload
let end = data!.count - 1
if (end - pos >= 0) {
payload = [UInt8](data![pos...end])
// receives an empty message
} else {
payload = []
}
}
override func pack() {
variableHeader += topic!.bytesWithLength
if qos > 0 {
variableHeader += msgid!.hlBytes
}
}
}
/**
* MQTT PUBACK Frame
*/
class CocoaMQTTFramePubAck: CocoaMQTTFrame {
var msgid: UInt16?
init(type: CocoaMQTTFrameType, msgid: UInt16) {
super.init(type: type)
if type == CocoaMQTTFrameType.pubrel {
qos = CocoaMQTTQOS.qos1.rawValue
}
self.msgid = msgid
}
override func pack() {
variableHeader += msgid!.hlBytes
}
}
/**
* MQTT SUBSCRIBE Frame
*/
class CocoaMQTTFrameSubscribe: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
var reqos: UInt8 = CocoaMQTTQOS.qos0.rawValue
init(msgid: UInt16, topic: String, reqos: UInt8) {
super.init(type: CocoaMQTTFrameType.subscribe)
self.msgid = msgid
self.topic = topic
self.reqos = reqos
self.qos = CocoaMQTTQOS.qos1.rawValue
}
override func pack() {
variableHeader += msgid!.hlBytes
payload += topic!.bytesWithLength
payload.append(reqos)
}
}
/**
* MQTT UNSUBSCRIBE Frame
*/
class CocoaMQTTFrameUnsubscribe: CocoaMQTTFrame {
var msgid: UInt16?
var topic: String?
init(msgid: UInt16, topic: String) {
super.init(type: CocoaMQTTFrameType.unsubscribe)
self.msgid = msgid
self.topic = topic
qos = CocoaMQTTQOS.qos1.rawValue
}
override func pack() {
variableHeader += msgid!.hlBytes
payload += topic!.bytesWithLength
}
}
//MARK: - Buffer
public protocol CocoaMQTTFrameBufferProtocol: class {
func buffer(_ buffer: CocoaMQTTFrameBuffer, sendPublishFrame frame: CocoaMQTTFramePublish)
}
open class CocoaMQTTFrameBuffer: NSObject {
open weak var delegate: CocoaMQTTFrameBufferProtocol?
// flow control
fileprivate var silos = [CocoaMQTTFramePublish]()
fileprivate var silosMaxNumber = 10
fileprivate var buffer = [CocoaMQTTFramePublish]()
fileprivate var bufferSize = 1000
//TODO: bufferCapacity
//fileprivate var bufferCapacity = 50.MB // unit: byte
//
var isBufferEmpty: Bool { get { return buffer.count == 0 }}
var isBufferFull : Bool { get { return buffer.count > bufferSize }}
var isSilosFull : Bool { get { return silos.count >= silosMaxNumber }}
// return false means the frame is rejected because of the buffer is full
open func add(_ frame: CocoaMQTTFramePublish) -> Bool {
guard !isBufferFull else {
printDebug("Buffer is full, message(\(frame.msgid!)) was abandoned.")
return false
}
buffer.append(frame)
tryTransport()
return true
}
// try transport a frame from buffer to silo
func tryTransport() {
if isBufferEmpty || isSilosFull { return }
// take out the earliest frame
let frame = buffer.remove(at: 0)
send(frame)
Timer.after(60.seconds) {
let msgid = frame.msgid!
if self.removeFrameFromSilos(withMsgid: msgid) {
printDebug("timeout of frame:\(msgid)")
}
}
// keep trying after a transport
if frame.qos == 0 {
self.tryTransport()
} else {
silos.append(frame)
if !isSilosFull {
self.tryTransport()
}
}
}
func send(_ frame: CocoaMQTTFramePublish) {
delegate?.buffer(self, sendPublishFrame: frame)
}
open func sendSuccess(withMsgid msgid: UInt16) {
_ = removeFrameFromSilos(withMsgid: msgid)
printDebug("sendMessageSuccess:\(msgid)")
}
func removeFrameFromSilos(withMsgid msgid: UInt16) -> Bool {
var success = false
for (index, item) in silos.enumerated() {
if item.msgid == msgid {
success = true
silos.remove(at: index)
tryTransport()
break
}
}
return success
}
}
| 1225aecae2c4d3e00b7d4a8d3e7794e4 | 23.314741 | 130 | 0.513354 | false | false | false | false |
0416354917/FeedMeIOS | refs/heads/master | EVObjectDescription.swift | bsd-3-clause | 1 | //
// EVObjectDescription.swift
// EVReflection
//
// Created by Edwin Vermeer on 8/19/15.
// Copyright (c) 2015 evict. All rights reserved.
//
import Foundation
/**
Generate a description for an object by extracting information from the NSStringFromClass
*/
public class EVObjectDescription {
/// The name of the bundle
public var bundleName: String = ""
/// The name of the class
public var className: String = ""
/// The classpath starting from the bundle
public var classPath: [String] = []
/// The types of the items in the classpath
public var classPathType: [ObjectType] = []
/// The string representation used by Swift for the classpath
public var swiftClassID: String = ""
/**
Enum for the difrent types that can be part of an object description
*/
public enum ObjectType: String {
/// The target or bunldle
case Target = "t"
/// The Class
case Class = "C"
/// The Protocol
case Protocol = "P"
/// The function
case Function = "F"
/// A generic class
case Generic = "G"
}
/**
Initialize an instance and set all properties based on the object
- parameter forObject: the object that you want the description for
*/
public init(forObject: NSObject) {
bundleName = EVReflection.getCleanAppName()
swiftClassID = NSStringFromClass(forObject.dynamicType)
if swiftClassID.hasPrefix("_T") {
parseTypes((swiftClassID as NSString).substringFromIndex(2))
bundleName = classPath[0]
className = classPath.last!
} else {
// Root objects will already have a . notation
classPath = swiftClassID.characters.split(isSeparator: {$0 == "."}).map({String($0)})
if classPath.count > 1 {
bundleName = classPath[0]
className = classPath.last!
classPathType = [ObjectType](count: classPath.count, repeatedValue: ObjectType.Class)
classPathType[0] = .Target
}
}
}
/**
Get all types from the class string
- parameter classString: the string representation of a class
*/
private func parseTypes(classString: String) {
let characters = Array(classString.characters)
let type: String = String(characters[0])
if Int(type) == nil {
let ot: ObjectType = ObjectType(rawValue: type)!
if ot == .Target {
classPathType.append(ot)
} else {
classPathType.insert(ot, atIndex: 1) // after Target all types are in reverse order
}
parseTypes((classString as NSString).substringFromIndex(1))
} else {
parseNames(classString)
}
}
/**
Get all the names from the class string
:parameter: classString the string representation of the class
*/
private func parseNames(classString: String) {
let characters = Array(classString.characters)
var numForName = ""
var index = 0
while Int(String(characters[index])) != nil {
numForName = "\(numForName)\(characters[index])"
index += 1
}
//let range = Range<String.Index>(start:classString.startIndex.advancedBy(index), end:classString.startIndex.advancedBy((Int(numForName) ?? 0) + index))
let range = classString.startIndex.advancedBy(index)..<classString.startIndex.advancedBy((Int(numForName) ?? 0) + index)
let name = classString.substringWithRange(range)
classPath.append(name)
if name == "" {
return
}
if classPathType[classPath.count - 1] == .Function {
//TODO: reverse engineer function description. For now only allow parameterless function that return void
//No param, no return FS0_FT_T_L_
//No param, return object FS0_FT_CS_
//String param, return object FS0_FSSCS_
//Int param, return object FS0_FSiCS_
//String param, no return FS0_FSST_L_
//2 param return object FS0_FTSS6param2SS_CS_
//3 param return object FS0_FTSS6parambSi6paramcSS_CS_
//3 param, 2 return values FS0_FTSS6parambSi6paramcSS_T1aSS1bCS_
//Parsing rules:
//Always start with FS0_F
//If next is S then 1 param defined by 1 letter type
//If next isT then sequence of S, type (S = string, i = int) number for lenghts, name, if nummer _ then no name
//Ends with T_L_ then no return value
//Ends with CS_ then there will be return value(s)
// New in Swift 2.3 FT_T_L_
if classString.containsString("FS0_") {
index = index + 11
} else {
index = index + 7
}
}
if characters.count > index + Int(numForName)! {
parseNames((classString as NSString).substringFromIndex(index + Int(numForName)!))
}
}
}
| f1277f207081749f7127069475793f59 | 36.561151 | 160 | 0.579391 | false | false | false | false |
AymenFarrah/PlayAir | refs/heads/master | PlayAir/PAPlayerData.swift | mit | 1 | //
// PAPlayerData.swift
// PlayAir
//
// Created by Aymen on 25/02/2016.
// Copyright © 2016 Farrah. All rights reserved.
//
import Foundation
@objc public enum PlayState : Int {
case Ready = 0
case Running = 1
case Playing = 2
case Buffering = 3
case Paused = 4
case Stopped = 5
case Error = 6
case Disposed = 7
}
class PAPlayerData: NSObject {
dynamic var songTitle : String?
dynamic var songBitrate : String?
dynamic var playerState : PlayState
init(title: String, bitrate: String, state:PlayState) {
songTitle = title
songBitrate = bitrate
playerState = state
super.init()
}
} | c543f8533b300ae4c5a9b0a2084039d8 | 18.542857 | 59 | 0.623719 | false | false | false | false |
huangboju/AsyncDisplay_Study | refs/heads/master | AsyncDisplay/Aslayout/OverviewTitleDescriptionCellNode.swift | mit | 1 | //
// OverviewTitleDescriptionCellNode.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/4/21.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import AsyncDisplayKit
class OverviewTitleDescriptionCellNode: ASCellNode {
let titleNode = ASTextNode()
let descriptionNode = ASTextNode()
override init() {
super.init()
addSubnode(titleNode)
addSubnode(descriptionNode)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let hasDescription = descriptionNode.attributedText!.length > 0
let verticalStackLayoutSpec = ASStackLayoutSpec.vertical()
verticalStackLayoutSpec.alignItems = .start
verticalStackLayoutSpec.spacing = 5.0
verticalStackLayoutSpec.children = hasDescription ? [titleNode, descriptionNode] : [titleNode]
return ASInsetLayoutSpec(insets: UIEdgeInsets.init(top: 10, left: 16, bottom: 10, right: 10), child: verticalStackLayoutSpec)
}
}
| 1e046dfb38a726f07dcf55eee8a9c1d6 | 30.34375 | 133 | 0.703888 | false | false | false | false |
inspace-io/INSPhotoGallery | refs/heads/master | INSPhotoGallery/INSPhotosOverlayView.swift | apache-2.0 | 1 | //
// INSPhotosOverlayView.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
public protocol INSPhotosOverlayViewable:class {
var photosViewController: INSPhotosViewController? { get set }
func populateWithPhoto(_ photo: INSPhotoViewable)
func setHidden(_ hidden: Bool, animated: Bool)
func view() -> UIView
}
extension INSPhotosOverlayViewable where Self: UIView {
public func view() -> UIView {
return self
}
}
open class INSPhotosOverlayView: UIView , INSPhotosOverlayViewable {
open private(set) var navigationBar: UINavigationBar!
open private(set) var captionLabel: UILabel!
open private(set) var deleteToolbar: UIToolbar!
open private(set) var navigationItem: UINavigationItem!
open weak var photosViewController: INSPhotosViewController?
private var currentPhoto: INSPhotoViewable?
private var topShadow: CAGradientLayer!
private var bottomShadow: CAGradientLayer!
open var leftBarButtonItem: UIBarButtonItem? {
didSet {
navigationItem.leftBarButtonItem = leftBarButtonItem
}
}
open var rightBarButtonItem: UIBarButtonItem? {
didSet {
navigationItem.rightBarButtonItem = rightBarButtonItem
}
}
#if swift(>=4.0)
open var titleTextAttributes: [NSAttributedString.Key : AnyObject] = [:] {
didSet {
navigationBar.titleTextAttributes = titleTextAttributes
}
}
#else
open var titleTextAttributes: [String : AnyObject] = [:] {
didSet {
navigationBar.titleTextAttributes = titleTextAttributes
}
}
#endif
public override init(frame: CGRect) {
super.init(frame: frame)
setupShadows()
setupNavigationBar()
setupCaptionLabel()
setupDeleteButton()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Pass the touches down to other views
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, with: event) , hitView != self {
return hitView
}
return nil
}
open override func layoutSubviews() {
// The navigation bar has a different intrinsic content size upon rotation, so we must update to that new size.
// Do it without animation to more closely match the behavior in `UINavigationController`
UIView.performWithoutAnimation { () -> Void in
self.navigationBar.invalidateIntrinsicContentSize()
self.navigationBar.layoutIfNeeded()
}
super.layoutSubviews()
self.updateShadowFrames()
}
open func setHidden(_ hidden: Bool, animated: Bool) {
if self.isHidden == hidden {
return
}
if animated {
self.isHidden = false
self.alpha = hidden ? 1.0 : 0.0
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.allowAnimatedContent, .allowUserInteraction], animations: { () -> Void in
self.alpha = hidden ? 0.0 : 1.0
}, completion: { result in
self.alpha = 1.0
self.isHidden = hidden
})
} else {
self.isHidden = hidden
}
}
open func populateWithPhoto(_ photo: INSPhotoViewable) {
self.currentPhoto = photo
if let photosViewController = photosViewController {
if let index = photosViewController.dataSource.indexOfPhoto(photo) {
navigationItem.title = String(format:NSLocalizedString("%d of %d",comment:""), index+1, photosViewController.dataSource.numberOfPhotos)
}
captionLabel.attributedText = photo.attributedTitle
}
self.deleteToolbar.isHidden = photo.isDeletable != true
}
@objc private func closeButtonTapped(_ sender: UIBarButtonItem) {
photosViewController?.dismiss(animated: true, completion: nil)
}
@objc private func actionButtonTapped(_ sender: UIBarButtonItem) {
if let currentPhoto = currentPhoto {
currentPhoto.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in
if let image = (image ?? currentPhoto.thumbnailImage) {
let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityController.popoverPresentationController?.barButtonItem = sender
self?.photosViewController?.present(activityController, animated: true, completion: nil)
}
});
}
}
@objc private func deleteButtonTapped(_ sender: UIBarButtonItem) {
photosViewController?.handleDeleteButtonTapped()
}
private func setupNavigationBar() {
navigationBar = UINavigationBar()
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.backgroundColor = UIColor.clear
navigationBar.barTintColor = nil
navigationBar.isTranslucent = true
navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationItem = UINavigationItem(title: "")
navigationBar.items = [navigationItem]
addSubview(navigationBar)
let topConstraint: NSLayoutConstraint
if #available(iOS 11.0, *) {
topConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .top, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
} else {
topConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0)
}
let widthConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0.0)
let horizontalPositionConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)
self.addConstraints([topConstraint,widthConstraint,horizontalPositionConstraint])
if let bundlePath = Bundle(for: type(of: self)).path(forResource: "INSPhotoGallery", ofType: "bundle") {
let bundle = Bundle(path: bundlePath)
leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "INSPhotoGalleryClose", in: bundle, compatibleWith: nil), landscapeImagePhone: UIImage(named: "INSPhotoGalleryCloseLandscape", in: bundle, compatibleWith: nil), style: .plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:)))
} else {
leftBarButtonItem = UIBarButtonItem(title: "CLOSE".uppercased(), style: .plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:)))
}
rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(INSPhotosOverlayView.actionButtonTapped(_:)))
}
private func setupCaptionLabel() {
captionLabel = UILabel()
captionLabel.translatesAutoresizingMaskIntoConstraints = false
captionLabel.backgroundColor = UIColor.clear
captionLabel.numberOfLines = 0
addSubview(captionLabel)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: captionLabel, attribute: .bottom, multiplier: 1.0, constant: 8.0)
let leadingConstraint = NSLayoutConstraint(item: captionLabel!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0)
let trailingConstraint = NSLayoutConstraint(item: captionLabel!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 8.0)
self.addConstraints([bottomConstraint,leadingConstraint,trailingConstraint])
}
private func setupShadows() {
let startColor = UIColor.black.withAlphaComponent(0.5)
let endColor = UIColor.clear
self.topShadow = CAGradientLayer()
topShadow.colors = [startColor.cgColor, endColor.cgColor]
self.layer.insertSublayer(topShadow, at: 0)
self.bottomShadow = CAGradientLayer()
bottomShadow.colors = [endColor.cgColor, startColor.cgColor]
self.layer.insertSublayer(bottomShadow, at: 0)
self.updateShadowFrames()
}
private func updateShadowFrames(){
topShadow.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 60)
bottomShadow.frame = CGRect(x: 0, y: self.frame.height - 60, width: self.frame.width, height: 60)
}
private func setupDeleteButton() {
deleteToolbar = UIToolbar()
deleteToolbar.translatesAutoresizingMaskIntoConstraints = false
deleteToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
deleteToolbar.setShadowImage(UIImage(), forToolbarPosition: .any)
deleteToolbar.isTranslucent = true
let item = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(INSPhotosOverlayView.deleteButtonTapped(_:)))
deleteToolbar.setItems([item], animated: false)
addSubview(deleteToolbar)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: deleteToolbar, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let trailingConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: deleteToolbar, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let widthConstraint = NSLayoutConstraint(item: deleteToolbar!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 65)
let heightConstraint = NSLayoutConstraint(item: deleteToolbar!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
self.addConstraints([bottomConstraint,trailingConstraint,widthConstraint, heightConstraint])
}
}
| e8f427fb151dd34b66ee25d4c8ff0cac | 44.847107 | 322 | 0.672465 | false | false | false | false |
nicky1525/ZDMetroLabel | refs/heads/master | ZDMetroLabel/ZDMetroLabel/ViewController.swift | mit | 1 | //
// ViewController.swift
// ZDMetroLabel
//
// Created by Nicole De La Feld on 09/03/2015.
// Copyright (c) 2015 ZD. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var metroLabel: ZDMetroLabel!
@IBOutlet weak var metroLabel2: ZDMetroLabel!
@IBOutlet weak var metroLabel3: ZDMetroLabel!
@IBOutlet weak var metroLabel4: ZDMetroLabel!
var timer: NSTimer?
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
metroLabel.direction = .DOWN
metroLabel2.direction = .LEFT
metroLabel3.direction = .UP
metroLabel4.direction = .RIGHT
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)
timer!.fire()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateLabel() {
metroLabel.text = "\(counter)"
metroLabel.layer.borderColor = UIColor.lightGrayColor().CGColor
metroLabel.layer.borderWidth = 0.5
metroLabel.layer.cornerRadius = 7
metroLabel2.text = "\(counter)"
metroLabel3.text = "\(counter)"
metroLabel4.text = "\(counter++)"
}
}
| a892d2803cb11b10f5d3e31f4b94024f | 27.886792 | 138 | 0.651862 | false | false | false | false |
Limon-O-O/Lady | refs/heads/master | Example/MetalRenderContextViewController.swift | mit | 1 | //
// MetalRenderContextViewController.swift
// Lady
//
// Created by Limon on 8/3/16.
// Copyright © 2016 Lady. All rights reserved.
//
import UIKit
import Lady
#if !(arch(i386) || arch(x86_64)) && (os(iOS) || os(watchOS) || os(tvOS))
import MetalKit
@available(iOS 9.0, *)
class MetalRenderContextViewController: UIViewController, MTKViewDelegate {
@IBOutlet private weak var metalView: MTKView!
private var context: CIContext!
private var commandQueue: MTLCommandQueue!
private var inputTexture: MTLTexture!
private let filter = HighPassSkinSmoothingFilter()
override func viewDidLoad() {
super.viewDidLoad()
guard let device = MTLCreateSystemDefaultDevice() else { return }
metalView.device = device
metalView.delegate = self
metalView.framebufferOnly = false
metalView.enableSetNeedsDisplay = true
context = CIContext(mtlDevice: device, options: [kCIContextWorkingColorSpace:CGColorSpaceCreateDeviceRGB()])
commandQueue = device.makeCommandQueue()
inputTexture = try! MTKTextureLoader(device: self.metalView.device!).newTexture(with: UIImage(named: "SampleImage")!.cgImage!, options: nil)
}
func draw(in view: MTKView) {
let commandBuffer = commandQueue.makeCommandBuffer()
let inputCIImage = CIImage(mtlTexture: inputTexture, options: nil)
filter.inputImage = inputCIImage
filter.inputAmount = 0.7
filter.inputRadius = Float(7.0 * (inputCIImage?.extent.width)!/750.0)
let outputCIImage = filter.outputImage!
let cs = CGColorSpaceCreateDeviceRGB()
let outputTexture = view.currentDrawable?.texture
context.render(outputCIImage, to: outputTexture!,
commandBuffer: commandBuffer, bounds: outputCIImage.extent, colorSpace: cs)
commandBuffer.present(view.currentDrawable!)
commandBuffer.commit()
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
view.draw()
}
}
#else
class MetalRenderContextViewController: UIViewController {
@IBOutlet private weak var metalView: UIView!
}
#endif
| 60d2f7f0152ba518da7d14b3fb10a593 | 28.391892 | 148 | 0.692874 | false | false | false | false |
syoung-smallwisdom/BrickBot | refs/heads/master | BrickBot/BrickBot/BBMotorCalibration.swift | mit | 1 | //
// BrickBotMotorCalibration.swift
// BrickBot
//
// Created by Shannon Young on 10/5/15.
// Copyright © 2015 Smallwisdom. All rights reserved.
//
import UIKit
let BBMotorCalibrationCenter: CGFloat = 90;
let BBMotorCalibrationMaxOffset: CGFloat = 75;
public enum BBMotorCalibrationState: Int {
case ForwardLeft = 0, ForwardStraight = 1, ForwardRight = 2, Count
}
public struct BBMotorCalibration: Equatable {
public var calibrationStates:[CGFloat] = [-0.5*BBMotorCalibrationCenter/BBMotorCalibrationMaxOffset, 0, 0.5*BBMotorCalibrationCenter/BBMotorCalibrationMaxOffset];
public init() {
// default value already set
}
public init(calibration:[CGFloat]) {
calibrationStates = calibration
}
public init(data: NSData?) {
// Check that the data is valid
if let data = data where (data.length != BBEmptyBank) { // bank returns a zero if not set
let bytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
for (var ii=0; ii < calibrationStates.count && ii < bytes.count; ii++) {
calibrationStates[ii] = round(((CGFloat(bytes[ii]) - BBMotorCalibrationCenter)/BBMotorCalibrationMaxOffset) * 100)/100
}
}
}
func bytes() -> [UInt8] {
var bytes: [UInt8] = []
for calibration in calibrationStates {
bytes += [UInt8(round(calibration * BBMotorCalibrationMaxOffset) + BBMotorCalibrationCenter)]
}
return bytes
}
mutating func setCalibration(idx: Int, value: CGFloat) {
guard let state = BBMotorCalibrationState(rawValue: idx) else { return; }
calibrationStates[idx] = value
if (state == .ForwardStraight) {
let rightIdx = BBMotorCalibrationState.ForwardRight.rawValue
let leftIdx = BBMotorCalibrationState.ForwardLeft.rawValue
if (calibrationStates[rightIdx] <= value) {
let rightVal = (BBMotorCalibrationCenter + value * BBMotorCalibrationMaxOffset) / (2 * BBMotorCalibrationMaxOffset)
calibrationStates[rightIdx] = round(rightVal * 100.0)/100
}
else if (calibrationStates[leftIdx] >= value) {
let leftVal = (value * BBMotorCalibrationMaxOffset - BBMotorCalibrationCenter) / (2 * BBMotorCalibrationMaxOffset)
calibrationStates[leftIdx] = round(leftVal * 100.0)/100
}
}
}
}
public func == (lhs: BBMotorCalibration, rhs: BBMotorCalibration) -> Bool {
return lhs.calibrationStates == rhs.calibrationStates
}
| 5f958484132c98edef836aecb22a5f06 | 37.676471 | 166 | 0.653992 | false | false | false | false |
IvanVorobei/RequestPermission | refs/heads/master | Example/SPPermission/SPPermission/Frameworks/SparrowKit/Extension/SPUIImageViewExtenshion.swift | mit | 1 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UIImageView {
func setNative() {
self.layer.borderWidth = 0.5
self.layer.borderColor = SPNativeColors.midGray.cgColor
self.layer.masksToBounds = true
}
func downloadedFrom(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit, withComplection complection: @escaping (UIImage?) -> () = {_ in }) {
DispatchQueue.main.async {
self.contentMode = mode
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { complection(nil); return }
DispatchQueue.main.async() { () -> Void in
self.image = image
complection(image)
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit, withComplection complection: @escaping (UIImage?) -> () = {_ in }) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode, withComplection: complection)
}
}
| 9c34e3b8940c8d6f206335014a71aa85 | 44.836364 | 162 | 0.672352 | false | false | false | false |
louchu0604/algorithm-swift | refs/heads/master | TestAPP/TestAPP/NO.89grayCode.swift | mit | 1 | //
// NO.89grayCode.swift
// TestAPP
//
// Created by louchu on 2019/3/4.
// Copyright © 2019年 Cy Lou. All rights reserved.
//
import Foundation
//MARK: 格雷编码
/*
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
*/
func grayCode(_ n: Int) -> [Int] {
if(n<=0)
{
return [0]
}
var result = [Int](repeating: 0, count: 1<<n)//初始化 都为0
let border = n+1
for index in 1..<border
{
let tmp0 = index - 1
let addlength = 1<<tmp0
for tmpindex in 0..<addlength
{
result[2*addlength-tmpindex-1] = addlength+result[tmpindex]
}
}
return result
}
| e1b8087f5feb09c4c3596bde46544694 | 13.894737 | 71 | 0.53828 | false | false | false | false |
mikaelm1/Gradebook | refs/heads/master | Gradebook/CourseGradeVC.swift | mit | 1 | //
// CourseGradeVC.swift
// Gradebook
//
// Created by Mikael Mukhsikaroyan on 4/10/16.
// Copyright © 2016 msquared. All rights reserved.
//
import UIKit
class CourseGradeVC: UIViewController {
@IBOutlet weak var letterGradeLabel: UILabel!
@IBOutlet weak var pointsEarnedLabel: UILabel!
@IBOutlet weak var totalPossiblePointsLabel: UILabel!
@IBOutlet weak var percentageCompleted: UILabel!
var course: Course!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let grade = calculateGrade()
letterGradeLabel.text = "Grade: \(grade.0)"
pointsEarnedLabel.text = "Points Earned: \(grade.1)"
totalPossiblePointsLabel.text = "Total Possible Points: \(grade.2)"
percentageCompleted.text = "Percent of course completed: \(grade.2)%"
}
func calculateGrade() -> (String, Int, Int) {
let assignments = getAssignments()
var score: Double = 0
var total: Double = 0
for i in assignments {
score += (i.gradeScore * i.gradeWeight)
total += i.gradeWeight
}
let points = calculatePointsEarned(assignments)
score = (score / total)
print("Score: \(score)")
let grade = gradeLetterFromScore(score)
return (grade, points, Int(total))
}
func calculatePointsEarned(assignments: [Assignment]) -> Int {
var points: Double = 0
for i in assignments {
let assignmentPoints = (i.gradeScore/100) * i.gradeWeight
points += assignmentPoints
}
return Int(points)
}
func getAssignments() -> [Assignment] {
var assignments = [Assignment]()
if course.assignments?.count > 0 {
for i in course.assignments! {
assignments.append(i as! Assignment)
}
}
return assignments
}
func gradeLetterFromScore(score: Double) -> String {
switch score {
case 93...100:
return Grade.GradeLetter.A.rawValue
case 90..<93:
return Grade.GradeLetter.AMinus.rawValue
case 87..<90:
return Grade.GradeLetter.BPlus.rawValue
case 83..<87:
return Grade.GradeLetter.B.rawValue
case 80..<83:
return Grade.GradeLetter.BMinus.rawValue
case 77..<80:
return Grade.GradeLetter.CPlus.rawValue
case 73..<77:
return Grade.GradeLetter.C.rawValue
case 70..<73:
return Grade.GradeLetter.CMinus.rawValue
case 67..<70:
return Grade.GradeLetter.DPlus.rawValue
case 63..<67:
return Grade.GradeLetter.D.rawValue
case 60..<63:
return Grade.GradeLetter.DMinus.rawValue
default:
return Grade.GradeLetter.F.rawValue
}
}
}
| 8d9a0e81b27d65cb0893298a6b5c6587 | 29.010101 | 77 | 0.595086 | false | false | false | false |
getwagit/Baya | refs/heads/master | Baya/layouts/BayaScrollLayout.swift | mit | 1 | //
// Copyright (c) 2016-2017 wag it GmbH.
// License: MIT
//
import Foundation
import UIKit
/**
A Layout for a ScrollContainer and its content.
*/
public struct BayaScrollLayout: BayaLayout {
public var bayaMargins: UIEdgeInsets
public var frame: CGRect
public let bayaModes: BayaLayoutOptions.Modes
var orientation: BayaLayoutOptions.Orientation
private var container: BayaScrollLayoutContainer
private var content: BayaLayoutable
private var contentMeasure: CGSize?
init(
content: BayaLayoutable,
container: BayaScrollLayoutContainer,
orientation: BayaLayoutOptions.Orientation,
bayaMargins: UIEdgeInsets) {
self.content = content
self.container = container
self.orientation = orientation
self.bayaMargins = bayaMargins
self.frame = CGRect()
self.bayaModes = BayaLayoutOptions.Modes(
width: content.bayaModes.width == .wrapContent && container.bayaModes.width == .wrapContent ?
.wrapContent : .matchParent,
height: content.bayaModes.height == .wrapContent && container.bayaModes.height == .wrapContent ?
.wrapContent : .matchParent)
}
mutating public func layoutWith(frame: CGRect) {
self.frame = frame
let maximalAvailableContentSize = sizeForMeasurement(frame.size)
let measuredContentSize = contentMeasure ?? content.sizeThatFits(maximalAvailableContentSize)
let adjustedContentSize: CGSize
switch orientation {
case .horizontal:
adjustedContentSize = CGSize(
width: content.bayaModes.width == .wrapContent ?
measuredContentSize.width : max(
measuredContentSize.width,
frame.size.width - container.horizontalMargins - content.horizontalMargins),
height: content.bayaModes.height == .wrapContent ?
measuredContentSize.height : frame.height - content.verticalMargins - container.verticalMargins)
case .vertical:
adjustedContentSize = CGSize(
width: content.bayaModes.width == .wrapContent ?
measuredContentSize.width : frame.width - content.horizontalMargins - container.horizontalMargins,
height: content.bayaModes.height == .wrapContent ?
measuredContentSize.height : max(
measuredContentSize.height,
frame.size.height - container.verticalMargins - content.verticalMargins)
)
}
let bayaMargins = content.bayaMargins
content.layoutWith(frame: CGRect(
origin: CGPoint(
x: bayaMargins.left,
y: bayaMargins.top),
size: adjustedContentSize))
container.layoutWith(frame: frame.subtractMargins(ofElement: container))
container.contentSize = adjustedContentSize.addMargins(ofElement: content)
}
mutating public func sizeThatFits(_ size: CGSize) -> CGSize {
let measureSize = sizeForMeasurement(size)
contentMeasure = content.sizeThatFits(measureSize)
return CGSize(
width: min(contentMeasure!.width + content.horizontalMargins + container.horizontalMargins, size.width),
height: min(contentMeasure!.height + content.verticalMargins + container.verticalMargins, size.height))
}
private func sizeForMeasurement(_ size: CGSize) -> CGSize {
let availableWidth: CGFloat
let availableHeight: CGFloat
switch orientation {
case .horizontal:
availableWidth = CGFloat.greatestFiniteMagnitude
availableHeight = size.height - content.verticalMargins - container.verticalMargins
case .vertical:
availableWidth = size.width - content.horizontalMargins - container.horizontalMargins
availableHeight = CGFloat.greatestFiniteMagnitude
}
return CGSize(width: availableWidth, height: availableHeight)
}
}
public extension BayaLayoutable {
/// Lays out the element as content of the given scroll container.
/// - parameter container: Typically a `UIScrollView`. All of the element's views should be sub views
/// of the container.
/// - parameter orientation: Determines the direction in which the element is allowed to extend past the
/// container. This is the direction that may be scrolled, if the element is large enough.
/// - parameter bayaMargins: The margins around the container.
/// - returns: A `BayaScrollLayout`.
func layoutScrollContent(
container: BayaScrollLayoutContainer,
orientation: BayaLayoutOptions.Orientation = .vertical,
bayaMargins: UIEdgeInsets = UIEdgeInsets.zero)
-> BayaScrollLayout {
return BayaScrollLayout(
content: self,
container: container,
orientation: orientation,
bayaMargins: bayaMargins)
}
}
| d35dac16e30607909e43746d5e097d6a | 42.756522 | 118 | 0.66097 | false | false | false | false |
jcfausto/transit-app | refs/heads/master | TransitApp/TransitApp/UIColor+Extension.swift | mit | 1 | //
// UIColor+Extension.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 24/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Foundation
import UIKit
//Custom init with hex string.
extension UIColor {
//This init could fail if the hex string doesn't contain 3 pairs of values for R, G, B.
convenience init(hexString: String) {
let hexColor = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hexColor).scanHexInt(&int)
let a, r, g, b: UInt32
switch hexColor.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
| 266d05f4a3d22441c743e3b1afe2e9c4 | 31.74359 | 119 | 0.5278 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/ProjectNotifications/Controller/ProjectNotificationsViewController.swift | apache-2.0 | 1 | import KsApi
import Library
import Prelude
import UIKit
internal final class ProjectNotificationsViewController: UITableViewController {
fileprivate let viewModel: ProjectNotificationsViewModelType = ProjectNotificationsViewModel()
fileprivate let dataSource = ProjectNotificationsDataSource()
internal static func instantiate() -> ProjectNotificationsViewController {
return Storyboard.Settings.instantiate(ProjectNotificationsViewController.self)
}
internal override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self.dataSource
self.tableView.delegate = self
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Styles.grid(6)))
self.tableView.rowHeight = 44.0
self.viewModel.inputs.viewDidLoad()
}
override func bindStyles() {
super.bindStyles()
_ = self
|> settingsViewControllerStyle
_ = self.tableView
|> \.separatorStyle .~ .singleLine
|> \.separatorColor .~ .ksr_support_300
|> \.separatorInset .~ .init(left: Styles.grid(2))
}
internal override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.projectNotifications
.observeForUI()
.observeValues { [weak self] notifications in
self?.dataSource.load(notifications: notifications)
self?.tableView.reloadData()
}
}
internal override func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt _: IndexPath) {
if let cell = cell as? ProjectNotificationCell {
cell.delegate = self
}
}
}
extension ProjectNotificationsViewController: UITabBarDelegate {
override func tableView(_: UITableView, heightForFooterInSection _: Int) -> CGFloat {
return 0.1 // Required to remove the footer in UITableViewStyleGrouped
}
}
extension ProjectNotificationsViewController: ProjectNotificationCellDelegate {
internal func projectNotificationCell(_: ProjectNotificationCell?, notificationSaveError: String) {
self.present(
UIAlertController.genericError(notificationSaveError),
animated: true,
completion: nil
)
}
}
| 8b7ae78ea53e0c81f9e30de5806cbf35 | 29.557143 | 110 | 0.734923 | false | false | false | false |
NPAW/lib-plugin-ios | refs/heads/master | YouboraLib/YBChrono.swift | mit | 1 | //
// YBChrono.swift
// YouboraLib iOS
//
// Created by Enrique Alfonso Burillo on 08/03/2019.
// Copyright © 2019 NPAW. All rights reserved.
//
import Foundation
/**
* Utility class that provides chronometer like functionality.
* Used to calculate the elapsed time between <start> and <stop> calls.
*/
@objc open class YBChrono: NSObject, NSCopying {
var value: Any?
/// ---------------------------------
/// @name Public properties
/// ---------------------------------
/// Start time
@objc public var startTime: Int64 = 0
@objc public var stopTime: Int64 = 0
@objc public var pauseTime: Int64 = 0
@objc public var offset: Int64 = 0
/// ---------------------------------
/// @name Static properties
/// ---------------------------------
/**
* Returns the current time in milliseconds
* @returns the current time in milliseconds
*/
@objc public var now: Int64 {
return Int64(round(Date().timeIntervalSince1970 * 1000))
}
/// ---------------------------------
/// @name Public methods
/// ---------------------------------
/**
* Returns the time between start and the last stop in ms. Returns -1 if start wasn't called.
* @param stop If true, it will force a stop if it wasn't sent before.
* @return Time lapse in ms or -1 if start was not called.
*/
@objc public func getDeltaTime(_ stop: Bool) -> Int64 {
let now = YBChrono().now
if self.startTime == 0 {
return -1
}
if stop && self.stopTime == 0 {
self.stop()
}
let tempOffset = self.pauseTime != 0 ? now - self.pauseTime : 0
let tempStop = self.stopTime != 0 ? self.stopTime : now
return self.offset - tempOffset + (tempStop - self.startTime)
}
/**
* Same as calling <getDeltaTime:> with stop = false
* @returns the elapsed time in ms since the start call.
*/
//TODO: Remove when there is no trace of objc
@objc public func getDeltaTime() -> Int64 {
return getDeltaTime(true)
}
/**
* Starts timing
*/
@objc public func start() {
self.startTime = YBChrono().now
self.stopTime = 0
self.offset = 0
}
/**
* Pauses timing
*/
@objc public func pause() {
self.pauseTime = YBChrono().now
}
/**
* Resumes timing
*/
@objc public func resume() {
self.offset -= YBChrono().now - pauseTime
self.pauseTime = 0
}
/**
* Stop the timer and returns the difference since it <start>ed
* @returns the difference since it <start>ed
*/
@objc @discardableResult public func stop() -> Int64 {
if pauseTime != 0 {
resume()
}
self.stopTime = YBChrono().now
return getDeltaTime(false)
}
/**
* Reset the Chrono to its initial state.
*/
@objc public func reset() {
self.startTime = 0
self.stopTime = 0
self.pauseTime = 0
self.offset = 0
}
@objc public func copy(with zone: NSZone? = nil) -> Any {
let c = YBChrono()
c.startTime = self.startTime
c.stopTime = self.stopTime
c.pauseTime = self.pauseTime
c.offset = self.offset
return c
}
}
| 04e5c7a8537b16692774e7550a18274a | 25.706349 | 97 | 0.530461 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Comments/CommentDetailInfoViewController.swift | gpl-2.0 | 1 | import Foundation
import WordPressUI
import UIKit
protocol CommentDetailInfoView: AnyObject {
func showAuthorPage(url: URL)
}
final class CommentDetailInfoViewController: UIViewController {
private static let cellReuseIdentifier = "infoCell"
private let tableView: UITableView = {
$0.translatesAutoresizingMaskIntoConstraints = false
return $0
}(UITableView())
private let viewModel: CommentDetailInfoViewModelType
init(viewModel: CommentDetailInfoViewModelType) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
addTableViewConstraints()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setPreferredContentSize()
}
private func configureTableView() {
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
}
private func addTableViewConstraints() {
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor)
])
}
private func setPreferredContentSize() {
tableView.layoutIfNeeded()
preferredContentSize = tableView.contentSize
}
}
// MARK: - CommentDetailInfoView
extension CommentDetailInfoViewController: CommentDetailInfoView {
func showAuthorPage(url: URL) {
let viewController = WebViewControllerFactory.controllerAuthenticatedWithDefaultAccount(url: url, source: "comment_detail")
let navigationControllerToPresent = UINavigationController(rootViewController: viewController)
present(navigationControllerToPresent, animated: true, completion: nil)
}
}
// MARK: - UITableViewDatasource
extension CommentDetailInfoViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewModel.userDetails.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Self.cellReuseIdentifier)
?? .init(style: .subtitle, reuseIdentifier: Self.cellReuseIdentifier)
let info = viewModel.userDetails[indexPath.item]
cell.selectionStyle = .none
cell.tintColor = .primary
cell.textLabel?.font = WPStyleGuide.fontForTextStyle(.subheadline)
cell.textLabel?.textColor = .textSubtle
cell.textLabel?.text = info.title
cell.detailTextLabel?.font = WPStyleGuide.fontForTextStyle(.body)
cell.detailTextLabel?.textColor = .text
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.text = info.description.isEmpty ? " " : info.description // prevent the cell from collapsing due to empty label text.
return cell
}
}
// MARK: - UITableViewDelegate
extension CommentDetailInfoViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.didSelectItem(at: indexPath.item)
}
}
// MARK: - DrawerPresentable
extension CommentDetailInfoViewController: DrawerPresentable {
var collapsedHeight: DrawerHeight {
.intrinsicHeight
}
var allowsUserTransition: Bool {
false
}
var compactWidth: DrawerWidth {
.maxWidth
}
}
// MARK: - ChildDrawerPositionable
extension CommentDetailInfoViewController: ChildDrawerPositionable {
var preferredDrawerPosition: DrawerPosition {
.collapsed
}
}
| d30f5e16d4df5eccc41944cfbbeeb890 | 31.227642 | 147 | 0.713925 | false | false | false | false |
Allow2CEO/browser-ios | refs/heads/master | brave/src/frontend/BraveURLBarView.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
let TabsBarHeight = CGFloat(29)
extension UILabel {
func bold(range: ClosedRange<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
}
class ButtonWithUnderlayView : UIButton {
lazy var starView: UIImageView = {
let v = UIImageView()
v.contentMode = .center
self.addSubview(v)
v.isUserInteractionEnabled = false
v.snp.makeConstraints {
make in
make.center.equalTo(self.snp.center)
}
return v
}()
// Visible when button is selected
lazy var underlay: UIView = {
let v = UIView()
if UIDevice.current.userInterfaceIdiom == .pad {
v.backgroundColor = BraveUX.ProgressBarColor
v.layer.cornerRadius = 4
v.layer.borderWidth = 0
v.layer.masksToBounds = true
}
v.isUserInteractionEnabled = false
v.isHidden = true
return v
}()
func hideUnderlay(_ hide: Bool) {
underlay.isHidden = hide
starView.isHidden = !hide
}
// func setStarImageBookmarked(_ on: Bool) {
// let starName = on ? "listpanel_bookmarked_star" : "listpanel_notbookmarked_star"
// let templateMode: UIImageRenderingMode = on ? .alwaysOriginal : .alwaysTemplate
// starView.image = UIImage(named: starName)!.withRenderingMode(templateMode)
// }
}
class BraveURLBarView : URLBarView {
static var CurrentHeight = UIConstants.ToolbarHeight
fileprivate static weak var currentInstance: BraveURLBarView?
lazy var leftSidePanelButton: ButtonWithUnderlayView = { return ButtonWithUnderlayView() }()
lazy var braveButton = { return UIButton() }()
lazy var readerModeToolbar: ReaderModeBarView = {
let toolbar = ReaderModeBarView(frame: CGRect.zero)
toolbar.isHidden = true
toolbar.delegate = getApp().browserViewController
return toolbar
}()
let tabsBarController = TabsBarViewController()
override func commonInit() {
BraveURLBarView.currentInstance = self
locationContainer.layer.cornerRadius = BraveUX.TextFieldCornerRadius
addSubview(leftSidePanelButton.underlay)
addSubview(leftSidePanelButton)
addSubview(braveButton)
super.commonInit()
leftSidePanelButton.addTarget(self, action: #selector(onClickLeftSlideOut), for: UIControlEvents.touchUpInside)
leftSidePanelButton.setImage(UIImage(named: "listpanel")?.withRenderingMode(.alwaysTemplate), for: .normal)
// leftSidePanelButton.setImage(UIImage(named: "listpanel_down")?.withRenderingMode(.alwaysTemplate), for: .selected)
leftSidePanelButton.accessibilityLabel = Strings.Bookmarks_and_History_Panel
// leftSidePanelButton.setStarImageBookmarked(false)
braveButton.addTarget(self, action: #selector(onClickBraveButton) , for: UIControlEvents.touchUpInside)
braveButton.setImage(UIImage(named: "bravePanelButton"), for: .normal)
braveButton.accessibilityLabel = Strings.Brave_Panel
braveButton.tintColor = BraveUX.ActionButtonTintColor
tabsBarController.view.alpha = 0.0
addSubview(tabsBarController.view)
getApp().browserViewController.addChildViewController(tabsBarController)
tabsBarController.didMove(toParentViewController: getApp().browserViewController)
addSubview(readerModeToolbar)
}
override func updateTabsBarShowing() {
var tabCount = getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.count
let showingPolicy = TabsBarShowPolicy(rawValue: Int(BraveApp.getPrefs()?.intForKey(kPrefKeyTabsBarShowPolicy) ?? Int32(kPrefKeyTabsBarOnDefaultValue.rawValue))) ?? kPrefKeyTabsBarOnDefaultValue
let bvc = getApp().browserViewController
let noShowDueToPortrait = UIDevice.current.userInterfaceIdiom == .phone &&
bvc!.shouldShowFooterForTraitCollection(bvc!.traitCollection) &&
showingPolicy == TabsBarShowPolicy.landscapeOnly
let isShowing = tabsBarController.view.alpha > 0
let shouldShow = showingPolicy != TabsBarShowPolicy.never && tabCount > 1 && !noShowDueToPortrait
func updateOffsets() {
bvc?.headerHeightConstraint?.update(offset: BraveURLBarView.CurrentHeight)
bvc?.webViewContainerTopOffset?.update(offset: BraveURLBarView.CurrentHeight)
}
if !isShowing && shouldShow {
self.tabsBarController.view.alpha = 1
BraveURLBarView.CurrentHeight = TabsBarHeight + UIConstants.ToolbarHeight
updateOffsets()
} else if isShowing && !shouldShow {
UIView.animate(withDuration: 0.1, animations: {
self.tabsBarController.view.alpha = 0
}, completion: { _ in
BraveURLBarView.CurrentHeight = UIConstants.ToolbarHeight
UIView.animate(withDuration: 0.2, animations: {
updateOffsets()
bvc?.view.layoutIfNeeded()
})
})
}
}
override func applyTheme(_ themeName: String) {
super.applyTheme(themeName)
guard let theme = URLBarViewUX.Themes[themeName] else { return }
leftSidePanelButton.tintColor = theme.buttonTintColor
switch(themeName) {
case Theme.NormalMode:
backgroundColor = BraveUX.ToolbarsBackgroundSolidColor
case Theme.PrivateMode:
backgroundColor = BraveUX.DarkToolbarsBackgroundSolidColor
default:
break
}
}
override func updateAlphaForSubviews(_ alpha: CGFloat) {
super.updateAlphaForSubviews(alpha)
// TODO tabsBarController use view.alpha to determine if it is shown or hidden, ideally this could be refactored to that
// any callers can do tabsBarController.view.alpha == xx, without knowing that it has a side-effect
tabsBarController.view.subviews.forEach { $0.alpha = alpha }
readerModeToolbar.alpha = alpha
leftSidePanelButton.alpha = alpha
braveButton.alpha = alpha
}
@objc func onClickLeftSlideOut() {
leftSidePanelButton.isSelected = !leftSidePanelButton.isSelected
NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationLeftSlideOutClicked), object: leftSidePanelButton)
}
@objc func onClickBraveButton() {
NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationBraveButtonClicked), object: braveButton)
}
override func updateTabCount(_ count: Int, animated: Bool = true) {
super.updateTabCount(count, animated: bottomToolbarIsHidden)
BraveBrowserBottomToolbar.updateTabCountDuplicatedButton(count, animated: animated)
}
class func tabButtonPressed() {
guard let instance = BraveURLBarView.currentInstance else { return }
instance.delegate?.urlBarDidPressTabs(instance)
}
override var accessibilityElements: [Any]? {
get {
if inSearchMode {
guard let locationTextField = locationTextField else { return nil }
return [leftSidePanelButton, locationTextField, cancelButton]
} else {
if bottomToolbarIsHidden {
return [backButton, forwardButton, leftSidePanelButton, locationView, braveButton, shareButton, tabsButton]
} else {
return [leftSidePanelButton, locationView, braveButton]
}
}
}
set {
super.accessibilityElements = newValue
}
}
override func updateViewsForSearchModeAndToolbarChanges() {
super.updateViewsForSearchModeAndToolbarChanges()
self.tabsButton.isHidden = !self.bottomToolbarIsHidden
}
override func prepareSearchAnimation() {
super.prepareSearchAnimation()
braveButton.isHidden = true
// If view is in reader mode, toolbar needs to be hidden.
// Otherwise it stays behind search screen but still responds to user gestures
if locationView.readerModeState == .Active {
readerModeToolbar.isHidden = true
}
}
override func transitionToSearch(_ didCancel: Bool = false) {
super.transitionToSearch(didCancel)
locationView.alpha = 0.0
}
override func leaveSearchMode(didCancel cancel: Bool) {
if !inSearchMode {
return
}
super.leaveSearchMode(didCancel: cancel)
locationView.alpha = 1.0
// The orange brave button sliding in looks odd, lets fade it in in-place
braveButton.alpha = 0
braveButton.isHidden = false
UIView.animate(withDuration: 0.3, animations: { self.braveButton.alpha = 1.0 })
// After leaving search mode we need to check wheter view is in reader mode to show it again
if locationView.readerModeState == .Active {
readerModeToolbar.isHidden = false
}
}
override func updateConstraints() {
super.updateConstraints()
if tabsBarController.view.superview != nil {
bringSubview(toFront: tabsBarController.view)
tabsBarController.view.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(self)
make.height.equalTo(TabsBarHeight)
}
}
clipsToBounds = false
bringSubview(toFront: readerModeToolbar)
readerModeToolbar.snp.makeConstraints {
make in
make.left.right.equalTo(self)
make.top.equalTo(snp.bottom)
make.height.equalTo(BraveUX.ReaderModeBarHeight)
}
leftSidePanelButton.underlay.snp.makeConstraints {
make in
make.left.right.equalTo(leftSidePanelButton).inset(4)
make.top.bottom.equalTo(leftSidePanelButton).inset(7)
}
remakeLocationView()
}
private func remakeLocationView() {
func pinLeftPanelButtonToLeft() {
leftSidePanelButton.snp.remakeConstraints { make in
if #available(iOS 11, *) {
make.left.equalTo(self.safeAreaLayoutGuide.snp.left)
} else {
make.left.equalTo(self)
}
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
if inSearchMode {
pwdMgrButton.isHidden = true
// In overlay mode, we always show the location view full width
self.locationContainer.snp.remakeConstraints { make in
make.left.equalTo(self.leftSidePanelButton.snp.right)//.offset(URLBarViewUX.LocationLeftPadding)
make.right.equalTo(self.cancelButton.snp.left)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.top.equalTo(self).inset(URLBarViewUX.LocationInset)
}
pinLeftPanelButtonToLeft()
} else {
self.locationContainer.snp.remakeConstraints { make in
if self.bottomToolbarIsHidden {
// Firefox is not referring to the bbackgrottom toolbar, it is asking is this class showing more tool buttons
make.leading.equalTo(self.leftSidePanelButton.snp.trailing)
let insetValue = -(UIConstants.ToolbarHeight * (3 + (pwdMgrButton.isHidden == false ? 1 : 0)))
if #available(iOS 11, *) {
make.trailing.equalTo(self.safeAreaLayoutGuide.snp.trailing).inset(insetValue)
} else {
make.trailing.equalTo(self).inset(insetValue)
}
} else {
make.left.right.equalTo(self).inset(UIConstants.ToolbarHeight)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.top.equalTo(self).inset(URLBarViewUX.LocationInset)
}
if self.bottomToolbarIsHidden {
leftSidePanelButton.snp.remakeConstraints { make in
make.left.equalTo(self.forwardButton.snp.right)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(UIConstants.ToolbarHeight)
}
} else {
pinLeftPanelButtonToLeft()
}
braveButton.snp.remakeConstraints { make in
make.left.equalTo(self.locationContainer.snp.right)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(UIConstants.ToolbarHeight)
}
pwdMgrButton.snp.updateConstraints { make in
make.width.equalTo(pwdMgrButton.isHidden ? 0 : UIConstants.ToolbarHeight)
}
}
}
override func setupConstraints() {
backButton.snp.remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
if #available(iOS 11, *) {
make.left.equalTo(self.safeAreaLayoutGuide.snp.left)
} else {
make.left.equalTo(self)
}
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp.makeConstraints { make in
make.left.equalTo(self.backButton.snp.right)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(backButton)
}
leftSidePanelButton.snp.makeConstraints { make in
make.left.equalTo(self.forwardButton.snp.right)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(UIConstants.ToolbarHeight)
}
locationView.snp.makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp.makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
if #available(iOS 11, *) {
make.trailing.equalTo(self.safeAreaLayoutGuide.snp.trailing)
} else {
make.trailing.equalTo(self)
}
}
shareButton.snp.remakeConstraints { make in
make.right.equalTo(self.pwdMgrButton.snp.left).offset(0)
make.centerY.equalTo(self.locationContainer)
make.width.equalTo(UIConstants.ToolbarHeight)
}
pwdMgrButton.snp.remakeConstraints { make in
make.right.equalTo(self.tabsButton.snp.left).offset(0)
make.centerY.equalTo(self.locationContainer)
make.width.equalTo(0)
}
tabsButton.snp.makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.right.equalTo(self)
if #available(iOS 11, *) {
make.right.equalTo(self.safeAreaLayoutGuide.snp.right)
} else {
make.right.equalTo(self)
}
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
fileprivate var progressIsCompleting = false
fileprivate var updateIsScheduled = false
override func updateProgressBar(_ progress: Float, dueToTabChange: Bool = false) {
struct staticProgress { static var val = Float(0) }
let minProgress = locationView.frame.width / 3.0
locationView.braveProgressView.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.ProgressBarDarkColor : BraveUX.ProgressBarColor
func setWidth(_ width: CGFloat) {
var frame = locationView.braveProgressView.frame
frame.size.width = width
locationView.braveProgressView.frame = frame
}
if dueToTabChange {
if (progress == 1.0 || progress == 0.0) {
locationView.braveProgressView.alpha = 0
}
else {
locationView.braveProgressView.alpha = 1
setWidth(minProgress + CGFloat(progress) * (self.locationView.frame.width - minProgress))
}
return
}
func performUpdate() {
let progress = staticProgress.val
if progress == 1.0 || progress == 0 {
if progressIsCompleting {
return
}
progressIsCompleting = true
UIView.animate(withDuration: 0.5, animations: {
setWidth(self.locationView.frame.width)
}, completion: { _ in
UIView.animate(withDuration: 0.5, animations: {
self.locationView.braveProgressView.alpha = 0.0
}, completion: { _ in
self.progressIsCompleting = false
setWidth(0)
})
})
} else {
self.locationView.braveProgressView.alpha = 1.0
progressIsCompleting = false
let w = minProgress + CGFloat(progress) * (self.locationView.frame.width - minProgress)
if w > locationView.braveProgressView.frame.size.width {
UIView.animate(withDuration: 0.5, animations: {
setWidth(w)
}, completion: { _ in
})
}
}
}
staticProgress.val = progress
if updateIsScheduled {
return
}
updateIsScheduled = true
postAsyncToMain(0.2) {
self.updateIsScheduled = false
performUpdate()
}
}
override func updateBookmarkStatus(_ isBookmarked: Bool) {
getApp().braveTopViewController.updateBookmarkStatus(isBookmarked)
//leftSidePanelButton.setStarImageBookmarked(isBookmarked)
}
func setBraveButtonState(shieldsEnabled: Bool, animated: Bool) {
let buttonImageName = shieldsEnabled ? "bravePanelButton" : "bravePanelButtonOff"
braveButton.setImage(UIImage(named: buttonImageName), for: .normal)
}
}
| 412f6fa5ec996c339bd14c39eb0ed848 | 38.146392 | 201 | 0.618508 | false | false | false | false |
CoderFeiSu/FFCategoryHUD | refs/heads/master | FFCategoryHUD/FFKeyboardContainer.swift | mit | 1 | // FFImageKeyboardContainer.swift
// FFCategoryHUDExample
//
// Created by Freedom on 2017/5/12.
// Copyright © 2017年 Freedom. All rights reserved.
//
import UIKit
@objc public protocol FFKeyboardContainerDelegate : class {
@objc optional func keyboardContainer(_ keyboardContainer: FFKeyboardContainer,didSelectItemAt indexPath: IndexPath)
@objc optional func keyboardContainer(_ keyboardContainer: FFKeyboardContainer, didDeselectItemAt indexPath: IndexPath)
}
public protocol FFKeyboardContainerDataSource : class {
func numberOfSections(in keyboardContainer: FFKeyboardContainer) -> Int
func keyboardContainer(_ keyboardContainer: FFKeyboardContainer, numberOfItemsInSection section: Int) -> Int
func keyboardContainer(_ keyboardContainer: FFKeyboardContainer, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
}
public class FFKeyboardContainer: UIView {
weak public var dataSource: FFKeyboardContainerDataSource?
weak public var delegate: FFKeyboardContainerDelegate?
fileprivate var content: FFKeyboardContent?
fileprivate var layout: FFCategoryKeyboardLayout
fileprivate var barStyle: FFKeyboardBarStyle
fileprivate var barTitles: [String]
/**
barTitles: 工具条文字
barStyle: 工具条样式
layout: 小格子样式
*/
public init(frame: CGRect, barTitles: [String], barStyle: FFKeyboardBarStyle, layout: FFCategoryKeyboardLayout) {
self.barTitles = barTitles
self.barStyle = barStyle
self.layout = layout
super.init(frame: frame)
addChildView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension FFKeyboardContainer {
public func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) {
self.content?.register(cellClass, forCellWithReuseIdentifier: identifier)
}
public func reloadData() {
self.content?.reloadData()
}
public func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell {
return (self.content?.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath))!
}
public func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell? {
return self.content?.cellForItem(at: indexPath)
}
}
extension FFKeyboardContainer: FFKeyboardContentDataSource, FFKeyboardContentDelegate {
func numberOfSections(in keyboardContent: FFKeyboardContent) -> Int {
assert(dataSource != nil, "dataSource不能为空")
let sections = dataSource?.numberOfSections(in: self) ?? 0
assert(barTitles.count == sections, "文字标题数量必须和section数量相等")
return sections
}
func keyboardContent(_ keyboardContent: FFKeyboardContent, numberOfItemsInSection section: Int) -> Int {
return dataSource?.keyboardContainer(self, numberOfItemsInSection: section) ?? 0
}
func keyboardContent(_ keyboardContent: FFKeyboardContent, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = dataSource?.keyboardContainer(self, cellForItemAt: indexPath)
return cell!
}
func keyboardContent(_ keyboardContent: FFKeyboardContent,didSelectItemAt indexPath: IndexPath) {
self.delegate?.keyboardContainer?(self, didSelectItemAt: indexPath)
}
func categoryKeyboardView(_ categoryKeyboardView: FFKeyboardContent, didDeselectItemAt indexPath: IndexPath) {
self.delegate?.keyboardContainer?(self, didDeselectItemAt: indexPath)
}
}
extension FFKeyboardContainer {
fileprivate func addChildView() {
// 添加文字标题
var barY: CGFloat = 0
barStyle.isTitleOnTop ? (barY = 0) : (barY = bounds.height - barStyle.height)
let barFrame = CGRect(x: 0, y: barY, width: bounds.width, height: barStyle.height)
let bar = FFKeyboardBar.init(frame: barFrame, titles: barTitles, style: barStyle)
addSubview(bar)
// 添加内容
var contentY: CGFloat = 0
barStyle.isTitleOnTop ? (contentY = barStyle.height) : (contentY = 0)
let contentFrame = CGRect(x: 0, y: contentY, width: bounds.width, height: bounds.height - barStyle.height)
let content = FFKeyboardContent.init(frame: contentFrame, style: barStyle, layout: layout)
bar.delegate = content
content.actionDelegate = bar
content.delegate = self
content.dataSource = self
addSubview(content)
self.content = content
}
}
| 1e7ea49ea799e57795fc24cac5028542 | 35.864 | 128 | 0.711372 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | Carthage/Checkouts/Eureka/Source/Core/BaseRow.swift | apache-2.0 | 3 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
open class BaseRow: BaseRowType {
var callbackOnChange: (() -> Void)?
var callbackCellUpdate: (() -> Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (() -> Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var callbackOnCellHighlightChanged: (() -> Void)?
var callbackOnRowValidationChanged: (() -> Void)?
var _inlineRow: BaseRow?
var _cachedOptionsData: Any?
public var validationOptions: ValidationOptions = .validatesOnBlur
// validation state
public internal(set) var validationErrors = [ValidationError]() {
didSet {
guard validationErrors != oldValue else { return }
RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self)
callbackOnRowValidationChanged?()
updateCell()
}
}
public internal(set) var wasBlurred = false
public internal(set) var wasChanged = false
public var isValid: Bool { return validationErrors.isEmpty }
public var isHighlighted: Bool = false
/// The title will be displayed in the textLabel of the row.
public var title: String?
/// Parameter used when creating the cell for this row.
public var cellStyle = UITableViewCell.CellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
public var tag: String?
/// The untyped cell associated to this row.
public var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
public var baseValue: Any? {
set {}
get { return nil }
}
open func validate(quietly: Bool = false) -> [ValidationError] {
return []
}
// Reset validation
open func cleanValidationErrors() {
validationErrors = []
}
public static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
public var disabled: Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
public var hidden: Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
public var isDisabled: Bool { return disabledCache }
/// Returns if this row is currently hidden or not
public var isHidden: Bool { return hiddenCache }
/// The section to which this row belongs.
open weak var section: Section?
public lazy var trailingSwipe = {[unowned self] in SwipeConfiguration(self)}()
//needs the accessor because if marked directly this throws "Stored properties cannot be marked potentially unavailable with '@available'"
private lazy var _leadingSwipe = {[unowned self] in SwipeConfiguration(self)}()
@available(iOS 11,*)
public var leadingSwipe: SwipeConfiguration{
get { return self._leadingSwipe }
set { self._leadingSwipe = newValue }
}
public required init(tag: String? = nil) {
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
open func prepare(for segue: UIStoryboardSegue) {}
/**
Helps to pick destination part of the cell after scrolling
*/
open var destinationScrollPosition: UITableView.ScrollPosition? = UITableView.ScrollPosition.bottom
/**
Returns the IndexPath where this row is in the current form.
*/
public final var indexPath: IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.firstIndex(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
var hiddenCache = false
var disabledCache = false {
willSet {
if newValue && !disabledCache {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_, let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hide(row: self)
} else {
section?.show(row: self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_, let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedTo(section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers() {
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm() {
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func willBeRemovedFromSection() {
willBeRemovedFromForm()
section = nil
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers() {
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(with rowAnimation: UITableView.RowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(animated: Bool = true) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(animated: Bool = false, scrollPosition: UITableView.ScrollPosition = .none) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
}
public func == (lhs: BaseRow, rhs: BaseRow) -> Bool {
return lhs === rhs
}
| c533feb0bb8322df5c3fe564a7ed819e | 34.370748 | 177 | 0.655448 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Runtime/Registers.swift | apache-2.0 | 1 | //
// Registers.swift
// LispKit
//
// Created by Matthias Zenger on 20/12/2021.
// Copyright © 2021 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Atomics
///
/// `Registers` collects all register values in a single struct; it includes:
/// - `rid`: a registers id
/// - `code`: a reference to the code being executed
/// - `captured`: a list of captured expressions
/// - `ip`: the instruction pointer
/// - `fp`: the frame pointer
/// - `initialFp`: the initial frame pointer
///
struct Registers {
let rid: Int
var code: Code
var captured: Exprs
var ip: Int
var fp: Int
let initialFp: Int
/// Atomic counter for managing register ids
private static let nextRid = ManagedAtomic<Int>(0)
init(code: Code, captured: Exprs, fp: Int, root: Bool) {
if root {
self.rid = 0
} else {
self.rid = Registers.nextRid.wrappingIncrementThenLoad(ordering: .relaxed)
}
self.code = code
self.captured = captured
self.ip = 0
self.fp = fp
self.initialFp = fp
}
mutating func use(code: Code, captured: Exprs, fp: Int) {
self.code = code
self.captured = captured
self.ip = 0
self.fp = fp
}
var topLevel: Bool {
return self.fp == self.initialFp
}
var isInitialized: Bool {
return self.rid == 0 && self.code.instructions.count > 0
}
public func mark(in gc: GarbageCollector) {
gc.mark(self.code)
for i in self.captured.indices {
gc.markLater(self.captured[i])
}
}
}
| 2e6fd5c08cc15ab0e8f154dfa0037e62 | 25.75641 | 80 | 0.65932 | false | false | false | false |
BillowingCat/DouYuZB | refs/heads/master | DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift | mit | 1 | //
// RecommendViewController.swift
// DYZB
//
// Created by 訾玉洁 on 2016/11/4.
// Copyright © 2016年 鼎商动力. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin)/2
private let kItemH = kItemW * 3 / 4
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: UIViewController {
//MARK: - 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
//宽高随着父控件的拉伸而拉伸
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
//MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.purple
//设置UI界面fun
setupUI()
}
}
//MARK: - 设置UI界面内容
extension RecommendViewController {
fileprivate func setupUI(){
// 1.将collectionView添加到控制器的View中
view.addSubview(collectionView)
}
}
//MARK: - 遵守UICollectionView协议
extension RecommendViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出section的HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath)
return headerView
}
}
| fedd0b8f0b9d772ebb37baa707697a61 | 32.376344 | 186 | 0.695876 | false | false | false | false |
getsocial-im/getsocial-ios-sdk | refs/heads/master | example/GetSocialDemo/Views/Communities/Tags/TagTableViewCell.swift | apache-2.0 | 1 | //
// GenericTableViewCell.swift
// GetSocialInternalDemo
//
// Copyright © 2020 GetSocial BV. All rights reserved.
//
import Foundation
import UIKit
protocol TagTableViewCellDelegate {
func onShowActions(_ tag: Tag, isFollowed: Bool)
}
class TagTableViewCell: UITableViewCell {
internal var hashtag: Tag?
var isFollowed: Bool = false
var delegate: TagTableViewCellDelegate?
var displayName = UILabel.init()
var tagScore: UILabel = UILabel()
var tagActivitiesCount: UILabel = UILabel()
var tagFollowers: UILabel = UILabel()
var actionButton = UIButton.init(type: .roundedRect)
public required init?(coder: NSCoder) {
super.init(coder: coder)
setupUIElements()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUIElements()
}
func update(tag: Tag) {
self.hashtag = tag
self.displayName.text = tag.name
self.isFollowed = tag.isFollowedByMe
self.tagFollowers.text = "\(tag.followersCount) follower\(tag.followersCount > 1 ? "s" : "")"
self.tagScore.text = "Popularity: \(tag.popularity)"
self.tagActivitiesCount.text = "Activities count: \(tag.activitiesCount)"
self.actionButton.setTitle("Actions", for: .normal)
}
@objc
func showActions(sender: Any?) {
self.delegate?.onShowActions(self.hashtag!, isFollowed: self.isFollowed)
}
func setupUIElements() {
self.displayName.translatesAutoresizingMaskIntoConstraints = false
self.displayName.font = self.displayName.font.withSize(14)
self.contentView.addSubview(self.displayName)
let displayNameConstraints = [
self.displayName.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
self.displayName.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 8)
]
NSLayoutConstraint.activate(displayNameConstraints)
self.tagScore.translatesAutoresizingMaskIntoConstraints = false
self.tagScore.font = self.tagScore.font.withSize(14)
self.contentView.addSubview(self.tagScore)
let tagScoreConstraints = [
self.tagScore.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
self.tagScore.topAnchor.constraint(equalTo: self.displayName.bottomAnchor, constant: 8)
]
NSLayoutConstraint.activate(tagScoreConstraints)
self.tagActivitiesCount.translatesAutoresizingMaskIntoConstraints = false
self.tagActivitiesCount.font = self.tagActivitiesCount.font.withSize(14)
self.contentView.addSubview(self.tagActivitiesCount)
let tagActivitiesCountConstraints = [
self.tagActivitiesCount.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
self.tagActivitiesCount.topAnchor.constraint(equalTo: self.tagScore.bottomAnchor, constant: 8)
]
NSLayoutConstraint.activate(tagActivitiesCountConstraints)
self.tagFollowers.translatesAutoresizingMaskIntoConstraints = false
self.tagFollowers.font = self.tagFollowers.font.withSize(14)
self.contentView.addSubview(self.tagFollowers)
let tagFollowersConstraints = [
self.tagFollowers.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
self.tagFollowers.topAnchor.constraint(equalTo: self.tagActivitiesCount.bottomAnchor, constant: 8)
]
NSLayoutConstraint.activate(tagFollowersConstraints)
self.actionButton.addTarget(self, action: #selector(showActions(sender:)), for: .touchUpInside)
self.actionButton.frame = CGRect(x: 0, y: 0, width: 140, height: 30)
self.actionButton.setTitleColor(.black, for: .normal)
self.actionButton.backgroundColor = .lightGray
self.actionButton.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.actionButton)
let actionButtonConstraints = [
self.actionButton.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor, constant: 0),
self.actionButton.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8)
]
NSLayoutConstraint.activate(actionButtonConstraints)
}
}
| 72437ff871242d2939a3d77950e87de5 | 37.651376 | 111 | 0.74911 | false | false | false | false |
elslooo/hoverboard | refs/heads/master | Hoverboard/Utilities/LoginItem.swift | mit | 1 | /*
* Copyright (c) 2017 Tim van Elsloo
*
* 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
/**
* This class provides a wrapper around LSSharedFileListItem for
* kLSSharedFileListSessionLoginItems.
*/
public class LoginItem {
/**
* A login item is referenced by its url of the application to start at
* launch.
*/
public let url: URL
/**
* If this login item already exists, we keep a reference to the
* corresponding `LSSharedFileListItem` so we can use that to remove it
* later on.
*/
private var reference: LSSharedFileListItem?
/**
* This is a login item for the main bundle. Most of the time, this is the
* only login item you will need. The only exception is when you're bundling
* helper apps.
*
* - NOTE: this does not mean that the login item is automatically added to
* the system.
*/
public static let main = LoginItem(url: Bundle.main.bundleURL)
/**
* This function initializes a new login item with the given url. It does
* not automatically enable it, however. If it already exists, it also does
* not disable it.
*/
public init(url: URL) {
self.url = url
if let item = LoginItem.all.first(where: { $0.url == url }) {
self.reference = item.reference
}
}
/**
* This function initializes a new login item with the given native
* reference.
*/
private init?(reference: LSSharedFileListItem) {
self.reference = reference
let resolutionFlags = UInt32(kLSSharedFileListNoUserInteraction |
kLSSharedFileListDoNotMountVolumes)
// We retrieve the url that corresponds to the given item. For some
// reason, Apple indicates that this method may fail, therefore this
// initializer is failable as well.
guard let url = LSSharedFileListItemCopyResolvedURL(reference,
resolutionFlags,
nil) else {
return nil
}
self.url = url.takeUnretainedValue() as URL
}
/**
* This property returns a list of all login items registered on the user
* system.
*
* - NOTE: this also includes login items for other applications.
*/
public static var all: [LoginItem] {
// We want to retrieve login items.
let type = kLSSharedFileListSessionLoginItems.takeUnretainedValue()
// If we cannot retrieve them (I guess for example if the app is
// sandboxed), this call will fail and we return an empty array.
guard let items = LSSharedFileListCreate(nil, type, nil) else {
return []
}
let list = items.takeUnretainedValue()
// Snapshot seed can be used to update an existing snapshot (educated
// guess). We don't need that.
var seed: UInt32 = 0
guard let copy = LSSharedFileListCopySnapshot(list, &seed) else {
return []
}
guard let snapshot = copy.takeUnretainedValue() as?
[LSSharedFileListItem] else {
return []
}
var results: [LoginItem] = []
for item in snapshot {
guard let item = LoginItem(reference: item) else {
continue
}
results.append(item)
}
// At least in Swift 3.1, memory of the file list and its snapshot is
// managed by the system and we should not manually release any of it.
return results
}
/**
* This property returns a boolean that reflects whether or not the login
* item is actually enabled. Upon changing this value, we automatically add
* or remove the login item from / to the system's login items list. This
* operation may fail, in which case the getter will reflect the actual
* state of the login item.
*/
var isEnabled: Bool {
get {
return LoginItem.all.contains(where: { $0.url == self.url })
}
set {
if self.isEnabled == newValue {
return
}
// We want to retrieve login items.
let type = kLSSharedFileListSessionLoginItems.takeUnretainedValue()
guard let items = LSSharedFileListCreate(nil, type, nil) else {
return
}
if newValue {
// I am not sure why this is an optional. My guess would be it
// may not be available on all systems and is NULL or nil on
// earlier systems.
guard let order = kLSSharedFileListItemBeforeFirst else {
return
}
LSSharedFileListInsertItemURL(items.takeUnretainedValue(),
order.takeUnretainedValue(), nil,
nil, self.url as CFURL, nil, nil)
if let item = LoginItem.all.first(where: { $0.url == url }) {
self.reference = item.reference
}
} else {
LSSharedFileListItemRemove(items.takeUnretainedValue(),
self.reference)
self.reference = nil
}
}
}
}
| 98bac2ec011b39f8a7aa7841640abc72 | 34.944444 | 80 | 0.598764 | false | false | false | false |
iggym/PlaygroundNotes | refs/heads/master | Playground-Markup.playground/Pages/Code Blocks Examples.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous) | [Home](Overview) | [Code Blocks Notes](Code%20Blocks)| [Next](@next)
/*:
## Code Block example
- - -
- - -
### Using code block indented at least four spaces or one tab
A loop to print each character on a seperate line
for character in "Aesop" {
println(character)
}
A block of code
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
A loop to print
var n = 2
while n < 100 {
n = n * 2
}
print(n)
- - -
### Using four backquotes (`) on a line above and below the lines for the code block.
````
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
// the range represents integer values 0, 1, and 2
rangeOfThreeItems.firstValue = 6
// the range now represents integer values 6, 7, and 8
````
````
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
````
````
var n = 2
while n < 100 {
n = n * 2
}
````
````
some code
````
*/
//: ---
//: ---
//: [Next](@next) | [Home](Overview) | [List of Markup Examples](Examples%20Overview) | [[Code Blocks Notes](Code%20Blocks)]
| 2b412909841cdee1568a6bf39068bbdc | 17.481481 | 124 | 0.557782 | false | false | false | false |
cplaverty/KeitaiWaniKani | refs/heads/master | AlliCrab/Util/XibLoadable.swift | mit | 1 | //
// XibLoadable.swift
// AlliCrab
//
// Copyright © 2019 Chris Laverty. All rights reserved.
//
import UIKit
protocol XibLoadable {
var xibName: String { get }
}
extension XibLoadable where Self: UIView {
var xibName: String {
return String(describing: type(of: self))
}
func setupContentViewFromXib() -> UIView {
let contentView = loadViewFromXib()
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(contentView)
return contentView
}
private func loadViewFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: xibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
}
| e51d1b592af0ec7c08e632e453ed1108 | 23.027778 | 82 | 0.621965 | false | false | false | false |
Nana-Muthuswamy/TwitterLite | refs/heads/master | TwitterLite/User.swift | mit | 1 | //
// User.swift
// TwitterLite
//
// Created by Nana on 4/15/17.
// Copyright © 2017 Nana. All rights reserved.
//
import Foundation
class User {
var id: Int
var idStr: String
var name: String?
var screenName: String?
var profileURL: URL?
var tagline: String?
var tweetsCount: Int
var followingCount: Int
var followersCount: Int
var dictionary: Dictionary<String, Any>!
init(dictionary: Dictionary<String, Any>) {
// Persist input dictionary for future use
self.dictionary = dictionary
id = dictionary["id"] as! Int
idStr = dictionary["id_str"] as! String
if let userName = dictionary["name"] as? String {
name = userName
}
if let userScreenName = dictionary["screen_name"] as? String {
screenName = "@" + userScreenName
}
if let profileURLPath = dictionary["profile_image_url"] as? String {
profileURL = URL(string: profileURLPath)
}
if let userTagline = dictionary["description"] as? String {
tagline = userTagline
}
tweetsCount = dictionary["statuses_count"] as? Int ?? 0
followingCount = dictionary["friends_count"] as? Int ?? 0
followersCount = dictionary["followers_count"] as? Int ?? 0
}
private static var _currentUser: User?
static var currentUser: User? {
get {
if _currentUser == nil {
// TDO: Should use DispatchSemaphore to initiate login and fetch user details when not persisted
if let userData = UserDefaults.standard.data(forKey: "userData") {
let userDict = try! JSONSerialization.jsonObject(with: userData, options: []) as! Dictionary<String, Any>
_currentUser = User(dictionary: userDict)
}
}
return _currentUser
}
set(newUser) {
_currentUser = newUser
let defaults = UserDefaults.standard
if _currentUser == nil {
defaults.removeObject(forKey: "userData")
} else {
let userData = try! JSONSerialization.data(withJSONObject: newUser?.dictionary as Any, options: [])
defaults.set(userData, forKey: "userData")
}
defaults.synchronize()
}
}
}
| 1966a01e257b4de7374253cc3bafe55d | 26.181818 | 125 | 0.577759 | false | false | false | false |
cocoaswifty/iVoice | refs/heads/master | iVoice/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// iVoice
//
// Created by jianhao on 2016/4/24.
// Copyright © 2016年 cocoaSwifty. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if NSUserDefaults.standardUserDefaults().valueForKey("uid") == nil { //First Launch 第一次啟用app
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstLaunchVC = storyboard.instantiateViewControllerWithIdentifier("FirstLaunch")
window?.rootViewController = firstLaunchVC
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 0158e03fbc7e7734be90c8e83264c6e1 | 45.296296 | 285 | 0.736 | false | false | false | false |
cam-hop/APIUtility | refs/heads/master | RxSwiftFlux/Dispatcher.swift | mit | 2 | //
// Dispatcher.swift
// RxSwiftFlux
//
// Created by DUONG VANHOP on 2017/06/14.
// Copyright © 2017年 DUONG VANHOP. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public typealias DispatchToken = String
public protocol Dispatcher {
func dispatch<T: Action>(action: T, result: T.Payload)
func dispatchErr<T: Action>(action: T, error: T.ErrorType)
func register<T: Action>(type: T.Type) -> DispatchToken
func unregister(_ dispatchToken: DispatchToken)
func dispatchSbj<T: Action>(type: T.Type, dispatchToken: DispatchToken) -> AnyObject?
func dispatchSbjErr<T: Action>(type: T.Type, dispatchToken: DispatchToken) -> AnyObject?
}
public class DefaultDispatcher: Dispatcher {
public static let shared = DefaultDispatcher()
private var dispatchObjs: [DispatchToken: AnyObject] = [:]
private init() {}
public func dispatch<T>(action: T, result: T.Payload) where T : Action {
for dispatchToken in dispatchObjs.keys {
if let dispatchObj = dispatchObjs[dispatchToken] as? DispatchObject<T> {
dispatchObj.dispatchSbj.dispatch(result)
}
}
}
public func dispatchErr<T>(action: T, error: T.ErrorType) where T : Action {
for dispatchToken in dispatchObjs.keys {
if let dispatchObj = dispatchObjs[dispatchToken] as? DispatchObject<T> {
dispatchObj.dispatchSbjErr.dispatch(error)
}
}
}
public func register<T>(type: T.Type) -> DispatchToken where T : Action {
let nextDispatchToken = NSUUID().uuidString
let dispatchSbj = DispatchSubject<T.Payload>()
let dispatchSbjErr = DispatchSubject<T.ErrorType>()
dispatchObjs[nextDispatchToken] = DispatchObject<T>(type: type, dispatchSbj: dispatchSbj, dispatchSbjErr: dispatchSbjErr)
return nextDispatchToken
}
public func unregister(_ dispatchToken: DispatchToken) {
dispatchObjs.removeValue(forKey: dispatchToken)
}
public func dispatchSbj<T: Action>(type: T.Type, dispatchToken: DispatchToken) -> AnyObject? {
guard let dispatchObj = dispatchObjs[dispatchToken] as? DispatchObject<T> else { return nil}
return dispatchObj.dispatchSbj
}
public func dispatchSbjErr<T: Action>(type: T.Type, dispatchToken: DispatchToken) -> AnyObject? {
guard let dispatchObj = dispatchObjs[dispatchToken] as? DispatchObject<T> else { return nil}
return dispatchObj.dispatchSbjErr
}
}
private class DispatchObject<T: Action> {
let type: T.Type
let dispatchSbj: DispatchSubject<T.Payload>
let dispatchSbjErr: DispatchSubject<T.ErrorType>
init(type: T.Type, dispatchSbj: DispatchSubject<T.Payload>, dispatchSbjErr: DispatchSubject<T.ErrorType>) {
self.type = type
self.dispatchSbj = dispatchSbj
self.dispatchSbjErr = dispatchSbjErr
}
}
| bdb892555a1d9e6aeefd611b1b5cb81a | 35.012195 | 129 | 0.680664 | false | false | false | false |
ReSwift/CounterExample-Navigation-TimeTravel | refs/heads/master | Carthage/Checkouts/ReSwift-Router/ReSwiftRouterTests/ReSwiftRouterIntegrationTests.swift | mit | 3 | //
// SwiftFlowRouterTests.swift
// SwiftFlowRouterTests
//
// Created by Benjamin Encz on 12/2/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Quick
import Nimble
import ReSwift
@testable import ReSwiftRouter
class MockRoutable: Routable {
var callsToPushRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = []
var callsToPopRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = []
var callsToChangeRouteSegment: [(
from: RouteElementIdentifier,
to: RouteElementIdentifier,
animated: Bool
)] = []
func pushRouteSegment(
_ routeElementIdentifier: RouteElementIdentifier,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler
) -> Routable {
callsToPushRouteSegment.append(
(routeElement: routeElementIdentifier, animated: animated)
)
completionHandler()
return MockRoutable()
}
func popRouteSegment(
_ routeElementIdentifier: RouteElementIdentifier,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) {
callsToPopRouteSegment.append(
(routeElement: routeElementIdentifier, animated: animated)
)
completionHandler()
}
func changeRouteSegment(
_ from: RouteElementIdentifier,
to: RouteElementIdentifier,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler
) -> Routable {
completionHandler()
callsToChangeRouteSegment.append((from: from, to: to, animated: animated))
return MockRoutable()
}
}
struct FakeAppState: StateType {
var navigationState = NavigationState()
}
func fakeReducer(action: Action, state: FakeAppState?) -> FakeAppState {
return state ?? FakeAppState()
}
func appReducer(action: Action, state: FakeAppState?) -> FakeAppState {
return FakeAppState(
navigationState: NavigationReducer.handleAction(action, state: state?.navigationState)
)
}
class SwiftFlowRouterIntegrationTests: QuickSpec {
override func spec() {
describe("routing calls") {
var store: Store<FakeAppState>!
beforeEach {
store = Store(reducer: appReducer, state: FakeAppState())
}
describe("setup") {
it("does not request the root view controller when no route is provided") {
class FakeRootRoutable: Routable {
var called = false
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
completionHandler: RoutingCompletionHandler) -> Routable {
called = true
return MockRoutable()
}
}
let routable = FakeRootRoutable()
let _ = Router(store: store, rootRoutable: routable) { state in
state.select { $0.navigationState }
}
expect(routable.called).to(beFalse())
}
it("requests the root with identifier when an initial route is provided") {
store.dispatch(
SetRouteAction(
["TabBarViewController"]
)
)
class FakeRootRoutable: Routable {
var calledWithIdentifier: (RouteElementIdentifier?) -> Void
init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) {
self.calledWithIdentifier = calledWithIdentifier
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) -> Routable {
calledWithIdentifier(routeElementIdentifier)
completionHandler()
return MockRoutable()
}
}
waitUntil(timeout: 2.0) { fullfill in
let rootRoutable = FakeRootRoutable { identifier in
if identifier == "TabBarViewController" {
fullfill()
}
}
let _ = Router(store: store, rootRoutable: rootRoutable) { state in
state.select { $0.navigationState }
}
}
}
it("calls push on the root for a route with two elements") {
store.dispatch(
SetRouteAction(
["TabBarViewController", "SecondViewController"]
)
)
class FakeChildRoutable: Routable {
var calledWithIdentifier: (RouteElementIdentifier?) -> Void
init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) {
self.calledWithIdentifier = calledWithIdentifier
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) -> Routable {
calledWithIdentifier(routeElementIdentifier)
completionHandler()
return MockRoutable()
}
}
waitUntil(timeout: 5.0) { completion in
let fakeChildRoutable = FakeChildRoutable() { identifier in
if identifier == "SecondViewController" {
completion()
}
}
class FakeRootRoutable: Routable {
let injectedRoutable: Routable
init(injectedRoutable: Routable) {
self.injectedRoutable = injectedRoutable
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) -> Routable {
completionHandler()
return injectedRoutable
}
}
let _ = Router(store: store, rootRoutable:
FakeRootRoutable(injectedRoutable: fakeChildRoutable)) { state in
state.select { $0.navigationState }
}
}
}
}
}
describe("route specific data") {
var store: Store<FakeAppState>!
beforeEach {
store = Store(reducer: appReducer, state: nil)
}
context("when setting route specific data") {
beforeEach {
store.dispatch(SetRouteSpecificData(route: ["part1", "part2"], data: "UserID_10"))
}
it("allows accessing the data when providing the expected type") {
let data: String? = store.state.navigationState.getRouteSpecificState(
["part1", "part2"]
)
expect(data).toEventually(equal("UserID_10"))
}
}
}
describe("configuring animated/unanimated navigation") {
var store: Store<FakeAppState>!
var mockRoutable: MockRoutable!
var router: Router<FakeAppState>!
beforeEach {
store = Store(reducer: appReducer, state: nil)
mockRoutable = MockRoutable()
router = Router(store: store, rootRoutable: mockRoutable) { state in
state.select { $0.navigationState }
}
// silence router not read warning, need to keep router alive via reference
_ = router
}
context("when dispatching an animated route change") {
beforeEach {
store.dispatch(SetRouteAction(["someRoute"], animated: true))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue())
}
}
context("when dispatching an unanimated route change") {
beforeEach {
store.dispatch(SetRouteAction(["someRoute"], animated: false))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beFalse())
}
}
context("when dispatching a default route change") {
beforeEach {
store.dispatch(SetRouteAction(["someRoute"]))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue())
}
}
}
}
}
| 34ad2e0a701d169cc99453f5541fc5eb | 33.850534 | 180 | 0.512815 | false | false | false | false |
jeroendesloovere/examples-swift | refs/heads/master | Swift-Playgrounds/Methods.playground/section-1.swift | mit | 1 | // Methods Chapter
// Instance Methods
class Counter {
var count = 0
func increment() {
count++
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
counter.incrementBy(5)
counter.reset()
// amount is a local name only.
// numberOfTimes is both a local and external name
class CounterTwo {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
let counter2 = CounterTwo()
counter2.incrementBy(5, numberOfTimes:3)
// You don’t need to define an external parameter name for the first argument value, because its purpose is clear from the function name incrementBy. The second argument, however, is qualified by an external parameter name to make its purpose clear when the method is called.
// The self Property
// Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use this implicit self property to refer to the current instance within its own instance methods.
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
return self.x > x
}
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
println("This point is to the right of the line where x == 1.0")
}
// Modifying Value TYpes from Within
// Instance Methods
// if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.
struct Point2 {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY:Double) {
x += deltaX
y += deltaY
}
}
var somePoint2 = Point2(x: 1.0, y: 1.0)
somePoint2.moveByX(2.0, y:3.0)
println("The point is now at (\(somePoint2.x), \(somePoint2.y))")
let fixedPoint = Point2(x: 3.0, y: 3.0)
//fixedPoint.moveByX(2.0, y: 3.0)
// this will report an error because fixedPoint is a constant
// Assigning to self Within a Mutating Method
struct Point3 {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
self = Point3(x: x + deltaX, y: y + deltaY)
}
}
// Mutating methods for enumerations can set the implicit self parameter to be a different member from the same enumeration:
enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
ovenLight.next()
// Type Methods
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) {
if level > highestUnlockedLevel { highestUnlockedLevel = level }
}
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level: Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level + 1)
tracker.advanceToLevel(level + 1)
}
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios")
player.completedLevel(1)
println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
player = Player(name: "Beto")
if player.tracker.advanceToLevel(6) {
println("player is now on level 6")
} else {
println("level 6 has not yet been unlocked")
}
| 202d21c63e384bf058f14f194370879f | 26.409722 | 276 | 0.658728 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.