repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
almazrafi/Metatron | Sources/ID3v2/FrameStuffs/ID3v2ContentType.swift | 1 | 6559 | //
// ID3v2ContentType.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class ID3v2ContentType: ID3v2BaseTextInformation {
// MARK: Instance Methods
public override func deserialize(fields: [String], version: ID3v2Version) -> [String] {
var genres: [String] = []
for field in fields {
let characters = [Character](field.characters)
if (characters.count >= 2) && (characters[0] == "(") {
if let separator = characters.suffix(from: 1).index(of: ")") {
var nextGenre: String
if characters[1] == "(" {
nextGenre = String(characters[1...separator])
} else {
nextGenre = String(characters[1..<separator])
if let genreIndex = Int(nextGenre) {
if (genreIndex >= 0) && (genreIndex < ID3v1GenreList.count) {
nextGenre = ID3v1GenreList[genreIndex]
}
}
}
genres.append(nextGenre)
var scanStart = separator + 1
var textStart = scanStart
while let nextStart = characters.suffix(from: scanStart).index(of: "(") {
scanStart = nextStart + 1
if let separator = characters.suffix(from: scanStart).index(of: ")") {
if textStart < nextStart {
genres.append(String(characters[textStart..<nextStart]))
}
if characters[scanStart] == "(" {
nextGenre = String(characters[scanStart...separator])
} else {
nextGenre = String(characters[scanStart..<separator])
if let genreIndex = Int(nextGenre) {
if (genreIndex >= 0) && (genreIndex < ID3v1GenreList.count) {
nextGenre = ID3v1GenreList[genreIndex]
}
}
}
genres.append(nextGenre)
scanStart = separator + 1
textStart = scanStart
} else {
break
}
}
if textStart < characters.count {
genres.append(String(characters.suffix(from: textStart)))
}
} else {
var genre = field
if let genreIndex = Int(genre) {
if (genreIndex >= 0) && (genreIndex < ID3v1GenreList.count) {
genre = ID3v1GenreList[genreIndex]
}
}
genres.append(genre)
}
} else {
var genre = field
if let genreIndex = Int(genre) {
if (genreIndex >= 0) && (genreIndex < ID3v1GenreList.count) {
genre = ID3v1GenreList[genreIndex]
}
}
genres.append(genre)
}
}
return genres
}
public override func serialize(fields: [String], version: ID3v2Version) -> [String] {
guard !fields.isEmpty else {
return []
}
switch version {
case ID3v2Version.v2, ID3v2Version.v3:
var genres = ""
for field in fields {
let components = field.components(separatedBy: "(")
if !components[0].isEmpty {
if let genreIndex = ID3v1GenreList.index(of: components[0]) {
genres.append("(\(genreIndex))")
} else {
genres.append("(\(components[0]))")
}
} else if components.count == 1 {
genres.append("()")
}
for i in 1..<components.count {
genres.append("((\(components[i])")
}
}
return [genres]
case ID3v2Version.v4:
var genres: [String] = []
for field in fields {
if field.hasPrefix("(") {
genres.append("(\(field)")
} else {
genres.append(field)
}
}
return genres
}
}
}
public class ID3v2ContentTypeFormat: ID3v2FrameStuffSubclassFormat {
// MARK: Type Properties
public static let regular = ID3v2ContentTypeFormat()
// MARK: Instance Methods
public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2ContentType {
return ID3v2ContentType(fromData: data, version: version)
}
public func createStuffSubclass(fromOther other: ID3v2ContentType) -> ID3v2ContentType {
let stuff = ID3v2ContentType()
stuff.textEncoding = other.textEncoding
stuff.fields = other.fields
return stuff
}
public func createStuffSubclass() -> ID3v2ContentType {
return ID3v2ContentType()
}
}
| mit | 40b2f56fefaae135ac9f595b744ca04f | 33.888298 | 104 | 0.500381 | 5.230463 | false | false | false | false |
ifels/swiftDemo | DragDropGridviewDemo/DragDropGridviewDemo/GridViewController.swift | 1 | 4209 | //
// ViewController.swift
// DragDropGridviewDemo
//
// Created by 聂鑫鑫 on 16/11/16.
// Copyright © 2016年 ifels. All rights reserved.
//
import UIKit
import UIKit
import SnapKit
class GridViewController: UIViewController {
let itemWidth:CGFloat = 150
var gridView : ReorderableGridView?
var itemCount: Int = 0
var borderColor: UIColor?
var bgColor: UIColor?
var bottomColor: UIColor?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.view.backgroundColor = UIColor(hexString: "#373a50")!
initData()
setupViews()
}
func initData(){
borderColor = RGBColor(233, g: 233, b: 233)
bgColor = RGBColor(242, g: 242, b: 242)
bottomColor = RGBColor(65, g: 65, b: 65)
}
// MARK: Grid View
func setupViews () {
print("PatternsController.setupViews...")
var origin = view.frame.origin
var size = view.frame.size
origin.y = origin.y + 30
size.height = size.height - 60
let frame = CGRect(origin: origin, size: size)
gridView = ReorderableGridView(frame: frame, itemWidth: itemWidth, verticalPadding: 20)
view.addSubview(gridView!)
for i in 0..<4 {
gridView!.addReorderableView(itemView(i))
}
}
func itemView (_ index: Int) -> ReorderableView {
let w : CGFloat = itemWidth
let h : CGFloat = 80
let view = ReorderableView (x: 0, y: 0, w: w, h: h)
view.layer.borderColor = borderColor?.cgColor
view.layer.backgroundColor = UIColor.white.cgColor
view.layer.borderWidth = 1
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
let topView = UIView(x: 0, y: 0, w: view.w, h: 50)
view.addSubview(topView)
let itemLabel = UILabel (frame: topView.frame)
itemLabel.center = topView.center
itemLabel.font = UIFont.HelveticaNeue(.Thin, size: 20)
itemLabel.textAlignment = NSTextAlignment.center
itemLabel.textColor = bottomColor
itemLabel.text = "\(index)"
itemLabel.layer.masksToBounds = true
topView.addSubview(itemLabel)
let sepLayer = CALayer ()
sepLayer.frame = CGRect (x: 0, y: topView.bottom, width: topView.w, height: 1)
sepLayer.backgroundColor = borderColor?.cgColor
topView.layer.addSublayer(sepLayer)
let bottomView = UIView(frame: CGRect(x: 0, y: topView.bottom, width: view.w, height: view.h-topView.h))
let bottomLayer = CALayer ()
bottomLayer.frame = CGRect (x: 0, y: bottomView.h-5, width: bottomView.w, height: 5)
bottomLayer.backgroundColor = bottomColor?.cgColor
bottomView.layer.addSublayer(bottomLayer)
bottomView.layer.masksToBounds = true
view.addSubview(bottomView)
return view
}
// MARK: Interface Rotation
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
let w = UIScreen.main.bounds.size.width
let h = UIScreen.main.bounds.size.height
gridView?.setW(h, h: w)
gridView?.invalidateLayout()
}
// MARK: Utils
func randomColor () -> UIColor {
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
func RGBColor(_ r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
return UIColor (red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1)
}
func RGBAColor (_ r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
return UIColor (red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
override func viewDidAppear(_ animated: Bool) {
if let grid = gridView {
grid.invalidateLayout()
}
}
}
| apache-2.0 | e29d9b74e89e55713e01dc0926598318 | 31.061069 | 112 | 0.60619 | 4.388715 | false | false | false | false |
dmorrow/UTSwiftUtils | Classes/UI/KeyboardHandler.swift | 1 | 3229 | //
// KeyboardHandler.swift
// UTSwiftUtils
//
// Created by Danny Morrow on 11/17/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
@objc(KeyboardHandler)
public protocol KeyboardHandler {
var scrollableView:UIScrollView? { get }
var isObservingKeyboard:Bool { get set }
var observesKeyboard:Bool { get }
func keyboardWillShow(_ notification: Notification)
func keyboardDidShow(_ notification: Notification)
func keyboardWillHide(_ notification: Notification)
func keyboardDidHide(_ notification: Notification)
func keyboardResize(_ notification: Notification)
func textfieldDidBeginEditing(_ notification: Notification)
func textviewDidBeginEditing(_ notification: Notification)
}
public extension KeyboardHandler where Self: UIViewController {
public func addKeyboardObservers() {
guard scrollableView != nil, observesKeyboard else { return }
if !isObservingKeyboard {
isObservingKeyboard = true
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(keyboardResize(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(textfieldDidBeginEditing(_:)), name: UITextField.textDidBeginEditingNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(textviewDidBeginEditing(_:)), name: UITextView.textDidBeginEditingNotification, object: nil)
}
}
public func removeKeyboardObservers() {
if isObservingKeyboard {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil)
notificationCenter.removeObserver(self, name: UITextField.textDidBeginEditingNotification, object: nil)
notificationCenter.removeObserver(self, name: UITextView.textDidBeginEditingNotification, object: nil)
isObservingKeyboard = false
}
}
}
| mit | 70f647516d4aea30137bf9708b660c7d | 52.8 | 163 | 0.742255 | 6.113636 | false | false | false | false |
yfix/webrtc | src/ios/PCObserver.swift | 1 | 2420 | import Foundation
class PCObserver : NSObject, RTCPeerConnectionDelegate {
var session: Session
init(session: Session) {
self.session = session
}
func peerConnection(peerConnection: RTCPeerConnection!,
addedStream stream: RTCMediaStream!) {
print("PCO onAddStream.")
dispatch_async(dispatch_get_main_queue()) {
if stream.videoTracks.count > 0 {
self.session.addVideoTrack(stream.videoTracks[0] as! RTCVideoTrack)
}
}
self.session.sendMessage(
"{\"type\": \"__answered\"}".dataUsingEncoding(NSUTF8StringEncoding)!)
}
func peerConnection(peerConnection: RTCPeerConnection!,
removedStream stream: RTCMediaStream!) {
print("PCO onRemoveStream.")
/*
dispatch_async(dispatch_get_main_queue()) {
if stream.videoTracks.count > 0 {
self.session.removeVideoTrack(stream.videoTracks[0] as RTCVideoTrack)
}
}*/
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceGatheringChanged newState: RTCICEGatheringState) {
print("PCO onIceGatheringChange. \(newState)")
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceConnectionChanged newState: RTCICEConnectionState) {
print("PCO onIceConnectionChange. \(newState)")
}
func peerConnection(peerConnection: RTCPeerConnection!,
gotICECandidate candidate: RTCICECandidate!) {
print("PCO onICECandidate.\n Mid[\(candidate.sdpMid)] Index[\(candidate.sdpMLineIndex)] Sdp[\(candidate.sdp)]")
var jsonError: NSError?
let json: AnyObject = [
"type": "candidate",
"label": candidate.sdpMLineIndex,
"id": candidate.sdpMid,
"candidate": candidate.sdp
]
let data: NSData?
do {
data = try NSJSONSerialization.dataWithJSONObject(json,
options: NSJSONWritingOptions())
} catch let error as NSError {
jsonError = error
data = nil
}
self.session.sendMessage(data!)
}
func peerConnection(peerConnection: RTCPeerConnection!,
signalingStateChanged stateChanged: RTCSignalingState) {
print("PCO onSignalingStateChange: \(stateChanged)")
}
func peerConnection(peerConnection: RTCPeerConnection!,
didOpenDataChannel dataChannel: RTCDataChannel!) {
print("PCO didOpenDataChannel.")
}
func peerConnectionOnError(peerConnection: RTCPeerConnection!) {
print("PCO onError.")
}
func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) {
print("PCO onRenegotiationNeeded.")
// TODO: Handle this
}
}
| apache-2.0 | 5ccca28a53fd97a965bb99f889c047e2 | 26.191011 | 114 | 0.734298 | 4.046823 | false | false | false | false |
bravelocation/yeltzland-ios | yeltzland/FixturesTableViewController.swift | 1 | 8524 | //
// FixturesTableViewController.swift
// yeltzland
//
// Created by John Pollard on 20/06/2016.
// Copyright © 2016 John Pollard. All rights reserved.
//
import UIKit
import Intents
import WidgetKit
private func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class FixturesTableViewController: UITableViewController {
var reloadButton: UIBarButtonItem!
private let cellIdentifier: String = "FixtureTableViewCell"
#if !targetEnvironment(macCatalyst)
private let fixturesRefreshControl = UIRefreshControl()
#endif
override init(style: UITableView.Style) {
super.init(style: style)
self.setupNotificationWatcher()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupNotificationWatcher()
}
fileprivate func setupNotificationWatcher() {
NotificationCenter.default.addObserver(self, selector: #selector(FixturesTableViewController.fixturesUpdated), name: .FixturesUpdated, object: nil)
print("Setup notification handler for fixture updates")
}
@objc fileprivate func fixturesUpdated() {
DispatchQueue.main.async(execute: { () -> Void in
#if !targetEnvironment(macCatalyst)
self.fixturesRefreshControl.endRefreshing()
#endif
self.tableView.reloadData()
let currentMonthIndexPath = IndexPath(row: 0, section: self.currentMonthSection())
// Try to handle case where fixtures may have updated
if (currentMonthIndexPath.section < FixtureDataProvider.shared.months.count) {
self.tableView.scrollToRow(at: currentMonthIndexPath, at: UITableView.ScrollPosition.top, animated: true)
}
})
}
fileprivate func currentMonthSection() -> Int {
var monthIndex = 0
let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMM"
let currentMonth = formatter.string(from: now)
for month in FixtureDataProvider.shared.months {
if (month == currentMonth) {
return monthIndex
}
monthIndex += 1
}
// No match found, so just start at the top
return 0
}
@objc func reloadButtonTouchUp() {
FixtureDataProvider.shared.refreshData() { result in
switch result {
case .success:
self.fixturesUpdated()
case .failure:
print("Couldn't update fixtures")
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = UIColor(named: "yeltz-blue")
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
let buttonAppearance = UIBarButtonItemAppearance(style: .plain)
buttonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.buttonAppearance = buttonAppearance
self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance
} else {
self.navigationController?.navigationBar.barTintColor = UIColor(named: "yeltz-blue")
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
self.navigationController?.navigationBar.tintColor = UIColor.white
}
override func viewDidLoad() {
super.viewDidLoad()
// Go get latest fixtures in background
self.reloadButtonTouchUp()
// Setup navigation
self.navigationItem.title = "Fixtures"
self.view.backgroundColor = AppColors.systemBackground
self.tableView.separatorColor = AppColors.systemBackground
self.tableView.register(UINib(nibName: self.cellIdentifier, bundle: nil), forCellReuseIdentifier: self.cellIdentifier)
// Setup refresh button
self.reloadButton = UIBarButtonItem(
barButtonSystemItem: .refresh,
target: self,
action: #selector(FixturesTableViewController.reloadButtonTouchUp)
)
self.reloadButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItems = [self.reloadButton]
#if !targetEnvironment(macCatalyst)
self.tableView.refreshControl = self.fixturesRefreshControl
self.fixturesRefreshControl.addTarget(self, action: #selector(FixturesTableViewController.refreshSearchData), for: .valueChanged)
#endif
}
@objc private func refreshSearchData(_ sender: Any) {
FixtureDataProvider.shared.refreshData() { result in
switch result {
case .success:
self.fixturesUpdated()
case .failure:
print("Couldn't update fixtures")
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
// Reload the table on trait change, in particular to change images on dark mode change
self.tableView.reloadData()
}
@objc func goBack() {
self.navigationController?.popViewController(animated: true)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return FixtureDataProvider.shared.months.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let months = FixtureDataProvider.shared.months
if (months.count <= section) {
return 0
}
let fixturesForMonth = FixtureDataProvider.shared.fixturesForMonth(months[section])
if (fixturesForMonth == nil || fixturesForMonth?.count == 0) {
return 0
}
return fixturesForMonth!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as! FixtureTableViewCell
// Find the fixture
var currentFixture: Fixture? = nil
let months = FixtureDataProvider.shared.months
if (months.count > (indexPath as NSIndexPath).section) {
let fixturesForMonth = FixtureDataProvider.shared.fixturesForMonth(months[(indexPath as NSIndexPath).section])
if (fixturesForMonth != nil && fixturesForMonth?.count > (indexPath as NSIndexPath).row) {
currentFixture = fixturesForMonth![(indexPath as NSIndexPath).row]
}
}
if let fixture = currentFixture {
cell.assignFixture(fixture)
}
return cell
}
override func tableView( _ tableView: UITableView, titleForHeaderInSection section: Int) -> String {
let months = FixtureDataProvider.shared.months
if (months.count <= section) {
return ""
}
let fixturesForMonth = FixtureDataProvider.shared.fixturesForMonth(months[section])
if (fixturesForMonth == nil || fixturesForMonth?.count == 0) {
return ""
}
return fixturesForMonth![0].fixtureMonth
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 33.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 33.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0
}
}
| mit | 2f0101b637cf3fb9c6b6180ca3ccbc6b | 33.506073 | 155 | 0.632172 | 5.625743 | false | false | false | false |
vlfm/swapi-swift | Source/SW.swift | 1 | 3902 | import Foundation
/// All ResponseHandlers are called on arbitrary background queue.
public final class SW {
public let client: Client
public let requests: Requests
public let services: Services
public convenience init() {
self.init(network: URLSession.shared)
}
init(network: Network) {
client = DefaultClient(
transport: DefaultTransport(
network: network,
deserializer: JsonDeserializer.make()))
requests = Requests(baseUrl: URL(string: "http://swapi.co/api")!)
services = Services(client: client, requests: requests)
}
}
extension SW {
public final class Services {
public let film: FilmService
public let person: PersonService
public let planet: PlanetService
public let species: SpeciesService
public let starship: StarshipService
public let vehicle: VehicleService
init(client: Client, requests: Requests) {
film = DefaultFilmService(
rawService: AnyService(
client: client,
requests: requests.film))
person = DefaultPersonService(
rawService: AnyService(
client: client,
requests: requests.person))
planet = DefaultPlanetService(
rawService: AnyService(
client: client,
requests: requests.planet))
species = DefaultSpeciesService(
rawService: AnyService(
client: client,
requests: requests.species))
starship = DefaultStarshipService(
rawService: AnyService(
client: client,
requests: requests.starship))
vehicle = DefaultVehicleService(
rawService: AnyService(
client: client,
requests: requests.vehicle))
}
}
}
extension SW {
public final class Requests {
public let film: RequestFactory<Film>
public let person: RequestFactory<Person>
public let planet: RequestFactory<Planet>
public let species: RequestFactory<Species>
public let starship: RequestFactory<Starship>
public let vehicle: RequestFactory<Vehicle>
public let root: Request<Root>
init(baseUrl: URL) {
film = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/films"),
parsers: ParserFactory.film())
person = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/people"),
parsers: ParserFactory.person())
planet = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/planets"),
parsers: ParserFactory.planet())
species = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/species"),
parsers: ParserFactory.species())
starship = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/starships"),
parsers: ParserFactory.starship())
vehicle = RequestFactory(
endpoint: Endpoint(
baseUrl: baseUrl,
path: "/vehicles"),
parsers: ParserFactory.vehicle())
root = Request(url: baseUrl, parser: RootParser.make())
}
}
}
| apache-2.0 | 0ed4edca6e2c3ab7c41478a6e799a5c5 | 32.067797 | 73 | 0.509482 | 6.203498 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Core/Operations/AppOperations/SeenStatusPersistingOperation.swift | 1 | 2322 | //
// SeenStatusPersistingOperation.swift
//
// Created by Andrey K. on 20/04/16.
//
//
import UIKit
import CoreData
final class SeenStatusPersistingOperation: MMOperation {
let context: NSManagedObjectContext
let finishBlock: (() -> Void)?
let messageIds: [String]
let mmContext: MobileMessaging
init(userInitiated: Bool, messageIds: [String], context: NSManagedObjectContext, mmContext: MobileMessaging, finishBlock: (() -> Void)? = nil) {
self.messageIds = messageIds
self.context = context
self.finishBlock = finishBlock
self.mmContext = mmContext
super.init(isUserInitiated: userInitiated)
}
override func execute() {
logDebug("started...")
markMessagesAsSeen()
}
private func markMessagesAsSeen() {
guard !self.messageIds.isEmpty else {
logDebug("no messages to mark seen. Finishing")
finish()
return
}
context.performAndWait {
context.reset()
if let dbMessages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "seenStatusValue == \(MMSeenStatus.NotSeen.rawValue) AND messageTypeValue == \(MMMessageType.Default.rawValue) AND messageId IN %@", self.messageIds), context: self.context), !dbMessages.isEmpty {
dbMessages.forEach { message in
logDebug("message \(message.messageId) marked as seen")
message.seenStatus = .SeenNotSent
message.seenDate = MobileMessaging.date.now // we store only the very first seen date, any repeated seen update is ignored
}
self.context.MM_saveToPersistentStoreAndWait()
} else {
logDebug("no messages in internal storage to set seen")
}
self.updateMessageStorage(with: messageIds) {
self.finish()
}
}
}
private func updateMessageStorage(with messageIds: [String], completion: @escaping () -> Void) {
guard !messageIds.isEmpty else {
logDebug("no message ids to set seen in message storage")
completion()
return
}
logDebug("updating message storage")
mmContext.messageStorages.values.forEachAsync({ (storage, finishBlock) in
storage.batchSeenStatusUpdate(messageIds: messageIds, seenStatus: .SeenNotSent, completion: finishBlock)
}, completion: completion)
}
override func finished(_ errors: [NSError]) {
assert(userInitiated == Thread.isMainThread)
logDebug("finished with errors: \(errors)")
finishBlock?()
}
}
| apache-2.0 | e5e3f0dd4858b63115233468bcd8947a | 30.378378 | 285 | 0.727821 | 3.989691 | false | false | false | false |
fienlute/programmeerproject | GOals/GoalsViewController.swift | 1 | 8437 | //
// GoalsViewController.swift
// GOals
//
// De gebruiker krijgt de toegevoegde doelen te zien van de groep waar hij/zij in zit. Ook kan hij/zij zelf
// doelen toevoegen of afvinken. Als een doel wordt afgevinkt, dan worden de punten opgeteld bij het puntensaldo van de gebruiker.
//
// Created by Fien Lute on 12-01-17.
// Copyright © 2017 Fien Lute. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class GoalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Properties
var senderDisplayName: String?
var goalRef = FIRDatabase.database().reference(withPath: "goals")
let usersRef = FIRDatabase.database().reference(withPath: "online")
var items: [Goal] = []
var goal: Goal!
var user: User!
var group: String = ""
var name: String = ""
var pointsInt: Int = 0
var pointsString: String = ""
var completedBy: String = ""
// MARK: Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "mountainbackgroundgoals.png")!)
title = "Goals"
retrieveUserDataFirebase()
}
override func viewWillAppear(_ animated: Bool) {
// hides empty cells of tableview
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
// MARK : Actions
@IBAction func addGoalDidTouch(_ sender: Any) {
let alert = UIAlertController(title: "Goal",
message: "Add a new goal",
preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save",
style: .default) { action in
let goalField = alert.textFields![0].text
let pointsString = alert.textFields![1].text
if goalField! == "" || pointsString == "" {
self.errorAlert(title: "Error", alertCase: "Fill in all the fields")
} else if self.isNumeric(a: pointsString!) {
self.errorAlert(title: "Error", alertCase: "the points field should contain only numbers")
} else {
let pointsField: Int = Int(pointsString!)!
let goalItem = Goal(name: goalField!, addedByUser: self.name, completed: false, points: pointsField, group: self.group, completedBy: self.completedBy)
let goalItemRef = self.goalRef.child((goalField?.lowercased())!)
self.items.append(goalItem)
goalItemRef.setValue(goalItem.toAnyObject())
}
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .default)
alert.addTextField { textGoal in
textGoal.placeholder = "Enter a new goal"
}
alert.addTextField { textPoints in
textPoints.placeholder = "How many points is this worth?"
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
@IBAction func LogoutDidTouch(_ sender: Any) {
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
// MARK: Functions
func toggleCellCheckbox(_ cell: UITableViewCell, isCompleted: Bool) {
if !isCompleted {
cell.accessoryType = .none
} else {
cell.accessoryType = .checkmark
}
}
func errorAlert(title: String, alertCase: String) {
let alert = UIAlertController(title: title, message: alertCase , preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok!", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func retrieveUserDataFirebase(){
FIRAuth.auth()!.addStateDidChangeListener { auth, user in
guard let user = user else { return }
self.user = User(authData: user)
let currentUser = FIRDatabase.database().reference(withPath: "Users").child(self.user.uid)
currentUser.observeSingleEvent(of: .value, with: { snapshot in
let value = snapshot.value as? NSDictionary
self.group = value?["group"] as! String
self.name = value?["email"] as! String
self.pointsInt = value?["points"] as! Int
self.pointsString = String(self.pointsInt)
self.goalRef.queryOrdered(byChild: "group").queryEqual(toValue: self.group).observe(.value, with:
{ (snapshot) in
self.goalRef.queryOrdered(byChild: "completedBy").queryEqual(toValue: "").observe(.value, with:
{ (snapshot) in
var newItems: [Goal] = []
for item in snapshot.children {
let goalItem = Goal(snapshot: item as! FIRDataSnapshot)
newItems.append(goalItem)
}
self.items = newItems
self.tableView.reloadData()
})
})
})
}
}
func isNumeric(a: String) -> Bool {
return Double(a) == nil
}
// MARK: UITableView Delegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GoalsCell
cell.selectedBackgroundView = UIView(frame: cell.frame)
cell.selectedBackgroundView?.backgroundColor = UIColor.blue
let goal = items[indexPath.row]
cell.goalLabel.text = goal.name
cell.addedByLabel.text = "Added by: " + goal.addedByUser
cell.pointsLabel.text = String(goal.points) + " xp"
toggleCellCheckbox(cell, isCompleted: goal.completed)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let goal = items[indexPath.row]
let toggledCompletion = !goal.completed
let currentPointsInt = pointsInt + goal.points
let userPointRef = usersRef.child("points")
let newCompletedBy = self.name
let currentUser = FIRDatabase.database().reference(withPath: "Users").child(self.user.uid)
toggleCellCheckbox(cell, isCompleted: toggledCompletion)
goal.ref?.updateChildValues(["completed": toggledCompletion])
pointsInt = currentPointsInt
userPointRef.updateChildValues(["points":currentPointsInt])
currentUser.child("points").setValue(pointsInt)
goal.ref?.updateChildValues(["completedBy" : newCompletedBy])
sleep(2)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let goal = items[indexPath.row]
goal.ref?.removeValue()
}
}
}
| mit | 8c81908e5c0f24b13a7bbc159c899b97 | 37.697248 | 190 | 0.539237 | 5.292346 | false | false | false | false |
zhixingxi/JJA_Swift | JJA_Swift/Pods/TimedSilver/Sources/Foundation/Timer+TSBlock.swift | 1 | 4076 | //
// Timer+TSBlock.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/10/16.
// Copyright © 2016 Hilen. All rights reserved.
//
// https://github.com/radex/SwiftyTimer/blob/swift3/Sources/SwiftyTimer.swift
import Foundation
extension Timer {
// MARK: Schedule timers
/// Create and schedule a timer that will call `block` once after the specified time.
@discardableResult
public class func ts_after(_ interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
let timer = Timer.ts_new(after: interval, block)
timer.ts_start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
@discardableResult
public class func ts_every(_ interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
let timer = Timer.ts_new(every: interval, block)
timer.ts_start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
/// (This variant also passes the timer instance to the block)
@nonobjc @discardableResult
public class func ts_every(_ interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
let timer = Timer.ts_new(every: interval, block)
timer.ts_start()
return timer
}
// MARK: Create timers without scheduling
/// Create a timer that will call `block` once after the specified time.
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.after` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
public class func ts_new(after interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, 0, 0, 0) { _ in
block()
}
}
/// Create a timer that will call `block` repeatedly in specified time intervals.
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.every` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
public class func ts_new(every interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
block()
}
}
/// Create a timer that will call `block` repeatedly in specified time intervals.
/// (This variant also passes the timer instance to the block)
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.every` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
@nonobjc public class func ts_new(every interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
block(timer)
}
return timer
}
// MARK: Manual scheduling
/// Schedule this timer on the run loop
///
/// By default, the timer is scheduled on the current run loop for the default mode.
/// Specify `runLoop` or `modes` to override these defaults.
public func ts_start(runLoop: RunLoop = RunLoop.current, modes: RunLoopMode...) {
let modes = modes.isEmpty ? [RunLoopMode.defaultRunLoopMode] : modes
for mode in modes {
runLoop.add(self, forMode: mode)
}
}
}
| mit | 816ebc34f371279fa5af161fafa1c028 | 39.75 | 130 | 0.643436 | 4.517738 | false | false | false | false |
yuenhsi/interactive-bridge | Interactive Bridge/Interactive Bridge/Hand.swift | 1 | 1223 | //
// Hand.swift
// Interactive Bridge
//
// Created by Yuen Hsi Chang on 1/26/17.
// Copyright © 2017 Yuen Hsi Chang. All rights reserved.
//
import Foundation
class Hand {
var cards: [Card]!
init(_ cards: [Card]) {
self.cards = cards
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func sortCardsBySuit(first: Card, second: Card) -> Bool {
if first.Suit == second.Suit {
return first.Rank.hashValue > second.Rank.hashValue
} else {
return first.Suit.hashValue > second.Suit.hashValue
}
}
func cardsIn(suit: Suit) -> Int {
return (cards.filter { $0.Suit == suit }).count
}
func addCard(card: Card) {
self.cards.append(card)
}
func removeCard(card: Card) {
self.cards = self.cards.filter() { $0 != card }
}
func sort() {
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func removeAll() {
self.cards.removeAll()
}
func hasSuit(suit: Suit?) -> Bool {
if suit == nil {
return false
}
return self.cards.contains(where: { $0.Suit == suit} )
}
}
| mit | 19b5977372e7e633825feee34ddee9c0 | 21.62963 | 66 | 0.536825 | 3.626113 | false | false | false | false |
adamkaplan/swifter | Swifter/PartialFunction.swift | 1 | 6262 | //
// PartialFunction.swift
// Swifter
//
// Created by Adam Kaplan on 6/3/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import Foundation
public enum DefinedResult<Z> {
case Defined(Z)
case Undefined
}
public class UndefinedArgumentException : TryFailure {
public func fail() -> () {
NSException(name: "UndefinedArgumentException", reason: nil, userInfo: nil).raise()
}
}
public class PartialFunction<A,B> {
typealias PF = PartialFunction<A,B>
typealias Z = B // The final return type, provided to be overriden
typealias DefaultPF = PartialFunction<A,Z>
private let applyOrCheck: (A, Bool) -> DefinedResult<Z>
init(f: (A, Bool) -> DefinedResult<Z>) {
self.applyOrCheck = f
}
deinit {
DLog(.PartialFunction, "Deinitializing PartialFunction")
}
/** Optionally applies this PartialFunction to `a` if it is in the domain. */
public func apply(a: A) -> B? {
switch applyOrCheck(a, false) {
case .Defined(let p):
return p
case .Undefined:
return nil
}
}
/** Applies this PartialFunction to `a`, and in the case that 'a' is undefined
for the function, applies defaultPF to `a`. */
public func applyOrElse(a: A, defaultPF: DefaultPF) -> Z? {
switch applyOrCheck(a, false) {
case .Defined(let p):
return p
default:
return defaultPF.apply(a)
}
}
/** Attempts to apply this PartialFunction to `a` and returns a Try of the attempt. */
public func tryApply(a: A) -> Try<B> {
switch applyOrCheck(a, false) {
case .Defined(let p):
return .Success([p])
case .Undefined:
return .Failure(UndefinedArgumentException())
}
}
/** Returns true if this PartialFunction can be applied to `a` */
public func isDefinedAt(a: A) -> Bool {
switch applyOrCheck(a, true) {
case .Defined(_):
return true
case .Undefined:
return false
}
}
/** Returns a PartialFunction that first applies this function, or else applies otherPF. */
public func orElse(otherPF: PF) -> PF {
return OrElse(f1: self, f2: otherPF)
}
/** Returns a PartialFunction that first applies this function, and if successful,
next applies nextPF. */
public func andThen<C>(nextPF: PartialFunction<B,C>) -> PartialFunction<A,C> {
return AndThen<A,B,C>(f1: self, f2: nextPF)
}
}
private class OrElse<A,B> : PartialFunction<A,B> {
let _f1, _f2: PF
init(f1: PF, f2: PF) {
_f1 = f1
_f2 = f2
super.init( {
(a, checkOnly) in
let result1 = f1.applyOrCheck(a, checkOnly)
switch result1 {
case .Defined(_):
return result1
case .Undefined:
return f2.applyOrCheck(a, checkOnly)
}
})
}
deinit {
DLog(.PartialFunction, "Deinitializing OrElse")
}
override func isDefinedAt(a: A) -> Bool {
return _f1.isDefinedAt(a) || _f2.isDefinedAt(a)
}
override func orElse(f3: PF) -> PF {
return OrElse(f1: _f1, f2: _f2.orElse(f3))
}
override func applyOrElse(a: A, defaultPF: PF) -> B? {
switch _f1.applyOrCheck(a, false) {
case .Defined(let result1):
return result1
default:
return _f2.applyOrElse(a, defaultPF: defaultPF)
}
}
override func andThen<C>(nextPF: PartialFunction<B,C>) -> PartialFunction<A,C> {
return OrElse<A,C>(
f1: AndThen<A,B,C>(f1: _f1, f2: nextPF),
f2: AndThen<A,B,C>(f1: _f2, f2: nextPF))
}
}
private class AndThen<A,B,C> : PartialFunction<A,C> {
typealias NextPF = PartialFunction<B,C>
typealias Z = C
let _f1: PartialFunction<A,B>
let _f2: NextPF
init(f1: PartialFunction<A,B>, f2: NextPF) {
_f1 = f1
_f2 = f2
super.init( {
(a, checkOnly) in
let result1 = f1.applyOrCheck(a, checkOnly)
switch result1 {
case .Defined(let r1):
let result2 = f2.applyOrCheck(r1, checkOnly)
switch result2 {
case .Defined(_):
return result2
case .Undefined:
return .Undefined
}
case .Undefined:
return .Undefined
}
})
}
deinit {
DLog(.PartialFunction, "Deinitializing AndThen")
}
override func applyOrElse(a: A, defaultPF: DefaultPF) -> Z? {
switch self.applyOrCheck(a, false) {
case .Defined(let result):
return result
case .Undefined:
return defaultPF.apply(a)
}
}
}
/* Creates a non-side-effect PartialFunction from body for a specific domain. */
infix operator >< {precedence 255}
func >< <A,B> (domain: (a: A) -> Bool, body: (a: A) -> B) -> PartialFunction<A,B> {
return PartialFunction<A,B>( {
(a: A, _) in
if domain(a: a) {
return .Defined(body(a: a))
} else {
return .Undefined
}
})
}
/** Joins two PartialFunctions via PartialFunction.andThen(). */
infix operator => {precedence 128 associativity left}
func => <A,B,C> (pf: PartialFunction<A, B>, nextPF: PartialFunction<B,C>) -> PartialFunction<A,C>{
return pf.andThen(nextPF)
}
/** Joins two PartialFunctions via PartialFunction.orElse(). */
infix operator | {precedence 64 associativity left}
func | <A,B> (pf: PartialFunction<A,B>, otherPF: PartialFunction<A,B>) -> PartialFunction<A,B> {
return pf.orElse(otherPF)
}
/** Matches the value with the PartialFunction.
Example usage:
match(5) {
{ $0 ~~ String.self } =|= { "Kitty says " + $0 }
{ $0 ~~ Int.self } =|= { "This is an integer: \($0)" }
} // returns "This is an integer: 5" */
func match<A,B>(value: A, patternMatch: () -> PartialFunction<A,B>) -> B? {
return patternMatch().apply(value)
}
| apache-2.0 | e78bd8c0ddadba5795c19f477b2b9c36 | 27.593607 | 98 | 0.553976 | 3.899128 | false | false | false | false |
warnerbros/cpe-manifest-ios-experience | Source/Out-of-Movie Experience/ExtrasSceneLocationsViewController.swift | 1 | 20279 | //
// ExtrasSceneLocationsViewController.swift
//
import UIKit
import MapKit
import CPEData
class ExtrasSceneLocationsViewController: ExtrasExperienceViewController, UICollectionViewDataSource {
fileprivate struct Constants {
static let CollectionViewItemSpacing: CGFloat = (DeviceType.IS_IPAD ? 12 : 5)
static let CollectionViewLineSpacing: CGFloat = (DeviceType.IS_IPAD ? 12 : 15)
static let CollectionViewPadding: CGFloat = (DeviceType.IS_IPAD ? 15 : 10)
static let CollectionViewImageAspectRatio: CGFloat = 16 / 9
static let CollectionViewLabelHeight: CGFloat = (DeviceType.IS_IPAD ? 35 : 30)
}
@IBOutlet weak private var mapView: MultiMapView!
@IBOutlet weak private var breadcrumbsPrimaryButton: UIButton!
@IBOutlet weak private var breadcrumbsSecondaryArrowImageView: UIImageView!
@IBOutlet weak private var breadcrumbsSecondaryLabel: UILabel!
@IBOutlet weak private var collectionView: UICollectionView!
private var mapTypeDidChangeObserver: NSObjectProtocol?
@IBOutlet weak private var locationDetailView: UIView!
@IBOutlet weak private var videoContainerView: UIView!
private var videoPlayerViewController: VideoPlayerViewController?
private var videoPlayerDidToggleFullScreenObserver: NSObjectProtocol?
private var videoPlayerDidEndVideoObserver: NSObjectProtocol?
@IBOutlet weak private var galleryScrollView: ImageGalleryScrollView!
@IBOutlet weak private var galleryPageControl: UIPageControl!
@IBOutlet weak private var closeButton: UIButton?
private var galleryDidToggleFullScreenObserver: NSObjectProtocol?
private var galleryDidScrollToPageObserver: NSObjectProtocol?
@IBOutlet private var containerTopConstraint: NSLayoutConstraint?
@IBOutlet private var containerBottomConstraint: NSLayoutConstraint?
@IBOutlet private var containerAspectRatioConstraint: NSLayoutConstraint?
@IBOutlet private var containerBottomInnerConstraint: NSLayoutConstraint?
private var locationExperiences = [Experience]()
fileprivate var markers = [String: MultiMapMarker]() // ExperienceID: MultiMapMarker
fileprivate var selectedExperience: Experience? {
didSet {
if let selectedExperience = selectedExperience {
if let marker = markers[selectedExperience.id] {
if let location = selectedExperience.location {
mapView.maxZoomLevel = (location.zoomLocked ? location.zoomLevel : -1)
mapView.setLocation(marker.location, zoomLevel: location.zoomLevel, animated: true)
}
mapView.selectedMarker = marker
}
} else {
mapView.selectedMarker = nil
var lowestZoomLevel = Int.max
for locationExperience in locationExperiences {
if let location = locationExperience.location, location.zoomLocked, location.zoomLevel < lowestZoomLevel {
lowestZoomLevel = location.zoomLevel
}
}
mapView.maxZoomLevel = lowestZoomLevel
mapView.zoomToFitAllMarkers()
}
if selectedExperience == nil || selectedExperience!.locationMediaCount > 0 {
reloadBreadcrumbs()
collectionView.reloadData()
collectionView.contentOffset = CGPoint.zero
}
}
}
private var currentGalleryAnalyticsIdentifier: String?
private var currentVideoAnalyticsIdentifier: String?
deinit {
let center = NotificationCenter.default
if let observer = mapTypeDidChangeObserver {
center.removeObserver(observer)
mapTypeDidChangeObserver = nil
}
if let observer = videoPlayerDidToggleFullScreenObserver {
center.removeObserver(observer)
videoPlayerDidToggleFullScreenObserver = nil
}
if let observer = videoPlayerDidEndVideoObserver {
center.removeObserver(observer)
videoPlayerDidEndVideoObserver = nil
}
if let observer = galleryDidToggleFullScreenObserver {
center.removeObserver(observer)
galleryDidToggleFullScreenObserver = nil
}
if let observer = galleryDidScrollToPageObserver {
center.removeObserver(observer)
galleryDidScrollToPageObserver = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
galleryScrollView.cleanInvisibleImages()
}
override func viewDidLoad() {
super.viewDidLoad()
if let childExperiences = experience.childExperiences {
locationExperiences = childExperiences
}
breadcrumbsPrimaryButton.setTitle(experience.title.uppercased(), for: .normal)
collectionView.register(UINib(nibName: MapItemCell.NibName, bundle: Bundle.frameworkResources), forCellWithReuseIdentifier: MapItemCell.ReuseIdentifier)
closeButton?.titleLabel?.font = UIFont.themeCondensedFont(17)
closeButton?.setTitle(String.localize("label.close"), for: .normal)
closeButton?.setImage(UIImage(named: "Close", in: Bundle.frameworkResources, compatibleWith: nil), for: .normal)
closeButton?.contentEdgeInsets = UIEdgeInsets(top: 0, left: -35, bottom: 0, right: 0)
closeButton?.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 25)
closeButton?.imageEdgeInsets = UIEdgeInsets(top: 0, left: 110, bottom: 0, right: 0)
breadcrumbsSecondaryArrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
mapTypeDidChangeObserver = NotificationCenter.default.addObserver(forName: .locationsMapTypeDidChange, object: nil, queue: OperationQueue.main, using: { (notification) in
if let mapType = notification.userInfo?[NotificationConstants.mapType] as? MultiMapType {
Analytics.log(event: .extrasSceneLocationsAction, action: .setMapType, itemName: (mapType == .satellite ? AnalyticsLabel.satellite : AnalyticsLabel.road))
}
})
videoPlayerDidToggleFullScreenObserver = NotificationCenter.default.addObserver(forName: .videoPlayerDidToggleFullScreen, object: nil, queue: OperationQueue.main, using: { [weak self] (notification) in
if let isFullScreen = notification.userInfo?[NotificationConstants.isFullScreen] as? Bool, isFullScreen {
Analytics.log(event: .extrasSceneLocationsAction, action: .setVideoFullScreen, itemId: self?.currentVideoAnalyticsIdentifier)
}
})
videoPlayerDidEndVideoObserver = NotificationCenter.default.addObserver(forName: .videoPlayerDidEndVideo, object: nil, queue: OperationQueue.main, using: { [weak self] (_) in
self?.closeDetailView(animated: true)
})
galleryDidToggleFullScreenObserver = NotificationCenter.default.addObserver(forName: .imageGalleryDidToggleFullScreen, object: nil, queue: OperationQueue.main, using: { [weak self] (notification) in
if let isFullScreen = notification.userInfo?[NotificationConstants.isFullScreen] as? Bool {
self?.closeButton?.isHidden = isFullScreen
self?.galleryPageControl.isHidden = isFullScreen
if isFullScreen {
Analytics.log(event: .extrasSceneLocationsAction, action: .setImageGalleryFullScreen, itemId: self?.currentGalleryAnalyticsIdentifier)
}
}
})
galleryDidScrollToPageObserver = NotificationCenter.default.addObserver(forName: .imageGalleryDidScrollToPage, object: nil, queue: OperationQueue.main, using: { [weak self] (notification) in
if let page = notification.userInfo?[NotificationConstants.page] as? Int {
self?.galleryPageControl.currentPage = page
Analytics.log(event: .extrasSceneLocationsAction, action: .selectImage, itemId: self?.currentGalleryAnalyticsIdentifier)
}
})
galleryScrollView.allowsFullScreen = DeviceType.IS_IPAD
// Set up map markers
for locationExperience in locationExperiences {
if let location = locationExperience.location {
markers[locationExperience.id] = mapView.addMarker(location.centerPoint, title: location.name, subtitle: location.address, icon: location.iconImage, autoSelect: false)
}
}
mapView.addControls()
mapView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
selectedExperience = nil
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let toLandscape = (size.width > size.height)
containerAspectRatioConstraint?.isActive = !toLandscape
containerTopConstraint?.constant = (toLandscape ? 0 : ExtrasExperienceViewController.Constants.TitleImageHeight)
containerBottomConstraint?.isActive = !toLandscape
containerBottomInnerConstraint?.isActive = !toLandscape
if #available(iOS 11.0, *) {
self.setNeedsUpdateOfHomeIndicatorAutoHidden()
}
coordinator.animate(alongsideTransition: nil, completion: { (_) in
self.galleryScrollView.layoutPages()
})
if toLandscape {
if let galleryAnalyticsIdentifier = currentGalleryAnalyticsIdentifier {
Analytics.log(event: .extrasSceneLocationsAction, action: .setImageGalleryFullScreen, itemId: galleryAnalyticsIdentifier)
} else if let videoAnalyticsIdentifier = currentVideoAnalyticsIdentifier {
Analytics.log(event: .extrasSceneLocationsAction, action: .setVideoFullScreen, itemId: videoAnalyticsIdentifier)
}
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if DeviceType.IS_IPAD || (currentGalleryAnalyticsIdentifier == nil && currentVideoAnalyticsIdentifier == nil) {
return super.supportedInterfaceOrientations
}
return .all
}
override func prefersHomeIndicatorAutoHidden() -> Bool {
return (containerBottomConstraint != nil && !containerBottomConstraint!.isActive)
}
private func playVideo(fromExperience experience: Experience) {
if let videoURL = experience.video?.url {
let shouldAnimateOpen = locationDetailView.isHidden
closeDetailView(animated: false)
if let videoPlayerViewController = UIStoryboard.viewController(for: VideoPlayerViewController.self) as? VideoPlayerViewController {
videoPlayerViewController.mode = VideoPlayerMode.supplemental
videoPlayerViewController.view.frame = videoContainerView.bounds
videoContainerView.addSubview(videoPlayerViewController.view)
self.addChildViewController(videoPlayerViewController)
videoPlayerViewController.didMove(toParentViewController: self)
if !DeviceType.IS_IPAD && videoPlayerViewController.fullScreenButton != nil {
videoPlayerViewController.fullScreenButton?.removeFromSuperview()
}
self.videoPlayerViewController = videoPlayerViewController
locationDetailView.alpha = 0
locationDetailView.isHidden = false
if shouldAnimateOpen {
UIView.animate(withDuration: 0.25, animations: {
self.locationDetailView.alpha = 1
}, completion: { (_) in
self.videoPlayerViewController?.playAsset(withURL: videoURL, title: experience.title, imageURL: experience.thumbnailImageURL)
})
} else {
locationDetailView.alpha = 1
self.videoPlayerViewController?.playAsset(withURL: videoURL, title: experience.title, imageURL: experience.thumbnailImageURL)
}
}
}
}
func showGallery(_ gallery: Gallery) {
let shouldAnimateOpen = locationDetailView.isHidden
closeDetailView(animated: false)
galleryScrollView.load(with: gallery)
galleryScrollView.isHidden = false
if gallery.isTurntable {
galleryPageControl.isHidden = true
} else {
galleryPageControl.isHidden = false
galleryPageControl.numberOfPages = gallery.numPictures
galleryPageControl.currentPage = 0
}
locationDetailView.alpha = 0
locationDetailView.isHidden = false
if shouldAnimateOpen {
UIView.animate(withDuration: 0.25, animations: {
self.locationDetailView.alpha = 1
})
} else {
locationDetailView.alpha = 1
}
}
@IBAction func closeDetailView() {
closeDetailView(animated: true)
}
private func closeDetailView(animated: Bool) {
let hideViews = {
self.locationDetailView.isHidden = true
self.galleryScrollView.load(with: nil)
self.galleryScrollView.isHidden = true
self.galleryPageControl.isHidden = true
self.videoPlayerViewController?.willMove(toParentViewController: nil)
self.videoPlayerViewController?.view.removeFromSuperview()
self.videoPlayerViewController?.removeFromParentViewController()
self.videoPlayerViewController = nil
}
if animated {
UIView.animate(withDuration: 0.2, animations: {
self.locationDetailView.alpha = 0
}, completion: { (_) in
hideViews()
})
} else {
hideViews()
}
}
func reloadBreadcrumbs() {
breadcrumbsPrimaryButton.isUserInteractionEnabled = false
breadcrumbsSecondaryArrowImageView.isHidden = true
breadcrumbsSecondaryLabel.isHidden = true
if let selectedExperience = selectedExperience, selectedExperience.locationMediaCount > 0 {
breadcrumbsSecondaryLabel.text = selectedExperience.title.uppercased()
breadcrumbsSecondaryLabel.sizeToFit()
breadcrumbsSecondaryLabel.frame.size.height = breadcrumbsPrimaryButton.frame.height
breadcrumbsSecondaryArrowImageView.isHidden = false
breadcrumbsSecondaryLabel.isHidden = false
breadcrumbsPrimaryButton.isUserInteractionEnabled = true
}
}
// MARK: Actions
override func close() {
if !locationDetailView.isHidden && !DeviceType.IS_IPAD {
closeDetailView()
} else {
mapView.destroy()
mapView = nil
super.close()
}
}
@IBAction func onTapBreadcrumb(_ sender: UIButton) {
closeDetailView(animated: false)
selectedExperience = nil
currentVideoAnalyticsIdentifier = nil
currentGalleryAnalyticsIdentifier = nil
}
@IBAction func onPageControlValueChanged() {
galleryScrollView.gotoPage(galleryPageControl.currentPage, animated: true)
}
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let selectedExperience = selectedExperience, selectedExperience.locationMediaCount > 0 {
return selectedExperience.locationMediaCount
}
return locationExperiences.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: MapItemCell.ReuseIdentifier, for: indexPath)
guard let cell = collectionViewCell as? MapItemCell else {
return collectionViewCell
}
cell.backgroundColor = UIColor.black.withAlphaComponent(0.5)
if let selectedExperience = selectedExperience, selectedExperience.locationMediaCount > 0 {
if let experience = selectedExperience.locationMediaAtIndex(indexPath.row) {
cell.playButtonVisible = experience.isType(.audioVisual)
cell.imageURL = experience.thumbnailImageURL
cell.title = experience.title
}
} else {
let experience = locationExperiences[indexPath.row]
cell.playButtonVisible = false
cell.imageURL = experience.thumbnailImageURL
cell.title = experience.title
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
currentVideoAnalyticsIdentifier = nil
currentGalleryAnalyticsIdentifier = nil
if let selectedExperience = selectedExperience, selectedExperience.locationMediaCount > 0 {
if let experience = selectedExperience.locationMediaAtIndex(indexPath.row) {
if let video = experience.video {
playVideo(fromExperience: experience)
currentVideoAnalyticsIdentifier = video.analyticsID
Analytics.log(event: .extrasSceneLocationsAction, action: .selectVideo, itemId: currentVideoAnalyticsIdentifier)
} else if let gallery = experience.gallery {
showGallery(gallery)
currentGalleryAnalyticsIdentifier = gallery.analyticsID
Analytics.log(event: .extrasSceneLocationsAction, action: .selectImageGallery, itemId: currentGalleryAnalyticsIdentifier)
}
}
} else {
selectedExperience = locationExperiences[indexPath.row]
Analytics.log(event: .extrasSceneLocationsAction, action: .selectLocationThumbnail, itemId: selectedExperience?.analyticsID)
}
}
}
extension ExtrasSceneLocationsViewController: MultiMapViewDelegate {
func mapView(_ mapView: MultiMapView, didTapMarker marker: MultiMapMarker) {
for (experienceID, locationMarker) in markers {
if marker == locationMarker {
selectedExperience = CPEXMLSuite.current!.manifest.experienceWithID(experienceID)
Analytics.log(event: .extrasSceneLocationsAction, action: .selectLocationMarker, itemId: experienceID)
return
}
}
}
}
extension ExtrasSceneLocationsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if DeviceType.IS_IPAD {
let itemHeight = collectionView.frame.height
return CGSize(width: (itemHeight - Constants.CollectionViewLabelHeight) * Constants.CollectionViewImageAspectRatio, height: itemHeight)
}
let itemWidth = (collectionView.frame.width - (Constants.CollectionViewPadding * 2) - Constants.CollectionViewItemSpacing) / 2
return CGSize(width: itemWidth, height: (itemWidth / Constants.CollectionViewImageAspectRatio) + Constants.CollectionViewLabelHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return Constants.CollectionViewLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return Constants.CollectionViewItemSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: Constants.CollectionViewPadding, left: Constants.CollectionViewPadding, bottom: Constants.CollectionViewPadding, right: Constants.CollectionViewPadding)
}
}
| apache-2.0 | 93e366ecf50d7da63d1de1810606bd9e | 44.164811 | 209 | 0.684945 | 6.276385 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01925-swift-parser-consumetoken.swift | 1 | 588 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let a {
protocol A {
typealias h: b = g: (g: b = 1
return ")
let foo as a: H.b = {
}
func b: Boolean>(A>(".advance(f).b = a(i<()
}
init() {
class A.init(i(A.f = a(x: Int
var f<T..c == b<T>)
| apache-2.0 | ecfa9980716715a3f2969acc8aaa6e76 | 29.947368 | 79 | 0.680272 | 3.094737 | false | false | false | false |
mcudich/TemplateKit | Source/Core/Animation/Animatable.swift | 1 | 2276 | //
// Animatable.swift
// TemplateKit
//
// Created by Matias Cudich on 10/18/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
public enum AnimationState {
case pending
case running
case done
}
public protocol Tickable {
var hashValue: Int { get }
var state: AnimationState { get }
func tick(time: TimeInterval)
func equals(_ other: Tickable) -> Bool
}
public class Animatable<T: Equatable & Interpolatable>: Tickable, Model, Equatable {
public var hashValue: Int {
return ObjectIdentifier(self as AnyObject).hashValue
}
public private(set) var value: T?
public var duration: TimeInterval = 0
public var delay: TimeInterval = 0
public var interpolator: Interpolator
public var state: AnimationState {
if toValue != nil && beginTime == nil {
return .pending
} else if beginTime != nil {
return .running
}
return .done
}
private var fromValue: T?
private var toValue: T?
private var beginTime: TimeInterval?
public init(_ value: T?, duration: TimeInterval = 0, delay: TimeInterval = 0, interpolator: Interpolator = BezierInterpolator(.linear)) {
self.value = value
self.duration = duration
self.delay = delay
self.interpolator = interpolator
}
public func set(_ value: T?) {
if value != self.value && duration > 0 {
fromValue = self.value
toValue = value
return
}
self.value = value
}
public func tick(time: TimeInterval) {
if beginTime == nil {
beginTime = time
}
guard let beginTime = beginTime, let fromValue = fromValue, let toValue = toValue, time >= beginTime + delay else {
return
}
let effectiveBeginTime = beginTime + delay
if time - effectiveBeginTime > duration {
reset()
return
}
value = interpolator.interpolate(fromValue, toValue, time - effectiveBeginTime, duration)
}
public func reset() {
beginTime = nil
toValue = nil
fromValue = nil
}
public func equals(_ other: Tickable) -> Bool {
guard let other = other as? Animatable<T> else {
return false
}
return self == other
}
}
public func ==<T: Equatable>(lhs: Animatable<T>, rhs: Animatable<T>) -> Bool {
return lhs.value == rhs.value
}
| mit | 0f3d641a3744b7d2ee098e3a705c9834 | 22.214286 | 139 | 0.658462 | 4.236499 | false | false | false | false |
shepting/AutoLayout | AutoLayoutDemo/AutoLayoutDemo/Message.swift | 1 | 1769 | //
// Message.swift
// AutoLayoutDemo
//
// Created by Steven Hepting on 8/28/14.
// Copyright (c) 2014 Protospec. All rights reserved.
//
// Hipster Ipsum: http://hipsum.co/
// Corporate Ipsum: http://www.cipsum.com/
//
import UIKit
internal class Message: NSObject {
internal let text: String
internal let timeAgo: String
var author: User
override init() {
let samplePosts = ["Locavore Shoreditch semiotics, sustainable chia fashion axe stumptown brunch slow-carb.",
"Scenester gluten-free Bushwick Truffaut sustainable chia iPhone, ethical food truck.",
"Gluten-free deep v XOXO Portland sriracha PBR&B McSweeney's skateboard Schlitz VHS slow-carb iPhone. Typewriter aesthetic vegan Cosby sweater, Pinterest ethical mlkshk shabby chic viral Banksy pickled.",
"Letterpress artisan VHS sartorial fixie.",
"Keytar hoodie authentic cliche, roof party chia deep v XOXO Etsy fap. Stumptown asymmetrical ethnic, messenger bag readymade synth gentrify brunch food truck irony banjo DIY fingerstache yr.",
"Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI.",
"Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions."
]
let index = Int(arc4random_uniform(UInt32(samplePosts.count)))
text = samplePosts[index]
timeAgo = String(format: "%d h", arc4random_uniform(36) + 1)
author = User()
}
}
| mit | d98d825858d4375468080598bc8cd031 | 49.542857 | 236 | 0.723007 | 3.8125 | false | false | false | false |
jlyu/swift-demo | Whereami/Whereami/ViewController.swift | 1 | 5267 | //
// ViewController.swift
// Whereami
//
// Created by chain on 14-6-18.
// Copyright (c) 2014 chain. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate {
@IBOutlet var printLabel : UILabel = nil
@IBOutlet var worldView : MKMapView = nil
@IBOutlet var locationTitleField : UITextField = nil
@IBOutlet var activityIndicator : UIActivityIndicatorView = nil
var locationManager: CLLocationManager? = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.printLabel.text = ""
self.printLabel.numberOfLines = 0
self.printLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
locationManager!.delegate = self
locationManager!.desiredAccuracy = kCLLocationAccuracyBest
locationManager!.distanceFilter = 10
locationManager!.startUpdatingLocation() // to be del..
worldView.showsUserLocation = true
//worldView.mapType = .Satellite
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
self.locationManager = nil
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
var location:CLLocation = locations[locations.count-1] as CLLocation
self.locationManager!.stopUpdatingLocation()
println("-> \(location.coordinate.latitude), \(location.coordinate.longitude)")
self.printLabel.text = "Now we're here -> \(location.coordinate.latitude), \(location.coordinate.longitude)"
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Could not find location: \(error)")
self.printLabel.text = "Could not find location: \(error)"
}
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
if userLocation.updating {
var region :MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 50, 50)
self.worldView.setRegion(region, animated: true)
self.activityIndicator.stopAnimating()
}
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
var t: NSTimeInterval = newLocation.timestamp.timeIntervalSinceNow
if t < -10 {
return;
}
foundLocation(newLocation)
}
func showPlaceMarksOnWorldMap(placeMarks:AnyObject[]!, error: NSError!) {
if !placeMarks {
println(error)
self.printLabel.text = "Could not find location: \(error)"
return
}
var queryStr: String = self.locationTitleField.text
var placeMarkArray: CLPlacemark[]?
//placeMarkArray = placeMarks as? CLPlacemark[]
if placeMarks.count > 0 {
self.worldView.removeAnnotations(self.worldView.annotations)
}
for var i=placeMarks.count-1; i>0; --i {
if let placeMark = placeMarks[i] as? CLPlacemark {
var viewRegion: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(placeMark.location.coordinate, 10000, 10000)
self.worldView.setRegion(viewRegion, animated: true)
var mapPoint: BNRMapPoint = BNRMapPoint(coordinate: placeMark.location.coordinate, title: queryStr)
self.worldView.addAnnotation(mapPoint)
}
self.printLabel.text = "find \(queryStr)"
}
//if placeMarkArray {
// println("placeMarkArray -> \(placeMarkArray!.count)")
//}
}
func findLocation(queryStr: String) {
println(queryStr) // ok
var geoCode: CLGeocoder = CLGeocoder()
geoCode.geocodeAddressString(queryStr, completionHandler: showPlaceMarksOnWorldMap)
}
func foundLocation(loc:CLLocation) {
var mapPoint: BNRMapPoint = BNRMapPoint(coordinate: loc.coordinate, title: self.locationTitleField.text)
self.worldView.addAnnotation(mapPoint)
var region :MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(loc.coordinate, 50, 50)
self.worldView.setRegion(region, animated: true)
self.locationTitleField.text = "moved"
self.locationTitleField.hidden = false
activityIndicator.stopAnimating()
locationManager!.stopUpdatingLocation()
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
locationManager!.stopUpdatingLocation()
activityIndicator.startAnimating()
locationTitleField.hidden = true
findLocation(self.locationTitleField.text)
locationTitleField.resignFirstResponder()
locationTitleField.hidden = false
activityIndicator.stopAnimating()
return true
}
}
| mit | 3715229d6b2f7a62c575b6f1132e95eb | 34.348993 | 140 | 0.648187 | 5.633155 | false | false | false | false |
thislooksfun/Tavi | Tavi/Helper/Logger.swift | 1 | 16897 | //
// Logger.swift
// Tavi
//
// Copyright (C) 2016 thislooksfun
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
//#if
import UIKit
/// A (decently) simple logging system
public class Logger
{
/// The longest function name we have yet seen - used to try to equalize the log positions
private static var longestFunctionNameSoFar = 0
/// The longest file name we have yet seen - used to try to equalize the log positions
private static var longestFileNameSoFar = 0
/// The longest line number we have yet seen - used to try to equalize the log positions
private static var longestLineNumberSoFar = 0
/// The minimum level required for a message to be displayed
private static var minLogLevel: LogLevel?
/// The indentation prefix
private static var indentPrefix = ""
/// Increases the indent by two spaces
public static func indent() {
indentPrefix += " "
}
/// If the current indent is greater than two spaces, decrease the index by two spaces
/// Otherwise, set the indent to an empty string
public static func outdent() {
if indentPrefix.characters.count >= 2 {
indentPrefix = indentPrefix.substringToIndex(indentPrefix.endIndex.advancedBy(-2))
} else {
indentPrefix = ""
}
}
/// Sets the minimum log level
///
/// - Parameter level: The new minimum log level
public static func setLogLevel(level: LogLevel) {
minLogLevel = level
}
/// Whether or not to include the function signature in the log
public static var useFunctionName = false
/// Whether or not to include the file name in the log
public static var useFileName = true
/// Whether or not to include the line number in the log - does nothing if `useFileName` is `false`
public static var useLineNumber = true
//TODO: Add more settings here
public static var xcodeColorsEnabled: Bool = {
let colors = NSProcessInfo.processInfo().environment["XcodeColors"]
return colors == "YES"
}()
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - vals: The values to log
public static func log<T>(level: LogLevel, vals: T..., functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(level, seperator: " ", arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - vals: The values to log
public static func log<T>(level: LogLevel, vals: T?..., functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(level, seperator: " ", arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - seperator: The string to insert between the vals
/// - vals: The values to log
public static func log<T>(level: LogLevel, seperator: String, vals: T..., functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(level, seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - seperator: The string to insert between the vals
/// - vals: The values to log
public static func log<T>(level: LogLevel, seperator: String, vals: T?..., functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(level, seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - seperator: The string to insert between the vals
/// - vals: The values to log
private static func log<T>(level: LogLevel, seperator: String, arr: [T?], functionName: String, filePath: String, lineNumber: Int) {
var out = [String]()
for v in arr {
if v == nil {
out.append("nil")
} else {
out.append("Optional(\(v!))")
}
}
log(level, seperator: seperator, arr: out, functionName: functionName, filePath: filePath, lineNumber: lineNumber)
}
/// Logs a message at the specified level
///
/// - Parameters:
/// - level: The level to log at
/// - seperator: The string to insert between the vals
/// - vals: The values to log
private static func log<T>(level: LogLevel, seperator: String, arr: [T], functionName: String, filePath: String, lineNumber: Int) {
if minLogLevel == nil {
minLogLevel = LogLevel.Info
}
guard level.index >= minLogLevel!.index else { return }
var callerInfo = ""
if useFunctionName {
var funcName = functionName+" "
if funcName.length > longestFunctionNameSoFar {
longestFunctionNameSoFar = funcName.length
} else {
funcName.ensureAtLeast(longestFunctionNameSoFar)
}
callerInfo += funcName
}
if useFileName {
var fileName = "("+(filePath as NSString).lastPathComponent
if fileName.length > longestFileNameSoFar {
longestFileNameSoFar = fileName.length
} else {
fileName.ensureAtLeast(longestFileNameSoFar, prepend: true)
}
callerInfo += fileName
if useLineNumber {
var lineNum = "\(lineNumber)) "
if lineNum.length > longestLineNumberSoFar {
longestLineNumberSoFar = lineNum.length
} else {
lineNum.ensureAtLeast(longestLineNumberSoFar)
}
callerInfo += ":\(lineNum)"
} else {
callerInfo += ") "
}
}
let prefix = "\(level.prefix)\(indentPrefix)"
if xcodeColorsEnabled {
// s = "\(level.color.format())\(s)\(XcodeColor.reset)"
// prefix = "\(level.color.format())\(level.prefix)\(XcodeColor.reset)\(indentPrefix)"
}
var s = ""
for v in arr {
let stringified = "\(v)"
s += (s == "" ? "" : seperator)+stringified
}
s = s.stringByReplacingOccurrencesOfString("\r\n", withString: "\n")
s = s.stringByReplacingOccurrencesOfString("\r", withString: "\\r\n")
s = s.stringByReplacingOccurrencesOfString("\n", withString: "\n\(callerInfo)\(prefix)")
print("\(callerInfo)\(prefix)\(s)")
}
/// Logs a message at the plain level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func plain<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { plain(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the plain level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func plain<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { plain(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func plain<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Plain, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func plain<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Plain, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the debug level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func debug<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { debug(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the debug level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func debug<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { debug(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func debug<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Debug, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func debug<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Debug, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the trace level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func trace<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { trace(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the trace level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func trace<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { trace(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func trace<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Trace, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func trace<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Trace, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the info level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func info<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { info(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the info level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func info<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { info(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func info<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Info, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func info<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Info, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the warn level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func warn<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { warn(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the warn level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func warn<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { warn(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func warn<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Warn, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func warn<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Warn, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the error level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func error<T>(vals: T..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { error(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
/// Logs a message at the error level
///
/// - Parameters:
/// - vals: The values to log
/// - seperator: The seperator to use (Default: `" "`)
public static func error<T>(vals: T?..., seperator: String = " ", functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { error(seperator: seperator, arr: vals, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func error<T>(seperator seperator: String, arr: [T], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Error, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
private static func error<T>(seperator seperator: String, arr: [T?], functionName: String = #function, filePath: String = #file, lineNumber: Int = #line) { log(.Error, seperator: seperator, arr: arr, functionName: functionName, filePath: filePath, lineNumber: lineNumber) }
//TODO: Get colors working. Maybe use https://github.com/robbiehanson/XcodeColors ? (Wow that link looks crap on this background)
/// The level to log at
public struct LogLevel
{
/// The Debug level
///
/// This is the lowest level, used primarily for internal testing and, well, debugging
public static let Debug = LogLevel(index: 0, prefix: "DEBUG: ", color: "")
/// The Plain level
///
/// This is the 2nd lowest level, used for displaying plain-text messages with no prefix
public static let Plain = LogLevel(index: 1, prefix: "", color: "")
/// The Trace level
///
/// This is the 3rd level, used for verbose logging, such as incoming HTTP messages and loop outputs
public static let Trace = LogLevel(index: 2, prefix: "TRACE: ", color: "")
/// The Info level
///
/// This is the 4th level, and is used for general information logging
public static let Info = LogLevel(index: 3, prefix: " INFO: ", color: "")
/// The Warn level
///
/// This is the 2nd highest level, used for items that could cause strange behaviour, but are not app-breaking
public static let Warn = LogLevel(index: 4, prefix: " WARN: ", color: "")
/// The Error level
///
/// This is the highest level. These messages will always be displayed, and thus
/// are used for errors that must be addressed ASAP
public static let Error = LogLevel(index: 5, prefix: "ERROR: ", color: "")
/// The prefix for this log level
private let prefix: String
/// The color to print (this isn't working yet)
private let color: String
private let index: Int
private init(index: Int, prefix: String, color: String) {
self.prefix = prefix
self.color = color
self.index = index
}
}
} | gpl-3.0 | 09897ecf8deae3199ad6c119d0dfdbe6 | 50.361702 | 280 | 0.688406 | 3.877237 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/Photo/EditorImageResizerView+Initial.swift | 1 | 13522 | //
// EditorImageResizerView+Initial.swift
// HXPHPicker
//
// Created by Slience on 2021/8/25.
//
import UIKit
import AVFoundation
extension EditorImageResizerView {
func setCropData(cropData: PhotoEditCropData) {
hasCropping = true
// 记录当前数据
oldAngle = cropData.angle
oldMirrorType = cropData.mirrorType
oldTransform = cropData.transform
cropSize = cropData.cropSize
oldContentInset = cropData.contentInset
let rect = AVMakeRect(aspectRatio: cropData.maskRect.size, insideRect: getEditableArea())
let widthScale = rect.width / cropData.maskRect.width
oldZoomScale = cropData.zoomScale * widthScale
oldMinimumZoomScale = cropData.minimumZoomScale * widthScale
oldMaximumZoomScale = cropData.maximumZoomScale * widthScale
let scrollViewContentInset = getScrollViewContentInset(rect, true)
let offsetX = baseImageSize.width * cropData.offsetScale.x * oldZoomScale - scrollViewContentInset.left
let offsetY = baseImageSize.height * cropData.offsetScale.y * oldZoomScale - scrollViewContentInset.top
oldContentOffset = CGPoint(x: offsetX, y: offsetY)
oldMaskRect = rect
imageView.stickerView.angle = oldAngle
imageView.stickerView.mirrorType = oldMirrorType
}
func setStickerData(stickerData: EditorStickerData?) {
if let stickerData = stickerData {
imageView.stickerView.setStickerData(stickerData: stickerData, viewSize: imageView.bounds.size)
}
}
func setBrushData(brushData: [PhotoEditorBrushData]) {
if !brushData.isEmpty {
imageView.drawView.setBrushData(brushData, viewSize: imageView.bounds.size)
}
}
func setMosaicData(mosaicData: [PhotoEditorMosaicData]) {
if !mosaicData.isEmpty {
imageView.mosaicView.setMosaicData(mosaicDatas: mosaicData, viewSize: imageView.bounds.size)
}
}
func getEditableArea() -> CGRect {
let editWidth = containerView.width - contentInsets.left - contentInsets.right
let editHeight = containerView.height - contentInsets.top - contentInsets.bottom
let editX = contentInsets.left
let editY = contentInsets.top
return CGRect(x: editX, y: editY, width: editWidth, height: editHeight)
}
func setImage(_ image: UIImage) {
updateContentInsets()
if image.size.equalTo(.zero) {
imageScale = 1
}else {
imageScale = image.width / image.height
}
imageView.setImage(image)
configAspectRatio()
updateScrollView()
updateImageViewFrame(getImageViewFrame())
/// 手势最大范围
let maxControlRect = CGRect(
x: contentInsets.left,
y: contentInsets.top,
width: containerView.width - contentInsets.left - contentInsets.right,
height: containerView.height - contentInsets.top - contentInsets.bottom
)
controlView.maxImageresizerFrame = maxControlRect
}
func setAVAsset(_ asset: AVAsset, coverImage: UIImage) {
setImage(coverImage)
imageView.videoView.avAsset = asset
}
/// 更新图片
func updateImage(_ image: UIImage) {
imageView.setImage(image)
}
func setMosaicOriginalImage(_ image: UIImage?) {
imageView.setMosaicOriginalImage(image)
}
/// 配置宽高比数据
func configAspectRatio() {
controlView.fixedRatio = cropConfig.fixedRatio
controlViewAspectRatio()
if cropConfig.isRoundCrop {
controlView.fixedRatio = true
controlView.aspectRatio = CGSize(width: 1, height: 1)
}
isFixedRatio = controlView.fixedRatio
currentAspectRatio = controlView.aspectRatio
checkOriginalRatio()
}
/// 裁剪框的宽高比
func controlViewAspectRatio() {
switch cropConfig.aspectRatioType {
case .original:
if cropConfig.fixedRatio {
controlView.aspectRatio = imageView.image!.size
}else {
controlView.aspectRatio = .zero
}
case .ratio_1x1:
controlView.aspectRatio = CGSize(width: 1, height: 1)
case .ratio_2x3:
controlView.aspectRatio = CGSize(width: 2, height: 3)
case .ratio_3x2:
controlView.aspectRatio = CGSize(width: 3, height: 2)
case .ratio_3x4:
controlView.aspectRatio = CGSize(width: 3, height: 4)
case .ratio_4x3:
controlView.aspectRatio = CGSize(width: 4, height: 3)
case .ratio_9x16:
controlView.aspectRatio = CGSize(width: 9, height: 16)
case .ratio_16x9:
controlView.aspectRatio = CGSize(width: 16, height: 9)
case .custom(let aspectRatio):
if aspectRatio.equalTo(.zero) && cropConfig.fixedRatio {
controlView.aspectRatio = imageView.image!.size
}else {
controlView.aspectRatio = aspectRatio
}
}
}
/// 检测是否原始宽高比
func checkOriginalRatio() {
isOriginalRatio = false
let aspectRatio = controlView.aspectRatio
if aspectRatio.equalTo(.zero) {
isOriginalRatio = true
}else {
if aspectRatio.width / aspectRatio.height == imageScale {
isOriginalRatio = true
}
}
}
/// 获取当前宽高比下裁剪框的位置大小
func getInitializationRatioMaskRect() -> CGRect {
let maxWidth = containerView.width - contentInsets.left - contentInsets.right
let maxHeight = containerView.height - contentInsets.top - contentInsets.bottom
var maskWidth = maxWidth
var maskHeight = maskWidth * (currentAspectRatio.height / currentAspectRatio.width)
if maskHeight > maxHeight {
maskWidth = maskWidth * (maxHeight / maskHeight)
maskHeight = maxHeight
}
let maskX = (maxWidth - maskWidth) * 0.5 + contentInsets.left
let maskY = (maxHeight - maskHeight) * 0.5 + contentInsets.top
return CGRect(x: maskX, y: maskY, width: maskWidth, height: maskHeight)
}
/// 获取初始缩放比例
func getInitialZoomScale() -> CGFloat {
let maxWidth = containerView.width - contentInsets.left - contentInsets.right
let maxHeight = containerView.height - contentInsets.top - contentInsets.bottom
var imageWidth: CGFloat
var imageHeight: CGFloat
switch getImageOrientation() {
case .up, .down:
imageWidth = maxWidth
imageHeight = imageWidth / imageScale
if imageHeight > maxHeight {
imageHeight = maxHeight
imageWidth = imageHeight * imageScale
}
if !isOriginalRatio {
let maskRect = getInitializationRatioMaskRect()
if imageHeight < maskRect.height {
imageWidth = imageWidth * (maskRect.height / imageHeight)
}
if imageWidth < maskRect.width {
imageWidth = maskRect.width
}
}
case .left, .right:
imageHeight = maxWidth
imageWidth = imageHeight * imageScale
if imageWidth > maxHeight {
imageWidth = maxHeight
imageHeight = imageWidth / imageScale
}
if !isOriginalRatio {
let maskRect = getInitializationRatioMaskRect()
if imageWidth < maskRect.height {
imageHeight = imageHeight * (maskRect.height / imageWidth)
}
if imageHeight < maskRect.width {
imageHeight = maskRect.width
}
imageWidth = imageHeight * imageScale
}
}
let minimumZoomScale = imageWidth / baseImageSize.width
return minimumZoomScale
}
/// 获取imageView初始位置大小
func getImageViewFrame() -> CGRect {
let maxWidth = containerView.width
let maxHeight = containerView.height
let imageWidth = maxWidth
let imageHeight = imageWidth / imageScale
var imageX: CGFloat = 0
var imageY: CGFloat = 0
if imageHeight < maxHeight {
imageY = (maxHeight - imageHeight) * 0.5
}
if imageWidth < maxWidth {
imageX = (maxWidth - imageWidth) * 0.5
}
return CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
}
/// 更新imageView位置大小
func updateImageViewFrame(_ imageFrame: CGRect) {
imageView.size = imageFrame.size
baseImageSize = imageView.size
scrollView.contentSize = imageView.size
if imageView.height < containerView.height {
let top = (containerView.height - imageView.height) * 0.5
let left = (containerView.width - imageView.width) * 0.5
scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
}
}
/// 更新边距
func updateContentInsets(_ isCropTime: Bool = false) {
if UIDevice.isPortrait {
contentInsets = UIEdgeInsets(
top: isCropTime ? 10 + UIDevice.topMargin : 20 + UIDevice.generalStatusBarHeight,
left: 30 + UIDevice.leftMargin,
bottom: isCropTime ? 155 + UIDevice.bottomMargin : 125 + UIDevice.bottomMargin,
right: 30 + UIDevice.rightMargin
)
}else {
contentInsets = UIEdgeInsets(
top: isCropTime ? 10 + UIDevice.topMargin : 20,
left: 30 + UIDevice.leftMargin,
bottom: isCropTime ? 160 + UIDevice.bottomMargin : 125 + UIDevice.bottomMargin,
right: 30 + UIDevice.rightMargin
)
}
}
/// 屏幕旋转时需要还原到初始配置
func updateBaseConfig() {
updateContentInsets()
scrollView.contentInset = .zero
updateImageViewFrame(getImageViewFrame())
/// 手势最大范围
let maxControlRect = CGRect(
x: contentInsets.left,
y: contentInsets.top,
width: containerView.width - contentInsets.left - contentInsets.right,
height: containerView.height - contentInsets.top - contentInsets.bottom
)
controlView.maxImageresizerFrame = maxControlRect
}
func setViewFrame(_ frame: CGRect) {
containerView.frame = frame
maskBgView.frame = containerView.bounds
maskLinesView.frame = containerView.bounds
scrollView.frame = containerView.bounds
}
func getEditedData(
_ filterImageURL: URL?
) -> PhotoEditData {
let brushData = imageView.drawView.getBrushData()
let rect = maskBgView.convert(controlView.frame, to: imageView)
let offsetScale = CGPoint(x: rect.minX / baseImageSize.width, y: rect.minY / baseImageSize.height)
var cropData: PhotoEditCropData?
if canReset() {
cropData = .init(
cropSize: cropSize,
isRoundCrop: layer.cornerRadius > 0 ? cropConfig.isRoundCrop : false,
zoomScale: oldZoomScale,
contentInset: oldContentInset,
offsetScale: offsetScale,
minimumZoomScale: oldMinimumZoomScale,
maximumZoomScale: oldMaximumZoomScale,
maskRect: oldMaskRect,
angle: oldAngle,
transform: oldTransform,
mirrorType: oldMirrorType
)
}
let mosaicData = imageView.mosaicView.getMosaicData()
let stickerData = imageView.stickerView.stickerData()
let editedData = PhotoEditData(
isPortrait: UIDevice.isPortrait,
cropData: cropData,
brushData: brushData,
hasFilter: hasFilter,
filterImageURL: filterImageURL,
mosaicData: mosaicData,
stickerData: stickerData
)
return editedData
}
func getVideoEditedData() -> VideoEditedCropSize {
let brushData = imageView.drawView.getBrushData()
let rect = maskBgView.convert(controlView.frame, to: imageView)
let offsetScale = CGPoint(x: rect.minX / baseImageSize.width, y: rect.minY / baseImageSize.height)
var cropData: PhotoEditCropData?
if canReset() {
cropData = .init(
cropSize: cropSize,
isRoundCrop: layer.cornerRadius > 0 ? cropConfig.isRoundCrop : false,
zoomScale: oldZoomScale,
contentInset: oldContentInset,
offsetScale: offsetScale,
minimumZoomScale: oldMinimumZoomScale,
maximumZoomScale: oldMaximumZoomScale,
maskRect: oldMaskRect,
angle: oldAngle,
transform: oldTransform,
mirrorType: oldMirrorType
)
}
let stickerData = imageView.stickerView.stickerData()
return .init(
isPortrait: UIDevice.isPortrait,
cropData: cropData,
brushData: brushData,
stickerData: stickerData,
filter: videoFilter
)
}
}
| mit | 789ad92daa662f2766a8221fa1bbbc5f | 38.061584 | 111 | 0.604354 | 5.308888 | false | false | false | false |
wagnersouz4/replay | Replay/Replay/Source/ViewControllers/Movies/Details/MovieDetailsViewController.swift | 1 | 2056 | //
// MovieDetailsViewController.swift
// Replay
//
// Created by Wagner Souza on 10/04/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import UIKit
class MovieDetailsViewController: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
var movieId: Int!
private var movie: Movie!
private var tableDelegateDataSource: MovieDetailsTableDelegateDataSource?
override func viewDidLoad() {
configureUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupTableView()
loadDetails()
}
private func configureUI() {
automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = .background
tableView.backgroundColor = .background
tableView.estimatedRowHeight = GridHelper(view).landscapeLayout.tableViewHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
private func setupTableView() {
let titleSubtitleNib = TitleSubTitleTableViewCell.nib
tableView.register(titleSubtitleNib, forCellReuseIdentifier: TitleSubTitleTableViewCell.identifier)
let titleTextNib = TitleTextTableViewCell.nib
tableView.register(titleTextNib, forCellReuseIdentifier: TitleTextTableViewCell.identifier)
tableDelegateDataSource = MovieDetailsTableDelegateDataSource(view: view)
tableView.dataSource = tableDelegateDataSource
tableView.delegate = tableDelegateDataSource
}
private func loadDetails() {
spinner.startAnimating()
Networking.loadMovie(id: movieId) { [weak self] movie in
if let movie = movie {
self?.movie = movie
self?.showContent()
} else {
print("Could not load movie Details")
}
}
}
private func showContent() {
tableDelegateDataSource?.setMovie(movie)
tableView.reloadData()
spinner.stopAnimating()
}
}
| mit | a877f5c55932de412264ecbb758502f1 | 29.220588 | 107 | 0.684185 | 5.692521 | false | false | false | false |
br1sk/brisk-ios | Pods/Sonar/Sources/Sonar/APIs/SonarError.swift | 1 | 1180 | import Alamofire
import Foundation
/// Represents an error on the communication and/or response parsing.
public struct SonarError: Error {
/// The message that represents the error condition.
public let message: String
/// Used to catch the things we can't gracefully fail.
static let unknownError = SonarError(message: "Unknown error")
/// Used when the token expires.
static let authenticationError = SonarError(message: "Unauthorized, perhaps you have the wrong password")
init(message: String) {
self.message = message
}
/// Factory to create a `SonarError` based on a `Response`.
///
/// - parameter response: The HTTP resposne that is known to be failed.
///
/// - returns: The error representing the problem.
static func from<T>(_ response: DataResponse<T>) -> SonarError {
if response.response?.statusCode == 401 {
return .authenticationError
}
switch response.result {
case .failure(let error as NSError):
return SonarError(message: error.localizedDescription)
default:
return .unknownError
}
}
}
| mit | e93d9737dfd1cecaa9b1c87512fc98d1 | 31.777778 | 109 | 0.649153 | 4.978903 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.ActiveIdentifier.swift | 1 | 2075 | import Foundation
public extension AnyCharacteristic {
static func activeIdentifier(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Active Identifier",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = 0,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.activeIdentifier(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func activeIdentifier(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Active Identifier",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = 0,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt32> {
GenericCharacteristic<UInt32>(
type: .activeIdentifier,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 7b4d666cf21c29d42453e376b79c3e3d | 33.016393 | 75 | 0.581205 | 5.375648 | false | false | false | false |
mtonio91/valio | Valio/SectionHeaderView.swift | 1 | 1439 | //
// SectionHeaderView.swift
// Valio
//
// Created by Sam Soffes on 6/6/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
import UIKit
class SectionHeaderView: UIVisualEffectView {
let titleLabel: UILabel = {
let label = UILabel()
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont(name: "Avenir", size: 18)
label.textColor = UIColor(red: 0.514, green: 0.525, blue: 0.541, alpha: 1)
return label
}()
let lineView: UIView = {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.backgroundColor = UIColor(red: 0.906, green: 0.914, blue: 0.918, alpha: 1)
return view
}()
init(effect: UIVisualEffect) {
super.init(effect: UIBlurEffect(style: .Light))
contentView.addSubview(titleLabel)
contentView.addSubview(lineView)
let views = [
"titleLabel": titleLabel,
"lineView": lineView
]
let metrics = [
"verticalMargin": 8
]
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[titleLabel]|", options: nil, metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(verticalMargin)-[titleLabel]-(verticalMargin)-[lineView(1)]|", options: nil, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[lineView]|", options: nil, metrics: metrics, views: views))
}
}
| mit | bc1d74a954b1cfdb55ecd8ec9555cf9b | 30.282609 | 191 | 0.720639 | 4.042135 | false | false | false | false |
Bouke/HAP | Sources/HAP/Utils/Data+Extensions.swift | 1 | 791 | import Foundation
// Removed in Xcode 8 beta 3
func + (lhs: Data, rhs: Data) -> Data {
var result = lhs
result.append(rhs)
return result
}
extension Data {
init?(hex: String) {
var result = [UInt8]()
var from = hex.startIndex
while from < hex.endIndex {
guard let to = hex.index(from, offsetBy: 2, limitedBy: hex.endIndex) else {
return nil
}
guard let num = UInt8(hex[from..<to], radix: 16) else {
return nil
}
result.append(num)
from = to
}
self = Data(result)
}
}
extension RandomAccessCollection where Iterator.Element == UInt8 {
var hex: String {
self.reduce("") { $0 + String(format: "%02x", $1) }
}
}
| mit | 15c7f0254b650496f118f64ed3619824 | 23.71875 | 87 | 0.525917 | 3.955 | false | false | false | false |
eugeneego/utilities-ios | Sources/Network/Transformers/Light/EnumLightTransformer.swift | 1 | 1990 | //
// EnumTransformer
// Legacy
//
// Copyright (c) 2015 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
public struct EnumCastLightTransformer<Enum: RawRepresentable>: LightTransformer {
public typealias T = Enum
public init() {}
public func from(any value: Any?) -> T? {
(value as? T.RawValue).flatMap(T.init)
}
public func to(any value: T?) -> Any? {
value?.rawValue
}
}
public struct EnumLightTransformer<Enum: RawRepresentable, RawTransformer: LightTransformer>: LightTransformer
where RawTransformer.T == Enum.RawValue {
public typealias T = Enum
public let transformer: RawTransformer
public init(transformer: RawTransformer) {
self.transformer = transformer
}
public func from(any value: Any?) -> T? {
transformer.from(any: value).flatMap(T.init)
}
public func to(any value: T?) -> Any? {
transformer.to(any: value?.rawValue)
}
}
public struct DictionaryEnumLightTransformer<Enum: Hashable, ValueTransformer: LightTransformer>: LightTransformer
where ValueTransformer.T: Hashable {
public typealias T = Enum
public typealias Value = ValueTransformer.T
public let transformer: ValueTransformer
public let enumValueDictionary: [Enum: Value]
public let valueEnumDictionary: [Value: Enum]
public init(transformer: ValueTransformer, dictionary: [Enum: Value]) {
self.transformer = transformer
enumValueDictionary = dictionary
valueEnumDictionary = dictionary.reduce([:]) { result, keyValue in
var result = result
result[keyValue.1] = keyValue.0
return result
}
}
public func from(any value: Any?) -> T? {
transformer.from(any: value).flatMap { valueEnumDictionary[$0] }
}
public func to(any value: T?) -> Any? {
value.flatMap { enumValueDictionary[$0] }.flatMap(transformer.to(any:))
}
}
| mit | 6283d603f5292a83e05f788d86da15bc | 27.428571 | 114 | 0.664322 | 4.481982 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Me/App Settings/DebugMenuViewController.swift | 1 | 9799 | import UIKit
import AutomatticTracks
import SwiftUI
class DebugMenuViewController: UITableViewController {
private var blogService: BlogService {
let context = ContextManager.sharedInstance().mainContext
return BlogService(managedObjectContext: context)
}
fileprivate var handler: ImmuTableViewHandler!
override init(style: UITableView.Style) {
super.init(style: style)
title = NSLocalizedString("Debug Settings", comment: "Debug settings title")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required convenience init() {
self.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
ImmuTable.registerRows([
SwitchWithSubtitleRow.self,
ButtonRow.self,
EditableTextRow.self
], tableView: tableView)
handler = ImmuTableViewHandler(takeOver: self)
reloadViewModel()
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
}
private func reloadViewModel() {
let cases = FeatureFlag.allCases.filter({ $0.canOverride })
let rows: [ImmuTableRow] = cases.map({ makeRow(for: $0) })
handler.viewModel = ImmuTable(sections: [
ImmuTableSection(headerText: Strings.featureFlags, rows: rows),
ImmuTableSection(headerText: Strings.tools, rows: toolsRows),
ImmuTableSection(headerText: Strings.crashLogging, rows: crashLoggingRows),
ImmuTableSection(headerText: Strings.reader, rows: readerRows),
])
}
private func makeRow(for flag: FeatureFlag) -> ImmuTableRow {
let store = FeatureFlagOverrideStore()
let overridden: String? = store.isOverridden(flag) ? Strings.overridden : nil
return SwitchWithSubtitleRow(title: String(describing: flag), value: flag.enabled, subtitle: overridden, onChange: { isOn in
try? store.override(flag, withValue: isOn)
self.reloadViewModel()
})
}
// MARK: Tools
private var toolsRows: [ImmuTableRow] {
var toolsRows = [
ButtonRow(title: Strings.quickStartForNewSiteRow, action: { [weak self] _ in
self?.displayBlogPickerForQuickStart(type: .newSite)
}),
ButtonRow(title: Strings.quickStartForExistingSiteRow, action: { [weak self] _ in
self?.displayBlogPickerForQuickStart(type: .existingSite)
}),
ButtonRow(title: Strings.sandboxStoreCookieSecretRow, action: { [weak self] _ in
self?.displayStoreSandboxSecretInserter()
}),
]
if Feature.enabled(.weeklyRoundup) {
toolsRows.append(ButtonRow(title: "Weekly Roundup", action: { [weak self] _ in
self?.displayWeeklyRoundupDebugTools()
}))
}
return toolsRows
}
// MARK: Crash Logging
private var crashLoggingRows: [ImmuTableRow] {
var rows: [ImmuTableRow] = [
ButtonRow(title: Strings.sendLogMessage, action: { _ in
WordPressAppDelegate.crashLogging?.logMessage("Debug Log Message \(UUID().uuidString)")
self.tableView.deselectSelectedRowWithAnimationAfterDelay(true)
}),
ButtonRow(title: Strings.sendTestCrash, action: { _ in
DDLogInfo("Initiating user-requested crash")
WordPressAppDelegate.crashLogging?.crash()
})
]
if let eventLogging = WordPressAppDelegate.eventLogging {
let tableViewController = EncryptedLogTableViewController(eventLogging: eventLogging)
let encryptedLoggingRow = ButtonRow(title: Strings.encryptedLogging) { _ in
self.navigationController?.pushViewController(tableViewController, animated: true)
}
rows.append(encryptedLoggingRow)
}
let alwaysSendLogsRow = SwitchWithSubtitleRow(title: Strings.alwaysSendLogs, value: UserSettings.userHasForcedCrashLoggingEnabled) { isOn in
UserSettings.userHasForcedCrashLoggingEnabled = isOn
}
rows.append(alwaysSendLogsRow)
return rows
}
private func displayBlogPickerForQuickStart(type: QuickStartType) {
let successHandler: BlogSelectorSuccessHandler = { [weak self] selectedObjectID in
guard let blog = self?.blogService.managedObjectContext.object(with: selectedObjectID) as? Blog else {
return
}
self?.dismiss(animated: true) { [weak self] in
self?.enableQuickStart(for: blog, type: type)
}
}
let selectorViewController = BlogSelectorViewController(selectedBlogObjectID: nil,
successHandler: successHandler,
dismissHandler: nil)
selectorViewController.displaysNavigationBarWhenSearching = WPDeviceIdentification.isiPad()
selectorViewController.dismissOnCancellation = true
selectorViewController.displaysOnlyDefaultAccountSites = true
let navigationController = UINavigationController(rootViewController: selectorViewController)
present(navigationController, animated: true)
}
private func displayStoreSandboxSecretInserter() {
let view = StoreSandboxSecretScreen(cookieJar: HTTPCookieStorage.shared)
let viewController = UIHostingController(rootView: view)
self.navigationController?.pushViewController(viewController, animated: true)
}
private func displayWeeklyRoundupDebugTools() {
let view = WeeklyRoundupDebugScreen()
let viewController = UIHostingController(rootView: view)
self.navigationController?.pushViewController(viewController, animated: true)
}
private func enableQuickStart(for blog: Blog, type: QuickStartType) {
QuickStartTourGuide.shared.setup(for: blog, type: type)
}
// MARK: Reader
private var readerRows: [ImmuTableRow] {
return [
EditableTextRow(title: Strings.readerCssTitle, value: ReaderCSS().customAddress ?? "") { row in
let textViewController = SettingsTextViewController(text: ReaderCSS().customAddress, placeholder: Strings.readerURLPlaceholder, hint: Strings.readerURLHint)
textViewController.title = Strings.readerCssTitle
textViewController.onAttributedValueChanged = { [weak self] url in
var readerCSS = ReaderCSS()
readerCSS.customAddress = url.string
self?.reloadViewModel()
}
self.navigationController?.pushViewController(textViewController, animated: true)
}
]
}
enum Strings {
static let overridden = NSLocalizedString("Overridden", comment: "Used to indicate a setting is overridden in debug builds of the app")
static let featureFlags = NSLocalizedString("Feature flags", comment: "Title of the Feature Flags screen used in debug builds of the app")
static let tools = NSLocalizedString("Tools", comment: "Title of the Tools section of the debug screen used in debug builds of the app")
static let sandboxStoreCookieSecretRow = NSLocalizedString("Use Sandbox Store", comment: "Title of a row displayed on the debug screen used to configure the sandbox store use in the App.")
static let quickStartForNewSiteRow = NSLocalizedString("Enable Quick Start for New Site", comment: "Title of a row displayed on the debug screen used in debug builds of the app")
static let quickStartForExistingSiteRow = NSLocalizedString("Enable Quick Start for Existing Site", comment: "Title of a row displayed on the debug screen used in debug builds of the app")
static let sendTestCrash = NSLocalizedString("Send Test Crash", comment: "Title of a row displayed on the debug screen used to crash the app and send a crash report to the crash logging provider to ensure everything is working correctly")
static let sendLogMessage = NSLocalizedString("Send Log Message", comment: "Title of a row displayed on the debug screen used to send a pretend error message to the crash logging provider to ensure everything is working correctly")
static let alwaysSendLogs = NSLocalizedString("Always Send Crash Logs", comment: "Title of a row displayed on the debug screen used to indicate whether crash logs should be forced to send, even if they otherwise wouldn't")
static let crashLogging = NSLocalizedString("Crash Logging", comment: "Title of a section on the debug screen that shows a list of actions related to crash logging")
static let encryptedLogging = NSLocalizedString("Encrypted Logs", comment: "Title of a row displayed on the debug screen used to display a screen that shows a list of encrypted logs")
static let reader = NSLocalizedString("Reader", comment: "Title of the Reader section of the debug screen used in debug builds of the app")
static let readerCssTitle = NSLocalizedString("Reader CSS URL", comment: "Title of the screen that allows the user to change the Reader CSS URL for debug builds")
static let readerURLPlaceholder = NSLocalizedString("Default URL", comment: "Placeholder for the reader CSS URL")
static let readerURLHint = NSLocalizedString("Add a custom CSS URL here to be loaded in Reader. If you're running Calypso locally this can be something like: http://192.168.15.23:3000/calypso/reader-mobile.css", comment: "Hint for the reader CSS URL field")
}
}
| gpl-2.0 | f9b9bec53d07dc49f332e6df2b71fb08 | 48.241206 | 265 | 0.68109 | 5.387026 | false | false | false | false |
CoderSLZeng/SLPageView | SLPageView设计/SLPageView/SLTitleStyle.swift | 1 | 1306 | //
// SLTitleStyle.swift
// SLPageView设计
//
// Created by Anthony on 2017/4/14.
// Copyright © 2017年 SLZeng. All rights reserved.
//
import UIKit
class SLTitleStyle {
/// 是否是滚动的Title
var isScrollEnable : Bool = false
/// 普通Title颜色
var normalColor : UIColor = UIColor(r: 0, g: 0, b: 0)
/// 选中Title颜色
var selectedColor : UIColor = UIColor(r: 255, g: 127, b: 0)
/// Title字体大小
var font : UIFont = UIFont.systemFont(ofSize: 14.0)
/// title的高度
var titleHeight : CGFloat = 44
/// 滚动Title的字体间距
var titleMargin : CGFloat = 20
/// 是否显示底部滚动条
var isShowBottomLine : Bool = false
/// 底部滚动条的高度
var bottomLineHeight : CGFloat = 2
/// 底部滚动条的颜色
var bottomLineColor : UIColor = .orange
/// 是否显示遮盖
var isShowCover : Bool = false
/// 遮盖背景颜色
var coverBgColor : UIColor = UIColor.lightGray
/// 文字&遮盖间隙
var coverMargin : CGFloat = 5
/// 遮盖的高度
var coverHeight : CGFloat = 25
/// 设置圆角大小
var coverRadius : CGFloat = 12
/// 是否进行缩放
var isNeedScale : Bool = false
var scaleRange : CGFloat = 1.2
}
| mit | 954a96b7c02e27466deb6246cf962bc8 | 22.395833 | 63 | 0.606411 | 3.84589 | false | false | false | false |
coodly/laughing-adventure | Source/Purchase/Storefront.swift | 1 | 5729 | /*
* Copyright 2016 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import StoreKit
public enum PurchaseResult {
case success
case cancelled
case failure
case deferred
case restored
case notAllowed
case restoreFailure
}
public protocol PurchaseMonitor: class {
func purchaseResult(_ result: PurchaseResult, for identifier: String)
}
public typealias ProductsResponse = ([SKProduct], [String]) -> ()
public class Storefront: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
private var requests = [SKProductsRequest: ProductsResponse]()
public weak var passiveMonitor: PurchaseMonitor?
public weak var activeMonitor: PurchaseMonitor?
override public init() {
super.init()
SKPaymentQueue.default().add(self)
}
public func retrieve(products: [String], completion: @escaping ProductsResponse) {
Logging.log("Retrieve products: \(products)")
let request = SKProductsRequest(productIdentifiers: Set(products))
request.delegate = self
requests[request] = completion
request.start()
}
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
Logging.log("Retrieved: \(response.products.count). Invalid \(response.invalidProductIdentifiers)")
guard let completion = requests.removeValue(forKey: request) else {
return
}
completion(response.products, response.invalidProductIdentifiers)
}
public func purchase(_ product: SKProduct) {
Logging.log("Purchase:\(product.productIdentifier)")
guard SKPaymentQueue.canMakePayments() else {
monitor()?.purchaseResult(.notAllowed, for: product.productIdentifier)
return
}
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
public func restore() {
Logging.log("restore purchases")
SKPaymentQueue.default().restoreCompletedTransactions()
}
private func monitor() -> PurchaseMonitor? {
return activeMonitor ?? passiveMonitor
}
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
Logging.log("updatedTransactions: \(transactions.count)")
for transaction in transactions {
var finishTransaction = false
defer {
if finishTransaction {
queue.finishTransaction(transaction)
}
}
let notifyMonitor = monitor()
let productIdentifier = transaction.payment.productIdentifier
if notifyMonitor == nil {
Logging.log("No monitor set")
}
Logging.log("Identifier: \(productIdentifier)")
switch transaction.transactionState {
// Transaction is being added to the server queue.
case .purchasing: Logging.log("Purchasing")
case .purchased: // Transaction is in queue, user has been charged. Client should complete the transaction.
Logging.log("Purchased")
notifyMonitor?.purchaseResult(.success, for: productIdentifier)
finishTransaction = true
case .failed: // Transaction was cancelled or failed before being added to the server queue.
Logging.log("Failed: \(transaction.error.debugDescription)")
finishTransaction = true
let cancelledCode = SKError.paymentCancelled.rawValue
if let error = transaction.error as NSError?, error.code == cancelledCode {
notifyMonitor?.purchaseResult(.cancelled, for: productIdentifier)
} else {
notifyMonitor?.purchaseResult(.failure, for: productIdentifier)
}
case .restored: // Transaction was restored from user's purchase history. Client should complete the transaction.
Logging.log("Restored")
finishTransaction = true
notifyMonitor?.purchaseResult(.restored, for: productIdentifier)
case .deferred: // The transaction is in the queue, but its final status is pending external action.
Logging.log("Deferred")
notifyMonitor?.purchaseResult(.cancelled, for: productIdentifier)
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
Logging.log("Restore completed")
monitor()?.purchaseResult(.restored, for: "")
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
Logging.log("Restore failed with error: \(error)")
let cancelledCode = SKError.paymentCancelled.rawValue
if let error = error as NSError?, error.code == cancelledCode {
monitor()?.purchaseResult(.cancelled, for: "")
} else {
monitor()?.purchaseResult(.restoreFailure, for: "")
}
}
}
| apache-2.0 | 8353e5188e542bda1dd4f86a3ae26ce3 | 39.062937 | 126 | 0.647059 | 5.734735 | false | false | false | false |
lorentey/Attabench | BenchmarkRunner/Dispatch Extensions.swift | 2 | 2387 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Foundation
extension DispatchData {
init(_ data: Data) {
// Data and DispatchData are toll-free bridged in Objective-C, but I don't think we can exploit this in Swift
self.init(bytes: UnsafeRawBufferPointer(start: (data as NSData).bytes, count: data.count))
}
}
extension DispatchIO {
enum Chunk<Payload> {
case record(Payload)
case endOfFile
case error(Int32)
}
/// Read variable-length records delimited by `delimiter`.
func readRecords(on queue: DispatchQueue, delimitedBy delimiter: UInt8, handler: @escaping (Chunk<Data>) -> Void) {
// FIXME This code is horrible
var pending = Data()
self.read(offset: 0, length: Int(bitPattern: SIZE_MAX), queue: queue) { done, data, err in
if var data = data {
// Find record boundaries and send complete records to handler (including delimiter).
while let index = data.index(of: delimiter) {
pending.append(contentsOf: data.subdata(in: 0 ..< index + 1))
handler(.record(pending))
pending = Data()
data = data.subdata(in: index + 1 ..< data.count)
}
pending.append(contentsOf: data)
}
if done {
// Send last partial record.
if !pending.isEmpty {
handler(.record(pending))
pending.removeAll()
}
handler(err != 0 ? .error(err) : .endOfFile)
}
}
}
func readUTF8Lines(on queue: DispatchQueue, handler: @escaping (Chunk<String>) -> Void) {
self.readRecords(on: queue, delimitedBy: 0x0A) { chunk in
switch chunk {
case .record(let data):
if let line = String(data: data, encoding: .utf8) {
// FIXME report decoding errors, don't just ignore them
handler(.record(line))
}
case .endOfFile:
handler(.endOfFile)
case .error(let err):
handler(.error(err))
}
}
}
}
| mit | 194f20b4e7e222c6dfaefcc6e8052be4 | 37.451613 | 119 | 0.551594 | 4.65625 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/extension/UITabBarController+extension.swift | 1 | 1742 | //
// UITabBarController+extension.swift
// swift4.2Demo
//
// Created by baiqiang on 2018/11/13.
// Copyright © 2018年 baiqiang. All rights reserved.
//
import UIKit
public let kVcName: String = "kVcName"
public let kVcTitle: String = "kVcTitle"
public let kSelectImg: String = "kSelectImg"
public let kNormalImg: String = "kNormalImg"
extension UITabBarController {
/// 快捷创建tabbarVc方式
///
/// - Parameter arr: 数组嵌套字典 vcName: selectImg: normalImg:
/// - Returns: 返回tabbarVc
public class func createVc(arr: [[String: String]], needNav: Bool = true) -> UITabBarController {
let tabbarVc = UITabBarController()
if arr.count == 0 {
return tabbarVc
}
var vcArr:[UIViewController] = []
for vcInfo in arr {
guard let vcName = vcInfo[kVcName], let selectImg = vcInfo[kSelectImg], let normalImg = vcInfo[kNormalImg], let title = vcInfo[kVcTitle] else {
continue
}
if let vc = BQTool.loadVc(vcName: vcName) {
let tabbarItem = UITabBarItem(title: title, image: UIImage.orginImg(name: normalImg), selectedImage: UIImage.orginImg(name: selectImg))
vc.tabBarItem = tabbarItem
vc.title = title
if needNav {
let navVc = UINavigationController(rootViewController: vc)
vcArr.append(navVc)
} else {
vcArr.append(vc)
}
}
}
tabbarVc.viewControllers = vcArr
return tabbarVc
}
}
| apache-2.0 | 3e8daae5d40244873af89d083a24fdf7 | 28.5 | 155 | 0.548217 | 4.636856 | false | false | false | false |
rustedivan/tapmap | tapmap/App/RuntimeWorld.swift | 1 | 2676 | //
// RuntimeWorld.swift
// tapmap
//
// Created by Ivan Milles on 2020-04-18.
// Copyright © 2020 Wildbrain. All rights reserved.
//
import Foundation
typealias GeoContinentMap = [RegionHash : GeoContinent]
typealias GeoCountryMap = [RegionHash : GeoCountry]
typealias GeoProvinceMap = [RegionHash : GeoProvince]
class RuntimeWorld {
// Complete set
let allContinents: GeoContinentMap
let allCountries: GeoCountryMap
let allProvinces: GeoProvinceMap
// Closed set
var availableContinents: GeoContinentMap = [:]
var availableCountries: GeoCountryMap = [:]
var availableProvinces: GeoProvinceMap = [:]
// Visible set
var visibleContinents: GeoContinentMap = [:]
var visibleCountries: GeoCountryMap = [:]
var visibleProvinces: GeoProvinceMap = [:]
// Lookups and mappings
let continentForRegion: GeoContinentMap
let geoWorld: GeoWorld
init(withGeoWorld world: GeoWorld) {
geoWorld = world
let continentList = geoWorld.children
allContinents = Dictionary(uniqueKeysWithValues: continentList.map { ($0.geographyId.hashed, $0)})
let countryList = continentList.flatMap { $0.children }
allCountries = Dictionary(uniqueKeysWithValues: countryList.map { ($0.geographyId.hashed, $0) })
let provinceList = countryList.flatMap { $0.children }
allProvinces = Dictionary(uniqueKeysWithValues: provinceList.map { ($0.geographyId.hashed, $0) })
// Note which continent a region belongs to (including the continents themselves)
var regionHashToContinentMap: GeoContinentMap = [:]
for continent in continentList {
let countries = continent.children
let countryHashes = countries.map { $0.geographyId.hashed }
let provinces = countries.flatMap { $0.children }
let provinceHashes = provinces.map { $0.geographyId.hashed }
let allContinentHashes = [continent.geographyId.hashed] + countryHashes + provinceHashes
for h in allContinentHashes {
regionHashToContinentMap[h] = continent
}
}
continentForRegion = regionHashToContinentMap
}
}
extension RuntimeWorld: UIStateDelegate, UserStateDelegate {
func availabilityDidChange(availableSet: Set<RegionHash>) {
availableContinents = allContinents.filter { availableSet.contains($0.key) }
availableCountries = allCountries.filter { availableSet.contains($0.key) }
availableProvinces = allProvinces.filter { availableSet.contains($0.key) }
}
func visibilityDidChange(visibleSet: Set<RegionHash>) {
visibleContinents = availableContinents.filter { visibleSet.contains($0.key) }
visibleCountries = availableCountries.filter { visibleSet.contains($0.key) }
visibleProvinces = availableProvinces.filter { visibleSet.contains($0.key) }
}
}
| mit | a536bdad9e0986e2c2e14db9b17cab15 | 33.74026 | 100 | 0.758131 | 4.034691 | false | false | false | false |
jpchmura/JPCDataSourceController | JPCDataSourceControllerExamples/JPCDataSourceControllerExamples/AppDelegate.swift | 1 | 2619 | //
// AppDelegate.swift
// JPCDataSourceControllerExamples
//
// Created by Jon Chmura on 3/31/15.
// Copyright (c) 2015 Jon Chmura. All rights reserved.
//
import UIKit
import MagicalRecord
func isRunningTests() -> Bool {
let environment = NSProcessInfo.processInfo().environment
if let injectBundle = environment["XCInjectBundle"] {
return NSURL(fileURLWithPath: injectBundle).pathExtension == "xctest"
}
return false
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if isRunningTests() {
self.window?.rootViewController = UIViewController()
return true
}
// For CoreDataExample
MagicalRecord.setupCoreDataStackWithInMemoryStore()
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:.
}
}
| mit | 9b555f24467bbadc3b45b496dd11db30 | 40.571429 | 285 | 0.733486 | 5.57234 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/RMBTThroughputHistory.swift | 1 | 5814 | /*****************************************************************************************************
* Copyright 2013 appscape gmbh
* Copyright 2014-2016 SPECURE GmbH
*
* 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
///
open class RMBTThroughputHistory: CustomStringConvertible {
/// Total bytes/time transferred so far. Equal to sum of all reported lengths / largest reported timestamp.
open var totalThroughput = RMBTThroughput(length: 0, startNanos: 0, endNanos: 0)
/// Time axis is split into periods of this duration. Each period has a throughput object associated with it.
/// Reported transfers are then proportionally divided accross the throughputs it spans over.
open var resolutionNanos: UInt64
/// Array of throughput objects for each period
open var periods: [RMBTThroughput] = []
/// Returns the index of the last period which is complete, meaning that no reports can change its value.
/// -1 if not even the first period is complete yet
open var lastFrozenPeriodIndex: Int = -1
/// See freeze
open var isFrozen: Bool = false
//
///
public init(resolutionNanos: UInt64) {
self.resolutionNanos = resolutionNanos
}
///
func addLength(_ length: UInt64, atNanos timestampNanos: UInt64) {
assert(!isFrozen, "Tried adding to frozen history")
totalThroughput.length += length
totalThroughput.endNanos = max(totalThroughput.endNanos, timestampNanos)
if periods.count == 0 {
// Create first period
periods.append(RMBTThroughput(length: 0, startNanos: 0, endNanos: 0))
}
var leftoverLength = length
let startPeriodIndex = periods.count - 1
var endPeriodIndex = timestampNanos / resolutionNanos
if timestampNanos - (resolutionNanos * endPeriodIndex) == 0 {
endPeriodIndex -= 1 // Boundary condition
}
assert(startPeriodIndex > lastFrozenPeriodIndex, "Start period \(startPeriodIndex) < \(lastFrozenPeriodIndex)")
assert(Int(endPeriodIndex) > lastFrozenPeriodIndex, "End period \(endPeriodIndex) < \(lastFrozenPeriodIndex)")
//
let startPeriod = periods[startPeriodIndex]
let transferNanos = timestampNanos - startPeriod.endNanos
assert(transferNanos > 0, "Transfer happened before last reported transfer?")
let lengthPerPeriod = UInt64(Double(length) * (Double(resolutionNanos) / Double(transferNanos))) // TODO: improve
if startPeriodIndex == Int(endPeriodIndex) {
// Just add to the start period
startPeriod.length += length
startPeriod.endNanos = timestampNanos
} else {
// Attribute part to the start period, except if we started on the boundary
if startPeriod.endNanos < (UInt64(startPeriodIndex) + 1) * resolutionNanos {
// TODO: improve calculation
let startLength = UInt64(Double(length) * (Double(resolutionNanos - (startPeriod.endNanos % resolutionNanos)) / Double(transferNanos)))
startPeriod.length += startLength
startPeriod.endNanos = (UInt64(startPeriodIndex) + 1) * resolutionNanos
leftoverLength -= startLength
}
// Create periods in between
for i: UInt64 in (UInt64(startPeriodIndex) + 1) ..< endPeriodIndex {
leftoverLength -= lengthPerPeriod
periods.append(RMBTThroughput(length: lengthPerPeriod, startNanos: i * resolutionNanos, endNanos: (i + 1) * resolutionNanos))
}
// Create new end period and add the rest of bytes to it
periods.append(RMBTThroughput(length: leftoverLength, startNanos: endPeriodIndex * resolutionNanos, endNanos: timestampNanos))
}
lastFrozenPeriodIndex = Int(endPeriodIndex) - 1
}
/// Marks history as frozen, also marking all periods as passed, not allowing futher reports.
func freeze() {
isFrozen = true
lastFrozenPeriodIndex = periods.count - 1
}
/// Concatenetes last count periods into one, or nop if there are less than two periods in the history.
func squashLastPeriods(_ count: Int) {
assert(count >= 1, "Count must be >= 1")
assert(isFrozen, "History should be frozen before squashing")
if periods.count < count {
return
}
let index = periods.count - count - 1
if index < 0 {
return
}
let finalTput = periods[index]
for _ in 0 ..< count {
if let t = periods.last {
finalTput.endNanos = max(t.endNanos, finalTput.endNanos)
finalTput.length += t.length
periods.removeLast()
}
}
}
///
func log() {
Log.logger.debug("Throughputs:")
for t in periods {
Log.logger.debug("- \(t.description)")
}
Log.logger.debug("Total: \(self.totalThroughput.description)")
}
///
open var description: String {
return "total = \(totalThroughput), entries = \(periods.description)"
}
}
| apache-2.0 | 5918e2229fe75d5c65488ff04c4bf7ac | 36.269231 | 151 | 0.622979 | 5.029412 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/views/trip overview/TKUIAttributionCell.swift | 1 | 1406 | //
// TKUIAttributionCell.swift
// TripKitUI
//
// Created by Adrian Schoenig on 3/4/17.
// Copyright © 2017 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
class TKUIAttributionCell: UITableViewCell {
@IBOutlet weak var titleTextView: UITextView!
@IBOutlet weak var bodyTextView: UITextView!
static let reuseIdentifier = "TKUIAttributionCell"
static let nib = UINib(nibName: "TKUIAttributionCell", bundle: Bundle(for: TKUIAttributionCell.self))
var attribution: TKAPI.DataAttribution? {
didSet { updateUI() }
}
override func awakeFromNib() {
super.awakeFromNib()
tintColor = .tkAppTintColor
backgroundColor = .tkBackgroundTile
titleTextView.font = TKStyleManager.customFont(forTextStyle: .headline)
titleTextView.textColor = .tkLabelPrimary
titleTextView.backgroundColor = .clear
bodyTextView.font = TKStyleManager.customFont(forTextStyle: .subheadline)
bodyTextView.textColor = .tkLabelPrimary
bodyTextView.backgroundColor = .clear
}
private func updateUI() {
guard let attribution = self.attribution else { return }
titleTextView.text = attribution.provider.name
bodyTextView.text = attribution.disclaimer
bodyTextView.isHidden = (attribution.disclaimer?.isEmpty ?? true)
accessoryType = (attribution.provider.website != nil) ? .detailButton : .none
}
}
| apache-2.0 | 83888aeefc09390eff6c8d663c478ef7 | 27.1 | 103 | 0.725267 | 4.861592 | false | false | false | false |
superman-coder/pakr | pakr/pakr/UserInterface/DetailParking/DetailParkingController.swift | 1 | 12914 | //
// DetailParkingController.swift
// pakr
//
// Created by nguyen trung quang on 4/9/16.
// Copyright © 2016 Pakr. All rights reserved.
//
import UIKit
import AFNetworking
import MapKit
class DetailParkingController: UIViewController {
var topic: Topic!
var parking : Parking!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var fromBusinessView: UIControl!
@IBOutlet weak var addressView: UIControl!
@IBOutlet weak var photoCollectionView: UICollectionView!
@IBOutlet weak var infoTableView: UITableView!
@IBOutlet weak var commentsTableView: UITableView!
@IBOutlet weak var mapkit: MKMapView!
@IBOutlet weak var btnBookMark: UIButton!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var infoTableHeight: NSLayoutConstraint!
@IBOutlet weak var commentsTableHeight: NSLayoutConstraint!
@IBOutlet weak var imageChitBottom: UIImageView!
@IBOutlet weak var imgParkingTop: UIImageView!
@IBOutlet weak var imgPackingOpaciti: UIImageView!
@IBOutlet weak var lblAddress: UILabel!
@IBOutlet weak var lblBusinessReview: UILabel!
@IBOutlet weak var rating: RatingControl!
@IBOutlet weak var hoursToday: UILabel!
@IBOutlet weak var numReviews: UILabel!
var arrInfo: NSArray?
var arrInfoImage: NSArray?
var arrCommentUserName: NSArray?
var arrCommentsImage: NSArray?
var arrCommentsDicriptions: NSArray?
var arrUrlImageParking: NSArray?
override func viewDidLoad() {
super.viewDidLoad()
infoTableView.scrollEnabled = false
commentsTableView.scrollEnabled = false
//
self.navigationController?.navigationBar.translucent = false
if (self.respondsToSelector(Selector("edgesForExtendedLayout"))) {
self.edgesForExtendedLayout = UIRectEdge.None
}
//
let nib = UINib(nibName: "PhotosCollectionViewCell", bundle: nil)
photoCollectionView.registerNib(nib, forCellWithReuseIdentifier: "PhotosCollectionViewCell")
let nibComment = UINib(nibName: "CommentTableViewCell", bundle: nil)
commentsTableView.registerNib(nibComment, forCellReuseIdentifier: "CommentTableViewCell")
setData()
setBookMark()
self.title = parking.parkingName
setShadow()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private Method
func setBookMark(){
let user = WebServiceFactory.getAuthService().getLoginUser()
WebServiceFactory.getAddressService().checkIsBookMarkTopicByUser((user?.objectId)!, topicId: topic.postId!) { (isBookMark) in
dispatch_async(dispatch_get_main_queue(), {
self.btnBookMark.selected = isBookMark
self.btnBookMark.enabled = true
})
}
}
func setShadow(){
LayoutUtils.dropShadowView(photoCollectionView)
LayoutUtils.dropShadowView(infoTableView)
LayoutUtils.dropShadowView(commentsTableView)
LayoutUtils.dropShadowView(mapkit)
LayoutUtils.dropShadowView(imgParkingTop)
LayoutUtils.dropShadowView(imageChitBottom)
LayoutUtils.dropShadowView(addressView)
LayoutUtils.dropShadowView(fromBusinessView)
}
func setData(){
btnBookMark.enabled = false
parking = topic.parking
arrUrlImageParking = parking.imageUrl
lblAddress.text = parking.addressName
lblBusinessReview.text = parking.business.businessDescription
var dayOfWeek = getDayOfWeek()
if dayOfWeek == 1 {
dayOfWeek = 6
}else{
dayOfWeek = dayOfWeek - 2
}
if parking.schedule.count >= 6 {
let closeTime = "\(parking.schedule[dayOfWeek].closeTime)"
let openTime = "\(parking.schedule[dayOfWeek].openTime)"
hoursToday.text = "Hours ToDay: \(openTime) - \(closeTime)"
}
rating.rating = topic.rating
numReviews.text = " "
WebServiceFactory.getAddressService().getAllCommentsByTopic(topic.postId!, success: { (comments) in
self.numReviews.text = " \(comments.count) Reviews"
if comments.count > 0 {
var rating = 0
for comment in comments {
rating = comment.rating + rating
}
self.rating.rating = rating / comments.count
}
}) { (error) in
self.numReviews.text = "0 Review"
}
if parking.imageUrl != nil {
let url = NSURL(string:(parking.imageUrl?.first)!)!
imgParkingTop.setImageWithURL(url, placeholderImage: nil)
}
arrInfo = ["Direction","Call","More Info"]
arrInfoImage = ["direction","call","more"]
infoTableView.reloadData()
centerMapOnLocation()
}
func getDayOfWeek()->Int {
let today = NSDate()
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: today)
let weekDay = myComponents.weekday
return weekDay
}
func centerMapOnLocation(){
let location = CLLocation(latitude: parking.coordinate.latitude, longitude: parking.coordinate.longitude)
let regionRadius: CLLocationDistance = 1000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapkit.setRegion(coordinateRegion, animated: true)
}
func callParkingOwn(){
let busPhone = self.parking.business.telephone
if let url = NSURL(string: "tel://\(busPhone)") {
UIApplication.sharedApplication().openURL(url)
}
}
func showMoreInfo(){
let info = MoreInfoViewController()
info.parking = parking
self.navigationController?.pushViewController(info, animated: true)
}
func openMapForPlace() {
let latitute:CLLocationDegrees = parking.coordinate.latitude
let longitute:CLLocationDegrees = parking.coordinate.longitude
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitute, longitute)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = parking.parkingName
mapItem.openInMapsWithLaunchOptions(options)
}
func startReview(){
let reviewCOntroler = ReviewViewController()
reviewCOntroler.topic = topic
self.navigationController?.pushViewController(reviewCOntroler, animated: true)
}
func showAllComments(){
let allCommentsViewController = ShowAllCommentTableViewController()
allCommentsViewController.topic = topic
self.navigationController?.pushViewController(allCommentsViewController, animated: true)
}
// MARK: - IBAction
@IBAction func didSelectMapView(sender: AnyObject) {
let mapDetailViewController = MapDetailViewController()
mapDetailViewController.initialLocation = CLLocation(latitude: parking.coordinate.latitude, longitude: parking.coordinate.longitude)
self.navigationController?.pushViewController(mapDetailViewController, animated: true)
}
@IBAction func showBusinessReview(sender: AnyObject) {
}
@IBAction func showAddressDetail(sender: AnyObject) {
didSelectMapView(sender)
}
@IBAction func bookMarkAction(sender: AnyObject) {
if btnBookMark.selected {
return
}else{
self.btnBookMark.selected = true
let currentUser = WebServiceFactory.getAuthService().getLoginUser()
let bookMark = Bookmark(userId: currentUser?.objectId, topicId: topic.postId, topic: topic)
WebServiceFactory.getAddressService().postBookMark(bookMark) { (bookMark, error) in
if error == nil {
let userInfo : [String:Bookmark] = ["bookMark": bookMark!]
NSNotificationCenter.defaultCenter().postNotificationName(EventSignal.UpLoadBookMarkDone, object: nil, userInfo: userInfo)
}else{
self.btnBookMark.selected = false
}
}
}
}
}
// MARK: - Extension
//Animation in top when Scroll
extension DetailParkingController: UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = abs(scrollView.contentOffset.y)
if offset > 0 {
imgPackingOpaciti.alpha = 0.8 - offset/100
}else{
imgPackingOpaciti.alpha = 0.8
}
}
}
extension DetailParkingController: UITableViewDataSource, UITableViewDelegate{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView.isEqual(infoTableView) {
return (arrInfo?.count)!
}else{
var row = arrCommentUserName?.count ?? 0
row += 5
return row
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView.isEqual(infoTableView) {
let cell = UITableViewCell()
cell.imageView?.image = UIImage(named: arrInfoImage![indexPath.row] as! String)
cell.textLabel?.text = arrInfo![indexPath.row] as? String
cell.accessoryType = .DisclosureIndicator
return cell
}else{
if indexPath.row == 0 {
let cell = CommentTableViewCell.initCommentCellFromNib()
let authenService = WebServiceFactory.getAuthService()
let user = authenService.getLoginUser()
if user != nil{
cell.disPlay((user?.avatarUrl)!, name: (user?.name)!)
}
return cell
}else{
let cell = CommentTableViewCell.initSeeAllComment()
return cell
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(tableView.isEqual(commentsTableView)){
if indexPath.row == 0 {
return 60
}else{
return 40
}
}else{
return 45
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
}
// - Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView .deselectRowAtIndexPath(indexPath, animated: false)
if tableView.isEqual(infoTableView) {
switch indexPath.row {
case 0:
openMapForPlace()
case 1:
callParkingOwn()
case 2:
showMoreInfo()
default:
break
}
}else{
if indexPath.row == 0 {
startReview()
}else{
showAllComments()
}
}
}
}
extension DetailParkingController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrUrlImageParking?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: PhotosCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier("PhotosCollectionViewCell", forIndexPath: indexPath) as! PhotosCollectionViewCell
cell.disPlay(arrUrlImageParking![indexPath.row] as! String)
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
return CGSizeMake(120 , 120)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
return UIEdgeInsetsMake(5, 5, 5, 5)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
}
| apache-2.0 | 950a63f102c0b36b51ebf2a1ecbe36ae | 38.854938 | 181 | 0.650197 | 5.483227 | false | false | false | false |
psmortal/Berry | Pod/Classes/UIImagePickerController+RxCreate.swift | 1 | 2128 | //
// UIImagePickerController+RxCreate.swift
// RxExample
//
// Created by Krunoslav Zaher on 1/10/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
func dismissViewController(_ viewController: UIViewController, animated: Bool) {
if viewController.isBeingDismissed || viewController.isBeingPresented {
DispatchQueue.main.async {
dismissViewController(viewController, animated: animated)
}
return
}
if viewController.presentingViewController != nil {
viewController.dismiss(animated: animated, completion: nil)
}
}
public extension Reactive where Base: UIImagePickerController {
static func createWithParent(_ parent: UIViewController?, animated: Bool = true, configureImagePicker: @escaping (UIImagePickerController) throws -> () = { x in }) -> Observable<UIImagePickerController> {
return Observable.create { [weak parent] observer in
let imagePicker = UIImagePickerController()
let dismissDisposable = imagePicker.rx
.didCancel
.subscribe(onNext: { [weak imagePicker] in
guard let imagePicker = imagePicker else {
return
}
dismissViewController(imagePicker, animated: animated)
})
do {
try configureImagePicker(imagePicker)
}
catch let error {
observer.on(.error(error))
return Disposables.create()
}
guard let parent = parent else {
observer.on(.completed)
return Disposables.create()
}
parent.present(imagePicker, animated: animated, completion: nil)
observer.on(.next(imagePicker))
return Disposables.create(dismissDisposable, Disposables.create {
dismissViewController(imagePicker, animated: animated)
})
}
}
}
| mit | 35a5e25e8517bc88b9cc6f1208e91df3 | 32.234375 | 208 | 0.603667 | 5.811475 | false | false | false | false |
tad-iizuka/swift-sdk | Tests/AlchemyDataNewsV1Tests/AlchemyDataNewsTests.swift | 3 | 5240 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import XCTest
import Foundation
import AlchemyDataNewsV1
class AlchemyDataNewsTests: XCTestCase {
private var alchemyDataNews: AlchemyDataNews!
private let timeout: TimeInterval = 5.0
static var allTests : [(String, (AlchemyDataNewsTests) -> () throws -> Void)] {
return [
("testGetNews", testGetNews),
("testGetNewsWithQuery", testGetNewsWithQuery),
("testGetNewsWithInvalidQuery", testGetNewsWithInvalidQuery),
("testGetNewsWithInvalidReturnQuery", testGetNewsWithInvalidReturnQuery),
("testGetNewsInvalidTimeframe", testGetNewsInvalidTimeframe)
]
}
override func setUp() {
super.setUp()
alchemyDataNews = AlchemyDataNews(apiKey: Credentials.AlchemyAPIKey)
}
/** Fail false negatives. */
func failWithError(error: Error) {
XCTFail("Positive test failed with error: \(error)")
}
/** Fail false positives. */
func failWithResult<T>(result: T) {
XCTFail("Negative test returned a result.")
}
/** Wait for expectations. */
func waitForExpectations() {
waitForExpectations(timeout: timeout) { error in
XCTAssertNil(error, "Timeout")
}
}
// Positive Unit Tests
func testGetNews() {
let description = "Get the volume of articles within a timeframe"
let expectation = self.expectation(description: description)
alchemyDataNews.getNews(from: "now-1d", to: "now", failure: failWithError) { news in
XCTAssertNotNil(news, "Response should not be nil")
XCTAssertNotNil(news.result!.count, "Count should not be nil")
expectation.fulfill()
}
waitForExpectations()
}
func testGetNewsWithQuery() {
let description = "Get articles with IBM in the title and assorted values"
let expectation = self.expectation(description: description)
var queryDict = [String: String]()
queryDict["q.enriched.url.title"] = "O[IBM^Apple]"
queryDict["return"] = "enriched.url.title,enriched.url.entities.entity.text,enriched.url.entities.entity.type"
alchemyDataNews.getNews(from: "now-1d", to: "now", query: queryDict, failure: failWithError) { news in
XCTAssertNotNil(news, "Response should not be nil")
XCTAssertNil(news.result?.count, "Count should not return")
XCTAssertNotNil(news.result?.docs?[0].id, "Document ID should not be nil")
XCTAssertNotNil(news.result?.docs?[0].source?.enriched?.url?.title, "Title should not be nil")
XCTAssertNotNil(news.result?.docs?[0].source?.enriched?.url?.entities![0].text, "Entity text should not be nil")
XCTAssertNotNil(news.result?.docs?[0].source?.enriched?.url?.entities![0].type, "Entity type should not be nil")
expectation.fulfill()
}
waitForExpectations()
}
// Negative Unit Tests
func testGetNewsWithInvalidQuery() {
let description = "Use an invalid return key"
let expectation = self.expectation(description: description)
var queryDict = [String: String]()
queryDict["q.enriched.url.apple"] = "O[IBM^Apple]"
queryDict["return"] = "enriched.url.title"
let failure = { (error: Error) in
expectation.fulfill()
}
alchemyDataNews.getNews(from: "now-1d", to: "now", query: queryDict, failure: failure, success: failWithResult)
waitForExpectations()
}
func testGetNewsWithInvalidReturnQuery() {
let description = "Use an invalid return key"
let expectation = self.expectation(description: description)
var queryDict = [String: String]()
queryDict["q.enriched.url.title"] = "O[IBM^Apple]"
queryDict["return"] = "enriched.url.hotdog"
let failure = { (error: Error) in
expectation.fulfill()
}
alchemyDataNews.getNews(from: "now-1d", to: "now", query: queryDict, failure: failure, success: failWithResult)
waitForExpectations()
}
func testGetNewsInvalidTimeframe() {
let description = "Get the volume of articles within a timeframe"
let expectation = self.expectation(description: description)
let failure = { (error: Error) in
expectation.fulfill()
}
alchemyDataNews.getNews(from: "now", to: "now-1d", failure: failure, success: failWithResult)
waitForExpectations()
}
}
| apache-2.0 | cc25cc36312c23a5f4301ac4d25d811e | 37.248175 | 124 | 0.637786 | 4.781022 | false | true | false | false |
hrscy/TodayNews | News/News/Classes/Mine/Controller/SettingViewController.swift | 1 | 3745 | //
// TableViewController.swift
// News
//
// Created by 杨蒙 on 2017/9/29.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
import Kingfisher
class SettingViewController: UITableViewController {
/// 存储 plist 文件中的数据
var sections = [[SettingModel]]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 设置状态栏属性
navigationController?.navigationBar.barStyle = .default
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UI
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as SettingCell
cell.setting = sections[indexPath.section][indexPath.row]
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell.calculateDiskCashSize() // 清理缓存,从沙盒中获取缓存数据的大小
case 2: cell.selectionStyle = .none // 摘要
default: break
}
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! SettingCell
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell.clearCacheAlertController() // 清理缓存
case 1: cell.setupFontAlertController() // 设置字体大小
case 3: cell.setupNetworkAlertController() // 非 WiFi 网络流量
case 4: cell.setupPlayNoticeAlertController() // 非 WiFi 网络播放提醒
default: break
}
case 1:
if indexPath.row == 0 { // 离线下载
navigationController?.pushViewController(OfflineDownloadController(), animated: true)
}
default: break
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 10))
view.theme_backgroundColor = "colors.tableViewBackgroundColor"
return view
}
}
extension SettingViewController {
/// 设置 UI
private func setupUI() {
// pilst 文件的路径
let path = Bundle.main.path(forResource: "settingPlist", ofType: "plist")
// plist 文件中的数据
let cellPlist = NSArray(contentsOfFile: path!) as! [Any]
sections = cellPlist.compactMap({ section in
(section as! [Any]).compactMap({ SettingModel.deserialize(from: $0 as? [String: Any]) })
})
tableView.sectionHeaderHeight = 10
tableView.ym_registerCell(cell: SettingCell.self)
tableView.rowHeight = 44
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
tableView.theme_backgroundColor = "colors.tableViewBackgroundColor"
}
}
| mit | b38323f614587638ae7041600521e574 | 33.815534 | 109 | 0.628555 | 4.9326 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Home/Controller/HomeJokeViewController.swift | 1 | 1299 | //
// HomeJokeViewController.swift
// News
//
// Created by 杨蒙 on 2018/1/26.
// Copyright © 2018年 hrscy. All rights reserved.
//
// 段子 或 街拍
//
import UIKit
class HomeJokeViewController: HomeTableViewController {
/// 是否是段子
var isJoke = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.ym_registerCell(cell: HomeJokeCell.self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Table view data source
extension HomeJokeViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let aNews = news[indexPath.row]
return isJoke ? aNews.jokeCellHeight : aNews.girlCellHeight
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return news.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as HomeJokeCell
cell.isJoke = isJoke
cell.joke = news[indexPath.row]
return cell
}
}
| mit | 5640a3d1e904d17d137c64dbe048eaf1 | 27.266667 | 109 | 0.675314 | 4.608696 | false | false | false | false |
roambotics/swift | test/Generics/issue-55182.swift | 2 | 883 | // RUN: %target-typecheck-verify-swift -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/55182
// CHECK-LABEL: .ColorModel@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[ColorModel]Float32Components.[ColorComponents]Model, Self.[ColorModel]Float32Components : ColorComponents>
public protocol ColorModel {
associatedtype Float32Components: ColorComponents where Float32Components.Model == Self
}
public protocol ColorComponents {
associatedtype Model: ColorModel
}
public protocol ColorPixel {
associatedtype Model: ColorModel
}
// CHECK-LABEL: .P@
// CHECK-NEXT: Requirement signature: <Self where Self.[P]A : ColorPixel, Self.[P]B : ColorPixel, Self.[P]A.[ColorPixel]Model == Self.[P]B.[ColorPixel]Model>
public protocol P {
associatedtype A: ColorPixel
associatedtype B: ColorPixel where B.Model == A.Model
}
| apache-2.0 | e145258f9c537f01ae22470f12019a6b | 35.791667 | 170 | 0.763307 | 3.995475 | false | false | false | false |
svdo/ReRxSwift | ExampleTests/TableAndCollection/TableAndCollectionReducerSpec.swift | 1 | 1415 | // Copyright © 2017 Stefan van den Oord. All rights reserved.
import Quick
import Nimble
@testable import Example
class TableAndControllerSpec: QuickSpec {
override func spec() {
let categories: [ShopCategory] = [
ShopCategory(title: "cat1", description: "desc1", shops: [
Shop(name: "shop1", rating: 0.1),
Shop(name: "shop2", rating: 0.2)
]),
ShopCategory(title: "cat2", description: "desc2", shops: [
Shop(name: "shop3", rating: 0.3),
Shop(name: "shop4", rating: 0.4)
])
]
it("handles Reverse") {
let initialState = TableAndCollectionState(categories: categories)
let action = ReverseShops()
let nextState = tableAndCollectionReducer(action: action, state: initialState)
expect(nextState.categories.count) == 2
expect(nextState.categories[0].shops.count) == 2
expect(nextState.categories[1].shops.count) == 2
expect(nextState.categories[0].shops[0]) == initialState.categories[1].shops[1]
expect(nextState.categories[0].shops[1]) == initialState.categories[1].shops[0]
expect(nextState.categories[1].shops[0]) == initialState.categories[0].shops[1]
expect(nextState.categories[1].shops[1]) == initialState.categories[0].shops[0]
}
}
}
| mit | d10d24eba61c3e900b289aa4374e30c2 | 40.588235 | 91 | 0.597595 | 4.098551 | false | false | false | false |
imitationgame/pokemonpassport | pokepass/Model/Create/MCreateOptionsItemSave.swift | 1 | 2640 | import UIKit
class MCreateOptionsItemSave:MCreateOptionsItem
{
private let kImage:String = "optionsSave"
init()
{
let title:String = NSLocalizedString("MCreateOptionsItemSave_title", comment:"")
super.init(image:kImage, title:title)
}
override func selected(controller:CCreate)
{
if controller.model.locations.isEmpty
{
VMainAlert.Message(
message:NSLocalizedString("MCreateOptionsItemSave_empty", comment:""))
}
else if controller.loadedProject != nil
{
controller.update()
}
else
{
let alert:UIAlertController = UIAlertController(
title:
NSLocalizedString("MCreateOptionsItemSave_alertTitle", comment:""),
message:
NSLocalizedString("MCreateOptionsItemSave_alertMessage", comment:""),
preferredStyle:UIAlertControllerStyle.alert)
let actionAccept:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("MCreateOptionsItemSave_accept", comment:""),
style:
UIAlertActionStyle.default)
{ [weak controller] (action) in
var projectName:String = alert.textFields!.last!.text!
if projectName.isEmpty
{
projectName = NSLocalizedString("MCreateOptionsItemSave_noName", comment:"")
}
controller?.save(name:projectName)
}
let actionCancel:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("MCreateOptionsItemSave_cancel", comment:""),
style:
UIAlertActionStyle.cancel, handler:nil)
alert.addAction(actionAccept)
alert.addAction(actionCancel)
alert.addTextField
{ (field) in
field.font = UIFont.regular(size:18)
field.keyboardAppearance = UIKeyboardAppearance.light
field.autocorrectionType = UITextAutocorrectionType.no
field.spellCheckingType = UITextSpellCheckingType.no
field.autocapitalizationType = UITextAutocapitalizationType.words
field.placeholder = NSLocalizedString("MCreateOptionsItemSave_noName", comment:"")
}
controller.present(alert, animated:true, completion:nil)
}
}
}
| mit | d4c4d60e15d4d995683a3c19acc5884e | 35.666667 | 102 | 0.552652 | 6.839378 | false | false | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/Browser/TopTabsViews.swift | 1 | 10403 | /* 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 Foundation
import Shared
struct TopTabsSeparatorUX {
static let Identifier = "Separator"
static let Width: CGFloat = 1
}
class TopTabsSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.theme.topTabs.separator
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsHeaderFooter: UICollectionReusableView {
let line = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
line.semanticContentAttribute = .forceLeftToRight
addSubview(line)
line.backgroundColor = UIColor.theme.topTabs.separator
}
func arrangeLine(_ kind: String) {
line.snp.removeConstraints()
switch kind {
case UICollectionView.elementKindSectionHeader:
line.snp.makeConstraints { make in
make.trailing.equalTo(self)
}
case UICollectionView.elementKindSectionFooter:
line.snp.makeConstraints { make in
make.leading.equalTo(self)
}
default:
break
}
line.snp.makeConstraints { make in
make.height.equalTo(TopTabsUX.SeparatorHeight)
make.width.equalTo(TopTabsUX.SeparatorWidth)
make.top.equalTo(self).offset(TopTabsUX.SeparatorYOffset)
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabCell: UICollectionViewCell, PrivateModeUI {
static let Identifier = "TopTabCellIdentifier"
static let ShadowOffsetSize: CGFloat = 2 //The shadow is used to hide the tab separator
var selectedTab = false {
didSet {
backgroundColor = selectedTab ? UIColor.theme.topTabs.tabBackgroundSelected : UIColor.theme.topTabs.tabBackgroundUnselected
titleText.textColor = selectedTab ? UIColor.theme.topTabs.tabForegroundSelected : UIColor.theme.topTabs.tabForegroundUnselected
highlightLine.isHidden = !selectedTab
closeButton.tintColor = selectedTab ? UIColor.theme.topTabs.closeButtonSelectedTab : UIColor.theme.topTabs.closeButtonUnselectedTab
closeButton.backgroundColor = backgroundColor
closeButton.layer.shadowColor = backgroundColor?.cgColor
if selectedTab {
drawShadow()
} else {
self.layer.shadowOpacity = 0
}
}
}
let titleText: UILabel = {
let titleText = UILabel()
titleText.textAlignment = .left
titleText.isUserInteractionEnabled = false
titleText.numberOfLines = 1
titleText.lineBreakMode = .byCharWrapping
titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
titleText.semanticContentAttribute = .forceLeftToRight
return titleText
}()
let favicon: UIImageView = {
let favicon = UIImageView()
favicon.layer.cornerRadius = 2.0
favicon.layer.masksToBounds = true
favicon.semanticContentAttribute = .forceLeftToRight
return favicon
}()
let closeButton: UIButton = {
let closeButton = UIButton()
closeButton.setImage(UIImage.templateImageNamed("menu-CloseTabs"), for: [])
closeButton.tintColor = UIColor.Photon.Grey40
closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: TopTabsUX.TabTitlePadding, bottom: 15, right: TopTabsUX.TabTitlePadding)
closeButton.layer.shadowOpacity = 0.8
closeButton.layer.masksToBounds = false
closeButton.layer.shadowOffset = CGSize(width: -TopTabsUX.TabTitlePadding, height: 0)
closeButton.semanticContentAttribute = .forceLeftToRight
return closeButton
}()
let highlightLine: UIView = {
let line = UIView()
line.backgroundColor = UIColor.Photon.Blue60
line.isHidden = true
line.semanticContentAttribute = .forceLeftToRight
return line
}()
weak var delegate: TopTabCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
closeButton.addTarget(self, action: #selector(closeTab), for: .touchUpInside)
contentView.addSubview(titleText)
contentView.addSubview(closeButton)
contentView.addSubview(favicon)
contentView.addSubview(highlightLine)
favicon.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.size.equalTo(TabTrayControllerUX.FaviconSize)
make.leading.equalTo(self).offset(TopTabsUX.TabTitlePadding)
}
titleText.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.trailing.equalTo(closeButton.snp.leading).offset(TopTabsUX.TabTitlePadding)
make.leading.equalTo(favicon.snp.trailing).offset(TopTabsUX.TabTitlePadding)
}
closeButton.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.height.equalTo(self)
make.width.equalTo(self.snp.height).offset(-TopTabsUX.TabTitlePadding)
make.trailing.equalTo(self.snp.trailing)
}
highlightLine.snp.makeConstraints { make in
make.top.equalTo(self)
make.leading.equalTo(self).offset(-TopTabCell.ShadowOffsetSize)
make.trailing.equalTo(self).offset(TopTabCell.ShadowOffsetSize)
make.height.equalTo(TopTabsUX.HighlightLineWidth)
}
self.clipsToBounds = false
applyUIMode(isPrivate: false)
}
func applyUIMode(isPrivate: Bool) {
highlightLine.backgroundColor = UIColor.theme.topTabs.tabSelectedIndicatorBar(isPrivate)
}
func configureWith(tab: Tab, isSelected: Bool) {
applyUIMode(isPrivate: tab.isPrivate)
self.titleText.text = tab.displayTitle
if tab.displayTitle.isEmpty {
if let url = tab.webView?.url, let internalScheme = InternalURL(url) {
self.titleText.text = Strings.AppMenuNewTabTitleString
self.accessibilityLabel = internalScheme.aboutComponent
} else {
self.titleText.text = tab.webView?.url?.absoluteDisplayString
}
self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, self.titleText.text ?? "")
} else {
self.accessibilityLabel = tab.displayTitle
self.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle)
}
self.selectedTab = isSelected
if let siteURL = tab.url?.displayURL {
self.favicon.contentMode = .center
self.favicon.setImageAndBackground(forIcon: tab.displayFavicon, website: siteURL) { [weak self] in
guard let self = self else { return }
self.favicon.image = self.favicon.image?.createScaled(CGSize(width: 15, height: 15))
if self.favicon.backgroundColor == .clear {
self.favicon.backgroundColor = .white
}
}
} else {
self.favicon.image = UIImage(named: "defaultFavicon")
self.favicon.tintColor = UIColor.theme.tabTray.faviconTint
self.favicon.contentMode = .scaleAspectFit
self.favicon.backgroundColor = .clear
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
self.layer.shadowOpacity = 0
}
@objc func closeTab() {
delegate?.tabCellDidClose(self)
}
// When a tab is selected the shadow prevents the tab separators from showing.
func drawShadow() {
self.layer.masksToBounds = false
self.layer.shadowColor = backgroundColor?.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowRadius = 0
self.layer.shadowPath = UIBezierPath(roundedRect: CGRect(width: self.frame.size.width + (TopTabCell.ShadowOffsetSize * 2), height: self.frame.size.height), cornerRadius: 0).cgPath
self.layer.shadowOffset = CGSize(width: -TopTabCell.ShadowOffsetSize, height: 0)
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
}
class TopTabFader: UIView {
lazy var hMaskLayer: CAGradientLayer = {
let innerColor: CGColor = UIColor.Photon.White100.cgColor
let outerColor: CGColor = UIColor(white: 1, alpha: 0.0).cgColor
let hMaskLayer = CAGradientLayer()
hMaskLayer.colors = [outerColor, innerColor, innerColor, outerColor]
hMaskLayer.locations = [0.00, 0.005, 0.995, 1.0]
hMaskLayer.startPoint = CGPoint(x: 0, y: 0.5)
hMaskLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
hMaskLayer.anchorPoint = .zero
return hMaskLayer
}()
init() {
super.init(frame: .zero)
layer.mask = hMaskLayer
}
internal override func layoutSubviews() {
super.layoutSubviews()
let widthA = NSNumber(value: Float(CGFloat(8) / frame.width))
let widthB = NSNumber(value: Float(1 - CGFloat(8) / frame.width))
hMaskLayer.locations = [0.00, widthA, widthB, 1.0]
hMaskLayer.frame = CGRect(width: frame.width, height: frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsViewLayoutAttributes: UICollectionViewLayoutAttributes {
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? TopTabsViewLayoutAttributes else {
return false
}
return super.isEqual(object)
}
}
| mpl-2.0 | 5ea07ad2f29b81d937d346af0b6c462d | 36.967153 | 187 | 0.657118 | 5.013494 | false | false | false | false |
gxf2015/DYZB | DYZB/DYZB/Classes/Main/View/PageContenView.swift | 1 | 4785 | //
// PageContenView.swift
// DYZB
//
// Created by guo xiaofei on 2017/8/10.
// Copyright © 2017年 guo xiaofei. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContenView, progress : CGFloat, sourceIndex : Int, targerIndex : Int)
}
fileprivate let contenCellID = "contenCellID"
class PageContenView: UIView {
fileprivate var childVcs : [UIViewController]
fileprivate weak var parentViewController : UIViewController?
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contenCellID)
return collectionView
}()
init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContenView{
fileprivate func setupUI(){
// 1.
for chldVc in childVcs {
parentViewController?.addChildViewController(chldVc)
}
// 2
addSubview(collectionView)
collectionView.frame = bounds
}
}
extension PageContenView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contenCellID, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
extension PageContenView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffsetX = scrollView.contentOffset.x
isForbidScrollDelegate = false
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isForbidScrollDelegate{ return }
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX {
//1
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
//2
sourceIndex = Int(currentOffsetX / scrollViewW)
//3
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//4
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else{
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
targetIndex = Int(currentOffsetX / scrollViewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targerIndex: targetIndex)
}
}
extension PageContenView{
func setCurrentIndex(currentIndex : Int) {
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x : offsetX, y : 0), animated: false)
}
}
| mit | bea4020ed5225ac8ea78cc62f2a51995 | 29.265823 | 124 | 0.641782 | 5.955168 | false | false | false | false |
juliensagot/JSSwitch | JSSwitch.swift | 1 | 5576 | //
// JSSwitch.swift
// JSSwitch
//
// Created by Julien Sagot on 29/05/16.
// Copyright © 2016 Julien Sagot. All rights reserved.
//
import AppKit
public class JSSwitch: NSControl {
// MARK: - Properties
private var pressed = false
private let backgroundLayer = CALayer()
private let knobContainer = CALayer()
private let knobLayer = CALayer()
private let knobShadows = (smallStroke: CALayer(), smallShadow: CALayer(), mediumShadow: CALayer(), bigShadow: CALayer())
// MARK: Computed
public override var wantsUpdateLayer: Bool { return true }
public override var intrinsicContentSize: NSSize {
return CGSize(width: 52, height: 32)
}
private var scaleFactor: CGFloat {
return ceil(frame.size.height / 62) // Hardcoded base height
}
public var tintColor = NSColor(deviceRed: 76/255, green: 217/255, blue: 100/255, alpha: 1.0) {
didSet { needsDisplay = true }
}
public var on = false {
didSet { needsDisplay = true }
}
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
setupLayers()
}
// MARK: - Layers Setup
private func setupLayers() {
wantsLayer = true
layer?.masksToBounds = false
layerContentsRedrawPolicy = .onSetNeedsDisplay
// Background
setupBackgroundLayer()
layer?.addSublayer(backgroundLayer)
// Knob
setupKnobLayers()
layer?.addSublayer(knobContainer)
}
// MARK: Background Layer
private func setupBackgroundLayer() {
backgroundLayer.frame = bounds
backgroundLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
}
// MARK: Knob
private func setupKnobLayers() {
setupKnobContainerLayer()
setupKnobLayer()
setupKnobLayerShadows()
knobContainer.addSublayer(knobLayer)
knobContainer.insertSublayer(knobShadows.smallStroke, below: knobLayer)
knobContainer.insertSublayer(knobShadows.smallShadow, below: knobShadows.smallStroke)
knobContainer.insertSublayer(knobShadows.mediumShadow, below: knobShadows.smallShadow)
knobContainer.insertSublayer(knobShadows.bigShadow, below: knobShadows.mediumShadow)
}
private func setupKnobContainerLayer() {
knobContainer.frame = knobFrameForState(on: false, pressed: false)
}
private func setupKnobLayer() {
knobLayer.autoresizingMask = [.layerWidthSizable]
knobLayer.backgroundColor = NSColor.white.cgColor
knobLayer.frame = knobContainer.bounds
knobLayer.cornerRadius = ceil(knobContainer.bounds.height / 2)
}
private func setupKnobLayerShadows() {
let effectScale = scaleFactor
// Small Stroke
let smallStroke = knobShadows.smallStroke
smallStroke.frame = knobLayer.frame.insetBy(dx: -1, dy: -1)
smallStroke.autoresizingMask = [.layerWidthSizable]
smallStroke.backgroundColor = NSColor.black.withAlphaComponent(0.06).cgColor
smallStroke.cornerRadius = ceil(smallStroke.bounds.height / 2)
let smallShadow = knobShadows.smallShadow
smallShadow.frame = knobLayer.frame.insetBy(dx: 2, dy: 2)
smallShadow.autoresizingMask = [.layerWidthSizable]
smallShadow.cornerRadius = ceil(smallShadow.bounds.height / 2)
smallShadow.backgroundColor = NSColor.red.cgColor
smallShadow.shadowColor = NSColor.black.cgColor
smallShadow.shadowOffset = CGSize(width: 0, height: -3 * effectScale)
smallShadow.shadowOpacity = 0.12
smallShadow.shadowRadius = 2.0 * effectScale
let mediumShadow = knobShadows.mediumShadow
mediumShadow.frame = smallShadow.frame
mediumShadow.autoresizingMask = [.layerWidthSizable]
mediumShadow.cornerRadius = smallShadow.cornerRadius
mediumShadow.backgroundColor = NSColor.red.cgColor
mediumShadow.shadowColor = NSColor.black.cgColor
mediumShadow.shadowOffset = CGSize(width: 0, height: -9 * effectScale)
mediumShadow.shadowOpacity = 0.16
mediumShadow.shadowRadius = 6.0 * effectScale
let bigShadow = knobShadows.bigShadow
bigShadow.frame = smallShadow.frame
bigShadow.autoresizingMask = [.layerWidthSizable]
bigShadow.cornerRadius = smallShadow.cornerRadius
bigShadow.backgroundColor = NSColor.red.cgColor
bigShadow.shadowColor = NSColor.black.cgColor
bigShadow.shadowOffset = CGSize(width: 0, height: -9 * effectScale)
bigShadow.shadowOpacity = 0.06
bigShadow.shadowRadius = 0.5 * effectScale
}
// MARK: - Drawing
public override func updateLayer() {
// Background
backgroundLayer.cornerRadius = ceil(bounds.height / 2)
backgroundLayer.borderWidth = on ? ceil(bounds.height) : 3.0 * scaleFactor
backgroundLayer.borderColor = on ? tintColor.cgColor : NSColor.black.withAlphaComponent(0.09).cgColor
// Knob
knobContainer.frame = knobFrameForState(on: on, pressed: pressed)
knobLayer.cornerRadius = ceil(knobContainer.bounds.height / 2)
}
// MARK: - Helpers
private func knobFrameForState(on: Bool, pressed: Bool) -> CGRect {
let borderWidth = 3.0 * scaleFactor
var origin: CGPoint
var size: CGSize {
if pressed {
return CGSize(
width: ceil(bounds.width * 0.69) - (2 * borderWidth),
height: bounds.height - (2 * borderWidth)
)
}
return CGSize(width: bounds.height - (2 * borderWidth), height: bounds.height - (2 * borderWidth))
}
if on {
origin = CGPoint(x: bounds.width - size.width - borderWidth, y: borderWidth)
} else {
origin = CGPoint(x: borderWidth, y: borderWidth)
}
return CGRect(origin: origin, size: size)
}
// MARK: - Events
public override func mouseDown(with theEvent: NSEvent) {
pressed = true
needsDisplay = true
}
public override func mouseUp(with theEvent: NSEvent) {
pressed = false
on = !on
}
}
| mit | a46c32d2eb52fd56588205ee8d63eeee | 30.857143 | 122 | 0.746009 | 3.931594 | false | false | false | false |
ludoded/ReceiptBot | ReceiptBot/DataModel/UserInfo.swift | 1 | 2007 | //
// UserInfo.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/8/17.
// Copyright © 2017 receiptbot. All rights reserved.
//
import CoreData
@objc(UserInfo)
final class UserInfo: NSManagedObject {
@NSManaged fileprivate(set) var userId: NSNumber?
@NSManaged fileprivate(set) var orgId: NSNumber?
@NSManaged fileprivate(set) var companyId: NSNumber?
@NSManaged fileprivate(set) var emailAddress: String?
@NSManaged fileprivate(set) var fullName: String?
@NSManaged fileprivate(set) var orgName: String?
@NSManaged fileprivate(set) var country: NSNumber?
@NSManaged fileprivate(set) var accType: NSNumber?
@NSManaged fileprivate(set) var businessSector: String?
@NSManaged fileprivate(set) var profileImage: Data?
@NSManaged fileprivate(set) var companyName: String?
@NSManaged fileprivate(set) var accountingSoftware: NSNumber?
static func insert(into context: NSManagedObjectContext, response: AuthResponse) -> UserInfo {
let userInfo: UserInfo = context.insertObject()
userInfo.userId = NSNumber(value: 1)
userInfo.orgId = NSNumber(value: response.organisationId)
userInfo.companyId = NSNumber(value: response.entityId)
userInfo.emailAddress = response.emailAddress
userInfo.fullName = response.credentials.fullName
userInfo.orgName = response.organisationName
userInfo.country = NSNumber(value: 0) /// NOTE: Back-end returns Null for countryId
userInfo.accType = NSNumber(value: 0) /// NOTE: Back-end returns Null for accType
userInfo.businessSector = nil /// NOTE: Back-end doesn't returns business sector
userInfo.profileImage = nil /// NOTE: Back-end doesn't returns profileImage
userInfo.companyName = response.entityName
userInfo.accountingSoftware = NSNumber(value: Int(response.accountPackageId) ?? 0)
return userInfo
}
}
extension UserInfo: Managed, ManagedCrud {
typealias R = AuthResponse
}
| lgpl-3.0 | 8c38506196c61e1ee7b753d7e7d20f15 | 41.680851 | 98 | 0.718345 | 4.548753 | false | false | false | false |
kuririnz/KkListActionSheet-Swift | KkListActionSheetSwiftDemo/KkListActionSheetSwiftDemo/ViewController.swift | 1 | 1493 | //
// ViewController.swift
// KkListActionSheet-SwiftDemo
//
// Created by keisuke kuribayashi on 2015/10/11.
// Copyright © 2015年 keisuke kuribayashi. All rights reserved.
//
import UIKit
import KkListActionSheetSwift
class ViewController: UIViewController, KkListActionSheetDelegate {
var kkListActionSheet: KkListActionSheet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
kkListActionSheet = KkListActionSheet.createInit(self)
kkListActionSheet!.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPushed (sender: UIButton) {
kkListActionSheet!.showHide()
}
// MARK: KkListActionSheet Delegate Method
func kkTableView(tableView: UITableView, rowsInSection section: NSInteger) -> NSInteger {
return 20
}
func kkTableView(tableView: UITableView, currentIndx indexPath: NSIndexPath) -> UITableViewCell {
let cellIdenfier = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdenfier)
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdenfier)
}
cell?.textLabel?.text = String(format: "%ld", indexPath.row)
return cell!
}
}
| mit | 158659a1fd13181b9b9f8eeb5882d3e6 | 28.8 | 101 | 0.671812 | 5.359712 | false | false | false | false |
Miguel-Herrero/Swift | Dream Lister/Dream Lister/MaterialView.swift | 1 | 1033 | //
// MaterialView.swift
// Dream Lister
//
// Created by Miguel Herrero on 30/11/16.
// Copyright © 2016 Miguel Herrero. All rights reserved.
//
import UIKit
private var _materialKey = false
extension UIView {
@IBInspectable var materialDesign: Bool {
get {
return _materialKey
}
set {
_materialKey = newValue
if _materialKey {
self.layer.masksToBounds = false
self.layer.cornerRadius = 3.0
self.layer.shadowOpacity = 0.8
self.layer.shadowRadius = 3.0
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowColor = UIColor(red: 157/255, green: 157/255, blue: 157/255, alpha: 1.0).cgColor
} else {
self.layer.cornerRadius = 0
self.layer.shadowOpacity = 0
self.layer.shadowRadius = 0
self.layer.shadowColor = nil
}
}
}
}
| gpl-3.0 | f613bd72796b387882c0b19d588d3524 | 24.8 | 113 | 0.52907 | 4.391489 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/LowEnergyRxChannel.swift | 1 | 1089 | //
// LowEnergyRxChannel.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/// Bluetooth LE Rx Channel
@frozen
public struct LowEnergyRxChannel: RawRepresentable, Equatable, Hashable, Comparable {
/// 100 msec
public static let min = LowEnergyRxChannel(0x00)
/// 32 seconds
public static let max = LowEnergyRxChannel(0x27)
public let rawValue: UInt8
public init?(rawValue: UInt8) {
guard rawValue >= LowEnergyRxChannel.min.rawValue,
rawValue <= LowEnergyRxChannel.max.rawValue
else { return nil }
assert((LowEnergyRxChannel.min.rawValue ... LowEnergyRxChannel.max.rawValue).contains(rawValue))
self.rawValue = rawValue
}
// Private, unsafe
private init(_ rawValue: UInt8) {
self.rawValue = rawValue
}
// Comparable
public static func < (lhs: LowEnergyRxChannel, rhs: LowEnergyRxChannel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
| mit | df85f685deadb449a9735fd837bfa036 | 25.536585 | 104 | 0.637868 | 4.857143 | false | false | false | false |
vmachiel/swift | CalculatorV2/Calculator/ViewController.swift | 1 | 8971 | //
// ViewController.swift
// Calculator
//
// Created by Machiel van Dorst on 24-07-17.
// Copyright © 2017 vmachiel. All rights reserved.
//
import UIKit
// ViewController as a label for display, and computed property for its value, that is
// get and set by the CalCulatorBrain.
class ViewController: UIViewController {
// MARK: - Properties and Outlets
// The text in the display
@IBOutlet weak var display: UILabel!
// The text in the description display
@IBOutlet weak var descriptionDisplay: UILabel!
// The text of the memory display
@IBOutlet weak var memoryDisplay: UILabel!
// Has the user typed a number already?
var userIsInTheMiddleOfTyping = false
// This property is passed to the brain (the number in the display)
// This property is set to the result when the brain returns it.
// Is a Double to be used by brain, set to string to use as display.text
var displayValue: Double {
// Assume there's always a valid double
get {
return Double(display.text!)!
}
// When you do displayValue = x, newValue is set to x
set {
display.text = String(newValue)
}
}
// The whole brain is set to this var to communicate with it.
private var brain = CalculatorBrain()
// The dict which can store variables like M (memory) to send to the evaluate method of the calc
// brain. One it has been updated, use didSet to update the screen. Map all the memory keys (variables),
// and their values using flatmap to format them, and joined() to make it into one string. Beautify!
private var variables = Dictionary<String, Double>() {
didSet {
memoryDisplay.text = variables.compactMap{$0+": \($1)"}.joined(separator: ", ").beautifyNumbers()
}
}
// MARK: - Buttons
// Called when the user touches a button. Properties of the button are in the
// sender parameter. You get the number from it's title.
@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
// If you have already typed numbers, add them.
// if not, set the display to the first digit typed
// and set userIsTyping to true for the next digits.
// check for invalid number!
if userIsInTheMiddleOfTyping {
let textCurrentlyInDisplay = display.text!
// you have to unwrap display. But not its text property, since
// it can be set, and is set. So compiler knows it has a value
// String cat.
// Touched digit is not . or there is no . on screen yet:
if digit != "." || !textCurrentlyInDisplay.contains(".") {
display.text = textCurrentlyInDisplay + digit
}
// And for new numbers: is the digit a ., make screen 0.
// If it's a 0, and the screen is set to 0, do nothing.
// If it's a 0, but there is a number from previous calc,
// fallthrough to default which is:
// Default: set screen to typed digit. In any case:
// Make userIsInTheMiddleOfTyping bool.
} else {
switch digit {
case ".":
display.text = "0."
case "0":
if display.text == "0" {
return // exit switch
}
fallthrough
default:
display.text = digit
}
userIsInTheMiddleOfTyping = true
}
}
// Run when the user touches a operation button, properties are send to the
// sender parameter. If there is a number typed, send the operand to the brain
// and reset the bool. Then the button that is pressed is send as the
// symbol used to the brain using performOperation method.
// Finally, call the displayResults() method to eval en display resutls. This is
// factored out into seperate private function because it's called from different places.
@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(displayValue) // get is used here
userIsInTheMiddleOfTyping = false // IMPORTANT!! This will ensure a new number after an operation.
}
if let mathmaticalSymbol = sender.currentTitle {
brain.performOperation(operation: mathmaticalSymbol)
}
calcAndDisplayResult()
}
// Reset button. Reset everything by re-initializing the brain.
// set display value to 0, set description to empty string and
// user typing bool false. Reset the variables
@IBAction func reset(_ sender: UIButton) {
brain = CalculatorBrain()
displayValue = 0
descriptionDisplay.text = " "
userIsInTheMiddleOfTyping = false
variables = Dictionary<String, Double>()
}
// Undo button. If user is typing, and the text has something in it,
// set current text to var. Remove it's last char. If it's now empty,
// set it to 0 and userIsInTheMiddleOfTyping to false.
// Finally, set the display.text to the text var
// If display is empty, userIsTyping will be false.
// In that case: undo. This removes the last Element from the stack.
// After that, call calcAndDisplayResult to re-eval and update displays again.
@IBAction func undo(_ sender: UIButton) {
if userIsInTheMiddleOfTyping, var text = display.text {
text.remove(at: text.index(before: text.endIndex))
if text.isEmpty || text == "0" {
text = "0"
userIsInTheMiddleOfTyping = false
}
display.text = text
} else {
brain.undo()
calcAndDisplayResult()
}
}
// Memory, is currently the only variable supported. A dict is used to more easily add more later.
// Add memory to the stack, and start typing new number. calc/update display
@IBAction func callMemory(_ sender: UIButton) {
brain.setOperand(variable: "M")
userIsInTheMiddleOfTyping = false
calcAndDisplayResult()
}
// Set current value to memory, and start typing new number. calc/update display
@IBAction func storeToMemory(_ sender: UIButton) {
variables["M"] = displayValue
userIsInTheMiddleOfTyping = false
calcAndDisplayResult()
}
// MARK: - Update Display
// Main method to eval result and update display
// The brain calls its evaluate method to calulate the result. It's passed the variables
// The result and descriptions are accessed from the evaluation, remember, it returns a tuple,
// (result, isPending, description)
// They are set and formatted to their displays (display and descriptiondisplay)
// For des. display, call beautifynumbers, and check if resultIsPending.
private func calcAndDisplayResult() {
let evaluation = brain.evaluate(using: variables)
if let error = evaluation.error {
display.text = error
} else if let result = evaluation.result {
displayValue = result // set is used here
}
// If description is not empty:
if evaluation.description != "" {
descriptionDisplay.text = evaluation.description.beautifyNumbers() + (evaluation.isPending ? "..." : "=")
} else {
descriptionDisplay.text = " "
}
}
}
// MARK: - Extensions
// Extend string to clean up the numbers for the discprition display
// String will get some beautification code using Regex. Extention is used
// because it might be needed again.
// Regex takes a pattern and options, can throw error.
// Range is made by counting the caracters in the string the method is done
// on
// Finally, the result is return onto itself (this is a method)
// The pattern (regex constant) is replaced with the provided replacement template.
// This will be used in cases where the full string needs to be replaced.. i think.
extension String {
func replace(pattern: String, with replacement: String) -> String {
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSMakeRange(0, self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement)
}
}
// The extention that's used by the viewcontroller. It replaces the pattern with the
// substring. So, \\. finds the dot, then none or one or more 0's, then either no number
// at all [^0-9] or the end of the string. So it find .0 or .00 or .0000 etc
// but not .00004 or .000423000243. It replaces that with $1, which is nothing so an
// empty string. So it replaces it with an empty string, effectively deleting it.
extension String {
func beautifyNumbers() -> String {
return self.replace(pattern: "\\.0+([^0-9]|$)", with: "$1")
}
}
| mit | 75d503dc1289a22c98b81088b113090f | 40.915888 | 117 | 0.642363 | 4.733509 | false | false | false | false |
SJTBA/Scrape | Sources/XMLNodeSet.swift | 1 | 6218 | //
// XMLNodeSet.swift
// Scrape
//
// Created by Sergej Jaskiewicz on 11.09.16.
//
//
/// Instances of this class represent an immutable collection of DOM nodes. An instance provides the interface similar to
/// the `Node`'s one.
public final class XMLNodeSet {
fileprivate var nodes: [XMLElement] = []
/// Concatenated HTML content of nodes in the collection. May be `nil` if no content is available.
public var html: String? {
let html = nodes.reduce("") {
if let text = $1.html {
return $0 + text
}
return $0
}
return html.isEmpty ? nil : html
}
/// Concatenated XML content of nodes in the collection. May be `nil` if no content is available.
public var xml: String? {
let xml = nodes.reduce("") {
if let text = $1.xml {
return $0 + text
}
return $0
}
return xml.isEmpty ? nil : xml
}
/// Concatenated inner HTML content of nodes in the collection.
public var innerHTML: String? {
let html = nodes.reduce("") {
if let text = $1.innerHTML {
return $0 + text
}
return $0
}
return html.isEmpty ? nil : html
}
/// Concatenated text content of nodes in the collection. May be `nil` if no content is available.
public var text: String? {
let html = nodes.reduce("") {
if let text = $1.text {
return $0 + text
}
return $0
}
return html
}
/// Creates an empty collection of nodes.
public init() {}
/// Creates a collection of nodes from the provided array of `XMLElement`s
///
/// - parameter nodes: Nodes to create a node set from.
public init(nodes: [XMLElement]) {
self.nodes = nodes
}
}
extension XMLNodeSet: Collection {
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Int {
return nodes.startIndex
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// ```swift
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
/// ```
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Int {
return nodes.endIndex
}
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// ```swift
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
/// ```
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
public subscript(position: Int) -> XMLElement {
return nodes[position]
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return nodes.index(after: i)
}
}
extension XMLNodeSet: Equatable {
/// 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.
public static func ==(lhs: XMLNodeSet, rhs: XMLNodeSet) -> Bool {
return lhs.nodes.enumerated().map { (index: Int, element: XMLElement) in
element.xml == rhs[index].xml
}.reduce(true) { $0 && $1 }
}
}
extension XMLNodeSet: CustomStringConvertible {
/// A textual representation of this instance.
///
/// Instead of accessing this property directly, convert an instance of any
/// type to a string by using the `String(describing:)` initializer. For
/// example:
///
/// ```swift
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
/// ```
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
public var description: String {
let nodesDescription = nodes.map { node -> String in
let rows = String(describing: node).characters.split(separator: "\n").map(String.init)
let indentedRows = rows.map { row -> String in
return row.isEmpty ? "" : "\n " + row
}
return indentedRows.joined()
}.joined(separator: ",")
return "[" + nodesDescription + "\n]"
}
}
| mit | 6fa2373fd20dcb2920b7af80491f427c | 29.630542 | 121 | 0.545352 | 4.489531 | false | false | false | false |
fgengine/quickly | Quickly/Views/Fields/Text/QTextFieldSuggestionController.swift | 1 | 1409 | //
// Quickly
//
public class QTextFieldSuggestionController : QCollectionController, IQTextFieldSuggestionController {
public var onSelectSuggestion: SelectSuggestionClosure?
public var font: UIFont
public var color: UIColor
private lazy var _section: QCollectionSection = {
let section = QCollectionSection(items: [])
section.insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
section.minimumInteritemSpacing = 6
return section
}()
public init(
font: UIFont,
color: UIColor
) {
self.font = font
self.color = color
super.init(cells: [
Cell.self
])
}
open override func configure() {
super.configure()
self.sections = [ self._section ]
}
public func set(variants: [String]) {
self._section.setItems(variants.compactMap({
return Item(text: $0, font: self.font, color: self.color)
}))
self.reload()
}
}
extension QTextFieldSuggestionController {
@objc
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = self.item(indexPath: indexPath)
if let item = item as? Item {
self.onSelectSuggestion?(self, item.text)
}
self.deselect(item: item, animated: true)
}
}
| mit | 7964cfc40a12390e321e3b571fd4d378 | 25.092593 | 102 | 0.604684 | 4.728188 | false | false | false | false |
BenziAhamed/Nevergrid | NeverGrid/Source/Entity.swift | 1 | 3338 | //
// Entity.swift
// gameninja
//
// Created by Benzi on 19/06/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
// MARK: Entity ------------------------------------------
class Entity: Equatable {
var id:Int
init(id:Int){
self.id = id
}
}
func ==(a:Entity, b:Entity) -> Bool {
return a.id == b.id
}
// MARK: EntityManager ------------------------------------------
class EntityManager {
struct EntityId{
static var lowestIdCreated:Int = 0
}
var entities:[Int]
var componentsByType:[ComponentType:[Int:Component]]
init(){
entities = []
componentsByType = [ComponentType:[Int:Component]]()
}
func createEntityId() -> Int {
if EntityId.lowestIdCreated < Int.max {
return EntityId.lowestIdCreated++
} else {
for i in 1..<Int.max {
if !entities.contains(i) {
return i
}
}
}
return 0
}
func createEntity() -> Entity {
let e = Entity(id: createEntityId())
self.entities.append(e.id)
return e
}
func removeEntity(e:Entity) {
for k in componentsByType.keys {
// get value
var components = componentsByType[k]!
if let componentForEntity = components[e.id] {
components.removeValueForKey(e.id)
// update back
componentsByType[k] = components
}
}
for i in 0..<entities.count {
if entities[i] == e.id {
entities.removeAtIndex(i)
break
}
}
}
func entityExists(e:Entity) -> Bool {
for id in entities {
if e.id == id { return true }
}
return false
}
func addComponent(e:Entity, c:Component){
if componentsByType[c.type] == nil {
componentsByType[c.type] = [Int:Component]()
}
// get value
var componentMap = componentsByType[c.type]!
componentMap[e.id] = c
// update back
componentsByType[c.type] = componentMap
}
func removeComponent(e:Entity, c:Component) {
if let componentMap = componentsByType[c.type] {
// get value
var componentMap = componentsByType[c.type]!
componentMap[e.id] = nil
// update back
componentsByType[c.type] = componentMap
}
}
func getComponent(e:Entity, type:ComponentType) -> Component? {
if let componentSet = componentsByType[type] {
if let component = componentSet[e.id] {
return component
}
}
return nil
}
func hasComponent(e:Entity, type:ComponentType) -> Bool {
if let c = getComponent(e, type: type) { return true }
return false
}
func getEntitiesWithComponent(type:ComponentType) -> [Entity] {
if let components = componentsByType[type] {
var entities = [Entity]()
for k in components.keys {
entities.append(Entity(id: k))
}
return entities
}
return []
}
}
| isc | 985ad7bace1bd43c80c27b768e817e9d | 23.544118 | 67 | 0.502097 | 4.649025 | false | false | false | false |
santosli/100-Days-of-Swift-3 | Project 34/Project 34/ViewController.swift | 1 | 6939 | //
// ViewController.swift
// Project 34
//
// Created by Santos on 23/01/2017.
// Copyright © 2017 santos. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let screenWidth = UIScreen.main.bounds.width
let screenHeigth = UIScreen.main.bounds.height
let googleLogWidth = 200
let googleLogHeigth = 80
let initAlpha: CGFloat = 0
let googleLogView = UIImageView()
let searhBarView = UIImageView()
let settingIconView = UIImageView()
let reorderIconView = UIImageView()
let signInButton = UIButton()
let voiceIconView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//init view
initView()
}
override func viewDidAppear(_ animated: Bool) {
//do animation
showItems()
}
func initView() {
//google Log
googleLogView.image = UIImage(named: "googlelog.png")
googleLogView.frame = CGRect(x: Int(screenWidth/2) - googleLogWidth/2, y: Int(screenHeigth/2) - googleLogHeigth/2, width: googleLogWidth, height: googleLogHeigth)
googleLogView.contentMode = .scaleAspectFit
self.view.addSubview(googleLogView)
//search bar
searhBarView.image = UIImage(named: "searchbar.png")
searhBarView.frame = CGRect(x: Int(screenWidth/2) - 150, y: Int(screenHeigth/2) + 20, width: 300, height: 45)
searhBarView.layer.shadowColor = UIColor.gray.cgColor
searhBarView.layer.shadowOpacity = 1
searhBarView.layer.shadowOffset = CGSize.zero
searhBarView.layer.shadowRadius = 1
searhBarView.alpha = initAlpha
self.view.addSubview(searhBarView)
//setting icon
settingIconView.image = UIImage(named: "settings.png")
settingIconView.frame = CGRect(x: 60, y: 80, width: 25, height: 25)
settingIconView.alpha = initAlpha
self.view.addSubview(settingIconView)
//reorder icon
reorderIconView.image = UIImage(named: "reorder.png")
reorderIconView.frame = CGRect(x: 300, y: 80, width: 25, height: 25)
reorderIconView.alpha = initAlpha
self.view.addSubview(reorderIconView)
//sign in button
signInButton.setTitle("SIGN IN", for: .normal)
signInButton.setTitleColor(.gray, for: .normal)
signInButton.frame = CGRect(x: 140, y: 80, width: 80, height: 25)
signInButton.alpha = initAlpha
self.view.addSubview(signInButton)
//voice icon
voiceIconView.image = resizeImage(UIImage(named: "voice.png")!, targetSize: CGSize(width: 35, height: 35))
voiceIconView.frame = CGRect(x: 160, y: 420, width: 0, height: 0)
voiceIconView.layer.borderWidth = 0
voiceIconView.layer.cornerRadius = 30
voiceIconView.layer.shadowColor = UIColor.gray.cgColor
voiceIconView.layer.shadowOpacity = 0.5
voiceIconView.layer.shadowOffset = CGSize.zero
voiceIconView.layer.shadowRadius = 1
voiceIconView.backgroundColor = .white
voiceIconView.contentMode = .center
voiceIconView.alpha = initAlpha
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showSpeakerView))
voiceIconView.isUserInteractionEnabled = true
voiceIconView.addGestureRecognizer(tapGesture)
self.view.addSubview(voiceIconView)
}
func showItems() {
//do animate
let duration = 0.2
let delay = 0.1
let options = UIViewAnimationOptions.curveEaseInOut
let damping = 0.3 // set damping ration
let velocity = 1.0 // set initial velocity
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping:CGFloat(damping),
initialSpringVelocity: CGFloat(velocity), options: options, animations: {
self.googleLogView.frame = CGRect(x: Int(self.screenWidth/2) - self.googleLogWidth/2, y: Int(self.screenHeigth/2) - self.googleLogHeigth/2 - 100, width: self.googleLogWidth, height: self.googleLogHeigth)
self.searhBarView.frame = CGRect(x: Int(self.screenWidth/2) - 150, y: Int(self.screenHeigth/2) - 20, width: 300, height: 45)
self.settingIconView.frame = CGRect(x: 25, y: 25, width: 25, height: 25)
self.reorderIconView.frame = CGRect(x: 325, y: 25, width: 25, height: 25)
self.signInButton.frame = CGRect(x: 140, y: 25, width: 80, height: 25)
self.voiceIconView.frame = CGRect(x: 160, y: 420, width: 60, height: 60)
self.searhBarView.alpha = 1.0
self.settingIconView.alpha = 1.0
self.reorderIconView.alpha = 1.0
self.signInButton.alpha = 1.0
self.voiceIconView.alpha = 1.0
}, completion: { finished in
})
}
override var prefersStatusBarHidden : Bool {
return true
}
func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
let segueIdentifier = "showSpeaker"
func showSpeakerView() {
self.performSegue(withIdentifier: segueIdentifier, sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
@IBAction func unwindToFirst(segue: UIStoryboardSegue) {}
}
| apache-2.0 | 98b8bb7c576b45dd15db8b911fd6b98b | 39.337209 | 227 | 0.615884 | 4.818056 | false | false | false | false |
iMetalk/TCZDemo | RealmTest-swift-/Pods/RealmSwift/RealmSwift/Migration.swift | 18 | 8962 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
The type of a migration block used to migrate a Realm.
- parameter migration: A `Migration` object used to perform the migration. The migration object allows you to
enumerate and alter any existing objects which require migration.
- parameter oldSchemaVersion: The schema version of the Realm being migrated.
*/
public typealias MigrationBlock = (_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void
/// An object class used during migrations.
public typealias MigrationObject = DynamicObject
/**
A block type which provides both the old and new versions of an object in the Realm. Object
properties can only be accessed using subscripting.
- parameter oldObject: The object from the original Realm (read-only).
- parameter newObject: The object from the migrated Realm (read-write).
*/
public typealias MigrationObjectEnumerateBlock = (_ oldObject: MigrationObject?, _ newObject: MigrationObject?) -> Void
/**
Returns the schema version for a Realm at a given local URL.
- parameter fileURL: Local URL to a Realm file.
- parameter encryptionKey: 64-byte key used to encrypt the file, or `nil` if it is unencrypted.
- throws: An `NSError` that describes the problem.
*/
public func schemaVersionAtURL(_ fileURL: URL, encryptionKey: Data? = nil) throws -> UInt64 {
var error: NSError?
let version = RLMRealm.__schemaVersion(at: fileURL, encryptionKey: encryptionKey, error: &error)
guard version != RLMNotVersioned else {
throw error!
}
return version
}
extension Realm {
/**
Performs the given Realm configuration's migration block on a Realm at the given path.
This method is called automatically when opening a Realm for the first time and does not need to be called
explicitly. You can choose to call this method to control exactly when and how migrations are performed.
- parameter configuration: The Realm configuration used to open and migrate the Realm.
*/
public static func performMigration(for configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration) throws {
try RLMRealm.performMigration(for: configuration.rlmConfiguration)
}
}
/**
`Migration` instances encapsulate information intended to facilitate a schema migration.
A `Migration` instance is passed into a user-defined `MigrationBlock` block when updating the version of a Realm. This
instance provides access to the old and new database schemas, the objects in the Realm, and provides functionality for
modifying the Realm during the migration.
*/
public struct Migration {
// MARK: Properties
/// The old schema, describing the Realm before applying a migration.
public var oldSchema: Schema { return Schema(rlmMigration.oldSchema) }
/// The new schema, describing the Realm after applying a migration.
public var newSchema: Schema { return Schema(rlmMigration.newSchema) }
internal var rlmMigration: RLMMigration
// MARK: Altering Objects During a Migration
/**
Enumerates all the objects of a given type in this Realm, providing both the old and new versions of each object.
Properties on an object can be accessed using subscripting.
- parameter objectClassName: The name of the `Object` class to enumerate.
- parameter block: The block providing both the old and new versions of an object in this Realm.
*/
public func enumerateObjects(ofType typeName: String, _ block: MigrationObjectEnumerateBlock) {
rlmMigration.enumerateObjects(typeName) { oldObject, newObject in
block(unsafeBitCast(oldObject, to: MigrationObject.self),
unsafeBitCast(newObject, to: MigrationObject.self))
}
}
/**
Creates and returns an `Object` of type `className` in the Realm being migrated.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- parameter className: The name of the `Object` class to create.
- parameter value: The value used to populate the created object.
- returns: The newly created object.
*/
@discardableResult
public func create(_ typeName: String, value: Any = [:]) -> MigrationObject {
return unsafeBitCast(rlmMigration.createObject(typeName, withValue: value), to: MigrationObject.self)
}
/**
Deletes an object from a Realm during a migration.
It is permitted to call this method from within the block passed to `enumerate(_:block:)`.
- parameter object: An object to be deleted from the Realm being migrated.
*/
public func delete(_ object: MigrationObject) {
rlmMigration.delete(object.unsafeCastToRLMObject())
}
/**
Deletes the data for the class with the given name.
All objects of the given class will be deleted. If the `Object` subclass no longer exists in your program, any
remaining metadata for the class will be removed from the Realm file.
- parameter objectClassName: The name of the `Object` class to delete.
- returns: A Boolean value indicating whether there was any data to delete.
*/
@discardableResult
public func deleteData(forType typeName: String) -> Bool {
return rlmMigration.deleteData(forClassName: typeName)
}
/**
Renames a property of the given class from `oldName` to `newName`.
- parameter className: The name of the class whose property should be renamed. This class must be present
in both the old and new Realm schemas.
- parameter oldName: The old name for the property to be renamed. There must not be a property with this name in
the class as defined by the new Realm schema.
- parameter newName: The new name for the property to be renamed. There must not be a property with this name in
the class as defined by the old Realm schema.
*/
public func renameProperty(onType typeName: String, from oldName: String, to newName: String) {
rlmMigration.renameProperty(forClass: typeName, oldName: oldName, newName: newName)
}
internal init(_ rlmMigration: RLMMigration) {
self.rlmMigration = rlmMigration
}
}
// MARK: Private Helpers
internal func accessorMigrationBlock(_ migrationBlock: @escaping MigrationBlock) -> RLMMigrationBlock {
return { migration, oldVersion in
// set all accessor classes to MigrationObject
for objectSchema in migration.oldSchema.objectSchema {
objectSchema.accessorClass = MigrationObject.self
// isSwiftClass is always `false` for object schema generated
// from the table, but we need to pretend it's from a swift class
// (even if it isn't) for the accessors to be initialized correctly.
objectSchema.isSwiftClass = true
}
for objectSchema in migration.newSchema.objectSchema {
objectSchema.accessorClass = MigrationObject.self
}
// run migration
migrationBlock(Migration(migration), oldVersion)
}
}
// MARK: Unavailable
extension Migration {
@available(*, unavailable, renamed: "enumerateObjects(ofType:_:)")
public func enumerate(_ objectClassName: String, _ block: MigrationObjectEnumerateBlock) { fatalError() }
@available(*, unavailable, renamed: "deleteData(forType:)")
public func deleteData(_ objectClassName: String) -> Bool {
fatalError()
}
@available(*, unavailable, renamed: "renameProperty(onType:from:to:)")
public func renamePropertyForClass(_ className: String, oldName: String, newName: String) { fatalError() }
}
| mit | 5ba1a80869a88de7b0d482fdab42cd23 | 41.273585 | 131 | 0.700625 | 5.02636 | false | false | false | false |
monyschuk/CwlSignal | CwlSignal.playground/Pages/App scenario - dynamic view properties.xcplaygroundpage/Contents.swift | 1 | 3953 | /*:
# App scenario, part 2
> **This playground requires the CwlSignal.framework built by the CwlSignal_macOS scheme.** If you're seeing the error: "no such module 'CwlSignal'" follow the Build Instructions on the [Introduction](Introduction) page.
## Dynamic view properties
This page creates and maintains a view with an "Add to favorites" button that is enabled if (and only if) both of the following are true:
1. the user is logged in
2. the file selection is non-empty
The login status and the number of selected files are also displayed in the view as a checkbox and a text label. Neither of these are "real" (they cycle through states on a timer) but they should allow you to see how everything is connected and updated.
The most important part of the code are the three "dynamic properties" at the bottom of the `loadView` function. These take data provided by incoming signals and apply the result to the views.
## Using the Assistant View
To display the "view" for this playgrounds page, you should enable the Playgrounds "Timeline" Assistant View. To do this,
1. Make sure you can see Assistant Editor (from the menubar: "View" → "Assistant Editor" → "Show Assistant Editor").
2. Use the toolbar at the top of the Assistant Editor to select "Timeline" (the popup you need is to the right of the "< >" arrows but to the left of the filename/filepath.
After the page has run, you should be able to use the "timeline" slider to move forwards and backwards in time and see how the view state changed in response to the two state values.
---
*/
import Cocoa
import CwlSignal
import PlaygroundSupport
// Create an instance of our view controller
let controller = ViewController(nibName: nil, bundle: nil)!
PlaygroundPage.current.liveView = controller.view
// This is a dummy Login class. Every 1.5 seconds, it toggles login on the background thread
class Login {
let signal = intervalSignal(interval: .fromSeconds(1.5)).map { v in v % 2 == 0 }.continuous(initial: false)
}
// This is a FileSelection class. Every 0.5 seconds, it changes the number of selected files on the main thread
class FileSelection {
let signal = intervalSignal(interval: .fromSeconds(0.5), context: .main).map { v in Array<Int>(repeating: 0, count: v % 3) }.continuous(initial: Array<Int>())
}
class ViewController: NSViewController {
// Child controls
let addToFavoritesButton = NSButton(title: "Add to favorites", target: nil, action: nil)
let loggedInStatusButton = NSButton(checkboxWithTitle: "Logged In", target: nil, action: nil)
let filesSelectedLabel = NSTextField(labelWithString: "")
// Connections to model objects
let login = Login()
let fileSelection = FileSelection()
var endpoints = [Cancellable]()
override func loadView() {
// The view is an NSStackView (for layout convenience)
let view = NSStackView(frame: NSRect(x: 0, y: 0, width: 150, height: 100))
// Set static properties
view.orientation = .vertical
view.setHuggingPriority(NSLayoutPriorityRequired, for: .horizontal)
// Construct the view tree
view.addView(addToFavoritesButton, in: NSStackViewGravity.center)
view.addView(loggedInStatusButton, in: NSStackViewGravity.center)
view.addView(filesSelectedLabel, in: NSStackViewGravity.center)
view.layoutSubtreeIfNeeded()
// Configure dynamic properties
endpoints += login.signal.subscribe(context: .main) { r in
self.loggedInStatusButton.state = (r.value ?? false) ? NSOnState : NSOffState
}
endpoints += fileSelection.signal.subscribe(context: .main) { r in
self.filesSelectedLabel.stringValue = "Selected file count: \(r.value?.count ?? 0)"
}
endpoints += login.signal.combineLatest(second: fileSelection.signal) { $0 && !$1.isEmpty }.subscribe(context: .main) { result in
self.addToFavoritesButton.isEnabled = result.value ?? false
}
// Set the view
self.view = view
}
}
/*:
---
[Previous page: App scenario - threadsafe key-value storage](@previous)
*/
| isc | 0fd02b00ff667520a95e766d99f708f2 | 41.923913 | 253 | 0.748291 | 4.033708 | false | false | false | false |
housenkui/SKStruct | SKProject01/CoreDataTEst01/AppDelegate.swift | 1 | 4603 | //
// AppDelegate.swift
// CoreDataTest01
//
// Created by 侯森魁 on 2017/6/7.
// Copyright © 2017年 侯森魁. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataTest01")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 1c7094e21ffe666b4965409c2759e83f | 48.333333 | 285 | 0.68592 | 5.771069 | false | false | false | false |
daggmano/photo-management-studio | src/Client/OSX/Photo Management Studio/Photo Management Studio/NetworkMessageObject.swift | 1 | 2085 | //
// NetworkMessageObject.swift
// Photo Management Studio
//
// Created by Darren Oster on 11/02/2016.
// Copyright © 2016 Darren Oster. All rights reserved.
//
import Foundation
enum NetworkMessageType: Int {
case ServerSpecification
}
protocol INetworkMessageObject {
var messageType: NetworkMessageType? { get }
}
class NetworkMessageObject : NSObject, INetworkMessageObject, JsonProtocol {
internal private(set) var messageType: NetworkMessageType?
init(messageType: NetworkMessageType) {
self.messageType = messageType
}
required init(json: [String: AnyObject]) {
if let messageType = json["messageType"] as? Int {
self.messageType = NetworkMessageType(rawValue: messageType)
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let messageType = self.messageType {
result["messageType"] = messageType.rawValue
}
return result
}
}
class NetworkMessageObjectGeneric<T : JsonProtocol> : NSObject, INetworkMessageObject, JsonProtocol {
internal private(set) var messageType: NetworkMessageType?
internal private(set) var message: T?
init(messageType: NetworkMessageType, message: T) {
self.messageType = messageType
self.message = message
}
required init(json: [String: AnyObject]) {
if let messageType = json["messageType"] as? Int {
self.messageType = NetworkMessageType(rawValue: messageType)
}
if let message = json["message"] as? [String: AnyObject] {
let m = T(json: message)
print(m)
self.message = T(json: message)
}
}
func toJSON() -> [String: AnyObject] {
var result = [String: AnyObject]()
if let messageType = self.messageType {
result["messageType"] = messageType.rawValue
}
if let message = self.message {
result["message"] = message.toJSON()
}
return result
}
}
| mit | fc089945e5cdc316c1a664d8bceb226b | 26.786667 | 101 | 0.622841 | 4.846512 | false | false | false | false |
sucrewar/SwiftUEx | SwiftEx/Classes/DefaultFonts.swift | 1 | 749 | //
// DefaultFonts.swift
// smiity
//
// Created by Diogo Grilo on 28/08/15.
// Copyright © 2015 Diogo Grilo. All rights reserved.
//
import UIKit
public extension UILabel {
var substituteFontName: String {
get { return self.font.fontName }
set {
if self.font.fontName != newValue {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
public func setFontSize (size: CGFloat) {
self.font = UIFont(name: self.font.fontName, size: size)
}
public func setFontIcon (fontName: String) {
self.substituteFontName = fontName
}
public func setFontIconwhitName (name: String) {
self.substituteFontName = name
}
}
| mit | da54bbf10c659155359dc94207ebe6ca | 21.666667 | 77 | 0.608289 | 4.043243 | false | false | false | false |
rnystrom/GitHawk | Local Pods/SwipeCellKit/Source/Swipeable.swift | 2 | 625 | //
// Swipeable.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
// MARK: - Internal
protocol Swipeable {
var actionsView: SwipeActionsView? { get }
var state: SwipeState { get }
var frame: CGRect { get }
}
extension SwipeTableViewCell: Swipeable {}
enum SwipeState: Int {
case center = 0
case left
case right
case dragging
case animatingToCenter
init(orientation: SwipeActionsOrientation) {
self = orientation == .left ? .left : .right
}
var isActive: Bool { return self != .center }
}
| mit | d43bc16147d06615d277dd7e90167a44 | 17.352941 | 54 | 0.633013 | 4.273973 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/TableView/TableController.swift | 1 | 2953 | import UIKit
class TableController: NSObject, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
}
var sections = [TableSectionProtocol]() {
didSet { reload() }
}
func reload() {
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection index: Int) -> Int {
guard let section = section(for: index) else { return 0 }
return section.numberOfRows()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection index: Int) -> String? {
guard self.tableView(tableView, viewForHeaderInSection: index) == nil else { return nil }
guard let section = section(for: index) as? TableSection else { return nil }
return section.name
}
func tableView(_ tableView: UITableView, viewForHeaderInSection index: Int) -> UIView? {
guard let section = section(for: index) else { return nil }
return section.headerView()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection index: Int) -> CGFloat {
guard let sections = section(for: index) else { return 0 }
return sections.headerHeight()
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
guard let item = item(for: indexPath) else { return false }
return item.shouldHighlight()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = item(for: indexPath) else { return }
tableView.deselectRow(at: indexPath, animated: true)
item.selectionBlock?()
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let item = item(for: indexPath) {
return item.estimatedCellHeight
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = item(for: indexPath) else {
assertionFailure("failed to get item for \(indexPath)")
return UITableViewCell()
}
return item.cell(tableView: tableView, indexPath: indexPath)
}
// MARK: - Utility
func section(for index: Int) -> TableSectionProtocol? {
guard sections.count > index else { return nil }
return sections[index]
}
func item(for indexPath: IndexPath) -> TableItem? {
guard let section = section(for: indexPath.section) as? TableSection else { return nil }
guard section.items.count > indexPath.row else { return nil }
return section.items[indexPath.row]
}
}
| mit | d4837b9699b97088e3bb5d4532ae18ff | 34.578313 | 103 | 0.659329 | 5.126736 | false | false | false | false |
abelsanchezali/ViewBuilder | ViewBuilderDemo/ViewBuilderDemo/ViewControllers/Card3CollectionViewCell.swift | 1 | 2613 | //
// Card3CollectionViewCell.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 8/4/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
import ViewBuilder
public class Card3CollectionViewCell: UICollectionViewCell, DataSourceReceiverProtocol {
static let shared = Card3CollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
var summaryLabel: UILabel!
var insightLabel: UILabel!
var imageView: UIView!
var button: UIButton!
public override init(frame: CGRect) {
super.init(frame: frame)
self.margin = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
if !self.contentView.loadFromDocument(Constants.bundle.path(forResource: "SampleCard3", ofType: "xml")!) {
fatalError("Ups!!!")
}
summaryLabel = self.contentView.documentReferences!["summaryLabel"] as! UILabel
insightLabel = self.contentView.documentReferences!["insightLabel"] as! UILabel
imageView = self.contentView.documentReferences!["imageView"] as! UIView
button = self.contentView.documentReferences!["button"] as! UIButton
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var dataSource: AnyObject? = nil {
didSet {
let dataSource = self.dataSource as? ViewModel
let summary = dataSource?["summary"] as? String
let insight = dataSource?["insight"] as? String
let mode = dataSource?["mode"] as? Int ?? 0
summaryLabel.text = summary
insightLabel.text = insight
imageView.backgroundColor = Converter.intToColor(mode)
}
}
}
extension Card3CollectionViewCell: CollectionViewCellProtocol {
public static func measureForFitSize(_ size: CGSize, dataSource: AnyObject?) -> CGSize {
shared.translatesAutoresizingMaskIntoConstraints = false
shared.contentView.translatesAutoresizingMaskIntoConstraints = false
shared.dataSource = dataSource
let width = size.width - shared.margin.left - shared.margin.right
let measure = shared.contentView.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
return measure
}
}
extension Card3CollectionViewCell: DocumentAssociatedProtocol {
public var associatedDocumentPath: String? { return Constants.bundle.path(forResource: "SampleCard3", ofType: "xml") }
}
| mit | 24d1262c6ae84967a69163721ba9c26b | 39.8125 | 215 | 0.691424 | 4.928302 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK | LGKKCoreLib/LGKKCoreLib/Modules/SPExtensions/UIWindow+SPExtension.swift | 1 | 1814 | //
// UIWindow+Extension.swift
// spDirect
//
// Created by Admin on 2/17/17.
// Copyright © 2017 SiliconPrime. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public extension UIWindow {
public func sp_set(rootViewController newRootViewController: UIViewController,
withTransition transition: CATransition? = nil) {
let previousViewController = rootViewController
if let transition = transition {
// Add the transition
layer.add(transition, forKey: kCATransition)
}
rootViewController = newRootViewController
// Update status bar appearance using the new view controllers appearance - animate if needed
if UIView.areAnimationsEnabled {
UIView.animate(withDuration: CATransaction.animationDuration()) {
newRootViewController.setNeedsStatusBarAppearanceUpdate()
}
} else {
newRootViewController.setNeedsStatusBarAppearanceUpdate()
}
/* The presenting view controllers view doesn't get removed from the window
as its currently transistioning and presenting a view controller */
if let transitionViewClass = NSClassFromString("UITransitionView") {
for subview in subviews where subview.isKind(of: transitionViewClass) {
subview.removeFromSuperview()
}
}
if let previousViewController = previousViewController {
// Allow the view controller to be deallocated
previousViewController.dismiss(animated: false) {
// Remove the root view in case its still showing
previousViewController.view.removeFromSuperview()
}
}
}
}
| mit | 779c1be06dfc4c1f1b17bba176d7087e | 35.26 | 101 | 0.644788 | 6.208904 | false | false | false | false |
zisko/swift | test/SILGen/keypaths.swift | 1 | 12735 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
struct S<T> {
var x: T
let y: String
var z: C<T>
var computed: C<T> { fatalError() }
var observed: C<T> { didSet { fatalError() } }
var reabstracted: () -> ()
}
class C<T> {
final var x: T
final let y: String
final var z: S<T>
var nonfinal: S<T>
var computed: S<T> { fatalError() }
var observed: S<T> { didSet { fatalError() } }
final var reabstracted: () -> ()
init() { fatalError() }
}
protocol P {
var x: Int { get }
var y: String { get set }
}
extension P {
var z: String {
return y
}
var w: String {
get { return "" }
nonmutating set { }
}
}
// CHECK-LABEL: sil hidden @{{.*}}storedProperties
func storedProperties<T>(_: T) {
// CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \S<T>.x
// CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T>
_ = \S<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \S<T>.z.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = \C<T>.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.y
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = \C<T>.z.x
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = \C<T>.z.z.y
}
// CHECK-LABEL: sil hidden @{{.*}}computedProperties
func computedProperties<T: P>(_: T) {
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$S8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @$S8keypaths1CC8nonfinalAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>, @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.nonfinal
// CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: gettable_property $S<τ_0_0>,
// CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$S8keypaths1CC8computedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>
// CHECK-SAME: ) <T>
_ = \C<T>.computed
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @$S8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out S<τ_0_0>,
// CHECK-SAME: setter @$S8keypaths1CC8observedAA1SVyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>, @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.observed
_ = \C<T>.nonfinal.x
_ = \C<T>.computed.x
_ = \C<T>.observed.x
_ = \C<T>.z.computed
_ = \C<T>.z.observed
_ = \C<T>.observed.x
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##C.reabstracted,
// CHECK-SAME: getter @$S8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>) -> @out @callee_guaranteed (@in ()) -> @out (),
// CHECK-SAME: setter @$S8keypaths1CC12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in @callee_guaranteed (@in ()) -> @out (), @in C<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \C<T>.reabstracted
// CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>,
// CHECK-SAME: id @$S8keypaths1SV8computedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @$S8keypaths1SV8computedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out C<τ_0_0>
// CHECK-SAME: ) <T>
_ = \S<T>.computed
// CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $C<τ_0_0>,
// CHECK-SAME: id @$S8keypaths1SV8observedAA1CCyxGvg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @$S8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out C<τ_0_0>,
// CHECK-SAME: setter @$S8keypaths1SV8observedAA1CCyxGvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in C<τ_0_0>, @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.observed
_ = \S<T>.z.nonfinal
_ = \S<T>.z.computed
_ = \S<T>.z.observed
_ = \S<T>.computed.x
_ = \S<T>.computed.y
// CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##S.reabstracted,
// CHECK-SAME: getter @$S8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in S<τ_0_0>) -> @out @callee_guaranteed (@in ()) -> @out (),
// CHECK-SAME: setter @$S8keypaths1SV12reabstractedyycvpAA1PRzlACyxGTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in @callee_guaranteed (@in ()) -> @out (), @inout S<τ_0_0>) -> ()
// CHECK-SAME: ) <T>
_ = \S<T>.reabstracted
// CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $Int,
// CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int,
// CHECK-SAME: getter @$S8keypaths1PP1xSivpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out Int
// CHECK-SAME: ) <T>
_ = \T.x
// CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: settable_property $String,
// CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String,
// CHECK-SAME: getter @$S8keypaths1PP1ySSvpAaBRzlxTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out String,
// CHECK-SAME: setter @$S8keypaths1PP1ySSvpAaBRzlxTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in String, @inout τ_0_0) -> ()
// CHECK-SAME: ) <T>
_ = \T.y
// CHECK: keypath $KeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @$S8keypaths1PPAAE1zSSvg
_ = \T.z
}
struct Concrete: P {
var x: Int
var y: String
}
// CHECK-LABEL: sil hidden @$S8keypaths35keyPathsWithSpecificGenericInstanceyyF
func keyPathsWithSpecificGenericInstance() {
// CHECK: keypath $KeyPath<Concrete, String>, (
// CHECK-SAME: gettable_property $String,
// CHECK-SAME: id @$S8keypaths1PPAAE1zSSvg
// CHECK-SAME: getter @$S8keypaths1PPAAE1zSSvpAA8ConcreteVTK : $@convention(thin) (@in Concrete) -> @out String
_ = \Concrete.z
_ = \S<Concrete>.computed
}
class AA<T> {
var a: Int { get { return 0 } set { } }
}
class BB<U, V>: AA<V> {
}
func keyPathForInheritedMember() {
_ = \BB<Int, String>.a
}
func keyPathForExistentialMember() {
_ = \P.x
_ = \P.y
_ = \P.z
_ = \P.w
}
struct OptionalFields {
var x: S<Int>?
}
struct OptionalFields2 {
var y: OptionalFields?
}
// CHECK-LABEL: sil hidden @$S8keypaths18keyPathForOptionalyyF
func keyPathForOptional() {
// CHECK: keypath $WritableKeyPath<OptionalFields, S<Int>>, (
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>;
// CHECK-SAME: optional_force : $S<Int>)
_ = \OptionalFields.x!
// CHECK: keypath $KeyPath<OptionalFields, Optional<String>>, (
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>;
// CHECK-SAME: optional_chain : $S<Int>;
// CHECK-SAME: stored_property #S.y : $String;
// CHECK-SAME: optional_wrap : $Optional<String>)
_ = \OptionalFields.x?.y
// CHECK: keypath $KeyPath<OptionalFields2, Optional<S<Int>>>, (
// CHECK-SAME: root $OptionalFields2;
// CHECK-SAME: stored_property #OptionalFields2.y : $Optional<OptionalFields>;
// CHECK-SAME: optional_chain : $OptionalFields;
// CHECK-SAME: stored_property #OptionalFields.x : $Optional<S<Int>>)
_ = \OptionalFields2.y?.x
}
class StorageQualified {
weak var tooWeak: StorageQualified?
unowned var disowned: StorageQualified
init() { fatalError() }
}
final class FinalStorageQualified {
weak var tooWeak: StorageQualified?
unowned var disowned: StorageQualified
init() { fatalError() }
}
// CHECK-LABEL: sil hidden @{{.*}}keyPathForStorageQualified
func keyPathForStorageQualified() {
// CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, Optional<StorageQualified>>,
// CHECK-SAME: settable_property $Optional<StorageQualified>, id #StorageQualified.tooWeak!getter.1
_ = \StorageQualified.tooWeak
// CHECK: = keypath $ReferenceWritableKeyPath<StorageQualified, StorageQualified>,
// CHECK-SAME: settable_property $StorageQualified, id #StorageQualified.disowned!getter.1
_ = \StorageQualified.disowned
// CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, Optional<StorageQualified>>,
// CHECK-SAME: settable_property $Optional<StorageQualified>, id ##FinalStorageQualified.tooWeak
_ = \FinalStorageQualified.tooWeak
// CHECK: = keypath $ReferenceWritableKeyPath<FinalStorageQualified, StorageQualified>,
// CHECK-SAME: settable_property $StorageQualified, id ##FinalStorageQualified.disowned
_ = \FinalStorageQualified.disowned
}
struct IUOProperty {
var iuo: IUOBlob!
}
struct IUOBlob {
var x: Int
subscript(y: String) -> String {
get { return y }
set {}
}
}
// CHECK-LABEL: sil hidden @{{.*}}11iuoKeyPaths
func iuoKeyPaths() {
// CHECK: = keypath $WritableKeyPath<IUOProperty, Int>,
// CHECK-SAME: stored_property #IUOProperty.iuo
// CHECK-SAME: optional_force
// CHECK-SAME: stored_property #IUOBlob.x
_ = \IUOProperty.iuo.x
// CHECK: = keypath $WritableKeyPath<IUOProperty, Int>,
// CHECK-SAME: stored_property #IUOProperty.iuo
// CHECK-SAME: optional_force
// CHECK-SAME: stored_property #IUOBlob.x
_ = \IUOProperty.iuo!.x
}
class Bass: Hashable {
static func ==(_: Bass, _: Bass) -> Bool { return false }
var hashValue: Int { return 0 }
}
class Treble: Bass { }
struct Subscripts<T> {
subscript() -> T {
get { fatalError() }
set { fatalError() }
}
subscript(generic x: T) -> T {
get { fatalError() }
set { fatalError() }
}
subscript(concrete x: String) -> String {
get { fatalError() }
set { fatalError() }
}
subscript(x: String, y: String) -> String {
get { fatalError() }
set { fatalError() }
}
subscript<U>(subGeneric z: U) -> U {
get { fatalError() }
set { fatalError() }
}
subscript(mutable x: T) -> T {
get { fatalError() }
set { fatalError() }
}
subscript(bass: Bass) -> Bass {
get { return bass }
set { }
}
}
// CHECK-LABEL: sil hidden @{{.*}}10subscripts
func subscripts<T: Hashable, U: Hashable>(x: T, y: U, s: String) {
_ = \Subscripts<T>.[]
_ = \Subscripts<T>.[generic: x]
_ = \Subscripts<T>.[concrete: s]
_ = \Subscripts<T>.[s, s]
_ = \Subscripts<T>.[subGeneric: s]
_ = \Subscripts<T>.[subGeneric: x]
_ = \Subscripts<T>.[subGeneric: y]
_ = \Subscripts<U>.[]
_ = \Subscripts<U>.[generic: y]
_ = \Subscripts<U>.[concrete: s]
_ = \Subscripts<U>.[s, s]
_ = \Subscripts<U>.[subGeneric: s]
_ = \Subscripts<U>.[subGeneric: x]
_ = \Subscripts<U>.[subGeneric: y]
_ = \Subscripts<String>.[]
_ = \Subscripts<String>.[generic: s]
_ = \Subscripts<String>.[concrete: s]
_ = \Subscripts<String>.[s, s]
_ = \Subscripts<String>.[subGeneric: s]
_ = \Subscripts<String>.[subGeneric: x]
_ = \Subscripts<String>.[subGeneric: y]
_ = \Subscripts<T>.[s, s].count
_ = \Subscripts<T>.[Bass()]
_ = \Subscripts<T>.[Treble()]
}
| apache-2.0 | c16b1bbb0f7d89d3289db7990cd2be2f | 36.33432 | 188 | 0.615342 | 2.864699 | false | false | false | false |
pseudomuto/CircuitBreaker | Pod/Classes/HalfOpenState.swift | 1 | 1243 | //
// HalfOpenState.swift
// Pods
//
// Created by David Muto on 2016-02-05.
//
//
class HalfOpenState: BaseState {
let successThreshold: Int
let invocationTimeout: NSTimeInterval
private(set) var successes: Int
private var running: Int32 = 0
init(_ breakerSwitch: Switch, invoker: Invoker, successThreshold: Int, invocationTimeout: NSTimeInterval) {
self.successThreshold = successThreshold
self.invocationTimeout = invocationTimeout
self.successes = 0
super.init(breakerSwitch, invoker: invoker)
}
override func type() -> StateType {
return .HalfOpen
}
override func activate() {
synchronized {
self.running = 0
self.successes = 0
}
}
override func onSuccess() {
synchronized {
self.running = 0
self.successes++
if self.successes == self.successThreshold {
self.breakerSwitch.reset(self)
}
}
}
override func onError() {
breakerSwitch.trip(self)
}
override func invoke<T>(block: () throws -> T) throws -> T {
if OSAtomicCompareAndSwap32(0, 1, &running) {
return try invoker.invoke(self, timeout: invocationTimeout, block: block)
}
throw Error.OpenCircuit
}
}
| mit | 98280d9d6dff75d484cf42734ee8bcc4 | 20.807018 | 109 | 0.645213 | 4.185185 | false | false | false | false |
ronaldmak/ZFRippleButton | Classes/ZFRippleButton.swift | 1 | 6522 | //
// ZFRippleButton.swift
// ZFRippleButtonDemo
//
// Created by Amornchai Kanokpullwad on 6/26/14.
// Copyright (c) 2014 zoonref. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class ZFRippleButton: UIButton {
@IBInspectable var ripplePercent: Float = 0.8 {
didSet {
setupRippleView()
}
}
@IBInspectable var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) {
didSet {
rippleView.backgroundColor = rippleColor
}
}
@IBInspectable var rippleBackgroundColor: UIColor = UIColor(white: 0.95, alpha: 1) {
didSet {
rippleBackgroundView.backgroundColor = rippleBackgroundColor
}
}
@IBInspectable var buttonCornerRadius: Float = 0 {
didSet{
layer.cornerRadius = CGFloat(buttonCornerRadius)
}
}
@IBInspectable var rippleOverBounds: Bool = false
@IBInspectable var shadowRippleRadius: Float = 1
@IBInspectable var shadowRippleEnable: Bool = true
@IBInspectable var trackTouchLocation: Bool = false
@IBInspectable var touchUpAnimationTime: Double = 0.6
let rippleView = UIView()
let rippleBackgroundView = UIView()
private var tempShadowRadius: CGFloat = 0
private var tempShadowOpacity: Float = 0
private var touchCenterLocation: CGPoint?
private var rippleMask: CAShapeLayer? {
get {
if !rippleOverBounds {
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius).CGPath
return maskLayer
} else {
return nil
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
setupRippleView()
rippleBackgroundView.backgroundColor = rippleBackgroundColor
rippleBackgroundView.frame = bounds
layer.addSublayer(rippleBackgroundView.layer)
rippleBackgroundView.layer.addSublayer(rippleView.layer)
rippleBackgroundView.alpha = 0
layer.shadowRadius = 0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor(white: 0.0, alpha: 0.5).CGColor
}
private func setupRippleView() {
let size: CGFloat = CGRectGetWidth(bounds) * CGFloat(ripplePercent)
let x: CGFloat = (CGRectGetWidth(bounds)/2) - (size/2)
let y: CGFloat = (CGRectGetHeight(bounds)/2) - (size/2)
let corner: CGFloat = size/2
rippleView.backgroundColor = rippleColor
rippleView.frame = CGRectMake(x, y, size, size)
rippleView.layer.cornerRadius = corner
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
if trackTouchLocation {
touchCenterLocation = touch.locationInView(self)
} else {
touchCenterLocation = nil
}
UIView.animateWithDuration(0.1,
animations: {
self.rippleBackgroundView.alpha = 1
}, completion: nil)
rippleView.transform = CGAffineTransformMakeScale(0.5, 0.5)
UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseOut,
animations: {
self.rippleView.transform = CGAffineTransformIdentity
}, completion: nil)
if shadowRippleEnable {
tempShadowRadius = layer.shadowRadius
tempShadowOpacity = layer.shadowOpacity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = shadowRippleRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = 1
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.removedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
layer.addAnimation(groupAnim, forKey:"shadow")
}
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override func cancelTrackingWithEvent(event: UIEvent?) {
super.cancelTrackingWithEvent(event)
animateToNormal()
}
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
super.endTrackingWithTouch(touch, withEvent: event)
animateToNormal()
}
private func animateToNormal() {
UIView.animateWithDuration(0.1,
animations: {
self.rippleBackgroundView.alpha = 1
},
completion: {(success: Bool) -> () in
UIView.animateWithDuration(self.touchUpAnimationTime,
animations: {
self.rippleBackgroundView.alpha = 0
}, completion: nil)
}
)
UIView.animateWithDuration(0.7, delay: 0,
options: [.CurveEaseOut, .BeginFromCurrentState],
animations: {
self.rippleView.transform = CGAffineTransformIdentity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = self.tempShadowRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = self.tempShadowOpacity
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.removedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
self.layer.addAnimation(groupAnim, forKey:"shadowBack")
}, completion: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
setupRippleView()
if let knownTouchCenterLocation = touchCenterLocation {
rippleView.center = knownTouchCenterLocation
}
rippleBackgroundView.layer.frame = bounds
rippleBackgroundView.layer.mask = rippleMask
}
}
| mit | b24f2af03e325638eade0288e4eb5020 | 32.27551 | 93 | 0.59583 | 5.574359 | false | false | false | false |
natmark/ProcessingKit | ProcessingKit/Core/Context/Context.swift | 1 | 1013 | //
// Context.swift
// ProcessingKit
//
// Created by AtsuyaSato on 2017/12/31.
// Copyright © 2017年 Atsuya Sato. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
public typealias UIColor = NSColor
public typealias UIImageView = NSImageView
public typealias UIImage = NSImage
public typealias UIViewController = NSViewController
public typealias UITouch = NSTouch
public typealias UIFont = NSFont
public typealias UIEvent = NSEvent
public typealias UIView = NSView
public typealias UIResponder = NSResponder
public typealias CGRect = NSRect
public typealias CGPoint = NSPoint
#endif
public protocol ContextComponenetsContract {
var context: CGContext? { get }
}
public class ContextComponents: ContextComponenetsContract {
public init() {
}
public var context: CGContext? {
#if os(iOS)
return UIGraphicsGetCurrentContext()
#elseif os(OSX)
return NSGraphicsContext.current?.cgContext
#endif
}
}
| mit | 12e317cc27c12c88582ba96503b7a905 | 22.488372 | 60 | 0.741584 | 4.633028 | false | false | false | false |
TTVS/NightOut | Clubber/AddToMenuVC.swift | 1 | 2246 | //
// MenuTableViewController.swift
// Clubber
//
// Created by Terra on 8/2/15.
// Copyright (c) 2015 Dino Media Asia. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
var menuItems = ["Feed", "Activity", "Create", "Messenger", "My ID"]
var currentItem = "Feed"
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return menuItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MenuTableViewCell
// Configure the cell...
cell.titleLabel.text = menuItems[indexPath.row]
cell.titleLabel.textColor = (menuItems[indexPath.row] == currentItem) ? UIColor.whiteColor() : UIColor.grayColor()
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let menuTableViewController = segue.sourceViewController as! MenuTableViewController
if let selectedRow = menuTableViewController.tableView.indexPathForSelectedRow?.row {
currentItem = menuItems[selectedRow]
}
}
}
| apache-2.0 | 21c34b806401bf963407b8511b3c9742 | 28.552632 | 122 | 0.677204 | 5.744246 | false | false | false | false |
objecthub/swift-lispkit | Sources/LispKit/Compiler/RuntimeError.swift | 1 | 27406 | //
// RuntimeError.swift
// LispKit
//
// Created by Matthias Zenger on 20/11/2015.
// Copyright © 2015-2022 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
///
/// Class `RuntimeError` defines a universal representation of errors in LispKit. A runtime
/// error consists of the following components:
/// - `pos`: The position of the error in some source code (if available)
/// - `descriptor`: A structured descriptor of the error
/// - `irritants`: An array of expressions that the descriptor may refer to
/// - `stackTrace`: An optional stack trace in terms of the invoked LispKit functions
///
public class RuntimeError: Error, Hashable, CustomStringConvertible {
public let pos: SourcePosition
public let descriptor: ErrorDescriptor
public let irritants: [Expr]
public private(set) var library: Expr?
public private(set) var stackTrace: [Procedure]?
public private(set) var callTrace: [String]?
internal init(_ pos: SourcePosition,
_ descriptor: ErrorDescriptor,
_ irritants: [Expr],
stackTrace: [Procedure]? = nil,
callTrace: [String]? = nil) {
self.pos = pos
self.descriptor = descriptor
self.irritants = irritants
self.stackTrace = stackTrace
self.callTrace = callTrace
}
public class func lexical(_ error: LexicalError,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.lexical(error), [])
}
public class func syntax(_ error: SyntaxError,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.syntax(error), [])
}
public class func type(_ expr: Expr,
expected: Set<Type>,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.type(expr.type, expected), [expr])
}
public class func range(parameter: Int? = nil,
of: String? = nil,
_ expr: Expr,
min: Int64 = Int64.min,
max: Int64 = Int64.max,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.range(of, parameter, min, max), [expr])
}
public class func argumentCount(of: String? = nil,
min: Int = 0,
max: Int = Int.max,
expr: Expr,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
guard case .pair(let fun, let args) = expr else {
return RuntimeError.argumentCount(of: of, min: min, max: max, args: expr, at: pos)
}
if of == nil, case .symbol(let sym) = fun {
return RuntimeError.argumentCount(
of: sym.description, min: min, max: max, args: args, at: pos)
}
return RuntimeError.argumentCount(of: of, min: min, max: max, args: args, at: pos)
}
public class func argumentCount(of: String? = nil,
min: Int = 0,
max: Int = Int.max,
args: Expr,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos,
ErrorDescriptor.argumentCount(of, min, max),
[.makeNumber(args.toExprs().0.count), args])
}
public class func argumentCount(of: String? = nil,
num: Int,
expr: Expr,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
guard case .pair(let fun, let args) = expr else {
return RuntimeError.argumentCount(of: of, num: num, args: expr, at: pos)
}
if of == nil, case .symbol(let sym) = fun {
return RuntimeError.argumentCount(of: sym.description, num: num, args: args, at: pos)
}
return RuntimeError.argumentCount(of: of, num: num, args: args, at: pos)
}
public class func argumentCount(of: String? = nil,
num: Int,
args: Expr,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos,
ErrorDescriptor.argumentCount(of, num, num),
[.makeNumber(args.toExprs().0.count), args])
}
public class func eval(_ error: EvalError,
_ irritants: Expr...,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.eval(error), irritants)
}
public class func os(_ error: Error,
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(pos, ErrorDescriptor.os(error), [])
}
public class func abortion(at pos: SourcePosition = SourcePosition.unknown,
stackTrace: [Procedure]? = nil,
callTrace: [String]? = nil) -> RuntimeError {
return RuntimeError(pos,
ErrorDescriptor.abortion,
[],
stackTrace: stackTrace,
callTrace: callTrace)
}
public class func uncaught(_ expr: Expr,
at pos: SourcePosition = SourcePosition.unknown,
stackTrace: [Procedure]? = nil,
callTrace: [String]? = nil) -> RuntimeError {
// TODO: figure out if we want uncaught of uncaught exceptions?
return RuntimeError(pos,
ErrorDescriptor.uncaught,
[expr],
stackTrace: stackTrace,
callTrace: callTrace)
}
public class func custom(_ kind: String,
_ template: String,
_ irritants: [Expr],
at pos: SourcePosition = SourcePosition.unknown) -> RuntimeError {
return RuntimeError(SourcePosition.unknown, ErrorDescriptor.custom(kind, template), irritants)
}
public func at(_ pos: SourcePosition) -> RuntimeError {
return RuntimeError(pos,
self.descriptor,
self.irritants,
stackTrace: self.stackTrace,
callTrace: self.callTrace)
}
@discardableResult public func attach(callTrace: [String]?) -> RuntimeError {
if self.callTrace == nil {
self.callTrace = callTrace
}
return self
}
@discardableResult public func attach(vm: VirtualMachine,
current: Procedure? = nil) -> RuntimeError {
if self.stackTrace == nil {
self.stackTrace = vm.getStackTrace(current: current)
}
if self.callTrace == nil {
self.callTrace = vm.getCallTraceInfo(current: current)
}
return self
}
@discardableResult public func attach(stackTrace: [Procedure]) -> RuntimeError {
if self.stackTrace == nil {
self.stackTrace = stackTrace
}
return self
}
@discardableResult public func attach(library: Expr) -> RuntimeError {
if self.library == nil {
self.library = library
}
return self
}
public func hash(into hasher: inout Hasher) {
for irritant in self.irritants {
hasher.combine(irritant)
}
hasher.combine(self.descriptor)
hasher.combine(self.pos)
}
public var message: String {
var usedIrritants = Set<Int>()
return self.replacePlaceholders(in: self.descriptor.messageTemplate,
with: self.irritants,
recordingUsage: &usedIrritants)
}
public var description: String {
var usedIrritants = Set<Int>()
let message = self.replacePlaceholders(in: self.descriptor.messageTemplate,
with: self.irritants,
recordingUsage: &usedIrritants)
var builder = StringBuilder(prefix: "[\(self.descriptor.typeDescription)] \(message)",
postfix: "",
separator: ", ",
initial: ": ")
for index in self.irritants.indices {
if !usedIrritants.contains(index) {
builder.append(self.irritants[index].description)
}
}
return builder.description
}
public var inlineDescription: String {
var usedIrritants = Set<Int>()
let message = self.replacePlaceholders(in: self.descriptor.messageTemplate,
with: self.irritants,
recordingUsage: &usedIrritants)
return "\(self.descriptor.typeDescription): \(message)"
}
public func printableDescription(context: Context,
typeOpen: String? = "[",
typeClose: String = "] ",
irritantHeader: String? = "\nirritants: ",
irritantSeparator: String = ", ",
positionHeader: String? = "\nat: ",
libraryHeader: String? = "\nlibrary: ",
stackTraceHeader: String? = "\ncall trace: ",
stackTraceSeparator: String = ", ") -> String {
if self.descriptor == .uncaught,
self.irritants.count == 1,
case .error(let err) = self.irritants.first! {
let message: String
if let typeOpen = typeOpen {
message = "\(typeOpen)\(self.descriptor.typeDescription)\(typeClose)"
} else {
message = "\(self.descriptor.typeDescription): "
}
return message +
err.printableDescription(context: context,
typeOpen: typeOpen,
typeClose: typeClose,
irritantHeader: irritantHeader,
irritantSeparator: irritantSeparator,
positionHeader: positionHeader,
libraryHeader: libraryHeader,
stackTraceHeader: stackTraceHeader,
stackTraceSeparator: stackTraceSeparator)
}
var usedIrritants = Set<Int>()
var message = self.replacePlaceholders(in: self.descriptor.messageTemplate,
with: self.irritants,
recordingUsage: &usedIrritants)
if let typeOpen = typeOpen {
message = "\(typeOpen)\(self.descriptor.typeDescription)\(typeClose)\(message)"
}
var builder = StringBuilder(prefix: message, postfix: "", separator: "\n", initial: "")
if let irritantHeader = irritantHeader {
var irritantBuilder = StringBuilder(prefix: "",
postfix: "",
separator: irritantSeparator,
initial: irritantHeader)
var count = 0
for index in self.irritants.indices {
if !usedIrritants.contains(index) {
count += 1
irritantBuilder.append(self.irritants[index].description)
}
}
if count > 0 {
builder.append(irritantBuilder.description)
}
}
if let positionHeader = positionHeader, !self.pos.isUnknown {
if let filename = context.sources.sourcePath(for: pos.sourceId) {
builder.append("\(positionHeader)\(self.pos.description):\(filename)")
} else {
builder.append("\(positionHeader)\(self.pos.description)")
}
}
if let libraryHeader = libraryHeader,
let libraryName = self.library?.description {
builder.append("\(libraryHeader)\(libraryName)")
}
if let stackTraceHeader = stackTraceHeader, self.callTrace != nil || self.stackTrace != nil {
builder = StringBuilder(prefix: builder.description,
postfix: "",
separator: stackTraceSeparator,
initial: stackTraceHeader)
if let callTrace = self.callTrace {
for call in callTrace {
builder.append(call)
}
if let stackTrace = self.stackTrace, stackTrace.count > callTrace.count {
if stackTrace.count == callTrace.count + 1 {
builder.append("+1 call")
} else {
builder.append("+\(stackTrace.count - callTrace.count) calls")
}
}
} else if let stackTrace = self.stackTrace {
for proc in stackTrace {
builder.append(proc.name)
}
}
}
return builder.description
}
/// This method assumes the string contains variables of the form `$n` where `n` is a
/// variable index into the array `values`. It replaces occurences of `$n` with the value at
/// index `n`. If there is no such value or the index is not well-formed, the variable
/// reference remains in the string.
/// It is possible to terminate parsing the index `n` by using "~". For instance, "$0~1" gets
/// expanded into "zero1" assuming that "zero" is the value for variable `0`.
/// It is possible to escape both "$" and "~" by prefixing the characters with "$". For
/// instance, "$$0" gets expanded into "$0".
/// It is possible to use placeholders of the form `$,n` for embedding a value using
/// an unescaped string representation of the value.
private func replacePlaceholders(in template: String,
with values: [Expr],
recordingUsage used: inout Set<Int>) -> String {
var res: String = ""
var variable: String = ""
var parsingVariable = false
var embedVariable = false
for ch in template {
if parsingVariable {
switch ch {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
variable.append(ch)
continue
case "~":
if variable.isEmpty {
if embedVariable {
res.append("$,~")
} else {
res.append(ch)
}
parsingVariable = false
embedVariable = false
continue
}
case "$":
if variable.isEmpty {
if embedVariable {
res.append("$,$")
} else {
res.append(ch)
}
parsingVariable = false
embedVariable = false
continue
}
case ",":
if variable.isEmpty {
if embedVariable {
res.append("$,,")
parsingVariable = false
embedVariable = false
} else {
embedVariable = true
}
continue
}
default:
if variable.isEmpty {
res.append("$")
if embedVariable {
res.append(",")
}
res.append(ch)
parsingVariable = false
embedVariable = false
continue
}
break
}
let varNum = Int(variable)
if varNum != nil && varNum! >= 0 && varNum! < values.count {
if embedVariable {
res.append(values[varNum!].unescapedDescription)
} else {
res.append(values[varNum!].description)
}
used.insert(varNum!)
variable = ""
parsingVariable = false
embedVariable = false
} else {
res.append("$")
if embedVariable {
res.append(",")
}
res.append(variable)
variable = ""
parsingVariable = false
embedVariable = false
if ch == "~" {
res.append("~")
continue
}
}
if ch == "$" {
parsingVariable = true
} else if ch != "~" {
res.append(ch)
}
} else if ch == "$" {
parsingVariable = true
} else {
res.append(ch)
}
}
if parsingVariable {
let varNum = Int(variable)
if varNum != nil && varNum! >= 0 && varNum! < values.count {
var value = values[varNum!]
if embedVariable {
switch value {
case .pair(_, _):
var builder = StringBuilder(prefix: "", postfix: "", separator: ", ")
while case .pair(let car, let cdr) = value {
builder.append(car.unescapedDescription)
value = cdr
}
res.append(builder.description)
if !value.isNull {
res.append(" (")
res.append(value.unescapedDescription)
res.append(")")
}
default:
res.append(value.unescapedDescription)
}
} else {
res.append(value.description)
}
used.insert(varNum!)
} else {
res.append("$")
if embedVariable {
res.append(",")
}
res.append(variable)
}
}
return res
}
public static func ==(_ lhs: RuntimeError, _ rhs: RuntimeError) -> Bool {
return lhs.pos == rhs.pos &&
lhs.descriptor == rhs.descriptor &&
lhs.irritants == rhs.irritants &&
(lhs.stackTrace == nil && rhs.stackTrace == nil ||
lhs.stackTrace != nil && rhs.stackTrace != nil && lhs.stackTrace! == rhs.stackTrace!)
}
}
///
/// An `ErrorDescriptor` value describes an error in a structured way. Error descriptors may
/// not encapsulate expressions, but their textual description may refer to them via the reference
/// `$n` or `$,n` (see method `replacePlaceholders` above).
///
public enum ErrorDescriptor: Hashable {
case lexical(LexicalError)
case syntax(SyntaxError)
case type(Type, Set<Type>)
case range(String?, Int?, Int64, Int64)
case argumentCount(String?, Int, Int)
case eval(EvalError)
case os(Error)
case abortion
case uncaught
case custom(String, String)
public var isFileError: Bool {
guard case .eval(let err) = self else {
return false
}
switch err {
case .cannotOpenFile, .cannotOpenAsset, .cannotOpenUrl, .cannotWriteToPort, .unknownFile:
return true
default:
return false
}
}
public var isReadError: Bool {
switch self {
case .lexical(_), .syntax(_):
return true
default:
return false
}
}
public var typeDescription: String {
switch self {
case .lexical(_):
return "lexical error"
case .syntax(_):
return "syntax error"
case .type(_, _):
return "type error"
case .range(_, _, _, _):
return "range error"
case .argumentCount(_, _, _):
return "argument count error"
case .eval(_):
return "eval error"
case .os(_):
return "os error"
case .abortion:
return "abortion"
case .uncaught:
return "uncaught"
case .custom(let type, _):
return type
}
}
public var shortTypeDescription: String {
switch self {
case .lexical(_):
return "lexical"
case .syntax(_):
return "syntax"
case .type(_, _):
return "type"
case .range(_, _, _, _):
return "range"
case .argumentCount(_, _, _):
return "arg"
case .eval(_):
return "eval"
case .os(_):
return "os"
case .abortion:
return "abort"
case .uncaught:
return "uncaught"
case .custom(_, _):
return "custom"
}
}
public var messageTemplate: String {
switch self {
case .lexical(let error):
return error.message
case .syntax(let error):
return error.message
case .type(let found, let expected):
guard expected.count > 0 else {
return "unexpected expression $0"
}
var tpe: Type? = nil
var res = ""
for type in expected {
if let t = tpe {
res += (res.isEmpty ? "" : ", ") + t.description
}
tpe = type
}
if res.isEmpty {
res = "a " + tpe!.description
} else {
res = "either a " + res + " or " + tpe!.description
}
return "$0 is of type \(found.description), but is required to be \(res) value"
case .range(let fun, let par, let low, let high):
if let fun = fun, let par = par {
if low == Int64.min {
if high == 0 {
return "expected argument \(par) of function \(fun) to be a negative integer " +
"value; is $0 instead"
} else {
return "expected argument \(par) of function \(fun) to be an integer value less " +
"than equals \(high); is $0 instead"
}
} else if high == Int64.max {
if low == 0 {
return "expected argument \(par) of function \(fun) to be a positive integer " +
"value; is $0 instead"
} else {
return "expected argument \(par) of function \(fun) to be an integer value greater " +
"than equals \(low); is $0 instead"
}
} else {
return "expected argument \(par) of function \(fun) to be an integer value within " +
"the range [\(low), \(high)]; is $0 instead"
}
} else if low == Int64.min {
if high == 0 {
return "expected $0 to be a negative integer value"
} else {
return "expected $0 to be an integer value less than equals \(high)"
}
} else if high == Int64.max {
if low == 0 {
return "expected $0 to be a positive integer value"
} else {
return "expected $0 to be an integer value greater than equals \(low)"
}
} else {
return "expected $0 to be an integer value within the range [\(low), \(high)]"
}
case .argumentCount(let fun, let min, let max):
if let fun = fun {
if min == max {
return "\(fun) expects \(self.arguments(min)), but received $0 arguments: $1"
} else if max == Int.max {
return "\(fun) expects at least \(self.arguments(min)), but received only " +
"$0 arguments: $1"
} else {
return "\(fun) expects between \(min) and \(self.arguments(max)), but received $0 " +
"arguments: $1"
}
} else {
if min == max {
return "function expects \(self.arguments(min)), but received $0 arguments: $1"
} else if max == Int.max {
return "function expects at least \(self.arguments(min)), but received only " +
"$0 arguments: $1"
} else {
return "function expects between \(min) and \(self.arguments(max)), but received " +
"$0 arguments: $1"
}
}
case .eval(let error):
return error.message
case .os(let error):
let nserror = error as NSError
if let underlying = nserror.userInfo[NSUnderlyingErrorKey] as? NSError {
let prefix = underlying.localizedFailureReason ?? underlying.localizedDescription
return "\(prefix): \(error.localizedDescription) (error \(nserror.code))"
} else {
return "\(error.localizedDescription) (error \(nserror.code))"
}
case .abortion:
return "abortion"
case .uncaught:
return "$0"
case .custom(_, let message):
return message
}
}
private func arguments(_ n: Int) -> String {
if n == 1 {
return "1 argument"
} else {
return "\(n) arguments"
}
}
public func hash(into hasher: inout Hasher) {
switch self {
case .lexical(let error):
hasher.combine(error)
case .syntax(let error):
hasher.combine(1)
hasher.combine(error)
case .type(let found, let expected):
hasher.combine(2)
hasher.combine(found)
hasher.combine(expected)
case .range(let fun, let argn, let low, let high):
hasher.combine(3)
hasher.combine(fun)
hasher.combine(argn)
hasher.combine(low)
hasher.combine(high)
case .argumentCount(let fun, let min, let max):
hasher.combine(4)
hasher.combine(fun)
hasher.combine(min)
hasher.combine(max)
case .eval(let error):
hasher.combine(5)
hasher.combine(error)
case .os(let error):
hasher.combine(6)
hasher.combine(error as NSError)
case .abortion:
hasher.combine(7)
case .uncaught:
hasher.combine(8)
case .custom(let kind, let message):
hasher.combine(9)
hasher.combine(kind)
hasher.combine(message)
}
}
public static func ==(_ lhs: ErrorDescriptor, _ rhs: ErrorDescriptor) -> Bool {
switch (lhs, rhs) {
case (.lexical(let lerr), .lexical(let rerr)):
return lerr == rerr
case (.syntax(let lerr), .syntax(let rerr)):
return lerr == rerr
case (.type(let lfound, let lexp), .type(let rfound, let rexp)):
return lfound == rfound && lexp == rexp
case (.range(let lfun, let largn, let llow, let lhigh),
.range(let rfun, let rargn, let rlow, let rhigh)):
return lfun == rfun && largn == rargn && llow == rlow && lhigh == rhigh
case (.argumentCount(let lfun, let lmin, let lmax),
.argumentCount(let rfun, let rmin, let rmax)):
return lfun == rfun && lmin == rmin && lmax == rmax
case (.eval(let lerr), .eval(let rerr)):
return lerr == rerr
case (.os(let lerr), .os(let rerr)):
return lerr.localizedDescription == rerr.localizedDescription
case (.abortion, .abortion):
return true
case (.uncaught, .uncaught):
return true
case (.custom(let lkind, let lmessage), .custom(let rkind, let rmessage)):
return lkind == rkind && lmessage == rmessage
default:
return false
}
}
}
| apache-2.0 | e75f5f904b03c5392d2f28b891ed79fe | 35.54 | 100 | 0.534355 | 4.896373 | false | false | false | false |
goto10/Vapor-FileMaker | Sources/FMSConnector/FMPQuery.swift | 1 | 16083 | //
// FMPQuery.swift
// PerfectFileMaker
//
// Created by Kyle Jessup on 2016-08-02.
// Copyright (C) 2016 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Foundation
import Vapor
import HTTP
/// A database action.
public enum FMPAction: CustomStringConvertible {
/// Perform a search given the current query.
case find
/// Find all records in the database.
case findAll
/// Find and retrieve a random record.
case findAny
/// Create a new record given the current query data.
case new
/// Edit (update) the record indicated by the record id with the current query fields/values.
case edit
/// Delete the record indicated by the current record id.
case delete
/// Duplicate the record indicated by the current record id.
case duplicate
public var description: String {
switch self {
case .find: return "-findquery"
case .findAll: return "-findall"
case .findAny: return "-findany"
case .new: return "-new"
case .edit: return "-edit"
case .delete: return "-delete"
case .duplicate: return "-dup"
}
}
}
/// A record sort order.
public enum FMPSortOrder: CustomStringConvertible {
/// Sort the records by the indicated field in ascending order.
case ascending
/// Sort the records by the indicated field in descending order.
case descending
/// Sort the records by the indicated field in a custom order.
case custom
public var description: String {
switch self {
case .ascending: return "ascend"
case .descending: return "descend"
case .custom: return "custom"
}
}
}
/// A sort field indicator.
public struct FMPSortField {
/// The name of the field on which to sort.
public let name: String
/// A field sort order.
public let order: FMPSortOrder
/// Initialize with a field name and sort order.
public init(name: String, order: FMPSortOrder) {
self.name = name
self.order = order
}
/// Initialize with a field name using the default FMPSortOrder.ascending sort order.
public init(name: String) {
self.init(name: name, order: .ascending)
}
}
/// An individual field search operator.
public enum FMPFieldOp {
case equal
case contains
case beginsWith
case endsWith
case greaterThan
case greaterThanEqual
case lessThan
case lessThanEqual
}
/// An individual query field.
public struct FMPQueryField {
/// The name of the field.
public let name: String
/// The value for the field.
public let value: Any
/// The search operator.
public let op: FMPFieldOp
/// Initialize with a name, value and operator.
public init(name: String, value: Any, op: FMPFieldOp = .beginsWith) {
self.name = name
self.value = value
self.op = op
}
var valueWithOp: String {
switch op {
case .equal: return "==\(value)"
case .contains: return "==*\(value)*"
case .beginsWith: return "==\(value)*"
case .endsWith: return "==*\(value)"
case .greaterThan: return ">\(value)"
case .greaterThanEqual: return ">=\(value)"
case .lessThan: return "<\(value)"
case .lessThanEqual: return "<=\(value)"
}
}
}
/// A logical operator used with query field groups.
public enum FMPLogicalOp {
case and, or, not
}
/// A group of query fields.
public struct FMPQueryFieldGroup {
/// The logical operator for the field group.
public let op: FMPLogicalOp
/// The list of fiedls in the group.
public let fields: [FMPQueryField]
/// Initialize with an operator and field list.
/// The default logical operator is FMPLogicalOp.and.
public init(fields: [FMPQueryField], op: FMPLogicalOp = .and) {
self.op = op
self.fields = fields
}
var simpleFieldsString: String {
return fields.map {
let vstr = "\($0.value)"
return "\($0.name.stringByEncodingURL)=\(vstr.stringByEncodingURL)"
}.joined(separator: "&")
}
}
/// Indicates an invalid record id.
public let fmpNoRecordId = -1
/// Indicates no max records value.
public let fmpAllRecords = -1
/// An individual query & database action.
public struct FMPQuery: CustomStringConvertible {
let database: String
let layout: String
let action: FMPAction
let queryFields: [FMPQueryFieldGroup]
let sortFields: [FMPSortField]
let recordId: Int
let preSortScripts: [String]
let preFindScripts: [String]
let postFindScripts: [String]
let responseLayout: String
let responseFields: [String]
let maxRecords: Int
let skipRecords: Int
/// Initialize with a database name, layout name & database action.
public init(database: String, layout: String, action: FMPAction) {
queryFields = [FMPQueryFieldGroup]()
sortFields = [FMPSortField]()
recordId = fmpNoRecordId
preSortScripts = [String]()
preFindScripts = [String]()
postFindScripts = [String]()
responseLayout = ""
responseFields = [String]()
maxRecords = fmpAllRecords
skipRecords = 0
self.database = database
self.layout = layout
self.action = action
}
init(queryFields: [FMPQueryFieldGroup],
sortFields: [FMPSortField],
recordId: Int,
preSortScripts: [String],
preFindScripts: [String],
postFindScripts: [String],
responseLayout: String,
responseFields: [String],
maxRecords: Int,
skipRecords: Int,
action: FMPAction,
database: String,
layout: String) {
self.queryFields = queryFields
self.sortFields = sortFields
self.recordId = recordId
self.preSortScripts = preSortScripts
self.preFindScripts = preFindScripts
self.postFindScripts = postFindScripts
self.responseLayout = responseLayout
self.responseFields = responseFields
self.maxRecords = maxRecords
self.skipRecords = skipRecords
self.action = action
self.database = database
self.layout = layout
}
/// Sets the record id and returns the adjusted query.
public func recordId(_ recordId: Int) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the query fields and returns the adjusted query.
public func queryFields(_ queryFields: [FMPQueryFieldGroup]) -> FMPQuery {
return FMPQuery(queryFields: self.queryFields + queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the query fields and returns the adjusted query.
public func queryFields(_ queryFields: [FMPQueryField]) -> FMPQuery {
return FMPQuery(queryFields: self.queryFields + [FMPQueryFieldGroup(fields: queryFields)], sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the sort fields and returns the adjusted query.
public func sortFields(_ sortFields: [FMPSortField]) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: self.sortFields + sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the indicated pre-sort scripts and returns the adjusted query.
public func preSortScripts(_ preSortScripts: [String]) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: self.preSortScripts + preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the indicated pre-find scripts and returns the adjusted query.
public func preFindScripts(_ preFindScripts: [String]) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: self.preFindScripts + preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds the indicated post-find scripts and returns the adjusted query.
public func postFindScripts(_ postFindScripts: [String]) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: self.postFindScripts + postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Sets the response layout and returns the adjusted query.
public func responseLayout(_ responseLayout: String) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Adds response fields and returns the adjusted query.
public func responseFields(_ responseFields: [String]) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: self.responseFields + responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Sets the maximum records to fetch and returns the adjusted query.
public func maxRecords(_ maxRecords: Int) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
/// Sets the number of records to skip in the found set and returns the adjusted query.
public func skipRecords(_ skipRecords: Int) -> FMPQuery {
return FMPQuery(queryFields: queryFields, sortFields: sortFields, recordId: recordId,
preSortScripts: preSortScripts, preFindScripts: preFindScripts,
postFindScripts: postFindScripts, responseLayout: responseLayout,
responseFields: responseFields, maxRecords: maxRecords, skipRecords: skipRecords,
action: action, database: database, layout: layout)
}
func maybeAmp(_ s: String) -> String {
if s.isEmpty {
return ""
}
return s + "&"
}
var fieldCount: Int {
return queryFields.reduce(0) {
partialResult, grp -> Int in
return partialResult + grp.fields.count
}
}
var dbLayString: String {
return "-db=\(database.stringByEncodingURL)&-lay=\(layout.stringByEncodingURL)&"
}
var sortFieldsString: String {
var colNum = 1
return sortFields.map { field -> String in
let ret = "-sortfield.\(colNum)=\(field.name.stringByEncodingURL)&-sortorder.\(colNum)=\(field.order)"
colNum += 1
return ret
}.joined(separator: "&")
}
var responseFieldsString: String {
return responseFields.map { "-field=\($0.stringByEncodingURL)" }.joined(separator: "&")
}
var scriptsString: String {
let preSorts = preSortScripts.map { "-script.presort=\($0.stringByEncodingURL)" }.joined(separator: "&")
let preFinds = preFindScripts.map { "-script.prefind=\($0.stringByEncodingURL)" }.joined(separator: "&")
let postFinds = postFindScripts.map { "-script=\($0.stringByEncodingURL)" }.joined(separator: "&")
return maybeAmp(preSorts) + maybeAmp(preFinds) + postFinds
}
var maxSkipString: String{
return "-skip=\(skipRecords)&-max=\(maxRecords == fmpAllRecords ? "all" : String(maxRecords))"
}
var recidString: String {
if recordId != fmpNoRecordId && action != .findAny {
return "-recid=\(recordId)"
}
return ""
}
var responseLayoutString: String {
if responseLayout.isEmpty {
return ""
}
return "-lay.response=\(responseLayout.stringByEncodingURL)"
}
var actionString: String {
return "\(action)"
}
var simpleFieldsString: String {
return queryFields.map {
$0.simpleFieldsString
}.joined(separator: "&")
}
var compoundQueryString: String {
var num = 0
var segments = [String]()
for group in queryFields {
switch group.op {
case .and:
let str = "(\(group.fields.map { _ in num += 1 ; return "q\(num)" }.joined(separator: ",")))"
segments.append(str)
case .or:
let str = "\(group.fields.map { _ in num += 1 ; return "(q\(num))" }.joined(separator: ";"))"
segments.append(str)
case .not:
let str = "!(\(group.fields.map { _ in num += 1 ; return "q\(num)" }.joined(separator: ",")))"
segments.append(str)
}
}
return "-query=\(segments.joined(separator: ";").stringByEncodingURL)"
}
var compoundFieldsString: String {
var num = 0
var segments = [String]()
for group in queryFields {
let str = group.fields.map {
num += 1
return "-q\(num)=\($0.name.stringByEncodingURL)&-q\(num).value=\($0.valueWithOp.stringByEncodingURL)"
}.joined(separator: "&")
segments.append(str)
}
return segments.joined(separator: "&")
}
public var description: String {
return queryString
}
/// Returns the formulated query string.
/// Useful for debugging purposes.
public var queryString: String {
let starter = dbLayString +
maybeAmp(scriptsString) +
maybeAmp(responseLayoutString)
switch action {
case .delete, .duplicate:
return starter +
maybeAmp(recidString) + actionString
case .edit:
return starter +
maybeAmp(recidString) +
maybeAmp(simpleFieldsString) + actionString
case .new:
return starter +
maybeAmp(simpleFieldsString) + actionString
case .findAny:
return starter + actionString
case .findAll:
return starter +
maybeAmp(sortFieldsString) +
maybeAmp(maxSkipString) + actionString
case .find:
if recordId != fmpNoRecordId {
return starter +
maybeAmp(recidString) + "-find"
}
return starter +
maybeAmp(sortFieldsString) +
maybeAmp(maxSkipString) +
maybeAmp(compoundQueryString) +
maybeAmp(compoundFieldsString) + actionString
}
}
}
| apache-2.0 | 3c29ad17df78d42836ae8b9403411d4a | 34.899554 | 136 | 0.692595 | 4.376327 | false | false | false | false |
avito-tech/Paparazzo | Example/PaparazzoExample_NoMarshroute/AppDelegate.swift | 1 | 3847 | import Paparazzo
import ImageSource
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
-> Bool
{
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = rootViewController()
window?.makeKeyAndVisible()
return true
}
private func rootViewController() -> UIViewController {
let exampleController = ExampleViewController()
var mediaPickerItems = [MediaPickerItem]()
var photoLibraryItems = [PhotoLibraryItem]()
exampleController.setItems([
ExampleViewItem(title: "Photo Library v2 — New flow", onTap: { [weak exampleController] in
let viewController = PaparazzoFacade.libraryV2ViewController(
theme: PaparazzoUITheme.appSpecificTheme(),
parameters: PhotoLibraryV2Data(
mediaPickerData: MediaPickerData()
),
onFinish: { result in
print(result)
}
)
exampleController?.present(viewController, animated: true, completion: nil)
}),
ExampleViewItem(title: "Photo Library v1", onTap: { [weak exampleController] in
let viewController = PaparazzoFacade.libraryViewController(
theme: PaparazzoUITheme.appSpecificTheme(),
parameters: PhotoLibraryData(
selectedItems: photoLibraryItems,
maxSelectedItemsCount: 3
),
onFinish: { images in
photoLibraryItems = images
}
)
exampleController?.present(viewController, animated: true, completion: nil)
}),
ExampleViewItem(title: "Media Picker", onTap: { [weak exampleController] in
let viewController = PaparazzoFacade.paparazzoViewController(
theme: PaparazzoUITheme.appSpecificTheme(),
parameters: MediaPickerData(
items: mediaPickerItems,
maxItemsCount: 1
),
onFinish: { images in
mediaPickerItems = images
}
)
exampleController?.present(viewController, animated: true)
}),
ExampleViewItem(title: "Mask Cropper", onTap: { [weak exampleController] in
guard let pathToImage = Bundle.main.path(forResource: "kitten", ofType: "jpg") else {
assertionFailure("Oooops. Kitten is lost :(")
return
}
let viewController = PaparazzoFacade.maskCropperViewController(
theme: PaparazzoUITheme.appSpecificTheme(),
parameters: MaskCropperData(
imageSource: LocalImageSource(path: pathToImage)
),
croppingOverlayProvider: CroppingOverlayProvidersFactoryImpl().circleCroppingOverlayProvider(),
onFinish: { imageSource in
print("Cropped image: \(imageSource)")
}
)
exampleController?.present(viewController, animated: true, completion: nil)
})
])
return NavigationController(rootViewController: exampleController)
}
}
| mit | 23480e1c29bfc163d3b2156338447204 | 39.052083 | 115 | 0.535241 | 7.068015 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/ShadowboxViewController.swift | 1 | 8353 | //
// ShadowboxViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/5/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import UIKit
class ShadowboxViewController: SwipeDownModalVC, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var vCs: [UIViewController] = [ClearVC()]
var baseSubmissions: [RSubmission] = []
public init(submissions: [RSubmission]){
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
self.baseSubmissions = submissions
for s in baseSubmissions {
self.vCs.append(ShadowboxLinkViewController.init(submission: s))
}
let firstViewController = self.vCs[1]
self.setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge.all
self.extendedLayoutIncludesOpaqueBars = true
self.view.backgroundColor = UIColor.clear
}
var navItem: UINavigationItem?
func exit(){
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad(){
super.viewDidLoad()
self.dataSource = self
self.delegate = self
view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
self.navigationController?.view.backgroundColor = UIColor.clear
let navigationBar = UINavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 56))
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
navigationBar.isTranslucent = true
navItem = UINavigationItem(title: "")
let close = UIButton.init(type: .custom)
close.setImage(UIImage.init(named: "close")?.imageResize(sizeChange: CGSize.init(width: 25, height: 25)), for: UIControlState.normal)
close.addTarget(self, action: #selector(self.exit), for: UIControlEvents.touchUpInside)
close.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let closeB = UIBarButtonItem.init(customView: close)
navItem?.leftBarButtonItem = closeB
var gridB = UIBarButtonItem(image: UIImage(named: "grid")?.imageResize(sizeChange: CGSize.init(width: 25, height: 25)).withRenderingMode(.alwaysOriginal), style:.plain, target: self, action: #selector(overview(_:)))
// navItem?.rightBarButtonItem = gridB
navigationBar.setItems([navItem!], animated: false)
self.view.addSubview(navigationBar)
}
func overview(_ sender: AnyObject){
}
func pageViewController(_ pageViewController : UIPageViewController, didFinishAnimating: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) {
if(pageViewController.viewControllers?.first == vCs[0]){
self.dismiss(animated: true, completion: nil)
}
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = vCs.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard vCs.count > previousIndex else {
return nil
}
return vCs[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = vCs.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = vCs.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return vCs[nextIndex]
}
}
public extension UIPanGestureRecognizer {
override open class func initialize() {
super.initialize()
guard self === UIPanGestureRecognizer.self else { return }
func replace(_ method: Selector, with anotherMethod: Selector, for clаss: AnyClass) {
let original = class_getInstanceMethod(clаss, method)
let swizzled = class_getInstanceMethod(clаss, anotherMethod)
switch class_addMethod(clаss, method, method_getImplementation(swizzled), method_getTypeEncoding(swizzled)) {
case true:
class_replaceMethod(clаss, anotherMethod, method_getImplementation(original), method_getTypeEncoding(original))
case false:
method_exchangeImplementations(original, swizzled)
}
}
let selector1 = #selector(UIPanGestureRecognizer.touchesBegan(_:with:))
let selector2 = #selector(UIPanGestureRecognizer.swizzling_touchesBegan(_:with:))
replace(selector1, with: selector2, for: self)
let selector3 = #selector(UIPanGestureRecognizer.touchesMoved(_:with:))
let selector4 = #selector(UIPanGestureRecognizer.swizzling_touchesMoved(_:with:))
replace(selector3, with: selector4, for: self)
}
@objc private func swizzling_touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
self.swizzling_touchesBegan(touches, with: event)
guard direction != nil else { return }
touchesBegan = true
}
@objc private func swizzling_touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
self.swizzling_touchesMoved(touches, with: event)
guard let direction = direction, touchesBegan == true else { return }
defer {
touchesBegan = false
}
let forbiddenDirectionsCount = touches
.flatMap({ ($0.location(in: $0.view) - $0.previousLocation(in: $0.view)).direction })
.filter({ $0 != direction })
.count
if forbiddenDirectionsCount > 0 {
state = .failed
}
}
}
public extension UIPanGestureRecognizer {
public enum Direction: Int {
case horizontal = 0
case vertical
}
private struct UIPanGestureRecognizerRuntimeKeys {
static var directions = "\(#file)+\(#line)"
static var touchesBegan = "\(#file)+\(#line)"
}
public var direction: UIPanGestureRecognizer.Direction? {
get {
let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions)
return object as? UIPanGestureRecognizer.Direction
}
set {
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.directions, newValue, policy)
}
}
fileprivate var touchesBegan: Bool {
get {
let object = objc_getAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan)
return (object as? Bool) ?? false
}
set {
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &UIPanGestureRecognizerRuntimeKeys.touchesBegan, newValue, policy)
}
}
}
fileprivate extension CGPoint {
var direction: UIPanGestureRecognizer.Direction? {
guard self != .zero else { return nil }
switch fabs(x) > fabs(y) {
case true: return .horizontal
case false: return .vertical
}
}
static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
}
| apache-2.0 | 13f4e245b2a7d27b0ba56bb4cc74da7a | 36.769231 | 223 | 0.632203 | 5.385161 | false | false | false | false |
adeca/SwiftySwift | SwiftyCore/SignedNumeric+Extensions.swift | 1 | 274 | //
// SignedNumeric+Extensions.swift
// SwiftySwift
//
// Copyright © 2017 Agustín de Cabrera. All rights reserved.
//
extension SignedNumeric where Self.Magnitude == Self {
public var sign: Self {
return self == 0 ? 0 : self == abs(self) ? 1 : -1
}
}
| mit | c43a1b4e89771d9ba747e2bc9d16b7d0 | 21.666667 | 61 | 0.628676 | 3.487179 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/SwiftyDemo/Extesion/Inherit(继承)/MoreButton.swift | 3 | 1167 | //
// MoreButton.swift
// chart2
//
// Created by i-Techsys.com on 16/12/9.
// Copyright © 2016年 i-Techsys. All rights reserved.
//
import UIKit
class MoreButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
// 设置字体颜色
self.setTitleColor(UIColor.colorWithCustom(r: 10, g: 10, b: 10), for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 16)
self.titleLabel?.adjustsFontSizeToFitWidth = true
// 让文字居中显示
self.titleLabel?.textAlignment = NSTextAlignment.center;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.mg_y = self.mg_height * 0.15;
self.imageView?.mg_centerX = self.mg_width * 0.5;
// 调整文字位置
self.titleLabel?.mg_width = self.mg_width;
self.titleLabel?.mg_height = self.mg_height - self.imageView!.mg_height;
self.titleLabel?.mg_x = 0;
self.titleLabel?.mg_y = self.imageView!.frame.maxY
}
}
| mit | 79569bf644178bf41ca530c398bdc4e6 | 29.432432 | 86 | 0.620782 | 3.753333 | false | false | false | false |
strike65/SwiftyStats | SwiftyStats/CommonSource/SpecialFunctions/ContFrac/SSContFrac.swift | 1 | 4067 | //
// SSContFrac.swift
// SwiftyStats
//
// Created by strike65 on 19.07.17.
//
/*
Copyright (2017-2019) strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
/// An abstract class used to evaluate continued fractions. This class must be subclassed.
/// The n<sup>th</sup> coefficient is computed using the methods a_N:N point:x and b_N:N point:x<br/>
/// <img src="../img/cf.png" alt="">
internal class SSContFrac<T: SSFloatingPoint>: NSObject {
/// max error
var eps:T = T.ulpOfOne
/// initializes a new instance
override public init() {
super.init()
self.eps = T.ulpOfOne
}
/// The n<sup>th</sup> a coefficient at x. If a is a function of x, x is passed as well.
/// - Parameter n: n
/// - Parameter x: x
func a_N(n: Int, point x: T) -> T {
return T.nan
}
/// The n<sup>th</sup> b coefficient at x. If a is a function of x, x is passed as well.
/// - Parameter n: n
/// - Parameter x: x
func b_N(n: Int, point x: T) -> T {
return T.nan
}
/// Evaluates the continued fraction at point x. The evaluation will be stopped, when max iteration count is reached or one of the convergents is NAN.
/// Algorithm according to Lentz, modified by Thompson and Barnett (http://www.fresco.org.uk/papers/Thompson-JCP64p490.pdf)
/// - Parameter x: x
/// - Parameter eps: max error allowed
/// - Parameter maxIter: Maximum number of iterations
/// - Parameter converged: TRUE if the result is valid
/// - Parameter iterations: On return it contains the number of iterations needed.
/// - Returns: The result of the evaluated cf. If the cf didn't converge, converged is set to false and Double.nan is returned.
func compute(x: T, eps: T = T.ulpOfOne, maxIter: Int, converged: UnsafeMutablePointer<Bool>!, iterations: UnsafeMutablePointer<Int>!) -> T {
var n: Int = 1
var hPrev: T
let tiny: T = Helpers.makeFP(1E-50)
hPrev = self.a_N(n:0, point:x)
if (hPrev == 0) {
hPrev = tiny
}
var dPrev: T = 0
var cPrev: T = hPrev
var HN: T = hPrev
var aN: T
var bN: T
var DN: T
var CN: T
var Delta: T
var DeltaN: T
while (n < maxIter) {
aN = self.a_N(n: n, point: x)
bN = self.b_N(n: n, point: x)
DN = aN + bN * dPrev;
Delta = abs(DN);
if (Delta <= eps) {
DN = tiny;
}
CN = aN + bN / cPrev
Delta = abs(CN)
if (CN <= eps) {
CN = tiny
}
DN = 1 / DN
DeltaN = DN * CN
HN = hPrev * DeltaN
if (HN.isInfinite) {
converged.pointee = false;
return T.nan;
}
if (HN.isInfinite) {
converged.pointee = false;
return T.nan;
}
if (abs(DeltaN - Helpers.makeFP(1.0)) < eps) {
converged.pointee = true;
iterations.pointee = n;
return HN;
}
dPrev = DN;
cPrev = CN;
hPrev = HN;
n = n + 1
}
if (n >= maxIter) {
converged.pointee = false;
return T.nan;
}
converged.pointee = true;
iterations.pointee = n
return HN
}
}
| gpl-3.0 | d4450138183bae9e05c77cbe862336a1 | 32.336066 | 154 | 0.550283 | 3.891866 | false | false | false | false |
kstaring/swift | test/SILOptimizer/inout_deshadow_integration.swift | 1 | 3041 | // RUN: %target-swift-frontend %s -emit-sil | %FileCheck %s
// This is an integration check for the inout-deshadow pass, verifying that it
// deshadows the inout variables in certain cases. These test should not be
// very specific (as they are running the parser, silgen and other sil
// diagnostic passes), they should just check the inout shadow got removed.
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_dead(a: inout Int) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_returned(a: inout Int) -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored(a: inout Int) {
a = 12
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored_returned(a: inout Int) -> Int {
a = 12
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_dead(a: inout String) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_returned(a: inout String) -> String {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored(a: inout String) {
a = "x"
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored_returned(a: inout String) -> String {
a = "x"
return a
}
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
// We should be able to deshadow this. The closure is capturing self, but it
// is itself noescape.
mutating func mutatingMethod() {
takesNoEscapeClosure { x = 42; return x }
}
mutating func testStandardLibraryOperators() {
if x != 4 || x != 0 {
testStandardLibraryOperators()
}
}
}
// CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
// CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod28testStandardLibraryOperators{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box $@box StructWithMutatingMethod
// CHECK-NOT: alloc_stack $StructWithMutatingMethod
// CHECK: }
| apache-2.0 | d2c608588797393020e3281fca73aefb | 27.961905 | 187 | 0.701743 | 3.615933 | false | false | false | false |
AlexBianzd/NiceApp | NiceApp/Classes/Base/ZDBaseView.swift | 1 | 584 | //
// ZDBaseView.swift
// NiceApp
//
// Created by 边振东 on 27/11/2016.
// Copyright © 2016 边振东. All rights reserved.
//
import UIKit
@IBDesignable
class ZDBaseView: UIView {
@IBInspectable var cornerRadius : CGFloat = 0 {
didSet{
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth : CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor : UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
}
| mit | 40210a43ee572a291204721ae21fe207 | 16.84375 | 49 | 0.639229 | 3.965278 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Nodes/Generators/Oscillators/Morphing Oscillator/AKMorphingOscillator.swift | 1 | 9112 | //
// AKMorphingOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This is an oscillator with linear interpolation that is capable of morphing
/// between an arbitrary number of wavetables.
///
/// - parameter waveformArray: An array of exactly four waveforms
/// - parameter frequency: Frequency (in Hz)
/// - parameter amplitude: Amplitude (typically a value between 0 and 1).
/// - parameter index: Index of the wavetable to use (fractional are okay).
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
/// - parameter phase: Initial phase of waveform, expects a value 0-1
///
public class AKMorphingOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKMorphingOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var waveformArray = [AKTable]()
private var phase: Double
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var indexParameter: AUParameter?
private var detuningOffsetParameter: AUParameter?
private var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Index of the wavetable to use (fractional are okay).
public var index: Double = 0.0 {
willSet {
let transformedValue = Float(newValue) / Float(waveformArray.count - 1)
// if internalAU!.isSetUp() {
// indexParameter?.setValue(Float(transformedValue), originator: token!)
// } else {
internalAU?.index = Float(transformedValue)
// }
}
}
/// Frequency offset in Hz.
public var detuningOffset: Double = 0 {
willSet {
if detuningOffset != newValue {
if internalAU!.isSetUp() {
detuningOffsetParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
public var detuningMultiplier: Double = 1 {
willSet {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
override public convenience init() {
self.init(waveformArray: [AKTable(.Triangle), AKTable(.Square), AKTable(.Sine), AKTable(.Sawtooth)])
}
/// Initialize this Morpher node
///
/// - parameter waveformArray: An array of exactly four waveforms
/// - parameter frequency: Frequency (in Hz)
/// - parameter amplitude: Amplitude (typically a value between 0 and 1).
/// - parameter index: Index of the wavetable to use (fractional are okay).
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
/// - parameter phase: Initial phase of waveform, expects a value 0-1
///
public init(
waveformArray: [AKTable],
frequency: Double = 440,
amplitude: Double = 0.5,
index: Double = 0.0,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1,
phase: Double = 0) {
// AOP Note: Waveforms are currently hardcoded, need to upgrade this
self.waveformArray = waveformArray
self.frequency = frequency
self.amplitude = amplitude
self.phase = phase
self.index = index
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x6d6f7266 /*'morf'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKMorphingOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKMorphingOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKMorphingOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
/// AOP need to set up phase
for i in 0 ..< waveformArray.count {
self.internalAU?.setupWaveform(UInt32(i), size: Int32(waveformArray[i].size))
for j in 0 ..< waveformArray[i].size{
self.internalAU?.setWaveform(UInt32(i), withValue: waveformArray[i].values[j], atIndex: UInt32(j))
}
}
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
indexParameter = tree.valueForKey("index") as? AUParameter
detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter
detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.indexParameter!.address {
self.index = Double(value)
} else if address == self.detuningOffsetParameter!.address {
self.detuningOffset = Double(value)
} else if address == self.detuningMultiplierParameter!.address {
self.detuningMultiplier = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.index = Float(index) / Float(waveformArray.count - 1)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function create an identical new node for use in creating polyphonic instruments
override public func duplicate() -> AKVoice {
let copy = AKMorphingOscillator(waveformArray: self.waveformArray, frequency: self.frequency, amplitude: self.amplitude, index: self.index, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier, phase: self.phase)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
override public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
override public func stop() {
self.internalAU!.stop()
}
}
| mit | 1aa35799c68a7bc336e82723d59b7dc5 | 38.107296 | 248 | 0.605904 | 5.586757 | false | false | false | false |
leo150/Pelican | Sources/Pelican/API/Types/Type+Extensions.swift | 1 | 2670 | //
// Type+Extensions.swift
// Pelican
//
// Created by Ido Constantine on 31/08/2017.
//
import Foundation
import Vapor
import FluentProvider
/*
An extension used to switch from snake to camel case and back again
*/
extension String {
/**
Checks that the given URL for MessageFile types is either a valid internal or remote source.
*/
func checkURLValidity(acceptedExtensions: [String]) -> Bool {
// Check that the file has a valid file-extension.
if acceptedExtensions.count > 0 {
if self.components(separatedBy: ".").last == nil { return false }
let ext = self.components(separatedBy: ".").last!
if acceptedExtensions.contains(ext) == false { return false }
return true
}
// Add checks for remote/internal paths and path consistency.
return true
}
/**
Converts a string that has snake case formatting to a camel case format.
*/
var snakeToCamelCase: String {
let items = self.components(separatedBy: "_")
var camelCase = ""
items.enumerated().forEach {
camelCase += 0 == $0 ? $1 : $1.capitalized
}
return camelCase
}
/**
Converts a string that has camel case formatting to a snake case format.
*/
var camelToSnakeCase: String {
// Check that we have characters...
guard self.characters.count > 0 else { return self }
var newString: String = ""
// Break up the string into only "Unicode Scalars", which boils it down to a UTF-32 code.
// This allows us to check if the identifier belongs in the "uppercase letter" set.
let first = self.unicodeScalars.first!
newString.append(Character(first))
for scalar in self.unicodeScalars.dropFirst() {
// If the unicode scalar contains an upper case letter, add an underscore and lowercase the letter.
if CharacterSet.uppercaseLetters.contains(scalar) {
let character = Character(scalar)
newString.append("_")
newString += String(character).lowercased()
}
// Otherwise append it to the new string.
else {
let character = Character(scalar)
newString.append(character)
}
}
return newString
}
}
extension Row {
/**
Strips row data of any entries that have a value of "null", including any nested data.
Useful for constructing queries and requests where null values are not compatible.
*/
mutating func removeNullEntries() throws {
if self.object != nil {
for row in self.object! {
if row.value.isNull == true {
self.removeKey(row.key)
}
else if row.value.object != nil {
var newRow = row.value
try newRow.removeNullEntries()
self.removeKey(row.key)
try self.set(row.key, newRow)
}
}
}
}
}
| mit | fb39fbf3ceac22f0ed3974ce58ca2285 | 22.839286 | 102 | 0.676779 | 3.78187 | false | false | false | false |
koscida/Kos_AMAD_Spring2015 | Spring_16/IGNORE_work/projects/Girl_Game/Girl_Game/GameIntroScene.swift | 2 | 5792 | //
// GameInroScene.swift
// Girl_Game
//
// Created by Brittany Kos on 4/6/16.
// Copyright © 2016 Kode Studios. All rights reserved.
//
import UIKit
import SpriteKit
/*
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
do {
let sceneData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
//var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameIntroScene
archiver.finishDecoding()
return scene
} catch {
print(error)
}
} else {
return nil
}
return nil
}
}
*/
class GameIntroScene: SKScene {
var frameWidth: CGFloat = 0;
var frameHeight: CGFloat = 0;
var frameCenterWidth: CGFloat = 0;
var frameCenterHeight: CGFloat = 0;
let frameBorder: CGFloat = 20
var titleView = SKNode()
var state = 0;
override func didMoveToView(view: SKView) {
//print("in GameIntroScene")
frameWidth = CGRectGetWidth(frame)
frameCenterWidth = frameWidth / 2
frameHeight = CGRectGetHeight(frame)
frameCenterHeight = frameHeight / 2
//print("frameWidth: \(frameWidth) frameCenterWidth: \(frameCenterWidth)")
//print("frameHeight: \(frameHeight) frameCenterHeight: \(frameCenterHeight)")
if(state == 0) {
loadTitleView()
}
}
override init(size: CGSize) {
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
///////////////////////////////////////
// Scene loaders //
///////////////////////////////////////
func loadTitleView() {
let titleLabel1 = createSKLabelNode(
text: "Welcome to \"Strong Female Character\"",
fontSize: 100,
fontColor: UIColor.whiteColor()
)
titleLabel1.position = CGPoint(x: frameCenterWidth, y: frameCenterHeight+(titleLabel1.frame.height*2))
titleLabel1.name = "titleLabel1"
titleView.addChild(titleLabel1)
let titleLabel2 = createSKLabelNode(
text: "A game about playing the game of life",
fontSize: 100,
fontColor: UIColor.whiteColor()
)
titleLabel2.position = CGPoint(x: frameCenterWidth, y: frameCenterHeight)
titleView.addChild(titleLabel2)
let titleLabel3 = createSKLabelNode(
text: "as a girl.",
fontSize: 100,
fontColor: pinkColor
)
titleLabel3.position = CGPoint(x: frameCenterWidth, y: frameCenterHeight-(titleLabel3.frame.height*2))
titleView.addChild(titleLabel3)
let playButtonShapeWidth: CGFloat = 300
let playButtonShapeHeight: CGFloat = 130
let playButtonShapeRect = CGRect(x: frameCenterWidth-(playButtonShapeWidth/2), y: 0+frameBorder, width: playButtonShapeWidth, height: playButtonShapeHeight)
let playButtonShape = createSKShapeNodeRect(name: "playButtonShape", rect: playButtonShapeRect, fillColor: pinkColor)
playButtonShape.strokeColor = UIColor(white: 1, alpha: 1)
titleView.addChild(playButtonShape)
let playLabel = createSKLabelNodeAdj(
name: "playLabel",
text: "PLAY",
x: frameCenterWidth, y: (playButtonShapeHeight/2)+frameBorder,
width: playButtonShapeWidth*(2/3), height: playButtonShapeHeight*(2/3),
fontColor: UIColor.whiteColor()
)
titleView.addChild(playLabel)
self.addChild(titleView)
}
func loadInstructionsView() {
//self.addChild(instructionsView)
}
func stateChangeNext() {
switch state {
case 0:
titleView.removeFromParent()
//loadInstructionsView()
let transition = SKTransition.flipVerticalWithDuration(1.0)
let game = GameCharacterCreationScene(size:frame.size)
view!.presentScene(game, transition: transition)
default:
return;
}
state++
}
////////////////////////////////////
// Game Logic //
////////////////////////////////////
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)
//print("x: \(location.x)")
//print("y: \(location.y)")
if let name = touchedNode.name
{
if name == "playLabel" || name == "playButtonShape"
{
//print("Touched")
stateChangeNext()
}
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| gpl-3.0 | 41285ce89ab65e29ef6b18e07428fa07 | 29.478947 | 164 | 0.544811 | 5.504753 | false | false | false | false |
avtr/bluejay | Bluejay/Bluejay/ReadCharacteristic.swift | 1 | 3024 | //
// ReadCharacteristic.swift
// Bluejay
//
// Created by Jeremy Chiang on 2017-01-04.
// Copyright © 2017 Steamclock Software. All rights reserved.
//
import Foundation
import CoreBluetooth
/// A read operation.
class ReadCharacteristic<T: Receivable>: Operation {
/// The queue this operation belongs to.
var queue: Queue?
/// The state of this operation.
var state: QueueableState
/// The peripheral this operation is for.
var peripheral: CBPeripheral
/// The characteristic to read from.
private var characteristicIdentifier: CharacteristicIdentifier
/// Callback for the read attempt.
private var callback: ((ReadResult<T>) -> Void)?
init(characteristicIdentifier: CharacteristicIdentifier, peripheral: CBPeripheral, callback: @escaping (ReadResult<T>) -> Void) {
self.state = .notStarted
self.characteristicIdentifier = characteristicIdentifier
self.peripheral = peripheral
self.callback = callback
}
func start() {
guard
let service = peripheral.service(with: characteristicIdentifier.service.uuid),
let characteristic = service.characteristic(with: characteristicIdentifier.uuid)
else {
fail(BluejayError.missingCharacteristic(characteristicIdentifier))
return
}
state = .running
peripheral.readValue(for: characteristic)
log("Started read for \(characteristicIdentifier.uuid) on \(peripheral.identifier).")
}
func process(event: Event) {
if case .didReadCharacteristic(let readFrom, let value) = event {
if readFrom.uuid != characteristicIdentifier.uuid {
preconditionFailure("Expecting read from charactersitic: \(characteristicIdentifier.uuid), but actually read from: \(readFrom.uuid)")
}
state = .completed
log("Read for \(characteristicIdentifier.uuid) on \(peripheral.identifier) is successful.")
callback?(ReadResult<T>(dataResult: .success(value)))
callback = nil
updateQueue()
}
else {
preconditionFailure("Expecting write to characteristic: \(characteristicIdentifier.uuid), but received event: \(event)")
}
}
func cancel() {
cancelled()
}
func cancelled() {
state = .cancelled
log("Cancelled read for \(characteristicIdentifier.uuid) on \(peripheral.identifier).")
callback?(.cancelled)
callback = nil
updateQueue()
}
func fail(_ error: Error) {
state = .failed(error)
log("Failed reading for \(characteristicIdentifier.uuid) on \(peripheral.identifier) with error: \(error.localizedDescription)")
callback?(.failure(error))
callback = nil
updateQueue()
}
}
| mit | ad5089a542970234f1032b4e50df5911 | 29.23 | 149 | 0.612306 | 5.608534 | false | false | false | false |
m0rb1u5/Accediendo-a-la-nube-con-iOS_Semanas-1-2-3-y-5_Petici-n-al-servidor-openlibrary.org | Accediendo-a-la-nube-con-iOS_Semana-1_Petici-n-al-servidor-openlibrary.org/Libro.swift | 1 | 3729 | //
// Libro.swift
// Accediendo-a-la-nube-con-iOS_Semana-1_Petici-n-al-servidor-openlibrary.org
//
// Created by Juan Carlos Carbajal Ipenza on 11/11/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import Foundation
import UIKit
class Libro {
var isbn: String?
var titulo: String?
var autores: Array<String> = Array<String>()
var cover: UIImage?
init() {
self.isbn = nil
self.titulo = nil
self.autores = Array<String>()
self.cover = nil
}
init(isbn: String?, titulo: String?, autores: Array<String>, cover: UIImage?) {
self.isbn = isbn
self.titulo = titulo
self.autores = autores
self.cover = cover
}
func getAttributedText() -> NSMutableAttributedString {
let bodyFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
let bodyFont = UIFont(descriptor: bodyFontDescriptor, size: 0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributedText = NSMutableAttributedString.init(string: "")
if (self.titulo != nil) {
let boldFontDescriptor = bodyFont.fontDescriptor.withSymbolicTraits(.traitBold)
let boldFont = UIFont(descriptor: boldFontDescriptor!, size: 24.0)
let agregarTitulo = NSMutableAttributedString.init(string: self.titulo! + "\n")
agregarTitulo.addAttribute(NSFontAttributeName, value: boldFont, range: NSMakeRange(0, agregarTitulo.length))
agregarTitulo.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, agregarTitulo.length))
agregarTitulo.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 165/255, blue: 247/255, alpha: 1.0), range: NSMakeRange(0, agregarTitulo.length))
attributedText.append(agregarTitulo)
}
if (!self.autores.isEmpty) {
var texto_autores = "escrito por "
texto_autores += self.autores[0]
for index in 1..<self.autores.count {
texto_autores += ", "
texto_autores += self.autores[index]
}
texto_autores += "\n\n"
let agregarNombre = NSMutableAttributedString.init(string: texto_autores)
agregarNombre.addAttribute(NSFontAttributeName, value: bodyFont, range: NSMakeRange(0, agregarNombre.length))
agregarNombre.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, agregarNombre.length))
agregarNombre.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1.0), range: NSMakeRange(0, agregarNombre.length))
attributedText.append(agregarNombre)
}
if (self.cover != nil) {
let textAttachment = NSTextAttachment()
let image = self.cover!
textAttachment.image = image
textAttachment.bounds = CGRect(origin: CGPoint.zero, size: (image.size))
let textAttachmentString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textAttachment))
textAttachmentString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, textAttachmentString.length))
attributedText.append(textAttachmentString)
}
return attributedText
}
func isEmpty() -> Bool {
if (self.isbn == nil && self.titulo == nil && self.autores.isEmpty && self.cover == nil) {
return true
}
else {
return false
}
}
}
| gpl-3.0 | c517a2c00d8466926ea0248031389a95 | 46.189873 | 188 | 0.65853 | 4.804124 | false | false | false | false |
yuByte/Surge | Source/Exponential.swift | 9 | 3141 | // Exponential.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// 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 Accelerate
// MARK: Exponentiation
public func exp(x: [Float]) -> [Float] {
var results = [Float](count: x.count, repeatedValue: 0.0)
vvexpf(&results, x, [Int32(x.count)])
return results
}
public func exp(x: [Double]) -> [Double] {
var results = [Double](count: x.count, repeatedValue: 0.0)
vvexp(&results, x, [Int32(x.count)])
return results
}
// MARK: Square Exponentiation
public func exp2(x: [Float]) -> [Float] {
var results = [Float](count: x.count, repeatedValue: 0.0)
vvexp2f(&results, x, [Int32(x.count)])
return results
}
public func exp2(x: [Double]) -> [Double] {
var results = [Double](count: x.count, repeatedValue: 0.0)
vvexp2(&results, x, [Int32(x.count)])
return results
}
// MARK: Natural Logarithm
public func log(x: [Float]) -> [Float] {
var results = [Float](x)
vvlogf(&results, x, [Int32(x.count)])
return results
}
public func log(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog(&results, x, [Int32(x.count)])
return results
}
// MARK: Base-2 Logarithm
public func log2(x: [Float]) -> [Float] {
var results = [Float](x)
vvlog2f(&results, x, [Int32(x.count)])
return results
}
public func log2(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog2(&results, x, [Int32(x.count)])
return results
}
// MARK: Base-10 Logarithm
public func log10(x: [Float]) -> [Float] {
var results = [Float](x)
vvlog10f(&results, x, [Int32(x.count)])
return results
}
public func log10(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog10(&results, x, [Int32(x.count)])
return results
}
// MARK: Logarithmic Exponentiation
public func logb(x: [Float]) -> [Float] {
var results = [Float](x)
vvlogbf(&results, x, [Int32(x.count)])
return results
}
public func logb(x: [Double]) -> [Double] {
var results = [Double](x)
vvlogb(&results, x, [Int32(x.count)])
return results
}
| mit | e0331a47ad2338fadc8f4601221e44a9 | 25.378151 | 80 | 0.667729 | 3.453245 | false | false | false | false |
vzool/ios-nanodegree-earth-diary | Charts/Classes/Utils/ChartTransformer.swift | 51 | 10148 | //
// ChartTransformer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 6/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards.
public class ChartTransformer: NSObject
{
/// matrix to map the values to the screen pixels
internal var _matrixValueToPx = CGAffineTransformIdentity
/// matrix for handling the different offsets of the chart
internal var _matrixOffset = CGAffineTransformIdentity
internal var _viewPortHandler: ChartViewPortHandler
public init(viewPortHandler: ChartViewPortHandler)
{
_viewPortHandler = viewPortHandler
}
/// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets.
public func prepareMatrixValuePx(#chartXMin: Double, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Double)
{
var scaleX = (_viewPortHandler.contentWidth / deltaX)
var scaleY = (_viewPortHandler.contentHeight / deltaY)
// setup all matrices
_matrixValueToPx = CGAffineTransformIdentity
_matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY)
_matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin))
}
/// Prepares the matrix that contains all offsets.
public func prepareMatrixOffset(inverted: Bool)
{
if (!inverted)
{
_matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom)
}
else
{
_matrixOffset = CGAffineTransformMakeScale(1.0, -1.0)
_matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop)
}
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the SCATTERCHART.
public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
for (var j = 0; j < entries.count; j++)
{
var e = entries[j]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BUBBLECHART.
public func generateTransformedValuesBubble(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint]
{
let count = to - from
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(count)
for (var j = 0; j < count; j++)
{
var e = entries[j + from]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex - from) * phaseX + CGFloat(from), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the LINECHART.
public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint]
{
let count = Int(ceil(CGFloat(to - from) * phaseX))
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(count)
for (var j = 0; j < count; j++)
{
var e = entries[j + from]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the CANDLESTICKCHART.
public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
for (var j = 0; j < entries.count; j++)
{
var e = entries[j]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
var setCount = barData.dataSetCount
var space = barData.groupSpace
for (var j = 0; j < entries.count; j++)
{
var e = entries[j]
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + (e.xIndex * (setCount - 1)) + dataSet) + space * CGFloat(e.xIndex) + space / 2.0
var y = e.value
valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
var setCount = barData.dataSetCount
var space = barData.groupSpace
for (var j = 0; j < entries.count; j++)
{
var e = entries[j]
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + (e.xIndex * (setCount - 1)) + dataSet) + space * CGFloat(e.xIndex) + space / 2.0
var y = e.value
valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transform an array of points with all matrices.
// VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming.
public func pointValuesToPixel(inout pts: [CGPoint])
{
var trans = valueToPixelMatrix
for (var i = 0, count = pts.count; i < count; i++)
{
pts[i] = CGPointApplyAffineTransform(pts[i], trans)
}
}
public func pointValueToPixel(inout point: CGPoint)
{
point = CGPointApplyAffineTransform(point, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices.
public func rectValueToPixel(inout r: CGRect)
{
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
if (r.origin.y > 0.0)
{
r.origin.y *= phaseY
}
else
{
var bottom = r.origin.y + r.size.height
bottom *= phaseY
r.size.height = bottom - r.origin.y
}
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
if (r.origin.x > 0.0)
{
r.origin.x *= phaseY
}
else
{
var right = r.origin.x + r.size.width
right *= phaseY
r.size.width = right - r.origin.x
}
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// transforms multiple rects with all matrices
public func rectValuesToPixel(inout rects: [CGRect])
{
var trans = valueToPixelMatrix
for (var i = 0; i < rects.count; i++)
{
rects[i] = CGRectApplyAffineTransform(rects[i], trans)
}
}
/// Transforms the given array of touch points (pixels) into values on the chart.
public func pixelsToValue(inout pixels: [CGPoint])
{
var trans = pixelToValueMatrix
for (var i = 0; i < pixels.count; i++)
{
pixels[i] = CGPointApplyAffineTransform(pixels[i], trans)
}
}
/// Transforms the given touch point (pixels) into a value on the chart.
public func pixelToValue(inout pixel: CGPoint)
{
pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix)
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart.
public func getValueByTouchPoint(point: CGPoint) -> CGPoint
{
return CGPointApplyAffineTransform(point, pixelToValueMatrix)
}
public var valueToPixelMatrix: CGAffineTransform
{
return
CGAffineTransformConcat(
CGAffineTransformConcat(
_matrixValueToPx,
_viewPortHandler.touchMatrix
),
_matrixOffset
)
}
public var pixelToValueMatrix: CGAffineTransform
{
return CGAffineTransformInvert(valueToPixelMatrix)
}
} | mit | 6bee4d11f8dc3b9b3b3b6aed18edf0d9 | 33.876289 | 153 | 0.628597 | 5.03373 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/Foundation/NSRange.swift | 1 | 7739 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSRange : Hashable {
public var hashValue: Int {
#if arch(i386) || arch(arm)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 16)))
#elseif arch(x86_64) || arch(arm64)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 32)))
#endif
}
public static func==(lhs: NSRange, rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
}
extension NSRange : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return "{\(location), \(length)}" }
public var debugDescription: String {
guard location != NSNotFound else {
return "{NSNotFound, \(length)}"
}
return "{\(location), \(length)}"
}
}
extension NSRange {
public init?(_ string: __shared String) {
var savedLocation = 0
if string.isEmpty {
// fail early if the string is empty
return nil
}
let scanner = Scanner(string: string)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return nil
}
var location = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&location) else {
return nil
}
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return nil
}
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
location = integral
}
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return nil
}
var length = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&length) else {
return nil
}
if !scanner.isAtEnd {
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
length = integral
}
}
self.init(location: location, length: length)
}
}
extension NSRange {
public var lowerBound: Int { return location }
public var upperBound: Int { return location + length }
public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) }
public mutating func formUnion(_ other: NSRange) {
self = union(other)
}
public func union(_ other: NSRange) -> NSRange {
let max1 = location + length
let max2 = other.location + other.length
let maxend = (max1 < max2) ? max2 : max1
let minloc = location < other.location ? location : other.location
return NSRange(location: minloc, length: maxend - minloc)
}
public func intersection(_ other: NSRange) -> NSRange? {
let max1 = location + length
let max2 = other.location + other.length
let minend = (max1 < max2) ? max1 : max2
if other.location <= location && location < max2 {
return NSRange(location: location, length: minend - location)
} else if location <= other.location && other.location < max1 {
return NSRange(location: other.location, length: minend - other.location);
}
return nil
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init<R: RangeExpression>(_ region: R)
where R.Bound: FixedWidthInteger {
let r = region.relative(to: 0..<R.Bound.max)
self.init(location: numericCast(r.lowerBound), length: numericCast(r.count))
}
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
where R.Bound == S.Index, S.Index == String.Index {
let r = region.relative(to: target)
self = NSRange(
location: r.lowerBound.encodedOffset - target.startIndex.encodedOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset
)
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
extension Range where Bound: BinaryInteger {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}
// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}
extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: __shared String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }
self = lowerBound..<upperBound
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : _CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "NSRange.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .range(Int64(location), Int64(length))
}
}
extension NSRange : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let location = try container.decode(Int.self)
let length = try container.decode(Int.self)
self.init(location: location, length: length)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.location)
try container.encode(self.length)
}
}
| apache-2.0 | f2f41de424c2ce4231f0f1a14e684db0 | 34.177273 | 117 | 0.59633 | 4.750767 | false | false | false | false |
dasdom/Poster | ADN/PostService.swift | 1 | 2743 | //
// PostService.swift
// Jupp
//
// Created by dasdom on 05.12.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import Foundation
import Cocoa
import KeychainAccess
public class PostService: NSObject, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {
var session = NSURLSession()
public class var sharedService: PostService {
struct Singleton {
static let instance = PostService()
}
return Singleton.instance
}
// public func uploadImage(image: NSImage, session: NSURLSession, completion: ([String:AnyObject]) -> (), progress: (Float) -> ()) {
//
// self.session = session
//
// if let accessToken = KeychainAccess.passwordForAccount("AccessToken") {
// let imageUploadRequest = RequestFactory.imageUploadRequest(image, accessToken: accessToken)
//
//// let imageURL = ImageService().saveImageToUpload(image, name: "imageName")
//
// let sessionTask = session.dataTaskWithRequest(imageUploadRequest)
// sessionTask.resume()
// }
// }
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
println("didBecomeInvalidWithError \(error)")
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
println("didReceiveResponse: \(response)")
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
println("didSendBodyData")
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
println("didReceiveData")
dispatch_async(dispatch_get_main_queue()) {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("uploadImage dataString \(dataString)")
}
}
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
println("URLSessionDidFinishEventsForBackgroundURLSession")
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
println("didCompleteWithError: session \(session) task \(task) error \(error)")
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse!) -> Void) {
println("willCacheResponse")
}
}
| mit | f2dbe3be4f7f45da850b7dac3633d7fd | 37.633803 | 191 | 0.687204 | 5.586558 | false | false | false | false |
zhz821/KAWebBrowser | KAWebBrowser/Classes/KAWebBrowser.swift | 1 | 4225 | //
// KAWebBrowser.swift
// KAWebBrowser
//
// Created by zhihuazhang on 2016/06/08.
// Copyright © 2016年 Kapps Inc. All rights reserved.
//
import UIKit
import WebKit
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOTitle = "title"
open class KAWebBrowser: UIViewController {
fileprivate lazy var webView: WKWebView = {
let webView = WKWebView(frame: CGRect.zero)
return webView
}()
fileprivate lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.alpha = 0
return progressBar
}()
open class func navigationControllerWithBrowser() -> UINavigationController {
let browser = KAWebBrowser()
let closeBtn = UIBarButtonItem(barButtonSystemItem: .stop, target: browser, action: #selector(closeButtonPressed))
browser.navigationItem.leftBarButtonItem = closeBtn
return UINavigationController(rootViewController: browser)
}
open func loadURLString(_ urlString: String) {
guard let url = URL(string: urlString) else {
return
}
loadURL(url)
}
open func loadURL(_ url: URL) {
let request = URLRequest(url: url)
loadRequest(request)
}
open func loadRequest(_ request: URLRequest) {
webView.load(request)
}
override open func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: .alignAllLeft, metrics: nil, views: ["webView": webView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: .alignAllTop, metrics: nil, views: ["webView": webView]))
webView.addObserver(self, forKeyPath: KVOTitle, options: .new, context: nil)
guard let _ = navigationController else {
print("need UINavigationController to show progressbar")
return
}
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
view.addSubview(progressBar)
progressBar.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: progressBar, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[progressBar]|", options: .alignAllLeft, metrics: nil, views: ["progressBar": progressBar]))
}
fileprivate func updateProgressBar(_ progress: Float) {
if progress == 1.0 {
progressBar.setProgress(progress, animated: true)
UIView.animate(withDuration: 1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if progressBar.alpha < 1.0 {
progressBar.alpha = 1.0
}
progressBar.setProgress(progress, animated: (progress > progressBar.progress) && true)
}
}
@objc func closeButtonPressed() {
navigationController?.dismiss(animated: true, completion: nil)
}
deinit{
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOTitle)
}
// MARK: - KVO
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == KVOEstimatedProgress {
updateProgressBar(Float(webView.estimatedProgress))
}
if keyPath == KVOTitle {
title = self.webView.title
}
}
}
extension UINavigationController {
public func webBrowser() -> KAWebBrowser? {
return viewControllers.first as? KAWebBrowser
}
}
| mit | 8ad13f79eba35cc9a25c0f3fc2aeb41c | 33.048387 | 173 | 0.63406 | 5.357868 | false | false | false | false |
powerytg/PearlCam | PearlCam/PearlFX/Filters/ContrastFilterNode.swift | 2 | 743 | //
// ContrastFilterNode.swift
// PearlCam
//
// Contrast filter node
//
// Created by Tiangong You on 6/10/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import GPUImage
class ContrastFilterNode: FilterNode {
var contrastFilter = ContrastAdjustment()
init() {
super.init(filter: contrastFilter)
enabled = true
}
var contrast : Float? {
didSet {
if contrast != nil {
contrastFilter.contrast = contrast!
}
}
}
override func cloneFilter() -> FilterNode? {
let clone = ContrastFilterNode()
clone.enabled = enabled
clone.contrast = contrast
return clone
}
}
| bsd-3-clause | 496bacb6079a0f2f58cf3a6b581aa30e | 18.526316 | 55 | 0.578167 | 4.416667 | false | false | false | false |
pt-dot/DOTFlatButton | DOTFlatButton/Classes/DOTFlatButton.swift | 1 | 9867 | //
// DOTFlatButton.swift
// DOTFlatButton
//
// Created by Agus Cahyono on 6/29/16.
// Copyright © 2016 DOT Indonesia. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UICOLOR Extension
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
/// Color Inspired from http://flatuicolors.com/
/// TURQUOISE COLOR
class DOTFlatButtonTurQuoise: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x1abc9c)
self.tintColor = UIColor.whiteColor()
}
}
/// EMERALD COLOR
class DOTFlatButtonEmerald: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x2ecc71)
self.tintColor = UIColor.whiteColor()
}
}
/// PITER REVER COLOR
class DOTFlatButtonPeterRiver: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x3498db)
self.tintColor = UIColor.whiteColor()
}
}
/// AMETHYST COLOR
class DOTFlatButtonAmethyst: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x9b59b6)
self.tintColor = UIColor.whiteColor()
}
}
/// WET ASPALT COLOR
class DOTFlatButtonWetAspalt: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x34495e)
self.tintColor = UIColor.whiteColor()
}
}
/// GREEN SEA COLOR
class DOTFlatButtonGreenSea: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x16a085)
self.tintColor = UIColor.whiteColor()
}
}
/// NEPHRITIS COLOR
class DOTFlatButtonNephRitis: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x27ae60)
self.tintColor = UIColor.whiteColor()
}
}
/// BELIZE HOLE COLOR
class DOTFlatButtonBelizeHole: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x2980b9)
self.tintColor = UIColor.whiteColor()
}
}
/// WISTERIA COLOR
class DOTFlatButtonWisteria: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x8e44ad)
self.tintColor = UIColor.whiteColor()
}
}
/// MIDNIGHT BLUE COLOR
class DOTFlatButtonMidnightBlue: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x2c3e50)
self.tintColor = UIColor.whiteColor()
}
}
/// SUN FLOWER COLOR
class DOTFlatButtonSunFLower: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xf1c40f)
self.tintColor = UIColor.whiteColor()
}
}
/// CARROT COLOR
class DOTFlatButtonCarrot: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xe67e22)
self.tintColor = UIColor.whiteColor()
}
}
/// ALIZARIN COLOR
class DOTFlatButtonAlizarin: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xe74c3c)
self.tintColor = UIColor.whiteColor()
}
}
/// CLOUDS COLOR
class DOTFlatButtonClouds: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xecf0f1)
self.tintColor = UIColor.whiteColor()
}
}
/// CONCRETE COLOR
class DOTFlatButtonConcrete: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x95a5a6)
self.tintColor = UIColor.whiteColor()
}
}
/// ORANGE COLOR
class DOTFlatButtonOrange: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xf39c12)
self.tintColor = UIColor.whiteColor()
}
}
/// PUMPKIN COLOR
class DOTFlatButtonPumpkin: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xd35400)
self.tintColor = UIColor.whiteColor()
}
}
/// POMEGRENATE COLOR
class DOTFlatButtonPomeGrenate: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xc0392b)
self.tintColor = UIColor.whiteColor()
}
}
/// SILVER COLOR
class DOTFlatButtonSilver: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0xbdc3c7)
self.tintColor = UIColor.whiteColor()
}
}
/// ASBESTOS COLOR
class DOTFlatButtonAsbestos: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 0.0
self.layer.borderColor = UIColor.clearColor().CGColor
self.layer.borderWidth = 1.0
self.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)
self.backgroundColor = UIColor(netHex: 0x7f8c8d)
self.tintColor = UIColor.whiteColor()
}
}
| mit | f349c88e0136b9b56b15763b129d0337 | 33.376307 | 116 | 0.661666 | 4.025296 | false | false | false | false |
lorentey/GlueKit | Tests/GlueKitTests/ObservableTypeTests.swift | 1 | 2626 | //
// ObservableTypeTests.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-28.
// Copyright © 2015–2017 Károly Lőrentey.
//
import XCTest
import GlueKit
class ObservableTypeTests: XCTestCase {
func test_UpdatableType_withTransaction() {
let test = TestUpdatable(0)
let sink = MockUpdateSink<TestChange>()
test.updates.add(sink)
sink.expecting(["begin", "end"]) {
test.withTransaction {}
}
sink.expecting(["begin", "0 -> 1", "end"]) {
test.withTransaction {
test.apply(TestChange(from: 0, to: 1))
}
}
sink.expecting(["begin", "1 -> 2", "2 -> 3", "end"]) {
test.withTransaction {
test.apply(TestChange(from: 1, to: 2))
test.apply(TestChange(from: 2, to: 3))
}
}
sink.expecting(["begin", "3 -> 4", "end"]) {
test.withTransaction {
test.withTransaction {
test.apply(TestChange(from: 3, to: 4))
}
}
}
test.updates.remove(sink)
}
func test_UpdatableType_applyChange() {
let test = TestUpdatable(0)
let sink = MockUpdateSink<TestChange>()
test.updates.add(sink)
sink.expecting(["begin", "0 -> 1", "end"]) {
test.apply(TestChange([0, 1]))
}
test.updates.remove(sink)
}
#if false // TODO Compiler crash in Xcode 8.3.2
func test_Connector_connectObservableToUpdateSink() {
let observable = TestObservable(0)
let connector = Connector()
var received: [Update<TestChange>] = []
connector.connect(observable) { update in received.append(update) }
observable.value = 1
XCTAssertEqual(received.map { "\($0)" }, ["beginTransaction", "change(0 -> 1)", "endTransaction"])
received = []
connector.disconnect()
observable.value = 2
XCTAssertEqual(received.map { "\($0)" }, [])
}
#endif
#if false // TODO Compiler crash in Xcode 8.3.2
func test_Connector_connectObservableToChangeSink() {
let observable = TestObservable(0)
let connector = Connector()
var received: [TestChange] = []
connector.connect(observable) { change in received.append(change) }
observable.value = 1
XCTAssertEqual(received.map { "\($0)" }, ["0 -> 1"])
received = []
connector.disconnect()
observable.value = 2
XCTAssertEqual(received.map { "\($0)" }, [])
}
#endif
}
| mit | 9f4919faa593bbd7aecf202d002cebe4 | 24.427184 | 106 | 0.545628 | 4.321782 | false | true | false | false |
orta/Moya | Demo/DemoTests/EndpointSpec.swift | 1 | 3644 | import Quick
import Moya
import Nimble
extension Moya.ParameterEncoding: Equatable {
}
public func ==(lhs: Moya.ParameterEncoding, rhs: Moya.ParameterEncoding) -> Bool {
switch (lhs, rhs) {
case (.URL, .URL):
return true
case (.JSON, .JSON):
return true
case (.PropertyList(_), .PropertyList(_)):
return true
case (.Custom(_), .Custom(_)):
return true
default:
return false
}
}
class EndpointSpec: QuickSpec {
override func spec() {
describe("an endpoint") { () -> () in
var endpoint: Endpoint<GitHub>!
beforeEach { () -> () in
let target: GitHub = .Zen
let parameters = ["Nemesis": "Harvey"]
let headerFields = ["Title": "Dominar"]
endpoint = Endpoint<GitHub>(URL: url(target), sampleResponse: .Success(200, {target.sampleData}), method: Moya.Method.GET, parameters: parameters, parameterEncoding: .JSON, httpHeaderFields: headerFields)
}
it("returns a new endpoint for endpointByAddingParameters") {
let message = "I hate it when villains quote Shakespeare."
let newEndpoint = endpoint.endpointByAddingParameters(["message": message])
let newEndpointMessageObject: AnyObject? = newEndpoint.parameters["message"]
let newEndpointMessage = newEndpointMessageObject as? String
// Make sure our closure updated the sample response, as proof that it can modify the Endpoint
expect(newEndpointMessage).to(equal(message))
// Compare other properties to ensure they've been copied correctly
expect(newEndpoint.URL).to(equal(endpoint.URL))
expect(newEndpoint.method).to(equal(endpoint.method))
expect(newEndpoint.parameterEncoding).to(equal(endpoint.parameterEncoding))
expect(newEndpoint.httpHeaderFields.count).to(equal(endpoint.httpHeaderFields.count))
}
it("returns a new endpoint for endpointByAddingHTTPHeaderFields") {
let agent = "Zalbinian"
let newEndpoint = endpoint.endpointByAddingHTTPHeaderFields(["User-Agent": agent])
let newEndpointAgentObject: AnyObject? = newEndpoint.httpHeaderFields["User-Agent"]
let newEndpointAgent = newEndpointAgentObject as? String
// Make sure our closure updated the sample response, as proof that it can modify the Endpoint
expect(newEndpointAgent).to(equal(agent))
// Compare other properties to ensure they've been copied correctly
expect(newEndpoint.URL).to(equal(endpoint.URL))
expect(newEndpoint.method).to(equal(endpoint.method))
expect(newEndpoint.parameters.count).to(equal(endpoint.parameters.count))
expect(newEndpoint.parameterEncoding).to(equal(endpoint.parameterEncoding))
}
it("returns a correct URL request") {
let request = endpoint.urlRequest
expect(request.URL!.absoluteString).to(equal("https://api.github.com/zen"))
expect(NSString(data: request.HTTPBody!, encoding: 4)).to(equal("{\"Nemesis\":\"Harvey\"}"))
let titleObject: AnyObject? = endpoint.httpHeaderFields["Title"]
let title = titleObject as? String
expect(title).to(equal("Dominar"))
}
}
}
}
| mit | dd2f023e64b4099f44b689393a378b64 | 46.324675 | 220 | 0.597695 | 5.343109 | false | false | false | false |
cocoascientist/Jetstream | JetstreamPresentation/ViewModel/TodayViewModel.swift | 1 | 995 | //
// TodayViewModel.swift
// Jetstream-iOS
//
// Created by Andrew Shepard on 9/29/19.
// Copyright © 2019 Andrew Shepard. All rights reserved.
//
import Foundation
import JetstreamCore
public struct TodayConditionsViewModel {
let forecast: Forecast?
public var dayOfWeek: String {
guard let forecast = forecast else { return "" }
let date = Date(timeIntervalSince1970: forecast.timestamp.timeIntervalSince1970)
return DateFormatter.dayOfWeek.string(from: date)
}
public var lowTemperature: String {
guard let forecast = forecast else { return "" }
let temperature = NSNumber(value: forecast.lowTemp)
return NumberFormatter.decimal.string(from: temperature) ?? ""
}
public var highTemperature: String {
guard let forecast = forecast else { return "" }
let temperature = NSNumber(value: forecast.highTemp)
return NumberFormatter.decimal.string(from: temperature) ?? ""
}
}
| mit | 484c6eb343934e72a7a953acee8e16e5 | 30.0625 | 88 | 0.677062 | 4.64486 | false | false | false | false |
pikacode/EBBannerView | EBBannerView/SwiftClasses/EBCustomBanner.swift | 1 | 6746 | //
// EBCustomBanner.swift
// EBBannerViewSwift
//
// Created by pikacode on 2020/1/2.
//
import UIKit
import AudioToolbox
class EBCustomBanner: NSObject {
static var sharedBanners = [EBCustomBanner]()
static let sharedWindow = EBBannerWindow.shared
enum TransitionStyle {
case top, left, right, bottom
case center(durations: (alpha: TimeInterval, max: TimeInterval, final: TimeInterval) = (0.3, 0.2, 0.1))
}
init(view: UIView) {
self.view = view
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidChangeStatusBarOrientation), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil)
}
///make a custom view and show immediately,
@discardableResult
static func show(_ view: UIView) -> EBCustomBanner { return EBCustomBanner(view: view).show() }
@discardableResult
func show() -> EBCustomBanner {
EBCustomBanner.sharedBanners.append(self)
var soundID: SystemSoundID = 0
switch maker.soundID {
case .none:
break
case .name(let name):
guard let url = Bundle.main.url(forResource: name, withExtension: nil) else { break }
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
case .id(let id):
soundID = id
}
EBMuteDetector.shared.detect { (isMute) in
if isMute && self.maker.vibrateOnMute {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
} else {
AudioServicesPlaySystemSound(soundID)
}
}
EBCustomBanner.sharedWindow.rootViewController?.view.addSubview(view)
switch currentStyle {
case .center(durations: let durations):
DispatchQueue.main.async { [weak self] in
guard let weakSelf = self else { return }
weakSelf.view.frame = weakSelf.showFrame
weakSelf.view.alpha = 0
UIView.animate(withDuration: durations.alpha, animations: {
weakSelf.view.alpha = 1
})
weakSelf.view.alpha = 0
weakSelf.view.layer.shouldRasterize = true
weakSelf.view.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
UIView.animate(withDuration: durations.max, animations: {
weakSelf.view.alpha = 1
weakSelf.view.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}) { _ in
UIView.animate(withDuration: durations.final, animations: {
weakSelf.view.alpha = 1
weakSelf.view.transform = CGAffineTransform.identity
}) { _ in
weakSelf.view.layer.shouldRasterize = false
if weakSelf.maker.stayDuration > 0 {
Timer.scheduledTimer(timeInterval: weakSelf.maker.stayDuration, target: weakSelf, selector: #selector(weakSelf.hide), userInfo: nil, repeats: false)
}
}
}
}
default:
view.frame = hideFrame
UIView.animate(withDuration: maker.animationDuration, animations: {
self.view.frame = self.showFrame
}) { (finish) in
if self.maker.stayDuration > 0 {
Timer.scheduledTimer(timeInterval: self.maker.stayDuration, target: self, selector: #selector(self.hide), userInfo: nil, repeats: false)
}
}
}
return self
}
@objc func hide() {
if view.superview == nil {
return
}
switch currentStyle {
case .center(durations: let durations):
DispatchQueue.main.async { [weak self] in
UIView.animate(withDuration: durations.alpha) {
self?.view.alpha = 0
}
self?.view.layer.shouldRasterize = true
UIView.animate(withDuration: durations.max, animations: {
self?.view.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}) { (finish) in
UIView.animate(withDuration: durations.final, animations: {
self?.view.alpha = 0
self?.view.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
}) { (finish) in
self?.view.removeFromSuperview()
guard let weakSelf = self else { return }
guard let index = EBCustomBanner.sharedBanners.firstIndex(of: weakSelf) else { return }
EBCustomBanner.sharedBanners.remove(at: index)
}
}
}
default:
UIView.animate(withDuration: maker.animationDuration, animations: {
self.view.frame = self.hideFrame
}) { (finish) in
self.view.removeFromSuperview()
EBCustomBanner.sharedBanners.removeAll { $0 == self }
}
}
}
private var view: UIView
private let maker = EBCustomBannerMaker()
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension EBCustomBanner {
var currentIsLandscape: Bool { return UIDevice.current.orientation.isLandscape }
var showFrame: CGRect { return currentIsLandscape ? maker.landscapeFrame : maker.portraitFrame }
var currentStyle: TransitionStyle { return currentIsLandscape ? maker.landscapeStyle : maker.portraitStyle }
var hideFrame: CGRect {
var hideFrame = showFrame
let screenSize = UIScreen.main.bounds.size
switch currentStyle {
case .top:
hideFrame.origin.y = -hideFrame.size.height
case .left:
hideFrame.origin.x = -hideFrame.size.width
case .right:
hideFrame.origin.x = screenSize.width + hideFrame.size.width
case .bottom:
hideFrame.origin.y = screenSize.height
default:
break;
}
return hideFrame
}
@objc func applicationDidChangeStatusBarOrientation() {
if EBCustomBanner.sharedBanners.count == 0 {
return
}
if currentIsLandscape {
EBCustomBanner.sharedBanners.forEach{ $0.view.frame = $0.maker.landscapeFrame }
} else {
EBCustomBanner.sharedBanners.forEach{ $0.view.frame = $0.maker.portraitFrame}
}
}
}
| mit | e5f6e7456c10e27f7b1bad6446f7232b | 35.074866 | 191 | 0.56137 | 5.221362 | false | false | false | false |
tootbot/tootbot | Pods/KeyboardLayoutGuide/Swift-3/KeyboardLayoutGuide/KeyboardLayoutGuide/KeyboardLayoutGuide.swift | 1 | 9263 | //
// KeyboardLayoutGuide.swift
// KeyboardLayoutGuide
//
// Created by Zachary Waldowski on 8/23/15.
// Copyright © 2015-2016. Licensed under MIT. Some rights reserved.
//
import UIKit
/// A keyboard layout guide may be used as an item in Auto Layout, for its
/// layout anchors, or may be queried for its length property.
public final class KeyboardLayoutGuide: UILayoutGuide, UILayoutSupport {
private static let didUpdate = Notification.Name(rawValue: "KeyboardLayoutGuideDidUpdateNotification")
// MARK: Lifecycle
private let notificationCenter: NotificationCenter
private func commonInit() {
notificationCenter.addObserver(self, selector: #selector(noteKeyboardShow), name: .UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteKeyboardHide), name: .UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteKeyboardShow), name: .UIKeyboardDidChangeFrame, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteAncestorGuideUpdate), name: KeyboardLayoutGuide.didUpdate, object: nil)
}
public override convenience init() {
self.init(notificationCenter: .default)
}
public required init?(coder aDecoder: NSCoder) {
self.notificationCenter = .default
super.init(coder: aDecoder)
commonInit()
}
init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
commonInit()
}
// MARK: Public API
/// If assigned, and this scroll view contains the first responder, it will
/// be scrolled into view upon any keyboard change.
///
/// It is not necessary to track the scroll view that is managed as the
/// primary view of a `UITableViewController` or, as of iOS 9,
/// `UICollectionViewController`.
public weak var avoidFirstResponderInScrollView: UIScrollView?
// MARK: UILayoutGuide
/// The view that owns this layout guide.
override public weak var owningView: UIView? {
didSet {
activateConstraints()
}
}
// MARK: UILayoutSupport
/// Provides the length, in points, of the portion of a view controller’s
/// view that is visible outside of translucent or transparent UIKit bars
/// and the keyboard.
public var length: CGFloat {
return layoutFrame.height
}
// MARK: Actions
private var keyboardBottomConstraint: NSLayoutConstraint?
private func activateConstraints() {
guard let view = owningView else {
keyboardBottomConstraint = nil
return
}
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
view.layoutMarginsGuide.trailingAnchor.constraint(equalTo: trailingAnchor), {
let constraint = topAnchor.constraint(equalTo: view.topAnchor)
constraint.priority = UILayoutPriorityDefaultLow
return constraint
}(), {
let constraint = view.bottomAnchor.constraint(equalTo: bottomAnchor)
constraint.priority = 998
self.keyboardBottomConstraint = constraint
return constraint
}()
])
}
@objc
private func updateKeyboard(forUserInfo userInfo: [AnyHashable: Any]?) {
let info = KeyboardInfo(userInfo: userInfo)
guard info.isLocal else { return }
let oldOverlap = keyboardBottomConstraint?.constant ?? 0
guard let view = owningView, !view.isEffectivelyDisappearing else { return }
let newOverlap = info.overlap(in: view)
keyboardBottomConstraint?.constant = newOverlap
info.animate {
self.avoidFirstResponderInScrollView?.contentInset.bottom += newOverlap - oldOverlap
self.avoidFirstResponderInScrollView?.scrollFirstResponderToVisible(animated: true)
view.layoutIfNeeded()
NotificationCenter.default.post(name: KeyboardLayoutGuide.didUpdate, object: view, userInfo: userInfo)
}
}
// MARK: - Notifications
@objc
private func noteKeyboardShow(note: Notification) {
type(of: self).cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateKeyboard), object: nil)
updateKeyboard(forUserInfo: note.userInfo)
}
@objc
private func noteKeyboardHide(note: Notification) {
perform(#selector(updateKeyboard), with: nil, afterDelay: 0, inModes: [ .commonModes ])
}
@objc private func noteAncestorGuideUpdate(note: Notification) {
guard let view = owningView, let ancestorView = note.object as? UIView,
view !== ancestorView, view.isDescendant(of: ancestorView) else { return }
keyboardBottomConstraint?.constant = KeyboardInfo(userInfo: note.userInfo).overlap(in: view)
}
}
// MARK: - UIViewController
extension UIViewController {
private static var keyboardLayoutGuideKey = false
/// For unit testing purposes only.
@nonobjc
internal func makeKeyboardLayoutGuide(notificationCenter: NotificationCenter) -> KeyboardLayoutGuide {
assert(isViewLoaded, "This layout guide should not be accessed before the view is loaded.")
let guide = KeyboardLayoutGuide(notificationCenter: notificationCenter)
view.addLayoutGuide(guide)
NSLayoutConstraint.activate([
guide.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
bottomLayoutGuide.topAnchor.constraint(greaterThanOrEqualTo: guide.bottomAnchor)
])
return guide
}
/// A keyboard layout guide is a rectangle in the layout system representing
/// the area on screen not currently occupied by the keyboard; thus, it is a
/// simplified model for performing layout by avoiding the keyboard.
///
/// Normally, the guide is a rectangle matching the top and bottom
/// guides of a receiving view controller and the leading and trailing
/// margins of its view. When the keyboard is active.
///
/// - seealso: KeyboardLayoutGuide
@nonobjc
public var keyboardLayoutGuide: KeyboardLayoutGuide {
if let guide = objc_getAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey) as? KeyboardLayoutGuide {
return guide
}
let guide = makeKeyboardLayoutGuide(notificationCenter: .default)
objc_setAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey, guide, .OBJC_ASSOCIATION_ASSIGN)
return guide
}
}
// MARK: - Extensions
private extension UIView {
func findNextViewController() -> UIViewController? {
var next: UIResponder? = self
while let current = next {
if let vc = current as? UIViewController { return vc }
next = current.next
}
return nil
}
var isEffectivelyInPopover: Bool {
guard let vc = findNextViewController() else { return false }
var presenter = vc.presentingViewController
while let current = presenter {
if current.presentationController is UIPopoverPresentationController { return true }
if current.presentationController?.shouldPresentInFullscreen == true { return false }
presenter = current.presentingViewController
}
return false
}
var isEffectivelyDisappearing: Bool {
guard let vc = findNextViewController() else { return false }
return vc.isBeingDismissed || vc.isMovingFromParentViewController
}
}
private struct KeyboardInfo {
let animationDuration: TimeInterval
let animationCurve: UIViewAnimationOptions
let endFrame: CGRect
let isLocal: Bool
init(userInfo: [AnyHashable: Any]?) {
self.animationDuration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0.25
self.animationCurve = UIViewAnimationOptions(rawValue: ((userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? UInt) ?? 7) << 16)
self.endFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect ?? .zero
self.isLocal = (userInfo?[UIKeyboardIsLocalUserInfoKey] as? Bool) ?? true
}
func animate(by animations: @escaping() -> Void) {
// When performing a keyboard update around a screen rotation animation,
// UIKit disables animations and sends a duration of 0.
//
// For the keyboard, we're just going to assume a layout pass happens
// soon. (And maybe pray. Just a little.)
guard UIView.areAnimationsEnabled && !animationDuration.isZero else { return }
UIView.animate(withDuration: animationDuration, delay: 0, options: [ animationCurve, .beginFromCurrentState ], animations: animations)
}
// Modeled after -[UIPeripheralHost getVerticalOverlapForView:usingKeyboardInfo:]
func overlap(in view: UIView) -> CGFloat {
guard !view.isEffectivelyInPopover, !endFrame.isEmpty, let target = view.superview else { return 0 }
let localMinY = target.convert(endFrame, from: UIScreen.main.coordinateSpace).minY
return max(view.frame.maxY - localMinY, 0)
}
}
| agpl-3.0 | b111b39d4bb87081776041e2fc8d748e | 36.489879 | 142 | 0.688877 | 5.421546 | false | false | false | false |
lukejmann/FBLA2017 | Pods/Instructions/Sources/Controllers/Public/CoachMark.swift | 1 | 5707 | // CoachMark.swift
//
// Copyright (c) 2015, 2016 Frédéric Maquin <[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
/// This structure handle the parametrization of a given coach mark.
/// It doesn't provide any clue about the way it will look, however.
public struct CoachMark {
// MARK: - Public properties
/// Change this value to change the duration of the fade.
public var animationDuration = Constants.coachMarkFadeAnimationDuration
/// The path to cut in the overlay, so the point of interest will be visible.
public var cutoutPath: UIBezierPath?
/// The vertical offset for the arrow (in rare cases, the arrow might need to overlap with
/// the coach mark body).
public var gapBetweenBodyAndArrow: CGFloat = 2.0
/// The orientation of the arrow, around the body of the coach mark (top or bottom).
public var arrowOrientation: CoachMarkArrowOrientation?
/// The "point of interest" toward which the arrow will point.
///
/// At the moment, it's only used to shift the arrow horizontally and make it sits above/below
/// the point of interest.
public var pointOfInterest: CGPoint?
/// Offset between the coach mark and the cutout path.
public var gapBetweenCoachMarkAndCutoutPath: CGFloat = 2.0
/// Maximum width for a coach mark.
public var maxWidth: CGFloat = 350
/// Trailing and leading margin of the coach mark.
public var horizontalMargin: CGFloat = 20
/// Set this property to `true` to disable a tap on the overlay.
/// (only if the tap capture was enabled)
///
/// If you need to disable the tap for all the coachmarks, prefer setting
/// `CoachMarkController.allowOverlayTap`.
public var disableOverlayTap: Bool = false
/// Set this property to `true` to allow touch forwarding inside the cutoutPath.
public var allowTouchInsideCutoutPath: Bool = false
// MARK: - Initialization
/// Allocate and initialize a Coach mark with default values.
public init () {
}
// MARK: - Internal Methods
/// This method perform both `computeOrientationInFrame` and `computePointOfInterestInFrame`.
///
/// - Parameter frame: the frame in which compute the orientation
/// (likely to match the overlay's frame)
internal mutating func computeMetadata(inFrame frame: CGRect) {
self.computeOrientation(inFrame: frame)
self.computePointOfInterest()
}
/// Compute the orientation of the arrow, given the frame in which the coach mark
/// will be displayed.
///
/// - Parameter frame: the frame in which compute the orientation
/// (likely to match the overlay's frame)
internal mutating func computeOrientation(inFrame frame: CGRect) {
// No cutout path means no arrow. That way, no orientation
// computation is needed.
guard let cutoutPath = self.cutoutPath else {
self.arrowOrientation = nil
return
}
if self.arrowOrientation != nil {
return
}
if cutoutPath.bounds.origin.y > frame.size.height / 2 {
self.arrowOrientation = .bottom
} else {
self.arrowOrientation = .top
}
}
/// Compute the orientation of the arrow, given the frame in which the coach mark
/// will be displayed.
internal mutating func computePointOfInterest() {
/// If the value is already set, don't do anything.
if self.pointOfInterest != nil { return }
/// No cutout path means no point of interest.
/// That way, no orientation computation is needed.
guard let cutoutPath = self.cutoutPath else { return }
let x = cutoutPath.bounds.origin.x + cutoutPath.bounds.width / 2
let y = cutoutPath.bounds.origin.y + cutoutPath.bounds.height / 2
self.pointOfInterest = CGPoint(x: x, y: y)
}
}
extension CoachMark: Equatable {}
public func == (lhs: CoachMark, rhs: CoachMark) -> Bool {
return lhs.animationDuration == rhs.animationDuration &&
lhs.cutoutPath == rhs.cutoutPath &&
lhs.gapBetweenBodyAndArrow == rhs.gapBetweenBodyAndArrow &&
lhs.arrowOrientation == rhs.arrowOrientation &&
lhs.pointOfInterest == rhs.pointOfInterest &&
lhs.gapBetweenCoachMarkAndCutoutPath == rhs.gapBetweenCoachMarkAndCutoutPath &&
lhs.maxWidth == rhs.maxWidth &&
lhs.horizontalMargin == rhs.horizontalMargin &&
lhs.disableOverlayTap == rhs.disableOverlayTap &&
lhs.allowTouchInsideCutoutPath == rhs.allowTouchInsideCutoutPath
}
| mit | d4541a3c637efc660c5db2c2bade9122 | 40.642336 | 98 | 0.68589 | 4.867747 | false | false | false | false |
diegosanchezr/Chatto | ChattoAdditions/Tests/Chat Items/PhotoMessages/PhotoMessagePresenterTests.swift | 1 | 4481 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 XCTest
@testable import ChattoAdditions
class PhotoMessagePresenterTests: XCTestCase, UICollectionViewDataSource {
var presenter: PhotoMessagePresenter<PhotoMessageViewModelDefaultBuilder, PhotoMessageTestHandler>!
let decorationAttributes = ChatItemDecorationAttributes(bottomMargin: 0, showsTail: false)
let testImage = UIImage()
override func setUp() {
let viewModelBuilder = PhotoMessageViewModelDefaultBuilder()
let sizingCell = PhotoMessageCollectionViewCell.sizingCell()
let photoStyle = PhotoMessageCollectionViewCellDefaultStyle()
let baseStyle = BaseMessageCollectionViewCellDefaultSyle()
let messageModel = MessageModel(uid: "uid", senderId: "senderId", type: "photo-message", isIncoming: true, date: NSDate(), status: .Success)
let photoMessageModel = PhotoMessageModel(messageModel: messageModel, imageSize: CGSize(width: 30, height: 30), image: self.testImage)
self.presenter = PhotoMessagePresenter(messageModel: photoMessageModel, viewModelBuilder: viewModelBuilder, interactionHandler: PhotoMessageTestHandler(), sizingCell: sizingCell, baseCellStyle: baseStyle, photoCellStyle: photoStyle)
}
func testThat_heightForCelReturnsPositiveHeight() {
let height = self.presenter.heightForCell(maximumWidth: 320, decorationAttributes: self.decorationAttributes)
XCTAssertTrue(height > 0)
}
func testThat_CellIsConfigured() {
let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero)
self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes)
XCTAssertEqual(self.testImage, cell.bubbleView.photoMessageViewModel.image.value)
}
func testThat_CanCalculateHeightInBackground() {
XCTAssertTrue(self.presenter.canCalculateHeightInBackground)
}
func testThat_RegistersAndDequeuesCells() {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
PhotoMessagePresenter<PhotoMessageViewModelDefaultBuilder, PhotoMessageTestHandler>.registerCells(collectionView)
collectionView.dataSource = self
collectionView.reloadData()
XCTAssertNotNil(self.presenter.dequeueCell(collectionView: collectionView, indexPath: NSIndexPath(forItem: 0, inSection: 0)))
collectionView.dataSource = nil
}
// MARK: Helpers
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return self.presenter.dequeueCell(collectionView: collectionView, indexPath: indexPath)
}
}
class PhotoMessageTestHandler: BaseMessageInteractionHandlerProtocol {
typealias ViewModelT = PhotoMessageViewModel
var didHandleTapOnFailIcon = false
func userDidTapOnFailIcon(viewModel viewModel: ViewModelT) {
self.didHandleTapOnFailIcon = true
}
var didHandleTapOnBubble = false
func userDidTapOnBubble(viewModel viewModel: ViewModelT) {
self.didHandleTapOnBubble = true
}
var didHandleLongPressOnBubble = false
func userDidLongPressOnBubble(viewModel viewModel: ViewModelT) {
self.didHandleLongPressOnBubble = true
}
}
| mit | afa6057fa7340fc96e85ec247a37f7df | 46.168421 | 240 | 0.772149 | 5.518473 | false | true | false | false |
wdkk/CAIM | Metal/caimmetal04/CAIM/CAIMViewController.swift | 28 | 2620 | //
// CAIMViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
public class CAIMViewController: UIViewController
{
// ビューコントローラ設定用オーバーライド関数
public func setup() {}
public func update() {}
public func teardown() {}
public var pixelX:CGFloat {
get { return self.view.pixelX }
set { self.view.pixelX = newValue }
}
public var pixelY:CGFloat {
get { return self.view.pixelY }
set { self.view.pixelY = newValue }
}
public var pixelWidth:CGFloat {
get { return self.view.pixelWidth }
set { self.view.pixelWidth = newValue }
}
public var pixelHeight:CGFloat {
get { return self.view.pixelHeight }
set { self.view.pixelHeight = newValue }
}
public var pixelFrame:CGRect {
get { return view.pixelFrame }
set { self.view.pixelFrame = newValue }
}
public var pixelBounds:CGRect {
get { return view.pixelBounds }
set { self.view.pixelBounds = newValue }
}
fileprivate var _display_link:CADisplayLink! // ループ処理用ディスプレイリンク
// ページがロード(生成)された時、処理される。主にUI部品などを作るときに利用
public override func viewDidLoad() {
// 親のviewDidLoadを呼ぶ[必須]
super.viewDidLoad()
self.view.backgroundColor = .white
}
public override func viewDidAppear(_ animated: Bool) {
// 親のviewDidAppearを呼ぶ
super.viewDidAppear(animated)
// オーバーライド関数のコール
setup()
// updateのループ処理を開始
_display_link = CADisplayLink(target: self, selector: #selector(CAIMViewController.polling(_:)))
_display_link.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
public override func viewDidDisappear(_ animated: Bool) {
// 親のviewDidAppearを呼ぶ
super.viewDidDisappear(animated)
// updateのループ処理を終了
_display_link.remove(from: RunLoop.current, forMode: RunLoopMode.commonModes)
teardown()
}
// CADisplayLinkで60fpsで呼ばれる関数
@objc func polling(_ display_link :CADisplayLink) {
// オーバーライド関数のコール
update()
}
}
| mit | e3ea0d71d1f9f9a59df1cf1be3a2abb3 | 27.216867 | 104 | 0.625107 | 3.969492 | false | false | false | false |
JakeLin/IBAnimatable | Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallClipRotatePulse.swift | 2 | 3599 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallClipRotatePulse: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1
fileprivate let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
animateSmallCircle(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
animateBigCircle(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
}
}
// MARK: Small circle
private extension ActivityIndicatorAnimationBallClipRotatePulse {
func animateSmallCircle(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
let animation = makeSmallCircleAnimation()
let circleSize = size.width / 2
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func makeSmallCircleAnimation() -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: .scale)
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
// MARK: Big circle
private extension ActivityIndicatorAnimationBallClipRotatePulse {
func animateBigCircle(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
let animation = makeBigCircleAnimation()
let circle = ActivityIndicatorShape.ringTwoHalfVertical.makeLayer(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func makeBigCircleAnimation() -> CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: .scale)
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
return scaleAnimation
}
var rotateAnimation: CAKeyframeAnimation {
let rotateAnimation = CAKeyframeAnimation(keyPath: .rotationZ)
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
rotateAnimation.duration = duration
return rotateAnimation
}
}
| mit | 3de1cd20b790bc3e096b7fe5fdfd8371 | 36.103093 | 138 | 0.720478 | 4.817938 | false | false | false | false |
envoyproxy/envoy | mobile/library/swift/RetryPolicyMapper.swift | 2 | 2281 | extension RetryPolicy {
/// Converts the retry policy to a set of headers recognized by Envoy.
///
/// - returns: The header representation of the retry policy.
func outboundHeaders() -> [String: [String]] {
var headers = [
"x-envoy-max-retries": ["\(self.maxRetryCount)"],
"x-envoy-upstream-rq-timeout-ms": ["\(self.totalUpstreamTimeoutMS ?? 0)"],
]
var retryOn = self.retryOn.map { $0.stringValue }
if !self.retryStatusCodes.isEmpty {
retryOn.append("retriable-status-codes")
headers["x-envoy-retriable-status-codes"] = self.retryStatusCodes.map { "\($0)" }
}
headers["x-envoy-retry-on"] = retryOn
if let perRetryTimeoutMS = self.perRetryTimeoutMS {
headers["x-envoy-upstream-rq-per-try-timeout-ms"] = ["\(perRetryTimeoutMS)"]
}
return headers
}
// Envoy internally coalesces multiple x-envoy header values into one comma-delimited value.
// These functions split those values up to correctly map back to Swift enums.
static func splitRetryRule(value: String) -> [RetryRule] {
return value.components(separatedBy: ",").compactMap(RetryRule.init)
}
static func splitRetriableStatusCodes(value: String) -> [UInt] {
return value.components(separatedBy: ",").compactMap(UInt.init)
}
/// Initialize the retry policy from a set of headers.
///
/// - parameter headers: The headers with which to initialize the retry policy.
///
/// - returns: The `RetryPolicy` if one was derived from the headers.
static func from(headers: Headers) -> RetryPolicy? {
guard let maxRetryCount = headers.value(forName: "x-envoy-max-retries")?
.first.flatMap(UInt.init) else
{
return nil
}
return RetryPolicy(
maxRetryCount: maxRetryCount,
retryOn: headers.value(forName: "x-envoy-retry-on")?
.flatMap(RetryPolicy.splitRetryRule) ?? [],
retryStatusCodes: headers.value(forName: "x-envoy-retriable-status-codes")?
.flatMap(RetryPolicy.splitRetriableStatusCodes) ?? [],
perRetryTimeoutMS: headers.value(forName: "x-envoy-upstream-rq-per-try-timeout-ms")?
.first.flatMap(UInt.init),
totalUpstreamTimeoutMS: headers.value(forName: "x-envoy-upstream-rq-timeout-ms")?
.first.flatMap(UInt.init)
)
}
}
| apache-2.0 | 2e258412b7cce71525247a8a1ecebccd | 37.661017 | 94 | 0.678211 | 3.953206 | false | false | false | false |
wircho/SwiftyNotification | SwiftyNotificationSample/SwiftyNotificationSample/ViewController.swift | 1 | 2405 | //
// ViewController.swift
// SwiftyNotificationSample
//
// Created by AdolfoX Rodriguez on 2016-06-01.
// Copyright © 2016 Mokriya. All rights reserved.
//
import UIKit
// MARK: Preparation
// Keyboard Appeared Notification
final class KeyboardAppeared: Notification {
static let name = UIKeyboardDidShowNotification
static func parameters(note: NSNotification) throws -> (beginFrame:CGRect,endFrame:CGRect) {
let beginFrame = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectNull
let endFrame = (note.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectNull
return (beginFrame,endFrame)
}
}
// Keyboard Disappeared Notification
final class KeyboardDisappeared: Notification {
static let name = UIKeyboardDidHideNotification
static func parameters(note: NSNotification) throws -> (beginFrame:CGRect,endFrame:CGRect) {
let beginFrame = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectNull
let endFrame = (note.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectNull
return (beginFrame,endFrame)
}
}
class ViewController: UIViewController {
// MARK: IBOutlets & IBActions
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var dismissKeyboardButton: UIButton!
@IBAction func dismissKeyboard(sender: AnyObject) {
textField.resignFirstResponder()
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Registering as observer
// No need to unregister, since that will happen
// once the view controller gets released
dismissKeyboardButton.enabled = false
KeyboardAppeared.register(self) {
innerSelf,params in
innerSelf.label.text = "Keyboard Appeared\nFrom \(params.beginFrame)\nTo \(params.endFrame)"
innerSelf.dismissKeyboardButton.enabled = true
}
KeyboardDisappeared.register(self) {
innerSelf,params in
innerSelf.label.text = "Keyboard Disappeared\nFrom \(params.beginFrame)\nTo \(params.endFrame)"
innerSelf.dismissKeyboardButton.enabled = false
}
}
}
| mit | 0a99aad4aa9cc0409ee454235bd31561 | 32.859155 | 115 | 0.678869 | 5.306843 | false | false | false | false |
KaiCode2/ResearchKit | samples/ORKSample/ORKSample/ProfileViewController.swift | 8 | 7254 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
import HealthKit
class ProfileViewController: UITableViewController, HealthClientType {
// MARK: Properties
let healthObjectTypes = [
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!
]
var healthStore: HKHealthStore?
@IBOutlet var applicationNameLabel: UILabel!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
guard let healthStore = healthStore else { fatalError("healhStore not set") }
// Ensure the table view automatically sizes its rows.
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
// Request authrization to query the health objects that need to be shown.
let typesToRequest = Set<HKObjectType>(healthObjectTypes)
healthStore.requestAuthorizationToShareTypes(nil, readTypes: typesToRequest) { authorized, error in
guard authorized else { return }
// Reload the table view cells on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock() {
let allRowIndexPaths = self.healthObjectTypes.enumerate().map { NSIndexPath(forRow: $0.index, inSection: 0) }
self.tableView.reloadRowsAtIndexPaths(allRowIndexPaths, withRowAnimation: .Automatic)
}
}
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return healthObjectTypes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier(ProfileStaticTableViewCell.reuseIdentifier, forIndexPath: indexPath) as? ProfileStaticTableViewCell else { fatalError("Unable to dequeue a ProfileStaticTableViewCell") }
let objectType = healthObjectTypes[indexPath.row]
switch(objectType.identifier) {
case HKCharacteristicTypeIdentifierDateOfBirth:
configureCellWithDateOfBirth(cell)
case HKQuantityTypeIdentifierHeight:
let title = NSLocalizedString("Height", comment: "")
configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier)
case HKQuantityTypeIdentifierBodyMass:
let title = NSLocalizedString("Weight", comment: "")
configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier)
default:
fatalError("Unexpected health object type identifier - \(objectType.identifier)")
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: Cell configuration
func configureCellWithDateOfBirth(cell: ProfileStaticTableViewCell) {
// Set the default cell content.
cell.titleLabel.text = NSLocalizedString("Date of Birth", comment: "")
cell.valueLabel.text = NSLocalizedString("-", comment: "")
// Update the value label with the date of birth from the health store.
guard let healthStore = healthStore else { return }
do {
let dateOfBirth = try healthStore.dateOfBirth()
let now = NSDate()
let ageComponents = NSCalendar.currentCalendar().components(.Year, fromDate: dateOfBirth, toDate: now, options: .WrapComponents)
let age = ageComponents.year
cell.valueLabel.text = "\(age)"
}
catch {
}
}
func configureCell(cell: ProfileStaticTableViewCell, withTitleText titleText: String, valueForQuantityTypeIdentifier identifier: String) {
// Set the default cell content.
cell.titleLabel.text = titleText
cell.valueLabel.text = NSLocalizedString("-", comment: "")
/*
Check a health store has been set and a `HKQuantityType` can be
created with the identifier provided.
*/
guard let healthStore = healthStore, quantityType = HKQuantityType.quantityTypeForIdentifier(identifier) else { return }
// Get the most recent entry from the health store.
healthStore.mostRecentQauntitySampleOfType(quantityType) { quantity, _ in
guard let quantity = quantity else { return }
// Update the cell on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock() {
guard let indexPath = self.indexPathForObjectTypeIdentifier(identifier) else { return }
guard let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? ProfileStaticTableViewCell else { return }
cell.valueLabel.text = "\(quantity)"
}
}
}
// MARK: Convenience
func indexPathForObjectTypeIdentifier(identifier: String) -> NSIndexPath? {
for (index, objectType) in healthObjectTypes.enumerate() where objectType.identifier == identifier {
return NSIndexPath(forRow: index, inSection: 0)
}
return nil
}
}
| bsd-3-clause | 93214466241b43cb9de197f1d68e48f4 | 43.777778 | 238 | 0.697408 | 5.883212 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.