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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
codepgq/AnimateDemo
|
Animate/Animate/controller/BaseAnimation/Rotation/RotationController.swift
|
1
|
2071
|
//
// RotationController.swift
// Animate
//
// Created by Mac on 17/2/6.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class RotationController: BaseViewController {
@IBOutlet weak var rotationImg: UIImageView!
@IBOutlet weak var textY: UITextField!
@IBOutlet weak var textX: UITextField!
// 自定义XY
@IBAction func rotationXY(_ sender: Any) {
let x : Double = (textX.text! as NSString).doubleValue
let y : Double = (textY.text! as NSString).doubleValue
rotationImg.layer.anchorPoint = CGPoint(x: x, y: y)
rotationImg.layer.removeAllAnimations()
let animate = Animate.baseAnimationWithKeyPath("transform.rotation.z", fromValue: nil , toValue: 2 * M_PI, duration: 1.0, repeatCount: Float.infinity, timingFunction: kCAMediaTimingFunctionLinear)
rotationImg.layer.add(animate, forKey: "transform.rotation.z")
}
@IBAction func rotationX(_ sender: Any) {
rotationImg.layer.removeAllAnimations()
let animate = Animate.baseAnimationWithKeyPath("transform.rotation.x", fromValue: nil , toValue: 2 * M_PI, duration: 1.0, repeatCount: Float.infinity, timingFunction: kCAMediaTimingFunctionLinear)
rotationImg.layer.add(animate, forKey: "transform.rotation.x")
}
@IBAction func rotationY(_ sender: Any) {
rotationImg.layer.removeAllAnimations()
let animate = Animate.baseAnimationWithKeyPath("transform.rotation.y", fromValue: nil , toValue: 2 * M_PI, duration: 1.0, repeatCount: Float.infinity, timingFunction: kCAMediaTimingFunctionEaseIn)
rotationImg.layer.add(animate, forKey: "transform.rotation.y")
}
@IBAction func rotationZ(_ sender: Any) {
rotationImg.layer.removeAllAnimations()
let animate = Animate.baseAnimationWithKeyPath("transform.rotation.z", fromValue: nil , toValue: 2 * M_PI, duration: 1.0, repeatCount: Float.infinity, timingFunction: kCAMediaTimingFunctionEaseOut)
rotationImg.layer.add(animate, forKey: "transform.rotation.z")
}
}
|
apache-2.0
|
3f4c46b7a92288cb67c740540fd68a5d
| 43.826087 | 205 | 0.703201 | 4.286902 | false | false | false | false |
huangboju/Moots
|
Examples/SwiftUI/PokeMaster/PokeMaster/View/List/PokemonList.swift
|
1
|
1630
|
//
// PokemonList.swift
// PokeMaster
//
// Created by 黄伯驹 on 2021/11/14.
//
import SwiftUI
struct PokemonList: View {
@State private var expandingIndex: Int?
var body: some View {
// List(PokemonViewModel.all) {
// PokemonInfoRow(model: $0, expanded: false)
// .listRowSeparator(.hidden)
// }
ScrollView {
LazyVStack {
ForEach(PokemonViewModel.all) { pokemon in
PokemonInfoRow(model: pokemon, expanded: expandingIndex == pokemon.id)
.listRowSeparator(.hidden)
.onTapGesture {
withAnimation(
.spring(response: 0.55,
dampingFraction: 0.425,
blendDuration: 0)
) {
if self.expandingIndex == pokemon.id {
self.expandingIndex = nil
} else {
self.expandingIndex = pokemon.id
}
}
}
}
}
}
// .overlay(
// VStack {
// Spacer()
// PokemonInfoPanel(model: .sample(id: 1))
// }
// .edgesIgnoringSafeArea(.bottom)
// )
}
}
struct PokemonList_Previews: PreviewProvider {
static var previews: some View {
PokemonList()
}
}
|
mit
|
1414810e7f888cff9eea48353ae18d44
| 29.641509 | 90 | 0.399631 | 5.431438 | false | false | false | false |
toco/IPDC-14
|
IPDC/PopoverControllerDelegate.swift
|
1
|
1250
|
//
// PopoverControllerDelegate.swift
// IPDC
//
// Created by Tobias Conradi on 14.11.14.
// Copyright (c) 2014 Tobias Conradi. All rights reserved.
//
import UIKit
class PopoverControllerDelegate: NSObject, UIPopoverPresentationControllerDelegate {
let sourceTextView: UITextView
let sourceTextRange: NSRange
init(textView:UITextView, textRange:NSRange) {
sourceTextView = textView
sourceTextRange = textRange
}
func popoverPresentationController(popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer<CGRect>, inView view: AutoreleasingUnsafeMutablePointer<UIView?>) {
let textRange = sourceTextRange
let sourceView = sourceTextView
let textRect = sourceView.frameOfTextRange(textRange)
rect.memory = textRect
view.memory = sourceView
}
func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
return UINavigationController(rootViewController:controller.presentedViewController)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .FullScreen
}
}
|
mit
|
60889668444d8037e0789b531fb38a63
| 31.894737 | 222 | 0.8184 | 5.364807 | false | false | false | false |
yanif/circator
|
MetabolicCompassWatchExtension/GlanceController.swift
|
1
|
4297
|
//
// GlanceController.swift
// CircatorWatch Extension
//
// Created by Mariano on 3/2/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class GlanceController: WKInterfaceController {
@IBOutlet var firstRow: WKInterfaceLabel!
@IBOutlet var secondRow: WKInterfaceLabel!
@IBOutlet var thirdRow: WKInterfaceLabel!
@IBOutlet var fourthRow: WKInterfaceLabel!
var weightString:String = "150"
var BMIString:String = "23.4"
var maxDailyFastingString:String = "need data"
var currentFastingTimeString:String = "need data"
var lastAteAsString:String = "no data"
var proteinString:String = "ProteinAsString"
var carbohydrateString:String = "carbs"
var fatString:String = "fat"
var stepsString:String = "stepsAsString"
var heartRateString:String = "heartRateAsString"
var firstRowString:String = "entry"
var secondRowString:String = "2nd row"
var thirdRowString:String = "3rd row long"
var wokeFromSleep:String = "data needed"
var finishedExerciseLast:String = "no data"
var cumulativeWeeklyFastingString:String = "CWF"
var cumulativeWeeklyNonFastString:String = "CWNF"
var weeklyFastingVariabilityString:String = "wFV"
var samplesCollectedString:String = "sampled"
var fastSleepString:String = "fastSleep"
var fastAwakeString:String = "fastAwake"
var fastEatString:String = "fastEat"
var fastExerciseString:String = "fastExercise"
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
override func willActivate() {
super.willActivate()
print("glance updated")
firstRow.setText("M-Compass Stats:")
firstRow.setTextColor(UIColor.greenColor())
maxDailyFastingString = "Fast: \(MetricsStore.sharedInstance.fastingTime)"
secondRow.setText(maxDailyFastingString)
currentFastingTimeString = "Current Fast: \(MetricsStore.sharedInstance.currentFastingTime)"
lastAteAsString = "Last Ate: \(MetricsStore.sharedInstance.lastAte)"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
wokeFromSleep = "sleep: " + dateFormatter.stringFromDate(MetricsStore.sharedInstance.Sleep)
finishedExerciseLast = "exercise: " + dateFormatter.stringFromDate(MetricsStore.sharedInstance.Exercise)
weightString = " Lbs: " + MetricsStore.sharedInstance.weight
BMIString = " BMI: " + MetricsStore.sharedInstance.BMI
proteinString = " Prot: " + MetricsStore.sharedInstance.Protein
carbohydrateString = " Carb: " + MetricsStore.sharedInstance.Carbohydrate
fatString = " Fat: " + MetricsStore.sharedInstance.Fat
stepsString = " Steps: " + MetricsStore.sharedInstance.StepCount
cumulativeWeeklyFastingString = "WkF:" + MetricsStore.sharedInstance.cumulativeWeeklyFasting
cumulativeWeeklyNonFastString = "WklyNFst: " + MetricsStore.sharedInstance.cumulativeWeeklyNonFast
weeklyFastingVariabilityString = "Fst Var: " + MetricsStore.sharedInstance.weeklyFastingVariability
samplesCollectedString = "# Samples Collected: " + MetricsStore.sharedInstance.samplesCollected
fastSleepString = "fast to Sleep: " + MetricsStore.sharedInstance.fastSleep
fastAwakeString = "fast to Awake: " + MetricsStore.sharedInstance.fastAwake
fastEatString = "fast to Eat: " + MetricsStore.sharedInstance.fastEat
fastExerciseString = "fast to Exer: " + MetricsStore.sharedInstance.fastExercise
secondRow.setText(cumulativeWeeklyFastingString)
thirdRowString =
cumulativeWeeklyNonFastString + "\n" +
weeklyFastingVariabilityString + "\n" +
fastAwakeString + "\n" +
fastSleepString + "\n" +
fastEatString + "\n" +
fastExerciseString
thirdRow.setText(thirdRowString)
thirdRow.setTextColor(UIColor.blueColor())
// fourthRow.setText(samplesCollectedString)
fourthRow.setText("")
fourthRow.setTextColor(UIColor.yellowColor())
}
}
|
apache-2.0
|
061853890004de7969ccae34a2d0694c
| 45.695652 | 114 | 0.694367 | 4.570213 | false | false | false | false |
cinnamon/MPFramework
|
MPFramework/Extensions/NSDate+extension.swift
|
1
|
1086
|
//
// NSDate+extension.swift
// MPFramework
//
// Created by 이인재 on 2015.12.16.
// Copyright © 2015년 magentapink. All rights reserved.
//
import Foundation
extension Date {
public var closedWeekdays: [Date] {
var days = [Date](repeating: Date(), count: 7)
let daysInWeek = 7
let oneDayTimeInterval: TimeInterval = 60 * 60 * 24
let baseDate = self.addingTimeInterval((-self.timeIntervalSince1970).truncatingRemainder(dividingBy: 60))
let calendar = Calendar.current
let weekdayValue = (calendar as NSCalendar).component(NSCalendar.Unit.weekday, from: baseDate) - 1
for i in 0..<daysInWeek {
let internalIndex = (baseDate.timeIntervalSince1970 > Date().timeIntervalSince1970 ? 0 : 1) + i
let date = baseDate.addingTimeInterval(oneDayTimeInterval * TimeInterval(internalIndex))
var index = weekdayValue + internalIndex
if index >= daysInWeek {
index -= daysInWeek
}
days[index] = date
}
// for i in 0..<daysInWeek {
// print("### day[\(Weekday(rawValue: i)?.description)]:\(days[i])")
// }
return days
}
}
|
apache-2.0
|
a487d2b038f939e945e363fd3ccf3591
| 25.925 | 107 | 0.685237 | 3.626263 | false | false | false | false |
RLovelett/langserver-swift
|
Sources/LanguageServerProtocol/Types/ServerCapabilities.swift
|
1
|
2213
|
//
// ServerCapabilities.swift
// langserver-swift
//
// Created by Ryan Lovelett on 11/21/16.
//
//
import Argo
import Foundation
import Ogra
/// The capabilities the language server provides.
public struct ServerCapabilities {
/// Defines how text documents are synced.
let textDocumentSync: TextDocumentSyncKind?
/// The server provides hover support.
let hoverProvider: Bool?
/// The server provides completion support.
let completionProvider: CompletionOptions?
/// The server provides goto definition support.
let definitiionProvider: Bool?
/// The server provides find references support.
let referencesProvider: Bool?
/// The server provides document highlight support.
let documentHighlighProvider: Bool?
/// The server provides document symbol support.
let documentSymbolProvider: Bool?
/// The server provides workspace symbol support.
let workspaceSymbolProvider: Bool?
/// The server provides code actions.
let codeActionProvider: Bool?
/// The server provides document formatting.
let documentFormattingProvider: Bool?
/// The server provides document range formatting.
let documentRangeFormattingProvider: Bool?
/// The server provides rename support.
let renameProvider: Bool?
}
extension ServerCapabilities : Ogra.Encodable {
public func encode() -> JSON {
var obj: [String : JSON] = [ : ]
if let textDocumentSync = self.textDocumentSync {
obj["textDocumentSync"] = JSON.number(NSNumber(value: textDocumentSync.rawValue))
}
if let hoverProvider = self.hoverProvider {
obj["hoverProvider"] = JSON.bool(hoverProvider)
}
if let completionProvider = self.completionProvider {
obj["completionProvider"] = completionProvider.encode()
}
if let definitiionProvider = self.definitiionProvider {
obj["definitionProvider"] = JSON.bool(definitiionProvider)
}
if let workspaceSymbolProvider = self.workspaceSymbolProvider {
obj["workspaceSymbolProvider"] = JSON.bool(workspaceSymbolProvider)
}
return JSON.object(obj)
}
}
|
apache-2.0
|
e659bd218272377ac4d0e3bb8ae43325
| 25.987805 | 93 | 0.687302 | 4.71855 | false | false | false | false |
PJayRushton/StarvingStudentGuide
|
StarvingStudentGuide/HomeViewController.swift
|
1
|
8728
|
//
// HomeViewController.swift
// StarvingStudentGuide
//
// Created by Parker Rushton on 3/7/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
// MARK: - Types
enum Tab: Int {
case category
case az
var dataObject: TabDataObject {
switch self {
case .category:
return TabDataObject(title: "Category", imageName: nil)
case .az:
return TabDataObject(title: "Store", imageName: nil)
}
}
}
// MARK: - Interface references
@IBOutlet weak var settingsBarButtonItem: UIBarButtonItem!
@IBOutlet weak var customTabBar: CustomTabBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tabBarHeightConstraint: NSLayoutConstraint!
// MARK: - Properties
let service = DealService()
var deals: [Deal]?
private var filteredDeals = [Deal]()
private var currentDeals = [Deal]() {
didSet {
tableView.reloadData()
}
}
private var quantityViewController: QuantityViewController?
private var availableCategories: Set<CouponCategory> {
let categories = currentDeals.map { return $0.couponCategory }
return Set(categories)
}
private var shouldShowCategoryHeaders: Bool {
return Tab(rawValue: selectedTab)! == .category && !shouldShowSearchResults
}
private var shouldShowSearchResults: Bool {
return searchController.active
}
private var searchController = UISearchController()
private var selectedTab = 0 {
didSet {
loadDeals()
}
}
private var selectedTabObject: Tab {
return Tab(rawValue: selectedTab)!
}
private var ascending = true {
didSet {
loadDeals()
}
}
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
settingsBarButtonItem.tintColor = .mainColor()
setupSearchBar()
setupTabBar()
loadDeals()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadDeals()
}
func loadDeals() {
service.retrieveDeals(ascending) { deals in
if let deals = deals {
self.deals = deals
self.currentDeals = deals
self.tableView.reloadData()
}
}
}
}
// MARK: - Searching
extension HomeViewController: UISearchResultsUpdating, UISearchBarDelegate {
func setupSearchBar() {
searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.searchBar.delegate = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
tableView.tableHeaderView = controller.searchBar
return controller
})()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
guard let deals = deals, searchString = searchController.searchBar.text else { fatalError("deals are nil") }
filteredDeals = deals.filter() {
let storeTitle = $0.store.title as NSString
let dealName = $0.info as NSString
let categoryName = $0.couponCategory.title as NSString
return storeTitle.rangeOfString(searchString, options: .CaseInsensitiveSearch).location != NSNotFound || dealName.rangeOfString(searchString, options: .CaseInsensitiveSearch).location != NSNotFound || categoryName.rangeOfString(searchString, options: .CaseInsensitiveSearch).location != NSNotFound
}
currentDeals = filteredDeals
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
guard let deals = deals else { print("Unable to get deals after search ended"); return }
searchController.active = false
currentDeals = deals
}
}
// MARK: - Navigation
extension HomeViewController: SegueHandlerType {
enum SegueIdentifier: String {
case dealDetail
case settings
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segueIdentifierForSegue(segue) {
case .dealDetail:
guard let selectedIndexPath = tableView.indexPathForSelectedRow else { fatalError() }
guard let dealDetailViewController = segue.destinationViewController as? DealDetailViewController else { fatalError() }
let selectedDeal = dealAtIndexPath(selectedIndexPath)
dealDetailViewController.deal = selectedDeal
searchController.active = false
case .settings:
break
}
}
}
// MARK: - TableView DataSource + Delegate
extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
func dealsForCategorySection(section: Int) -> [Deal] {
let categoryForSection = CouponCategory(rawValue: section)!
var tempDeals = [Deal]()
for deal in currentDeals {
if deal.category == categoryForSection.title {
tempDeals.append(deal)
}
}
return tempDeals
}
func dealAtIndexPath(indexPath: NSIndexPath) -> Deal {
if shouldShowCategoryHeaders {
let dealsInSection = dealsForCategorySection(indexPath.section)
return dealsInSection[indexPath.row]
} else {
return currentDeals[indexPath.row]
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return shouldShowCategoryHeaders ? availableCategories.count : 1
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
let categoriesArray = availableCategories.sort { return $0.rawValue < $1.rawValue }
return shouldShowCategoryHeaders ? categoriesArray.map { return $0.indexTitle } : nil
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shouldShowCategoryHeaders ? dealsForCategorySection(section).count : currentDeals.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier(HeaderTableViewCell.reuseIdentifier) as! HeaderTableViewCell
headerCell.update(CouponCategory(rawValue: section)!)
return shouldShowCategoryHeaders ? headerCell : nil
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return shouldShowCategoryHeaders ? 50 : 0
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier(DealTableViewCell.reuseIdentifier) as? DealTableViewCell else { return UITableViewCell() }
cell.update(deal: dealAtIndexPath(indexPath), category: shouldShowCategoryHeaders)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier(.dealDetail, sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
extension HomeViewController: CustomTabBarDelegate {
func setupTabBar() {
var count = 0
var customTabDataObjects = [TabDataObject]()
while let tab = Tab(rawValue: count) {
customTabDataObjects.append(tab.dataObject)
count += 1
}
customTabBar.dataObjects = customTabDataObjects
customTabBar.delegate = self
}
func tabBar(tabBar: CustomTabBar, didSelectTab tab: Int) {
if tab == selectedTab {
tabBar.underlineTop = !tabBar.underlineTop
ascending = !ascending
} else {
guard let theTab = Tab(rawValue: tab) else { fatalError("No tab") }
switch theTab {
case .category:
selectedTab = 0
case .az:
selectedTab = 1
}
}
}
}
|
mit
|
b9e8ec10f128aa866ebb965607c165e3
| 31.442379 | 309 | 0.64226 | 5.608612 | false | false | false | false |
willlarche/material-components-ios
|
components/TextFields/examples/TextFieldFilledExample.swift
|
2
|
16523
|
/*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// swiftlint:disable function_body_length
import MaterialComponents.MaterialTextFields
final class TextFieldFilledSwiftExample: UIViewController {
let scrollView = UIScrollView()
let name: MDCTextField = {
let name = MDCTextField()
name.translatesAutoresizingMaskIntoConstraints = false
name.autocapitalizationType = .words
return name
}()
let address: MDCTextField = {
let address = MDCTextField()
address.translatesAutoresizingMaskIntoConstraints = false
address.autocapitalizationType = .words
return address
}()
let city: MDCTextField = {
let city = MDCTextField()
city.translatesAutoresizingMaskIntoConstraints = false
city.autocapitalizationType = .words
return city
}()
let cityController: MDCTextInputControllerFilled
let state: MDCTextField = {
let state = MDCTextField()
state.translatesAutoresizingMaskIntoConstraints = false
state.autocapitalizationType = .allCharacters
return state
}()
let stateController: MDCTextInputControllerFilled
let zip: MDCTextField = {
let zip = MDCTextField()
zip.translatesAutoresizingMaskIntoConstraints = false
return zip
}()
let zipController: MDCTextInputControllerFilled
let phone: MDCTextField = {
let phone = MDCTextField()
phone.translatesAutoresizingMaskIntoConstraints = false
return phone
}()
let message: MDCMultilineTextField = {
let message = MDCMultilineTextField()
message.translatesAutoresizingMaskIntoConstraints = false
return message
}()
var allTextFieldControllers = [MDCTextInputControllerFilled]()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
cityController = MDCTextInputControllerFilled(textInput: city)
stateController = MDCTextInputControllerFilled(textInput: state)
zipController = MDCTextInputControllerFilled(textInput: zip)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white:0.97, alpha: 1.0)
title = "Material Filled Text Field"
setupScrollView()
setupTextFields()
registerKeyboardNotifications()
addGestureRecognizer()
let styleButton = UIBarButtonItem(title: "Style",
style: .plain,
target: self,
action: #selector(buttonDidTouch(sender: )))
self.navigationItem.rightBarButtonItem = styleButton
}
func setupTextFields() {
scrollView.addSubview(name)
let nameController = MDCTextInputControllerFilled(textInput: name)
name.delegate = self
name.text = "Grace Hopper"
nameController.placeholderText = "Name"
nameController.helperText = "First and Last"
allTextFieldControllers.append(nameController)
scrollView.addSubview(address)
let addressController = MDCTextInputControllerFilled(textInput: address)
address.delegate = self
addressController.placeholderText = "Address"
allTextFieldControllers.append(addressController)
scrollView.addSubview(city)
city.delegate = self
cityController.placeholderText = "City"
allTextFieldControllers.append(cityController)
// In iOS 9+, you could accomplish this with a UILayoutGuide.
// TODO: (larche) add iOS version specific implementations
let stateZip = UIView()
stateZip.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stateZip)
stateZip.addSubview(state)
state.delegate = self
stateController.placeholderText = "State"
allTextFieldControllers.append(stateController)
stateZip.addSubview(zip)
zip.delegate = self
zipController.placeholderText = "Zip Code"
zipController.helperText = "XXXXX"
allTextFieldControllers.append(zipController)
scrollView.addSubview(phone)
let phoneController = MDCTextInputControllerFilled(textInput: phone)
phone.delegate = self
phoneController.placeholderText = "Phone Number"
allTextFieldControllers.append(phoneController)
scrollView.addSubview(message)
let messageController = MDCTextInputControllerFilled(textInput: message)
message.textView?.delegate = self
messageController.placeholderText = "Message"
allTextFieldControllers.append(messageController)
var tag = 0
for controller in allTextFieldControllers {
guard let textField = controller.textInput as? MDCTextField else { continue }
textField.tag = tag
tag += 1
}
let views = [ "name": name,
"address": address,
"city": city,
"stateZip": stateZip,
"phone": phone,
"message": message ]
var constraints = NSLayoutConstraint.constraints(withVisualFormat:
"V:[name]-[address]-[city]-[stateZip]-[phone]-[message]",
options: [.alignAllLeading, .alignAllTrailing],
metrics: nil,
views: views)
constraints += [NSLayoutConstraint(item: name,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leadingMargin,
multiplier: 1,
constant: 0)]
constraints += [NSLayoutConstraint(item: name,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailingMargin,
multiplier: 1,
constant: 0)]
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[name]|",
options: [],
metrics: nil,
views: views)
#if swift(>=3.2)
if #available(iOS 11.0, *) {
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
} else {
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
}
#else
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
#endif
let stateZipViews = [ "state": state, "zip": zip ]
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[state(80)]-[zip]|",
options: [.alignAllTop],
metrics: nil,
views: stateZipViews)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[state]|",
options: [],
metrics: nil,
views: stateZipViews)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[zip]|",
options: [],
metrics: nil,
views: stateZipViews)
NSLayoutConstraint.activate(constraints)
}
func setupScrollView() {
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(
withVisualFormat: "V:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
let marginOffset: CGFloat = 16
let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset)
scrollView.layoutMargins = margins
}
func addGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapDidTouch(sender: )))
self.scrollView.addGestureRecognizer(tapRecognizer)
}
// MARK: - Actions
@objc func tapDidTouch(sender: Any) {
self.view.endEditing(true)
}
@objc func buttonDidTouch(sender: Any) {
let isFloatingEnabled = allTextFieldControllers.first?.isFloatingEnabled ?? false
let alert = UIAlertController(title: "Floating Labels",
message: nil,
preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default (Yes)" + (isFloatingEnabled ? " ✓" : ""),
style: .default) { _ in
self.allTextFieldControllers.forEach({ (controller) in
controller.isFloatingEnabled = true
})
}
alert.addAction(defaultAction)
let floatingAction = UIAlertAction(title: "No" + (isFloatingEnabled ? "" : " ✓"),
style: .default) { _ in
self.allTextFieldControllers.forEach({ (controller) in
controller.isFloatingEnabled = false
})
}
alert.addAction(floatingAction)
present(alert, animated: true, completion: nil)
}
}
extension TextFieldFilledSwiftExample: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let rawText = textField.text else {
return true
}
let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string)
if textField == state {
if let range = fullString.rangeOfCharacter(from: CharacterSet.letters.inverted),
fullString[range].characters.count > 0 {
stateController.setErrorText("Error: State can only contain letters",
errorAccessibilityValue: nil)
} else {
stateController.setErrorText(nil, errorAccessibilityValue: nil)
}
} else if textField == zip { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters),
fullString[range].characters.count > 0 {
zipController.setErrorText("Error: Zip can only contain numbers",
errorAccessibilityValue: nil)
} else if fullString.characters.count > 5 {
zipController.setErrorText("Error: Zip can only contain five digits",
errorAccessibilityValue: nil)
} else {
zipController.setErrorText(nil, errorAccessibilityValue: nil)
}
} else if textField == city {
if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits),
fullString[range].characters.count > 0 {
cityController.setErrorText("Error: City can only contain letters",
errorAccessibilityValue: nil)
} else {
cityController.setErrorText(nil, errorAccessibilityValue: nil)
}
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let index = textField.tag
if index + 1 < allTextFieldControllers.count,
let nextField = allTextFieldControllers[index + 1].textInput {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
}
extension TextFieldFilledSwiftExample: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
print(textView.text)
}
}
// MARK: - Keyboard Handling
extension TextFieldFilledSwiftExample {
func registerKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillShow,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillChangeFrame,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillHide(notif:)),
name: .UIKeyboardWillHide,
object: nil)
}
@objc func keyboardWillShow(notif: Notification) {
guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
scrollView.contentInset = UIEdgeInsets(top: 0.0,
left: 0.0,
bottom: frame.height,
right: 0.0)
}
@objc func keyboardWillHide(notif: Notification) {
scrollView.contentInset = UIEdgeInsets()
}
}
// MARK: - Status Bar Style
extension TextFieldFilledSwiftExample {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension TextFieldFilledSwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Text Field", "Filled Text Fields"]
}
}
|
apache-2.0
|
2d580ccf7982eea4fc5cce5f802da9a5
| 37.868235 | 109 | 0.563775 | 6.27145 | false | false | false | false |
melling/ios_topics
|
CustomUIView/CustomUIView/CustomView.swift
|
1
|
3227
|
//
// CustomView.swift
// CustomUIView
//
// Created by Michael Mellinger on 6/2/16.
//
import UIKit
class CustomView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.orange
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addTriangle(_ x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat){
let center = CGPoint(x: width/2 + x, y: y)
let bottomLeft = CGPoint(x: x, y: height + y)
let bottomRight = CGPoint(x: width + x, y: height + y)
let layer = CAShapeLayer()
let path = UIBezierPath()
path.move(to: center)
path.addLine(to: bottomLeft)
path.addLine(to: bottomRight)
path.close()
layer.path = path.cgPath
self.layer.addSublayer(layer)
}
func addCircle(_ x: CGFloat, y: CGFloat, radius: CGFloat, color:UIColor){
let layer = CAShapeLayer()
let path = UIBezierPath(ovalIn: CGRect(x: x, y: y, width: radius, height: radius))
layer.fillColor = color.cgColor
layer.path = path.cgPath
self.layer.addSublayer(layer)
}
// Set cornerRadius=1 to make normal rectangle
func addRect(_ x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
let layer = CAShapeLayer()
layer.path = UIBezierPath(roundedRect: CGRect(x: 10, y: 10, width: 160, height: 160), cornerRadius: 1).cgPath
layer.fillColor = UIColor.blue.cgColor
layer.strokeColor = UIColor.black.cgColor
layer.lineWidth = 2
self.layer.addSublayer(layer)
}
func toRadians(_ degrees:CGFloat) -> CGFloat {
return degrees * CGFloat(Double.pi)/180
}
func addArc(_ radius:CGFloat, center:CGPoint){
let layer = CAShapeLayer()
let startAngle:CGFloat = 0
let endAngle:CGFloat = 180
let clockwise = true
layer.path = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: toRadians(startAngle),
endAngle:toRadians(endAngle),
clockwise: clockwise).cgPath
layer.fillColor = UIColor.white.cgColor
layer.strokeColor = UIColor.gray.cgColor
layer.lineWidth = 2
self.layer.addSublayer(layer)
}
override func draw(_ rect: CGRect) {
let width = self.frame.width
let eyeRadius = width * 40/200
// Drawing code
addCircle(0, y:0, radius:width, color: UIColor.gray)
addCircle(width*0.25, y:width*0.15, radius:eyeRadius, color: UIColor.black)
addCircle(width*0.6, y:width*0.15, radius:eyeRadius, color: UIColor.black)
addTriangle(width/2 - eyeRadius/2, y: width/2 - eyeRadius/2, width: eyeRadius, height: eyeRadius)
let mouthRadius:CGFloat = width/4
let mounthCenter = CGPoint(x: width/2, y: width*0.65)
addArc(mouthRadius, center: mounthCenter)
}
}
|
cc0-1.0
|
13bcf44538caa34fd421d725145c89ef
| 30.330097 | 117 | 0.575457 | 4.308411 | false | false | false | false |
milseman/swift
|
stdlib/public/core/BidirectionalCollection.swift
|
8
|
12284
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with bidirectional
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the
/// `BidirectionalCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead")
public typealias BidirectionalIndexable = _BidirectionalIndexable
public protocol _BidirectionalIndexable : _Indexable {
// FIXME(ABI)#22 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library.
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
func index(before i: Index) -> Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
func formIndex(before i: inout Index)
}
/// A collection that supports backward as well as forward traversal.
///
/// Bidirectional collections offer traversal backward from any valid index,
/// not including a collection's `startIndex`. Bidirectional collections can
/// therefore offer additional operations, such as a `last` property that
/// provides efficient access to the last element and a `reversed()` method
/// that presents the elements in reverse order. In addition, bidirectional
/// collections have more efficient implementations of some sequence and
/// collection methods, such as `suffix(_:)`.
///
/// Conforming to the BidirectionalCollection Protocol
/// ==================================================
///
/// To add `BidirectionalProtocol` conformance to your custom types, implement
/// the `index(before:)` method in addition to the requirements of the
/// `Collection` protocol.
///
/// Indices that are moved forward and backward in a bidirectional collection
/// move by the same amount in each direction. That is, for any index `i` into
/// a bidirectional collection `c`:
///
/// - If `i >= c.startIndex && i < c.endIndex`,
/// `c.index(before: c.index(after: i)) == i`.
/// - If `i > c.startIndex && i <= c.endIndex`
/// `c.index(after: c.index(before: i)) == i`.
public protocol BidirectionalCollection : _BidirectionalIndexable, Collection
// FIXME(ABI) (Revert Where Clauses): Restore these
// where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection
{
// TODO: swift-3-indexing-model - replaces functionality in BidirectionalIndex
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
func index(before i: Index) -> Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
func formIndex(before i: inout Index)
/// A sequence that can represent a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
// FIXME(ABI) (Revert Where Clauses): Remove these conformances
: _BidirectionalIndexable, Collection
= BidirectionalSlice<Self>
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices
// FIXME(ABI) (Revert Where Clauses): Remove these conformances
: _BidirectionalIndexable, Collection
= DefaultBidirectionalIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
// TODO: swift-3-indexing-model: tests.
/// The last element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let lastNumber = numbers.last {
/// print(lastNumber)
/// }
/// // Prints "50"
///
/// - Complexity: O(1)
var last: Element? { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
}
/// Default implementation for bidirectional collections.
extension _BidirectionalIndexable {
@inline(__always)
public func formIndex(before i: inout Index) {
i = index(before: i)
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
if n >= 0 {
return _advanceForward(i, by: n)
}
var i = i
for _ in stride(from: 0, to: n, by: -1) {
formIndex(before: &i)
}
return i
}
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
if n >= 0 {
return _advanceForward(i, by: n, limitedBy: limit)
}
var i = i
for _ in stride(from: 0, to: n, by: -1) {
if i == limit {
return nil
}
formIndex(before: &i)
}
return i
}
public func distance(from start: Index, to end: Index) -> IndexDistance {
var start = start
var count: IndexDistance = 0
if start < end {
while start != end {
count += 1 as IndexDistance
formIndex(after: &start)
}
}
else if start > end {
while start != end {
count -= 1 as IndexDistance
formIndex(before: &start)
}
}
return count
}
}
/// Supply the default "slicing" `subscript` for `BidirectionalCollection`
/// models that accept the default associated `SubSequence`,
/// `BidirectionalSlice<Self>`.
extension BidirectionalCollection where SubSequence == BidirectionalSlice<Self> {
public subscript(bounds: Range<Index>) -> BidirectionalSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return BidirectionalSlice(base: self, bounds: bounds)
}
}
extension BidirectionalCollection where SubSequence == Self {
/// Removes and returns the last element of the collection.
///
/// You can use `popLast()` to remove the last element of a collection that
/// might be empty. The `removeLast()` method must be used only on a
/// nonempty collection.
///
/// - Returns: The last element of the collection if the collection has one
/// or more elements; otherwise, `nil`.
///
/// - Complexity: O(1).
public mutating func popLast() -> Element? {
guard !isEmpty else { return nil }
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty. To remove the last element of a
/// collection that might be empty, use the `popLast()` method instead.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@discardableResult
public mutating func removeLast() -> Element {
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
/// Removes the given number of elements from the end of the collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater
/// than or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))]
}
}
extension BidirectionalCollection {
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off `n` elements from the end.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop.
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let end = index(
endIndex,
offsetBy: numericCast(-n),
limitedBy: startIndex) ?? startIndex
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains the entire collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is equal to `maxLength`.
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let start = index(
endIndex,
offsetBy: numericCast(-maxLength),
limitedBy: startIndex) ?? startIndex
return self[start..<endIndex]
}
}
|
apache-2.0
|
1adb3e89f8fd248c7ab8121058753530
| 36 | 116 | 0.648567 | 4.322308 | false | false | false | false |
tristanchu/FlavorFinder
|
FlavorFinder/FlavorFinder/AddMatchViewController.swift
|
1
|
3373
|
//
// AddMatchViewController.swift
// FlavorFinder
//
// Created by Jaki Kimball on 2/27/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
class AddMatchViewController : AddMatchPrototypeViewController {
// MARK: Properties:
let pageTitle = "Add New Match"
let ALREADY_EXISTS_SUFFIX = " is already a match!"
let DEFAULT_PROMPT = "Which ingredient are you creating a new match for?"
let FEEDBACK_PREFIX = "New match created for "
// MARK: connections:
@IBOutlet weak var chooseIngredientSearchBar: UISearchBar!
@IBOutlet weak var searchTableView: UITableView!
@IBOutlet weak var promptLabel: UILabel!
// MARK: Override methods: ----------------------------------------------
/* viewDidLoad:
*/
override func viewDidLoad() {
if !isUserLoggedIn() {
self.navigationController?.popToRootViewControllerAnimated(true)
return
}
// Assign values to parent class variables
ingredientSearchBar = chooseIngredientSearchBar
searchTable = searchTableView
navTitle = pageTitle
// Call super
super.viewDidLoad()
// make search bar border round:
chooseIngredientSearchBar.layer.cornerRadius = ROUNDED_SIZE
chooseIngredientSearchBar.clipsToBounds = true
// grey background:
view.backgroundColor = BACKGROUND_COLOR
}
/* viewDidAppear:
*/
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
reset()
}
// MARK: Overriding parent class functions ------------------------------
/* gotSelectedIngredient
- handle selection of ingredient w.r.t. creating a new match
*/
override func gotSelectedIngredient(selected: PFIngredient) {
if !isUserLoggedIn() {
errorLoggedOut()
return
}
if let _ = firstIngredient { // try to create a match
secondIngredient = selected
if let _ = getMatchForTwoIngredients(firstIngredient!, secondIngredient: secondIngredient!) {
let alreadyExistsText = "\(firstIngredient!.name) + \(secondIngredient!.name)\(ALREADY_EXISTS_SUFFIX)"
showFeedback(alreadyExistsText, vc: self)
} else {
let matchMadeText = "\(FEEDBACK_PREFIX)\(firstIngredient!.name) + \(secondIngredient!.name)"
addMatch(currentUser!, firstIngredient: firstIngredient!, secondIngredient: secondIngredient!)
showFeedback(matchMadeText, vc: self)
}
reset()
} else { // first ingredient of the match was selected
firstIngredient = selected
promptLabel.text = "\(PROMPT_PREFIX)\(firstIngredient!.name)\(PROMPT_SUFFIX)"
ingredientSearchBar?.text = ""
searchTable?.hidden = true
}
}
// MARK: Other functions ---------------------------------------------------
/* reset
- resets the view after a match has been added
*/
func reset() {
promptLabel.text = DEFAULT_PROMPT
firstIngredient = nil
secondIngredient = nil
ingredientSearchBar?.text = ""
searchTable?.hidden = true
}
}
|
mit
|
246189963f4c5bff906ef15b9e69c7a7
| 31.747573 | 118 | 0.59223 | 5.26875 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin
|
Pod/Classes/Sources.Api/NetworkStatusBridge.swift
|
1
|
7801
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli-
-cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for Managing the Network status
Auto-generated implementation of INetworkStatus specification.
*/
public class NetworkStatusBridge : BaseCommunicationBridge, INetworkStatus, APIBridge {
/**
API Delegate.
*/
private var delegate : INetworkStatus? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : INetworkStatus?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return INetworkStatus delegate that manages platform specific functions..
*/
public final func getDelegate() -> INetworkStatus? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : INetworkStatus) {
self.delegate = delegate;
}
/**
Add the listener for network status changes of the app
@param listener Listener with the result
@since v2.0
*/
public func addNetworkStatusListener(listener : INetworkStatusListener ) {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executing addNetworkStatusListener...")
}
if (self.delegate != nil) {
self.delegate!.addNetworkStatusListener(listener)
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executed 'addNetworkStatusListener' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge no delegate for 'addNetworkStatusListener'.")
}
}
}
/**
Un-registers an existing listener from receiving network status events.
@param listener Listener with the result
@since v2.0
*/
public func removeNetworkStatusListener(listener : INetworkStatusListener ) {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executing removeNetworkStatusListener...")
}
if (self.delegate != nil) {
self.delegate!.removeNetworkStatusListener(listener)
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executed 'removeNetworkStatusListener' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge no delegate for 'removeNetworkStatusListener'.")
}
}
}
/**
Removes all existing listeners from receiving network status events.
@since v2.0
*/
public func removeNetworkStatusListeners() {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executing removeNetworkStatusListeners...")
}
if (self.delegate != nil) {
self.delegate!.removeNetworkStatusListeners()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge executed 'removeNetworkStatusListeners' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "NetworkStatusBridge no delegate for 'removeNetworkStatusListeners'.")
}
}
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public override func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
case "addNetworkStatusListener":
let listener0 : INetworkStatusListener? = NetworkStatusListenerImpl(id: request.getAsyncId()!)
self.addNetworkStatusListener(listener0!);
case "removeNetworkStatusListener":
let listener1 : INetworkStatusListener? = NetworkStatusListenerImpl(id: request.getAsyncId()!)
self.removeNetworkStatusListener(listener1!);
case "removeNetworkStatusListeners":
self.removeNetworkStatusListeners();
default:
// 404 - response null.
responseCode = 404
responseMessage = "NetworkStatusBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
apache-2.0
|
cab78bf6ce956ba75d8bd6160052f3ca
| 40.484043 | 237 | 0.638031 | 5.327186 | false | false | false | false |
Azoy/Sword
|
Sources/Sword/Rest/Endpoint.swift
|
1
|
2081
|
//
// Endpoint.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2019 Alejandro Alonso. All rights reserved.
//
import Foundation
import NIOHTTP1
/// Represents an API call
struct Endpoint {
/// The http method used for this endpoint
let method: HTTPMethod
/// Path of endpoint
let path: Path
/// Query items
var query = [URLQueryItem]()
/// Bucket name for this endpoint
var route: String {
return "\(method):\(path.value):\(path.majorParam)"
}
/// The API URL
var url: String {
var components = URLComponents()
components.scheme = "https"
components.host = "discordapp.com"
components.path = "/api/" + Sword.apiVersion + path.value
components.queryItems = query
return components.url!.absoluteString
}
/// Creates an Endpoint
///
/// - parameter method: The HTTP method used for this endpoint
/// - parameter path: The API path for this endpoint
init(_ method: HTTPMethod, _ path: Path) {
self.method = method
self.path = path
}
}
extension Endpoint {
// Nifty thing that allows us to do "/channels/\(major: id)/" and receive the
// major param along with the whole url.
struct Path: ExpressibleByStringInterpolation {
let majorParam: String
let value: String
init(stringLiteral value: String) {
self.value = value
self.majorParam = ""
}
struct StringInterpolation: StringInterpolationProtocol {
var output = ""
var major = ""
init(literalCapacity: Int, interpolationCount: Int) {}
mutating func appendLiteral(_ literal: String) {
output += literal
}
mutating func appendInterpolation(_ literal: String) {
appendLiteral(literal)
}
mutating func appendInterpolation(major: String) {
self.major = major
appendLiteral(major)
}
}
init(stringInterpolation: StringInterpolation) {
self.value = stringInterpolation.output
self.majorParam = stringInterpolation.major
}
}
}
|
mit
|
7f087d7f4b2079e960d6a6d29e41c38c
| 22.908046 | 79 | 0.638942 | 4.705882 | false | false | false | false |
Poligun/NihonngoSwift
|
Nihonngo/EditWordViewController.swift
|
1
|
5779
|
//
// EditWordViewController.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/1.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class EditWordViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIAlertViewDelegate {
private let editCellIdentifier = "EditCell"
private let labelCellIdentifier = "LabelCellIdentifier"
private let meaningPreviewCellIdentifier = "MeaningPreviewCell"
private var tableView: UITableView!
private var onDeleteFunc: (() -> Void)?
private var editingWord: Word!
private var types: [WordType] = []
convenience init(editingWord: Word, onDelete: (() -> Void)?) {
self.init()
self.editingWord = editingWord
for type in editingWord.types.allObjects as [Type] {
types.append(type.wordType)
}
self.onDeleteFunc = onDelete
}
override func viewDidLoad() {
tableView = UITableView(frame: self.view.bounds, style: .Grouped)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
let recognizer = UITapGestureRecognizer(target: self, action: "endEditing")
recognizer.cancelsTouchesInView = false
tableView.addGestureRecognizer(recognizer)
tableView.registerClass(EditCell.self, forCellReuseIdentifier: editCellIdentifier)
tableView.registerClass(LabelCell.self, forCellReuseIdentifier: labelCellIdentifier)
tableView.registerClass(MeaningPreviewCell.self, forCellReuseIdentifier: meaningPreviewCellIdentifier)
navigationItem.title = "编辑单词"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "删除", style: .Plain, target: self, action: "onDeleteButtonClick:")
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
override func viewWillDisappear(animated: Bool) {
endEditing()
}
func endEditing() {
self.view.endEditing(false)
}
func onDeleteButtonClick(sender: AnyObject) {
UIAlertView(title: "确认删除该单词吗", message: "一旦删除将不可恢复。", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确认").show()
}
// AlertView Delegate
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if buttonIndex == 1 {
DataStore.sharedInstance.deleteWord(editingWord)
onDeleteFunc?()
navigationController?.popViewControllerAnimated(true)
}
}
// TextField Delegate for Word & Kana
func textFieldDidEndEditing(textField: UITextField) {
if textField.tag == 0 {
editingWord.word = textField.text
} else if textField.tag == 1 {
editingWord.kana = textField.text
}
DataStore.sharedInstance.saveContext()
}
// TableView DataSource & Delegate
let sectionHeaders = ["拼写", "类型", "释义"]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionHeaders.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionHeaders[section]
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 2
case 1:
return 1
case 2:
return editingWord.meanings.count
default:
return 0
}
}
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String! {
return "删除"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier(editCellIdentifier, forIndexPath: indexPath) as EditCell
if (indexPath.row == 0) {
cell.setAll(label: "单词", textField: self.editingWord.word, fieldTag: 0, delegate: self)
} else {
cell.setAll(label: "假名", textField: self.editingWord.kana, fieldTag: 1, delegate: self)
}
return cell
} else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier(labelCellIdentifier, forIndexPath: indexPath) as LabelCell
cell.setLabelText(editingWord.stringByJoiningTypes(), textAlignment: .Center)
return cell
} else if indexPath.section == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier(meaningPreviewCellIdentifier, forIndexPath: indexPath) as MeaningPreviewCell
cell.setMeaning(editingWord.meanings[indexPath.row] as Meaning)
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 1:
let viewController = EditTypeViewController(word: editingWord)
self.navigationController?.pushViewController(viewController, animated: true)
case 2:
let viewController = MeaningPreviewViewController(meaning: editingWord.meanings[indexPath.row] as Meaning)
self.navigationController?.pushViewController(viewController, animated: true)
default:
return
}
}
}
|
mit
|
2a977b8686401c8235709fd383e5fc84
| 35.754839 | 143 | 0.666316 | 5.32928 | false | false | false | false |
hamzamuhammad/iChan
|
iChan/iChan/AnimatedEqualizerView.swift
|
1
|
4392
|
//
// AnimatedEqualizerView.swift
// iChan
//
// Created by Hamza Muhammad on 12/18/16.
// Copyright © 2016 Hamza Muhammad. All rights reserved.
//
import UIKit
class AnimatedEqualizerView: UIView {
var containerView: UIView! // this is our view inside storyboard
let containerLayer = CALayer() // this is a container for all other layers
var childLayers = [CALayer]() // we will store animated layers inside an array
let lowBezierPath = UIBezierPath() // to create animation, we use a path as original shape
let middleBezierPath = UIBezierPath() // our lines will animate low, or high to create random effect
let highBezierPath = UIBezierPath() // and this is high position of animation
var animations = [CABasicAnimation]() // finally, an array to store animation objects
init(containerView: UIView) { //custom initializer
self.containerView = containerView // reference to container view
super.init(frame: containerView.frame) // then call super initializer
self.initCommon() // a function for common init
self.initContainerLayer() // init the container layer
self.initBezierPath() // init all paths
self.initBars() // init child layers which will draw lines
self.initAnimation() // init animation objects
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initCommon() {
self.frame = CGRect(x: 0, y: 0, width: containerView!.frame.size.width, height: containerView!.frame.size.height)
}
func initContainerLayer() {
containerLayer.frame = CGRect(x: 0, y: 0, width: 60, height: 65)
containerLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
containerLayer.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
self.layer.addSublayer(containerLayer)
}
func initBezierPath() {
lowBezierPath.move(to: CGPoint(x: 0, y: 55))
lowBezierPath.addLine(to: CGPoint(x: 0, y: 65))
lowBezierPath.addLine(to: CGPoint(x: 3, y: 65))
lowBezierPath.addLine(to: CGPoint(x: 3, y: 55))
lowBezierPath.addLine(to: CGPoint(x: 0, y: 55))
lowBezierPath.close()
middleBezierPath.move(to: CGPoint(x: 0, y: 15));
middleBezierPath.addLine(to: CGPoint(x: 0, y: 65));
middleBezierPath.addLine(to: CGPoint(x: 3, y: 65));
middleBezierPath.addLine(to: CGPoint(x: 3, y: 15));
middleBezierPath.addLine(to: CGPoint(x: 0, y: 15));
middleBezierPath.close();
highBezierPath.move(to: CGPoint(x: 0, y: 0));
highBezierPath.addLine(to: CGPoint(x: 0, y: 65));
highBezierPath.addLine(to: CGPoint(x: 3, y: 65));
highBezierPath.addLine(to: CGPoint(x: 3, y: 0));
highBezierPath.addLine(to: CGPoint(x: 0, y: 0));
highBezierPath.close();
}
func initBars() {
for index in 0...4 {
let bar = CAShapeLayer()
bar.frame = CGRect(x: CGFloat(15 * index), y: 0, width: 3, height: 65)
bar.path = lowBezierPath.cgPath
bar.fillColor = UIColor.white.cgColor
containerLayer.addSublayer(bar)
childLayers.append(bar)
}
}
func initAnimation() {
for index in 0...4 {
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = lowBezierPath.cgPath
if (index % 2 == 0) {
animation.toValue = middleBezierPath.cgPath
} else {
animation.toValue = highBezierPath.cgPath
}
animation.autoreverses = true
animation.duration = 0.5
animation.repeatCount = MAXFLOAT
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1)
animations.append(animation)
}
}
func animate() {
for index in 0...4 {
let delay = 0.1 * Double(index)
let deadlineTime = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
self.addAnimation(index: index)
}
}
}
func addAnimation(index: Int) {
let animationKey = "\(index)Animation"
childLayers[index].add(animations[index], forKey: animationKey)
}
}
|
apache-2.0
|
0ab6bfe3e6dfcf422fe44aa378174627
| 37.858407 | 121 | 0.616716 | 4.254845 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/Pods/Bolts-Swift/Sources/BoltsSwift/Task.swift
|
4
|
9324
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
enum TaskState<TResult> {
case pending()
case success(TResult)
case error(Error)
case cancelled
static func fromClosure(_ closure: () throws -> TResult) -> TaskState {
do {
return .success(try closure())
} catch is CancelledError {
return .cancelled
} catch {
return .error(error)
}
}
}
struct TaskContinuationOptions: OptionSet {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
static let RunOnSuccess = TaskContinuationOptions(rawValue: 1 << 0)
static let RunOnError = TaskContinuationOptions(rawValue: 1 << 1)
static let RunOnCancelled = TaskContinuationOptions(rawValue: 1 << 2)
static let RunAlways: TaskContinuationOptions = [ .RunOnSuccess, .RunOnError, .RunOnCancelled ]
}
//--------------------------------------
// MARK: - Task
//--------------------------------------
///
/// The consumer view of a Task.
/// Task has methods to inspect the state of the task, and to add continuations to be run once the task is complete.
///
public final class Task<TResult> {
public typealias Continuation = () -> Void
fileprivate let synchronizationQueue = DispatchQueue(label: "com.bolts.task", attributes: DispatchQueue.Attributes.concurrent)
fileprivate var _completedCondition: NSCondition?
fileprivate var _state: TaskState<TResult> = .pending()
fileprivate var _continuations: [Continuation] = Array()
// MARK: Initializers
init() {}
init(state: TaskState<TResult>) {
_state = state
}
/**
Creates a task that is already completed with the given result.
- parameter result: The task result.
*/
public init(_ result: TResult) {
_state = .success(result)
}
/**
Initializes a task that is already completed with the given error.
- parameter error: The task error.
*/
public init(error: Error) {
_state = .error(error)
}
/**
Creates a cancelled task.
- returns: A cancelled task.
*/
public class func cancelledTask() -> Self {
// Swift prevents this method from being called `cancelled` due to the `cancelled` instance var. This is most likely a bug.
return self.init(state: .cancelled)
}
class func emptyTask() -> Task<Void> {
return Task<Void>(state: .success())
}
// MARK: Execute
/**
Creates a task that will complete with the result of the given closure.
- note: The closure cannot make the returned task to fail. Use the other `execute` overload for this.
- parameter executor: Determines how the the closure is called. The default is to call the closure immediately.
- parameter closure: The closure that returns the result of the task.
The returned task will complete when the closure completes.
*/
public convenience init(_ executor: Executor = .default, closure: @escaping ((Void) throws -> TResult)) {
self.init(state: .pending())
executor.execute {
self.trySet(state: TaskState.fromClosure(closure))
}
}
/**
Creates a task that will continue with the task returned by the given closure.
- parameter executor: Determines how the the closure is called. The default is to call the closure immediately.
- parameter closure: The closure that returns the continuation task.
The returned task will complete when the continuation task completes.
- returns: A task that will continue with the task returned by the given closure.
*/
public class func execute(_ executor: Executor = .default, closure: @escaping ((Void) throws -> TResult)) -> Task {
return Task(executor, closure: closure)
}
/**
Creates a task that will continue with the task returned by the given closure.
- parameter executor: Determines how the the closure is called. The default is to call the closure immediately.
- parameter closure: The closure that returns the continuation task.
The returned task will complete when the continuation task completes.
- returns: A task that will continue with the task returned by the given closure.
*/
public class func executeWithTask(_ executor: Executor = .default, closure: @escaping (() throws -> Task)) -> Task {
return emptyTask().continueWithTask(executor) { _ in
return try closure()
}
}
// MARK: State Accessors
/// Whether this task is completed. A completed task can also be faulted or cancelled.
public var completed: Bool {
switch state {
case .pending:
return false
default:
return true
}
}
/// Whether this task has completed due to an error or exception. A `faulted` task is also completed.
public var faulted: Bool {
switch state {
case .error:
return true
default:
return false
}
}
/// Whether this task has been cancelled. A `cancelled` task is also completed.
public var cancelled: Bool {
switch state {
case .cancelled:
return true
default:
return false
}
}
/// The result of a successful task. Won't be set until the task completes with a `result`.
public var result: TResult? {
switch state {
case .success(let result):
return result
default:
break
}
return nil
}
/// The error of a errored task. Won't be set until the task completes with `error`.
public var error: Error? {
switch state {
case .error(let error):
return error
default:
break
}
return nil
}
/**
Waits until this operation is completed.
This method is inefficient and consumes a thread resource while it's running.
It should be avoided. This method logs a warning message if it is used on the main thread.
*/
public func waitUntilCompleted() {
if Thread.isMainThread {
debugPrint("Warning: A long-running operation is being executed on the main thread waiting on \(self).")
}
var conditon: NSCondition?
synchronizationQueue.sync(flags: .barrier, execute: {
if case .pending = self._state {
conditon = self._completedCondition ?? NSCondition()
self._completedCondition = conditon
}
})
guard let condition = conditon else {
// Task should have been completed
precondition(completed)
return
}
condition.lock()
while !completed {
condition.wait()
}
condition.unlock()
synchronizationQueue.sync(flags: .barrier, execute: {
self._completedCondition = nil
})
}
// MARK: State Change
@discardableResult
func trySet(state: TaskState<TResult>) -> Bool {
var stateChanged = false
var continuations: [Continuation]?
var completedCondition: NSCondition?
synchronizationQueue.sync(flags: .barrier, execute: {
switch self._state {
case .pending():
stateChanged = true
self._state = state
continuations = self._continuations
completedCondition = self._completedCondition
self._continuations.removeAll()
default:
break
}
})
if stateChanged {
completedCondition?.lock()
completedCondition?.broadcast()
completedCondition?.unlock()
for continuation in continuations! {
continuation()
}
}
return stateChanged
}
// MARK: Internal
func appendOrRunContinuation(_ continuation: @escaping Continuation) {
var runContinuation = false
synchronizationQueue.sync(flags: .barrier, execute: {
switch self._state {
case .pending:
self._continuations.append(continuation)
default:
runContinuation = true
}
})
if runContinuation {
continuation()
}
}
var state: TaskState<TResult> {
var value: TaskState<TResult>?
synchronizationQueue.sync {
value = self._state
}
return value!
}
}
//--------------------------------------
// MARK: - Description
//--------------------------------------
extension Task: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of `self`.
public var description: String {
return "Task: \(self.state)"
}
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return "Task: \(self.state)"
}
}
|
mit
|
d10933afbbe3e5563a8624019e622edf
| 29.272727 | 131 | 0.603604 | 5.002146 | false | false | false | false |
bradleypj823/ParseAndCoreImage
|
PhotoViewController.swift
|
1
|
9383
|
//
// PhotoViewController.swift
// ParseCoreImage
//
// Created by Bradley Johnson on 3/2/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import UIKit
import CoreImage
class PhotoViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDataSource, GalleryDelegate {
@IBOutlet weak var imageView: UIImageView!
let alertView = UIAlertController(title: "Options", message: "Select an Option", preferredStyle: UIAlertControllerStyle.ActionSheet)
var gpuContext : CIContext!
var filters = Array<(UIImage, CIContext)->(UIImage)>()
var thumbnail : UIImage!
var currentImage : UIImage! {
didSet(previousImage) {
self.imageView.image = currentImage
self.thumbnail = self.createThumbnail(currentImage)
self.collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var collectionViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var photoButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Post"
self.tabBarItem = UITabBarItem(title: "Post", image: UIImage(named: "picture-50"), selectedImage: UIImage(named: "picture-50"))
self.currentImage = UIImage(named: "photo.jpg")
//setup GPU context
let options = [kCIContextWorkingColorSpace : NSNull()] // helps keep things fast
let eaglContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2)
self.gpuContext = CIContext(EAGLContext: eaglContext, options: options)
self.filters.append(Filters.blur)
self.filters.append(Filters.instant)
self.filters.append(Filters.chrome)
self.filters.append(Filters.noir)
self.filters.append(Filters.sepia)
self.thumbnail = self.createThumbnail(self.imageView.image!)
self.collectionView.dataSource = self
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { (action) -> Void in
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
imagePicker.editing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
self.alertView.addAction(cameraAction)
}
// let sepiaAction = UIAlertAction(title: "Sepia", style: UIAlertActionStyle.Default) { (action) -> Void in
// let startImage = CIImage(image: self.imageView.image)
// let filter = CIFilter(name: "CISepiaTone")
// filter.setDefaults()
// filter.setValue(startImage, forKey: kCIInputImageKey)
// let result = filter.valueForKey(kCIOutputImageKey) as! CIImage
// let extent = result.extent()
// let imageRef = self.gpuContext.createCGImage(result, fromRect: extent)
// self.imageView.image = Filters.instant(self.imageView.image!, context: self.gpuContext)
// }
//self.alertView.addAction(sepiaAction)
let postAction = UIAlertAction(title: "Post", style: UIAlertActionStyle.Default) { (action) -> Void in
println(self.imageView.image!.size)
//resize image before upload
let desiredSize = CGSize(width: 600, height: 600)
UIGraphicsBeginImageContext(desiredSize)
self.imageView.image!.drawInRect(CGRect(x: 0, y: 0, width: 600, height: 600))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
println(resizedImage.size)
let imageData = UIImageJPEGRepresentation(resizedImage, 1.0)
let file = PFFile(name: "post.jpeg", data: imageData)
let imagePost = PFObject(className: "ImagePost")
imagePost["image"] = file
imagePost.saveInBackgroundWithBlock { (succeeded, error) -> Void in
println("save completed!")
}
}
self.alertView.addAction(postAction)
let filterAction = UIAlertAction(title: "Filter", style: UIAlertActionStyle.Default) { (action) -> Void in
self.collectionViewBottomConstraint.constant = 10
//remove and add height
self.view.removeConstraint(self.imageViewHeightConstraint)
self.imageViewHeightConstraint = NSLayoutConstraint(item: self.imageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0)
self.view.addConstraint(self.imageViewHeightConstraint)
//remove and add width
self.view.removeConstraint(self.imageViewWidthConstraint)
self.imageViewWidthConstraint = NSLayoutConstraint(item: self.imageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.6, constant: 0.0)
self.view.addConstraint(self.imageViewWidthConstraint)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: { (finished) -> Void in
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "donePressed")
})
}
self.alertView.addAction(filterAction)
let galleryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default) { (action) -> Void in
self.performSegueWithIdentifier("ShowGallery", sender: self)
}
self.alertView.addAction(galleryAction)
// Do any additional setup after loading the view.
}
func createThumbnail(originalImage : UIImage) -> UIImage {
let desiredSize = CGSize(width: 200, height: 200)
UIGraphicsBeginImageContext(desiredSize)
self.imageView.image!.drawInRect(CGRect(x: 0, y: 0, width: 200, height: 200))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
func donePressed() {
self.collectionViewBottomConstraint.constant = -100
//remove and add new height constraint
self.view.removeConstraint(self.imageViewHeightConstraint)
self.imageViewHeightConstraint = NSLayoutConstraint(item: self.imageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 0.7, constant: 0.0)
self.view.addConstraint(self.imageViewHeightConstraint)
//remove and add new width constraint
self.view.removeConstraint(self.imageViewWidthConstraint)
self.imageViewWidthConstraint = NSLayoutConstraint(item: self.imageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 0.7, constant: 0.0)
self.view.addConstraint(self.imageViewWidthConstraint)
//self.imageViewWidthConstraint.multiplier
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: { (finished) -> Void in
self.navigationItem.rightBarButtonItem = nil
})
}
@IBAction func photoButtonPressed(sender: AnyObject) {
//setup alert controller
if let presentationController = self.alertView.popoverPresentationController {
//location in super view
presentationController.sourceView = photoButton
//location in button
presentationController.sourceRect = photoButton.bounds
}
self.presentViewController(alertView, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
self.currentImage = editedImage
} else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.currentImage = originalImage
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.filters.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FilterCell", forIndexPath: indexPath) as! FilterCell
let filter = self.filters[indexPath.row]
cell.imageView.image = filter(self.thumbnail,self.gpuContext)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowGallery" {
let destination = segue.destinationViewController as! GalleryViewController
destination.delegate = self
}
}
func userDidSelectImage(image: UIImage) {
self.currentImage = image
}
}
|
mit
|
059fd9478deb496a4ade9de36b4fda29
| 42.845794 | 239 | 0.719386 | 5.08013 | false | false | false | false |
szhalf/iepg2ical
|
iEPG2iCal/Classes/TVProgramInfo.swift
|
1
|
6913
|
//
// TVProgramInfo.swift
// iEPG2iCal
//
// Created by Wataru SUZUKI on 8/3/14.
// Copyright (c) 2014 sz50.com. All rights reserved.
//
import Foundation
class TVProgramInfo {
enum FieldError: Error {
case yearValueUnspecified
case monthValueUnspecified
case dateValueUnspecified
case timeValueUnspecified
case startValueUnspecified
case endValueUnspecified
}
var startDateTime: Date {
return _startDateTime!
}
var endDateTime: Date {
return _endDateTime!
}
var station: String {
if let value = _station {
return value
} else {
return ""
}
}
var genre: Int?
var subGenre: Int?
var title: String {
if let value = _title {
return value
} else {
return ""
}
}
var subtitle: String {
if let value = _subtitle {
return value
} else {
return ""
}
}
var memo: String {
if let value = _memo {
return value
} else {
return ""
}
}
var performer: String {
if let value = _performer {
return value
} else {
return ""
}
}
fileprivate static let CRLF = "\r\n"
fileprivate static let CRLF_DATA = CRLF.data(using: String.Encoding.utf8)!
fileprivate var _data: Data
fileprivate var _encoding: String.Encoding
fileprivate var _version: String?
fileprivate var _startDateTime: Date?
fileprivate var _endDateTime: Date?
fileprivate var _station: String?
fileprivate var _title: String?
fileprivate var _subtitle: String?
fileprivate var _memo: String?
fileprivate var _performer: String?
fileprivate var _year: Int?
fileprivate var _month: Int?
fileprivate var _date: Int?
fileprivate var _timeStart: String?
fileprivate var _timeEnd: String?
init(data: Data) throws {
_encoding = String.Encoding.ascii
_data = data
try self.parse()
}
fileprivate func parse() throws {
var cursor = 0
while cursor < _data.count {
guard let range1 = _data.range(of: TVProgramInfo.CRLF_DATA, options: Data.SearchOptions(rawValue: 0), in: Range<Data.Index>(uncheckedBounds: (cursor, _data.count))) else {
break
}
let headerPartEnds = cursor == range1.lowerBound
if !headerPartEnds {
guard let line = String(data: _data.subdata(in: Range(uncheckedBounds: (cursor, range1.lowerBound))), encoding: _encoding) else {
cursor = range1.lowerBound + TVProgramInfo.CRLF_DATA.count
continue
}
let (name, value) = Utils.splitStringIntoKeyAndValue(line, delimiter: ":")
switch name.lowercased() {
case "content-type":
(_, _encoding) = Utils.parseContentType(value as String)
case "version":
_version = value
case "station":
_station = value
case "year":
_year = Int(value)
case "month":
_month = Int(value)
case "date":
_date = Int(value)
case "start":
_timeStart = value
case "end":
_timeEnd = value
case "program-title":
_title = value
case "program-subtitle":
_subtitle = value
case "performer":
_performer = value
case "genre":
self.genre = Int(value)
case "subgenre":
self.subGenre = Int(value)
default:
break
}
} else {
cursor += TVProgramInfo.CRLF_DATA.count
_memo = String(data: _data.subdata(in: Range(uncheckedBounds: (cursor, _data.count))), encoding: _encoding)
break
}
cursor = range1.lowerBound + TVProgramInfo.CRLF_DATA.count
}
do {
try _startDateTime = self.makeDate(claimedYear: _year, claimedMonth: _month, claimedDate: _date, claimedTime: _timeStart)
} catch FieldError.timeValueUnspecified {
throw FieldError.startValueUnspecified
}
do {
try _endDateTime = self.makeDate(claimedYear: _year, claimedMonth: _month, claimedDate: _date, claimedTime: _timeEnd)
} catch FieldError.timeValueUnspecified {
throw FieldError.endValueUnspecified
}
if let start = _startDateTime, let end = _endDateTime {
if (start.compare(end) == ComparisonResult.orderedDescending) {
_endDateTime = end.addingTimeInterval(TimeInterval(60 * 60 * 24))
}
}
}
fileprivate func makeDate(claimedYear: Int?, claimedMonth: Int?, claimedDate: Int?, claimedTime: String?) throws -> Date {
var claimedHour: Int? = nil
var claimedMinute: Int? = nil
if let time = claimedTime {
let array = time.components(separatedBy: ":")
claimedHour = Int(array[0])
claimedMinute = Int(array[1])
}
guard let year = claimedYear else {
throw FieldError.yearValueUnspecified
}
guard let month = claimedMonth else {
throw FieldError.monthValueUnspecified
}
guard let date = claimedDate else {
throw FieldError.dateValueUnspecified
}
guard let hour = claimedHour, let minute = claimedMinute else {
throw FieldError.timeValueUnspecified
}
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let components = [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day] as Set<Calendar.Component>
var dateComponents = calendar.dateComponents(components, from: Date())
dateComponents.setValue(year, for: Calendar.Component.year)
dateComponents.setValue(month, for: Calendar.Component.month)
dateComponents.setValue(date, for: Calendar.Component.day)
dateComponents.setValue(hour < 24 ? hour : hour - 24, for: Calendar.Component.hour)
dateComponents.setValue(minute, for: Calendar.Component.minute)
if hour >= 24 {
if let day = dateComponents.day {
dateComponents.setValue(day + 1, for: Calendar.Component.day)
}
}
return calendar.date(from: dateComponents)!
}
}
|
mit
|
eb4b9f31643aed086bb163b12cc9f2b7
| 30.13964 | 183 | 0.546073 | 4.797363 | false | false | false | false |
vector-im/vector-ios
|
Riot/Modules/Room/TimelineDecorations/Reactions/RoomReactionViewCell.swift
|
1
|
3736
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import Reusable
final class RoomReactionViewCell: UICollectionViewCell, NibReusable, Themable {
// MARK: - Constants
private enum Constants {
static let selectedBorderWidth: CGFloat = 1.0
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var reactionBackgroundView: UIView!
@IBOutlet private weak var emojiLabel: UILabel!
@IBOutlet private weak var countLabel: UILabel!
// MARK: Private
private var theme: Theme?
// MARK: Public
private var isReactionSelected: Bool = false
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.reactionBackgroundView.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
self.reactionBackgroundView.layer.cornerRadius = self.reactionBackgroundView.frame.size.height/2.0
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
/*
On iOS 12, there are issues with self-sizing cells as described in Apple release notes (https://developer.apple.com/documentation/ios_release_notes/ios_12_release_notes) :
"You might encounter issues with systemLayoutSizeFitting(_:) when using a UICollectionViewCell subclass that requires updateConstraints().
(42138227) — Workaround: Don't call the cell's setNeedsUpdateConstraints() method unless you need to support live constraint changes.
If you need to support live constraint changes, call updateConstraintsIfNeeded() before calling systemLayoutSizeFitting(_:)."
*/
self.updateConstraintsIfNeeded()
return super.preferredLayoutAttributesFitting(layoutAttributes)
}
// MARK: - Public
func fill(viewData: RoomReactionViewData) {
self.emojiLabel.text = viewData.emoji
self.countLabel.text = viewData.countString
self.isReactionSelected = viewData.isCurrentUserReacted
self.updateViews()
}
func update(theme: Theme) {
self.theme = theme
self.reactionBackgroundView.layer.borderColor = theme.tintColor.cgColor
self.emojiLabel.textColor = theme.textPrimaryColor
self.countLabel.textColor = theme.textPrimaryColor
self.updateViews()
}
// MARK: - Private
private func updateViews() {
let reactionBackgroundColor: UIColor?
let reactionBackgroundBorderWidth: CGFloat
if self.isReactionSelected {
reactionBackgroundColor = self.theme?.tintBackgroundColor
reactionBackgroundBorderWidth = Constants.selectedBorderWidth
} else {
reactionBackgroundColor = self.theme?.headerBackgroundColor
reactionBackgroundBorderWidth = 0.0
}
self.reactionBackgroundView.layer.borderWidth = reactionBackgroundBorderWidth
self.reactionBackgroundView.backgroundColor = reactionBackgroundColor
}
}
|
apache-2.0
|
00f65387dfc4ebfd62999135cc7ec2b7
| 33.897196 | 180 | 0.697375 | 5.573134 | false | false | false | false |
juliantejera/JTDataStructures
|
JTDataStructures/Trees/BinarySearchTreeNode.swift
|
1
|
2102
|
//
// BinarySearchTreeNode.swift
// JTDataStructures
//
// Created by Julian Tejera-Frias on 7/21/16.
// Copyright © 2016 Julian Tejera. All rights reserved.
//
import Foundation
public class BinarySearchTreeNode<T: Comparable> {
public var value: T
public var parent: BinarySearchTreeNode?
public var left: BinarySearchTreeNode?
public var right: BinarySearchTreeNode?
public var depth: Int {
var i = 0
var node = self
while let parent = node.parent {
node = parent
i += 1
}
return i
}
public var hasChildren: Bool {
return left != nil || right != nil
}
public var isLeftChild: Bool {
return parent?.left === self
}
public var isRightChild: Bool {
return parent?.right === self
}
public var isOrphan: Bool {
return parent == nil
}
public var minimum: BinarySearchTreeNode<T>? {
var currentNode = self
while let left = currentNode.left {
currentNode = left
}
return currentNode
}
public var maximum: BinarySearchTreeNode<T>? {
var currentNode = self
while let right = currentNode.right {
currentNode = right
}
return currentNode
}
public var successor: BinarySearchTreeNode<T>? {
if let right = self.right {
return right.minimum
}
var currentNode = self
while let parent = currentNode.parent , currentNode.isRightChild {
currentNode = parent
}
return currentNode.parent
}
public var predecessor: BinarySearchTreeNode<T>? {
if let left = self.left {
return left.maximum
}
var currentNode = self
while let parent = currentNode.parent , currentNode.isLeftChild {
currentNode = parent
}
return currentNode.parent
}
public init(value: T) {
self.value = value
}
}
|
mit
|
cd5fe37a71af52b5a334fbb227dd2464
| 22.087912 | 74 | 0.558306 | 5.174877 | false | false | false | false |
andrliu/hello-world-vapor
|
Sources/App/main.swift
|
1
|
4260
|
import Vapor
import VaporPostgreSQL
let drop = Droplet(
preparations: [Acronym.self],
providers: [VaporPostgreSQL.Provider.self]
)
//drop.get { req in
// return try drop.view.make("welcome", [
// "message": drop.localization[req.lang, "welcome", "title"]
// ])
//}
//
//drop.resource("posts", PostController())
//MARK:
//MARK: Getting Started
drop.get { request in
return "Hello World!"
}
drop.get("hello") { request in
return try JSON(node: [
"message": "Hello Again!"
])
}
drop.get("hello", "there") { request in
return try JSON(node: [
"message": "Hello There!"
])
}
drop.get("beers", Int.self) { request, beers in
return try JSON(node: [
"message": "One down, \(beers - 1) left..."
])
}
drop.post("post") { request in
guard let name = request.data["name"]?.string else {
throw Abort.badRequest
}
return try JSON(node: [
"message": "Hello, \(name)!"
])
}
//MARK:
//MARK: Templating with Leaf
drop.get("template") { request in
return try drop.view.make("hello", Node(node: ["name": "anyone"]))
}
drop.get("template", String.self) { request, name in
return try drop.view.make("hello", Node(node: ["name": name]))
}
drop.get("template-collection") { request in
let users = try ["Andrew", "Jacy", "Benben"].makeNode()
return try drop.view.make("hello_loop", Node(node: ["users": users]))
}
drop.get("template-collection-dictionary") { request in
let users = try [
["name": "Andrew", "email": "[email protected]"].makeNode(),
["name": "Jacy", "email": "[email protected]"].makeNode(),
["name": "Benben", "email": "[email protected]"].makeNode()
].makeNode()
return try drop.view.make("hello_loop_dic", Node(node: ["users": users]))
}
drop.get("template-ifelse") { request in
guard let sayHello = request.data["sayHello"]?.bool else {
throw Abort.badRequest
}
return try drop.view.make("hello_ifelse", Node(node: ["sayHello": sayHello.makeNode()]))
}
//MARK:
//MARK: Configuring a Database
//drop.get("version") { request in
// if let db = drop.database?.driver as? PostgreSQLDriver {
// let version = try db.raw("SELECT version()")
// return try JSON(node: version)
// } else {
// return "No db connection"
// }
//}
//MARK:
//MARK: Persisting Models
//drop.get("model") { request in
// let acronym = Acronym(short: "AFK", long: "Away From Keyboard")
// return try acronym.makeJSON()
//}
drop.get("test") { request in
var acronym = Acronym(short: "BRB", long: "Be Right Back")
try acronym.save()
return try JSON(node: Acronym.all().makeNode())
}
//MARK:
//MARK: CRUD Database Options
//MARK: Create
drop.get("new") { request in
var acronym = try Acronym(node: request.json)
try acronym.save()
return acronym
}
//MARK: Read
drop.get("all") { request in
return try JSON(node: Acronym.all().makeNode())
}
drop.get("first") { request in
return try JSON(node: Acronym.query().first()?.makeNode())
}
drop.get("afks") { request in
return try JSON(node: Acronym.query().filter("short", "AFK").all().makeNode())
}
drop.get("not-afks") { request in
return try JSON(node: Acronym.query().filter("short", .notEquals,"AFK").all().makeNode())
}
//MARK: Update
drop.get("update") { request in
guard var first = try Acronym.query().first(),
let long = request.data["long"]?.string else {
throw Abort.badRequest
}
first.long = long
try first.save()
return first
}
//MARK: Delete
drop.get("delete-afks") { request in
let query = try Acronym.query().filter("short", "AFK")
try query.delete()
return try JSON(node: Acronym.all().makeNode())
}
//MARK:
//MARK: Deploying to Heroku with PostgreSQL
// $heroku addons:create heroku-postgresql:hobby-dev
// $vi Procfile
// $web: App --env=production --workdir="./"
// $web: App --env=production --workdir=./ --config:servers.default.port=$PORT —config:postgresql.url=$DATABASE_URL
//MARK:
//MARK: Basic Controllers
let basic = BasicController()
basic.addRoutes(drop: drop)
//MARK:
//MARK: RESTful Controllers
let acronyms = AcronymsController()
drop.resource("acronyms", acronyms)
drop.run()
|
mit
|
1b8eea5bd1bedcefad64b5da9a671447
| 24.345238 | 115 | 0.628229 | 3.352756 | false | false | false | false |
CaryZheng/ZDropdown
|
ZDropdown/ZDropdown/ZDropdown/ZDropdownWidget.swift
|
1
|
5527
|
//
// ZDropdownWidget.swift
// ZDropdown
//
// Created by CaryZheng on 7/9/15.
// Copyright (c) 2015 CaryZheng. All rights reserved.
//
import UIKit
class ZDropdownWidget : UIView, IZDropdownView, IZDropdownContainer
{
var mDefaultSetting = "请选择"
var mCurrentSelectedIndex = -1
var mDataNameList = Array<String>()
var mDataCodeList = Array<AnyObject>()
private var mSelectedData = CommonKeyValue()
private var mBtn: UIButton!
private var mArrowImage: UIImageView!
private var mWindows = Array<UIWindow!>()
private var mDropdown: ZDropdownView!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView()
{
mBtn = UIButton(frame: self.bounds)
mBtn.backgroundColor = ColorUtility.colorize(0xEEEEEE)
setTitle(mDefaultSetting, tag: -1)
mBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
mBtn.addTarget(self, action: "onBtnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
mBtn.titleLabel!.font = mBtn.titleLabel!.font.fontWithSize(11)
self.addSubview(mBtn)
mArrowImage = UIImageView(image: UIImage(named: "pic_spinner_arrow_down"))
mArrowImage.frame.size = CGSizeMake(10, 10)
mArrowImage.center = CGPointMake(self.bounds.width-10, self.bounds.height/2)
self.addSubview(mArrowImage)
let dropdown = ZDropdownView()
dropdown.delegate = self
mDropdown = dropdown
}
func setTitle(text: String, tag: AnyObject)
{
mBtn.setTitle(text, forState: UIControlState.Normal)
mSelectedData.name = text
mSelectedData.code = tag
}
func getTitle() -> String?
{
return mSelectedData.name
}
func getTitleTag() -> AnyObject?
{
return mSelectedData.code
}
func onBtnPressed(sender: UIButton)
{
print("onBtnPressed")
didWillOpen()
let attachedView = sender
let sizeRect = UIScreen.mainScreen().bounds
let width = sizeRect.size.width
let height = sizeRect.size.height
let window = UIWindow(frame: CGRectMake(0, 0, width, height))
window.backgroundColor = UIColor.clearColor()
window.windowLevel = UIWindowLevelAlert
window.center = CGPointMake(width/2, height/2)
window.hidden = false
let mainView = ZDropdownContainer(frame: CGRectMake(0, 0, width, height))
mainView.delegate = self
mainView.backgroundColor = UIColor.clearColor()
window.addSubview(mainView)
let dropdown = mDropdown
let dropdownOrigin = attachedView.convertPoint(attachedView.bounds.origin, toView: nil)
dropdown.frame = CGRectMake(dropdownOrigin.x, dropdownOrigin.y+attachedView.bounds.height, attachedView.bounds.width, 140)
dropdown.showDropdown(attachedView)
mainView.addSubview(dropdown)
mWindows.append(window)
mArrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI*180/180))
}
func didWillOpen()
{
}
func didSelectItem(index: Int)
{
mCurrentSelectedIndex = index
setTitle(mDataNameList[index], tag: mDataCodeList[index])
hideDropdown()
}
func onZDropdownContainerTouchesBegan()
{
hideDropdown()
}
func hideDropdown()
{
self.mArrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI*0/180))
// close animation
UIView.animateWithDuration(0.2, delay: 0, options: .CurveLinear, animations: {
let tableView = self.mDropdown.getTableView()
if(nil == tableView)
{
return
}
tableView!.frame = CGRectMake(tableView!.frame.origin.x, tableView!.frame.origin.y, tableView!.bounds.width, 0)
}, completion: { finished in
if(0 == self.mWindows.count)
{
return
}
self.mWindows[0].removeFromSuperview()
self.mWindows = Array<UIWindow!>()
})
}
func getCurrentSelectedCode() -> AnyObject?
{
if(-1 == mCurrentSelectedIndex)
{
return nil
}
return mSelectedData.code
}
func getCurrentSelectedName() -> String?
{
if(-1 == mCurrentSelectedIndex)
{
return nil
}
return mSelectedData.name
}
func getCurrentSelectedIndex() -> Int
{
return mCurrentSelectedIndex
}
func setData(dataList: Array<String>)
{
mDataNameList = dataList
mDropdown.setData(dataList)
}
func setDataCode(dataList: Array<AnyObject>)
{
mDataCodeList = dataList
}
func reloadData()
{
mDropdown.reloadData()
}
func reset()
{
setTitle(mDefaultSetting, tag: -1)
setData(Array<String>())
setDataCode(Array<String>())
reloadData()
}
}
|
mit
|
6a2ef221a2297a969525153fbad46e7f
| 25.04717 | 130 | 0.577794 | 4.834501 | false | false | false | false |
JeffJin/ios9_notification
|
twilio/Services/Models/ViewModel/EventListViewModel.swift
|
2
|
3372
|
//
// Appointment.swift
// AppointmentManagement
//
// Created by Zhengyuan Jin on 2015-03-14.
// Copyright (c) 2015 eWorkspace Solutions Inc. All rights reserved.
//
import Foundation
@objc public class EventListViewModel : NSObject {
let defaultImage: NSString = "default-no-image.png"
//MARK: Properties
dynamic var searchText = ""
dynamic var previousSearches: [PreviousSearchViewModel]
var executeSearch: RACCommand!
let title = "Event Search"
var previousSearchSelected: RACCommand!
var connectionErrors: RACSignal!
private let services: ViewModelServices
//MARK: Public APIprintln
init(services: ViewModelServices) {
self.services = services
self.previousSearches = []
super.init()
setupRac()
}
func setupRac(){
var validSearchSignal = RACObserve(self, "searchText").mapAs {
(text: NSString) -> NSNumber in
return text.length > 3
}.distinctUntilChanged();
executeSearch = RACCommand(enabled: validSearchSignal) {
(any:AnyObject!) -> RACSignal in
return self.executeSearchSignal()
}
connectionErrors = executeSearch!.errors
previousSearchSelected = RACCommand() {
(any:AnyObject!) -> RACSignal in
let previousSearch = any as! PreviousSearchViewModel
self.searchText = previousSearch.searchString
return self.executeSearchSignal()
}
}
//MARK: Private methods
private func executeSearchSignal() -> RACSignal {
return services.appointmentService.searchAppointments(123456, keywords: "soccer").doNextAs {
(results: ScheduleSearchResults) -> () in
let viewModel = SearchResultsViewModel(services: self.services, searchResults: results)
self.services.pushViewModel(viewModel)
self.addToSearchHistory(results)
}
}
private func addToSearchHistory(result: ScheduleSearchResults) {
let matches = previousSearches.filter { $0.searchString == self.searchText }
var previousSearchesUpdated = previousSearches
if matches.count > 0 {
let match = matches[0]
var withoutMatch = previousSearchesUpdated.filter { $0.searchString != self.searchText }
withoutMatch.insert(match, atIndex: 0)
previousSearchesUpdated = withoutMatch
} else {
let previousSearch = PreviousSearchViewModel(searchString: searchText, totalResults: result.totalResults, thumbnail: NSURL(fileURLWithPath: result.events[0].imageLink as! String)!)
previousSearchesUpdated.insert(previousSearch, atIndex: 0)
}
if (previousSearchesUpdated.count > 10) {
previousSearchesUpdated.removeLast()
}
previousSearches = previousSearchesUpdated
}
public func getImage(imageLink:String) -> UIImage{
if(imageLink != ""){
var url: NSURL = NSURL(string: imageLink)!
var imageData = NSData(contentsOfURL: url)!
return UIImage(data: imageData)!
}
else{
return UIImage(named: self.defaultImage as String)!
}
}
}
|
apache-2.0
|
585817a15784f091221d246c48eb57ee
| 31.423077 | 192 | 0.622183 | 5.211747 | false | false | false | false |
micchyboy1023/CoreAnimation100Days
|
CoreAnimation100Days/Day5View.swift
|
1
|
4615
|
//
// Day5View.swift
// CoreAnimation100Days
//
// Created by UetaMasamichi on 2015/06/04.
// Copyright (c) 2015年 Masamichi Ueta. All rights reserved.
//
import UIKit
@objc(Day5View)
@IBDesignable class Day5View: UIView {
var gradientLayer: CAGradientLayer!
var circleProgressLayer: CAShapeLayer!
var circleBackLayer: CAShapeLayer!
var circleCenter: CGPoint!
var currentRate: CGFloat = 0
var timer: NSTimer!
var progress: CGFloat = 0.0
@IBOutlet weak var rateLabel: UILabel!
@IBInspectable var circleRadius: CGFloat = CGFloat(100)
@IBInspectable var gradientStartColor: UIColor = UIColor(red: 217 / 255.0, green: 69 / 255.0, blue: 74.0 / 255.0, alpha: 1.0)
@IBInspectable var gradientEndColor: UIColor = UIColor(red: 204.0 / 255.0, green: 104.0 / 255.0, blue: 58.0 / 255.0, alpha: 1.0)
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForInterfaceBuilder() {
circleCenter = CGPoint(x: self.center.x , y: 200)
drawBackgoundGradient()
drawBackCircle()
drawProgressCircle()
}
override func drawRect(rect: CGRect) {
circleCenter = CGPoint(x: self.center.x , y: 200)
drawBackgoundGradient()
drawBackCircle()
drawProgressCircle()
}
func drawBackgoundGradient() {
if gradientLayer == nil {
gradientLayer = CAGradientLayer()
let colors = [gradientStartColor.CGColor, gradientEndColor.CGColor]
let locations:[CGFloat] = [0.0, 1.0]
let space = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(space, colors, locations)
gradientLayer.colors = colors
gradientLayer.locations = locations
gradientLayer.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.bounds.width, height: self.bounds.height / 2.0))
self.layer.insertSublayer(gradientLayer, atIndex: 0)
}
}
func drawBackCircle() {
if circleBackLayer == nil {
circleBackLayer = CAShapeLayer()
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleBackLayer.path = path.CGPath
circleBackLayer.strokeColor = UIColor.blackColor().CGColor
circleBackLayer.opacity = 0.1
circleBackLayer.fillColor = nil
circleBackLayer.lineWidth = 20.0
self.layer.addSublayer(circleBackLayer)
}
}
func drawProgressCircle() {
if circleProgressLayer == nil {
circleProgressLayer = CAShapeLayer()
var startAngle = CGFloat(-M_PI_2)
var endAngle = CGFloat(M_PI + M_PI_2)
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
circleProgressLayer.path = path.CGPath
circleProgressLayer.lineWidth = 20.0
circleProgressLayer.lineCap = "round"
circleProgressLayer.strokeColor = UIColor.whiteColor().CGColor
circleProgressLayer.fillColor = nil
circleProgressLayer.strokeStart = 0.0
circleProgressLayer.strokeEnd = progress
self.layer.addSublayer(circleProgressLayer)
}
}
func animate() {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0.0
animation.toValue = progress
animation.duration = NSTimeInterval(progress * 1.5)
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.circleProgressLayer.strokeEnd = progress
self.circleProgressLayer.addAnimation(animation, forKey: "Progress")
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(CGFloat(animation.duration) / (progress * 100)), target: self, selector: "updateText:", userInfo: nil, repeats: true)
}
func updateText(timer: NSTimer) {
if currentRate >= progress * 100 {
timer.invalidate()
return
}
currentRate++
if currentRate % 2 == 0 || currentRate == progress * 100 - 1 {
rateLabel.text = "\(currentRate)%"
}
}
}
|
mit
|
69c17adf2a1a3aa65a9c33cef7ad9dc4
| 34.767442 | 187 | 0.624106 | 4.73614 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
Swift/LeetCode/Stack/20_Valid Parentheses.swift
|
1
|
1066
|
//
// 20. Valid Parentheses.swift
// https://leetcode.com/problems/valid-parentheses/
//
// Created by Honghao Zhang on 2016-11-06.
// Copyright © 2016 Honghaoz. All rights reserved.
//
//Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
//
//The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
import Foundation
class Num20_ValidParentheses: Solution {
func isValid(_ s: String) -> Bool {
let s = [Character](s)
guard s.count > 0 else { return true }
var stack = [Character]()
for char in s {
switch char {
case "(", "{", "[":
stack.append(char)
case ")":
if stack.popLast() != "(" {
return false
}
case "}":
if stack.popLast() != "{" {
return false
}
case "]":
if stack.popLast() != "[" {
return false
}
default: continue
}
}
return stack.count == 0
}
func test() {
}
}
|
mit
|
f4b7a6557b72e6467f29b0590dec4058
| 22.666667 | 120 | 0.529577 | 3.901099 | false | false | false | false |
eljeff/AudioKit
|
Sources/AudioKit/Nodes/Generators/Physical Models/TubularBells.swift
|
1
|
2396
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
#if !os(tvOS)
/// STK TubularBells
///
public class TubularBells: Node, AudioUnitContainer, Tappable, Toggleable {
/// Unique four-letter identifier "tbel"
public static let ComponentDescription = AudioComponentDescription(instrument: "tbel")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit type
public private(set) var internalAU: AudioUnitType?
/// Internal audio unit type for tubular bells
public class InternalAU: AudioUnitBase {
/// Create the tubular bells DSP
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
return akCreateDSP("TubularBellsDSP")
}
/// Trigger a tubular bells note
/// - Parameters:
/// - note: MIDI Note Number
/// - velocity: MIDI Velocity
public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity) {
if let midiBlock = scheduleMIDIEventBlock {
let event = MIDIEvent(noteOn: note, velocity: velocity, channel: 0)
event.data.withUnsafeBufferPointer { ptr in
guard let ptr = ptr.baseAddress else { return }
midiBlock(AUEventSampleTimeImmediate, 0, event.data.count, ptr)
}
}
}
}
// MARK: - Initialization
/// Initialize the STK Tubular Bells model
///
/// - Parameters:
/// - note: MIDI note number
/// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127
///
public init() {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
}
}
/// Trigger the sound with a set of parameters
///
/// - Parameters:
/// - note: MIDI note number
/// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127
///
public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity = 127) {
internalAU?.start()
internalAU?.trigger(note: note, velocity: velocity)
}
}
#endif
|
mit
|
b9ee2473f26de9fd4df4e9a61e3b53b2
| 30.116883 | 100 | 0.625626 | 4.860041 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PhoneNumberUtils.swift
|
1
|
1349
|
//
// PhoneNumberUtils.swift
// Telegram
//
// Created by Mikhail Filimonov on 01.11.2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import libphonenumber
private let phoneNumberUtil = NBPhoneNumberUtil()
func formatPhoneNumber(_ string: String) -> String {
do {
let number = try phoneNumberUtil.parse("+" + string, defaultRegion: nil)
return try phoneNumberUtil.format(number, numberFormat: .INTERNATIONAL)
} catch _ {
return string
}
}
func isViablePhoneNumber(_ string: String) -> Bool {
return phoneNumberUtil.isViablePhoneNumber(string)
}
class ParsedPhoneNumber: Equatable {
let rawPhoneNumber: NBPhoneNumber?
init?(string: String) {
if let number = try? phoneNumberUtil.parse(string, defaultRegion: NB_UNKNOWN_REGION) {
self.rawPhoneNumber = number
} else {
return nil
}
}
static func == (lhs: ParsedPhoneNumber, rhs: ParsedPhoneNumber) -> Bool {
var error: NSError?
let result = phoneNumberUtil.isNumberMatch(lhs.rawPhoneNumber, second: rhs.rawPhoneNumber, error: &error)
if error != nil {
return false
}
if result != .NO_MATCH && result != .NOT_A_NUMBER {
return true
} else {
return false
}
}
}
|
gpl-2.0
|
b616e4b11851a91af1db0f93650a7b46
| 26.510204 | 113 | 0.62908 | 4.306709 | false | false | false | false |
kstaring/swift
|
test/Serialization/class.swift
|
4
|
2158
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-object -emit-module -o %t %S/Inputs/def_class.swift -disable-objc-attr-requires-foundation-module
// RUN: llvm-bcanalyzer %t/def_class.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Defs To Decls" -sil-debug-serialization -I %t %s | %FileCheck %s -check-prefix=SIL
// RUN: echo "import def_class; struct A : ClassProto {}" | not %target-swift-frontend -parse -I %t - 2>&1 | %FileCheck %s -check-prefix=CHECK-STRUCT
// CHECK-NOT: UnknownCode
// CHECK-STRUCT: non-class type 'A' cannot conform to class protocol 'ClassProto'
// Make sure we can "merge" def_class.
// RUN: %target-swift-frontend -emit-module -o %t-merged.swiftmodule %t/def_class.swiftmodule -module-name def_class
import def_class
var a : Empty
var b = TwoInts(a: 1, b: 2)
var computedProperty : ComputedProperty
var sum = b.x + b.y + computedProperty.value
var intWrapper = ResettableIntWrapper()
var r : Resettable = intWrapper
r.reset()
r.doReset()
class AnotherIntWrapper : SpecialResettable, ClassProto {
init() { value = 0 }
var value : Int
func reset() {
value = 0
}
func compute() {
value = 42
}
}
var intWrapper2 = AnotherIntWrapper()
r = intWrapper2
r.reset()
var c : Cacheable = intWrapper2
c.compute()
c.reset()
var p = Pair(a: 1, b: 2.5)
p.first = 2
p.second = 5.0
struct Int {}
var gc = GenericCtor<Int>()
gc.doSomething()
a = StillEmpty()
r = StillEmpty()
var bp = BoolPair<Bool>()
bp.bothTrue()
var rawBP : Pair<Bool, Bool>
rawBP = bp
var rev : SpecialPair<Double>
rev.first = 42
var comp : Computable = rev
var simpleSub = ReadonlySimpleSubscript()
var subVal = simpleSub[4]
var complexSub = ComplexSubscript()
complexSub[4, false] = complexSub[3, true]
var rsrc = Resource()
getReqPairLike()
// SIL-LABEL: sil public_external [transparent] [fragile] @_TFsoi1pFTSiSi_Si : $@convention(thin) (Int, Int) -> Int {
func test(_ sharer: ResourceSharer) {}
class HasNoOptionalReqs : ObjCProtoWithOptional { }
HasNoOptionalReqs()
OptionalImplementer().unrelated()
extension def_class.ComputedProperty { }
|
apache-2.0
|
f055b6ad12570b1227937f4ad5709546
| 23.247191 | 158 | 0.702966 | 3.141194 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/WMFCurrentlyLoggedInUserFetcher.swift
|
1
|
2185
|
public enum WMFCurrentlyLoggedInUserFetcherError: LocalizedError {
case cannotExtractUserInfo
case userIsAnonymous
case blankUsernameOrPassword
public var errorDescription: String? {
switch self {
case .cannotExtractUserInfo:
return "Could not extract user info"
case .userIsAnonymous:
return "User is anonymous"
case .blankUsernameOrPassword:
return "Blank username or password"
}
}
}
public typealias WMFCurrentlyLoggedInUserBlock = (WMFCurrentlyLoggedInUser) -> Void
@objc public class WMFCurrentlyLoggedInUser: NSObject {
@objc public var userID: Int
@objc public var name: String
@objc public var groups: [String]
init(userID: Int, name: String, groups: [String]) {
self.userID = userID
self.name = name
self.groups = groups
}
}
public class WMFCurrentlyLoggedInUserFetcher: Fetcher {
public func fetch(siteURL: URL, success: @escaping WMFCurrentlyLoggedInUserBlock, failure: @escaping WMFErrorHandler) {
let parameters = [
"action": "query",
"meta": "userinfo",
"uiprop": "groups",
"format": "json"
]
performMediaWikiAPIPOST(for: siteURL, with: parameters) { (result, response, error) in
if let error = error {
failure(error)
return
}
guard
let query = result?["query"] as? [String : Any],
let userinfo = query["userinfo"] as? [String : Any],
let userID = userinfo["id"] as? Int,
let userName = userinfo["name"] as? String
else {
failure(WMFCurrentlyLoggedInUserFetcherError.cannotExtractUserInfo)
return
}
guard userinfo["anon"] == nil else {
failure(WMFCurrentlyLoggedInUserFetcherError.userIsAnonymous)
return
}
let groups = userinfo["groups"] as? [String] ?? []
success(WMFCurrentlyLoggedInUser.init(userID: userID, name: userName, groups: groups))
}
}
}
|
mit
|
5b0ad41a0a2c7a549808921f9b00355e
| 34.819672 | 123 | 0.588558 | 4.954649 | false | false | false | false |
piglikeYoung/iOS8-day-by-day
|
08-today-extension/GitHubToday/GitHubToday/TableViewController.swift
|
21
|
2472
|
//
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import GitHubTodayCommon
class TableViewController: UITableViewController {
let dataProvider = GitHubDataProvider()
let mostRecentEventCache = GitHubEventCache(userDefaults: NSUserDefaults(suiteName: "group.GitHubToday")!)
var events: [GitHubEvent] = [GitHubEvent]() {
didSet {
// Must call reload on the main thread
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
override func awakeFromNib() {
title = "GitHub Events"
dataProvider.getEvents("sammyd", callback: {
githubEvents in
self.events = githubEvents
self.mostRecentEventCache.mostRecentEvent = githubEvents[0]
})
}
func scrollToAndHighlightEvent(eventId: Int) {
var eventIndex: Int? = nil
for (index, event) in enumerate(events) {
if event.id == eventId {
eventIndex = index
break
}
}
if let eventIndex = eventIndex {
let indexPath = NSIndexPath(forRow: eventIndex, inSection: 0)
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Top)
}
}
// DataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = events.count
return count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("EventCell", forIndexPath: indexPath) as! UITableViewCell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let eventCell = cell as? EventTableViewCell {
let event = events[indexPath.row]
eventCell.event = event
}
}
}
|
apache-2.0
|
2dcd5d6dc0b0c8112a24870138f2ace9
| 30.291139 | 132 | 0.713188 | 4.672968 | false | false | false | false |
bermudadigitalstudio/Titan
|
Sources/TitanCore/TitanMethod.swift
|
4
|
2669
|
// Copyright 2017 Enervolution 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// An enumeration of available HTTP Request Methods
public indirect enum HTTPMethod: Equatable {
case get
case head
case put
case post
case patch
case delete
case trace
case options
case custom(named: String)
public static func == (lhs: HTTPMethod, rhs: HTTPMethod) -> Bool {
switch (lhs, rhs) {
case (.get, .get):
return true
case (.head, .head):
return true
case (.put, .put):
return true
case (.post, .post):
return true
case (.patch, .patch):
return true
case (.delete, .delete):
return true
case (.trace, .trace):
return true
case (.options, .options):
return true
case (.custom(let a), .custom(let b)):
return a == b
default:
return false
}
}
}
extension HTTPMethod: RawRepresentable {
public typealias RawValue = String
public init?(rawValue: String) {
switch rawValue.lowercased() {
case "get":
self = .get
case "head":
self = .head
case "put":
self = .put
case "post":
self = .post
case "patch":
self = .patch
case "delete":
self = .delete
case "trace":
self = .trace
case "options":
self = .options
default :
self = .custom(named: rawValue)
}
}
public var rawValue: String {
switch self {
case .get:
return "get"
case .head:
return "head"
case .put:
return "put"
case .post:
return "post"
case .patch:
return "patch"
case .delete:
return "delete"
case .trace:
return "trace"
case .options:
return "options"
case .custom(let named):
return named
}
}
}
|
apache-2.0
|
7d4ef573d51d3a1d850d91d819c45aea
| 24.912621 | 77 | 0.532409 | 4.609672 | false | false | false | false |
bestwpw/LTJelloSwitch
|
Pod/Classes/LTTriggerOnView.swift
|
1
|
2750
|
//
// LTTriggerOnView.swift
// LTJelloSwitch
//
// Created by Lex Tang on 4/13/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
import UIKit
public class LTTriggerOnView: UIView
{
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
backgroundColor = UIColor.clearColor()
}
public override func drawRect(rect: CGRect) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
let tintColor = UIColor.redColor()
let titleColor = UIColor.whiteColor()
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(7, 2, 32, 32))
tintColor.setFill()
ovalPath.fill()
//// Polygon Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 5.07, 16.51)
CGContextRotateCTM(context, 8 * CGFloat(M_PI) / 180)
var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(6.5, 0))
polygonPath.addLineToPoint(CGPointMake(12.13, 10.5))
polygonPath.addLineToPoint(CGPointMake(0.87, 10.5))
polygonPath.closePath()
tintColor.setFill()
polygonPath.fill()
CGContextRestoreGState(context)
//// Text Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 11, 13.76)
CGContextRotateCTM(context, -20.44 * CGFloat(M_PI) / 180)
let textRect = CGRectMake(0, 0, 21, 12)
var textTextContent = NSString(string: "On")
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Left
let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize()), NSForegroundColorAttributeName: titleColor, NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
}
|
mit
|
2180a6e34036146a9995e052b5ee84ad
| 33.810127 | 234 | 0.657818 | 5.238095 | false | false | false | false |
fespinoza/linked-ideas-osx
|
Playground-macOS.playground/Pages/NSTextView - Resetting Attributes.xcplaygroundpage/Contents.swift
|
1
|
1716
|
//: Playground - noun: a place where people can play
import Cocoa
import PlaygroundSupport
/*
# NSTextView + Resetting Attributes experiments
the idea is to check how to reset the NSTextView's attributes i added
A good indication is `NSTextView.typingAttributes`
*/
class BasicDelegate: NSObject, NSTextViewDelegate {
func textDidChange(_ notification: Notification) {
guard let textView = notification.object as? NSTextView else {
return
}
print(textView.attributedString())
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let textView = notification.object as? NSTextView else {
return
}
print("------")
print(textView.textStorage!)
// print(textView.attributedString())
}
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
switch commandSelector {
case #selector(NSTextView.insertNewline(_:)):
print("do something!")
guard let textStorage = textView.textStorage else {
print("no text storage")
return true
}
let defaultAttributes: [NSAttributedStringKey: Any] = [
.foregroundColor: NSColor.black,
.font: NSFont.systemFont(ofSize: 12)
]
let fullRange = NSRange(location: 0, length: textStorage.length)
textView.textStorage?.setAttributes(defaultAttributes, range: fullRange)
default:
print("unhandled \(commandSelector)")
}
return true
}
}
var str = "Hello, playground"
let delegate = BasicDelegate()
let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: 300, height: 150))
textView.string = str
textView.delegate = delegate
PlaygroundPage.current.liveView = textView
|
mit
|
505c61e20cad66ca34b432ba7d27d6c9
| 23.169014 | 88 | 0.695804 | 4.727273 | false | false | false | false |
ta2yak/FontAwesome.swift
|
FontAwesome/Enum.swift
|
1
|
22309
|
// Enum.swift
//
// Copyright (c) 2014-2015 Thi Doan
//
// 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.
public enum FontAwesome: String {
//case 500px = "\u{f26e}"
case Adjust = "\u{f042}"
case ADN = "\u{f170}"
case AlignCenter = "\u{f037}"
case AlignJustify = "\u{f039}"
case AlignLeft = "\u{f036}"
case AlignRight = "\u{f038}"
case Amazon = "\u{f270}"
case Ambulance = "\u{f0f9}"
case Anchor = "\u{f13d}"
case Android = "\u{f17b}"
case Angellist = "\u{f209}"
case AngleDoubleDown = "\u{f103}"
case AngleDoubleLeft = "\u{f100}"
case AngleDoubleRight = "\u{f101}"
case AngleDoubleUp = "\u{f102}"
case AngleDown = "\u{f107}"
case AngleLeft = "\u{f104}"
case AngleRight = "\u{f105}"
case AngleUp = "\u{f106}"
case Apple = "\u{f179}"
case Archive = "\u{f187}"
case AreaChart = "\u{f1fe}"
case ArrowCircleDown = "\u{f0ab}"
case ArrowCircleLeft = "\u{f0a8}"
case ArrowCircleODown = "\u{f01a}"
case ArrowCircleOLeft = "\u{f190}"
case ArrowCircleORight = "\u{f18e}"
case ArrowCircleOUp = "\u{f01b}"
case ArrowCircleRight = "\u{f0a9}"
case ArrowCircleUp = "\u{f0aa}"
case ArrowDown = "\u{f063}"
case ArrowLeft = "\u{f060}"
case ArrowRight = "\u{f061}"
case ArrowUp = "\u{f062}"
case Arrows = "\u{f047}"
case ArrowsAlt = "\u{f0b2}"
case ArrowsH = "\u{f07e}"
case ArrowsV = "\u{f07d}"
case Asterisk = "\u{f069}"
case At = "\u{f1fa}"
case Automobile = "\u{f1b9}"
case Backward = "\u{f04a}"
case BalanceScale = "\u{f24e}"
case Ban = "\u{f05e}"
case Bank = "\u{f19c}"
case BarChart = "\u{f080}"
case BarChartO = "\u{f080}A"
case Barcode = "\u{f02a}"
case Bars = "\u{f0c9}"
case Battery0 = "\u{f244}"
case Battery1 = "\u{f243}"
case Battery2 = "\u{f242}"
case Battery3 = "\u{f241}"
case Battery4 = "\u{f240}"
case BatteryEmpty = "\u{f244}A"
case BatteryFull = "\u{f240}A"
case BatteryHalf = "\u{f242}A"
case BatteryQuarter = "\u{f243}A"
case BatteryThreeQuarters = "\u{f241}A"
case Bed = "\u{f236}"
case Beer = "\u{f0fc}"
case Behance = "\u{f1b4}"
case BehanceSquare = "\u{f1b5}"
case Bell = "\u{f0f3}"
case BellO = "\u{f0a2}"
case BellSlash = "\u{f1f6}"
case BellSlashO = "\u{f1f7}"
case Bicycle = "\u{f206}"
case Binoculars = "\u{f1e5}"
case BirthdayCake = "\u{f1fd}"
case Bitbucket = "\u{f171}"
case BitbucketSquare = "\u{f172}"
case Bitcoin = "\u{f15a}"
case BlackTie = "\u{f27e}"
case Bold = "\u{f032}"
case Bolt = "\u{f0e7}"
case Bomb = "\u{f1e2}"
case Book = "\u{f02d}"
case Bookmark = "\u{f02e}"
case BookmarkO = "\u{f097}"
case Briefcase = "\u{f0b1}"
case BTC = "\u{f15a}A"
case Bug = "\u{f188}"
case Building = "\u{f1ad}"
case BuildingO = "\u{f0f7}"
case Bullhorn = "\u{f0a1}"
case Bullseye = "\u{f140}"
case Bus = "\u{f207}"
case Buysellads = "\u{f20d}"
case Cab = "\u{f1ba}"
case Calculator = "\u{f1ec}"
case Calendar = "\u{f073}"
case CalendarCheckO = "\u{f274}"
case CalendarMinusO = "\u{f272}"
case CalendarO = "\u{f133}"
case CalendarPlusO = "\u{f271}"
case CalendarTimesO = "\u{f273}"
case Camera = "\u{f030}"
case CameraRetro = "\u{f083}"
case Car = "\u{f1b9}A"
case CaretDown = "\u{f0d7}"
case CaretLeft = "\u{f0d9}"
case CaretRight = "\u{f0da}"
case CaretSquareODown = "\u{f150}"
case CaretSquareOLeft = "\u{f191}"
case CaretSquareORight = "\u{f152}"
case CaretSquareOUp = "\u{f151}"
case CaretUp = "\u{f0d8}"
case CartArrowDown = "\u{f218}"
case CartPlus = "\u{f217}"
case CC = "\u{f20a}"
case CCAmex = "\u{f1f3}"
case CCDinersClub = "\u{f24c}"
case CCDiscover = "\u{f1f2}"
case CCJCB = "\u{f24b}"
case CCMasterCard = "\u{f1f1}"
case CCPaypal = "\u{f1f4}"
case CCStripe = "\u{f1f5}"
case CCVisa = "\u{f1f0}"
case Certificate = "\u{f0a3}"
case Chain = "\u{f0c1}"
case ChainBroken = "\u{f127}"
case Check = "\u{f00c}"
case CheckCircle = "\u{f058}"
case CheckCircleO = "\u{f05d}"
case CheckSquare = "\u{f14a}"
case CheckSquareO = "\u{f046}"
case ChevronCircleDown = "\u{f13a}"
case ChevronCircleLeft = "\u{f137}"
case ChevronCircleRight = "\u{f138}"
case ChevronCircleUp = "\u{f139}"
case ChevronDown = "\u{f078}"
case ChevronLeft = "\u{f053}"
case ChevronRight = "\u{f054}"
case ChevronUp = "\u{f077}"
case Child = "\u{f1ae}"
case Chrome = "\u{f268}"
case Circle = "\u{f111}"
case CircleO = "\u{f10c}"
case CircleONotch = "\u{f1ce}"
case CircleThin = "\u{f1db}"
case Clipboard = "\u{f0ea}"
case ClockO = "\u{f017}"
case Clone = "\u{f24d}"
case Close = "\u{f00d}"
case Cloud = "\u{f0c2}"
case CloudDownload = "\u{f0ed}"
case CloudUpload = "\u{f0ee}"
case CNY = "\u{f157}"
case Code = "\u{f121}"
case CodeFork = "\u{f126}"
case Codepen = "\u{f1cb}"
case Coffee = "\u{f0f4}"
case Cog = "\u{f013}"
case Cogs = "\u{f085}"
case Columns = "\u{f0db}"
case Comment = "\u{f075}"
case CommentO = "\u{f0e5}"
case Commenting = "\u{f27a}"
case CommentingO = "\u{f27b}"
case Comments = "\u{f086}"
case CommentsO = "\u{f0e6}"
case Compass = "\u{f14e}"
case Compress = "\u{f066}"
case Connectdevelop = "\u{f20e}"
case Contao = "\u{f26d}"
case Copy = "\u{f0c5}"
case Copyright = "\u{f1f9}"
case CreativeCommons = "\u{f25e}"
case CreditCard = "\u{f09d}"
case Crop = "\u{f125}"
case Crosshairs = "\u{f05b}"
case Css3 = "\u{f13c}"
case Cube = "\u{f1b2}"
case Cubes = "\u{f1b3}"
case Cut = "\u{f0c4}"
case Cutlery = "\u{f0f5}"
case Dashboard = "\u{f0e4}"
case Dashcube = "\u{f210}"
case Database = "\u{f1c0}"
case Dedent = "\u{f03b}"
case Delicious = "\u{f1a5}"
case Desktop = "\u{f108}"
case Deviantart = "\u{f1bd}"
case Diamond = "\u{f219}"
case Digg = "\u{f1a6}"
case Dollar = "\u{f155}"
case DotCircleO = "\u{f192}"
case Download = "\u{f019}"
case Dribbble = "\u{f17d}"
case Dropbox = "\u{f16b}"
case Drupal = "\u{f1a9}"
case Edit = "\u{f044}"
case Eject = "\u{f052}"
case EllipsisH = "\u{f141}"
case EllipsisV = "\u{f142}"
case Empire = "\u{f1d1}"
case Envelope = "\u{f0e0}"
case EnvelopeO = "\u{f003}"
case EnvelopeSquare = "\u{f199}"
case Eraser = "\u{f12d}"
case EUR = "\u{f153}"
case Euro = "\u{f153}A"
case Exchange = "\u{f0ec}"
case Exclamation = "\u{f12a}"
case ExclamationCircle = "\u{f06a}"
case ExclamationTriangle = "\u{f071}"
case Expand = "\u{f065}"
case ExpeditedSSL = "\u{f23e}"
case ExternalLink = "\u{f08e}"
case ExternalLinkSquare = "\u{f14c}"
case Eye = "\u{f06e}"
case EyeSlash = "\u{f070}"
case Eyedropper = "\u{f1fb}"
case Facebook = "\u{f09a}"
case FacebookF = "\u{f09a}A"
case FacebookOfficial = "\u{f230}"
case FacebookSquare = "\u{f082}"
case FastBackward = "\u{f049}"
case FastForward = "\u{f050}"
case Fax = "\u{f1ac}"
case Feed = "\u{f09e}"
case Female = "\u{f182}"
case FighterJet = "\u{f0fb}"
case File = "\u{f15b}"
case FileArchiveO = "\u{f1c6}"
case FileAudioO = "\u{f1c7}"
case FileCodeO = "\u{f1c9}"
case FileExcelO = "\u{f1c3}"
case FileImageO = "\u{f1c5}"
case FileMovieO = "\u{f1c8}"
case FileO = "\u{f016}"
case FilePdfO = "\u{f1c1}"
case FilePhotoO = "\u{f1c5}A"
case FilePictureO = "\u{f1c5}B"
case FilePowerpointO = "\u{f1c4}"
case FileSoundO = "\u{f1c7}A"
case FileText = "\u{f15c}"
case FileTextO = "\u{f0f6}"
case FileVideoO = "\u{f1c8}A"
case FileWordO = "\u{f1c2}"
case FileZipO = "\u{f1c6}A"
case FilesO = "\u{f0c5}A"
case Film = "\u{f008}"
case Filter = "\u{f0b0}"
case Fire = "\u{f06d}"
case FireExtinguisher = "\u{f134}"
case Firefox = "\u{f269}"
case Flag = "\u{f024}"
case FlagCheckered = "\u{f11e}"
case FlagO = "\u{f11d}"
case Flash = "\u{f0e7}A"
case Flask = "\u{f0c3}"
case Flickr = "\u{f16e}"
case FloppyO = "\u{f0c7}"
case Folder = "\u{f07b}"
case FolderO = "\u{f114}"
case FolderOpen = "\u{f07c}"
case FolderOpenO = "\u{f115}"
case Font = "\u{f031}"
case Fonticons = "\u{f280}"
case Forumbee = "\u{f211}"
case Forward = "\u{f04e}"
case Foursquare = "\u{f180}"
case FrownO = "\u{f119}"
case FutbolO = "\u{f1e3}"
case Gamepad = "\u{f11b}"
case Gavel = "\u{f0e3}"
case GBP = "\u{f154}"
case Ge = "\u{f1d1}A"
case Gear = "\u{f013}A"
case Gears = "\u{f085}A"
case Genderless = "\u{f22d}"
case GetPocket = "\u{f265}"
case GG = "\u{f260}"
case GGCircle = "\u{f261}"
case Gift = "\u{f06b}"
case Git = "\u{f1d3}"
case GitSquare = "\u{f1d2}"
case Github = "\u{f09b}"
case GithubAlt = "\u{f113}"
case GithubSquare = "\u{f092}"
case Gittip = "\u{f184}"
case Glass = "\u{f000}"
case Globe = "\u{f0ac}"
case Google = "\u{f1a0}"
case GooglePlus = "\u{f0d5}"
case GooglePlusSquare = "\u{f0d4}"
case GoogleWallet = "\u{f1ee}"
case GraduationCap = "\u{f19d}"
case Gratipay = "\u{f184}A"
case Group = "\u{f0c0}"
case HSquare = "\u{f0fd}"
case HackerNews = "\u{f1d4}"
case HandGrabO = "\u{f255}"
case HandLizardO = "\u{f258}"
case HandODown = "\u{f0a7}"
case HandOLeft = "\u{f0a5}"
case HandORight = "\u{f0a4}"
case HandOUp = "\u{f0a6}"
case HandPaperO = "\u{f256}"
case HandPeaceO = "\u{f25b}"
case HandPointerO = "\u{f25a}"
case HandRockO = "\u{f255}A"
case HandScissorsO = "\u{f257}"
case HandSpockO = "\u{f259}"
case HandStopO = "\u{f256}A"
case HddO = "\u{f0a0}"
case Header = "\u{f1dc}"
case Headphones = "\u{f025}"
case Heart = "\u{f004}"
case HeartO = "\u{f08a}"
case Heartbeat = "\u{f21e}"
case History = "\u{f1da}"
case Home = "\u{f015}"
case HospitalO = "\u{f0f8}"
case Hotel = "\u{f236}A"
case Hourglass = "\u{f254}"
case Hourglass1 = "\u{f251}"
case Hourglass2 = "\u{f252}"
case Hourglass3 = "\u{f253}"
case HourglassEnd = "\u{f253}A"
case HourglassHalf = "\u{f252}A"
case HourglassO = "\u{f250}"
case HourglassStart = "\u{f251}A"
case Houzz = "\u{f27c}"
case Html5 = "\u{f13b}"
case ICursor = "\u{f246}"
case ILS = "\u{f20b}"
case Image = "\u{f03e}"
case Inbox = "\u{f01c}"
case Indent = "\u{f03c}"
case Industry = "\u{f275}"
case Info = "\u{f129}"
case InfoCircle = "\u{f05a}"
case INR = "\u{f156}"
case Instagram = "\u{f16d}"
case Institution = "\u{f19c}A"
case InternetExplorer = "\u{f26b}"
case Intersex = "\u{f224}"
case Ioxhost = "\u{f208}"
case Italic = "\u{f033}"
case Joomla = "\u{f1aa}"
case JPY = "\u{f157}A"
case Jsfiddle = "\u{f1cc}"
case Key = "\u{f084}"
case KeyboardO = "\u{f11c}"
case KRW = "\u{f159}"
case Language = "\u{f1ab}"
case Laptop = "\u{f109}"
case LastFM = "\u{f202}"
case LastFMSquare = "\u{f203}"
case Leaf = "\u{f06c}"
case Leanpub = "\u{f212}"
case Legal = "\u{f0e3}A"
case LemonO = "\u{f094}"
case LevelDown = "\u{f149}"
case LevelUp = "\u{f148}"
case LifeBouy = "\u{f1cd}"
case LifeBuoy = "\u{f1cd}A"
case LifeRing = "\u{f1cd}B"
case LifeSaver = "\u{f1cd}C"
case LightbulbO = "\u{f0eb}"
case LineChart = "\u{f201}"
case Link = "\u{f0c1}A"
case LinkedIn = "\u{f0e1}"
case LinkedInSquare = "\u{f08c}"
case Linux = "\u{f17c}"
case List = "\u{f03a}"
case ListAlt = "\u{f022}"
case ListOL = "\u{f0cb}"
case ListUL = "\u{f0ca}"
case LocationArrow = "\u{f124}"
case Lock = "\u{f023}"
case LongArrowDown = "\u{f175}"
case LongArrowLeft = "\u{f177}"
case LongArrowRight = "\u{f178}"
case LongArrowUp = "\u{f176}"
case Magic = "\u{f0d0}"
case Magnet = "\u{f076}"
case MailForward = "\u{f064}"
case MailReply = "\u{f112}"
case MailReplyAll = "\u{f122}"
case Male = "\u{f183}"
case Map = "\u{f279}"
case MapMarker = "\u{f041}"
case MapO = "\u{f278}"
case MapPin = "\u{f276}"
case MapSigns = "\u{f277}"
case Mars = "\u{f222}"
case MarsDouble = "\u{f227}"
case MarsStroke = "\u{f229}"
case MarsStrokeH = "\u{f22b}"
case MarsStrokeV = "\u{f22a}"
case Maxcdn = "\u{f136}"
case Meanpath = "\u{f20c}"
case Medium = "\u{f23a}"
case Medkit = "\u{f0fa}"
case MehO = "\u{f11a}"
case Mercury = "\u{f223}"
case Microphone = "\u{f130}"
case MicrophoneSlash = "\u{f131}"
case Minus = "\u{f068}"
case MinusCircle = "\u{f056}"
case MinusSquare = "\u{f146}"
case MinusSquareO = "\u{f147}"
case Mobile = "\u{f10b}"
case MobilePhone = "\u{f10b}A"
case Money = "\u{f0d6}"
case MoonO = "\u{f186}"
case MortarBoard = "\u{f19d}A"
case Motorcycle = "\u{f21c}"
case MousePointer = "\u{f245}"
case Music = "\u{f001}"
case Navicon = "\u{f0c9}A"
case Neuter = "\u{f22c}"
case NewspaperO = "\u{f1ea}"
case ObjectGroup = "\u{f247}"
case ObjectUngroup = "\u{f248}"
case Odnoklassniki = "\u{f263}"
case OdnoklassnikiSquare = "\u{f264}"
case OpenCart = "\u{f23d}"
case OpenID = "\u{f19b}"
case Opera = "\u{f26a}"
case OptinMonster = "\u{f23c}"
case Outdent = "\u{f03b}A"
case Pagelines = "\u{f18c}"
case PaintBrush = "\u{f1fc}"
case PaperPlane = "\u{f1d8}"
case PaperPlaneO = "\u{f1d9}"
case Paperclip = "\u{f0c6}"
case Paragraph = "\u{f1dd}"
case Paste = "\u{f0ea}A"
case Pause = "\u{f04c}"
case Paw = "\u{f1b0}"
case Paypal = "\u{f1ed}"
case Pencil = "\u{f040}"
case PencilSquare = "\u{f14b}"
case PencilSquareO = "\u{f044}A"
case Phone = "\u{f095}"
case PhoneSquare = "\u{f098}"
case Photo = "\u{f03e}A"
case PictureO = "\u{f03e}B"
case PieChart = "\u{f200}"
case PiedPiper = "\u{f1a7}"
case PiedPiperAlt = "\u{f1a8}"
case Pinterest = "\u{f0d2}"
case PinterestP = "\u{f231}"
case PinterestSquare = "\u{f0d3}"
case Plane = "\u{f072}"
case Play = "\u{f04b}"
case PlayCircle = "\u{f144}"
case PlayCircleO = "\u{f01d}"
case Plug = "\u{f1e6}"
case Plus = "\u{f067}"
case PlusCircle = "\u{f055}"
case PlusSquare = "\u{f0fe}"
case PlusSquareO = "\u{f196}"
case PowerOff = "\u{f011}"
case Print = "\u{f02f}"
case PuzzlePiece = "\u{f12e}"
case Qq = "\u{f1d6}"
case Qrcode = "\u{f029}"
case Question = "\u{f128}"
case QuestionCircle = "\u{f059}"
case QuoteLeft = "\u{f10d}"
case QuoteRight = "\u{f10e}"
case Ra = "\u{f1d0}"
case Random = "\u{f074}"
case Rebel = "\u{f1d0}A"
case Recycle = "\u{f1b8}"
case Reddit = "\u{f1a1}"
case RedditSquare = "\u{f1a2}"
case Refresh = "\u{f021}"
case Registered = "\u{f25d}"
case Remove = "\u{f00d}A"
case Renren = "\u{f18b}"
case Reorder = "\u{f0c9}B"
case Repeat = "\u{f01e}"
case Reply = "\u{f112}A"
case ReplyAll = "\u{f122}A"
case Retweet = "\u{f079}"
case RMB = "\u{f157}B"
case Road = "\u{f018}"
case Rocket = "\u{f135}"
case RotateLeft = "\u{f0e2}"
case RotateRight = "\u{f01e}A"
case Rouble = "\u{f158}"
case RSS = "\u{f09e}A"
case RSSSquare = "\u{f143}"
case RUB = "\u{f158}A"
case Ruble = "\u{f158}B"
case Rupee = "\u{f156}A"
case Safari = "\u{f267}"
case Save = "\u{f0c7}A"
case Scissors = "\u{f0c4}A"
case Search = "\u{f002}"
case SearchMinus = "\u{f010}"
case SearchPlus = "\u{f00e}"
case Sellsy = "\u{f213}"
case Send = "\u{f1d8}A"
case SendO = "\u{f1d9}A"
case Server = "\u{f233}"
case Share = "\u{f064}A"
case ShareAlt = "\u{f1e0}"
case ShareAltSquare = "\u{f1e1}"
case ShareSquare = "\u{f14d}"
case ShareSquareO = "\u{f045}"
case Shekel = "\u{f20b}A"
case Sheqel = "\u{f20b}B"
case Shield = "\u{f132}"
case Ship = "\u{f21a}"
case Shirtsinbulk = "\u{f214}"
case ShoppingCart = "\u{f07a}"
case SignIn = "\u{f090}"
case SignOut = "\u{f08b}"
case Signal = "\u{f012}"
case Simplybuilt = "\u{f215}"
case Sitemap = "\u{f0e8}"
case Skyatlas = "\u{f216}"
case Skype = "\u{f17e}"
case Slack = "\u{f198}"
case Sliders = "\u{f1de}"
case Slideshare = "\u{f1e7}"
case SmileO = "\u{f118}"
case SoccerBallO = "\u{f1e3}A"
case Sort = "\u{f0dc}"
case SortAlphaAsc = "\u{f15d}"
case SortAlphaDesc = "\u{f15e}"
case SortAmountAsc = "\u{f160}"
case SortAmountDesc = "\u{f161}"
case SortAsc = "\u{f0de}"
case SortDesc = "\u{f0dd}"
case SortDown = "\u{f0dd}A"
case SortNumericAsc = "\u{f162}"
case SortNumericDesc = "\u{f163}"
case SortUp = "\u{f0de}A"
case SoundCloud = "\u{f1be}"
case SpaceShuttle = "\u{f197}"
case Spinner = "\u{f110}"
case Spoon = "\u{f1b1}"
case Spotify = "\u{f1bc}"
case Square = "\u{f0c8}"
case SquareO = "\u{f096}"
case StackExchange = "\u{f18d}"
case StackOverflow = "\u{f16c}"
case Star = "\u{f005}"
case StarHalf = "\u{f089}"
case StarHalfEmpty = "\u{f123}"
case StarHalfFull = "\u{f123}A"
case StarHalfO = "\u{f123}B"
case StarO = "\u{f006}"
case Steam = "\u{f1b6}"
case SteamSquare = "\u{f1b7}"
case StepBackward = "\u{f048}"
case StepForward = "\u{f051}"
case Stethoscope = "\u{f0f1}"
case StickyNote = "\u{f249}"
case StickyNoteO = "\u{f24a}"
case Stop = "\u{f04d}"
case StreetView = "\u{f21d}"
case Strikethrough = "\u{f0cc}"
case StumbleUpon = "\u{f1a4}"
case StumbleUponCircle = "\u{f1a3}"
case Subscript = "\u{f12c}"
case Subway = "\u{f239}"
case Suitcase = "\u{f0f2}"
case SunO = "\u{f185}"
case Superscript = "\u{f12b}"
case Support = "\u{f1cd}D"
case Table = "\u{f0ce}"
case Tablet = "\u{f10a}"
case Tachometer = "\u{f0e4}A"
case Tag = "\u{f02b}"
case Tags = "\u{f02c}"
case Tasks = "\u{f0ae}"
case Taxi = "\u{f1ba}A"
case Television = "\u{f26c}"
case TencentWeibo = "\u{f1d5}"
case Terminal = "\u{f120}"
case TextHeight = "\u{f034}"
case TextWidth = "\u{f035}"
case Th = "\u{f00a}"
case ThLarge = "\u{f009}"
case ThList = "\u{f00b}"
case ThumbTack = "\u{f08d}"
case ThumbsDown = "\u{f165}"
case ThumbsODown = "\u{f088}"
case ThumbsOUp = "\u{f087}"
case ThumbsUp = "\u{f164}"
case Ticket = "\u{f145}"
case Times = "\u{f00d}B"
case TimesCircle = "\u{f057}"
case TimesCircleO = "\u{f05c}"
case Tint = "\u{f043}"
case ToggleDown = "\u{f150}A"
case ToggleLeft = "\u{f191}A"
case ToggleOff = "\u{f204}"
case ToggleOn = "\u{f205}"
case ToggleRight = "\u{f152}A"
case ToggleUp = "\u{f151}A"
case Trademark = "\u{f25c}"
case Train = "\u{f238}"
case Transgender = "\u{f224}A"
case TransgenderAlt = "\u{f225}"
case Trash = "\u{f1f8}"
case TrashO = "\u{f014}"
case Tree = "\u{f1bb}"
case Trello = "\u{f181}"
case TripAdvisor = "\u{f262}"
case Trophy = "\u{f091}"
case Truck = "\u{f0d1}"
case TRY = "\u{f195}"
case TTY = "\u{f1e4}"
case Tumblr = "\u{f173}"
case TumblrSquare = "\u{f174}"
case TurkishLira = "\u{f195}A"
case Tv = "\u{f26c}A"
case Twitch = "\u{f1e8}"
case Twitter = "\u{f099}"
case TwitterSquare = "\u{f081}"
case Umbrella = "\u{f0e9}"
case Underline = "\u{f0cd}"
case Undo = "\u{f0e2}A"
case University = "\u{f19c}B"
case Unlink = "\u{f127}A"
case Unlock = "\u{f09c}"
case UnlockAlt = "\u{f13e}"
case Unsorted = "\u{f0dc}A"
case Upload = "\u{f093}"
case USD = "\u{f155}A"
case User = "\u{f007}"
case UserMd = "\u{f0f0}"
case UserPlus = "\u{f234}"
case UserSecret = "\u{f21b}"
case UserTimes = "\u{f235}"
case Users = "\u{f0c0}A"
case Venus = "\u{f221}"
case VenusDouble = "\u{f226}"
case VenusMars = "\u{f228}"
case Viacoin = "\u{f237}"
case VideoCamera = "\u{f03d}"
case Vimeo = "\u{f27d}"
case VimeoSquare = "\u{f194}"
case Vine = "\u{f1ca}"
case Vk = "\u{f189}"
case VolumeDown = "\u{f027}"
case VolumeOff = "\u{f026}"
case VolumeUp = "\u{f028}"
case Warning = "\u{f071}A"
case Wechat = "\u{f1d7}"
case Weibo = "\u{f18a}"
case Weixin = "\u{f1d7}A"
case Whatsapp = "\u{f232}"
case Wheelchair = "\u{f193}"
case Wifi = "\u{f1eb}"
case WikipediaW = "\u{f266}"
case Windows = "\u{f17a}"
case Won = "\u{f159}A"
case Wordpress = "\u{f19a}"
case Wrench = "\u{f0ad}"
case Xing = "\u{f168}"
case XingSquare = "\u{f169}"
case YCombinator = "\u{f23b}"
case YCombinatorSquare = "\u{f1d4}A"
case Yahoo = "\u{f19e}"
case YC = "\u{f23b}A"
case YCSquare = "\u{f1d4}B"
case Yelp = "\u{f1e9}"
case Yen = "\u{f157}C"
case YouTube = "\u{f167}"
case YouTubePlay = "\u{f16a}"
case YouTubeSquare = "\u{f166}"
}
|
mit
|
c8872f1fdc59376564d330d6b8bf1af0
| 30.961318 | 80 | 0.564481 | 2.67976 | false | false | false | false |
donileo/RMessage
|
Sources/RMessage/Extensions/RMessage+Design.swift
|
1
|
4897
|
//
// RMessage+Design.swift
//
// Created by Adonis Peralta on 8/6/18.
// Copyright © 2018 None. All rights reserved.
//
import Foundation
import UIKit
extension RMessage {
func setupDesign(withMessageSpec spec: RMessageSpec, titleLabel: UILabel, bodyLabel: UILabel) {
setupDesign(messageSpec: spec)
setupDesign(forTitleLabel: titleLabel, messageSpec: spec)
setupDesign(forBodyLabel: bodyLabel, messageSpec: spec)
if let titleAttributes = spec.titleAttributes {
setup(attributedTitleLabel: titleLabel, withAttributes: titleAttributes)
}
if let bodyAttributes = spec.bodyAttributes {
setup(attributedTitleLabel: bodyLabel, withAttributes: bodyAttributes)
}
if spec.titleBodyLabelsSizeToFit { setupLabelConstraintsToSizeToFit() }
}
private func setupDesign(messageSpec spec: RMessageSpec) {
if spec.cornerRadius > 0 { clipsToBounds = true }
backgroundColor = spec.backgroundColor
}
private func setupDesign(forTitleLabel titleLabel: UILabel, messageSpec spec: RMessageSpec) {
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
titleLabel.textAlignment = .left
titleLabel.textColor = .black
titleLabel.shadowColor = nil
titleLabel.shadowOffset = CGSize.zero
titleLabel.backgroundColor = nil
titleLabel.font = spec.titleFont
titleLabel.textAlignment = spec.titleTextAlignment
titleLabel.textColor = spec.titleColor
titleLabel.shadowColor = spec.titleShadowColor
titleLabel.shadowOffset = spec.titleShadowOffset
}
private func setupDesign(forBodyLabel bodyLabel: UILabel, messageSpec spec: RMessageSpec) {
bodyLabel.numberOfLines = 0
bodyLabel.lineBreakMode = .byWordWrapping
bodyLabel.font = UIFont.boldSystemFont(ofSize: 12)
bodyLabel.textAlignment = .left
bodyLabel.textColor = .darkGray
bodyLabel.shadowColor = nil
bodyLabel.shadowOffset = CGSize.zero
bodyLabel.backgroundColor = nil
bodyLabel.font = spec.bodyFont
bodyLabel.textAlignment = spec.bodyTextAlignment
bodyLabel.textColor = spec.bodyColor
bodyLabel.shadowColor = spec.bodyShadowColor
bodyLabel.shadowOffset = spec.bodyShadowOffset
}
private func setup(attributedTitleLabel titleLabel: UILabel, withAttributes attrs: [NSAttributedStringKey: Any]) {
guard let titleText = titleLabel.text else { return }
let titleAttributedText = NSAttributedString(string: titleText, attributes: attrs)
titleLabel.attributedText = titleAttributedText
}
private func setup(attributedBodyLabel bodyLabel: UILabel, withAttributes attrs: [NSAttributedStringKey: Any]) {
guard let bodyText = bodyLabel.text else { return }
let bodyAttributedText = NSAttributedString(string: bodyText, attributes: attrs)
bodyLabel.attributedText = bodyAttributedText
}
func setPreferredLayoutWidth(forTitleLabel titleLabel: UILabel,
bodyLabel: UILabel,
inSuperview superview: UIView,
sizingToFit: Bool) {
var accessoryViewsAndPadding: CGFloat = 0
if let leftView = leftView { accessoryViewsAndPadding = leftView.bounds.size.width + 15 }
if let rightView = rightView { accessoryViewsAndPadding += rightView.bounds.size.width + 15 }
var preferredLayoutWidth = CGFloat(superview.bounds.size.width - accessoryViewsAndPadding - 30)
// Always set the preferredLayoutWidth before exit. Note that titleBodyLabelsSizeToFit changes
// preferredLayoutWidth further down below if it is true
defer {
titleLabel.preferredMaxLayoutWidth = preferredLayoutWidth
bodyLabel.preferredMaxLayoutWidth = preferredLayoutWidth
}
guard sizingToFit else { return }
// Get the biggest occupied width of the two strings, set the max preferred layout width to that of the longest label
let titleOneLineSize: CGSize
let bodyOneLineSize: CGSize
if let titleAttributedText = titleLabel.attributedText {
titleOneLineSize = titleAttributedText.size()
} else if let titleText = titleLabel.text {
titleOneLineSize = titleText.size(withAttributes: [.font: titleLabel.font])
} else {
titleOneLineSize = .zero
}
if let bodyAttributedText = bodyLabel.attributedText {
bodyOneLineSize = bodyAttributedText.size()
} else if let bodyText = bodyLabel.text {
bodyOneLineSize = bodyText.size(withAttributes: [.font: bodyLabel.font])
} else {
bodyOneLineSize = .zero
}
guard titleOneLineSize != .zero, bodyOneLineSize != .zero else { return }
let maxOccupiedLineWidth =
(titleOneLineSize.width > bodyOneLineSize.width) ? titleOneLineSize.width : bodyOneLineSize.width
if maxOccupiedLineWidth < preferredLayoutWidth {
preferredLayoutWidth = maxOccupiedLineWidth
}
}
}
|
mit
|
d64ebe22205392f97b3fbbcaf0f0970a
| 37.25 | 121 | 0.737745 | 5.016393 | false | false | false | false |
haawa799/WaniKani-iOS
|
WaniKani/Model/ReviewItem.swift
|
1
|
4851
|
//
// ReviewItem.swift
// WaniKani
//
// Created by Andriy K. on 11/3/15.
// Copyright © 2015 Andriy K. All rights reserved.
//
import RealmSwift
import Realm
import WaniKit
public enum ReviewItemType {
case Radical
case Kanji
case Vocabulary
public var toString: String {
return "\(self)".lowercaseString
}
public init(string: String) {
if string == ReviewItemType.Radical.toString {self = .Radical}
else if string == ReviewItemType.Kanji.toString {self = .Kanji}
else {self = .Vocabulary}
}
}
public protocol ItemColor {
func backgroundColor() -> UIColor?
}
//====================================================================
// MARK - ReviewItem
//====================================================================
public class ReviewItem: Object {
// Dictionary keys
private static let keyCharacter = "character"
private static let keyMeaning = "meaning"
private static let keyLevel = "level"
private static let keyUnlockedDate = "unlocked_date"
private static let keyPercentage = "percentage"
// Fields
public dynamic var character: String = ""
public dynamic var meaning: String = ""
public dynamic var level: Int = 0
public dynamic var unlockedDate: Int = 0
public dynamic var percentage: String = ""
required public init(dict: NSDictionary) {
super.init()
self.character = (dict[ReviewItem.keyCharacter] as? String) ?? ""
self.meaning = (dict[ReviewItem.keyMeaning] as? String) ?? ""
self.level = (dict[ReviewItem.keyLevel] as? Int) ?? 0
self.unlockedDate = (dict[ReviewItem.keyUnlockedDate] as? Int) ?? 0
self.percentage = (dict[ReviewItem.keyPercentage] as? String) ?? ""
}
required public init() {
super.init()
}
override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
extension ReviewItem: ItemColor {
public func backgroundColor() -> UIColor? {
return nil
}
}
//====================================================================
// MARK - RadicalItem
//====================================================================
public class RadicalItem: ReviewItem {
// Dictionary keys
private static let keyImage = "image"
// Fields
public dynamic var imageURL: String = ""
required public init(dict: NSDictionary) {
super.init(dict: dict)
self.imageURL = (dict[RadicalItem.keyImage] as? String) ?? ""
}
required public init() {
super.init(dict: NSDictionary())
}
override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
extension RadicalItem {
public override func backgroundColor() -> UIColor? {
return UIColor(red:0.23, green:0.7, blue:0.96, alpha:1)
}
}
//====================================================================
// MARK - RadicalItem
//====================================================================
public class KanjiItem: ReviewItem {
// Dictionary keys
private static let keyOnyomi = "onyomi"
private static let keyKunyomi = "kunyomi"
private static let keyNanori = "nanori"
private static let keyImportantReading = "important_reading"
// Fields
public dynamic var onyomi: String = ""
public dynamic var kunyomi: String = ""
public dynamic var nanori: String = ""
public dynamic var importantReading: String = ""
required public init(dict: NSDictionary) {
super.init(dict: dict)
self.onyomi = (dict[KanjiItem.keyOnyomi] as? String) ?? ""
self.kunyomi = (dict[KanjiItem.keyKunyomi] as? String) ?? ""
self.nanori = (dict[KanjiItem.keyNanori] as? String) ?? ""
self.importantReading = (dict[KanjiItem.keyImportantReading] as? String) ?? ""
}
required public init() {
super.init(dict: NSDictionary())
}
override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
extension KanjiItem {
public override func backgroundColor() -> UIColor? {
return UIColor(red:0.95, green:0, blue:0.63, alpha:1)
}
}
//====================================================================
// MARK - VocabItem
//====================================================================
public class VocabItem: ReviewItem {
// Dictionary keys
private static let keyKana = "kana"
// Fields
public dynamic var kana: String = ""
required public init(dict: NSDictionary) {
super.init(dict: dict)
self.kana = (dict[VocabItem.keyKana] as? String) ?? ""
}
required public init() {
super.init(dict: NSDictionary())
}
override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
extension VocabItem {
public override func backgroundColor() -> UIColor? {
return UIColor(red:0.63, green:0, blue:0.95, alpha:1)
}
}
|
gpl-3.0
|
6b537b4e46008acac8250a46bce29ca2
| 25.648352 | 82 | 0.59567 | 4.152397 | false | false | false | false |
calebkleveter/BluetoothKit
|
Source/BKConnectionAttempt.swift
|
3
|
1985
|
//
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// 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
internal func == (lhs: BKConnectionAttempt, rhs: BKConnectionAttempt) -> Bool {
return (lhs.remotePeripheral.identifier == rhs.remotePeripheral.identifier)
}
internal class BKConnectionAttempt: Equatable {
// MARK: Properties
internal let timer: Timer
internal let remotePeripheral: BKRemotePeripheral
internal let completionHandler: ((_ peripheralEntity: BKRemotePeripheral, _ error: BKConnectionPool.BKError?) -> Void)
// MARK: Initialization
internal init(remotePeripheral: BKRemotePeripheral, timer: Timer, completionHandler: @escaping ((BKRemotePeripheral, BKConnectionPool.BKError?) -> Void)) {
self.remotePeripheral = remotePeripheral
self.timer = timer
self.completionHandler = completionHandler
}
}
|
mit
|
c35322cc2bce28b8259c53e33167ba29
| 42.152174 | 159 | 0.748111 | 4.594907 | false | false | false | false |
tatsuyamoriguchi/PoliPoli
|
View Controller/GoalDoneViewController.swift
|
1
|
2432
|
//
// GoalDoneViewController.swift
// Poli
//
// Created by Tatsuya Moriguchi on 8/8/18.
// Copyright © 2018 Becko's Inc. All rights reserved.
//
import UIKit
import CoreData
class GoalDoneViewController: UIViewController {
var goal: Goal!
var goalDone: Bool!
var userName: String = ""
@IBOutlet weak var goalTitleLabel: UILabel!
@IBOutlet weak var goalDoneSwitch: UISwitch!
@IBAction func cancelButton(_ sender: UIButton) {
navigationController!.popToRootViewController(animated: true)
}
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
if userName != "" {
let NSL_naviPrompt = String(format:NSLocalizedString("NSL_naviPormpt", value: "Login as %@", comment: ""), userName)
self.navigationItem.prompt = NSL_naviPrompt
} else {
let NSL_naviMissing = NSLocalizedString("NSL_naviMissing", value: "Login info is missing!", comment: "")
self.navigationItem.prompt = NSL_naviMissing
}
goalTitleLabel.text = goal.goalTitle
goalDoneSwitch.isOn = goal.goalDone
let undoneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(undoneGoal))
self.navigationItem.rightBarButtonItem = undoneButton
// Do any additional setup after loading the view.
}
@objc func undoneGoal() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
goal.goalDone = goalDoneSwitch.isOn
do {
try context.save()
}catch{
print("Saving Error: \(error.localizedDescription)")
}
//navigationController!.popToRootViewController(animated: true)
performSegue(withIdentifier: "toGoalList", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toGoalList" {
let destVC = segue.destination as! GoalTableViewController
destVC.userName = userName
}
}
}
|
gpl-3.0
|
847b9b194b5f1707fbc2936c151abb2d
| 30.166667 | 128 | 0.649116 | 4.941057 | false | false | false | false |
NewBeeInc/NBFramework
|
UI/LibzBarCustom/NBQRCodeScanViewController.swift
|
1
|
1674
|
//
// NBQRCodeScanViewController.swift
// xiuxiu
//
// Created by Ke Yang on 6/28/16.
// Copyright © 2016 com.sangebaba. All rights reserved.
//
import UIKit
import KEYExtension
@objc public enum NBQRCodeScanViewControllerStyle: Int {
case fullScreen, custom
}
open class NBQRCodeScanViewController: ZBarReaderViewController {
fileprivate var style: NBQRCodeScanViewControllerStyle = .fullScreen
convenience init(style: NBQRCodeScanViewControllerStyle) {
self.init()
self.style = style
self.showsZBarControls = false
switch style {
case .fullScreen:
break
case .custom:
self.cameraOverlayView = ZBarPickerOverlayView(frame: UIScreen.main.bounds)
break
}
}
override open func viewDidLoad() {
super.viewDidLoad()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
switch self.style {
case .custom:
(self.cameraOverlayView as! ZBarPickerOverlayView).playScanAnim()
default:
break
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
switch self.style {
case .custom:
(self.cameraOverlayView as! ZBarPickerOverlayView).stopScanAnim()
default:
break
}
}
open class func extractResult(_ info: [String : AnyObject]) -> String? {
guard let results = info[ZBarReaderControllerResults] as? ZBarSymbolSet
else { return nil }
var symbolFound : ZBarSymbol?
for symbol in results {
symbolFound = symbol as? ZBarSymbol
break
}
return symbolFound?.data
}
}
extension ZBarSymbolSet: Sequence {
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
|
mit
|
6bf24d965191e5df5d9447b1be447b36
| 21.608108 | 78 | 0.735804 | 3.685022 | false | false | false | false |
TurfDb/Turf
|
Turf/SQLiteAdapter/SQLiteType.swift
|
1
|
4827
|
public protocol SQLiteType {
static var sqliteTypeName: SQLiteTypeName { get }
static var isNullable: Bool { get }
/**
Extract the type from a (sqlite3_stmt *).
- parameter stmt: sqlite3_stmt.
- parameter columnIndex: Index of the column to be extracted.
*/
init?(stmt: OpaquePointer, columnIndex: Int32)
/**
Bind the type to a sqlite3_stmt.
TODO: Remove `@discardableResult`.
- parameter stmt: sqlite3_stmt.
- parameter index: Index of the column to bind to.
*/
@discardableResult
func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32
func sqliteValue() -> SQLiteType
}
extension SQLiteType {
public var sqliteTypeName: SQLiteTypeName { return Self.sqliteTypeName }
public static var isNullable: Bool { return false }
}
extension Int: SQLiteType {
public static var sqliteTypeName: SQLiteTypeName {
return .Integer
}
public init?(stmt: OpaquePointer, columnIndex: Int32) {
self = Int(sqlite3_column_int64(stmt, columnIndex))
}
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
return sqlite3_bind_int64(stmt, index, Int64(self))
}
public func sqliteValue() -> SQLiteType {
return self
}
}
extension String: SQLiteType {
public static var sqliteTypeName: SQLiteTypeName {
return .Text
}
public init?(stmt: OpaquePointer, columnIndex: Int32) {
if let text = String(validatingUTF8: sqlite3_column_text(stmt, columnIndex)!) {
self = text
} else {
return nil
}
}
/// TODO: Remove `@discardableResult`.
@discardableResult
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
return sqlite3_bind_text(stmt, index, self, -1, SQLITE_TRANSIENT)
}
public func sqliteValue() -> SQLiteType {
return "`\(self)`"
}
public init?(validatingUTF8 cString: UnsafePointer<UInt8>) {
guard let (s, _) = String.decodeCString(cString, as: UTF8.self,
repairingInvalidCodeUnits: false) else {
return nil
}
self = s
}
}
extension Bool: SQLiteType {
public static var sqliteTypeName: SQLiteTypeName {
return .Integer
}
public init?(stmt: OpaquePointer, columnIndex: Int32) {
self = sqlite3_column_int64(stmt, columnIndex) != 0
}
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
return sqlite3_bind_int64(stmt, index, self ? 1 : 0)
}
public func sqliteValue() -> SQLiteType {
return self ? 1 : 0
}
}
extension Double: SQLiteType {
public static var sqliteTypeName: SQLiteTypeName {
return .Real
}
public init?(stmt: OpaquePointer, columnIndex: Int32) {
self = sqlite3_column_double(stmt, columnIndex)
}
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
return sqlite3_bind_double(stmt, index, self)
}
public func sqliteValue() -> SQLiteType {
return self
}
}
extension Float: SQLiteType {
public static var sqliteTypeName: SQLiteTypeName {
return .Real
}
public init?(stmt: OpaquePointer, columnIndex: Int32) {
self = Float(sqlite3_column_double(stmt, columnIndex))
}
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
return sqlite3_bind_double(stmt, index, Double(self))
}
public func sqliteValue() -> SQLiteType {
return self
}
}
public protocol TurfSQLiteOptional {
associatedtype _Wrapped: SQLiteType
}
public enum SQLiteOptional<Wrapped: SQLiteType>: SQLiteType, TurfSQLiteOptional {
public typealias _Wrapped = Wrapped
case some(Wrapped)
case none
public static var sqliteTypeName: SQLiteTypeName {
return Wrapped.sqliteTypeName
}
public static var isNullable: Bool { return true }
public init?(stmt: OpaquePointer, columnIndex: Int32) {
if let wrapped = Wrapped(stmt: stmt, columnIndex: columnIndex) {
self = .some(wrapped)
} else {
self = .none
}
}
public func sqliteBind(_ stmt: OpaquePointer, index: Int32) -> Int32 {
switch self {
case .some(let value):
return value.sqliteBind(stmt, index: index)
case .none:
return sqlite3_bind_null(stmt, index)
}
}
public func sqliteValue() -> SQLiteType {
return self
}
}
extension Optional where Wrapped: SQLiteType {
public func toSQLite() -> SQLiteOptional<Wrapped> {
switch self {
case .some(let wrapped): return .some(wrapped)
case .none: return .none
}
}
}
|
mit
|
fc808c3d808d5da713d8b2918d628704
| 25.816667 | 88 | 0.621711 | 4.340827 | false | false | false | false |
dabainihao/MapProject
|
MapProject/MapProject/LO_LoginController.swift
|
1
|
5209
|
//
// LO_Login.swift
// MapProject
//
// Created by 杨少锋 on 16/4/18.
// Copyright © 2016年 杨少锋. All rights reserved.
// 登陆界面
import UIKit
class LO_LoginController: UIViewController,UIAlertViewDelegate {
weak var userNameTextField : UITextField?
weak var passWorldTextField : UITextField?
weak var loginButton : UIButton?
weak var registButton : UIButton?
weak var forgetButton : UIButton?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "登陆"
self.view.backgroundColor = UIColor.whiteColor()
self.navigationController?.navigationBar.translucent = true;
// 设置返回按钮
let barButton : UIBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backAction")
self.navigationItem.leftBarButtonItem = barButton
NSNotificationCenter.defaultCenter().addObserver(self, selector: "usrNameChang", name: UITextFieldTextDidChangeNotification, object: nil)
let userName = UITextField(frame: CGRectMake(30,90 , self.view.bounds.size.width - 60, 40))
userName.placeholder = "请输入电话,邮箱或者用户名"
self.view .addSubview(userName)
userName.layer.borderColor = UIColor.grayColor().CGColor
userName.layer.borderWidth = 1;
userName.clearButtonMode = UITextFieldViewMode.WhileEditing
self.userNameTextField = userName
let passWorld = UITextField(frame: CGRectMake(30 , 140 , self.view.bounds.size.width - 60, 40))
passWorld.placeholder = "请输入密码"
self.view .addSubview(passWorld)
passWorld.layer.borderColor = UIColor.grayColor().CGColor
passWorld.layer.borderWidth = 1;
passWorld.clearButtonMode = UITextFieldViewMode.WhileEditing
passWorld.secureTextEntry = true
self.passWorldTextField = passWorld
let loginButton = UIButton(type: UIButtonType.System)
loginButton.frame = CGRectMake(30, 190, self.view.bounds.size.width - 60, 40)
loginButton.setTitle("登陆", forState: UIControlState.Normal)
loginButton.addTarget(self, action: "loginAction", forControlEvents: UIControlEvents.TouchUpInside)
loginButton .setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
loginButton.backgroundColor = UIColor.grayColor()
loginButton.enabled = false
self.view.addSubview(loginButton)
self.loginButton = loginButton
let registButton = UIButton(type: UIButtonType.System)
registButton.frame = CGRectMake(30, 240, 80, 40)
registButton.setTitle("注册", forState: UIControlState.Normal)
registButton.addTarget(self, action: "registAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view .addSubview(registButton)
registButton.titleLabel?.font = UIFont.systemFontOfSize(10)
self.registButton = registButton
let forgetButton = UIButton(type: UIButtonType.System)
forgetButton.frame = CGRectMake(260, 240, 80, 40)
forgetButton.titleLabel?.font = UIFont.systemFontOfSize(10)
forgetButton.setTitle("忘记密码", forState: UIControlState.Normal)
forgetButton.addTarget(self, action: "forgetButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view .addSubview(forgetButton)
self.forgetButton = forgetButton
}
func usrNameChang() {
if self.userNameTextField?.text != "" && self.passWorldTextField?.text != "" {
self.loginButton?.enabled = true
self.loginButton?.backgroundColor = UIColor.brownColor()
} else {
self.loginButton?.enabled = false
self.loginButton?.backgroundColor = UIColor.grayColor()
}
}
// 登陆
func loginAction() {
LO_loginHelper().loginWithInformation((self.userNameTextField?.text)!, passWorld: (self.passWorldTextField?.text)!, success: { (user) -> Void in
// print(user?.mobilePhoneNumber)
let alterView = UIAlertView(title: "温馨提示", message: "登录成功", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
alterView .show()
}) { (err) -> Void in
print(err)
let alterView = UIAlertView(title: "温馨提示", message: "登陆失败", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定")
alterView .show()
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
// 注册
func registAction() {
self.navigationController?.pushViewController(LO_RegistViewController(), animated: true)
}
// 忘记密码
func forgetButtonAction() {
self.navigationController?.pushViewController(LO_ForgetPassWorldViewController(), animated: true)
}
// 返回
func backAction() {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
}
|
apache-2.0
|
a94ba64406d0a8699b8f72b557de3bb8
| 43.672566 | 152 | 0.676704 | 4.816794 | false | false | false | false |
shaun-h/theplayer
|
theplayer/ipodLibraryAccess.swift
|
1
|
4975
|
//
// ipodLibrary.swift
// theplayer
//
// Created by Shaun Hevey on 17/11/2014.
// Copyright (c) 2014 Shaun Hevey. All rights reserved.
//
import Foundation
import MediaPlayer
public class ipodLibraryAccess {
func convertMPMediaItemToDictionary(media :MPMediaItem) -> Dictionary<String, String> {
var dict = Dictionary<String, String>()
if((media.title) != nil)
{
dict["Title"] = media.title
}
if((media.assetURL) != nil)
{
dict["URL"] = media.assetURL.absoluteString
}
return dict
}
func getIpodLibraryDictionary() -> Array<Dictionary<String,String>> {
var arr = Array<Dictionary<String,String>>()
var mediaQuery = MPMediaQuery()
for media in mediaQuery.items
{
arr.append(convertMPMediaItemToDictionary(media as MPMediaItem))
}
return arr
}
func getIpodLibrary() -> Array<MPMediaItem> {
var arr = Array<MPMediaItem>()
var mediaQuery = MPMediaQuery()
for media in mediaQuery.items
{
if(media.mediaType == MPMediaType.Music)
{
arr.append(media as MPMediaItem)
}
}
return arr
}
func getIpodLibraryAlbums() -> Array<MPMediaItem> {
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.albumsQuery()
for media in mediaQuery.collections
{
arr.append(media.representativeItem)
}
arr = sorted(arr){s1, s2 in s1.albumTitle < s2.albumTitle}
return arr
}
func getIpodLibraryArtists() -> Array<MPMediaItem> {
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.artistsQuery()
for media in mediaQuery.collections
{
arr.append(media.representativeItem)
}
return arr
}
func getIpodLibraryAlbumArtists() -> Array<MPMediaItem> {
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.albumsQuery()
for media1 in mediaQuery.collections
{
var media :MPMediaItem = media1.representativeItem as MPMediaItem
if(media.albumArtist? != nil)
{
var found = false
var add = true
for m in arr
{
if(m.albumArtist == media.albumArtist)
{
found = true
}
}
if(!found)
{
println(media.albumArtist)
arr.append(media1.representativeItem)
}
}
}
arr = sorted(arr){s1, s2 in s1.albumArtist < s2.albumArtist}
return arr
}
func getAlbumListFromArtist(media : MPMediaItem) -> Array<MPMediaItem> {
var artistPredicate: MPMediaPropertyPredicate = MPMediaPropertyPredicate(value:media.albumArtist , forProperty: MPMediaItemPropertyAlbumArtist, comparisonType: MPMediaPredicateComparison.EqualTo)
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.albumsQuery()
mediaQuery.addFilterPredicate(artistPredicate)
for media in mediaQuery.items
{
var found = false
for m in arr
{
if(m.albumTitle == media.albumTitle)
{
found = true
}
}
if(!found)
{
arr.append(media as MPMediaItem)
}
}
arr = sorted(arr){s1, s2 in s1.albumTitle < s2.albumTitle}
return arr
}
func getListFromAlbum(media : MPMediaItem) -> Array<MPMediaItem> {
var albumPredicate: MPMediaPropertyPredicate = MPMediaPropertyPredicate(value:media.albumTitle , forProperty: MPMediaItemPropertyAlbumTitle, comparisonType: MPMediaPredicateComparison.EqualTo)
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.songsQuery()
mediaQuery.addFilterPredicate(albumPredicate)
for media in mediaQuery.items
{
arr.append(media as MPMediaItem)
}
arr = sorted(arr){s1, s2 in s1.discNumber < s2.discNumber && s1.albumTrackNumber < s2.albumTrackNumber}
return arr
}
func getListOfAllSongs() -> Array<MPMediaItem> {
var arr = Array<MPMediaItem>()
var mediaQuery : MPMediaQuery = MPMediaQuery.songsQuery()
for media in mediaQuery.items
{
arr.append(media as MPMediaItem)
}
arr = sorted(arr){s1, s2 in s1.title < s2.title}
return arr
}
}
|
mit
|
1fc5f8b8fc15064b201facc97e5c2ccc
| 28.443787 | 203 | 0.550553 | 4.697828 | false | false | false | false |
kitasuke/SwiftProtobufSample
|
Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/JSONDecoder.swift
|
1
|
19883
|
// Sources/SwiftProtobuf/JSONDecoder.swift - JSON format decoding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
internal struct JSONDecoder: Decoder {
internal var scanner: JSONScanner
private var fieldCount = 0
private var isMapKey = false
private var fieldNameMap: _NameMap?
mutating func handleConflictingOneOf() throws {
throw JSONDecodingError.conflictingOneOf
}
internal init(source: UnsafeBufferPointer<UInt8>) {
self.scanner = JSONScanner(source: source)
}
private init(scanner: JSONScanner) {
self.scanner = scanner
}
mutating func nextFieldNumber() throws -> Int? {
if scanner.skipOptionalObjectEnd() {
return nil
}
if fieldCount > 0 {
try scanner.skipRequiredComma()
}
if let fieldNumber = try scanner.nextFieldNumber(names: fieldNameMap!) {
fieldCount += 1
return fieldNumber
}
return nil
}
mutating func decodeSingularFloatField(value: inout Float) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextFloat()
}
mutating func decodeSingularFloatField(value: inout Float?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextFloat()
}
mutating func decodeRepeatedFloatField(value: inout [Float]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextFloat()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularDoubleField(value: inout Double) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextDouble()
}
mutating func decodeSingularDoubleField(value: inout Double?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextDouble()
}
mutating func decodeRepeatedDoubleField(value: inout [Double]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextDouble()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularInt32Field(value: inout Int32) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value = Int32(truncatingBitPattern: n)
}
mutating func decodeSingularInt32Field(value: inout Int32?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value = Int32(truncatingBitPattern: n)
}
mutating func decodeRepeatedInt32Field(value: inout [Int32]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value.append(Int32(truncatingBitPattern: n))
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularInt64Field(value: inout Int64) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextSInt()
}
mutating func decodeSingularInt64Field(value: inout Int64?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextSInt()
}
mutating func decodeRepeatedInt64Field(value: inout [Int64]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextSInt()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularUInt32Field(value: inout UInt32) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value = UInt32(truncatingBitPattern: n)
}
mutating func decodeSingularUInt32Field(value: inout UInt32?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value = UInt32(truncatingBitPattern: n)
}
mutating func decodeRepeatedUInt32Field(value: inout [UInt32]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value.append(UInt32(truncatingBitPattern: n))
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularUInt64Field(value: inout UInt64) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextUInt()
}
mutating func decodeSingularUInt64Field(value: inout UInt64?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextUInt()
}
mutating func decodeRepeatedUInt64Field(value: inout [UInt64]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextUInt()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularSInt32Field(value: inout Int32) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeSingularSInt32Field(value: inout Int32?) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeRepeatedSInt32Field(value: inout [Int32]) throws {
try decodeRepeatedInt32Field(value: &value)
}
mutating func decodeSingularSInt64Field(value: inout Int64) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeSingularSInt64Field(value: inout Int64?) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeRepeatedSInt64Field(value: inout [Int64]) throws {
try decodeRepeatedInt64Field(value: &value)
}
mutating func decodeSingularFixed32Field(value: inout UInt32) throws {
try decodeSingularUInt32Field(value: &value)
}
mutating func decodeSingularFixed32Field(value: inout UInt32?) throws {
try decodeSingularUInt32Field(value: &value)
}
mutating func decodeRepeatedFixed32Field(value: inout [UInt32]) throws {
try decodeRepeatedUInt32Field(value: &value)
}
mutating func decodeSingularFixed64Field(value: inout UInt64) throws {
try decodeSingularUInt64Field(value: &value)
}
mutating func decodeSingularFixed64Field(value: inout UInt64?) throws {
try decodeSingularUInt64Field(value: &value)
}
mutating func decodeRepeatedFixed64Field(value: inout [UInt64]) throws {
try decodeRepeatedUInt64Field(value: &value)
}
mutating func decodeSingularSFixed32Field(value: inout Int32) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeSingularSFixed32Field(value: inout Int32?) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeRepeatedSFixed32Field(value: inout [Int32]) throws {
try decodeRepeatedInt32Field(value: &value)
}
mutating func decodeSingularSFixed64Field(value: inout Int64) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeSingularSFixed64Field(value: inout Int64?) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeRepeatedSFixed64Field(value: inout [Int64]) throws {
try decodeRepeatedInt64Field(value: &value)
}
mutating func decodeSingularBoolField(value: inout Bool) throws {
if scanner.skipOptionalNull() {
value = false
return
}
if isMapKey {
value = try scanner.nextQuotedBool()
} else {
value = try scanner.nextBool()
}
}
mutating func decodeSingularBoolField(value: inout Bool?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
if isMapKey {
value = try scanner.nextQuotedBool()
} else {
value = try scanner.nextBool()
}
}
mutating func decodeRepeatedBoolField(value: inout [Bool]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextBool()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularStringField(value: inout String) throws {
if scanner.skipOptionalNull() {
value = String()
return
}
value = try scanner.nextQuotedString()
}
mutating func decodeSingularStringField(value: inout String?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextQuotedString()
}
mutating func decodeRepeatedStringField(value: inout [String]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextQuotedString()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularBytesField(value: inout Data) throws {
if scanner.skipOptionalNull() {
value = Internal.emptyData
return
}
value = try scanner.nextBytesValue()
}
mutating func decodeSingularBytesField(value: inout Data?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextBytesValue()
}
mutating func decodeRepeatedBytesField(value: inout [Data]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextBytesValue()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularEnumField<E: Enum>(value: inout E?) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
value = nil
return
} else if let name = try scanner.nextOptionalQuotedString() {
if let v = E(name: name) {
value = v
return
}
} else {
let n = try scanner.nextSInt()
if let i = Int(exactly: n) {
value = E(rawValue: i)
return
}
}
throw JSONDecodingError.unrecognizedEnumValue
}
mutating func decodeSingularEnumField<E: Enum>(value: inout E) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
value = E()
return
} else if let name = try scanner.nextOptionalQuotedString() {
if let v = E(name: name) {
value = v
return
}
} else {
let n = try scanner.nextSInt()
if let i = Int(exactly: n) {
if let v = E(rawValue: i) {
value = v
return
}
}
}
throw JSONDecodingError.unrecognizedEnumValue
}
mutating func decodeRepeatedEnumField<E: Enum>(value: inout [E]) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
if let name = try scanner.nextOptionalQuotedString() {
if let v = E(name: name) {
value.append(v)
} else {
throw JSONDecodingError.unrecognizedEnumValue
}
} else {
let n = try scanner.nextSInt()
if let i = Int(exactly: n) {
if let v = E(rawValue: i) {
value.append(v)
} else {
throw JSONDecodingError.unrecognizedEnumValue
}
} else {
throw JSONDecodingError.numberRange
}
}
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
internal mutating func decodeFullObject<M: Message>(message: inout M) throws {
guard let nameProviding = (M.self as? _ProtoNameProviding.Type) else {
throw JSONDecodingError.missingFieldNames
}
fieldNameMap = nameProviding._protobuf_nameMap
if let m = message as? _CustomJSONCodable {
var customCodable = m
try customCodable.decodeJSON(from: &self)
message = customCodable as! M
} else {
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
try message.decodeMessage(decoder: &self)
}
}
mutating func decodeSingularMessageField<M: Message>(value: inout M?) throws {
if scanner.skipOptionalNull() {
if M.self is _CustomJSONCodable.Type {
value =
try (M.self as! _CustomJSONCodable.Type).decodedFromJSONNull() as? M
return
}
// All other message field types treat 'null' as an unset
value = nil
return
}
if value == nil {
value = M()
}
var subDecoder = JSONDecoder(scanner: scanner)
try subDecoder.decodeFullObject(message: &value!)
scanner = subDecoder.scanner
}
mutating func decodeRepeatedMessageField<M: Message>(
value: inout [M]
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
if scanner.skipOptionalNull() {
var appended = false
if M.self is _CustomJSONCodable.Type {
if let message = try (M.self as! _CustomJSONCodable.Type)
.decodedFromJSONNull() as? M {
value.append(message)
appended = true
}
}
if !appended {
throw JSONDecodingError.illegalNull
}
} else {
var message = M()
var subDecoder = JSONDecoder(scanner: scanner)
try subDecoder.decodeFullObject(message: &message)
scanner = subDecoder.scanner
value.append(message)
scanner = subDecoder.scanner
}
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularGroupField<G: Message>(value: inout G?) throws {
throw JSONDecodingError.schemaMismatch
}
mutating func decodeRepeatedGroupField<G: Message>(value: inout [G]) throws {
throw JSONDecodingError.schemaMismatch
}
mutating func decodeMapField<KeyType: MapKeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: inout _ProtobufMap<KeyType, ValueType>.BaseType
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType.BaseType?
try ValueType.decodeSingular(value: &valueField, from: &self)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeMapField<KeyType: MapKeyType, ValueType: Enum>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: inout _ProtobufEnumMap<KeyType, ValueType>.BaseType
) throws where ValueType.RawValue == Int {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType?
try decodeSingularEnumField(value: &valueField)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeMapField<
KeyType: MapKeyType,
ValueType: Message & Hashable
>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: inout _ProtobufMessageMap<KeyType, ValueType>.BaseType
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType?
try decodeSingularMessageField(value: &valueField)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeExtensionField(
values: inout ExtensionFieldValueSet,
messageType: Message.Type,
fieldNumber: Int
) throws {
throw JSONDecodingError.schemaMismatch
}
}
|
mit
|
aacd3a911ae41df2c4f043d6f7b36cfd
| 25.905277 | 80 | 0.647136 | 4.422375 | false | false | false | false |
rockgarden/swift_language
|
Playground/Temp.playground/Pages/didSet.xcplaygroundpage/Contents.swift
|
1
|
364
|
//: [Previous](@previous)
import UIKit
let MaxValue = 99
let MinValue = -99
var number = 0 {
willSet{
print("from \(number) to \(newValue)")
}
didSet {
if number > MaxValue {
number = MaxValue
} else if number < MinValue {
number = MinValue
}
print("from \(oldValue) to \(number)")
}
}
number = 1000
number
//: [Next](@next)
|
mit
|
7f423301632598ede81c6f8b0c3e96e3
| 14.826087 | 42 | 0.587912 | 3.401869 | false | false | false | false |
fulldecent/formant-analyzer
|
Formant Analyzer/Formant Analyzer/SpeechAnalyzer.swift
|
1
|
15668
|
//
// SpeechAnalyzer.swift
// FormantPlotter
//
// Created by William Entriken on 1/22/16.
// Copyright © 2016 William Entriken. All rights reserved.
//
import Foundation
class SpeechAnalyzer {
/// Individual audio samples
let samples: [Int16]
/// The rate in Hz
let sampleRate: Int
/// Human formants are < 5 kHz so we do not need signal information above 10 kHz
lazy var decimationFactor: Int = {
return self.sampleRate / 10000
}()
/// The part of `samples` which has a strong signal
lazy var strongPart: CountableRange<Int> = {
return SpeechAnalyzer.findStrongPartOfSignal(self.samples, withChunks: 300, sensitivity: 0.1)
}()
/// The part of `samples` which is a vowel utterance
lazy var vowelPart: CountableRange<Int> = {
return self.strongPart.truncatedTails(byPortion: 0.15)
}()
/// The vowel part of `samples` decimated by `decimationFactor`
fileprivate lazy var vowelSamplesDecimated: [Int16] = {
let range = self.vowelPart
return self.samples[range].decimated(by: self.decimationFactor)
}()
/// Linear prediction coefficients of the vowel signal
lazy var estimatedLpcCoefficients: [Double] = {
return SpeechAnalyzer.estimateLpcCoefficients(samples: self.vowelSamplesDecimated, sampleRate: self.sampleRate/self.decimationFactor, modelLength: 10)
}()
/// Synthesize the frequency response for the estimated LPC coefficients
///
/// - Returns: the response at frequencies 0, 5, ... Hz, the first index (identity) is 1.0
lazy var synthesizedFrequencyResponse: [Double] = {
let frequencies = Array(stride(from: 0, to: self.sampleRate/self.decimationFactor/2, by: 15))
return SpeechAnalyzer.synthesizeResponseForLPC(self.estimatedLpcCoefficients, withRate: self.sampleRate/self.decimationFactor, atFrequencies:frequencies)
}()
/// Finds at least first four formants which are in the range for estimating human vowel pronunciation
///
/// - Returns: Formants in Hz
lazy var formants: [Double] = {
let complexPolynomial = self.estimatedLpcCoefficients.map({0.0.i + $0})
let formants = SpeechAnalyzer.findFormants(complexPolynomial, sampleRate: self.sampleRate/self.decimationFactor)
return SpeechAnalyzer.filterSpeechFormants(formants)
}()
/// Reduce horizontal resolution of `strongPart` of `signal` for plotting
func downsampleStrongPartToSamples(_ newSampleCount: Int) -> [Int16] {
let chunkSize = self.strongPart.count / newSampleCount
var chunkMaxElements = [Int16]()
// Find the chunk with the most energy and set energy threshold
for chunkStart in stride(from: self.strongPart.lowerBound, through: self.strongPart.upperBound.advanced(by: -chunkSize), by: chunkSize) {
let range = (chunkStart..<chunkStart+chunkSize)
let maxValue = self.samples[range].max()!
chunkMaxElements.append(maxValue)
}
return chunkMaxElements
}
/// Reduce horizontal resolution of `signal` for plotting
func downsampleToSamples(_ newSampleCount: Int) -> [Int16] {
guard newSampleCount > 0 else {
return []
}
guard newSampleCount < self.samples.count else {
return self.samples
}
let chunkSize = self.samples.count / newSampleCount
var chunkMaxElements = [Int16]()
// Find the chunk with the most energy and set energy threshold
for chunkStart in stride(from: self.samples.startIndex, through: self.samples.endIndex.advanced(by: -chunkSize), by: chunkSize) {
let range = (chunkStart..<chunkStart+chunkSize)
let maxValue = self.samples[range].max()!
chunkMaxElements.append(maxValue)
}
return chunkMaxElements
}
/// Creates an analyzer with given 16-bit PCM samples
init(int16Samples data: Data, withFrequency rate: Int) {
samples = data.withUnsafeBytes {
Array(UnsafeBufferPointer<Int16>(start: $0, count: data.count / MemoryLayout<Int16>.size))
}
sampleRate = rate
}
//
//MARK: Class functions that allow tweaking of parameters
//
/// Analyzes a signal to find the significant part
///
/// Considers `numChunks` parts of the signal and trims ends with signal strength not greater than a `factor` of the maximum signal strength
///
/// - Returns the range of the selected signal from the selected chunks
class func findStrongPartOfSignal(_ signal: [Int16], withChunks numChunks: Int, sensitivity factor: Double) -> CountableRange<Int> {
let chunkSize = signal.count / numChunks
var chunkEnergies = [Double]()
var maxChunkEnergy: Double = 0
guard chunkSize > 0 else {
return 0..<0
}
// Find the chunk with the most energy and set energy threshold
for chunkStart in stride(from: signal.startIndex, through: signal.endIndex.advanced(by: -chunkSize), by: chunkSize) {
let range = (chunkStart..<chunkStart+chunkSize)
let chunkEnergy = signal[range].reduce(0, {$0 + Double($1)*Double($1)})
maxChunkEnergy = max(maxChunkEnergy, chunkEnergy)
chunkEnergies.append(chunkEnergy)
}
let firstSelectedChunk = chunkEnergies.firstIndex {$0 > maxChunkEnergy * factor} ?? 0
let lastSelectedChunk: Int
// http://stackoverflow.com/a/33153621/300224
if let reverseIndex = chunkEnergies.reversed().firstIndex(where: {$0 > maxChunkEnergy * factor}) {
lastSelectedChunk = reverseIndex.base - 1
} else {
lastSelectedChunk = chunkEnergies.endIndex - 1
}
return firstSelectedChunk * chunkSize ..< (lastSelectedChunk + 1) * chunkSize
}
/// Estimate LPC polynomial coefficients from the signal
/// Uses the Levinson-Durbin recursion algorithm
/// - Returns: `modelLength` + 1 autocorrelation coefficients for an all-pole model
/// the first coefficient is 1.0 for perfect autocorrelation with zero offset
class func estimateLpcCoefficients(samples: [Int16], sampleRate rate: Int, modelLength: Int) -> [Double] {
var correlations = [Double]()
var coefficients = [Double]()
var modelError: Double
guard samples.count > modelLength else {
return [Double](repeating: 1, count: modelLength + 1)
}
for delay in 0 ... modelLength {
var correlationSum = 0.0
for sampleIndex in 0 ..< samples.count - delay {
correlationSum += Double(samples[sampleIndex]) * Double(samples[sampleIndex + delay])
}
correlations.append(correlationSum)
}
// The first predictor (delay 0) is 100% correlation
modelError = correlations[0] // total power is unexplained
coefficients.append(1.0) // 100% correlation for zero delay
// For each coefficient in turn
for delay in 1 ... modelLength {
// Find next reflection coefficient from coefficients and correlations
var rcNum = 0.0
for i in 1 ... delay {
rcNum -= coefficients[delay - i] * correlations[i]
}
coefficients.append(rcNum / modelError)
// Perform recursion on coefficients
for i in stride(from: 1, through: delay/2, by: 1) {
let pci = coefficients[i] + coefficients[delay] * coefficients[delay - i]
let pcki = coefficients[delay - i] + coefficients[delay] * coefficients[i]
coefficients[i] = pci
coefficients[delay - i] = pcki
}
// Calculate residual error
modelError *= 1.0 - coefficients[delay] * coefficients[delay]
}
return coefficients
}
/// Synthesize the frequency response for the estimated LPC coefficients
///
/// - Parameter coefficients: an all-pole LPC model
/// - Parameter samplingRate: the sampling frequency in Hz
/// - Parameter frequencies: the frequencies whose response you'd like to know
/// - Returns: a response from 0 to 1 for each frequency you are interrogating
class func synthesizeResponseForLPC(_ coefficients: [Double], withRate samplingRate:Int, atFrequencies frequencies:[Int]) -> [Double] {
var retval = [Double]()
// Calculate frequency response of the inverse of the predictor filter
for frequency in frequencies {
let radians = Double(frequency) / Double(samplingRate) * Double.pi * 2
var response: Complex<Double> = 0.0 + 0.0.i
for (index, coefficient) in coefficients.enumerated() {
response += Complex<Double>(abs: coefficient, arg:Double(index) * radians)
}
retval.append(20 * log10(1.0 / response.abs))
}
return retval
}
/// Laguerre's method to find one root of the given complex polynomial
/// Call this method repeatedly to find all the complex roots one by one
/// Algorithm from Numerical Recipes in C by Press/Teutkolsky/Vetterling/Flannery
///
class func laguerreRoot(_ polynomial: [Complex<Double>], initialGuess guess: Complex<Double> = 0.0 + 0.0.i) -> Complex<Double> {
let m = polynomial.count - 1
let MR = 8
let MT = 10
let maximumIterations = MR * MT // is MR * MT
/// Error threshold
let EPSS = 1.0e-7
var abx, abp, abm, err: Double
var dx, x1, b, d, f, g, h, sq, gp, gm, g2: Complex<Double>
let frac = [0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 1.0]
var x = guess
for iteration in 1 ... maximumIterations {
b = polynomial[m]
err = b.abs
d = 0.0 + 0.0.i
f = 0.0 + 0.0.i
abx = x.abs
for j in stride(from: (m-1), through: 0, by: -1) {
// efficient computation of 1st and 2nd derivatives of polynomials
// f is P``/2
f = x * f + d
d = x * d + b
b = x * b + polynomial[j]
err = b.abs + abx * err
}
err *= EPSS // estimate of round-off error in evaluating polynomial
if (b.abs < err) {
return x
}
g = d / b
g2 = g * g
h = g2 - 2.0 * f / b
sq = sqrt((Double(m) - 1) * (Double(m) * h - g2))
gp = g + sq
gm = g - sq
abp = gp.abs
abm = gm.abs
if (abp < abm) {
gp = gm
}
dx = max(abp, abm) > 0.0 ? Double(m) / gp : (1 + abx) * (cos(Double(iteration)) + sin(Double(iteration)).i)
x1 = x - dx
if (x == x1) {
return x // converged
}
// Every so often we take a fractional step, to break any limit cycle (itself a rare occurrence)
if iteration % MT > 0 {
x = x1
} else {
x = x - frac[iteration/MT] * dx
}
}
NSLog("Too many iterations in Laguerre, giving up")
return 0 + 0.i
}
/// Use Laguerre's method to find roots.
///
/// - Parameter polynomial: coefficients of the input polynomial
/// - Note: Does not implement root polishing, so accuracy may be impacted
/// - Note: May include duplicated roots/formants
class func findFormants(_ polynomial: [Complex<Double>], sampleRate rate: Int) -> [Double] {
/// Laguerre imaginary noise gate
let EPS = 2.0e-6
var roots = [Complex<Double>]()
var deflatedPolynomial = polynomial
let modelOrder = polynomial.count - 1
for j in stride(from: modelOrder, through: 1, by: -1) {
var root = SpeechAnalyzer.laguerreRoot(deflatedPolynomial)
// If imaginary part is very small, ignore it
if abs(root.imag) < 2.0 * EPS * abs(root.real) {
root.imag = 0.0
}
roots.append(root)
// Perform forward deflation. Divide by the factor of the root found above
var b = deflatedPolynomial[j]
for jj in stride(from: (j-1), through: 0, by: -1) {
let c = deflatedPolynomial[jj]
deflatedPolynomial[jj] = b
b = root * b + c
}
}
let polishedRoots = roots.map({SpeechAnalyzer.laguerreRoot(polynomial, initialGuess: $0)})
//MAYBE: This may cause duplicated roots, is that a problem?
// Find real frequencies corresponding to all roots
let formantFrequencies = polishedRoots.map({$0.arg * Double(rate) / Double.pi / 2})
return formantFrequencies.sorted()
}
/// Finds the first four formants and cleans out negatives, and other problems
///
/// - Returns: Formants in Hz
class func filterSpeechFormants(_ formants: [Double]) -> [Double] {
/// Human minimum format ability in Hz
let MIN_FORMANT = 50.0
/// Maximum format ability in Hz
///
/// - Note: This should be lower than sampling rate / 2 - MIN_FORMANT
let MAX_FORMANT = 5000.0
/// Formants closer than this will be merged into one, in Hz
let MIN_DISTANCE = 10.0
var editedFormants = formants.sorted().compactMap({$0 >= MIN_FORMANT && $0 <= MAX_FORMANT ? $0 : nil})
var done = false
while !done {
{
for (index, formantA) in editedFormants.enumerated() {
guard index < editedFormants.count - 1 else {
continue
}
let formantB = editedFormants[(index + 1)]
if abs(formantA - formantB) < MIN_DISTANCE {
let newFormant = (formantA + formantB) / 2
editedFormants.remove(at: editedFormants.firstIndex(of: formantA)!)
editedFormants.remove(at: editedFormants.firstIndex(of: formantB)!)
editedFormants.append(newFormant)
editedFormants = editedFormants.sorted()
return
}
}
done = true
}()
}
for _ in stride(from: editedFormants.count, through: 4, by: 1) {
editedFormants.append(9999.0)
}
return editedFormants
}
}
// Must be able to represent an empty range
extension CountableRange where Bound.Stride == Int {
/// Shrink range by `portion` of its length from each size
/// - Parameter portion is a fraction in the range 0...0.5
func truncatedTails(byPortion portion: Double) -> CountableRange<Bound> {
let start = self.lowerBound.advanced(by: Int((portion * Double(self.count)).rounded()))
let end = self.lowerBound.advanced(by: Int(((1 - portion) * Double(self.count)).rounded()))
return start ..< end
}
}
extension ArraySlice {
/// Select the first of every `stride` items from `samples`
func decimated(by stride: Int) -> Array<Iterator.Element> {
let selectedSamples = Swift.stride(from: self.startIndex, to: self.endIndex, by: stride)
return selectedSamples.map({self[$0]})
}
}
|
mit
|
c678f2b5fbb478bfe1600a274da567d9
| 41.115591 | 161 | 0.591179 | 4.294682 | false | false | false | false |
gribozavr/swift
|
test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift
|
1
|
4956
|
// RUN: %swift -target %module-target-future -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceC5ValueVySS_SiSdGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|i8\* \(i8\*, i8\*, %swift.type\*\)\* @__swift_memcpy[0-9]+_[0-9]+ to i8\*)}}),
// CHECK-SAME: i8* bitcast (void (i8*, %swift.type*)* @__swift_noop_void_return to i8*),
// CHECK-SAME: i8* bitcast (i8* (i8*, i8*, %swift.type*)* @__swift_memcpy{{[0-9]+}}_{{[0-9]+}} to i8*),
// CHECK-SAME: i8* bitcast (i8* (i8*, i8*, %swift.type*)* @__swift_memcpy{{[0-9]+}}_{{[0-9]+}} to i8*),
// CHECK-SAME: i8* bitcast (i8* (i8*, i8*, %swift.type*)* @__swift_memcpy{{[0-9]+}}_{{[0-9]+}} to i8*),
// CHECK-SAME: i8* bitcast (i8* (i8*, i8*, %swift.type*)* @__swift_memcpy{{[0-9]+}}_{{[0-9]+}} to i8*),
// CHECK-SAME: i8* bitcast (i32 (%swift.opaque*, i32, %swift.type*)* @"$s4main9NamespaceC5ValueVySS_SiSdGwet" to i8*),
// CHECK-SAME: i8* bitcast (void (%swift.opaque*, i32, i32, %swift.type*)* @"$s4main9NamespaceC5ValueVySS_SiSdGwst" to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore the COMDAT on PE/COFF platforms
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main9NamespaceC5ValueVySS_SiSdGMf" = internal constant <{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, %swift.type*, i32, i32, i64 }> <{ i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceC5ValueVySS_SiSdGWV", i32 0, i32 0), [[INT]] 512, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*), %swift.type* @"$sSSN", %swift.type* @"$sSiN", %swift.type* @"$sSdN", i32 0, i32 8, i64 3 }>, align [[ALIGNMENT]]
final class Namespace<Arg> {
struct Value<First, Second> {
let first: First
let second: Second
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiSdGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Namespace<String>.Value(first: 13, second: 13.0) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]], %swift.type*, %swift.type*, %swift.type*) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: [[ERASED_TYPE_3:%[0-9]+]] = bitcast %swift.type* %3 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: [[EQUAL_TYPE_1_3:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_3]]
// CHECK: [[EQUAL_TYPES_1_3:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_2]], [[EQUAL_TYPE_1_3]]
// CHECK: br i1 [[EQUAL_TYPES_1_3]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main9NamespaceC5ValueVySS_SiSdGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* [[ERASED_TYPE_3]], %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
d01173de7c73a0ca312e4999067adf0b
| 74.090909 | 597 | 0.607345 | 2.687636 | false | false | false | false |
DevAndArtist/SingletonGenerator
|
SingletonGenerator.swift
|
1
|
2785
|
//
// SingletonGenerator.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Adrian Zubarev (a.k.a. DevAndArtist)
// Created on 06.07.15.
//
// 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.
//
public protocol SingletonType { /* private */ init() } // wait for this feature to create a true singleton
private var singletonInstances = [String: SingletonType]()
public extension SingletonType {
typealias SingletonInstance = Self
typealias SingletonMetatype = Self.Type
public static var getSingleton: SingletonInstance { return setSingleton { $0 } }
public static var setSingleton: SingletonMetatype { return self }
public static func setSingleton(setter: (_: SingletonInstance) -> SingletonInstance) -> SingletonInstance {
guard let instance = singletonInstances["\(self)"] as? Self else {
return setInstance(self.init(), withSetter: setter, overridable: true)
}
return setInstance(instance, withSetter: setter, overridable: false)
}
private static func setInstance(var instance: Self, withSetter setter: (_: Self) -> Self, overridable: Bool) -> Self {
instance = restoreInstanceIfNeeded(instance1: instance, instance2: setter(instance), overridable: overridable)
singletonInstances["\(self)"] = instance
return instance
}
private static func restoreInstanceIfNeeded(instance1 i1: Self, instance2 i2: Self, overridable: Bool) -> Self {
guard i1.dynamicType is AnyClass else { return i2 }
return ((i1 as! AnyObject) !== (i2 as! AnyObject)) && !overridable ? i1 : i2
}
}
infix operator « { associativity none }
func « <Instance: SingletonType>(type: Instance.Type, newInstance: Instance) -> Instance {
return type.setSingleton { (_) -> Instance in newInstance }
}
|
mit
|
eb6fc51b5e0dcaad841f9063b67333e1
| 37.652778 | 119 | 0.733741 | 4.147541 | false | false | false | false |
ryanipete/AmericanChronicle
|
AmericanChronicle/Code/Modules/DatePicker/Wireframe/TransitionControllers/ShowDatePickerTransitionController.swift
|
1
|
1496
|
import UIKit
final class ShowDatePickerTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 0.2
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) else { return }
let blackBG = UIView()
blackBG.backgroundColor = .black
transitionContext.containerView.addSubview(blackBG)
blackBG.fillSuperview(insets: .zero)
guard let snapshot = fromVC.view.snapshotView() else { return }
snapshot.tag = DatePickerTransitionConstants.snapshotTag
transitionContext.containerView.addSubview(snapshot)
guard let toVC = transitionContext.viewController(forKey: .to) as? DatePickerViewController else { return }
transitionContext.containerView.addSubview(toVC.view)
toVC.view.layoutIfNeeded()
toVC.view.backgroundColor = UIColor(white: 0, alpha: 0)
toVC.showKeyboard()
UIView.animate(withDuration: duration, animations: {
toVC.view.layoutIfNeeded()
toVC.view.backgroundColor = UIColor(white: 0, alpha: 0.8)
snapshot.transform = CGAffineTransform(scaleX: 0.99, y: 0.99)
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
duration
}
}
|
mit
|
d9b9eb1e0194496bbf1ec35b06f0728a
| 37.358974 | 115 | 0.698529 | 5.400722 | false | false | false | false |
salemoh/GoldenQuraniOS
|
GoldenQuranSwift/GoldenQuranSwift/RecitationManager.swift
|
1
|
2648
|
//
// RecitationManager.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 4/11/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
class RecitationManager: NSObject {
class func getRecitations() -> [Recitation]{
return DBManager.shared.getMushafRecitations(mushafType: Mus7afManager.shared.currentMus7af.type!)
}
class func getRecitationWithId(id:Int) -> Recitation{
return DBManager.shared.getMushafRecitationWithID(id: id, mushafType: Mus7afManager.shared.currentMus7af.type!)
}
class func setActiveRecitation( recitation:Recitation){
Mus7afManager.shared.currentMus7af.recitationId = recitation.id!
Mus7afManager.shared.updateMushafValues(mushaf: Mus7afManager.shared.currentMus7af)
}
class func isActiveRecitation( recitation:Recitation) -> Bool{
if recitation.id == Mus7afManager.shared.currentMus7af.recitationId {
return true
}
return false
}
class func isFavouriteRecitation( recitation:Recitation) -> Bool{
let favoriteRecitations = UserDefaults.standard.object(forKey: Constants.userDefaultsKeys.favouriteRecitations)
if let favs = favoriteRecitations as? Array<Int> {
if favs.contains(recitation.id!) {
return true
}
}
return false
}
class func favouriteRecitations() -> [Int] {
let favoriteRecitations:[Int] = UserDefaults.standard.object(forKey: Constants.userDefaultsKeys.favouriteRecitations) as! [Int]? ?? [Int]()
return favoriteRecitations
}
class func addRecitationToFavourite( recitation:Recitation) {
var favoriteRecitations:[Int] = UserDefaults.standard.object(forKey: Constants.userDefaultsKeys.favouriteRecitations) as! [Int]? ?? [Int]()
favoriteRecitations.append(recitation.id!)
UserDefaults.standard.set(favoriteRecitations, forKey: Constants.userDefaultsKeys.favouriteRecitations)
UserDefaults.standard.synchronize()
}
class func removeRecitationFromFavourite( recitation:Recitation) {
var favoriteRecitations:[Int] = UserDefaults.standard.object(forKey: Constants.userDefaultsKeys.favouriteRecitations) as! [Int]? ?? [Int]()
if favoriteRecitations.contains(recitation.id!) {
let index = favoriteRecitations.index(of: recitation.id!)!
favoriteRecitations.remove(at:index)
UserDefaults.standard.set(favoriteRecitations, forKey: Constants.userDefaultsKeys.favouriteRecitations)
UserDefaults.standard.synchronize()
}
}
}
|
mit
|
414951f1b39471e840b7c8a1f9efd1d9
| 40.359375 | 147 | 0.700793 | 4.16195 | false | false | false | false |
JoeLago/MHGDB-iOS
|
MHGDB/Screens/PalicoWeapon/PalicoWeaponDetailSection.swift
|
1
|
1648
|
//
// MIT License
// Copyright (c) Gathering Hall Studios
//
import UIKit
class PalicoWeaponDetailSection: MultiCellSection {
var weapon: PalicoWeapon
init(weapon: PalicoWeapon) {
self.weapon = weapon
super.init()
title = "Details"
}
override func populateCells() {
let sharpnessView = SharpnessView()
sharpnessView.sharpness = weapon.sharpness
sharpnessView.heightConstraint(10)
let sharpnessDetail = SingleDetailView(label: "Sharpness", detailView: sharpnessView)
addCell(MultiDetailCell(details: [
SingleDetailLabel(label: "Melee Dmg",
attributedString:
NSMutableAttributedString(damage: weapon.attackMelee,
element: weapon.element,
elementDamage: weapon.elementMelee)),
SingleDetailLabel(label: "Ranged Dmg",
attributedString:
NSMutableAttributedString(damage: weapon.attackRanged,
element: weapon.element,
elementDamage: weapon.elementRanged)),
sharpnessDetail
]))
addCell(MultiDetailCell(details: [
SingleDetailLabel(label: "Type", value: weapon.type),
SingleDetailLabel(label: "Balance", value: weapon.balance.string),
SingleDetailLabel(label: "Create Cost", value: weapon.creationCost),
]))
addDetail(label: "Description", text: weapon.description)
}
}
|
mit
|
1534c713f37fbe85747f8724e14f5194
| 35.622222 | 93 | 0.564927 | 5.438944 | false | false | false | false |
velvetroom/columbus
|
Source/Model/SettingsMemory/MSettingsMemoryProjects.swift
|
1
|
872
|
import UIKit
final class MSettingsMemoryProjects
{
private(set) var size:CGFloat
private var map:[String:MSettingsMemoryProjectsItem]
var identifiers:[String]
{
get
{
let identifiers:[String] = Array(map.keys)
return identifiers
}
}
init()
{
map = [:]
size = 0
}
//MARK: internal
func add(project:MSettingsMemoryProjectsItem)
{
map[project.identifier] = project
size += project.size
}
func pop(identifier:String) -> MSettingsMemoryProjectsItem?
{
guard
let item:MSettingsMemoryProjectsItem = map.removeValue(forKey:identifier)
else
{
return nil
}
size -= item.size
return item
}
}
|
mit
|
b4ee477aa49ca120b3adfe1267f90f06
| 17.553191 | 85 | 0.512615 | 5.069767 | false | false | false | false |
MagicianDL/Shark
|
Shark/Views/Home/SKHomeHeaderView.swift
|
1
|
9213
|
//
// SKHomeHeaderView.swift
// Shark
//
// Created by Dalang on 2017/3/5.
// Copyright © 2017年 青岛鲨鱼汇信息技术有限公司. All rights reserved.
//
import UIKit
fileprivate let TAG_HOMEHEADERVIEW_DOWNLOADBUTTON = 100
fileprivate let TAG_HOMEHEADERVIEW_QUESTIONBUTTON = 102
fileprivate let TAG_HOMEHEADERVIEW_SHARKBUTTON = 103
fileprivate let TAG_HOMEHEADERVIEW_TOOLBUTTON = 104
/// 主页的TableHeaderView
final class SKHomeHeaderView: UIView {
// MARK: Properties
// fileprivate lazy var cellInfoArray: [SKCarouselCellInfo] = {
//
// let array: Array = (NSArray(contentsOfFile: Bundle.main.path(forResource: "imageInfos", ofType: "plist")!)! as Array)
//
// var cellInfoArray = [SKCarouselCellInfo]()
//
// for index in 0..<array.count {
// let dic = array[index] as! [String: Any]
// let cellInfo = SKCarouselCellInfo(withDictionary: dic)
// cellInfoArray.append(cellInfo)
// }
//
// return cellInfoArray
// }()
var cellInfoArray: [SKCarouselCellInfo] = [SKCarouselCellInfo]()
fileprivate lazy var carouselView: SKCarouselView = {
let carouselView = SKCarouselView(frame: CGRect.zero, dataSource: self, delegate: self)
return carouselView
} ()
/// 下载按钮
fileprivate lazy var downloadButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_DOWNLOADBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_download"), title: "下载", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 问题按钮
fileprivate lazy var questionButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_QUESTIONBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_question"), title: "问题", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 鲨小白按钮
fileprivate lazy var sharkButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_SHARKBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_shark"), title: "鲨小白", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 工具箱按钮
fileprivate lazy var toolButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_TOOLBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_tools"), title: "工具箱", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 推荐阅读
fileprivate lazy var suggestedReadingView: UIView = {
let baseView: UIView = UIView()
baseView.backgroundColor = UIColor.clear
let view: UIView = UIView()
view.backgroundColor = UIColor.mainBlue
baseView.addSubview(view)
let label: UILabel = UILabel()
label.text = "推荐阅读"
label.textColor = UIColor(hexString: "#666666")
label.font = UIFont.systemFont(ofSize: 16)
label.backgroundColor = UIColor.clear
baseView.addSubview(label)
view.snp.makeConstraints { (maker) in
maker.left.equalTo(baseView.snp.left).offset(8)
maker.height.equalTo(19)
maker.width.equalTo(2)
maker.centerY.equalTo(baseView.snp.centerY)
}
label.snp.makeConstraints { (maker) in
maker.left.equalTo(view.snp.right).offset(8)
maker.top.equalTo(baseView.snp.top)
maker.bottom.equalTo(baseView.snp.bottom)
}
return baseView
} ()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
layout()
}
func reload() {
let array: Array = (NSArray(contentsOfFile: Bundle.main.path(forResource: "imageInfos", ofType: "plist")!)! as Array)
for index in 0..<array.count {
let dic = array[index] as! [String: Any]
let cellInfo = SKCarouselCellInfo(withDictionary: dic)
cellInfoArray.append(cellInfo)
}
carouselView.reloadData()
}
}
// MARK: - Private Method
extension SKHomeHeaderView {
/// 初始化界面
fileprivate func setup() {
self.addSubview(suggestedReadingView)
self.addSubview(downloadButton)
self.addSubview(questionButton)
self.addSubview(sharkButton)
self.addSubview(toolButton)
self.addSubview(carouselView)
}
/// 布局
fileprivate func layout() {
suggestedReadingView.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.right.equalTo(self.snp.right)
maker.bottom.equalTo(self.snp.bottom)
maker.height.equalTo(39)
}
downloadButton.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.bottom.equalTo(suggestedReadingView.snp.top)
maker.height.equalTo(86)
maker.width.equalTo(self.snp.width).multipliedBy(0.25)
}
questionButton.snp.makeConstraints { (maker) in
maker.left.equalTo(downloadButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
sharkButton.snp.makeConstraints { (maker) in
maker.left.equalTo(questionButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
toolButton.snp.makeConstraints { (maker) in
maker.left.equalTo(sharkButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
carouselView.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.right.equalTo(self.snp.right)
maker.bottom.equalTo(downloadButton.snp.top).offset(-5)
maker.height.equalTo(130)
}
}
/// 点击按钮
///
/// - Parameter button: UIButton
@objc fileprivate func buttonPressed(_ button: UIButton) {
}
}
// MARK: - SKCarouselViewDelegate SKCarouselViewDataSource
extension SKHomeHeaderView: SKCarouselViewDelegate, SKCarouselViewDataSource {
func sizeForPage(inCarouselView carouselView: SKCarouselView) -> CGSize {
return CGSize(width: 253, height: 130)
}
func numberOfPages(inCarouselView carouselView: SKCarouselView) -> Int {
return cellInfoArray.count
}
func carouselView(_ carouselView: SKCarouselView, cellForPageAtIndex index: Int) -> SKCarouselCell {
let cell = SKCarouselCellImageView(frame: CGRect(x: 0, y: 0, width: 253 - 4, height: 130))
let cellInfo = cellInfoArray[index]
cell.imageView.image = UIImage(named: cellInfo.imageName)
cell.showTime = TimeInterval(cellInfo.showTime)
return cell
}
func carouselView(_ carouselView: SKCarouselView, didScrollToPage page: Int) {
// print("didScrollToPage \(page)")
}
func carouselView(_ carouselView: SKCarouselView, didSelectPageAtIndex index: Int) {
// print("didSelectPageAtIndex \(index)")
}
}
|
mit
|
80da9fd475ae55087d032a662dbb6aa1
| 34.623529 | 127 | 0.615808 | 4.367308 | false | false | false | false |
lioonline/Swift
|
CoreLocation/CoreLocation/ViewController.swift
|
1
|
6898
|
//
// ViewController.swift
// CoreLocation
//
// Created by Carlos Butron on 19/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager: CLLocationManager = CLLocationManager()
var myLatitude: CLLocationDegrees!
var myLongitude: CLLocationDegrees!
var finalLatitude: CLLocationDegrees!
var finalLongitude: CLLocationDegrees!
var distance: CLLocationDistance!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let tap = UITapGestureRecognizer(target: self, action: "action:")
myMap.addGestureRecognizer(tap)
}
func action(gestureRecognizer:UIGestureRecognizer) {
var touchPoint = gestureRecognizer.locationInView(self.myMap)
var newCoord:CLLocationCoordinate2D = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)
var getLat: CLLocationDegrees = newCoord.latitude
var getLon: CLLocationDegrees = newCoord.longitude
//Convert to points to CLLocation. In this way we can measure distanceFromLocation
var newCoord2: CLLocation = CLLocation(latitude: getLat, longitude: getLon)
var newCoord3: CLLocation = CLLocation(latitude: myLatitude, longitude: myLongitude)
finalLatitude = newCoord2.coordinate.latitude
finalLongitude = newCoord2.coordinate.longitude
println("Original Latitude: \(myLatitude)")
println("Original Longitude: \(myLongitude)")
println("Final Latitude: \(finalLatitude)")
println("Final Longitude: \(finalLongitude)")
//distance between our position and the new point created
let distance = newCoord2.distanceFromLocation(newCoord3)
println("Distancia entre puntos: \(distance)")
var newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoord
newAnnotation.title = "My target"
newAnnotation.subtitle = ""
myMap.addAnnotation(newAnnotation)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
//get data from placemark
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
myLongitude = (containsPlacemark.location.coordinate.longitude)
myLatitude = (containsPlacemark.location.coordinate.latitude)
// testing show data
println("Locality: \(locality)")
println("PostalCode: \(postalCode)")
println("Area: \(administrativeArea)")
println("Country: \(country)")
println(myLatitude)
println(myLongitude)
//update map with my location
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1 , 0.1)
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: myLatitude, longitude: myLongitude)
let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan)
myMap.setRegion(theRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
//distance between two points
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }
func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {
let lat1 = degreesToRadians(point1.coordinate.latitude)
let lon1 = degreesToRadians(point1.coordinate.longitude)
let lat2 = degreesToRadians(point2.coordinate.latitude);
let lon2 = degreesToRadians(point2.coordinate.longitude);
println("Latitud inicial: \(point1.coordinate.latitude)")
println("Longitud inicial: \(point1.coordinate.longitude)")
println("Latitud final: \(point2.coordinate.latitude)")
println("Longitud final: \(point2.coordinate.longitude)")
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radiansBearing)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
gpl-3.0
|
e29d61cc217d503745c5d9cd51ea7cce
| 38.193182 | 126 | 0.649754 | 5.513989 | false | false | false | false |
schibsted/layout
|
Layout/Shared/Files.swift
|
1
|
1997
|
// Copyright © 2017 Schibsted. All rights reserved.
import Foundation
// An error relating to files or file parsing
struct FileError: Error, CustomStringConvertible {
let message: String
let file: URL
public init(_ message: String, for file: URL) {
self.message = message
self.file = file
}
public init(_ error: Error, for file: URL) {
let message = (error as NSError).localizedDescription
self.init(message, for: file)
}
public var description: String {
var description = message
if !description.contains(file.path) {
description = "\(description) at \(file.path)"
}
return description
}
/// Associates error thrown by the wrapped closure with the given path
static func wrap<T>(_ closure: () throws -> T, for file: URL) throws -> T {
do {
return try closure()
} catch {
throw self.init(error, for: file)
}
}
}
// Name of the Layout ignore file
let layoutIgnoreFile = ".layout-ignore"
// Parses a `.layout-ignore` file and returns the paths as URLs
func parseIgnoreFile(_ file: URL) throws -> [URL] {
let data = try FileError.wrap({ try Data(contentsOf: file) }, for: file)
guard let string = String(data: data, encoding: .utf8) else {
throw FileError("Unable to read \(file.lastPathComponent) file", for: file)
}
return parseIgnoreFile(string, baseURL: file.deletingLastPathComponent())
}
func parseIgnoreFile(_ contents: String, baseURL: URL) -> [URL] {
var paths = [URL]()
for line in contents.components(separatedBy: .newlines) {
let line = line
.replacingOccurrences(of: "\\s*#.*", with: "", options: .regularExpression)
.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
if !line.isEmpty {
let path = baseURL.appendingPathComponent(line)
paths.append(path)
}
}
return paths
}
|
mit
|
27bb37fbd7f11bebc11286c17c61c49c
| 31.193548 | 87 | 0.622244 | 4.283262 | false | false | false | false |
JamieScanlon/AugmentKit
|
AugmentKit/AKCore/Primatives/AKWorldDistance.swift
|
1
|
2381
|
//
// AKWorldDistance.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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
// MARK: - AKWorldDistance
/**
Represents the distance in meters between two points in the AR world.
*/
public struct AKWorldDistance {
/**
Meters in the X direcrion
*/
public var metersX: Double
/**
Meters in the Y direcrion
*/
public var metersY: Double
/**
Meters in the Z direcrion
*/
public var metersZ: Double
/**
The distance in the X/Z directrion in meters
*/
public private(set) var distance2D: Double
/**
The distance in meters
*/
public private(set) var distance3D: Double
/**
Initializes a new structure with meters X, Y, and Z
- Parameters:
- metersX: X value in meters
- metersY: Y value in meters
- metersZ: Z value in meters
*/
public init(metersX: Double = 0, metersY: Double = 0, metersZ: Double = 0) {
self.metersX = metersX
self.metersY = metersY
self.metersZ = metersZ
let planarDistance = sqrt(metersX * metersX + metersZ * metersZ)
self.distance2D = planarDistance
self.distance3D = sqrt(planarDistance * planarDistance + metersY * metersY)
}
}
|
mit
|
f8666fb8ca8e40a8544373f2f0c7c4e8
| 32.069444 | 83 | 0.680806 | 4.084048 | false | false | false | false |
shamanskyh/Precircuiter
|
Precircuiter/AppDelegate.swift
|
1
|
1636
|
//
// AppDelegate.swift
// Precircuiter
//
// Created by Harry Shamansky on 8/25/14.
// Copyright © 2014 Harry Shamansky. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var startScreenWindowController: NSWindowController?
func applicationWillFinishLaunching(_ notification: Notification) {
// Create an instance of the sub-classed document controller.
// This will be set as the shared document controller, according to the spec.
let _ = InstrumentDataDocumentController()
// register the default preferences
let defaultsDictionary = [kShowConnectionsPreferenceKey: true, kAnimateConnectionsPreferenceKey: true, kCutCornersPreferenceKey: true];
UserDefaults.standard.register(defaults: defaultsDictionary)
}
// prevent the app from creating a new document
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
return false
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Show the opening screen or jump straight into the open screen
if Preferences.stopShowingStartScreen == false {
let storyboard = NSStoryboard(name: kMainStoryboardIdentifier, bundle: nil)
startScreenWindowController = storyboard.instantiateController(withIdentifier: kStartScreenWindowIdentifier) as? NSWindowController
startScreenWindowController?.showWindow(self)
} else {
NSDocumentController.shared.openDocument(self)
}
}
}
|
mit
|
a1bc3d17dd5df5713f1346e7a29a254e
| 36.159091 | 143 | 0.705199 | 5.523649 | false | false | false | false |
fizx/jane
|
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/ServerSession.swift
|
4
|
2193
|
/*
* Copyright 2018, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Dispatch
import Foundation
import SwiftProtobuf
public protocol ServerSession: class {
var requestMetadata: Metadata { get }
var initialMetadata: Metadata { get set }
func cancel()
}
open class ServerSessionBase: ServerSession {
public var handler: Handler
public var requestMetadata: Metadata { return handler.requestMetadata }
public var initialMetadata: Metadata = Metadata()
public var call: Call { return handler.call }
public init(handler: Handler) {
self.handler = handler
}
public func cancel() {
call.cancel()
handler.shutdown()
}
func sendInitialMetadataAndWait() throws {
let sendMetadataSignal = DispatchSemaphore(value: 0)
var success = false
try handler.sendMetadata(initialMetadata: initialMetadata) {
success = $0
sendMetadataSignal.signal()
}
sendMetadataSignal.wait()
if !success {
throw ServerStatus.sendingInitialMetadataFailed
}
}
func receiveRequestAndWait() throws -> Data {
let sendMetadataSignal = DispatchSemaphore(value: 0)
var requestData: Data?
try handler.receiveMessage(initialMetadata: initialMetadata) {
requestData = $0
sendMetadataSignal.signal()
}
sendMetadataSignal.wait()
if let requestData = requestData {
return requestData
} else {
throw ServerStatus.noRequestData
}
}
}
open class ServerSessionTestStub: ServerSession {
open var requestMetadata = Metadata()
open var initialMetadata = Metadata()
public init() {}
open func cancel() {}
}
|
mit
|
87197404f4403a5af2b9db109aae9c38
| 24.8 | 75 | 0.709986 | 4.597484 | false | false | false | false |
chanhx/iGithub
|
iGithub/Views/Cell/StatusCell.swift
|
2
|
2088
|
//
// StatusCell.swift
// iGithub
//
// Created by Chan Hocheung on 7/23/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import UIKit
class StatusCell: UITableViewCell {
enum Status {
case loading
case error
case empty
}
var name: String
var status: Status! {
didSet {
switch status! {
case .loading:
promptLabel.text = "Loading \(name)"
indicator.startAnimating()
case .error:
promptLabel.text = "Error loading \(name)"
indicator.stopAnimating()
case .empty:
promptLabel.text = "No \(name)"
indicator.stopAnimating()
}
}
}
fileprivate let indicator = UIActivityIndicatorView(style: .gray)
fileprivate let promptLabel = UILabel()
init(name: String, status: Status = .loading) {
self.name = name
defer {
self.status = status
}
super.init(style: .default, reuseIdentifier: "StatusCell")
self.isUserInteractionEnabled = false
indicator.hidesWhenStopped = true
contentView.addSubviews([indicator, promptLabel])
let margins = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
indicator.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 3),
indicator.centerYAnchor.constraint(equalTo: promptLabel.centerYAnchor),
promptLabel.leadingAnchor.constraint(equalTo: indicator.trailingAnchor, constant: 8),
promptLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -8),
promptLabel.topAnchor.constraint(equalTo: margins.topAnchor, constant: 6),
promptLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -6)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
0a6bbf98f6cea834107bbd6bf1b046a1
| 28.814286 | 97 | 0.591279 | 5.230576 | false | false | false | false |
noremac/UIKitExtensions
|
Extensions/Source/UIKit/Section Data Source/TableViewDataSource.swift
|
1
|
5415
|
/*
The MIT License (MIT)
Copyright (c) 2017 Cameron Pulsford
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
public protocol TableViewCellDataSource: class {
associatedtype Element: CellReuseIdentifierProvider
func registerCells()
func configure(cell: UITableViewCell, at indexPath: IndexPath, with item: Element)
}
public protocol TableViewEditingDelegate: NSObjectProtocol {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
}
public protocol TableViewReorderingDelegate: NSObjectProtocol {
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
}
public protocol TableViewIndexDataSource: NSObjectProtocol {
func sectionIndexTitles(for tableView: UITableView) -> [String]?
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int
}
class TableViewDataSource<Element, CellDataSource: TableViewCellDataSource>: NSObject, UITableViewDataSource where CellDataSource.Element == Element {
private unowned var dataSource: DataSource<Element>
private weak var cellDataSource: CellDataSource?
private weak var editingDelegate: TableViewEditingDelegate?
private weak var reorderingDelegate: TableViewReorderingDelegate?
private weak var indexDataSource: TableViewIndexDataSource?
init(
dataSource: DataSource<Element>,
cellDataSource: CellDataSource,
editingDelegate: TableViewEditingDelegate?,
reorderingDelegate: TableViewReorderingDelegate?,
indexDataSource: TableViewIndexDataSource?) {
self.dataSource = dataSource
self.cellDataSource = cellDataSource
self.editingDelegate = editingDelegate
self.reorderingDelegate = reorderingDelegate
self.indexDataSource = indexDataSource
cellDataSource.registerCells()
}
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.sections[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let delegate = cellDataSource.orAssert("Internal consistency error. There is no data source.")
let item = dataSource.item(for: indexPath).orAssert("No item for index path \(indexPath).")
let identifier = item.cellReuseIdentifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
delegate.configure(cell: cell, at: indexPath, with: item)
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataSource.sections[section].headerTitle
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return dataSource.sections[section].footerTitle
}
override func responds(to selector: Selector) -> Bool {
if let object = object(for: selector) {
return object.responds(to: selector)
} else {
return super.responds(to: selector)
}
}
override func forwardingTarget(for selector: Selector) -> Any? {
if let object = object(for: selector) {
return object
} else {
return super.forwardingTarget(for: selector)
}
}
private func object(for selector: Selector) -> NSObjectProtocol? {
switch selector {
case #selector(UITableViewDataSource.tableView(_:canEditRowAt:)), #selector(UITableViewDataSource.tableView(_:commit:forRowAt:)):
return editingDelegate
case #selector(UITableViewDataSource.tableView(_:canMoveRowAt:)), #selector(UITableViewDataSource.tableView(_:moveRowAt:to:)):
return reorderingDelegate
case #selector(UITableViewDataSource.sectionIndexTitles(for:)), #selector(UITableViewDataSource.tableView(_:sectionForSectionIndexTitle:at:)):
return indexDataSource
default:
return nil
}
}
}
|
mit
|
e516e60215ca1be7475e54b9b02161af
| 38.816176 | 150 | 0.734257 | 5.469697 | false | false | false | false |
coreymason/LAHacks2017
|
ios/DreamWell/DreamWell/TrendsViewController.swift
|
1
|
3990
|
//
// TrendsViewController.swift
// DreamWell
//
// Created by Rohin Bhushan on 4/1/17.
// Copyright © 2017 rohin. All rights reserved.
//
import UIKit
import Charts
enum TrendType : String {
case airPressure = "Air Pressure"
case temperature = "Temperature"
case humidity = "Humidity"
static let trends = [airPressure, temperature, humidity]
}
class TrendsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var suggestion = ""
fileprivate let reuseIdentifier = "TrendCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: reuseIdentifier, bundle: Bundle.main), forCellReuseIdentifier: reuseIdentifier)
tableView.register(UINib(nibName: "KeywordCell", bundle: Bundle.main), forCellReuseIdentifier: "KeywordCell")
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
print("segmentChanged yo")
tableView.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension TrendsViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// one for keywords, then two for each trend type, becuase one for dream quality and one for sentiment
if segmentedControl.selectedSegmentIndex == 0 {
return 1
}
return 1 + (2 * TrendType.trends.count)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 2.50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if segmentedControl.selectedSegmentIndex == 0 {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "KeywordCell") as! KeywordCell
cell.firstLabel.text = "It seems like you could improve your sleep quality by following a few suggestions:\n- Increase the temperature\n- Increase the humidity\n- Decrease the light"
cell.firstHeightConstraint.constant = 160
cell.layoutIfNeeded()
cell.secondLabel.text = ""
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "KeywordCell") as! KeywordCell
cell.layer.borderColor = greenColor.cgColor
cell.layer.borderWidth = 1.0
cell.firstLabel.textColor = greenColor
cell.secondLabel.textColor = greenColor
cell.contentView.backgroundColor = UIColor.white
return cell
}
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! TrendCell
cell.isQuality = indexPath.row % 2 != 0
cell.type = TrendType.trends[(indexPath.row) / 2]
var yVals = [Double]()
for _ in 0..<(segmentedControl.selectedSegmentIndex == 2 ? 30 : segmentedControl.selectedSegmentIndex == 1 ? 7 : 1) {
yVals.append(Double(arc4random_uniform(27) + 1))
}
cell.updateChart(yVals: yVals)
return cell
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if segmentedControl.selectedSegmentIndex == 0 {
return 2
}
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return segmentedControl.selectedSegmentIndex == 0 ? indexPath.section == 0 ? 205 : 120 : 300.0
}
}
|
mit
|
d9dd21c5873703783c75af6e1c09e869
| 31.696721 | 186 | 0.724994 | 4.303128 | false | false | false | false |
manavgabhawala/CookieManager
|
Cookie Manager/CookieStore.swift
|
1
|
7450
|
//
// CookieStore.swift
// Cookie Manager
//
// Created by Manav Gabhawala on 29/07/15.
// Copyright © 2015 Manav Gabhawala. All rights reserved.
//
import Foundation
protocol CookieStoreDelegate: class
{
func startedParsingCookies()
func finishedParsingCookies()
func stoppedTrackingCookiesForBrowser(browser: Browser)
func madeProgress(progress: Double)
func updatedCookies()
func fullUpdate()
}
final class CookieStore
{
weak var delegate: CookieStoreDelegate?
private var safariStore: SafariCookieStore?
private var chromeStore: ChromeCookieStore?
private var firefoxStore : FirefoxCookieStore?
private let cookieHashQueue : dispatch_queue_t
private var cookieHash = [String : HTTPCookieDomain]()
{
didSet
{
if cookieHash.count % 50 == 0
{
delegate?.updatedCookies()
}
}
}
private var sortedHash = [String]()
private(set) var cookieCount : Int = 0
private var currentParses = 0
private var myProgress = 0.0
var domainCount : Int
{
return cookieHash.count
}
init(delegate: CookieStoreDelegate? = nil)
{
self.delegate = delegate
cookieHashQueue = dispatch_queue_create("ManavGabhawala.cookie-hash", DISPATCH_QUEUE_SERIAL)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.safariStore = SafariCookieStore(delegate: self)
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.chromeStore = ChromeCookieStore(delegate: self)
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.firefoxStore = FirefoxCookieStore(delegate: self)
})
}
func availableBrowsers() -> [Browser]
{
var browsers = [Browser]()
if safariStore != nil
{
browsers.append(.Safari)
}
if chromeStore != nil
{
browsers.append(.Chrome)
}
if firefoxStore != nil
{
browsers.append(.Firefox)
}
return browsers
}
func domainAtIndex(index: Int, useRecursion: Bool = true) -> HTTPCookieDomain?
{
guard index >= 0 && index < sortedHash.count, let domain = cookieHash[sortedHash[index]]
else
{
sortedHash = cookieHash.keys.sort(<)
return useRecursion ? domainAtIndex(index, useRecursion: false) : nil
}
return domain
}
func searchUsingString(string: String) -> [HTTPCookieDomain]
{
let searchStrings = string.componentsSeparatedByString(" ")
let domainsToSend = cookieHash.filter
{
for search in searchStrings
{
if $0.0.caseInsensitiveContainsString(search)
{
return true
}
for cookie in $0.1.cookies
{
if cookie.name.caseInsensitiveContainsString(search)
{
return true
}
if cookie.value.caseInsensitiveContainsString(search)
{
return true
}
if cookie.secure && search == "secure"
{
return true
}
}
}
return false
}
return domainsToSend.sort { $0.0 < $1.0 }.map { $0.1 }
}
func deleteCookies(cookies: [HTTPCookie]) throws
{
guard cookies.count > 0
else
{
return
}
let firefoxCookies = cookies.filter { $0.browser == .Firefox }
let firefoxIDs = firefoxCookies.map { $0.firefoxID! }
do
{
try firefoxStore?.deleteRows(firefoxIDs)
}
for cookie in firefoxCookies
{
guard let dom = cookieHash[cookie.domain]
else { continue }
if dom.removeCookie(cookie)
{
--cookieCount
}
if dom.cookies.count == 0
{
cookieHash.removeValueForKey(cookie.domain)
}
}
let chromeCookies = cookies.filter { $0.browser == .Chrome }
let chromeIDs = chromeCookies.map { $0.creationDate!.timeIntervalSince1970 }
do
{
try chromeStore?.deleteRows(chromeIDs)
}
for cookie in chromeCookies
{
guard let dom = cookieHash[cookie.domain]
else { continue }
if dom.removeCookie(cookie)
{
--cookieCount
}
if dom.cookies.count == 0
{
cookieHash.removeValueForKey(cookie.domain)
}
}
let safariCookies = cookies.filter { $0.browser == .Safari }
safariCookies
guard let domain = cookieHash[cookies.first!.domain]
else
{
return
}
if domain.cookies.count == 0
{
// TODO: Delete the domain also
}
delegate?.fullUpdate()
}
}
// MARK: - Shared
extension CookieStore : GenericCookieStoreDelegate
{
func startedParsingCookies()
{
if currentParses == 0
{
delegate?.startedParsingCookies()
}
++currentParses
}
func finishedParsingCookies()
{
--currentParses
currentParses = max(0, currentParses)
myProgress -= 1.0
sortedHash = cookieHash.keys.sort(<)
if currentParses == 0
{
delegate?.finishedParsingCookies()
}
}
func progressMade(progress: Double)
{
myProgress += progress
delegate?.madeProgress(myProgress / Double(currentParses))
}
func domainUpdated(domain: String, withCookies cookies: [HTTPCookie], forBrowser browser: Browser)
{
self.domainUpdated(domain, withCookies: cookies, forBrowser: browser, progressTime: nil)
}
func domainUpdated(domain: String, withCookies cookies: [HTTPCookie], forBrowser browser: Browser, progressTime: Double?, moreComing: Bool = true)
{
dispatch_async(cookieHashQueue, {
defer
{
if let prog = progressTime
{
self.progressMade(prog)
}
if !moreComing
{
self.finishedParsingCookies()
}
}
if let existingDomain = self.cookieHash[domain]
{
guard (existingDomain.cookies.filter { $0.browser == browser }) != cookies
else
{
return
}
self.cookieCount -= existingDomain.cookies.count
existingDomain.removeCookiesForBrowser(browser)
existingDomain.addCookies(cookies)
self.cookieCount += existingDomain.cookies.count
}
else
{
guard cookies.count > 0
else
{
return
}
self.cookieCount += cookies.count
self.cookieHash[domain] = HTTPCookieDomain(domain: domain, cookies: cookies, capacity: cookies.count)
}
})
}
func browser(browser: Browser, lostDomain domain: String)
{
dispatch_async(cookieHashQueue, {
guard let HTTPDomain = self.cookieHash[domain]
else
{
return
}
self.cookieCount -= HTTPDomain.removeCookiesForBrowser(browser)
if HTTPDomain.cookies.count == 0
{
self.cookieHash.removeValueForKey(domain)
}
})
}
}
// MARK: - Safari Store
extension CookieStore : SafariCookieStoreDelegate
{
func safariDomainsUpdated(domains: [(domain: String, cookies: [HTTPCookie])], eachProgress: Double, moreComing: Bool)
{
for domain in domains
{
self.domainUpdated(domain.domain, withCookies: domain.cookies, forBrowser: .Safari, progressTime: eachProgress, moreComing: moreComing)
}
}
func stoppedTrackingSafariCookies()
{
delegate?.stoppedTrackingCookiesForBrowser(.Safari)
safariStore = nil
cookieHash.map { $0.1.removeCookiesForBrowser(.Safari) }
for (domain, store) in cookieHash
{
if store.cookies.count == 0
{
cookieHash.removeValueForKey(domain)
}
}
}
}
// MARK: - Chrome Store
extension CookieStore: ChromeCookieStoreDelegate
{
func stoppedTrackingChromeCookies()
{
delegate?.stoppedTrackingCookiesForBrowser(.Chrome)
chromeStore = nil
cookieHash.map { $0.1.removeCookiesForBrowser(.Chrome) }
for (domain, store) in cookieHash
{
if store.cookies.count == 0
{
cookieHash.removeValueForKey(domain)
}
}
}
}
// MARK: - Firefox Store
extension CookieStore : FirefoxCookieStoreDelegate
{
func stoppedTrackingFirefoxCookies()
{
delegate?.stoppedTrackingCookiesForBrowser(.Firefox)
firefoxStore = nil
}
}
|
mit
|
340fcd35b2a45a96e3b4b6eb78984ec7
| 21.641337 | 147 | 0.696604 | 3.393622 | false | false | false | false |
jpsim/SourceKitten
|
Source/SourceKittenFramework/ObjCDeclarationKind.swift
|
1
|
3314
|
#if !os(Linux)
#if SWIFT_PACKAGE
import Clang_C
#endif
/**
Objective-C declaration kinds.
More or less equivalent to `SwiftDeclarationKind`, but with made up values because there's no such
thing as SourceKit for Objective-C.
*/
public enum ObjCDeclarationKind: String {
/// `category`.
case category = "sourcekitten.source.lang.objc.decl.category"
/// `class`.
case `class` = "sourcekitten.source.lang.objc.decl.class"
/// `constant`.
case constant = "sourcekitten.source.lang.objc.decl.constant"
/// `enum`.
case `enum` = "sourcekitten.source.lang.objc.decl.enum"
/// `enumcase`.
case enumcase = "sourcekitten.source.lang.objc.decl.enumcase"
/// `initializer`.
case initializer = "sourcekitten.source.lang.objc.decl.initializer"
/// `method.class`.
case methodClass = "sourcekitten.source.lang.objc.decl.method.class"
/// `method.instance`.
case methodInstance = "sourcekitten.source.lang.objc.decl.method.instance"
/// `property`.
case property = "sourcekitten.source.lang.objc.decl.property"
/// `protocol`.
case `protocol` = "sourcekitten.source.lang.objc.decl.protocol"
/// `typedef`.
case typedef = "sourcekitten.source.lang.objc.decl.typedef"
/// `function`.
case function = "sourcekitten.source.lang.objc.decl.function"
/// `mark`.
case mark = "sourcekitten.source.lang.objc.mark"
/// `struct`
case `struct` = "sourcekitten.source.lang.objc.decl.struct"
/// `union`
case `union` = "sourcekitten.source.lang.objc.decl.union"
/// `field`
case field = "sourcekitten.source.lang.objc.decl.field"
/// `ivar`
case ivar = "sourcekitten.source.lang.objc.decl.ivar"
/// `ModuleImport`
case moduleImport = "sourcekitten.source.lang.objc.module.import"
/// `UnexposedDecl`
case unexposedDecl = "sourcekitten.source.lang.objc.decl.unexposed"
// swiftlint:disable:next cyclomatic_complexity
public init(_ cursorKind: CXCursorKind) {
switch cursorKind {
case CXCursor_ObjCCategoryDecl: self = .category
case CXCursor_ObjCInterfaceDecl: self = .class
case CXCursor_EnumDecl: self = .enum
case CXCursor_EnumConstantDecl: self = .enumcase
case CXCursor_ObjCClassMethodDecl: self = .methodClass
case CXCursor_ObjCInstanceMethodDecl: self = .methodInstance
case CXCursor_ObjCPropertyDecl: self = .property
case CXCursor_ObjCProtocolDecl: self = .protocol
case CXCursor_TypedefDecl: self = .typedef
case CXCursor_VarDecl: self = .constant
case CXCursor_FunctionDecl: self = .function
case CXCursor_StructDecl: self = .struct
case CXCursor_UnionDecl: self = .union
case CXCursor_FieldDecl: self = .field
case CXCursor_ObjCIvarDecl: self = .ivar
case CXCursor_ModuleImportDecl: self = .moduleImport
case CXCursor_UnexposedDecl: self = .unexposedDecl
case CXCursor_ObjCImplementationDecl: self = .class
case CXCursor_ObjCCategoryImplDecl: self = .category
case CXCursor_ObjCDynamicDecl: self = .unexposedDecl
case CXCursor_ObjCSynthesizeDecl: self = .unexposedDecl
default: fatalError("Unsupported CXCursorKind: \(clang_getCursorKindSpelling(cursorKind))")
}
}
}
#endif
|
mit
|
f7f008b0e76045d26dd4a2c94db2f118
| 40.425 | 99 | 0.685878 | 4.061275 | false | false | false | false |
DouglasHeriot/protobuf-swift
|
Source/AbstractMessage.swift
|
1
|
8986
|
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google 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
public typealias ONEOF_NOT_SET = Int
public protocol ProtocolBuffersMessageInit {
}
public enum ProtocolBuffersError: Error {
case obvious(String)
//Streams
case invalidProtocolBuffer(String)
case illegalState(String)
case illegalArgument(String)
case outOfSpace
}
public protocol ProtocolBuffersMessage:ProtocolBuffersMessageInit {
var unknownFields:UnknownFieldSet{get}
func serializedSize() -> Int32
func isInitialized() throws
func writeTo(codedOutputStream:CodedOutputStream) throws
func writeTo(outputStream:OutputStream) throws
func data() throws -> Data
static func classBuilder()-> ProtocolBuffersMessageBuilder
func classBuilder()-> ProtocolBuffersMessageBuilder
//JSON
func encode() throws -> Dictionary<String,Any>
static func decode(jsonMap:Dictionary<String,Any>) throws -> Self
func toJSON() throws -> Data
static func fromJSON(data:Data) throws -> Self
}
public protocol ProtocolBuffersMessageBuilder {
var unknownFields:UnknownFieldSet{get set}
func clear() -> Self
func isInitialized() throws
func build() throws -> AbstractProtocolBuffersMessage
func merge(unknownField:UnknownFieldSet) throws -> Self
func mergeFrom(codedInputStream:CodedInputStream) throws -> Self
func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self
func mergeFrom(data:Data) throws -> Self
func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self
func mergeFrom(inputStream:InputStream) throws -> Self
func mergeFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self
//Delimited Encoding/Decoding
func mergeDelimitedFrom(inputStream:InputStream) throws -> Self?
static func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> Self
static func fromJSONToBuilder(data:Data) throws -> Self
}
public func == (lhs: AbstractProtocolBuffersMessage, rhs: AbstractProtocolBuffersMessage) -> Bool {
return lhs.hashValue == rhs.hashValue
}
open class AbstractProtocolBuffersMessage:Hashable, ProtocolBuffersMessage {
public var unknownFields:UnknownFieldSet
required public init() {
unknownFields = UnknownFieldSet(fields: Dictionary())
}
final public func data() -> Data {
let ser_size = serializedSize()
let data = Data(count: Int(ser_size))
let stream:CodedOutputStream = CodedOutputStream(data: data)
do {
try writeTo(codedOutputStream: stream)
}
catch {}
return Data(bytes: stream.buffer.buffer, count: Int(ser_size))
}
open func isInitialized() throws {
}
open func serializedSize() -> Int32 {
return 0
}
open func getDescription(indent:String) throws -> String {
throw ProtocolBuffersError.obvious("Override")
}
open func writeTo(codedOutputStream: CodedOutputStream) throws {
throw ProtocolBuffersError.obvious("Override")
}
final public func writeTo(outputStream: OutputStream) throws {
let codedOutput:CodedOutputStream = CodedOutputStream(stream:outputStream)
try! writeTo(codedOutputStream: codedOutput)
try codedOutput.flush()
}
public func writeDelimitedTo(outputStream: OutputStream) throws {
let serializedDataSize = serializedSize()
let codedOutputStream = CodedOutputStream(stream: outputStream)
try codedOutputStream.writeRawVarint32(value: serializedDataSize)
try writeTo(codedOutputStream: codedOutputStream)
try codedOutputStream.flush()
}
open class func classBuilder() -> ProtocolBuffersMessageBuilder {
return AbstractProtocolBuffersMessageBuilder()
}
open func classBuilder() -> ProtocolBuffersMessageBuilder {
return AbstractProtocolBuffersMessageBuilder()
}
open var hashValue: Int {
get {
return unknownFields.hashValue
}
}
//JSON
open func encode() throws -> Dictionary<String, Any> {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open class func decode(jsonMap: Dictionary<String, Any>) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open func toJSON() throws -> Data {
let json = try JSONSerialization.data(withJSONObject: encode(), options: JSONSerialization.WritingOptions(rawValue: 0))
return json
}
open class func fromJSON(data:Data) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
}
open class AbstractProtocolBuffersMessageBuilder:ProtocolBuffersMessageBuilder {
open var unknownFields:UnknownFieldSet
public init() {
unknownFields = UnknownFieldSet(fields:Dictionary())
}
open func build() throws -> AbstractProtocolBuffersMessage {
return AbstractProtocolBuffersMessage()
}
open func clone() throws -> Self {
return self
}
open func clear() -> Self {
return self
}
open func isInitialized() throws {
}
@discardableResult
open func mergeFrom(codedInputStream:CodedInputStream) throws -> Self {
return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry())
}
open func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self {
throw ProtocolBuffersError.obvious("Override")
}
@discardableResult
open func merge(unknownField: UnknownFieldSet) throws -> Self {
let merged:UnknownFieldSet = try UnknownFieldSet.builderWithUnknownFields(copyFrom: unknownFields).merge(unknownFields: unknownField).build()
unknownFields = merged
return self
}
@discardableResult
final public func mergeFrom(data:Data) throws -> Self {
let input:CodedInputStream = CodedInputStream(data:data)
_ = try mergeFrom(codedInputStream: input)
try input.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> Self {
let input:CodedInputStream = CodedInputStream(data:data)
_ = try mergeFrom(codedInputStream: input, extensionRegistry:extensionRegistry)
try input.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(inputStream: InputStream) throws -> Self {
let codedInput:CodedInputStream = CodedInputStream(stream: inputStream)
_ = try mergeFrom(codedInputStream: codedInput)
try codedInput.checkLastTagWas(value: 0)
return self
}
@discardableResult
final public func mergeFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Self {
let codedInput:CodedInputStream = CodedInputStream(stream: inputStream)
_ = try mergeFrom(codedInputStream: codedInput, extensionRegistry:extensionRegistry)
try codedInput.checkLastTagWas(value: 0)
return self
}
//Delimited Encoding/Decoding
@discardableResult
public func mergeDelimitedFrom(inputStream: InputStream) throws -> Self? {
var firstByte:UInt8 = 0
if inputStream.read(&firstByte, maxLength: 1) != 1 {
return nil
}
let rSize = try CodedInputStream.readRawVarint32(firstByte: firstByte, inputStream: inputStream)
var data = [UInt8](repeating: 0, count: Int(rSize))
_ = inputStream.read(&data, maxLength: Int(rSize))
return try mergeFrom(data: Data(data))
}
//JSON
class open func decodeToBuilder(jsonMap: Dictionary<String, Any>) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
open class func fromJSONToBuilder(data: Data) throws -> Self {
throw ProtocolBuffersError.obvious("JSON Encoding/Decoding available only in syntax=\"proto3\"")
}
}
|
apache-2.0
|
97c2f3426a1963c81749edb24cbc6885
| 35.528455 | 149 | 0.70187 | 5.251899 | false | false | false | false |
SomnusLee1988/SLAlertController
|
SLAlertController/Classes/Extensions/UIImageExtension.swift
|
2
|
2494
|
//
// UIImageExtension.swift
// Pods
//
// Created by Somnus on 16/6/24.
//
//
import Foundation
import UIKit
public extension UIImage {
convenience init(color: UIColor, size: CGSize = CGSizeMake(1, 1)) {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
func imageWithColor(color:UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let context:CGContextRef = UIGraphicsGetCurrentContext()!;
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, .Normal);
let rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextClipToMask(context, rect, self.CGImage);
color.setFill();
CGContextFillRect(context, rect);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
func imageFitInSize(viewsize:CGSize) -> UIImage
{
// calculate the fitted size
let size:CGSize = self.fitSize(self.size, inSize: viewsize);
UIGraphicsBeginImageContext(viewsize);
let dwidth:CGFloat = (viewsize.width - size.width) / 2.0;
let dheight:CGFloat = (viewsize.height - size.height) / 2.0;
let rect:CGRect = CGRectMake(dwidth, dheight, size.width, size.height);
self.drawInRect(rect);
let newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
func fitSize(thisSize:CGSize, inSize aSize:CGSize) -> CGSize
{
var scale:CGFloat;
var newsize = thisSize;
if (newsize.height > 0) && (newsize.height > aSize.height) {
scale = aSize.height / newsize.height;
newsize.width *= scale;
newsize.height *= scale;
}
if (newsize.width > 0) && (newsize.width >= aSize.width) {
scale = aSize.width / newsize.width;
newsize.width *= scale;
newsize.height *= scale;
}
return newsize;
}
}
|
mit
|
7372f6b049778e2ff7388a225f8e1566
| 30.974359 | 79 | 0.606656 | 4.576147 | false | false | false | false |
nheagy/WordPress-iOS
|
WordPress/Classes/ViewRelated/Reader/ReaderGapMarkerCell.swift
|
1
|
2451
|
import Foundation
import WordPressShared.WPStyleGuide
public class ReaderGapMarkerCell: UITableViewCell
{
@IBOutlet private weak var innerContentView: UIView!
@IBOutlet private weak var tearBackgroundView: UIView!
@IBOutlet private weak var tearMaskView: UIView!
@IBOutlet private weak var activityViewBackgroundView: UIView!
@IBOutlet private weak var activityView: UIActivityIndicatorView!
@IBOutlet private weak var button:UIButton!
public override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
private func applyStyles() {
// Background styles
selectedBackgroundView = UIView(frame: innerContentView.frame)
selectedBackgroundView?.backgroundColor = WPStyleGuide.greyLighten30()
innerContentView.backgroundColor = WPStyleGuide.greyLighten30()
tearMaskView.backgroundColor = WPStyleGuide.greyLighten30()
// Draw the tear
drawTearBackground()
activityViewBackgroundView.backgroundColor = WPStyleGuide.greyDarken10()
activityViewBackgroundView.layer.cornerRadius = 4.0
activityViewBackgroundView.layer.masksToBounds = true
// Button style
let text = NSLocalizedString("Load more posts", comment: "A short label. A call to action to load more posts.")
button.setTitle(text, forState: .Normal)
WPStyleGuide.applyGapMarkerButtonStyle(button)
button.layer.cornerRadius = 4.0
button.layer.masksToBounds = true
button.sizeToFit()
// Disable button interactions so the full cell handles the tap.
button.userInteractionEnabled = false
}
public func animateActivityView(animate:Bool) {
button.hidden = animate;
if animate {
activityView.startAnimating()
} else {
activityView.stopAnimating()
}
}
public override func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
button.highlighted = highlighted
if (highlighted) {
// Redraw the backgrounds when highlighted
drawTearBackground()
tearMaskView.backgroundColor = WPStyleGuide.greyLighten30()
}
}
func drawTearBackground() {
let tearImage = UIImage(named: "background-reader-tear")
tearBackgroundView.backgroundColor = UIColor(patternImage: tearImage!)
}
}
|
gpl-2.0
|
f5f145eac2ea3423c079f88b4b2f0fc0
| 35.044118 | 120 | 0.693594 | 5.545249 | false | false | false | false |
ylovesy/CodeFun
|
mayu/LetterCombinationsOfAPhoneNumber.swift
|
1
|
1546
|
import Foundation
/*
17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
*/
private class Solution {
func letterCombinations(_ digits: String) -> [String] {
var str = digits.replacingOccurrences(of: "0", with: "")
str = str.replacingOccurrences(of: "1", with: "")
let dic = ["2" : ["a", "b", "c"],
"3" : ["d", "e", "f"],
"4" : ["g", "h", "i"],
"5" : ["j", "k", "l"],
"6" : ["m", "n", "o"],
"7" : ["p", "q", "r", "s"],
"8" : ["t", "u", "v"],
"9" : ["w", "x", "y", "z"],]
var resAry = [String]()
for ch in str.characters {
if dic["\(ch)"] == nil {
continue
}
let tempAry = dic["\(ch)"]!
if resAry.isEmpty {
for str in tempAry {
resAry.append(str)
}
} else {
var newAry = [String]()
for resStr in resAry {
for str in tempAry {
newAry.append(resStr + str)
}
}
resAry = newAry
}
}
return resAry
}
}
|
apache-2.0
|
9ac70a9597db0ba451960637353210ec
| 32.608696 | 99 | 0.411384 | 3.953964 | false | false | false | false |
Eric217/-OnSale
|
打折啦/打折啦/RightLabelCell.swift
|
1
|
2176
|
//
// RightLabelCell.swift
// 打折啦
//
// Created by Eric on 31/08/2017.
// Copyright © 2017 INGStudio. All rights reserved.
//
import Foundation
class RightLabelCell: UITableViewCell {
var rightLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
rightLabel = UILabel()
rightLabel.textAlignment = .right
accessoryType = .disclosureIndicator
addSubview(rightLabel)
rightLabel.snp.makeConstraints{ m in
m.right.equalTo(-31)
m.centerY.height.equalTo(self)
m.width.equalTo(ScreenWidth*2/3+10)
}
}
///black, 17 by default
func setRightText(_ str: String, size: CGFloat = 17, color: UIColor = .black) {
rightLabel.text = str
rightLabel.font = UIFont.systemFont(ofSize: size)
rightLabel.textColor = color
}
///gray by default
func setLeftText(_ str: String, color: UIColor = .gray) {
textLabel?.text = str
textLabel?.textColor = color
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class RightLabelCell2: ELPersonSmallCell {
var rightLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
rightLabel = UILabel()
rightLabel.textAlignment = .right
accessoryType = .disclosureIndicator
addSubview(rightLabel)
rightLabel.snp.makeConstraints{ m in
m.right.equalTo(-35)
m.centerY.height.equalTo(self)
m.width.equalTo(ScreenWidth*2/3+10)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setRightText(_ str: String, size: CGFloat = 17, color: UIColor = .black) {
rightLabel.text = str
rightLabel.font = UIFont.systemFont(ofSize: size)
rightLabel.textColor = color
}
}
|
apache-2.0
|
15fafa8fee6453469dbbbd966241a12a
| 25.45122 | 83 | 0.626556 | 4.54717 | false | false | false | false |
bsmith11/ScoreReporter
|
ScoreReporterCore/ScoreReporterCore/Services/DateService.swift
|
1
|
2083
|
//
// DateService.swift
// ScoreReporter
//
// Created by Bradley Smith on 7/18/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
public struct DateService {
fileprivate static let eventDateFormat = "M/d/y h:mm:ss a"
fileprivate static let gameDateFormat = "M/d/y"
fileprivate static let gameTimeFormat = "h:mm a"
fileprivate static let gameStartDateFullFormat = "E h:mm a"
fileprivate static let eventSearchDateFormat = "MMM dd, yyyy"
fileprivate static let eventDetailsDateFormat = "MMM dd"
public static let eventDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = eventDateFormat
return dateFormatter
}()
public static let eventSearchDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = eventSearchDateFormat
return dateFormatter
}()
public static let gameDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = gameDateFormat
return dateFormatter
}()
public static let gameTimeFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = gameTimeFormat
return dateFormatter
}()
public static let gameStartDateFullFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = gameStartDateFullFormat
return dateFormatter
}()
public static let eventDetailsDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = eventDetailsDateFormat
return dateFormatter
}()
}
|
mit
|
f853ce424acbbddd8b7221954150f596
| 31.030769 | 67 | 0.695965 | 5.421875 | false | false | false | false |
FreddyZeng/Charts
|
Source/Charts/Charts/BarLineChartViewBase.swift
|
1
|
69546
|
//
// BarLineChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
open class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate
{
/// the maximum number of entries to which values will be drawn
/// (entry numbers greater than this value will cause value-labels to disappear)
internal var _maxVisibleCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragXEnabled = true
private var _dragYEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
@objc open var gridBackgroundColor = NSUIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
@objc open var borderColor = NSUIColor.black
@objc open var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
@objc open var drawGridBackgroundEnabled = false
/// When enabled, the borders rectangle will be rendered.
/// If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
@objc open var drawBordersEnabled = false
/// When enabled, the values will be clipped to contentRect, otherwise they can bleed outside the content rect.
@objc open var clipValuesToContentEnabled: Bool = false
/// When disabled, the data and/or highlights will not be clipped to contentRect. Disabling this option can
/// be useful, when the data lies fully within the content rect, but is drawn in such a way (such as thick lines)
/// that there is unwanted clipping.
@objc open var clipDataToContentEnabled: Bool = true
/// Sets the minimum offset (padding) around the chart, defaults to 10
@objc open var minOffset = CGFloat(10.0)
/// Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change)
/// **default**: false
@objc open var keepPositionOnRotation: Bool = false
/// The left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
@objc open internal(set) var leftAxis = YAxis(position: .left)
/// The right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
@objc open internal(set) var rightAxis = YAxis(position: .right)
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var leftYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: leftAxis, transformer: _leftAxisTransformer)
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var rightYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: rightAxis, transformer: _rightAxisTransformer)
internal var _leftAxisTransformer: Transformer!
internal var _rightAxisTransformer: Transformer!
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of XAxisRenderer
@objc open lazy var xAxisRenderer = XAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
internal var _tapGestureRecognizer: NSUITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: NSUITapGestureRecognizer!
#if !os(tvOS)
internal var _pinchGestureRecognizer: NSUIPinchGestureRecognizer!
#endif
internal var _panGestureRecognizer: NSUIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
self.highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
_doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognized(_:)))
_doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2
_panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized(_:)))
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
_panGestureRecognizer.isEnabled = _dragXEnabled || _dragYEnabled
#if !os(tvOS)
_pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.pinchGestureRecognized(_:)))
_pinchGestureRecognizer.delegate = self
self.addGestureRecognizer(_pinchGestureRecognizer)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
// Saving current position of chart.
var oldPoint: CGPoint?
if (keepPositionOnRotation && (keyPath == "frame" || keyPath == "bounds"))
{
oldPoint = viewPortHandler.contentRect.origin
getTransformer(forAxis: .left).pixelToValues(&oldPoint!)
}
// Superclass transforms chart.
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
// Restoring old position of chart
if var newPoint = oldPoint , keepPositionOnRotation
{
getTransformer(forAxis: .left).pointValueToPixel(&newPoint)
viewPortHandler.centerViewPort(pt: newPoint, chart: self)
}
else
{
viewPortHandler.refresh(newMatrix: viewPortHandler.touchMatrix, chart: self, invalidate: true)
}
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
guard data != nil, let renderer = renderer else { return }
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
// execute all drawing commands
drawGridBackground(context: context)
if _autoScaleMinMaxEnabled
{
autoScale()
}
if leftAxis.isEnabled
{
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
}
if rightAxis.isEnabled
{
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
}
if _xAxis.isEnabled
{
xAxisRenderer.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false)
}
xAxisRenderer.renderAxisLine(context: context)
leftYAxisRenderer.renderAxisLine(context: context)
rightYAxisRenderer.renderAxisLine(context: context)
// The renderers are responsible for clipping, to account for line-width center etc.
xAxisRenderer.renderGridLines(context: context)
leftYAxisRenderer.renderGridLines(context: context)
rightYAxisRenderer.renderGridLines(context: context)
if _xAxis.isEnabled && _xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
context.saveGState()
// make sure the data cannot be drawn outside the content-rect
if clipDataToContentEnabled {
context.clip(to: _viewPortHandler.contentRect)
}
renderer.drawData(context: context)
// if highlighting is enabled
if (valuesToHighlight())
{
renderer.drawHighlighted(context: context, indices: _indicesToHighlight)
}else {
renderer.drawHighlighted(context: context, indices: [])
}
context.restoreGState()
renderer.drawExtras(context: context)
if _xAxis.isEnabled && !_xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && !leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && !rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
xAxisRenderer.renderAxisLabels(context: context)
leftYAxisRenderer.renderAxisLabels(context: context)
rightYAxisRenderer.renderAxisLabels(context: context)
if clipValuesToContentEnabled
{
context.saveGState()
context.clip(to: _viewPortHandler.contentRect)
renderer.drawValues(context: context)
context.restoreGState()
}
else
{
renderer.drawValues(context: context)
}
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
private var _autoScaleLastLowestVisibleX: Double?
private var _autoScaleLastHighestVisibleX: Double?
/// Performs auto scaling of the axis by recalculating the minimum and maximum y-values based on the entries currently in view.
internal func autoScale()
{
guard let data = _data
else { return }
data.calcMinMaxY(fromX: self.lowestVisibleX, toX: self.highestVisibleX)
_xAxis.calculate(min: data.xMin, max: data.xMax)
// calculate axis range (min / max) according to provided data
if leftAxis.isEnabled
{
leftAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left))
}
if rightAxis.isEnabled
{
rightAxis.calculate(min: data.getYMin(axis: .right), max: data.getYMax(axis: .right))
}
calculateOffsets()
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(rightAxis.axisRange), chartYMin: rightAxis._axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(leftAxis.axisRange), chartYMin: leftAxis._axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(inverted: rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(inverted: leftAxis.isInverted)
}
open override func notifyDataSetChanged()
{
renderer?.initBuffers()
calcMinMax()
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
if let data = _data
{
xAxisRenderer.computeAxis(
min: _xAxis._axisMinimum,
max: _xAxis._axisMaximum,
inverted: false)
if _legend !== nil
{
legendRenderer?.computeLegend(data: data)
}
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
// calculate / set x-axis range
_xAxis.calculate(min: _data?.xMin ?? 0.0, max: _data?.xMax ?? 0.0)
// calculate axis range (min / max) according to provided data
leftAxis.calculate(min: _data?.getYMin(axis: .left) ?? 0.0, max: _data?.getYMax(axis: .left) ?? 0.0)
rightAxis.calculate(min: _data?.getYMin(axis: .right) ?? 0.0, max: _data?.getYMax(axis: .right) ?? 0.0)
}
internal func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat)
{
// setup offsets for legend
if _legend !== nil && _legend.isEnabled && !_legend.drawInside
{
switch _legend.orientation
{
case .vertical:
switch _legend.horizontalAlignment
{
case .left:
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .right:
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .center:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
default:
break
}
}
case .horizontal:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
offsetTop += xAxis.labelRotatedHeight
}
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
offsetBottom += xAxis.labelRotatedHeight
}
default:
break
}
}
}
}
internal override func calculateOffsets()
{
if !_customViewPortEnabled
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
calculateLegendOffsets(offsetLeft: &offsetLeft,
offsetTop: &offsetTop,
offsetRight: &offsetRight,
offsetBottom: &offsetBottom)
// offsets for y-labels
if leftAxis.needsOffset
{
offsetLeft += leftAxis.requiredSize().width
}
if rightAxis.needsOffset
{
offsetRight += rightAxis.requiredSize().width
}
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset
// offsets for x-labels
if xAxis.labelPosition == .bottom
{
offsetBottom += xlabelheight
}
else if xAxis.labelPosition == .top
{
offsetTop += xlabelheight
}
else if xAxis.labelPosition == .bothSided
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// draws the grid background
internal func drawGridBackground(context: CGContext)
{
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.saveGState()
}
if drawGridBackgroundEnabled
{
// draw the grid background
context.setFillColor(gridBackgroundColor.cgColor)
context.fill(_viewPortHandler.contentRect)
}
if drawBordersEnabled
{
context.setLineWidth(borderLineWidth)
context.setStrokeColor(borderColor.cgColor)
context.stroke(_viewPortHandler.contentRect)
}
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.restoreGState()
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case both
case x
case y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.both
private var _closestDataSetToTouch: IChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: NSUIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: TimeInterval = 0.0
private var _decelerationDisplayLink: NSUIDisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if !isHighLightPerTapEnabled { return }
let h = getHighlightByTouchPoint(recognizer.location(in: self))
if h === nil || h == self.lastHighlighted
{
lastHighlighted = nil
highlightValue(nil, callDelegate: true)
}
else
{
lastHighlighted = h
highlightValue(h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if _data !== nil && _doubleTapToZoomEnabled && (data?.entryCount ?? 0) > 0
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
self.zoom(scaleX: isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y)
}
}
}
#if !os(tvOS)
@objc private func pinchGestureRecognized(_ recognizer: NSUIPinchGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began
{
stopDeceleration()
if _data !== nil &&
(_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)
{
_isScaling = true
if _pinchZoomEnabled
{
_gestureScaleAxis = .both
}
else
{
let x = abs(recognizer.location(in: self).x - recognizer.nsuiLocationOfTouch(1, inView: self).x)
let y = abs(recognizer.location(in: self).y - recognizer.nsuiLocationOfTouch(1, inView: self).y)
if _scaleXEnabled != _scaleYEnabled
{
_gestureScaleAxis = _scaleXEnabled ? .x : .y
}
else
{
_gestureScaleAxis = x > y ? .x : .y
}
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended ||
recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isScaling
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
let isZoomingOut = (recognizer.nsuiScale < 1)
var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY
if _isScaling
{
canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .x)
canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .y)
if canZoomMoreX || canZoomMoreY
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0
let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0
var matrix = CGAffineTransform(translationX: location.x, y: location.y)
matrix = matrix.scaledBy(x: scaleX, y: scaleY)
matrix = matrix.translatedBy(x: -location.x, y: -location.y)
matrix = _viewPortHandler.touchMatrix.concatenating(matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if delegate !== nil
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.nsuiScale = 1.0
}
}
}
#endif
@objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began && recognizer.nsuiNumberOfTouches() > 0
{
stopDeceleration()
if _data === nil || !self.isDragEnabled
{ // If we have no data, we have nothing to pan and no data to highlight
return
}
// If drag is enabled and we are in a position where there's something to drag:
// * If we're zoomed in, then obviously we have something to drag.
// * If we have a drag offset - we always have something to drag
if !self.hasNoDragOffset || !self.isFullyZoomedOut
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(point: recognizer.nsuiLocationOfTouch(0, inView: self))
var translation = recognizer.translation(in: self)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let didUserDrag = translation.x != 0.0 || translation.y != 0.0
// Check to see if user dragged at all and if so, can the chart be dragged by the given amount
if didUserDrag && !performPanChange(translation: translation)
{
if _outerScrollView !== nil
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if _outerScrollView !== nil
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.nsuiIsScrollEnabled = false
}
}
_lastPanPoint = recognizer.translation(in: self)
}
else if self.isHighlightPerDragEnabled
{
// We will only handle highlights on NSUIGestureRecognizerState.Changed
_isDragging = false
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
if _isDragging
{
let originalTranslation = recognizer.translation(in: self)
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let _ = performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if isHighlightPerDragEnabled
{
let h = getHighlightByTouchPoint(recognizer.location(in: self))
let lastHighlighted = self.lastHighlighted
if h != lastHighlighted
{
self.lastHighlighted = h
self.highlightValue(h, callDelegate: true)
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isDragging
{
if recognizer.state == NSUIGestureRecognizerState.ended && isDragDecelerationEnabled
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocity(in: self)
_decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(BarLineChartViewBase.decelerationLoop))
_decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
_isDragging = false
}
if _outerScrollView !== nil
{
_outerScrollView?.nsuiIsScrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(translation: CGPoint) -> Bool
{
var translation = translation
if isTouchInverted()
{
if self is HorizontalBarChartView
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
let originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransform(translationX: translation.x, y: translation.y)
matrix = originalMatrix.concatenating(matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if delegate !== nil
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
private func isTouchInverted() -> Bool
{
return isAnyAxisInverted &&
_closestDataSetToTouch !== nil &&
getAxis(_closestDataSetToTouch.axisDependency).isInverted
}
@objc open func stopDeceleration()
{
if _decelerationDisplayLink !== nil
{
_decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
let distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if !performPanChange(translation: distance)
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
private func nsuiGestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool
{
if gestureRecognizer == _panGestureRecognizer
{
let velocity = _panGestureRecognizer.velocity(in: self)
if _data === nil || !isDragEnabled ||
(self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) ||
(!_dragYEnabled && fabs(velocity.y) > fabs(velocity.x)) ||
(!_dragXEnabled && fabs(velocity.y) < fabs(velocity.x))
{
return false
}
}
else
{
#if !os(tvOS)
if gestureRecognizer == _pinchGestureRecognizer
{
if _data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)
{
return false
}
}
#endif
}
return true
}
#if !os(OSX)
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
{
if !super.gestureRecognizerShouldBegin(gestureRecognizer)
{
return false
}
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
#if os(OSX)
public func gestureRecognizerShouldBegin(gestureRecognizer: NSGestureRecognizer) -> Bool
{
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
open func gestureRecognizer(_ gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: NSUIGestureRecognizer) -> Bool
{
#if !os(tvOS)
if ((gestureRecognizer is NSUIPinchGestureRecognizer && otherGestureRecognizer is NSUIPanGestureRecognizer) ||
(gestureRecognizer is NSUIPanGestureRecognizer && otherGestureRecognizer is NSUIPinchGestureRecognizer))
{
return true
}
#endif
if gestureRecognizer is NSUIPanGestureRecognizer,
otherGestureRecognizer is NSUIPanGestureRecognizer,
gestureRecognizer == _panGestureRecognizer
{
var scrollView = self.superview
while scrollView != nil && !(scrollView is NSUIScrollView)
{
scrollView = scrollView?.superview
}
// If there is two scrollview together, we pick the superview of the inner scrollview.
// In the case of UITableViewWrepperView, the superview will be UITableView
if let superViewOfScrollView = scrollView?.superview,
superViewOfScrollView is NSUIScrollView
{
scrollView = superViewOfScrollView
}
var foundScrollView = scrollView as? NSUIScrollView
if !(foundScrollView?.nsuiIsScrollEnabled ?? true)
{
foundScrollView = nil
}
let scrollViewPanGestureRecognizer = foundScrollView?.nsuiGestureRecognizers?.first {
$0 is NSUIPanGestureRecognizer
}
if otherGestureRecognizer === scrollViewPanGestureRecognizer
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center.
@objc open func zoomIn()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomIn(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center.
@objc open func zoomOut()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomOut(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out to original size.
@objc open func resetZoom()
{
let matrix = _viewPortHandler.resetZoom()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter x:
/// - parameter y:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
x: CGFloat,
y: CGFloat)
{
let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor.
/// x and y are the values (**not pixels**) of the zoom center.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let job = ZoomViewJob(
viewPortHandler: viewPortHandler,
scaleX: scaleX,
scaleY: scaleY,
xValue: xValue,
yValue: yValue,
transformer: getTransformer(forAxis: axis),
axis: axis,
view: self)
addViewportJob(job)
}
/// Zooms to the center of the chart with the given scale factor.
///
/// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis:
@objc open func zoomToCenter(
scaleX: CGFloat,
scaleY: CGFloat)
{
let center = centerOffsets
let matrix = viewPortHandler.zoom(
scaleX: scaleX,
scaleY: scaleY,
x: center.x,
y: -center.y)
viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let origin = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let job = AnimatedZoomViewJob(
viewPortHandler: viewPortHandler,
transformer: getTransformer(forAxis: axis),
view: self,
yAxis: getAxis(axis),
xAxisRange: _xAxis.axisRange,
scaleX: scaleX,
scaleY: scaleY,
xOrigin: viewPortHandler.scaleX,
yOrigin: viewPortHandler.scaleY,
zoomCenterX: CGFloat(xValue),
zoomCenterY: CGFloat(yValue),
zoomOriginX: origin.x,
zoomOriginY: origin.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - parameter scaleX:
/// - parameter scaleY:
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
@objc open func fitScreen()
{
let matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
@objc open func setScaleMinima(_ scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
@objc open var visibleXRange: Double
{
return abs(highestVisibleX - lowestVisibleX)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zooming out allowed).
///
/// If this is e.g. set to 10, no more than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMaximum(_ maxXRange: Double)
{
let xScale = _xAxis.axisRange / maxXRange
_viewPortHandler.setMinimumScaleX(CGFloat(xScale))
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
///
/// If this is e.g. set to 10, no less than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMinimum(_ minXRange: Double)
{
let xScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMaximumScaleX(CGFloat(xScale))
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
///
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRange(minXRange: Double, maxXRange: Double)
{
let minScale = _xAxis.axisRange / maxXRange
let maxScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMinMaxScaleX(
minScaleX: CGFloat(minScale),
maxScaleX: CGFloat(maxScale))
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMaximum(_ maxYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinimumScaleY(CGFloat(yScale))
}
/// Sets the size of the area (range on the y-axis) that should be minimum visible at once, no further zooming in possible.
///
/// - parameter yRange:
/// - parameter axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMinimum(_ minYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / minYRange
_viewPortHandler.setMaximumScaleY(CGFloat(yScale))
}
/// Limits the maximum and minimum y range that can be visible by pinching and zooming.
///
/// - parameter minYRange:
/// - parameter maxYRange:
/// - parameter axis:
@objc open func setVisibleYRange(minYRange: Double, maxYRange: Double, axis: YAxis.AxisDependency)
{
let minScale = getAxisRange(axis: axis) / minYRange
let maxScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinMaxScaleY(minScaleY: CGFloat(minScale), maxScaleY: CGFloat(maxScale))
}
/// Moves the left side of the current viewport to the specified x-value.
/// This also refreshes the chart by calling setNeedsDisplay().
@objc open func moveViewToX(_ xValue: Double)
{
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: 0.0,
transformer: getTransformer(forAxis: .left),
view: self)
addViewportJob(job)
}
/// Centers the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewToY(_ yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: 0.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewTo(xValue: Double, yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// This will move the center of the current viewport to the specified x-value and y-value.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: - which axis should be used as a reference for the y-axis
@objc open func centerViewTo(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - parameter xValue:
/// - parameter yValue:
/// - parameter axis: which axis should be used as a reference for the y-axis
/// - parameter duration: the duration of the animation in seconds
/// - parameter easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`.
@objc open func setViewPortOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if Thread.isMainThread
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
DispatchQueue.main.async(execute: {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically.
@objc open func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// - returns: The range of the specified axis.
@objc open func getAxisRange(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
return leftAxis.axisRange
}
else
{
return rightAxis.axisRange
}
}
/// - returns: The position (in pixels) the provided Entry has inside the chart view
@objc open func getPosition(entry e: ChartDataEntry, axis: YAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y))
getTransformer(forAxis: axis).pointValueToPixel(&vals)
return vals
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var dragEnabled: Bool
{
get
{
return _dragXEnabled || _dragYEnabled
}
set
{
_dragYEnabled = newValue
_dragXEnabled = newValue
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var isDragEnabled: Bool
{
return dragEnabled
}
/// is dragging on the X axis enabled?
@objc open var dragXEnabled: Bool
{
get
{
return _dragXEnabled
}
set
{
_dragXEnabled = newValue
}
}
/// is dragging on the Y axis enabled?
@objc open var dragYEnabled: Bool
{
get
{
return _dragYEnabled
}
set
{
_dragYEnabled = newValue
}
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
@objc open func setScaleEnabled(_ enabled: Bool)
{
if _scaleXEnabled != enabled || _scaleYEnabled != enabled
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
@objc open var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if _scaleXEnabled != newValue
{
_scaleXEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if _scaleYEnabled != newValue
{
_scaleYEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var isScaleXEnabled: Bool { return scaleXEnabled }
@objc open var isScaleYEnabled: Bool { return scaleYEnabled }
/// flag that indicates if double tap zoom is enabled or not
@objc open var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if _doubleTapToZoomEnabled != newValue
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
}
}
}
/// **default**: true
/// - returns: `true` if zooming via double-tap is enabled `false` ifnot.
@objc open var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
@objc open var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a `NSUIScrollView`
///
/// **default**: true
@objc open var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// **default**: true
/// - returns: `true` if drawing the grid background is enabled, `false` ifnot.
@objc open var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// **default**: false
/// - returns: `true` if drawing the borders rectangle is enabled, `false` ifnot.
@objc open var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// - returns: The x and y values in the chart at the given touch point
/// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// `getPixelsForValues(...)`.
@objc open func valueForTouchPoint(point pt: CGPoint, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).valueForTouchPoint(pt)
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to `valueForTouchPoint(...)`.
@objc open func pixelForValues(x: Double, y: Double, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).pixelForValues(x: x, y: y)
}
/// - returns: The Entry object displayed at the touched position of the chart
@objc open func getEntryByTouchPoint(point pt: CGPoint) -> ChartDataEntry!
{
if let h = getHighlightByTouchPoint(pt)
{
return _data!.entryForHighlight(h)
}
return nil
}
/// - returns: The DataSet object displayed at the touched position of the chart
@objc open func getDataSetByTouchPoint(point pt: CGPoint) -> IBarLineScatterCandleBubbleChartDataSet?
{
let h = getHighlightByTouchPoint(pt)
if h !== nil
{
return _data?.getDataSetByIndex(h!.dataSetIndex) as? IBarLineScatterCandleBubbleChartDataSet
}
return nil
}
/// - returns: The current x-scale factor
@objc open var scaleX: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// - returns: The current y-scale factor
@objc open var scaleY: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
@objc open var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut }
/// - returns: The y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
@objc open func getAxis(_ axis: YAxis.AxisDependency) -> YAxis
{
if axis == .left
{
return leftAxis
}
else
{
return rightAxis
}
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately
@objc open var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if _pinchZoomEnabled != newValue
{
_pinchZoomEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
/// **default**: false
/// - returns: `true` if pinch-zoom is enabled, `false` ifnot
@objc open var isPinchZoomEnabled: Bool { return pinchZoomEnabled }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
@objc open func setDragOffsetX(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
@objc open func setDragOffsetY(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// - returns: `true` if both drag offsets (x and y) are zero or smaller.
@objc open var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset }
open override var chartYMax: Double
{
return max(leftAxis._axisMaximum, rightAxis._axisMaximum)
}
open override var chartYMin: Double
{
return min(leftAxis._axisMinimum, rightAxis._axisMinimum)
}
/// - returns: `true` if either the left or the right or both axes are inverted.
@objc open var isAnyAxisInverted: Bool
{
return leftAxis.isInverted || rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
@objc open var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled }
set { _autoScaleMinMaxEnabled = newValue }
}
/// **default**: false
/// - returns: `true` if auto scaling on the y axis is enabled.
@objc open var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled }
/// Sets a minimum width to the specified y axis.
@objc open func setYAxisMinWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.minWidth = width
}
else
{
rightAxis.minWidth = width
}
}
/// **default**: 0.0
/// - returns: The (custom) minimum width of the specified Y axis.
@objc open func getYAxisMinWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.minWidth
}
else
{
return rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
@objc open func setYAxisMaxWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.maxWidth = width
}
else
{
rightAxis.maxWidth = width
}
}
/// Zero (0.0) means there's no maximum width
///
/// **default**: 0.0 (no maximum specified)
/// - returns: The (custom) maximum width of the specified Y axis.
@objc open func getYAxisMaxWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.maxWidth
}
else
{
return rightAxis.maxWidth
}
}
/// - returns the width of the specified y axis.
@objc open func getYAxisWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.requiredSize().width
}
else
{
return rightAxis.requiredSize().width
}
}
// MARK: - BarLineScatterCandleBubbleChartDataProvider
/// - returns: The Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
open func getTransformer(forAxis axis: YAxis.AxisDependency) -> Transformer
{
if axis == .left
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
/// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled
open override var maxVisibleCount: Int
{
get
{
return _maxVisibleCount
}
set
{
_maxVisibleCount = newValue
}
}
open func isInverted(axis: YAxis.AxisDependency) -> Bool
{
return getAxis(axis).isInverted
}
/// - returns: The lowest x-index (value on the x-axis) that is still visible on he chart.
open var lowestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentLeft,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return max(xAxis._axisMinimum, Double(pt.x))
}
/// - returns: The highest x-index (value on the x-axis) that is still visible on the chart.
open var highestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentRight,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return min(xAxis._axisMaximum, Double(pt.x))
}
}
|
apache-2.0
|
adc5843df6df37f053d23435270f85de
| 34.885449 | 238 | 0.585857 | 5.544165 | false | false | false | false |
P0ed/PowerCore
|
Carthage/Checkouts/Fx/Source/Disposable.swift
|
1
|
5860
|
//
// Disposable.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents something that can be “disposed,” usually associated with freeing
/// resources or canceling work.
public protocol Disposable: class {
/// Whether this disposable has been disposed already.
var disposed: Bool { get }
func dispose()
}
/// A disposable that only flips `disposed` upon disposal, and performs no other
/// work.
public final class SimpleDisposable: Disposable {
fileprivate let _disposed = Atomic(false)
public var disposed: Bool {
return _disposed.value
}
public init() {}
public func dispose() {
_disposed.value = true
}
}
/// A disposable that will run an action upon disposal.
public final class ActionDisposable: Disposable {
fileprivate let action: Atomic<(() -> ())?>
public var disposed: Bool {
return action.value == nil
}
/// Initializes the disposable to run the given action upon disposal.
public init(action: @escaping () -> ()) {
self.action = Atomic(action)
}
public func dispose() {
let oldAction = action.swap(nil)
oldAction?()
}
}
/// A disposable that will dispose of any number of other disposables.
public final class CompositeDisposable: Disposable {
fileprivate let disposables: Atomic<Bag<Disposable>?>
/// Represents a handle to a disposable previously added to a
/// CompositeDisposable.
public final class DisposableHandle {
fileprivate let bagToken: Atomic<RemovalToken?>
fileprivate weak var disposable: CompositeDisposable?
fileprivate static let empty = DisposableHandle()
fileprivate init() {
self.bagToken = Atomic(nil)
}
fileprivate init(bagToken: RemovalToken, disposable: CompositeDisposable) {
self.bagToken = Atomic(bagToken)
self.disposable = disposable
}
/// Removes the pointed-to disposable from its CompositeDisposable.
///
/// This is useful to minimize memory growth, by removing disposables
/// that are no longer needed.
public func remove() {
if let token = bagToken.swap(nil) {
_ = disposable?.disposables.modify { bag in
guard let immutableBag = bag else { return nil }
var mutableBag = immutableBag
mutableBag.removeValueForToken(token)
return mutableBag
}
}
}
}
public var disposed: Bool {
return disposables.value == nil
}
/// Initializes a CompositeDisposable containing the given sequence of
/// disposables.
public init<S: Sequence>(_ disposables: S) where S.Iterator.Element == Disposable {
var bag: Bag<Disposable> = Bag()
for disposable in disposables {
_ = bag.insert(disposable)
}
self.disposables = Atomic(bag)
}
/// Initializes an empty CompositeDisposable.
public convenience init() {
self.init([])
}
public func dispose() {
if let ds = disposables.swap(nil) {
for d in ds.reversed() {
d.dispose()
}
}
}
/// Adds the given disposable to the list, then returns a handle which can
/// be used to opaquely remove the disposable later (if desired).
public func addDisposable(_ d: Disposable?) -> DisposableHandle {
guard let d = d else {
return DisposableHandle.empty
}
var handle: DisposableHandle? = nil
disposables.modify { ds in
guard let immutableDs = ds else { return nil }
var mutableDs = immutableDs
let token = mutableDs.insert(d)
handle = DisposableHandle(bagToken: token, disposable: self)
return mutableDs
}
if let handle = handle {
return handle
} else {
d.dispose()
return DisposableHandle.empty
}
}
/// Adds an ActionDisposable to the list.
public func addDisposable(_ action: @escaping () -> ()) -> DisposableHandle {
return addDisposable(ActionDisposable(action: action))
}
}
/// A disposable that, upon deinitialization, will automatically dispose of
/// another disposable.
public final class ScopedDisposable: Disposable {
/// The disposable which will be disposed when the ScopedDisposable
/// deinitializes.
public let innerDisposable: Disposable
public var disposed: Bool {
return innerDisposable.disposed
}
/// Initializes the receiver to dispose of the argument upon
/// deinitialization.
public init(_ disposable: Disposable) {
innerDisposable = disposable
}
deinit {
dispose()
}
public func dispose() {
innerDisposable.dispose()
}
}
/// A disposable that will optionally dispose of another disposable.
public final class SerialDisposable: Disposable {
fileprivate struct State {
var innerDisposable: Disposable? = nil
var disposed = false
}
fileprivate let state = Atomic(State())
public var disposed: Bool {
return state.value.disposed
}
/// The inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var innerDisposable: Disposable? {
get {
return state.value.innerDisposable
}
set(d) {
let oldState = state.modify { state in
var mutableState = state
mutableState.innerDisposable = d
return mutableState
}
oldState.innerDisposable?.dispose()
if oldState.disposed {
d?.dispose()
}
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
public init(_ disposable: Disposable? = nil) {
innerDisposable = disposable
}
public func dispose() {
let orig = state.swap(State(innerDisposable: nil, disposed: true))
orig.innerDisposable?.dispose()
}
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(observer)
///
@discardableResult
public func +=(lhs: CompositeDisposable, rhs: Disposable?) -> CompositeDisposable.DisposableHandle {
return lhs.addDisposable(rhs)
}
|
mit
|
c6e2ce4bdaccb79e8883fcd5a5bcd979
| 23.708861 | 100 | 0.704577 | 3.956757 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Model/CGSSCard.swift
|
2
|
19190
|
//
// CGSSCard.swift
// CGSSFoundation
//
// Created by zzk on 16/6/14.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
extension CGSSCard {
var properPotential: Potential {
return Potential(vocal: 10, dance: 10, visual: 10, skill: 5, life: 0)
// switch attributeType {
// case CGSSAttributeTypes.vocal:
// return CGSSPotential(vocalLevel: 10, danceLevel: 10, visualLevel: 5, lifeLevel: 0)
// case CGSSAttributeTypes.dance:
// return CGSSPotential(vocalLevel: 5, danceLevel: 10, visualLevel: 10, lifeLevel: 0)
// case CGSSAttributeTypes.visual:
// return CGSSPotential(vocalLevel: 10, danceLevel: 5, visualLevel: 10, lifeLevel: 0)
// default:
// return CGSSPotential.zero
// }
}
func properPotentialByLevel(_ level: Int) -> Potential {
let first = min(level, 10)
let second = max(min(level - 10, 10), 0)
let third = max(min(level - 20, 10), 0)
let fourth = max(min(level - 30, 10), 0)
switch attributeType {
case CGSSAttributeTypes.vocal:
return Potential(vocal: first, dance: second, visual: third, skill: fourth, life: 0)
case CGSSAttributeTypes.dance:
return Potential(vocal: third, dance: first, visual: second, skill: fourth, life: 0)
case CGSSAttributeTypes.visual:
return Potential(vocal: second, dance: third, visual: first, skill: fourth, life: 0)
default:
return Potential.zero
}
}
}
extension CGSSCard {
var attShort: String {
switch attribute {
case "cute":
return "Cu"
case "cool":
return "Co"
case "passion":
return "Pa"
default:
return "unknown"
}
}
var attColor: UIColor {
switch attribute {
case "cute":
return .cute
case "cool":
return .cool
case "passion":
return .passion
default:
return .allType
}
}
var gachaType: CGSSAvailableTypes {
var type: CGSSAvailableTypes
if availableType != nil {
type = availableType!
}
else if CGSSGameResource.shared.gachaAvailabelList.contains(seriesId) { type = .normal }
else if CGSSGameResource.shared.fesAvailabelList.contains(seriesId) { type = .fes }
else if CGSSGameResource.shared.timeLimitAvailableList.contains(seriesId) { type = .limit }
else if CGSSGameResource.shared.eventAvailabelList.contains(seriesId) { type = .event }
else { type = .free }
availableType = type
return type
}
var chara: CGSSChar? {
if let id = charaId {
return CGSSDAO.shared.findCharById(id)
}
return nil
}
var leaderSkill: CGSSLeaderSkill? {
if let id = leaderSkillId {
return CGSSDAO.shared.findLeaderSkillById(id)
}
return nil
}
var skill: CGSSSkill? {
if let id = skillId {
return CGSSDAO.shared.findSkillById(id)
}
return nil
}
@objc dynamic var update_id: Int {
if let firstAvailable = firstAvailableAt {
return Int(firstAvailable.timeIntervalSince1970) + id
} else {
return id
}
}
// 用户排序的动态属性
@objc dynamic var sAlbumId: Int {
return albumId
}
@objc dynamic var sRarity: Int {
return rarity.rarity
}
//
@objc dynamic var dance: Int {
if let base = danceMax, let bonus = bonusDance {
return base + bonus
}
return 0
}
@objc dynamic var vocal: Int {
if let base = vocalMax, let bonus = bonusVocal {
return base + bonus
}
return 0
}
@objc dynamic var visual: Int {
if let base = visualMax, let bonus = bonusVisual {
return base + bonus
}
return 0
}
@objc dynamic var life: Int {
if let base = hpMax, let bonus = bonusHp {
return base + bonus
}
return 0
}
var appeal: CGSSAppeal {
return CGSSAppeal(visual: visual, vocal: vocal, dance: dance, life: life)
}
@objc dynamic var overall: Int {
if let base = overallMax, let bonus = overallBonus {
return base + bonus
}
return 0
}
// 用于filter的部分属性
var rarityType: CGSSRarityTypes {
return CGSSRarityTypes.init(rarity: rarity.rarity - 1)
}
var skillType: CGSSSkillTypes {
return skill?.skillFilterType ?? .none
}
var cardType: CGSSCardTypes {
return CGSSCardTypes.init(typeString: attribute)
}
var attributeType: CGSSAttributeTypes {
if let da = danceMax, let vo = vocalMax, let vi = visualMax {
if da >= vo && da >= vi {
return .dance
} else if vo >= vi && vo >= da {
return .vocal
} else {
return .visual
}
}
return .none
}
var favoriteType: CGSSFavoriteTypes {
return FavoriteCardsManager.shared.contains(self.id) ? CGSSFavoriteTypes.inFavorite : CGSSFavoriteTypes.notInFavorite
}
var spreadImageURL: URL? {
return URL(string: spreadImageRef)
}
var cardImageURL: URL? {
return URL(string: cardImageRef)
}
var spriteImageURL: URL? {
return URL(string: spriteImageRef)
}
}
class CGSSCard: CGSSBaseModel {
var albumId: Int!
var attribute: String!
var bestStat: Int!
var bonusDance: Int!
var bonusHp: Int!
var bonusVisual: Int!
var bonusVocal: Int!
var cardImageRef: String!
var charaId: Int!
var danceMax: Int!
var danceMin: Int!
var evolutionId: Int!
var evolutionType: Int!
var growType: Int!
var hasSign: Bool!
var hasSpread: Bool!
var hpMax: Int!
var hpMin: Int!
var iconImageRef: String!
var id: Int!
var leaderSkillId: Int!
var name: String!
var nameOnly: String!
var openDressId: Int!
var openStoryId: Int!
var overallBonus: Int!
var overallMax: Int!
var overallMin: Int!
var place: Int!
var pose: Int!
var rarity: CGSSCardRarity!
var seriesId: Int!
var skillId: Int!
var soloLive: Int!
var spreadImageRef: String!
var spriteImageRef: String!
var starLessonType: Int!
var title: String!
var titleFlag: Int!
var valist: [AnyObject]!
var visualMax: Int!
var visualMin: Int!
var vocalMax: Int!
var vocalMin: Int!
// 非JSON获取
var availableType: CGSSAvailableTypes?
@objc dynamic var odds = 0
var firstAvailableAt: Date?
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!) {
super.init()
if json == JSON.null {
return
}
albumId = json["album_id"].intValue
attribute = json["attribute"].stringValue
bestStat = json["best_stat"].intValue
bonusDance = json["bonus_dance"].intValue
bonusHp = json["bonus_hp"].intValue
bonusVisual = json["bonus_visual"].intValue
bonusVocal = json["bonus_vocal"].intValue
cardImageRef = json["card_image_ref"].stringValue
charaId = json["chara_id"].intValue
danceMax = json["dance_max"].intValue
danceMin = json["dance_min"].intValue
evolutionId = json["evolution_id"].intValue
evolutionType = json["evolution_type"].intValue
growType = json["grow_type"].intValue
hasSign = json["has_sign"].boolValue
hasSpread = json["has_spread"].boolValue
hpMax = json["hp_max"].intValue
hpMin = json["hp_min"].intValue
iconImageRef = json["icon_image_ref"].stringValue
id = json["id"].intValue
leaderSkillId = json["leader_skill_id"].intValue
name = json["name"].stringValue
nameOnly = json["name_only"].stringValue
openDressId = json["open_dress_id"].intValue
openStoryId = json["open_story_id"].intValue
overallBonus = json["overall_bonus"].intValue
overallMax = json["overall_max"].intValue
overallMin = json["overall_min"].intValue
place = json["place"].intValue
pose = json["pose"].intValue
let rarityJson = json["rarity"]
if rarityJson != JSON.null {
rarity = CGSSCardRarity(fromJson: rarityJson)
}
seriesId = json["series_id"].intValue
skillId = json["skill_id"].intValue
soloLive = json["solo_live"].intValue
spreadImageRef = json["spread_image_ref"].stringValue
spriteImageRef = json["sprite_image_ref"].stringValue
starLessonType = json["star_lesson_type"].intValue
title = json["title"].stringValue
titleFlag = json["title_flag"].intValue
valist = [AnyObject]()
let valistArray = json["valist"].arrayValue
for valistJson in valistArray {
valist.append(valistJson.stringValue as AnyObject)
}
visualMax = json["visual_max"].intValue
visualMin = json["visual_min"].intValue
vocalMax = json["vocal_max"].intValue
vocalMin = json["vocal_min"].intValue
let dao = CGSSDAO.shared
let skillJson = json["skill"]
if skillJson != JSON.null {
if let skill = dao.findSkillById(skillId), !skill.isOldVersion {
// skill 存在且不是老版本 则不做任何处理
} else {
let skill = CGSSSkill.init(fromJson: skillJson)
dao.skillDict.setValue(skill, forKey: String(skillId))
}
}
let charaJson = json["chara"]
if charaJson != JSON.null {
if let chara = dao.findCharById(charaId), !chara.isOldVersion {
} else {
let chara = CGSSChar(fromJson: charaJson)
dao.charDict.setValue(chara, forKey: String(charaId))
}
}
let leadSkillJson = json["lead_skill"]
if leadSkillJson != JSON.null {
if let leaderSkill = dao.findLeaderSkillById(leaderSkillId), leaderSkill.isOldVersion {
} else {
let leadSkill = CGSSLeaderSkill(fromJson: leadSkillJson)
dao.leaderSkillDict.setValue(leadSkill, forKey: String(leaderSkillId))
}
}
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
albumId = aDecoder.decodeObject(forKey: "album_id") as? Int
attribute = aDecoder.decodeObject(forKey: "attribute") as? String
bestStat = aDecoder.decodeObject(forKey: "best_stat") as? Int
bonusDance = aDecoder.decodeObject(forKey: "bonus_dance") as? Int
bonusHp = aDecoder.decodeObject(forKey: "bonus_hp") as? Int
bonusVisual = aDecoder.decodeObject(forKey: "bonus_visual") as? Int
bonusVocal = aDecoder.decodeObject(forKey: "bonus_vocal") as? Int
cardImageRef = aDecoder.decodeObject(forKey: "card_image_ref") as? String
charaId = aDecoder.decodeObject(forKey: "chara_id") as? Int
danceMax = aDecoder.decodeObject(forKey: "dance_max") as? Int
danceMin = aDecoder.decodeObject(forKey: "dance_min") as? Int
evolutionId = aDecoder.decodeObject(forKey: "evolution_id") as? Int
evolutionType = aDecoder.decodeObject(forKey: "evolution_type") as? Int
growType = aDecoder.decodeObject(forKey: "grow_type") as? Int
hasSign = aDecoder.decodeObject(forKey: "has_sign") as? Bool
hasSpread = aDecoder.decodeObject(forKey: "has_spread") as? Bool
hpMax = aDecoder.decodeObject(forKey: "hp_max") as? Int
hpMin = aDecoder.decodeObject(forKey: "hp_min") as? Int
iconImageRef = aDecoder.decodeObject(forKey: "icon_image_ref") as? String
id = aDecoder.decodeObject(forKey: "id") as? Int
leaderSkillId = aDecoder.decodeObject(forKey: "leader_skill_id") as? Int
name = aDecoder.decodeObject(forKey: "name") as? String
nameOnly = aDecoder.decodeObject(forKey: "name_only") as? String
openDressId = aDecoder.decodeObject(forKey: "open_dress_id") as? Int
openStoryId = aDecoder.decodeObject(forKey: "open_story_id") as? Int
overallBonus = aDecoder.decodeObject(forKey: "overall_bonus") as? Int
overallMax = aDecoder.decodeObject(forKey: "overall_max") as? Int
overallMin = aDecoder.decodeObject(forKey: "overall_min") as? Int
place = aDecoder.decodeObject(forKey: "place") as? Int
pose = aDecoder.decodeObject(forKey: "pose") as? Int
rarity = aDecoder.decodeObject(forKey: "rarity") as? CGSSCardRarity
seriesId = aDecoder.decodeObject(forKey: "series_id") as? Int
skillId = aDecoder.decodeObject(forKey: "skill_id") as? Int
soloLive = aDecoder.decodeObject(forKey: "solo_live") as? Int
spreadImageRef = aDecoder.decodeObject(forKey: "spread_image_ref") as? String
spriteImageRef = aDecoder.decodeObject(forKey: "sprite_image_ref") as? String
starLessonType = aDecoder.decodeObject(forKey: "star_lesson_type") as? Int
title = aDecoder.decodeObject(forKey: "title") as? String
titleFlag = aDecoder.decodeObject(forKey: "title_flag") as? Int
valist = aDecoder.decodeObject(forKey: "valist") as? [AnyObject]
visualMax = aDecoder.decodeObject(forKey: "visual_max") as? Int
visualMin = aDecoder.decodeObject(forKey: "visual_min") as? Int
vocalMax = aDecoder.decodeObject(forKey: "vocal_max") as? Int
vocalMin = aDecoder.decodeObject(forKey: "vocal_min") as? Int
// added in 1.1.3
availableType = CGSSAvailableTypes.init(rawValue: aDecoder.decodeObject(forKey: "availableType") as? UInt ?? 0)
firstAvailableAt = aDecoder.decodeObject(forKey: "firstAvailableAt") as? Date
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
override func encode(with aCoder: NSCoder)
{
super.encode(with: aCoder)
if albumId != nil {
aCoder.encode(albumId, forKey: "album_id")
}
if attribute != nil {
aCoder.encode(attribute, forKey: "attribute")
}
if bestStat != nil {
aCoder.encode(bestStat, forKey: "best_stat")
}
if bonusDance != nil {
aCoder.encode(bonusDance, forKey: "bonus_dance")
}
if bonusHp != nil {
aCoder.encode(bonusHp, forKey: "bonus_hp")
}
if bonusVisual != nil {
aCoder.encode(bonusVisual, forKey: "bonus_visual")
}
if bonusVocal != nil {
aCoder.encode(bonusVocal, forKey: "bonus_vocal")
}
if cardImageRef != nil {
aCoder.encode(cardImageRef, forKey: "card_image_ref")
}
if charaId != nil {
aCoder.encode(charaId, forKey: "chara_id")
}
if danceMax != nil {
aCoder.encode(danceMax, forKey: "dance_max")
}
if danceMin != nil {
aCoder.encode(danceMin, forKey: "dance_min")
}
if evolutionId != nil {
aCoder.encode(evolutionId, forKey: "evolution_id")
}
if evolutionType != nil {
aCoder.encode(evolutionType, forKey: "evolution_type")
}
if growType != nil {
aCoder.encode(growType, forKey: "grow_type")
}
if hasSign != nil {
aCoder.encode(hasSign, forKey: "has_sign")
}
if hasSpread != nil {
aCoder.encode(hasSpread, forKey: "has_spread")
}
if hpMax != nil {
aCoder.encode(hpMax, forKey: "hp_max")
}
if hpMin != nil {
aCoder.encode(hpMin, forKey: "hp_min")
}
if iconImageRef != nil {
aCoder.encode(iconImageRef, forKey: "icon_image_ref")
}
if id != nil {
aCoder.encode(id, forKey: "id")
}
if leaderSkillId != nil {
aCoder.encode(leaderSkillId, forKey: "leader_skill_id")
}
if name != nil {
aCoder.encode(name, forKey: "name")
}
if nameOnly != nil {
aCoder.encode(nameOnly, forKey: "name_only")
}
if openDressId != nil {
aCoder.encode(openDressId, forKey: "open_dress_id")
}
if openStoryId != nil {
aCoder.encode(openStoryId, forKey: "open_story_id")
}
if overallBonus != nil {
aCoder.encode(overallBonus, forKey: "overall_bonus")
}
if overallMax != nil {
aCoder.encode(overallMax, forKey: "overall_max")
}
if overallMin != nil {
aCoder.encode(overallMin, forKey: "overall_min")
}
if place != nil {
aCoder.encode(place, forKey: "place")
}
if pose != nil {
aCoder.encode(pose, forKey: "pose")
}
if rarity != nil {
aCoder.encode(rarity, forKey: "rarity")
}
if seriesId != nil {
aCoder.encode(seriesId, forKey: "series_id")
}
if skillId != nil {
aCoder.encode(skillId, forKey: "skill_id")
}
if soloLive != nil {
aCoder.encode(soloLive, forKey: "solo_live")
}
if spreadImageRef != nil {
aCoder.encode(spreadImageRef, forKey: "spread_image_ref")
}
if spriteImageRef != nil {
aCoder.encode(spriteImageRef, forKey: "sprite_image_ref")
}
if starLessonType != nil {
aCoder.encode(starLessonType, forKey: "star_lesson_type")
}
if title != nil {
aCoder.encode(title, forKey: "title")
}
if titleFlag != nil {
aCoder.encode(titleFlag, forKey: "title_flag")
}
if valist != nil {
aCoder.encode(valist, forKey: "valist")
}
if visualMax != nil {
aCoder.encode(visualMax, forKey: "visual_max")
}
if visualMin != nil {
aCoder.encode(visualMin, forKey: "visual_min")
}
if vocalMax != nil {
aCoder.encode(vocalMax, forKey: "vocal_max")
}
if vocalMin != nil {
aCoder.encode(vocalMin, forKey: "vocal_min")
}
// added in 1.1.3
if availableType != nil {
aCoder.encode(availableType?.rawValue, forKey: "availableType")
}
if firstAvailableAt != nil {
aCoder.encode(firstAvailableAt, forKey: "firstAvailableAt")
}
}
}
|
mit
|
5782a384250ad7ebcb25b7c864c635cf
| 33.576854 | 125 | 0.578212 | 4.096187 | false | false | false | false |
johnno1962/eidolon
|
KioskTests/Bid Fulfillment/BidderNetworkModelTests.swift
|
1
|
731
|
import Quick
import Nimble
import RxSwift
import Moya
@testable
import Kiosk
class BidderNetworkModelTests: QuickSpec {
override func spec() {
var bidDetails: BidDetails!
var subject: BidderNetworkModel!
beforeEach {
bidDetails = testBidDetails()
subject = BidderNetworkModel(provider: Networking.newStubbingNetworking(), bidDetails: bidDetails)
}
it("matches hasBeenRegistered is false") {
expect(subject.createdNewUser) == false
}
it("matches hasBeenRegistered is true") {
bidDetails.newUser.hasBeenRegistered.value = true
expect(try! subject.createdNewUser.toBlocking().first()) == true
}
}
}
|
mit
|
bd1db9565e06e30ca3de55642c34a4a9
| 26.111111 | 110 | 0.651163 | 5.111888 | false | true | false | false |
joalbright/Gameboard
|
Games/BoardController/BoardViews/MemoryBoardView.swift
|
1
|
2321
|
//
// MemoryBoardView.swift
// Games
//
// Created by Jo Albright on 4/25/18.
// Copyright © 2018 Jo Albright. All rights reserved.
//
import UIKit
@IBDesignable class MemoryBoardView : BoardView {
var guesses: Int = 0
override func prepareForInterfaceBuilder() {
board = Gameboard(.memory)
_ = try? board?.select(cardAt: (0,2))
_ = try? board?.match(cardAt: (2,1), withCard: (0,2))
super.prepareForInterfaceBuilder()
}
override func awakeFromNib() {
board = Gameboard(.memory)
super.awakeFromNib()
}
override func selectSquare(_ square: Square) {
let clean: () -> Void = {
self.board.highlights = [self.board.selected, square].compactMap { $0 }
self.board.selected = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
guard let highlights = self?.board.highlights, highlights.count > 1 else { return }
_ = try? self?.board.match(cardAt: highlights[1], withCard: highlights[0], reset: true)
self?.board.highlights = []
self?.updateBoard()
self?.checkDone()
}
}
if board.highlights.count > 1 {
return
} else if let selected = board.selected {
guesses += 1
do {
_ = try board.match(cardAt: square, withCard: selected)
clean()
} catch MemoryError.badmatch {
clean()
} catch { }
} else {
guard let _ = try? board.select(cardAt: square) else { return }
board.selected = square
}
updateBoard()
}
override func checkDone() {
let cardCount = board.grid.content.reduce(0) {
$0 + $1.reduce(0) { $0 + ($1 != EmptyPiece ? 1 : 0) }
}
if cardCount == 0 {
board?.showAlert?("Game Over", "It took \(guesses) Guesses")
guesses = 0
}
}
}
|
apache-2.0
|
ca14a180c4b0b105b8faf25a1d6e9b85
| 21.745098 | 103 | 0.461638 | 4.744376 | false | false | false | false |
liukunpengiOS/AlamofireManager
|
AlamofireManager/AlamofireManager.swift
|
1
|
4459
|
//
// AlamofireManager.swift
//
// Created by kunpeng on 2016/12/7.
// Copyright © 2016年 liukunpeng. All rights reserved.
//
import UIKit
import Alamofire
public class AlamofireManager {
public static let manager = AlamofireManager()
private init(){}
//MARK: Get
public func get(url:URLConvertible,parameters: Parameters,completion: @escaping((DataResponse<Any>) -> Void)) {
Alamofire.request(url, method: .get, parameters: parameters).responseJSON {(response) in
guard response.result.isSuccess else{
self.requestFailure(response)
return
}
completion(response)
}
}
//MARK: Post
public func post(url: URLConvertible, parameters: Parameters,completion: @escaping((DataResponse<Any>) ->Void)) {
Alamofire.request(url, method: .post, parameters: parameters).responseJSON {(response) in
guard response.result.isSuccess else{
self.requestFailure(response)
return
}
completion(response)
}
}
//MARK: Uploading data
func uploadData(url: URLConvertible, image: UIImage) {
let imageData = UIImagePNGRepresentation(image)!
Alamofire.upload(imageData, to: url).responseJSON { (response) in
debugPrint(response)
}
}
//MARK: Uploading file
func uploadFile(url: URLConvertible) {
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL!, to: url).responseJSON { (response) in
}
}
//MARK: Upload Multipart form data
func uploadMultipartFormData (url: URLConvertible) {
Alamofire.upload(
multipartFormData: { multipartFormData in
// multipartFormData.append(unicornImageURL, withName: "unicorn")
//multipartFormData.append(rainbowImageURL, withName: "rainbow")
},
to: url, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
//MARK: Upload Progress
func uploadWithProgress(url: URLConvertible) {
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL!, to: url)
.uploadProgress { progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
}
.downloadProgress { progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
}
}
//MARK: Download
func downloadFile(url:URLConvertible) {
Alamofire.download(url).responseData {(response) in
// if let data = response.result.value {
// let image = UIImage(data: data)
// }
}
}
//MARK: Download file destination
func downloadFileDestination(url: URLConvertible) {
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(url, to: destination).responseData { (response) in
}
}
//MARK: Download file with progress
func downloadFileWithProgress(url: URLConvertible){
Alamofire.download(url).downloadProgress { (progress) in
print("Download progress: \(progress.fractionCompleted)")
}.responseData { (response) in
// if let data = response.result.value {
// let image = UIImage(data: data)
// }
}
}
func requestFailure(_ response:DataResponse<Any>) {
print("请求失败\(response)")
}
}
|
mit
|
6eba7a536e845b7e3601c216d8dbc5d2
| 34.301587 | 117 | 0.538669 | 5.64467 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKit/vendor/ASPolygonKit/Geometry.swift
|
1
|
3828
|
//
// Geometry.swift
//
// Created by Adrian Schoenig on 18/2/17.
//
//
import Foundation
struct Point: Hashable {
// MARK: Point as a lat/long pair
init(latitude: Double, longitude: Double) {
self.y = latitude
self.x = longitude
}
var lat: Double { y }
var lng: Double { x }
var description: String {
String(format: "(%.6f,%.6f)", lat, lng)
}
// MARK: Point as a x/y pair
// It's easier to do math using own x/y values as lat/longs can be confusing mathematically as they don't follow the directions of the typical x/y coordinate system. latitudes are positive up, longitudes are positive right, while we'd like x to be positive right and y to be positive up.
let x: Double
let y: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
}
// MARK: Pythagoras
func distance(from point: Point) -> Double {
let delta_x = point.x - x
let delta_y = point.y - y
return sqrt(delta_y * delta_y + delta_x * delta_x)
}
}
extension Point: Equatable {}
func ==(lhs: Point, rhs: Point) -> Bool {
let epsilon = 0.000001
return abs(lhs.lat - rhs.lat) < epsilon
&& abs(lhs.lng - rhs.lng) < epsilon
}
/// A line is defined by two points
struct Line: Hashable {
let start: Point
let end: Point
// Inferred from start + end
let m: Double
let b: Double
init(start: Point, end: Point) {
assert(start != end)
self.start = start
self.end = end
if (end.x == start.x) {
m = Double.infinity
} else {
m = (end.y - start.y) / (end.x - start.x)
}
if m == Double.infinity {
b = 0
} else {
b = start.y - m * start.x
}
}
// MARK: Mathmatical formula
// Special care needs to be taken where start.x == end.x, i.e., vertical lines.
var formula: String {
if m == Double.infinity {
return "y = *"
} else {
return String(format: "y = %.1f x + %.1f", m, b)
}
}
var description: String {
return String(format: "%@ - %@", start.description, end.description)
}
//MARK: Contains check
func contains(_ point: Point) -> Bool {
if m == Double.infinity {
return inRange( (point.x, point.y) )
}
let epsilon = 0.000001
let y = m * point.x + b
if abs(y - point.y) < epsilon {
return inRange( (point.x, point.y) )
} else {
return false
}
}
//MARK: Intersection of lines
func inRange(_ xy: (Double, Double)) -> Bool {
let x = xy.0
let y = xy.1
return x.inBetween(start.x, and: end.x)
&& y.inBetween(start.y, and: end.y)
}
func intersection(with line: Line) -> Point? {
// The intersection is where the two lines meet. Mathematically that's by solving the two formulae. Since these lines have a specific start + end, we also need to check that the intersection lies within the range.
// Special care needs to be taken where start.x == end.x, i.e., vertical lines.
if (m == line.m) {
if inRange( (line.start.x, line.start.y) ) {
return line.start
} else if line.inRange( (start.x, start.y )) {
return start
} else {
return nil
}
}
var x : Double
if (m == Double.infinity) {
x = start.x
} else if (line.m == Double.infinity) {
x = line.start.x
} else {
x = (line.b - b) / (m - line.m)
}
var y : Double
if (m == Double.infinity) {
y = line.m * x + line.b
} else {
y = m * x + b
}
if (inRange((x, y)) && line.inRange((x, y))) {
return Point(x: x, y: y)
}
return nil
}
}
extension Double {
func inBetween(_ some: Double, and another: Double) -> Bool {
let eps = 0.000001
return self >= min(some, another) - eps && self <= max(some, another) + eps
}
}
|
apache-2.0
|
df521202857f2a064096ba41f996a27a
| 22.62963 | 289 | 0.567921 | 3.366755 | false | false | false | false |
tony-dinh/today
|
today/today/CalendarList.swift
|
1
|
2440
|
//
// CalendarList.swift
// today
//
// Created by Tony Dinh on 2016-11-11.
// Copyright © 2016 Tony Dinh. All rights reserved.
//
import Foundation
import EventKit
final class CalendarList {
let eventManager = EventManager.sharedInstance
var calendarSources: [String]? = nil
var calendarsBySource: [String: [EKCalendar]]? = nil
var calendars: [EKCalendar]? {
return eventManager.calendars
}
init() {
if eventManager.accessGranted {
fetchAll()
} else {
eventManager.requestAccess() { granted, error in
if granted {
self.fetchAll()
}
}
}
}
private func fetchCalendars(for sources: [String], from calendars: [EKCalendar]) -> [String: [EKCalendar]] {
var result = [String: [EKCalendar]]()
for source in sources {
let calendars = calendarsFor(source: source, from: calendars)
result.updateValue(calendars, forKey: source)
}
return result
}
private func fetchSources(from calendars:[EKCalendar]) -> [String]? {
var sourceSet = Set<String>()
for calendar in calendars {
let source = calendar.source.title
let containsSource = sourceSet.contains(source)
if !containsSource {
sourceSet.insert(source)
}
}
if sourceSet.count > 0 {
var sources: [String]? = [String]()
sources?.append(contentsOf: sourceSet)
return sources?.sorted(by: displayOrder)
}
return nil
}
private func displayOrder(first a: String, second b: String) -> Bool {
switch a {
case "Default":
return true
case "Other":
return false
default:
return a < b
}
}
func fetchAll() {
eventManager.getEventCalendars()
guard let calendars = calendars else {
return
}
calendarSources = fetchSources(from: calendars)
if let calendarSources = calendarSources {
calendarsBySource = fetchCalendars(for: calendarSources, from: calendars)
}
}
func calendarsFor(source: String, from calendars: [EKCalendar]) -> [EKCalendar] {
return calendars.filter({$0.source.title == source}).sorted(by: {$0.title < $1.title})
}
}
|
mit
|
70a5ab29acfe0e63063c77182752a5c8
| 27.694118 | 112 | 0.566626 | 4.66348 | false | false | false | false |
poodarchu/iDaily
|
iDaily/iDaily/PDHomeCollectionVC.swift
|
1
|
7234
|
//
// ViewController.swift
// iDaily
//
// Created by P. Chu on 5/31/16.
// Copyright © 2016 Poodar. All rights reserved.
//
import UIKit
import CoreData
let itemHeight: CGFloat = 150.0 //cell的高度
let itemWidth: CGFloat = 60.0 //cell的宽度
let collectionViewWidth = itemWidth * 3 //每行显示3个cell
class PDHomeCollectionVC: UICollectionViewController {
var diaries = [NSManagedObject]()
var fetchedResultsController: NSFetchedResultsController!
var yearsCount: Int = 1
var sectionsCount: Int = 0
override func viewDidLoad()
{
super.viewDidLoad()
// self.navigationController?.hidesBarsOnTap = true
self.view.backgroundColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: #selector(SSASideMenu.presentLeftMenuViewController))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "New", style: .Plain, target: self, action: #selector(SSASideMenu.presentRightMenuViewController))
do {
//NSFetchRequest: 描述查询需求
//此处查询Core Data的PDDiary数据
let fetchRequest = NSFetchRequest(entityName:"PDDiary")
//按照创建时间的升序排列
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "create_date", ascending: true)]
//NSFetchedResultsController:控制查询,控制查询结果
//NSManagedObjectContext: 数据库上下文
//初始化NSFetchedResultsController,并根据year分成不同的 section
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: managedContext,
sectionNameKeyPath: "year",
cacheName: nil)
//开始尝试查询
try self.fetchedResultsController.performFetch()
if (fetchedResultsController.fetchedObjects!.count == 0){
print("Present empty year") //没有查询到任何结果
}else{
//查询结果根据year分成不同的section,此处反过来根据section的数量来判断year的数量
if let sectionsCount = fetchedResultsController.sections?.count {
//每年是一个section
yearsCount = sectionsCount
//fecthedObjects: [NSManagedObject] 表示查询结果,返回给NSFetchedResultsController
diaries = fetchedResultsController.fetchedObjects as! [NSManagedObject]
}else {
sectionsCount = 0
yearsCount = 1
}
}
} catch let error as NSError {
debugPrint(error)
}
/**
* 分组通过以上过程,已经由NSFetchedResultsController自动完成,接下来是在年,月界面正确显示相关内容
*/
self.navigationController!.delegate = self
let yearLayout = iDailyLayout()
yearLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView?.setCollectionViewLayout(yearLayout, animated: false)
self.collectionView!.frame = CGRect(x: 0, y: 0, width: collectionViewWidth, height: itemHeight + 44)
//collectionView 在正中显示
self.collectionView!.center = CGPoint(x: self.view.frame.size.width/2.0, y: self.view.frame.size.height/2.0)
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.view.backgroundColor = UIColor.whiteColor()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return yearsCount
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> HomeYearCollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeYearCollectionViewCell", forIndexPath: indexPath) as! HomeYearCollectionViewCell
//格式化日期
var year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: NSDate())
if sectionsCount > 0 {
if let sectionInfo = fetchedResultsController.sections![indexPath.row] as? NSFetchedResultsSectionInfo {
print("Section info \(sectionInfo.name)")
year = Int(sectionInfo.name)!
}
}
cell.textInt = year
cell.labelText = "\(numToChinese(cell.textInt)) 年"
// Configure the cell
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets
{
let leftRightMagrin = (collectionViewWidth - itemWidth)/2
return UIEdgeInsetsMake(0, leftRightMagrin, 0, leftRightMagrin)
}
//当在Home点击某一年的时候,跳转到MonthDayCollectionVC
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let identifier = "iDailyYearCollectionVC"
let dvc = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as! YearCollectionVC
let components = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: NSDate())
var year = components
if sectionsCount > 0 {
if let sectionInfo = fetchedResultsController.sections![indexPath.row] as? NSFetchedResultsSectionInfo {
print("Section info \(sectionInfo.name)")
year = Int(sectionInfo.name)!
}
}
//向将要跳转到的dvc传输year信息
dvc.year = year
//页面跳转
self.navigationController!.pushViewController(dvc, animated: true)
}
}
extension PDHomeCollectionVC: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = iDailyAnimator()
animator.operation = operation
return animator
}
}
|
gpl-3.0
|
902a0fb2997b4676ce3ed7017ce62db8
| 37.846591 | 173 | 0.62074 | 5.904145 | false | false | false | false |
linkedin/ConsistencyManager-iOS
|
ConsistencyManagerTests/HelperClasses/ProjectionTreeModel.swift
|
2
|
5034
|
// © 2016 LinkedIn Corp. 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.
import Foundation
import ConsistencyManager
/**
This model is intended for unit testing the consistency manager.
It's an interesting class which could be one of three projections. I decided to use one class to test projections so:
- We could test overriding projection identifier.
- I wouldn't need to write 3 different classes.
This class has `data`, `otherData` and two optional children.
It has a projection of data, otherData or both. If it's the data projection, then otherData is nil and should be ignored.
*/
final class ProjectionTreeModel: ConsistencyManagerModel, Equatable {
let id: Int
let data: Int?
let otherData: Int?
let child: ProjectionTreeModel?
let otherChild: ProjectionTreeModel?
let type: Projection
/**
We're going to use one class which represents three projections.
One projection will have both data and otherData
The other's will just have one of these fields.
*/
enum Projection: String {
case data
case otherData
case both
}
init(type: Projection, id: Int, data: Int?, otherData: Int?, child: ProjectionTreeModel?, otherChild: ProjectionTreeModel?) {
self.type = type
self.id = id
self.data = data
self.otherData = otherData
self.child = child
self.otherChild = otherChild
}
var modelIdentifier: String? {
return "\(id)"
}
func map(_ transform: (ConsistencyManagerModel) -> ConsistencyManagerModel?) -> ConsistencyManagerModel? {
let newChild = child.flatMap(transform) as? ProjectionTreeModel
let newOtherChild = otherChild.flatMap(transform) as? ProjectionTreeModel
return ProjectionTreeModel(type: type, id: id, data: data, otherData: otherData, child: newChild, otherChild: newOtherChild)
}
func forEach(_ function: (ConsistencyManagerModel) -> Void) {
if let child = child {
function(child)
}
if let otherChild = otherChild {
function(otherChild)
}
}
func mergeModel(_ model: ConsistencyManagerModel) -> ConsistencyManagerModel {
if let model = model as? ProjectionTreeModel {
return projectionTreeModelFromMergeModel(model)
} else {
assertionFailure("Cannot merge this model.")
return self
}
}
var projectionIdentifier: String {
return type.rawValue
}
fileprivate func projectionTreeModelFromMergeModel(_ model: ProjectionTreeModel) -> ProjectionTreeModel {
// We only want to update fields that are on our projection
// If we are of type .data we don't want to grab the otherData field
var otherData = self.otherData
var data = self.data
// This is a little complex. We only want to update a field if both models care about that field.
switch type {
case .data:
if model.type == .both || model.type == .data {
data = model.data
}
case .otherData:
if model.type == .both || model.type == .otherData {
otherData = model.otherData
}
case .both:
if model.type == .both || model.type == .data {
data = model.data
}
if model.type == .both || model.type == .otherData {
otherData = model.otherData
}
}
let child = self.child?.projectionTreeModelFromMergeModel(model.child)
let otherChild = self.otherChild?.projectionTreeModelFromMergeModel(model.otherChild)
return ProjectionTreeModel(type: type, id: id, data: data, otherData: otherData, child: child, otherChild: otherChild)
}
fileprivate func projectionTreeModelFromMergeModel(_ model: ProjectionTreeModel?) -> ProjectionTreeModel? {
guard let model = model else {
return nil
}
return projectionTreeModelFromMergeModel(model)
}
}
func ==(lhs: ProjectionTreeModel, rhs: ProjectionTreeModel) -> Bool {
return lhs.id == rhs.id &&
lhs.data == rhs.data &&
lhs.otherData == rhs.otherData &&
lhs.child == rhs.child &&
lhs.otherChild == rhs.otherChild &&
lhs.type == rhs.type
}
// MARK - CustomStringConvertible
extension ProjectionTreeModel: CustomStringConvertible {
var description: String {
return "\(id):\(String(describing: data)):\(String(describing: otherData))|\(String(describing: child))|\(String(describing: otherChild))"
}
}
|
apache-2.0
|
261cae24c1251107b10a223552354d84
| 36.559701 | 146 | 0.653288 | 4.558877 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/View/IndicatorTableView.swift
|
1
|
1920
|
//
// IndicatorTableView.swift
// DereGuide
//
// Created by zzk on 2017/6/3.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
class IndicatorTableView: UITableView {
var indicator = ScrollViewIndicator(frame: CGRect.init(x: 0, y: 0, width: 40, height: 40))
lazy var debouncer: Debouncer = {
return Debouncer.init(interval: 3, callback: { [weak self] in
if self?.indicator.panGesture.state == .possible {
self?.indicator.hide()
} else {
self?.debouncer.call()
}
})
}()
override var sectionHeaderHeight: CGFloat {
set {
super.sectionHeaderHeight = newValue
indicator.insets.top = newValue
}
get {
return super.sectionHeaderHeight
}
}
override var sectionFooterHeight: CGFloat {
set {
super.sectionFooterHeight = newValue
indicator.insets.bottom = newValue
}
get {
return super.sectionFooterHeight
}
}
override var contentOffset: CGPoint {
set {
super.contentOffset = newValue
debouncer.call()
indicator.adjustFrameInScrollView()
}
get {
return super.contentOffset
}
}
@objc func handlePanGestureInside(_ pan: UIPanGestureRecognizer) {
if pan.state == .began {
indicator.show(to: self)
}
}
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
showsVerticalScrollIndicator = false
delaysContentTouches = false
panGestureRecognizer.addTarget(self, action: #selector(handlePanGestureInside(_:)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
2ce73c093c65e7877aa9eef9780f0eeb
| 25.625 | 94 | 0.574335 | 5.044737 | false | false | false | false |
ashfurrow/RxSwift
|
RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift
|
3
|
2784
|
//
// RxScrollViewDelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
/**
For more information take a look at `DelegateProxyType`.
*/
public class RxScrollViewDelegateProxy
: DelegateProxy
, UIScrollViewDelegate
, DelegateProxyType {
private var _contentOffsetSubject: ReplaySubject<CGPoint>?
/**
Typed parent object.
*/
public weak private(set) var scrollView: UIScrollView?
/**
Optimized version used for observing content offset changes.
*/
internal var contentOffsetSubject: Observable<CGPoint> {
if _contentOffsetSubject == nil {
let replaySubject = ReplaySubject<CGPoint>.create(bufferSize: 1)
_contentOffsetSubject = replaySubject
replaySubject.on(.Next(self.scrollView?.contentOffset ?? CGPointZero))
}
return _contentOffsetSubject!
}
/**
Initializes `RxScrollViewDelegateProxy`
- parameter parentObject: Parent object for delegate proxy.
*/
public required init(parentObject: AnyObject) {
self.scrollView = (parentObject as! UIScrollView)
super.init(parentObject: parentObject)
}
// MARK: delegate methods
/**
For more information take a look at `DelegateProxyType`.
*/
public func scrollViewDidScroll(scrollView: UIScrollView) {
if let contentOffset = _contentOffsetSubject {
contentOffset.on(.Next(scrollView.contentOffset))
}
self._forwardToDelegate?.scrollViewDidScroll?(scrollView)
}
// MARK: delegate proxy
/**
For more information take a look at `DelegateProxyType`.
*/
public override class func createProxyForObject(object: AnyObject) -> AnyObject {
let scrollView = (object as! UIScrollView)
return castOrFatalError(scrollView.rx_createDelegateProxy())
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let collectionView: UIScrollView = castOrFatalError(object)
collectionView.delegate = castOptionalOrFatalError(delegate)
}
/**
For more information take a look at `DelegateProxyType`.
*/
public class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let collectionView: UIScrollView = castOrFatalError(object)
return collectionView.delegate
}
deinit {
if let contentOffset = _contentOffsetSubject {
contentOffset.on(.Completed)
}
}
}
#endif
|
mit
|
f035e221fc810872deb1bf11b2642e94
| 26.564356 | 92 | 0.667385 | 5.374517 | false | false | false | false |
IAskWind/IAWExtensionTool
|
IAWExtensionTool/IAWExtensionTool/Classes/UIKit/IAW_UIView+Extension.swift
|
1
|
2562
|
//
// UIView+Extension.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
extension UIView {
/// 裁剪 view 的圆角
open func iaw_clipRectCorner(_ direction: UIRectCorner, cornerRadius: CGFloat) {
let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.addSublayer(maskLayer)
layer.mask = maskLayer
}
/// x
open var iaw_x: CGFloat {
get {
return frame.origin.x
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.x = newValue
frame = tempFrame
}
}
/// y
open var iaw_y: CGFloat {
get {
return frame.origin.y
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.origin.y = newValue
frame = tempFrame
}
}
/// height
open var iaw_height: CGFloat {
get {
return frame.size.height
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.height = newValue
frame = tempFrame
}
}
/// width
open var iaw_width: CGFloat {
get {
return frame.size.width
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size.width = newValue
frame = tempFrame
}
}
/// size
open var iaw_size: CGSize {
get {
return frame.size
}
set(newValue) {
var tempFrame: CGRect = frame
tempFrame.size = newValue
frame = tempFrame
}
}
/// centerX
open var iaw_centerX: CGFloat {
get {
return center.x
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.x = newValue
center = tempCenter
}
}
/// centerY
open var iaw_centerY: CGFloat {
get {
return center.y
}
set(newValue) {
var tempCenter: CGPoint = center
tempCenter.y = newValue
center = tempCenter;
}
}
}
|
mit
|
3b8e2c4c961f3986b75c0af84b8d4519
| 22.601852 | 111 | 0.497058 | 4.855238 | false | false | false | false |
sschiau/swift
|
benchmark/single-source/ProtocolDispatch2.swift
|
7
|
1835
|
//===--- ProtocolDispatch2.swift ------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This is a simple benchmark that tests the performance of calls to
// existential methods.
//===----------------------------------------------------------------------===//
import TestsUtils
public let ProtocolDispatch2 = BenchmarkInfo(
name: "ProtocolDispatch2",
runFunction: run_ProtocolDispatch2,
tags: [.validation, .abstraction])
protocol Pingable { func ping() -> Int; func pong() -> Int}
struct Game : Pingable {
func zero() -> Int { return 0}
func ping() -> Int { return 1}
func pong() -> Int { return 2}
func puff() -> Int { return 3}
}
@inline(never)
func use_protocol(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
var t = game1.ping() + game1.pong()
if (val % 2 == 0) {
t += game1.pong() + game1.ping()
}
t += game1.ping() + game1.pong()
t += game2.ping() + game2.pong()
if (val % 2 == 0) {
t += game2.pong() + game2.ping()
}
t += game2.ping() + game2.pong()
return t
}
@inline(never)
func wrapper(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
return use_protocol(val, game1, game2)
}
@inline(never)
public func run_ProtocolDispatch2(_ N: Int) {
var c = 0
let g1 = Game()
let g2 = Game()
for _ in 1...10*N {
c = 0
for i in 1...5000 {
c += wrapper(i, g1, g2)
}
}
CheckResults(c == 75000)
}
|
apache-2.0
|
c4d0caecdd8fe968e0a47d9a8d1c7522
| 26.38806 | 80 | 0.559673 | 3.640873 | false | false | false | false |
piscoTech/Workout
|
Workout Core/Model/WorkoutList.swift
|
1
|
6871
|
//
// WorkoutList.swift
// Workout
//
// Created by Marco Boschi on 08/06/2019.
// Copyright © 2019 Marco Boschi. All rights reserved.
//
import HealthKit
public typealias WorkoutListFilter = Set<HKWorkoutActivityType>
public protocol WorkoutListDelegate: AnyObject {
func loadingStatusChanged()
func listChanged()
func additionalWorkoutsLoaded(count: Int, oldCount: Int)
}
public class WorkoutList {
private enum Error: Swift.Error {
case missingHealth
}
private let healthData: Health
private let preferences: Preferences
public weak var delegate: WorkoutListDelegate?
public var startDate: Date? {
didSet {
if let start = startDate, let end = endDate, start.round(to: .day) > end.round(to: .day) {
endDate = nil
}
updateFilteredList()
}
}
public var endDate: Date? {
didSet {
if let start = startDate, let end = endDate, end.round(to: .day) < start.round(to: .day) {
startDate = nil
}
updateFilteredList()
}
}
public var filters: WorkoutListFilter = [] {
didSet {
if locked {
filters = oldValue
} else {
let av = availableFilters
let good = filters.intersection(av)
if good == av {
filters = []
} else if good != filters {
filters = good
}
if filters != oldValue {
updateFilteredList()
}
}
}
}
public var availableFilters: WorkoutListFilter {
guard let types = allWorkouts?.map({ $0.raw.workoutActivityType }) else {
return []
}
return Set(types)
}
public var isFiltering: Bool {
return !filters.isEmpty
}
public internal(set) var locked = false
/// The workout list, if `nil` either there's an error or the initial loading is being performed or it's waiting to be performed.
public private(set) var workouts: [Workout]?
public private(set) var isLoading = false
public private(set) var error: Swift.Error?
/// Whether calling `loadMore()` will yield more workouts.
private var canLoadMore = false
/// Whether calling `loadMore()` will yield more workouts to be displayed according to the current filters.
///
/// Type filters don't affect this value, but as the loading is performed by sorting on starting time, filtering on `startDate` can block displaying of any other workout being loaded.
public var canDisplayMore: Bool {
guard let start = startDate, let lastStart = allWorkouts?.last?.startDate else {
return canLoadMore
}
return canLoadMore && start <= lastStart
}
private var allWorkouts: [Workout]?
private let batchSize = 40
private let filteredLoadMultiplier = 5
public init(healthData: Health, preferences: Preferences) {
self.healthData = healthData
self.preferences = preferences
}
private func updateFilteredList() {
workouts = filter(workouts: allWorkouts)
DispatchQueue.main.async {
self.delegate?.listChanged()
}
}
private func filter(workouts wrkts: [Workout]?) -> [Workout]? {
return wrkts?.filter { w in
// Start time filter
// The dates set in the filters are inclusive
if let s = startDate?.round(to: .day), w.startDate < s {
return false
}
if let e = endDate?.round(to: .day), w.endDate.round(to: .day) > e {
return false
}
// Type filter
guard filters.isEmpty || filters.contains(w.type) else {
return false
}
return true
}
}
public func reload() {
guard !isLoading, !locked else {
return
}
allWorkouts = nil
canLoadMore = false
if healthData.isHealthDataAvailable {
error = nil
isLoading = true
DispatchQueue.main.async {
self.delegate?.loadingStatusChanged()
}
DispatchQueue.main.asyncAfter(delay: 0.5) {
self.loadBatch(targetDisplayCount: self.batchSize)
}
} else {
isLoading = false
error = WorkoutList.Error.missingHealth
}
updateFilteredList()
}
public func loadMore() {
guard !isLoading, !locked else {
return
}
isLoading = true
DispatchQueue.main.async {
self.delegate?.loadingStatusChanged()
self.loadBatch(targetDisplayCount: (self.workouts?.count ?? 0) + self.batchSize)
}
}
private func loadBatch(targetDisplayCount target: Int) {
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let type = HKObjectType.workoutType()
let predicate: NSPredicate?
let limit: Int
if let last = allWorkouts?.last {
let allCount = allWorkouts?.count ?? 0
predicate = NSPredicate(format: "%K <= %@", HKPredicateKeyPathStartDate, last.startDate as NSDate)
let sameDateCount = allCount - (allWorkouts?.firstIndex { $0.startDate == last.startDate } ?? allCount)
let missing = target - (workouts?.count ?? 0)
limit = sameDateCount + min(batchSize, isFiltering ? missing * filteredLoadMultiplier : missing)
} else {
predicate = nil
limit = target
}
let workoutQuery = HKSampleQuery(sampleType: type, predicate: predicate, limit: limit, sortDescriptors: [sortDescriptor]) { (_, r, err) in
// There's no need to call .load() as additional data is not needed here, we just need information about units
let res = r as? [HKWorkout]
self.error = err
DispatchQueue.workout.async {
if let res = res {
self.canLoadMore = res.count >= limit
var wrkts: [Workout] = []
do {
wrkts.reserveCapacity(res.count)
var addAll = false
// By searching the reversed collection we reduce comparison as both collections are sorted
let revLoaded = (self.allWorkouts ?? []).reversed()
for w in res {
if addAll || !revLoaded.contains(where: { $0.raw == w }) {
// Stop searching already loaded workouts when the first new workout is not present.
addAll = true
wrkts.append(Workout.workoutFor(raw: w, from: self.healthData, and: self.preferences))
}
}
}
let disp = self.filter(workouts: wrkts) ?? []
let oldCount = self.workouts?.count ?? 0
self.allWorkouts = (self.allWorkouts ?? []) + wrkts
self.workouts = (self.workouts ?? []) + disp
// Don't perform a meaningless load of all possible workout when we know none of them can be displayed
if self.canDisplayMore && (self.workouts?.count ?? 0) < target {
DispatchQueue.main.async {
self.delegate?.additionalWorkoutsLoaded(count: disp.count, oldCount: oldCount)
self.loadBatch(targetDisplayCount: target)
}
} else {
self.isLoading = false
DispatchQueue.main.async {
self.delegate?.loadingStatusChanged()
self.delegate?.additionalWorkoutsLoaded(count: disp.count, oldCount: oldCount)
}
}
} else {
self.isLoading = false
self.canLoadMore = false
DispatchQueue.main.async {
self.delegate?.loadingStatusChanged()
}
self.allWorkouts = nil
// This also notifies of updates
self.updateFilteredList()
}
}
}
healthData.store.execute(workoutQuery)
}
}
|
mit
|
4a57435f4a1b2725d4aae2e1b47a2094
| 26.15415 | 184 | 0.679913 | 3.665955 | false | false | false | false |
nielstj/GLChat
|
GLChat/Extensions/UIImageExtensions.swift
|
1
|
2862
|
//
// UIImageExtensions.swift
// GLChat
//
// Created by Daniel on 18/8/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import UIKit
public extension UIImage {
/// Represents a scaling mode
enum ScalingMode {
case aspectFill
case aspectFit
/// Calculates the aspect ratio between two sizes
///
/// - parameters:
/// - size: the first size used to calculate the ratio
/// - otherSize: the second size used to calculate the ratio
///
/// - return: the aspect ratio between the two sizes
func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
let aspectWidth = size.width/otherSize.width
let aspectHeight = size.height/otherSize.height
switch self {
case .aspectFill:
return max(aspectWidth, aspectHeight)
case .aspectFit:
return min(aspectWidth, aspectHeight)
}
}
}
/// Scales an image to fit within a bounds with a size governed by the passed size. Also keeps the aspect ratio.
///
/// - parameter:
/// - newSize: the size of the bounds the image must fit within.
/// - scalingMode: the desired scaling mode
///
/// - returns: a new scaled image.
func scaled(to newSize: CGSize, scalingMode: UIImage.ScalingMode = .aspectFill) -> UIImage {
let aspectRatio = scalingMode.aspectRatio(between: newSize, and: size)
/* Build the rectangle representing the area to be drawn */
var scaledImageRect = CGRect.zero
scaledImageRect.size.width = ceil(size.width * aspectRatio)
scaledImageRect.size.height = ceil(size.height * aspectRatio)
scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0
scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0
/* Draw and retrieve the scaled image */
UIGraphicsBeginImageContext(newSize)
draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
func scaled(to width: CGFloat) -> UIImage {
let oldWidth = self.size.width
let aspectRatio = width / oldWidth
let newHeight = ceil(self.size.height * aspectRatio)
let newWidth = ceil(self.size.width * aspectRatio)
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
|
mit
|
045f48e9c83348f277c801c361f88371
| 34.7625 | 116 | 0.608528 | 5.02812 | false | false | false | false |
AlesTsurko/DNMKit
|
DNM_iOS/DNM_iOS/Label.swift
|
1
|
1673
|
//
// Label.swift
// denm_view
//
// Created by James Bean on 10/7/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class Label: ViewNode {
public var x: CGFloat = 0
public var height: CGFloat = 0
public var text: String = ""
public var textLayer: TextLayerConstrainedByHeight!
public var pad: CGFloat { get { return 0.25 * height } }
// in subclasses, add possibility of graphics
public init(x: CGFloat = 0, top: CGFloat = 0, height: CGFloat = 10, text: String) {
self.x = x
self.height = height
self.text = text
super.init()
self.top = top
build()
backgroundColor = DNMColorManager.backgroundColor.CGColor
}
public override init() { super.init() }
public override init(layer: AnyObject) { super.init(layer: layer) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public func build() {
createTextLayer()
setFrame()
}
public func createTextLayer() {
let text_height = height - 2 * pad
textLayer = TextLayerConstrainedByHeight(
text: text,
x: 0,
top: pad,
height: text_height,
alignment: .Center,
fontName: "Baskerville-SemiBold"
)
textLayer.foregroundColor = UIColor.grayscaleColorWithDepthOfField(.Foreground).CGColor
addSublayer(textLayer)
}
public func setFrame() {
let w = textLayer.frame.width + 2 * pad
frame = CGRectMake(x - 0.5 * w, top, w, height)
textLayer.position.x = 0.5 * frame.width
}
}
|
gpl-2.0
|
09bd61e2d2f1a5c3d2966f1c11812757
| 28.333333 | 95 | 0.59689 | 4.211587 | false | false | false | false |
aferodeveloper/sango
|
Source/AssetCatalog/AppIcon.swift
|
1
|
5386
|
//
// AppIcon.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
import Cocoa
/// Creates and saves an App Icon asset catalog.
class AppIcon: NSObject {
/// The resized images.
var images: [String: [String: NSImage?]] = [:]
/// Generate the necessary images for the selected platforms.
///
/// - Parameters:
/// - platforms: The platforms to generate icon for.
/// - image: The image to generate the icon from.
/// - Throws: See AppIconError for possible values.
func generateImagesForPlatforms(_ platforms: [String], fromImage image: NSImage) throws {
// Loop through the selected platforms
for platform in platforms {
// Temporary dict to hold the generated images.
var tmpImages: [String: NSImage?] = [:]
// Create a new JSON object for the current platform.
let jsonData = try ContentsJSON(forType: IconAssetType.appIcon, andPlatforms: [platform])
for imageData in jsonData.images {
// Get the expected size, since App Icons are quadratic we only need one value.
guard let size = imageData["expected-size"] else {
throw AppIconError.missingDataForImageSize
}
// Get the filename.
guard let filename = imageData["filename"] else {
throw AppIconError.missingDataForImageName
}
if let size = Int(size) {
// Append the generated image to the temporary images dict.
tmpImages[filename] = image.resize(toSize: NSSize(width: size, height: size), aspectMode: .fit)
} else {
throw AppIconError.formatError
}
}
// Write back the images to self.images
images[platform] = tmpImages
}
}
/// Writes the App Icon for all selected platforms to the supplied file url.
///
/// - Parameters:
/// - name: The name of the asset catalog
/// - url: The URL to save the catalog to
/// - Throws: An AppIconError
func saveAssetCatalog(named name: String, toURL url: URL) throws {
for (platform, images) in self.images {
// Ignore pseudo platform iOS
if platform == iOSPlatformName {
continue
}
// let saveUrl = url.appendingPathComponent("\(appIconDir)/\(platform)/\(name).appiconset",
// isDirectory: true)
let saveUrl = url.appendingPathComponent("\(platform)/\(name).appiconset",
isDirectory: true)
try FileManager.default.createDirectory(at: saveUrl,
withIntermediateDirectories: true,
attributes: nil)
var contentsJson: ContentsJSON?
if platform == iPhonePlatformName || platform == iPadPlatformName {
try self.saveAsset(images: self.images[iOSPlatformName]!, toUrl: saveUrl)
contentsJson = try ContentsJSON(forType: IconAssetType.appIcon,
andPlatforms: [platform, iOSPlatformName])
} else {
contentsJson = try ContentsJSON(forType: IconAssetType.appIcon,
andPlatforms: [platform])
}
try contentsJson?.saveToURL(saveUrl)
try self.saveAsset(images: images, toUrl: saveUrl)
}
self.images = [:]
}
/// Writes the App Icon for all selected platforms, as combined asset, to the supplied file url.
///
/// - Parameters:
/// - name: The name of the asset catalog
/// - url: The URL to save the catalog to
/// - Throws: An AppIconError
func saveCombinedAssetCatalog(named name: String, toUrl url: URL) throws -> URL {
// let saveUrl = url.appendingPathComponent("\(appIconDir)/Combined/\(name).appiconset", isDirectory: true)
let saveUrl = url.appendingPathComponent("\(name).appiconset", isDirectory: true)
for (_, images) in images {
try FileManager.default.createDirectory(at: saveUrl,
withIntermediateDirectories: true,
attributes: nil)
var contentsJson = try ContentsJSON(forType: IconAssetType.appIcon,
andPlatforms: Array(self.images.keys))
try contentsJson.saveToURL(saveUrl)
try self.saveAsset(images: images, toUrl: saveUrl)
}
self.images = [:]
return saveUrl
}
/// Saves the supplied images as png to the supplied file url
///
/// - Parameters:
/// - images: The images to be saved
/// - url: The file URL to save the images to
/// - Throws: See AppIconError and NSImageExtensionError
private func saveAsset(images: [String: NSImage?], toUrl url: URL) throws {
for (filename, image) in images {
guard let img = image else {
throw AppIconError.missingImage
}
try img.savePngTo(url: url.appendingPathComponent(filename, isDirectory: false))
}
}
}
|
apache-2.0
|
6e641bc34ffbef56214e94f3eb0d54b0
| 40.751938 | 115 | 0.563127 | 5.21394 | false | false | false | false |
eofster/Telephone
|
UseCasesTestDoubles/CallEventTargetSpy.swift
|
1
|
1484
|
//
// CallEventTargetSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import UseCases
public final class CallEventTargetSpy {
public private(set) var didCallDidMake = false
public private(set) var didCallDidReceive = false
public private(set) var didCallIsConnecting = false
public private(set) var didCallDidDisconnect = false
public private(set) var invokedCall: Call?
public init() {}
}
extension CallEventTargetSpy: CallEventTarget {
public func didMake(_ call: Call) {
didCallDidMake = true
invokedCall = call
}
public func didReceive(_ call: Call) {
didCallDidReceive = true
invokedCall = call
}
public func isConnecting(_ call: Call) {
didCallIsConnecting = true
invokedCall = call
}
public func didDisconnect(_ call: Call) {
didCallDidDisconnect = true
invokedCall = call
}
}
|
gpl-3.0
|
059d7422c0245b1f5dab4a7bcc883a32
| 28.058824 | 72 | 0.696356 | 4.423881 | false | false | false | false |
Jnosh/swift
|
test/SILGen/subclass_existentials.swift
|
2
|
26023
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -parse-as-library -primary-file %s
// Note: we pass -verify above to ensure there are no spurious
// compiler warnings relating to casts.
protocol Q {}
class Base<T> : Q {
required init(classInit: ()) {}
func classSelfReturn() -> Self {
return self
}
static func classSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol P {
init(protocolInit: ())
func protocolSelfReturn() -> Self
static func protocolSelfReturn() -> Self
}
class Derived : Base<Int>, P {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {
return self
}
static func protocolSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol R {}
// CHECK-LABEL: sil hidden @_T021subclass_existentials11conversionsyAA1P_AA4BaseCySiGXc8baseAndP_AA7DerivedC7derivedAA1R_AIXc0hF1RAaC_AFXcXp0eF5PTypeAIm0H4TypeAaK_AIXcXp0hF5RTypetF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @owned Derived & R, @thick (Base<Int> & P).Type, @thick Derived.Type, @thick (Derived & R).Type) -> () {
func conversions(
baseAndP: Base<Int> & P,
derived: Derived,
derivedAndR: Derived & R,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type,
derivedAndRType: (Derived & R).Type) {
// Values
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROWED]] : $Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[BASE:%.*]] = upcast [[REF]] : $@opened("{{.*}}") Base<Int> & P to $Base<Int>
// CHECK: destroy_value [[BASE]] : $Base<Int>
// CHECK: end_borrow [[BORROWED]] from %0 : $Base<Int> & P
let _: Base<Int> = baseAndP
// CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROW]] : $Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $P
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*P, $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*P
// CHECK: dealloc_stack [[RESULT]] : $*P
// CHECK: end_borrow [[BORROW]] from %0 : $Base<Int> & P
let _: P = baseAndP
// CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROW]] : $Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $Q
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*Q, $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*Q
// CHECK: dealloc_stack [[RESULT]] : $*Q
// CHECK: end_borrow [[BORROW]] from %0 : $Base<Int> & P
let _: Q = baseAndP
// CHECK: [[BORROW:%.*]] = begin_borrow %2 : $Derived & R
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROW]] : $Derived & R
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[RESULT:%.*]] = init_existential_ref [[REF]] : $@opened("{{.*}}") Derived & R : $@opened("{{.*}}") Derived & R, $Base<Int> & P
// CHECK: destroy_value [[RESULT]]
// CHECK: end_borrow [[BORROW]] from %2 : $Derived & R
let _: Base<Int> & P = derivedAndR
// Metatypes
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = upcast [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type to $@thick Base<Int>.Type
let _: Base<Int>.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type, $@thick P.Type
let _: P.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type, $@thick Q.Type
let _: Q.Type = baseAndPType
// CHECK: [[RESULT:%.*]] = init_existential_metatype %4 : $@thick Derived.Type, $@thick (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %5 : $@thick (Derived & R).Type to $@thick (@opened("{{.*}}") (Derived & R)).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}") (Derived & R)).Type, $@thick (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedAndRType
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials11methodCallsyAA1P_AA4BaseCySiGXc8baseAndP_AaC_AFXcXp0fG5PTypetF : $@convention(thin) (@owned Base<Int> & P, @thick (Base<Int> & P).Type) -> () {
func methodCalls(
baseAndP: Base<Int> & P,
baseAndPType: (Base<Int> & P).Type) {
// CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROW]] : $Base<Int> & P to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] : $@opened("{{.*}}") Base<Int> & P
// CHECK: [[CLASS_REF:%.*]] = upcast [[REF]] : $@opened("{{.*}}") Base<Int> & P to $Base<Int>
// CHECK: [[METHOD:%.*]] = class_method [[CLASS_REF]] : $Base<Int>, #Base.classSelfReturn!1 : <T> (Base<T>) -> () -> @dynamic_self Base<T>, $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: [[RESULT_CLASS_REF:%.*]] = apply [[METHOD]]<Int>([[CLASS_REF]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: destroy_value [[CLASS_REF]] : $Base<Int>
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_CLASS_REF]] : $Base<Int> to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") Base<Int> & P : $@opened("{{.*}}") Base<Int> & P, $Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $Base<Int> & P
// CHECK: end_borrow [[BORROW]] from %0 : $Base<Int> & P
let _: Base<Int> & P = baseAndP.classSelfReturn()
// CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[BORROW]] : $Base<Int> & P to $@opened("{{.*}}") Base<Int> & P
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $@opened("{{.*}}") Base<Int> & P
// CHECK: store [[PAYLOAD]] to [init] [[SELF_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") Base<Int> & P, #P.protocolSelfReturn!1 : <Self where Self : P> (Self) -> () -> @dynamic_self Self, %16 : $@opened("{{.*}}") Base<Int> & P : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT_BOX:%.*]] = alloc_stack $@opened("{{.*}}") Base<Int> & P
// CHECK: apply [[METHOD]]<@opened("{{.*}}") Base<Int> & P>([[RESULT_BOX]], [[SELF_BOX]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT_REF:%.*]] = load [take] %20 : $*@opened("{{.*}}") Base<Int> & P
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") Base<Int> & P : $@opened("{{.*}}") Base<Int> & P, $Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $Base<Int> & P
// CHECK: dealloc_stack [[RESULT_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: dealloc_stack [[SELF_BOX]] : $*@opened("{{.*}}") Base<Int> & P
// CHECK: end_borrow [[BORROW]] from %0 : $Base<Int> & P
let _: Base<Int> & P = baseAndP.protocolSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[METHOD:%.*]] = function_ref @_T021subclass_existentials4BaseC15classSelfReturnACyxGXDyFZ : $@convention(method) <τ_0_0> (@thick Base<τ_0_0>.Type) -> @owned Base<τ_0_0>
// CHECK: [[METATYPE_REF:%.*]] = upcast [[METATYPE]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type to $@thick Base<Int>.Type
// CHECK: [[RESULT_REF2:%.*]] = apply [[METHOD]]<Int>([[METATYPE_REF]])
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_REF2]] : $Base<Int> to $@opened("{{.*}}") (Base<Int> & P)
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") (Base<Int> & P) : $@opened("{{.*}}") (Base<Int> & P), $Base<Int> & P
// CHECK: destroy_value [[RESULT]]
let _: Base<Int> & P = baseAndPType.classSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick (Base<Int> & P).Type to $@thick (@opened("{{.*}}") (Base<Int> & P)).Type
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") (Base<Int> & P), #P.protocolSelfReturn!1 : <Self where Self : P> (Self.Type) -> () -> @dynamic_self Self, [[METATYPE]] : $@thick (@opened("{{.*}}") (Base<Int> & P)).Type : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = alloc_stack $@opened("{{.*}}") (Base<Int> & P)
// CHECK: apply [[METHOD]]<@opened("{{.*}}") (Base<Int> & P)>(%37, %35) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT]] : $*@opened("{{.*}}") (Base<Int> & P)
// CHECK: [[RESULT_VALUE:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}") (Base<Int> & P) : $@opened("{{.*}}") (Base<Int> & P), $Base<Int> & P
// CHECK: destroy_value [[RESULT_VALUE]]
// CHECK: dealloc_stack [[RESULT]]
let _: Base<Int> & P = baseAndPType.protocolSelfReturn()
// Partial applications
let _: () -> (Base<Int> & P) = baseAndP.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndP.protocolSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.protocolSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.init(classInit:)
let _: () -> (Base<Int> & P) = baseAndPType.init(protocolInit:)
// CHECK: return
// CHECK-NEXT: }
}
protocol PropertyP {
var p: PropertyP & PropertyC { get set }
subscript(key: Int) -> Int { get set }
}
class PropertyC {
var c: PropertyP & PropertyC {
get {
return self as! PropertyP & PropertyC
}
set { }
}
subscript(key: (Int, Int)) -> Int {
get {
return 0
} set { }
}
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials16propertyAccessesyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@owned PropertyC & PropertyP) -> () {
func propertyAccesses(_ x: PropertyP & PropertyC) {
var xx = x
xx.p.p = x
xx.c.c = x
propertyAccesses(xx.p)
propertyAccesses(xx.c)
_ = xx[1]
xx[1] = 1
xx[1] += 1
_ = xx[(1, 2)]
xx[(1, 2)] = 1
xx[(1, 2)] += 1
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials19functionConversionsyAA1P_AA4BaseCySiGXcyc07returnsE4AndP_AaC_AFXcXpyc0feG5PTypeAA7DerivedCyc0fI0AJmyc0fI4TypeAA1R_AJXcyc0fiG1RAaM_AJXcXpyc0fiG5RTypetF : $@convention(thin) (@owned @callee_owned () -> @owned Base<Int> & P, @owned @callee_owned () -> @thick (Base<Int> & P).Type, @owned @callee_owned () -> @owned Derived, @owned @callee_owned () -> @thick Derived.Type, @owned @callee_owned () -> @owned Derived & R, @owned @callee_owned () -> @thick (Derived & R).Type) -> () {
func functionConversions(
returnsBaseAndP: @escaping () -> (Base<Int> & P),
returnsBaseAndPType: @escaping () -> (Base<Int> & P).Type,
returnsDerived: @escaping () -> Derived,
returnsDerivedType: @escaping () -> Derived.Type,
returnsDerivedAndR: @escaping () -> Derived & R,
returnsDerivedAndRType: @escaping () -> (Derived & R).Type) {
let _: () -> Base<Int> = returnsBaseAndP
let _: () -> Base<Int>.Type = returnsBaseAndPType
let _: () -> P = returnsBaseAndP
let _: () -> P.Type = returnsBaseAndPType
let _: () -> (Base<Int> & P) = returnsDerived
let _: () -> (Base<Int> & P).Type = returnsDerivedType
let _: () -> Base<Int> = returnsDerivedAndR
let _: () -> Base<Int>.Type = returnsDerivedAndRType
let _: () -> (Base<Int> & P) = returnsDerivedAndR
let _: () -> (Base<Int> & P).Type = returnsDerivedAndRType
let _: () -> P = returnsDerivedAndR
let _: () -> P.Type = returnsDerivedAndRType
// CHECK: return %
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials9downcastsyAA1P_AA4BaseCySiGXc8baseAndP_AA7DerivedC7derivedAaC_AFXcXp0eF5PTypeAIm0H4TypetF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @thick (Base<Int> & P).Type, @thick Derived.Type) -> () {
func downcasts(
baseAndP: Base<Int> & P,
derived: Derived,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type) {
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $Derived
let _ = baseAndP as? Derived
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $Derived
let _ = baseAndP as! Derived
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $Derived & R
let _ = baseAndP as? (Derived & R)
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $Derived & R
let _ = baseAndP as! (Derived & R)
// CHECK: checked_cast_br %3 : $@thick Derived.Type to $@thick (Derived & R).Type
let _ = derivedType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %3 : $@thick Derived.Type to $@thick (Derived & R).Type
let _ = derivedType as! (Derived & R).Type
// CHECK: checked_cast_br %2 : $@thick (Base<Int> & P).Type to $@thick Derived.Type
let _ = baseAndPType as? Derived.Type
// CHECK: unconditional_checked_cast %2 : $@thick (Base<Int> & P).Type to $@thick Derived.Type
let _ = baseAndPType as! Derived.Type
// CHECK: checked_cast_br %2 : $@thick (Base<Int> & P).Type to $@thick (Derived & R).Type
let _ = baseAndPType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %2 : $@thick (Base<Int> & P).Type to $@thick (Derived & R).Type
let _ = baseAndPType as! (Derived & R).Type
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials16archetypeUpcastsyq_9baseTAndP_q0_0E7IntAndPq1_7derivedtAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT) -> () {
func archetypeUpcasts<T,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
baseTAndP: BaseTAndP,
baseIntAndP : BaseIntAndP,
derived : DerivedT) {
// CHECK: [[BORROWED:%.*]] = begin_borrow %0 : $BaseTAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseTAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseTAndP : $BaseTAndP, $Base<T> & P
let _: Base<T> & P = baseTAndP
// CHECK: [[BORROWED:%.*]] = begin_borrow %1 : $BaseIntAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseIntAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseIntAndP : $BaseIntAndP, $Base<Int> & P
let _: Base<Int> & P = baseIntAndP
// CHECK: [[BORROWED:%.*]] = begin_borrow %2 : $DerivedT
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $DerivedT
// CHECK-NEXT: init_existential_ref [[COPIED]] : $DerivedT : $DerivedT, $Base<Int> & P
let _: Base<Int> & P = derived
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden @_T021subclass_existentials18archetypeDowncastsyx1s_q_1tq0_2ptq1_5baseTq2_0F3Intq3_0f6TAndP_C0q4_0fg5AndP_C0q5_08derived_C0AA1R_AA7DerivedCXc0ji2R_C0AA1P_AA4BaseCyq_GXc0fH10P_concreteAaO_AQySiGXc0fgi2P_M0tAaOR0_ARRb1_ATRb2_ARRb3_AaOR3_ATRb4_AaOR4_AMRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in S, @in T, @in PT, @owned BaseT, @owned BaseInt, @owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT, @owned Derived & R, @owned Base<T> & P, @owned Base<Int> & P) -> () {
func archetypeDowncasts<S,
T,
PT : P,
BaseT : Base<T>,
BaseInt : Base<Int>,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
s: S,
t: T,
pt: PT,
baseT : BaseT,
baseInt : BaseInt,
baseTAndP_archetype: BaseTAndP,
baseIntAndP_archetype : BaseIntAndP,
derived_archetype : DerivedT,
derivedAndR_archetype : Derived & R,
baseTAndP_concrete: Base<T> & P,
baseIntAndP_concrete: Base<Int> & P) {
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to Base<T> & P in [[RESULT]] : $*Base<T> & P
let _ = s as? (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast_addr take_always S in [[COPY]] : $*S to Base<T> & P in [[RESULT]] : $*Base<T> & P
let _ = s as! (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to Base<Int> & P in [[RESULT]] : $*Base<Int> & P
let _ = s as? (Base<Int> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [initialization] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast_addr take_always S in [[COPY]] : $*S to Base<Int> & P in [[RESULT]] : $*Base<Int> & P
let _ = s as! (Base<Int> & P)
// CHECK: [[BORROWED:%.*]] = begin_borrow %5 : $BaseTAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseTAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseTAndP to $Derived & R
let _ = baseTAndP_archetype as? (Derived & R)
// CHECK: [[BORROWED:%.*]] = begin_borrow %5 : $BaseTAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseTAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseTAndP to $Derived & R
let _ = baseTAndP_archetype as! (Derived & R)
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always Base<T> & P in [[COPY]] : $*Base<T> & P to S in [[PAYLOAD]] : $*S
let _ = baseTAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $Base<T> & P
// CHECK-NEXT: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr take_always Base<T> & P in [[COPY]] : $*Base<T> & P to S in [[RESULT]] : $*S
let _ = baseTAndP_concrete as! S
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseT
let _ = baseTAndP_concrete as? BaseT
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseT
let _ = baseTAndP_concrete as! BaseT
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseInt
let _ = baseTAndP_concrete as? BaseInt
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseInt
let _ = baseTAndP_concrete as! BaseInt
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<T> & P to $BaseTAndP
let _ = baseTAndP_concrete as? BaseTAndP
// CHECK: [[BORROWED:%.*]] = begin_borrow %9 : $Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<T> & P to $BaseTAndP
let _ = baseTAndP_concrete as! BaseTAndP
// CHECK: [[BORROWED:%.*]] = begin_borrow %6 : $BaseIntAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseIntAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseIntAndP to $Derived & R
let _ = baseIntAndP_archetype as? (Derived & R)
// CHECK: [[BORROWED:%.*]] = begin_borrow %6 : $BaseIntAndP
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $BaseIntAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseIntAndP to $Derived & R
let _ = baseIntAndP_archetype as! (Derived & R)
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always Base<Int> & P in [[COPY]] : $*Base<Int> & P to S in [[PAYLOAD]] : $*S
let _ = baseIntAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $Base<Int> & P
// CHECK-NEXT: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr take_always Base<Int> & P in [[COPY]] : $*Base<Int> & P to S in [[RESULT]] : $*S
let _ = baseIntAndP_concrete as! S
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $DerivedT
let _ = baseIntAndP_concrete as? DerivedT
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $DerivedT
let _ = baseIntAndP_concrete as! DerivedT
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseT
let _ = baseIntAndP_concrete as? BaseT
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseT
let _ = baseIntAndP_concrete as! BaseT
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseInt
let _ = baseIntAndP_concrete as? BaseInt
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseInt
let _ = baseIntAndP_concrete as! BaseInt
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $Base<Int> & P to $BaseTAndP
let _ = baseIntAndP_concrete as? BaseTAndP
// CHECK: [[BORROWED:%.*]] = begin_borrow %10 : $Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[BORROWED]] : $Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $Base<Int> & P to $BaseTAndP
let _ = baseIntAndP_concrete as! BaseTAndP
// CHECK: return
// CHECK-NEXT: }
}
|
apache-2.0
|
164df0a55148bce8ca09ec6059062e36
| 50.379447 | 694 | 0.583506 | 3.113533 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/Data/SyncCoordinator/SyncQuery.swift
|
1
|
1511
|
//
// SyncQuery.swift
// RoverData
//
// Created by Sean Rucker on 2018-08-28.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
public struct SyncQuery {
public struct Argument: Equatable, Hashable {
public var name: String
public var type: String
public init(name: String, type: String) {
self.name = name
self.type = type
}
}
public var name: String
public var body: String
public var arguments: [Argument]
public var fragments: [String]
public init(name: String, body: String, arguments: [Argument], fragments: [String]) {
self.name = name
self.body = body
self.arguments = arguments
self.fragments = fragments
}
}
extension SyncQuery {
var signature: String? {
if arguments.isEmpty {
return nil
}
return arguments.map {
"$\(name)\($0.name.capitalized):\($0.type)"
}.joined(separator: ", ")
}
var definition: String {
let expression: String = {
if arguments.isEmpty {
return ""
}
let signature = arguments.map {
"\($0.name):$\(name)\($0.name.capitalized)"
}.joined(separator: ", ")
return "(\(signature))"
}()
return """
\(name)\(expression) {
\(body)
}
"""
}
}
|
apache-2.0
|
0b3a7bf1708b85a8d84de2f4c5556f02
| 22.968254 | 89 | 0.495364 | 4.689441 | false | false | false | false |
zhiquan911/chance_btc_wallet
|
chance_btc_wallet/Pods/ESTabBarController-swift/Sources/ESTabBarItem.swift
|
2
|
4516
|
//
// ESTabBarController.swift
//
// Created by Vincent Li on 2017/2/8.
// Copyright (c) 2013-2018 ESTabBarController (https://github.com/eggswift/ESTabBarController)
//
// 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
/*
* ESTabBarItem继承自UITabBarItem,目的是为ESTabBarItemContentView提供UITabBarItem属性的设置。
* 目前支持大多常用的属性,例如image, selectedImage, title, tag 等。
*
* Unsupport properties:
* MARK: UIBarItem properties
* 1. var isEnabled: Bool
* 2. var landscapeImagePhone: UIImage?
* 3. var imageInsets: UIEdgeInsets
* 4. var landscapeImagePhoneInsets: UIEdgeInsets
* 5. func setTitleTextAttributes(_ attributes: [String : Any]?, for state: UIControlState)
* 6. func titleTextAttributes(for state: UIControlState) -> [String : Any]?
* MARK: UITabBarItem properties
* 7. var titlePositionAdjustment: UIOffset
* 8. func setBadgeTextAttributes(_ textAttributes: [String : Any]?, for state: UIControlState)
* 9. func badgeTextAttributes(for state: UIControlState) -> [String : Any]?
*/
@available(iOS 8.0, *)
open class ESTabBarItem: UITabBarItem {
/// Customize content view
open var contentView: ESTabBarItemContentView?
// MARK: UIBarItem properties
open override var title: String? // default is nil
{
didSet { self.contentView?.title = title }
}
open override var image: UIImage? // default is nil
{
didSet { self.contentView?.image = image }
}
// MARK: UITabBarItem properties
open override var selectedImage: UIImage? // default is nil
{
didSet { self.contentView?.selectedImage = selectedImage }
}
open override var badgeValue: String? // default is nil
{
get { return contentView?.badgeValue }
set(newValue) { contentView?.badgeValue = newValue }
}
/// Override UITabBarItem.badgeColor, make it available for iOS8.0 and later.
/// If this item displays a badge, this color will be used for the badge's background. If set to nil, the default background color will be used instead.
@available(iOS 8.0, *)
open override var badgeColor: UIColor? {
get { return contentView?.badgeColor }
set(newValue) { contentView?.badgeColor = newValue }
}
open override var tag: Int // default is 0
{
didSet { self.contentView?.tag = tag }
}
/* The unselected image is autogenerated from the image argument. The selected image
is autogenerated from the selectedImage if provided and the image argument otherwise.
To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal (see UIImage.h)
*/
public init(_ contentView: ESTabBarItemContentView = ESTabBarItemContentView(), title: String? = nil, image: UIImage? = nil, selectedImage: UIImage? = nil, tag: Int = 0) {
super.init()
self.contentView = contentView
self.setTitle(title, image: image, selectedImage: selectedImage, tag: tag)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func setTitle(_ title: String? = nil, image: UIImage? = nil, selectedImage: UIImage? = nil, tag: Int = 0) {
self.title = title
self.image = image
self.selectedImage = selectedImage
self.tag = tag
}
}
|
mit
|
8c53aab68c2f8c0271b61885c3d8d685
| 40.607477 | 175 | 0.688679 | 4.57554 | false | false | false | false |
AbelSu131/SimpleMemo
|
Memo/Memo/CoreDataStack.swift
|
1
|
5260
|
//
// CoreDataStack.swift
// EverMemo
//
// Created by 李俊 on 15/8/5.
// Copyright (c) 2015年 李俊. All rights reserved.
//
import CoreData
class CoreDataStack: NSObject {
static let shardedCoredataStack:CoreDataStack = CoreDataStack()
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.likumb.EverMemo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Memo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Memo.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext!.hasChanges {
do {
try managedObjectContext!.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
func creatMemo() -> Memo {
let context = CoreDataStack.shardedCoredataStack.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Memo", inManagedObjectContext:context!)
let note = Memo(entity: entityDescription!, insertIntoManagedObjectContext: context)
note.changeDate = NSDate()
note.isUpload = false
return note
}
func fetchAndSaveNewMemos(){
let sharedDefaults = NSUserDefaults(suiteName: "group.likumb.com.Memo")
let dict = sharedDefaults?.objectForKey("MemoContent") as? [[String: AnyObject]]
if let contents = dict {
for content in contents {
addMemo(content)
}
sharedDefaults?.removeObjectForKey("MemoContent")
}
}
func addMemo(dic: [String: AnyObject]){
let memo = CoreDataStack.shardedCoredataStack.creatMemo()
memo.text = dic["text"] as! String
memo.changeDate = dic["changeDate"] as! NSDate
CoreDataStack.shardedCoredataStack.saveContext()
}
}
|
mit
|
927f0e02d5987c91574f5deec6274695
| 40.322835 | 290 | 0.671684 | 5.716776 | false | false | false | false |
jpsim/CardsAgainst
|
CardsAgainst/AppDelegate.swift
|
1
|
1025
|
//
// AppDelegate.swift
// CardsAgainst
//
// Created by JP Simard on 10/25/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Window
window?.rootViewController = UINavigationController(rootViewController: MenuViewController())
window?.makeKeyAndVisible()
// Appearance
application.statusBarStyle = .lightContent
UINavigationBar.appearance().barTintColor = navBarColor
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: lightColor]
window?.tintColor = appTintColor
// Simultaneously advertise and browse for other players
ConnectionManager.start()
return true
}
}
|
mit
|
beedc4cd6dbaa3055e291514f00b4ea0
| 30.060606 | 114 | 0.701463 | 5.726257 | false | false | false | false |
wuwen1030/VisualStepper
|
VisualStepper/XTStepper.swift
|
1
|
2957
|
//
// XTStepper.swift
// VisualStepper
//
// Created by Ben on 15/5/16.
// Copyright (c) 2015年 X-Team. All rights reserved.
//
import UIKit
@IBDesignable class XTStepper: UIControl {
var view: UIView!
@IBOutlet weak private var valueLabel: UILabel!
@IBOutlet weak private var minusButton: UIButton!
@IBOutlet weak private var plusButton: UIButton!
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet{
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var value:Int = 0 {
didSet{
sendActionsForControlEvents(UIControlEvents.ValueChanged)
self.updateApperance()
}
}
@IBInspectable var maxinumValue:Int = 0 {
didSet{
self.updateApperance()
}
}
@IBInspectable var minmumValue:Int = 0 {
didSet{
self.updateApperance()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
addSubview(view)
var leading = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal,
toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
var top = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal,
toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
var trailing = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal,
toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
var bottom = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal,
toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
addConstraints([leading, top, trailing, bottom])
self.updateApperance()
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "XTStepper", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
func updateApperance(){
valueLabel.text = String(value)
minusButton.enabled = value > minmumValue && value <= maxinumValue
plusButton.enabled = value >= minmumValue && value < maxinumValue
}
@IBAction func minusButtonPressed(sender: AnyObject) {
--value;
}
@IBAction func plusButtonPressed(sender: AnyObject) {
++value;
}
}
|
mit
|
a4a2f8d353841ede3d6e4dafa452d6cf
| 31.833333 | 127 | 0.641286 | 4.828431 | false | false | false | false |
audiokit/AudioKit
|
Sources/AudioKit/Nodes/Effects/Distortion/DiodeClipper.swift
|
1
|
2831
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Clips a signal to a predefined limit, in a "soft" manner, using one of three
/// methods.
///
public class DiodeClipper: Node, AudioUnitContainer, Toggleable {
/// Unique four-letter identifier "dclp"
public static let ComponentDescription = AudioComponentDescription(effect: "dclp")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Parameters
/// Specification for the cutoff frequency
public static let cutoffFrequencyDef = NodeParameterDef(
identifier: "cutoffFrequency",
name: "Cutoff Frequency (Hz)",
address: akGetParameterAddress("DiodeClipperParameterCutoff"),
range: 12.0 ... 20_000.0,
unit: .hertz,
flags: .default)
/// Filter cutoff frequency.
@Parameter public var cutoffFrequency: AUValue
/// Specification for the gain
public static let gainDef = NodeParameterDef(
identifier: "gain",
name: "Gain",
address: akGetParameterAddress("DiodeClipperParameterGaindB"),
range: 0.0 ... 40.0,
unit: .decibels,
flags: .default)
/// Determines the amount of gain applied to the signal before waveshaping. A value of 1 gives slight distortion.
@Parameter public var gain: AUValue
// MARK: - Audio Unit
/// Internal audio unit for diode clipper
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[DiodeClipper.cutoffFrequencyDef,
DiodeClipper.gainDef]
}
/// Create diode clipper DSP
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("DiodeClipperDSP")
}
}
// MARK: - Initialization
/// Initialize this clipper node
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff frequency
/// - gain: Gain in dB
///
public init(_ input: Node,
cutoffFrequency: AUValue = 10000.0,
gain: AUValue = 20.0
) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.cutoffFrequency = cutoffFrequency
self.gain = gain
}
connections.append(input)
}
}
|
mit
|
423947ec63128a8a871966109f3fbde6
| 30.10989 | 117 | 0.638997 | 4.957968 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Test Doubles/Observers/CapturingLoginObserver.swift
|
2
|
491
|
import EurofurenceModel
class CapturingLoginObserver {
private(set) var notifiedLoginSucceeded = false
private(set) var notifiedLoginFailed = false
private(set) var loggedInUser: User?
func completionHandler(_ result: LoginResult) {
switch result {
case .success(let user):
self.notifiedLoginSucceeded = true
self.loggedInUser = user
case .failure:
self.notifiedLoginFailed = true
}
}
}
|
mit
|
1c923962ea47fa7c0b71db6b10594628
| 24.842105 | 51 | 0.633401 | 5.010204 | false | false | false | false |
darina/omim
|
iphone/Maps/TipsAndTricks/TutorialBlurView.swift
|
6
|
3433
|
@objc(MWMTutorialBlurView)
class TutorialBlurView: UIVisualEffectView {
var targetView: UIView?
private var maskPath: UIBezierPath?
private var maskLayer = CAShapeLayer()
private let layoutView = UIView(frame: CGRect(x: -100, y: -100, width: 0, height: 0))
private func setup() {
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
layer.mask = maskLayer
layoutView.translatesAutoresizingMaskIntoConstraints = false
layoutView.isUserInteractionEnabled = false
contentView.addSubview(layoutView)
effect = nil
}
override init(effect: UIVisualEffect?) {
super.init(effect: effect)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let pointInView = targetView?.bounds.contains(convert(point, to: targetView)) else {
return super.point(inside: point, with: event)
}
return !pointInView
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview != nil {
targetView?.centerXAnchor.constraint(equalTo: layoutView.centerXAnchor).isActive = true
targetView?.centerYAnchor.constraint(equalTo: layoutView.centerYAnchor).isActive = true
guard #available(iOS 11.0, *) else {
DispatchQueue.main.async {
self.setNeedsLayout()
}
return
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
let targetCenter = layoutView.center
let r: CGFloat = 40
let targetRect = CGRect(x: targetCenter.x - r, y: targetCenter.y - r, width: r * 2, height: r * 2)
maskPath = UIBezierPath(rect: bounds)
maskPath!.append(UIBezierPath(ovalIn: targetRect))
maskPath!.usesEvenOddFillRule = true
maskLayer.path = maskPath!.cgPath
let pulsationPath = UIBezierPath(rect: bounds)
pulsationPath.append(UIBezierPath(ovalIn: targetRect.insetBy(dx: -10, dy: -10)))
pulsationPath.usesEvenOddFillRule = true
addPulsation(pulsationPath)
}
func animateSizeChange(_ duration: TimeInterval) {
layer.mask = nil
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
self.layer.mask = self.maskLayer
self.setNeedsLayout()
}
}
func animateFadeOut(_ duration: TimeInterval, completion: @escaping () -> Void) {
UIView.animate(withDuration: duration, animations: {
self.effect = nil
self.contentView.alpha = 0
}) { _ in
self.contentView.backgroundColor = .clear
completion()
}
}
func animateAppearance(_ duration: TimeInterval) {
contentView.alpha = 0
UIView.animate(withDuration: duration) {
self.contentView.alpha = 1
self.effect = UIBlurEffect(style: UIColor.isNightMode() ? .light : .dark)
}
}
private func addPulsation(_ path: UIBezierPath) {
let animation = CABasicAnimation(keyPath: "path")
animation.duration = kDefaultAnimationDuration
animation.fromValue = maskLayer.path
animation.toValue = path.cgPath
animation.autoreverses = true
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.repeatCount = 2
let animationGroup = CAAnimationGroup()
animationGroup.duration = 3
animationGroup.repeatCount = Float(Int.max)
animationGroup.animations = [animation]
maskLayer.add(animationGroup, forKey: "path")
}
}
|
apache-2.0
|
63a55282038d70e998f1fdb81ff4ab0b
| 31.084112 | 102 | 0.699971 | 4.571238 | false | false | false | false |
Fri3ndlyGerman/OpenWeatherSwift
|
Sources/HPOpenWeather/DataTypes/HourlyForecast.swift
|
1
|
3681
|
import Foundation
public struct HourlyForecast: BasicWeatherResponse {
public let timestamp: Date
public let pressure: Double?
public let humidity: Double?
public let dewPoint: Double?
public let uvIndex: Double?
public let visibility: Double?
public let cloudCoverage: Double?
public let wind: Wind
public let temperature: Temperature
public let rain: Precipitation
public let snow: Precipitation
let weatherArray: [WeatherCondition]
public var weather: [WeatherCondition] {
weatherArray
}
enum CodingKeys: String, CodingKey {
case temperature = "temp"
case feelsLike = "feels_like"
case snow
case rain
case timestamp = "dt"
case pressure
case humidity
case dewPoint = "dew_point"
case uvIndex = "uvi"
case cloudCoverage = "clouds"
case visibility
case windSpeed = "wind_speed"
case windGust = "wind_gust"
case windDirection = "wind_deg"
case weatherArray = "weather"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
timestamp = try container.decode(Date.self, forKey: .timestamp)
snow = try container.decodeIfPresent(Precipitation.self, forKey: .snow) ?? Precipitation.none
rain = try container.decodeIfPresent(Precipitation.self, forKey: .rain) ?? Precipitation.none
weatherArray = try container.decode([WeatherCondition].self, forKey: .weatherArray)
pressure = try container.decodeIfPresent(Double.self, forKey: .pressure)
humidity = try container.decodeIfPresent(Double.self, forKey: .humidity)
dewPoint = try container.decodeIfPresent(Double.self, forKey: .dewPoint)
uvIndex = try container.decodeIfPresent(Double.self, forKey: .uvIndex)
visibility = try container.decodeIfPresent(Double.self, forKey: .visibility)
cloudCoverage = try container.decodeIfPresent(Double.self, forKey: .cloudCoverage)
let temp = try container.decode(Double.self, forKey: .temperature)
let feelsLike = try container.decode(Double.self, forKey: .feelsLike)
temperature = Temperature(actual: temp, feelsLike: feelsLike)
let windSpeed = try container.decodeIfPresent(Double.self, forKey: .windSpeed)
let windGust = try container.decodeIfPresent(Double.self, forKey: .windGust)
let windDirection = try container.decodeIfPresent(Double.self, forKey: .windDirection)
wind = Wind(speed: windSpeed, gust: windGust, degrees: windDirection)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(temperature.actual, forKey: .temperature)
try container.encode(temperature.feelsLike, forKey: .feelsLike)
try container.encode(timestamp, forKey: .timestamp)
try container.encode(pressure, forKey: .pressure)
try container.encode(humidity, forKey: .humidity)
try container.encode(dewPoint, forKey: .dewPoint)
try container.encode(uvIndex, forKey: .uvIndex)
try container.encode(visibility, forKey: .visibility)
try container.encode(cloudCoverage, forKey: .cloudCoverage)
try container.encode(rain, forKey: .rain)
try container.encode(snow, forKey: .snow)
try container.encode(wind.speed, forKey: .windSpeed)
try container.encode(wind.degrees, forKey: .windDirection)
try container.encode(wind.gust, forKey: .windGust)
try container.encode(weatherArray, forKey: .weatherArray)
}
}
|
mit
|
beea49fef0ad21877761e4e88c350c2c
| 41.802326 | 101 | 0.691388 | 4.522113 | false | false | false | false |
sundance2000/LegoDimensionsCalculator
|
LegoDimensionsCalculatorTests/VehicleTests.swift
|
1
|
1180
|
//
// VehicleTests.swift
// LegoDimensionsCalculator
//
// Created by Christian Oberdörfer on 04.05.16.
// Copyright © 2016 sundance. All rights reserved.
//
import XCTest
class VehicleTests: XCTestCase {
func testInit() {
// 1. Arrange
let name = "Test"
let name1 = "Test 1"
let name2 = "Test 2"
let abilities1 = [Ability.Acrobat]
let abilities2 = [Ability.Boomerang]
let vehicleVersion1 = VehicleVersion(name: name1, abilities: Set(abilities1))
let vehicleVersion2 = VehicleVersion(name: name2, abilities: Set(abilities2))
// 2. Action
let vehicle = Vehicle(name: name, versions: [vehicleVersion1, vehicleVersion2])
// 3. Assert
XCTAssertEqual(vehicle.name, name)
XCTAssertEqual(vehicle.abilities, Set(abilities1 + abilities2))
XCTAssertEqual(vehicle.versions[0].name, vehicleVersion1.name)
XCTAssertEqual(vehicle.versions[0].abilities, Set(vehicleVersion1.abilities))
XCTAssertEqual(vehicle.versions[1].name, vehicleVersion2.name)
XCTAssertEqual(vehicle.versions[1].abilities, Set(vehicleVersion2.abilities))
}
}
|
mit
|
1fddd92e74e2781d46ca939fad04fbf1
| 32.657143 | 87 | 0.670628 | 3.96633 | false | true | false | false |
citrusbyte/Healthy-Baby
|
M2XDemo/TriggersViewController.swift
|
1
|
4321
|
//
// TriggersViewController.swift
// M2XDemo
//
// Created by Luis Floreani on 11/24/14.
// Copyright (c) 2014 citrusbyte.com. All rights reserved.
//
import Foundation
class TriggersViewController : HBBaseViewController, TriggerDetailViewControllerDelegate, UITableViewDataSource, UITableViewDelegate {
var deviceId: String?
private var triggers: [AnyObject]?
@IBOutlet private var tableView: UITableView!
@IBOutlet private var addTriggerButton: UIBarButtonItem!
@IBOutlet private var detailNoDataLabel: UILabel!
private var refreshTriggers: Bool = false
private var refreshControl: UIRefreshControl?
private var device: M2XDevice?
override func viewDidLoad() {
super.viewDidLoad()
assert(deviceId != nil, "deviceId can't be nil")
navigationItem.rightBarButtonItem = addTriggerButton
detailNoDataLabel.alpha = 0
detailNoDataLabel.textColor = Colors.grayColor
refreshControl = UIRefreshControl()
tableView.addSubview(refreshControl!)
refreshControl!.addTarget(self, action: "refreshData", forControlEvents: .ValueChanged)
var defaults = NSUserDefaults.standardUserDefaults()
let key = defaults.valueForKey("key") as? String
let client = M2XClient(apiKey: key)
self.device = M2XDevice(client: client, attributes: ["id": deviceId!])
loadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let dc = segue.destinationViewController as? TriggerDetailViewController {
dc.delegate = self
dc.device = self.device
if segue.identifier == "EditTriggerSegue" {
let indexPath = self.tableView.indexPathForSelectedRow()
let obj = self.triggers![indexPath!.row] as! M2XTrigger
dc.trigger = obj
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
ProgressHUD.cancelCBBProgress()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if refreshTriggers {
loadData()
refreshTriggers = false
}
}
func loadData() {
self.refreshControl?.beginRefreshing()
refreshData()
}
func refreshData() {
device?.triggersWithCompletionHandler { (objects: [AnyObject]!, response: M2XResponse!) -> Void in
self.refreshControl?.endRefreshing()
if response.error {
HBBaseViewController.handleErrorAlert(response.errorObject!)
} else {
self.triggers = objects
self.detailNoDataLabel.alpha = self.triggers?.count > 0 ? 0 : 1
self.tableView.reloadData()
}
}
}
// MARK: TriggerDetailViewControllerDelegate
func needsTriggersRefresh() {
refreshTriggers = true
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64.0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return triggers?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let obj = triggers![indexPath.row] as! M2XTrigger
let stream = obj["conditions"].allKeys[0] as! String
let conditions = obj["conditions"][stream] as! NSDictionary
let condition = conditions.allKeys[0] as! String
let conditionSymbols = ["lt": "<", "lte": "<=", "eq": "=", "gt": ">", "gte": ">="]
cell.textLabel?.text = obj["name"] as? String
cell.detailTextLabel?.text = "\(conditionSymbols[condition]!) \(conditions[condition]!)"
return cell
}
@IBAction func dismissFromSegue(segue: UIStoryboardSegue) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
673989de63ee0491942a2e826a4170c9
| 31.992366 | 134 | 0.62717 | 5.367702 | false | false | false | false |
AquaGeek/DataStructures
|
DataStructures/Stack.swift
|
1
|
1214
|
//
// Stack.swift
// DataStructures
//
// Created by Tyler Stromberg on 4/26/15.
// Copyright (c) 2015 Tyler Stromberg. All rights reserved.
//
import Foundation
public class Stack<T> {
private var storage: Node<T>?
public private(set) var count = 0
public init() {
}
/// Pushes a new item onto the stack.
///
/// Complexity: O(1)
public func push(item: T) {
var newTop = Node<T>(item)
newTop.next = storage
count++
storage = newTop
}
/// Removes and returns the value at the top of the stack,
/// or `nil` if the stack is empty.
///
/// Complexity: O(1)
public func pop() -> T? {
if let sureStorage = storage {
storage = sureStorage.next
count--
return sureStorage.value
} else {
return nil
}
}
/// Returns `true` if the stack is empty.
public var isEmpty: Bool {
return count == 0
}
/// Returns the value at the top of the stack without removing it,
/// or `nil` if the stack is empty.
///
/// Complexity: O(1)
public func peek() -> T? {
return storage?.value
}
}
|
mit
|
4de864402b54cb69a9556970f453adf7
| 21.481481 | 70 | 0.537068 | 3.980328 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.