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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/Layout Picker/FilterableCategoriesViewController.swift | 1 | 10620 | import UIKit
import Gridicons
import Gutenberg
class FilterableCategoriesViewController: CollapsableHeaderViewController {
private enum CategoryFilterAnalyticsKeys {
static let modifiedFilter = "filter"
static let selectedFilters = "selected_filters"
static let location = "location"
}
typealias PreviewDevice = PreviewDeviceSelectionViewController.PreviewDevice
let tableView: UITableView
private lazy var debounceSelectionChange: Debouncer = {
Debouncer(delay: 0.1) { [weak self] in
guard let `self` = self else { return }
self.itemSelectionChanged(self.selectedItem != nil)
}
}()
internal var selectedItem: IndexPath? = nil {
didSet {
debounceSelectionChange.call()
}
}
private let filterBar: CollapsableHeaderFilterBar
internal var categorySections: [CategorySection] { get {
fatalError("This should be overridden by the subclass to provide a conforming collection of categories")
} }
private var filteredSections: [CategorySection]?
private var visibleSections: [CategorySection] { filteredSections ?? categorySections }
internal var isLoading: Bool = true {
didSet {
if isLoading {
tableView.startGhostAnimation(style: GhostCellStyle.muriel)
} else {
tableView.stopGhostAnimation()
}
loadingStateChanged(isLoading)
tableView.reloadData()
}
}
var selectedPreviewDevice = PreviewDevice.default {
didSet {
tableView.reloadData()
}
}
let analyticsLocation: String
init(
analyticsLocation: String,
mainTitle: String,
prompt: String,
primaryActionTitle: String,
secondaryActionTitle: String? = nil,
defaultActionTitle: String? = nil
) {
self.analyticsLocation = analyticsLocation
tableView = UITableView(frame: .zero, style: .plain)
tableView.separatorStyle = .singleLine
tableView.separatorInset = .zero
tableView.showsVerticalScrollIndicator = false
filterBar = CollapsableHeaderFilterBar()
super.init(scrollableView: tableView,
mainTitle: mainTitle,
prompt: prompt,
primaryActionTitle: primaryActionTitle,
secondaryActionTitle: secondaryActionTitle,
defaultActionTitle: defaultActionTitle,
accessoryView: filterBar)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CategorySectionTableViewCell.nib, forCellReuseIdentifier: CategorySectionTableViewCell.cellReuseIdentifier)
filterBar.filterDelegate = self
tableView.dataSource = self
configureCloseButton()
}
private func configureCloseButton() {
navigationItem.rightBarButtonItem = CollapsableHeaderViewController.closeButton(target: self, action: #selector(closeButtonTapped))
}
@objc func closeButtonTapped(_ sender: Any) {
dismiss(animated: true)
}
override func estimatedContentSize() -> CGSize {
let rowCount = CGFloat(max(visibleSections.count, 1))
let estimatedRowHeight: CGFloat = CategorySectionTableViewCell.estimatedCellHeight
let estimatedHeight = (estimatedRowHeight * rowCount)
return CGSize(width: tableView.contentSize.width, height: estimatedHeight)
}
public func loadingStateChanged(_ isLoading: Bool) {
filterBar.shouldShowGhostContent = isLoading
filterBar.allowsMultipleSelection = !isLoading
filterBar.reloadData()
}
}
extension FilterableCategoriesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return CategorySectionTableViewCell.estimatedCellHeight
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isLoading ? 1 : (visibleSections.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellReuseIdentifier = CategorySectionTableViewCell.cellReuseIdentifier
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as? CategorySectionTableViewCell else {
fatalError("Expected the cell with identifier \"\(cellReuseIdentifier)\" to be a \(CategorySectionTableViewCell.self). Please make sure the table view is registering the correct nib before loading the data")
}
cell.delegate = self
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.section = isLoading ? nil : visibleSections[indexPath.row]
cell.isGhostCell = isLoading
cell.layer.masksToBounds = false
cell.clipsToBounds = false
cell.collectionView.allowsSelection = !isLoading
if let selectedItem = selectedItem, containsSelectedItem(selectedItem, atIndexPath: indexPath) {
cell.selectItemAt(selectedItem.item)
}
return cell
}
private func containsSelectedItem(_ selectedIndexPath: IndexPath, atIndexPath indexPath: IndexPath) -> Bool {
let rowSection = visibleSections[indexPath.row]
let sectionSlug = categorySections[selectedIndexPath.section].categorySlug
return (sectionSlug == rowSection.categorySlug)
}
}
extension FilterableCategoriesViewController: CategorySectionTableViewCellDelegate {
func didSelectItemAt(_ position: Int, forCell cell: CategorySectionTableViewCell, slug: String) {
guard let cellIndexPath = tableView.indexPath(for: cell),
let sectionIndex = categorySections.firstIndex(where: { $0.categorySlug == slug })
else { return }
tableView.selectRow(at: cellIndexPath, animated: false, scrollPosition: .none)
deselectCurrentLayout()
selectedItem = IndexPath(item: position, section: sectionIndex)
}
func didDeselectItem(forCell cell: CategorySectionTableViewCell) {
selectedItem = nil
}
func accessibilityElementDidBecomeFocused(forCell cell: CategorySectionTableViewCell) {
guard UIAccessibility.isVoiceOverRunning, let cellIndexPath = tableView.indexPath(for: cell) else { return }
tableView.scrollToRow(at: cellIndexPath, at: .middle, animated: true)
}
private func deselectCurrentLayout() {
guard let previousSelection = selectedItem else { return }
tableView.indexPathsForVisibleRows?.forEach { (indexPath) in
if containsSelectedItem(previousSelection, atIndexPath: indexPath) {
(tableView.cellForRow(at: indexPath) as? CategorySectionTableViewCell)?.deselectItems()
}
}
}
}
extension FilterableCategoriesViewController: CollapsableHeaderFilterBarDelegate {
func numberOfFilters() -> Int {
return categorySections.count
}
func filter(forIndex index: Int) -> CategorySection {
return categorySections[index]
}
func didSelectFilter(withIndex selectedIndex: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
trackFiltersChangedEvent(isSelectionEvent: true, changedIndex: selectedIndex, selectedIndexes: selectedIndexes)
guard filteredSections == nil else {
insertFilterRow(withIndex: selectedIndex, withSelectedIndexes: selectedIndexes)
return
}
let rowsToRemove = (0..<categorySections.count).compactMap { ($0 == selectedIndex.item) ? nil : IndexPath(row: $0, section: 0) }
filteredSections = [categorySections[selectedIndex.item]]
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.deleteRows(at: rowsToRemove, with: .fade)
})
}
func insertFilterRow(withIndex selectedIndex: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
let sortedIndexes = selectedIndexes.sorted(by: { $0.item < $1.item })
for i in 0..<sortedIndexes.count {
if sortedIndexes[i].item == selectedIndex.item {
filteredSections?.insert(categorySections[selectedIndex.item], at: i)
break
}
}
tableView.performBatchUpdates({
if selectedIndexes.count == 2 {
contentSizeWillChange()
}
tableView.reloadSections([0], with: .automatic)
})
}
func didDeselectFilter(withIndex index: IndexPath, withSelectedIndexes selectedIndexes: [IndexPath]) {
trackFiltersChangedEvent(isSelectionEvent: false, changedIndex: index, selectedIndexes: selectedIndexes)
guard selectedIndexes.count == 0 else {
removeFilterRow(withIndex: index)
return
}
filteredSections = nil
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.reloadSections([0], with: .fade)
})
}
func trackFiltersChangedEvent(isSelectionEvent: Bool, changedIndex: IndexPath, selectedIndexes: [IndexPath]) {
let event: WPAnalyticsEvent = isSelectionEvent ? .categoryFilterSelected : .categoryFilterDeselected
let filter = categorySections[changedIndex.item].categorySlug
let selectedFilters = selectedIndexes.map({ categorySections[$0.item].categorySlug }).joined(separator: ", ")
WPAnalytics.track(event, properties: [
CategoryFilterAnalyticsKeys.location: analyticsLocation,
CategoryFilterAnalyticsKeys.modifiedFilter: filter,
CategoryFilterAnalyticsKeys.selectedFilters: selectedFilters
])
}
func removeFilterRow(withIndex index: IndexPath) {
guard let filteredSections = filteredSections else { return }
var row: IndexPath? = nil
let rowSlug = categorySections[index.item].categorySlug
for i in 0..<filteredSections.count {
if filteredSections[i].categorySlug == rowSlug {
let indexPath = IndexPath(row: i, section: 0)
self.filteredSections?.remove(at: i)
row = indexPath
break
}
}
guard let rowToRemove = row else { return }
tableView.performBatchUpdates({
contentSizeWillChange()
tableView.deleteRows(at: [rowToRemove], with: .fade)
})
}
}
| gpl-2.0 | 7914d1fdc07bfa330eb412cb5b3dd5a7 | 38.924812 | 219 | 0.678343 | 5.725067 | false | false | false | false |
leoMehlig/Charts | Charts/Classes/Data/Implementations/Standard/LineChartDataSet.swift | 2 | 5184 | //
// LineChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet
{
private func initialize()
{
// default color
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
private var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
public var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue
if (_cubicIntensity > 1.0)
{
_cubicIntensity = 1.0
}
if (_cubicIntensity < 0.05)
{
_cubicIntensity = 0.05
}
}
}
/// If true, cubic lines are drawn instead of linear
public var drawCubicEnabled = false
/// - returns: true if drawing cubic lines is enabled, false if not.
public var isDrawCubicEnabled: Bool { return drawCubicEnabled }
/// If true, stepped lines are drawn instead of linear
public var drawSteppedEnabled = false
/// - returns: true if drawing stepped lines is enabled, false if not.
public var isDrawSteppedEnabled: Bool { return drawSteppedEnabled }
/// The radius of the drawn circles.
public var circleRadius = CGFloat(8.0)
public var circleColors = [NSUIColor]()
/// - returns: the color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
public func getCircleColor(var index: Int) -> NSUIColor?
{
let size = circleColors.count
index = index % size
if (index >= size)
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
public func setCircleColor(color: NSUIColor)
{
circleColors.removeAll(keepCapacity: false)
circleColors.append(color)
}
/// Resets the circle-colors array and creates a new one
public func resetCircleColors(index: Int)
{
circleColors.removeAll(keepCapacity: false)
}
/// If true, drawing circles is enabled
public var drawCirclesEnabled = true
/// - returns: true if drawing circles for this DataSet is enabled, false if not
public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled }
/// The color of the inner circle (the circle-hole).
public var circleHoleColor = NSUIColor.whiteColor()
/// True if drawing circles for this DataSet is enabled, false if not
public var drawCircleHoleEnabled = true
/// - returns: true if drawing the circle-holes is enabled, false if not.
public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled }
/// This is how much (in pixels) into the dash pattern are we starting from.
public var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
public var lineDashLengths: [CGFloat]?
/// formatter for customizing the position of the fill-line
private var _fillFormatter: ChartFillFormatter = ChartDefaultFillFormatter()
/// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
public var fillFormatter: ChartFillFormatter?
{
get
{
return _fillFormatter
}
set
{
if newValue == nil
{
_fillFormatter = ChartDefaultFillFormatter()
}
else
{
_fillFormatter = newValue!
}
}
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineChartDataSet
copy.circleColors = circleColors
copy.circleRadius = circleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCubicEnabled = drawCubicEnabled
copy.drawSteppedEnabled = drawSteppedEnabled
return copy
}
}
| apache-2.0 | eb96013dbabd990fdebc15279c165ea5 | 29.139535 | 154 | 0.612654 | 4.970278 | false | false | false | false |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/SettingsViewController.swift | 1 | 25121 | //
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate, ColorPickerTextFieldDelegate {
let sectionTitles = ["UIKeyboard handling",
"IQToolbar handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"IQKeyboardManager Debug"]
let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font","Toolbar Tint Color","Toolbar Done BarButtonItem Image","Toolbar Done Button Text"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Debugging logs in Console"]]
let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text","Override toolbar tintColor property","Replace toolbar done button text with provided image","Override toolbar done button text"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Setting enableDebugging to YES/No to turn on/off debugging mode"]]
var selectedIndexPathForOptions : NSIndexPath?
@IBAction func doneAction (sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/** UIKeyboard Handling */
func enableAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enable = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
func keyboardDistanceFromTextFieldAction (sender: UIStepper) {
IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
func preventShowingBottomBlankSpaceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.on
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** IQToolbar handling */
func enableAutoToolbarAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().enableAutoToolbar = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
func shouldToolbarUsesTextFieldTintColorAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.on
}
func shouldShowTextFieldPlaceholder (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.on
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
func toolbarDoneBarButtonItemImage (sender: UISwitch) {
if sender.on {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = UIImage(named:"IQButtonBarArrowDown")
} else {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = nil
}
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** "Keyboard appearance overriding */
func overrideKeyboardAppearanceAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.on
self.tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Fade)
}
/** Resign first responder handling */
func shouldResignOnTouchOutsideAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.on
}
/** Sound handling */
func shouldPlayInputClicksAction (sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.on
}
/** Debugging */
func enableDebugging (sender: UISwitch) {
IQKeyboardManager.sharedManager().enableDebugging = sender.on
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.sharedManager().enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.sharedManager().enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 2:
if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 3,4,5:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enable
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.preventShowingBottomBlankSpaceAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 1:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldShowTextFieldPlaceholder(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
case 5:
let cell = tableView.dequeueReusableCellWithIdentifier("ColorTableViewCell") as! ColorTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.colorPickerTextField.selectedColor = IQKeyboardManager.sharedManager().toolbarTintColor
cell.colorPickerTextField.tag = 15
cell.colorPickerTextField.delegate = self
return cell
case 6:
let cell = tableView.dequeueReusableCellWithIdentifier("ImageSwitchTableViewCell") as! ImageSwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.arrowImageView.image = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage
cell.switchEnable.on = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage != nil
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 7:
let cell = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell") as! TextFieldTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.textField.text = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText
cell.textField.tag = 17
cell.textField.delegate = self
return cell
default:
break
}
case 2:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
return cell
default:
break
}
case 3:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 4:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
case 5:
switch (indexPath.row) {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.enabled = true
cell.labelTitle.text = keyboardManagerProperties[indexPath.section][indexPath.row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[indexPath.section][indexPath.row]
cell.switchEnable.on = IQKeyboardManager.sharedManager().enableDebugging
cell.switchEnable.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), forControlEvents: UIControlEvents.ValueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func colorPickerTextField(textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String : AnyObject]) {
if textField.tag == 15 {
let color = colorAttributes["color"] as! UIColor
if color.isEqual(UIColor.clearColor() == true) {
IQKeyboardManager.sharedManager().toolbarTintColor = nil
} else {
IQKeyboardManager.sharedManager().toolbarTintColor = color
}
}
}
func textFieldDidEndEditing(textField: UITextField) {
if textField.tag == 17 {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = textField.text?.characters.count != 0 ? textField.text : nil
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destinationViewController as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPathForCell(cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont {
if let index = fonts.indexOf(placeholderFont) {
controller.selectedIndex = index
}
}
} else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if selectedIndexPath.section == 1 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if selectedIndexPath.section == 1 && selectedIndexPath.row == 4 {
let fonts = [UIFont.boldSystemFontOfSize(12),UIFont.italicSystemFontOfSize(12),UIFont.systemFontOfSize(12)]
IQKeyboardManager.sharedManager().placeholderFont = fonts[index]
} else if selectedIndexPath.section == 2 && selectedIndexPath.row == 1 {
IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
| mit | e5fb5f21e6aaa67ab2fe7230525fa282 | 44.925046 | 377 | 0.610804 | 7.231146 | false | false | false | false |
sora0077/NicoKit | Playground.playground/Contents.swift | 1 | 409 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
import NicoKit
import LoggingKit
LOGGING_VERBOSE()
var str = "Hello, playgrouna"
let api = API()
let query = Search.Query(type: .Tag("Sims4"))
let search = Search(query: query)
api.request(search).onSuccess { response in
Logging.d(response.0.first)
}
let aaa = [17]
XCPSetExecutionShouldContinueIndefinitely()
| mit | 70d19045cf07963ab98c95bbda0faea6 | 16.041667 | 52 | 0.738386 | 3.325203 | false | false | false | false |
byu-oit/ios-byuSuite | byuSuite/Classes/Reusable/UI/ByuSearchViewController.swift | 2 | 4499 | //
// ByuSearchViewController.swift
// byuSuite
//
// Created by Erik Brady on 5/8/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
/*!
* @class ByuSearchViewController
* @brief A ByuViewController that helps with searching a table view
* @discussion This class was created in response to how the search display controller displays itself in the BYU app. With the structure of the BYU app and its features, every search bar is in a view controller that is part of a UINavigationController's stack. The transitions to display and hide the UISearchDisplayController aren't perfectly smooth due to the UINavigationController. This class contains the functionality of UISearchDisplayController without the extra controller and glitchy UI. The search bar remains in its location instead of moving up to replace the navigation bar.
HOW TO USE:
If your class uses a UISearchBar to search a table view, extend this class.
The implementation of this class conforms to the UISearchBarDelegate protocol; therefore, your class's implementation does not need to conform to it.
You must implement -searchBar:textDidChange:. This class only calls -searchBar:textDidChange: to invoke reloading the table view's data, but the logic needs to be located in your implementation. -searchBar:textDidChange: itself doesn't reload the table view data; therefore, your class's implementation must call the table view's -reloadData (e.g., [self.tableView reloadData];) at the end of the callback in order to work properly. Since UISearchDisplayController is not being used, the search results will not be loaded in a new table view; your table view needs to display the search results. The search results will change as the user types, which requires reloading the table view's data each time the text changes.
Any callbacks that you do not implement or override will use this class's implementation or UISearchBarDelegate's default implementation if this class has not implemented them.
*/
class ByuSearchViewController: ByuViewController2, UISearchBarDelegate {
/*
Since this class is an alternative to UISearchDisplayController, there needs to be some way
to indicate that the search bar is actively being edited. With a search display controller,
there is a property 'active' (e.g., self.searchDisplayController.active). searchIsActive's
purpose is to mimick self.searchDisplayController.active. Use it in the same
way self.searchDisplayController.active would be used.
*/
var searchIsActive = false
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchIsActive = false
/*
The following line is needed just in case -searchBarShouldEndEditing: never gets called.
(e.g., user clicks cancel after clicking the search button on their keyboard)
*/
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
searchBar.text = ""
//See explanation for this function in the documentation comment in ByuSearchableViewController.h
self.searchBar(searchBar, textDidChange: searchBar.text ?? "")
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchIsActive = true
searchBar.tintColor = UIColor.byuTint
searchBar.showsCancelButton = true
//See explanation for this function in the documentation comment in ByuSearchableViewController.h
self.searchBar(searchBar, textDidChange: searchBar.text ?? "")
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsCancelButton = false
if searchBar.text == "" {
/*
This scenario is triggered when a user gives focus to the search bar text field, doesn't enter any search text, and
begins scrolling through the table view. Since the user didn't enter any specific search text, this just shows them
the original table view data.
*/
searchBarCancelButtonClicked(searchBar)
}
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//Implement this in your own view controller
}
}
| apache-2.0 | 3faae1755b94ed4d87805532e7167a6c | 50.701149 | 721 | 0.725211 | 5.519018 | false | false | false | false |
rokity/GCM-Sample | ios/appinvites/AppInvitesExampleSwift/ViewController.swift | 61 | 3471 | //
// Copyright (c) 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 UIKit
// Match the ObjC symbol name inside Main.storyboard.
@objc(ViewController)
// [START viewcontroller_interfaces]
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate, GINInviteDelegate {
// [END viewcontroller_interfaces]
// [START viewcontroller_vars]
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var inviteButton: UIButton!
@IBOutlet weak var statusText: UILabel!
// [END viewcontroller_vars]
// [START viewdidload]
override func viewWillAppear(animated: Bool) {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
toggleAuthUI()
}
// [END viewdidload]
// [START signin_handler]
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil) {
// User Successfully signed in.
statusText.text = "Signed in as \(user.profile.name)"
toggleAuthUI()
} else {
println("\(error.localizedDescription)")
toggleAuthUI()
}
}
// [END signin_handler]
// [START signout_tapped]
@IBAction func signOutTapped(sender: AnyObject) {
GIDSignIn.sharedInstance().signOut()
statusText.text = "Signed out"
toggleAuthUI()
}
// [END signout_tapped]
// [START disconnect_tapped]
@IBAction func disconnectTapped(sender: AnyObject) {
GIDSignIn.sharedInstance().disconnect()
statusText.text = "Disconnected"
toggleAuthUI()
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {
toggleAuthUI()
}
// [END disconnect_tapped]
// [START invite_tapped]
@IBAction func inviteTapped(sender: AnyObject) {
let invite = GINInvite.inviteDialog()
invite.setMessage("Message")
invite.setTitle("Title")
invite.setDeepLink("/invite")
invite.open()
}
// [END invite_tapped]
// [START toggle_auth]
func toggleAuthUI() {
if (GIDSignIn.sharedInstance().hasAuthInKeychain()) {
// Signed in
signOutButton.enabled = true
disconnectButton.enabled = true
inviteButton.enabled = true
} else {
signOutButton.enabled = false
disconnectButton.enabled = false
inviteButton.enabled = false
self.performSegueWithIdentifier("SignedOutScreen", sender:self)
}
}
// [END toggle_auth]
// [START invite_finished]
func inviteFinishedWithInvitations(invitationIds: [AnyObject]!, error: NSError!) {
if (error != nil) {
println("Failed: " + error.localizedDescription)
} else {
println("Invitations sent")
}
}
// [END invite_finished]
// Sets the status bar to white.
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| apache-2.0 | 9ec1d1280eba867ebac514951d17964b | 29.447368 | 106 | 0.698646 | 4.455712 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Data/Implementations/Standard/BarChartDataSet.swift | 6 | 5861 | //
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.black
self.calcStackSize(yVals as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(_ yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0
for i in 0 ..< yVals.count
{
let vals = yVals[i].values
if (vals == nil)
{
_entryCountStacks += 1
}
else
{
_entryCountStacks += vals!.count
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(_ yVals: [BarChartDataEntry]!)
{
for i in 0 ..< yVals.count
{
if let vals = yVals[i].values
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
open override func calcMinMax(start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for i in stride(from: start, through: endValue, by: 1)
{
if let e = _yVals[i] as? BarChartDataEntry
{
if !e.value.isNaN
{
if e.values == nil
{
if e.value < _yMin
{
_yMin = e.value
}
if e.value > _yMax
{
_yMax = e.value
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the maximum number of bars that can be stacked upon another in this DataSet.
open var stackSize: Int
{
return _stackSize
}
/// - returns: true if this DataSet is stacked (stacksize > 1) or not.
open var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: the overall entry count, including counting each stack-value individually
open var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
open var barSpace: CGFloat = 0.15
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor.black
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barSpace = barSpace
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
| mit | 8ffd3ae557c30f1b5bb5a7870ae62000 | 27.871921 | 148 | 0.517488 | 5.237712 | false | false | false | false |
timothypmiller/Autocomplete | Autocomplete/IconsStyleKit.swift | 1 | 6101 | //
// IconsStyleKit.swift
// Autocomplete
//
// Created by Timothy P Miller on 4/28/15.
// Copyright (c) 2015 Timothy P Miller. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
open class IconsStyleKit : NSObject {
//// Cache
fileprivate struct Cache {
static var imageOfCanvas2: UIImage?
static var canvas2Targets: [AnyObject]?
static var imageOfCanvas4: UIImage?
static var canvas4Targets: [AnyObject]?
}
//// Drawing Methods
open class func drawCanvas2() {
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 5.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 5.5, y: 18.5))
bezierPath.addLine(to: CGPoint(x: 9.5, y: 18.5))
bezierPath.addLine(to: CGPoint(x: 9.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 9.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 9.5, y: 6.5))
bezierPath.addLine(to: CGPoint(x: 14.5, y: 6.5))
bezierPath.addLine(to: CGPoint(x: 14.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 20.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 20.5, y: 12.5))
bezierPath.addLine(to: CGPoint(x: 24.5, y: 12.5))
bezierPath.addLine(to: CGPoint(x: 24.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 27.5, y: 4.5))
bezierPath.addLine(to: CGPoint(x: 29.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 34.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 34.5, y: 27.5))
UIColor.black.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
}
open class func drawCanvas4() {
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 0.5, y: 2.5))
bezier2Path.addCurve(to: CGPoint(x: 33.5, y: 2.5), controlPoint1: CGPoint(x: 33.5, y: 2.5), controlPoint2: CGPoint(x: 33.5, y: 2.5))
UIColor.black.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0.5, y: 31.5))
bezierPath.addCurve(to: CGPoint(x: 33.5, y: 31.5), controlPoint1: CGPoint(x: 33.5, y: 31.5), controlPoint2: CGPoint(x: 33.5, y: 31.5))
UIColor.black.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
//// Group
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 15.5, y: 4.5, width: 18, height: 25))
UIColor.black.setStroke()
ovalPath.lineWidth = 1
ovalPath.stroke()
//// Oval 2 Drawing
let oval2Path = UIBezierPath(ovalIn: CGRect(x: 20.5, y: 8.5, width: 8, height: 10))
UIColor.black.setStroke()
oval2Path.lineWidth = 1
oval2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 21.93, y: 17.66))
bezier3Path.addCurve(to: CGPoint(x: 16.79, y: 22.92), controlPoint1: CGPoint(x: 16.79, y: 22.92), controlPoint2: CGPoint(x: 16.79, y: 22.92))
UIColor.black.setStroke()
bezier3Path.lineWidth = 1
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 28.36, y: 18.97))
bezier4Path.addCurve(to: CGPoint(x: 30.93, y: 24.24), controlPoint1: CGPoint(x: 30.93, y: 24.24), controlPoint2: CGPoint(x: 30.93, y: 24.24))
UIColor.black.setStroke()
bezier4Path.lineWidth = 1
bezier4Path.stroke()
//// Star Drawing
let starPath = UIBezierPath()
starPath.move(to: CGPoint(x: 5.5, y: 13.25))
starPath.addLine(to: CGPoint(x: 7.35, y: 15.95))
starPath.addLine(to: CGPoint(x: 10.49, y: 16.88))
starPath.addLine(to: CGPoint(x: 8.5, y: 19.47))
starPath.addLine(to: CGPoint(x: 8.59, y: 22.75))
starPath.addLine(to: CGPoint(x: 5.5, y: 21.65))
starPath.addLine(to: CGPoint(x: 2.41, y: 22.75))
starPath.addLine(to: CGPoint(x: 2.5, y: 19.47))
starPath.addLine(to: CGPoint(x: 0.51, y: 16.88))
starPath.addLine(to: CGPoint(x: 3.65, y: 15.95))
starPath.close()
UIColor.black.setStroke()
starPath.lineWidth = 1
starPath.stroke()
}
//// Generated Images
open class var imageOfCanvas2: UIImage {
if Cache.imageOfCanvas2 != nil {
return Cache.imageOfCanvas2!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 34, height: 34), false, 0)
IconsStyleKit.drawCanvas2()
Cache.imageOfCanvas2 = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return Cache.imageOfCanvas2!
}
open class var imageOfCanvas4: UIImage {
if Cache.imageOfCanvas4 != nil {
return Cache.imageOfCanvas4!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 34, height: 34), false, 0)
IconsStyleKit.drawCanvas4()
Cache.imageOfCanvas4 = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return Cache.imageOfCanvas4!
}
//// Customization Infrastructure
@IBOutlet var canvas2Targets: [AnyObject]! {
get { return Cache.canvas2Targets }
set {
Cache.canvas2Targets = newValue
for target: AnyObject in newValue {
target.setImage(IconsStyleKit.imageOfCanvas2)
}
}
}
@IBOutlet var canvas4Targets: [AnyObject]! {
get { return Cache.canvas4Targets }
set {
Cache.canvas4Targets = newValue
for target: AnyObject in newValue {
target.setImage(IconsStyleKit.imageOfCanvas4)
}
}
}
}
@objc protocol StyleKitSettableImage {
func setImage(_ image: UIImage!)
}
@objc protocol StyleKitSettableSelectedImage {
func setSelectedImage(_ image: UIImage!)
}
| mit | 75386e6a2ea28dfc8a31fdd32716cf35 | 31.625668 | 149 | 0.603672 | 3.693099 | false | false | false | false |
barbosa/clappr-ios | Example/Tests/ContainerTests.swift | 1 | 18164 | import Quick
import Nimble
import Clappr
class ContainerTests: QuickSpec {
override func spec() {
describe("Container") {
var container: Container!
var playback: StubPlayback!
let options = [kSourceUrl : "http://globo.com/video.mp4"]
beforeEach() {
playback = StubPlayback(options: options)
container = Container(playback: playback)
}
describe("Initialization") {
it("Should have the playback as subview after rendered") {
container.render()
expect(playback.superview) == container
}
it("Should have a constructor that receive options") {
let options = ["aOption" : "option"]
let container = Container(playback: playback, options: options)
let option = container.options["aOption"] as! String
expect(option) == "option"
}
}
describe("Destroy") {
it("Should be removed from superview and destroy playback when destroy is called") {
let wrapperView = UIView()
wrapperView.addSubview(container)
container.destroy()
expect(playback.superview).to(beNil())
expect(container.superview).to(beNil())
}
it("Should stop listening to events after destroy is called") {
var callbackWasCalled = false
container.on("some-event") { _ in
callbackWasCalled = true
}
container.destroy()
container.trigger("some-event")
expect(callbackWasCalled) == false
}
}
describe("Event Binding") {
var eventWasTriggered = false
let eventCallback: EventCallback = { _ in
eventWasTriggered = true
}
beforeEach{
eventWasTriggered = false
}
it("Should trigger container progress event when playback progress event happens") {
let expectedStart: Float = 0.7, expectedEnd: Float = 15.4, expectedDuration: NSTimeInterval = 10
var start: Float!, end: Float!, duration: NSTimeInterval!
container.once(ContainerEvent.Progress.rawValue) { userInfo in
start = userInfo?["start_position"] as! Float
end = userInfo?["end_position"] as! Float
duration = userInfo?["duration"] as! NSTimeInterval
}
let userInfo: EventUserInfo = ["start_position": expectedStart,
"end_position": expectedEnd,
"duration": expectedDuration]
playback.trigger(PlaybackEvent.Progress.rawValue, userInfo: userInfo)
expect(start) == expectedStart
expect(end) == expectedEnd
expect(duration) == expectedDuration
}
it("Should trigger container time updated event when playback respective event happens") {
let expectedPosition: Float = 10.3, expectedDuration: NSTimeInterval = 12.7
var position: Float!, duration: NSTimeInterval!
container.once(ContainerEvent.TimeUpdated.rawValue) { userInfo in
position = userInfo?["position"] as! Float
duration = userInfo?["duration"] as! NSTimeInterval
}
let userInfo: EventUserInfo = ["position": expectedPosition, "duration": expectedDuration]
playback.trigger(PlaybackEvent.TimeUpdated.rawValue, userInfo: userInfo)
expect(position) == expectedPosition
expect(duration) == expectedDuration
}
it("Should trigger container loaded metadata event when playback respective event happens") {
let expectedDuration: NSTimeInterval = 20.0
var duration: NSTimeInterval!
container.once(ContainerEvent.LoadedMetadata.rawValue) { userInfo in
duration = userInfo?["duration"] as! NSTimeInterval
}
let userInfo: EventUserInfo = ["duration": expectedDuration]
playback.trigger(PlaybackEvent.LoadedMetadata.rawValue, userInfo: userInfo)
expect(duration) == expectedDuration
}
it("Should trigger container bit rate event when playback respective event happens") {
let expectedBitRate: NSTimeInterval = 11.0
var bitRate: NSTimeInterval!
container.once(ContainerEvent.BitRate.rawValue) { userInfo in
bitRate = userInfo?["bit_rate"] as! NSTimeInterval
}
let userInfo: EventUserInfo = ["bit_rate": expectedBitRate]
playback.trigger(PlaybackEvent.BitRate.rawValue, userInfo: userInfo)
expect(bitRate) == expectedBitRate
}
it("Should trigger container DVR state event when playback respective event happens with params") {
var dvrInUse = false
container.once(ContainerEvent.PlaybackDVRStateChanged.rawValue) { userInfo in
dvrInUse = userInfo?["dvr_in_use"] as! Bool
}
let userInfo: EventUserInfo = ["dvr_in_use": true]
playback.trigger(PlaybackEvent.DVRStateChanged.rawValue, userInfo: userInfo)
expect(dvrInUse).to(beTrue())
}
it("Should trigger container Error event when playback respective event happens with params") {
var error = ""
container.once(ContainerEvent.Error.rawValue) { userInfo in
error = userInfo?["error"] as! String
}
let userInfo: EventUserInfo = ["error": "Error"]
playback.trigger(PlaybackEvent.Error.rawValue, userInfo: userInfo)
expect(error) == "Error"
}
it("Should update container dvrInUse property on playback DVRSTateChanged event") {
let userInfo: EventUserInfo = ["dvr_in_use": true]
expect(container.dvrInUse).to(beFalse())
playback.trigger(PlaybackEvent.DVRStateChanged.rawValue, userInfo: userInfo)
expect(container.dvrInUse).to(beTrue())
}
it("Should be ready after playback ready event is triggered") {
expect(container.ready) == false
playback.trigger(PlaybackEvent.Ready.rawValue)
expect(container.ready) == true
}
it("Should trigger buffering event after playback respective event is triggered") {
container.on(ContainerEvent.Buffering.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.Buffering.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger buffer full event after playback respective event is triggered") {
container.on(ContainerEvent.BufferFull.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.BufferFull.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger settings event after playback respective event is triggered") {
container.on(ContainerEvent.SettingsUpdated.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.SettingsUpdated.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger HD updated event after playback respective event is triggered") {
container.on(ContainerEvent.HighDefinitionUpdated.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.HighDefinitionUpdated.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger State Changed event after playback respective event is triggered") {
container.on(ContainerEvent.PlaybackStateChanged.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.StateChanged.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger Media Control Disabled event after playback respective event is triggered") {
container.on(ContainerEvent.MediaControlDisabled.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.MediaControlDisabled.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger Media Control Enabled event after playback respective event is triggered") {
container.on(ContainerEvent.MediaControlEnabled.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.MediaControlEnabled.rawValue)
expect(eventWasTriggered) == true
}
it("Should update mediaControlEnabled property after playback MediaControleEnabled or Disabled is triggered") {
playback.trigger(PlaybackEvent.MediaControlEnabled.rawValue)
expect(container.mediaControlEnabled).to(beTrue())
playback.trigger(PlaybackEvent.MediaControlDisabled.rawValue)
expect(container.mediaControlEnabled).to(beFalse())
}
it("Should trigger Ended event after playback respective event is triggered") {
container.on(ContainerEvent.Ended.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.Ended.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger Play event after playback respective event is triggered") {
container.on(ContainerEvent.Play.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.Play.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger Pause event after playback respective event is triggered") {
container.on(ContainerEvent.Pause.rawValue, callback: eventCallback)
playback.trigger(PlaybackEvent.Pause.rawValue)
expect(eventWasTriggered) == true
}
it("Should trigger it's Stop event after stop is called") {
container.on(ContainerEvent.Stop.rawValue, callback: eventCallback)
container.stop()
expect(eventWasTriggered) == true
}
context("Bindings with mocked playback") {
class MockedSettingsPlayback: Playback {
var stopWasCalled = false , playWasCalled = false, pauseWasCalled = false
override var settings: [String: AnyObject] {
return ["foo": "bar"]
}
override var isPlaying: Bool {
return true
}
override func stop() {
stopWasCalled = true
}
override func pause() {
pauseWasCalled = true
}
override func play() {
playWasCalled = true
}
}
var mockedPlayback: MockedSettingsPlayback!
beforeEach() {
mockedPlayback = MockedSettingsPlayback(options: options)
container = Container(playback: mockedPlayback)
}
it("Should update it's settings after playback's settings update event") {
mockedPlayback.trigger(PlaybackEvent.SettingsUpdated.rawValue)
let fooSetting = container.settings["foo"] as? String
expect(fooSetting) == "bar"
}
it("Should update it's settings after playback's DVR State changed event") {
mockedPlayback.trigger(PlaybackEvent.DVRStateChanged.rawValue)
let fooSetting = container.settings["foo"] as? String
expect(fooSetting) == "bar"
}
it("Should call playback's stop method after calling respective method on container") {
container.stop()
expect(mockedPlayback.stopWasCalled).to(beTrue())
}
it("Should call playback's play method after calling respective method on container") {
container.play()
expect(mockedPlayback.playWasCalled).to(beTrue())
}
it("Should call playback's pause method after calling respective method on container") {
container.pause()
expect(mockedPlayback.pauseWasCalled).to(beTrue())
}
it("Should return playback 'isPlaying' status when respective property is accessed") {
expect(container.isPlaying) == mockedPlayback.isPlaying
}
}
}
describe("Plugins") {
class FakeUIContainerPlugin: UIContainerPlugin {}
class AnotherUIContainerPlugin: UIContainerPlugin {}
it("Should be able to add a new container UIPlugin") {
container.addPlugin(FakeUIContainerPlugin())
expect(container.plugins).toNot(beEmpty())
}
it("Should be able to check if has a plugin with given class") {
container.addPlugin(FakeUIContainerPlugin())
expect(container.hasPlugin(FakeUIContainerPlugin)).to(beTrue())
}
it("Should return false if plugin isn't on container") {
container.addPlugin(FakeUIContainerPlugin())
expect(container.hasPlugin(AnotherUIContainerPlugin)).to(beFalse())
}
it("Should add self reference on the plugin") {
let plugin = FakeUIContainerPlugin()
container.addPlugin(plugin)
expect(plugin.container) == container
}
it("Should add plugin as subview after rendered") {
let plugin = FakeUIContainerPlugin()
container.addPlugin(plugin)
container.render()
expect(plugin.superview) == container
}
}
describe("Source") {
it("Should be able to load a source") {
let container = Container(playback: NoOpPlayback(options: [:]))
expect(container.playback.pluginName) == "NoOp"
container.load("http://globo.com/video.mp4")
expect(container.playback.pluginName) == "AVPlayback"
expect(container.playback.superview) == container
}
it("Should be able to load a source with mime type") {
let container = Container(playback: NoOpPlayback(options: [:]))
expect(container.playback.pluginName) == "NoOp"
container.load("http://globo.com/video", mimeType: "video/mp4")
expect(container.playback.pluginName) == "AVPlayback"
expect(container.playback.superview) == container
}
}
}
}
class StubPlayback: Playback {
override var pluginName: String {
return "stubPlayback"
}
}
} | bsd-3-clause | edcdfe1b9fceb335da601c65efe7e58f | 47.31117 | 127 | 0.494329 | 6.916984 | false | false | false | false |
crazypoo/PTools | Pods/CollectionViewPagingLayout/Lib/Snapshot/SnapshotContainerView.swift | 1 | 2212 | //
// SnapshotContainerView.swift
// CollectionViewPagingLayout
//
// Created by Amir on 07/03/2020.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
public class SnapshotContainerView: UIView {
// MARK: Properties
public let snapshots: [UIView]
public let identifier: String
public let snapshotSize: CGSize
public let pieceSizeRatio: CGSize
private weak var targetView: UIView?
// MARK: Lifecycle
public init?(targetView: UIView, pieceSizeRatio: CGSize, identifier: String) {
var snapshots: [UIView] = []
self.pieceSizeRatio = pieceSizeRatio
guard pieceSizeRatio.width > 0, pieceSizeRatio.height > 0 else {
return nil
}
var x: CGFloat = 0
var y: CGFloat = 0
var width = pieceSizeRatio.width * targetView.frame.width
var height = pieceSizeRatio.height * targetView.frame.height
if width > targetView.frame.width {
width = targetView.frame.width
}
if height > targetView.frame.height {
height = targetView.frame.height
}
while true {
if y >= targetView.frame.height {
break
}
let frame = CGRect(x: x, y: y, width: min(width, targetView.frame.width - x), height: min(height, targetView.frame.height - y))
if let view = targetView.resizableSnapshotView(from: frame, afterScreenUpdates: true, withCapInsets: .zero) {
view.frame = frame
snapshots.append(view)
}
x += width
if x >= targetView.frame.width {
x = 0
y += height
}
}
if snapshots.isEmpty {
return nil
}
self.targetView = targetView
self.identifier = identifier
self.snapshots = snapshots
snapshotSize = targetView.bounds.size
super.init(frame: targetView.frame)
snapshots.forEach {
self.addSubview($0)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported")
}
}
| mit | 4bb3de9ebc0af008cc2d11b4540f2fc3 | 28.48 | 139 | 0.57033 | 4.902439 | false | false | false | false |
crazypoo/PTools | Pods/JXSegmentedView/Sources/Number/JXSegmentedNumberCell.swift | 1 | 1731 | //
// JXSegmentedNumberCell.swift
// JXSegmentedView
//
// Created by jiaxin on 2018/12/28.
// Copyright © 2018 jiaxin. All rights reserved.
//
import UIKit
open class JXSegmentedNumberCell: JXSegmentedTitleCell {
public let numberLabel = UILabel()
open override func commonInit() {
super.commonInit()
numberLabel.isHidden = true
numberLabel.textAlignment = .center
numberLabel.layer.masksToBounds = true
contentView.addSubview(numberLabel)
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let myItemModel = itemModel as? JXSegmentedNumberItemModel else {
return
}
numberLabel.sizeToFit()
let height = myItemModel.numberHeight
numberLabel.layer.cornerRadius = height/2
numberLabel.bounds.size = CGSize(width: numberLabel.bounds.size.width + myItemModel.numberWidthIncrement, height: height)
numberLabel.center = CGPoint(x: titleLabel.frame.maxX + myItemModel.numberOffset.x, y: titleLabel.frame.minY + myItemModel.numberOffset.y)
}
open override func reloadData(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) {
super.reloadData(itemModel: itemModel, selectedType: selectedType )
guard let myItemModel = itemModel as? JXSegmentedNumberItemModel else {
return
}
numberLabel.backgroundColor = myItemModel.numberBackgroundColor
numberLabel.textColor = myItemModel.numberTextColor
numberLabel.text = myItemModel.numberString
numberLabel.font = myItemModel.numberFont
numberLabel.isHidden = myItemModel.number == 0
setNeedsLayout()
}
}
| mit | 9e00eacfe8260798a125de5c09c72e3f | 32.269231 | 146 | 0.704046 | 5.306748 | false | false | false | false |
rock-n-code/Kashmir | Kashmir/iOS/Features/Cell/Extensions/CellExtensions.swift | 1 | 2520 | //
// CellExtensions.swift
// Kashmir_iOS
//
// Created by Javier Cicchelli on 19/01/2018.
// Copyright © 2018 Rock & Code. All rights reserved.
//
import UIKit
public extension Cell where Self: UITableViewCell {
// MARK: Static
/**
Registers a nib object containing the cell into a table.
- parameter tableView: A table view in which to register the nib object.
*/
static func registerNib(in tableView: UITableView) {
let bundle = Bundle(for: self)
let nib = UINib(nibName: nibName,
bundle: bundle)
tableView.register(nib,
forCellReuseIdentifier: reuseIdentifier)
}
/**
Returns a reusable table view cell object dequeued from a specified index in a table view.
- parameters:
- tableView: A table view from where to dequeue the reusable cell.
- indexPath: The index path specifying the location of the cell.
- throws: A `CellError` error is thrown during the dequeuing of the cell.
- returns: A dequeued table view cell object.
*/
static func dequeue(from tableView: UITableView,
at indexPath: IndexPath) throws -> Self {
guard
let dequededCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier,
for: indexPath) as? Self
else {
throw CellError.dequeueFailed
}
return dequededCell
}
}
public extension Cell where Self: UICollectionViewCell {
// MARK: Static
/**
Registers a nib object containing the cell into a collection.
- parameter collectionView: A collection view in which to register the nib object.
*/
static func registerNib(in collectionView: UICollectionView) {
let bundle = Bundle(for: self)
let nib = UINib(nibName: nibName,
bundle: bundle)
collectionView.register(nib,
forCellWithReuseIdentifier: reuseIdentifier)
}
/**
Returns a reusable collection view cell object dequeued from a specified index in a collection view.
- parameters:
- collectionView: A collection view from where to dequeue the reusable cell.
- indexPath: The index path specifying the location of the cell.
- throws: A `CellError` error is thrown during the dequeuing of the cell.
- returns: A dequeued collection view cell object.
*/
static func dequeue(from collectionView: UICollectionView,
at indexPath: IndexPath) throws -> Self {
guard
let dequededCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as? Self
else {
throw CellError.dequeueFailed
}
return dequededCell
}
}
| mit | b97ca69e82c946ade877e25930c6b97c | 26.681319 | 101 | 0.719333 | 4.156766 | false | false | false | false |
FabrizioBrancati/BFKit-Swift | Sources/BFKit/Apple/UIKit/UITextView+Extensions.swift | 1 | 6018 | //
// UITextView+Extensions.swift
// BFKit-Swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2019 Fabrizio Brancati.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - UITextView extension
/// This extesion adds some useful functions to UITextView.
public extension UITextView {
// MARK: - Functions
/// Create an UITextView and set some parameters.
///
/// - Parameters:
/// - frame: TextView frame.
/// - text: TextView text.
/// - font: TextView text font.
/// - textColor: TextView text color.
/// - alignment: TextView text alignment.
/// - dataDetectorTypes: TextView data detector types.
/// - editable: Set if TextView is editable.
/// - selectable: Set if TextView is selectable.
/// - returnKeyType: TextView return key type.
/// - keyboardType: TextView keyboard type.
/// - secure: Set if the TextView is secure or not.
/// - autocapitalizationType: TextView text capitalization.
/// - keyboardAppearance: TextView keyboard appearence.
/// - enablesReturnKeyAutomatically: Set if the TextView has to automatically enables the return key.
/// - autocorrectionType: TextView auto correction type.
/// - delegate: TextView delegate. Set nil if it has no delegate.
convenience init(frame: CGRect, text: String, font: UIFont, textColor: UIColor, alignment: NSTextAlignment, dataDetectorTypes: UIDataDetectorTypes, editable: Bool, selectable: Bool, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, autocorrectionType: UITextAutocorrectionType, delegate: UITextViewDelegate?) {
self.init(frame: frame)
self.text = text
self.autocorrectionType = autocorrectionType
self.textAlignment = alignment
self.keyboardType = keyboardType
self.autocapitalizationType = autocapitalizationType
self.textColor = textColor
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
isSecureTextEntry = secure
self.keyboardAppearance = keyboardAppearance
self.font = font
self.delegate = delegate
self.dataDetectorTypes = dataDetectorTypes
isEditable = editable
isSelectable = selectable
}
/// Create an UITextView and set some parameters.
///
/// - Parameters:
/// - frame: TextView frame.
/// - text: TextView text.
/// - font: TextView text font name.
/// - fontSize: TextView text size.
/// - textColor: TextView text color.
/// - alignment: TextView text alignment.
/// - dataDetectorTypes: TextView data detector types.
/// - editable: Set if TextView is editable.
/// - selectable: Set if TextView is selectable.
/// - returnKeyType: TextView return key type.
/// - keyboardType: TextView keyboard type.
/// - secure: Set if the TextView is secure or not.
/// - autocapitalizationType: TextView text capitalization.
/// - keyboardAppearance: TextView keyboard appearence.
/// - enablesReturnKeyAutomatically: Set if the TextView has to automatically enables the return key.
/// - autocorrectionType: TextView auto correction type.
/// - delegate: TextView delegate. Set nil if it has no delegate.
convenience init(frame: CGRect, text: String, font: FontName, fontSize: CGFloat, textColor: UIColor, alignment: NSTextAlignment, dataDetectorTypes: UIDataDetectorTypes, editable: Bool, selectable: Bool, returnKeyType: UIReturnKeyType, keyboardType: UIKeyboardType, secure: Bool, autocapitalizationType: UITextAutocapitalizationType, keyboardAppearance: UIKeyboardAppearance, enablesReturnKeyAutomatically: Bool, autocorrectionType: UITextAutocorrectionType, delegate: UITextViewDelegate?) {
self.init(frame: frame)
self.text = text
self.autocorrectionType = autocorrectionType
textAlignment = alignment
self.keyboardType = keyboardType
self.autocapitalizationType = autocapitalizationType
self.textColor = textColor
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
isSecureTextEntry = secure
self.keyboardAppearance = keyboardAppearance
self.font = UIFont(fontName: font, size: fontSize)
self.delegate = delegate
self.dataDetectorTypes = dataDetectorTypes
isEditable = editable
isSelectable = selectable
}
/// Paste the pasteboard text to UITextView
func pasteFromPasteboard() {
text = UIPasteboard.getString()
}
/// Copy UITextView text to pasteboard
func copyToPasteboard() {
UIPasteboard.copy(text: text)
}
}
| mit | 229de9f19071b21b03230b7a7283f275 | 48.327869 | 494 | 0.706713 | 5.33984 | false | false | false | false |
Swift-Squirrel/Squirrel | Sources/Squirrel/HTTPHeaderElement.swift | 1 | 7009 | //
// HTTPHeaders.swift
// Micros
//
// Created by Filip Klembara on 6/26/17.
//
//
/// HTTP header
///
/// - contentLength: Content length
/// - contentEncoding: Content encoding
/// - contentType: Content type
/// - location: Location
public enum HTTPHeaderElement {
case contentLength(size: Int)
case contentEncoding(HTTPHeaderElement.Encoding)
case contentType(HTTPHeaderElement.ContentType)
case location(location: String)
case range(UInt, UInt)
case contentRange(start: UInt, end: UInt, from: UInt)
case connection(HTTPHeaderElement.Connection)
}
// MARK: - Hashable
extension HTTPHeaderElement: Hashable {
/// Hash value
public var hashValue: Int {
switch self {
case .contentType:
return 0
case .contentEncoding:
return 1
case .contentLength:
return 2
case .location:
return 3
case .range:
return 4
case .contentRange:
return 5
case .connection:
return 6
}
}
/// Check string equality
///
/// - Parameters:
/// - lhs: lhs
/// - rhs: rhs
/// - Returns: `lhs.description == rhs.description`
public static func == (lhs: HTTPHeaderElement, rhs: HTTPHeaderElement) -> Bool {
return lhs.description == rhs.description
}
}
// MARK: - Sub enums
public extension HTTPHeaderElement {
/// Connection
///
/// - keepAlive
/// - close
public enum Connection: String, CustomStringConvertible {
/// rawValue of case
public var description: String {
return rawValue
}
case keepAlive = "keep-alive"
case close
}
/// Encoding
///
/// - gzip
/// - deflate
public enum Encoding: String, CustomStringConvertible {
case gzip
case deflate
/// Returns raw value
public var description: String {
return self.rawValue
}
}
/// Content type
enum ContentType: String, CustomStringConvertible {
// Image
case png
case jpeg
case svg = "svg+xml"
//Text
case html
case plain
case css
// Application
case js = "javascript"
case json = "json"
case formUrlencoded = "x-www-form-urlencoded"
case forceDownload = "force-download"
// multipart
case formData = "form-data"
// video
case mp4
case ogg
case mov = "quicktime"
case webm
case wmv = "x-ms-wmv"
case avi = "x-msvideo"
/// MIME representation
public var description: String {
let mime: String
switch self {
case .png, .jpeg, .svg:
mime = "image"
case .html, .plain, .css:
mime = "text"
case .js, .json, .formUrlencoded, .forceDownload:
mime = "application"
case .formData:
mime = "multipart"
case .mp4, .ogg, .mov, .webm, .wmv, .avi:
mime = "video"
}
return "\(mime)/\(rawValue)"
}
}
}
// MARK: - Getting values from HTTPHeader
extension HTTPHeaderElement: CustomStringConvertible {
/// <key>: <value> description
public var description: String {
let (key, value) = keyValue
return "\(key): \(value)"
}
/// Returns key and value
public var keyValue: (key: String, value: String) {
let key: HTTPHeaderKey
let value: String
switch self {
case .contentLength(let size):
key = .contentLength
value = size.description
case .contentEncoding(let encoding):
key = .contentEncoding
value = encoding.description
case .contentType(let type):
key = .contentType
value = type.description
case .location(let location):
key = .location
value = location
case .range(let bottom, let top):
key = .range
value = "bytes=\(bottom)-\(top)"
case .contentRange(let start, let end, let from):
key = .contentRange
value = "bytes \(start)-\(end)/\(from)"
case .connection(let con):
key = .connection
value = con.description
}
return (key.description, value)
}
}
/// Request-line in HTTP request
public enum RequestLine {
/// HTTP Method
///
/// - post: POST
/// - get: GET
/// - put: PUT
/// - delete: DELETE
/// - head: HEAD
/// - option: OPTIONS
/// - patch: PATCH
public enum Method: String, CustomStringConvertible {
case post = "POST"
case get = "GET"
case put = "PUT"
case delete = "DELETE"
case head = "HEAD"
case options = "OPTIONS"
case patch = "PATCH"
/// Uppercased rawValue
public var description: String {
return rawValue
}
}
/// HTTP protocol
///
/// - http11: 1.1
public enum HTTPProtocol: String, CustomStringConvertible {
case http11 = "HTTP/1.1"
init?(rawHTTPValue value: String) {
guard value == "HTTP/1.1" else {
return nil
}
self = .http11
}
/// Returns `rawValue`
/// - Note: Value is uppercased
public var description: String {
return rawValue
}
}
}
/// Check if pattern match value
///
/// - Parameters:
/// - pattern: pattern
/// - value: value
/// - Returns: if pattern matches value
public func ~= (pattern: HTTPHeaderElement.ContentType, value: String) -> Bool {
guard let valueType = value.split(separator: "/", maxSplits: 1).last?
.split(separator: ";").first?.split(separator: " ").first,
let patternValue = HTTPHeaderElement.ContentType(rawValue: valueType.description) else {
return false
}
guard patternValue == pattern else {
return false
}
return true
}
/// Check lowercased equality
///
/// - Parameters:
/// - lhs: lhs
/// - rhs: rhs
/// - Returns: If string representation in lowercased is same
public func == (lhs: String?, rhs: HTTPHeaderElement.ContentType) -> Bool {
return lhs?.lowercased() == rhs.description.lowercased()
}
/// Check lowercased equality
///
/// - Parameters:
/// - lhs: lhs
/// - rhs: rhs
/// - Returns: If string representation in lowercased is same
public func == (lhs: String?, rhs: HTTPHeaderElement.Connection) -> Bool {
return lhs?.lowercased() == rhs.description.lowercased()
}
/// Check lowercased equality
///
/// - Parameters:
/// - lhs: lhs
/// - rhs: rhs
/// - Returns: If string representation in lowercased is same
public func == (lhs: String?, rhs: HTTPHeaderElement.Encoding) -> Bool {
return lhs?.lowercased() == rhs.description.lowercased()
}
| apache-2.0 | 12c74b3c9a9f8d00cd9f31bfa681447d | 24.673993 | 96 | 0.556285 | 4.581046 | false | false | false | false |
15cm/AMM | AMM/Menu/TaskMenuItemViewController.swift | 1 | 2794 | //
// AMMTaskMenuItemViewController.swift
// AMM
//
// Created by Sinkerine on 30/01/2017.
// Copyright © 2017 sinkerine. All rights reserved.
//
import Cocoa
class TaskMenuItemViewController: NSViewController {
@objc var task: Aria2Task = Aria2Task()
@IBOutlet var viewDark: NSView!
init() {
super.init(nibName: NSNib.Name(rawValue: "TaskMenuItemViewController"), bundle: nil)
}
init?(task: Aria2Task) {
self.task = task
super.init(nibName: NSNib.Name(rawValue: "TaskMenuItemViewController"), bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
if AMMPreferences.instance.darkModeEnabled {
self.view = viewDark
}
super.viewDidLoad()
// Do view setup here.
}
}
// KVO bindings
extension Aria2Task {
@objc dynamic var statusIcon: NSImage {
switch status {
case .active:
return #imageLiteral(resourceName: "fa-download")
case .paused:
return #imageLiteral(resourceName: "fa-pause")
case .complete:
return #imageLiteral(resourceName: "fa-check")
case .stopped:
return #imageLiteral(resourceName: "fa-stop")
case .error:
return #imageLiteral(resourceName: "iconmoon-cross")
case .unknown:
return #imageLiteral(resourceName: "fa-question")
default:
return #imageLiteral(resourceName: "fa-question")
}
}
@objc dynamic class func keyPathsForValuesAffectingStatusIcon() -> Set<String> {
return Set(["statusRawValue"])
}
@objc dynamic var percentage: Double {
return totalLength == 0 ? 0 : Double(completedLength) / Double(totalLength) * 100
}
@objc dynamic class func keyPathsForValuesAffectingPercentage() -> Set<String> {
return Set(["completedLength", "totalLength"])
}
@objc dynamic var downloadSpeedReadable: String {
return Aria2.getReadable(length: downloadSpeed) + "/s"
}
@objc dynamic class func keyPathsForValuesAffectingDownloadSpeedReadable() -> Set<String> {
return Set(["downloadSpeed"])
}
@objc dynamic var uploadSpeedReadable: String {
return Aria2.getReadable(length: uploadSpeed) + "/s"
}
@objc dynamic class func keyPathsForValuesAffectingUploadSpeedReadable() -> Set<String> {
return Set(["uploadSpeed"])
}
@objc dynamic var totalLengthReadable: String {
return Aria2.getReadable(length: totalLength)
}
@objc dynamic class func keyPathsForValuesAffectingTotalLengthReadable() -> Set<String> {
return Set(["totalLength"])
}
}
| gpl-3.0 | ef82e73275c07876db464bf5e7a8ea18 | 30.382022 | 95 | 0.636233 | 4.578689 | false | false | false | false |
matsprea/omim | iphone/Maps/Core/Theme/Colors.swift | 1 | 8309 | class DayColors: IColors {
var clear = UIColor.clear
var primaryDark = UIColor(24, 128, 68, alpha100)
var primary = UIColor(32, 152, 82, alpha100)
var secondary = UIColor(45, 137, 83, alpha100)
// Light green color
var primaryLight = UIColor(36, 180, 98, alpha100)
var menuBackground = UIColor(255, 255, 255, alpha90)
var downloadBadgeBackground = UIColor(255, 55, 35, alpha100)
// Background color && press color
var pressBackground = UIColor(245, 245, 245, alpha100)
// Red color (use for status closed in place page)
var red = UIColor(230, 15, 35, alpha100)
var errorPink = UIColor(246, 60, 51, alpha12)
// Orange color (use for status 15 min in place page)
var orange = UIColor(255, 120, 5, alpha100)
// Blue color (use for links and phone numbers)
var linkBlue = UIColor(30, 150, 240, alpha100)
var linkBlueHighlighted = UIColor(30, 150, 240, alpha30)
var linkBlueDark = UIColor(25, 135, 215, alpha100)
var buttonRed = UIColor(244, 67, 67, alpha100)
var buttonRedHighlighted = UIColor(183, 28, 28, alpha100)
var blackPrimaryText = UIColor(0, 0, 0, alpha87)
var blackSecondaryText = UIColor(0, 0, 0, alpha54)
var blackHintText = UIColor(0, 0, 0, alpha26)
var blackDividers = UIColor(0, 0, 0, alpha12)
var solidDividers = UIColor(224, 224, 224, alpha100)
var white = UIColor(255, 255, 255, alpha100)
var whitePrimaryText = UIColor(255, 255, 255, alpha87);
var whitePrimaryTextHighlighted = UIColor(255, 255, 255, alpha30);
var whiteSecondaryText = UIColor(255, 255, 255, alpha54)
var whiteHintText = UIColor(255, 255, 255, alpha30)
var buttonDisabledBlueText = UIColor(3, 122, 255, alpha26)
var alertBackground = UIColor(255, 255, 255, alpha90)
var blackOpaque = UIColor(0, 0, 0, alpha04)
var toastBackground = UIColor(255, 255, 255, alpha87)
var statusBarBackground = UIColor(255, 255, 255, alpha36)
var bannerBackground = UIColor(242, 245, 212, alpha100)
var searchPromoBackground = UIColor(249, 251, 231, alpha100)
var border = UIColor(0, 0, 0, alpha04)
var discountBackground = UIColor(240, 100, 60, alpha100)
var discountText = UIColor(60, 64, 68, alpha100)
var bookmarkSubscriptionBackground = UIColor(240, 252, 255, alpha100)
var bookmarkSubscriptionScrollBackground = UIColor(137, 217, 255, alpha100)
var bookmarkSubscriptionFooterBackground = UIColor(47, 58, 73, alpha100)
var bookingBackground = UIColor(25, 69, 125, alpha100)
var opentableBackground = UIColor(218, 55, 67, alpha100)
var transparentGreen = UIColor(233, 244, 233, alpha26)
var ratingRed = UIColor(229, 57, 53, alpha100)
var ratingOrange = UIColor(244, 81, 30, alpha100)
var ratingYellow = UIColor(245, 176, 39, alpha100)
var ratingLightGreen = UIColor(124, 179, 66, alpha100)
var ratingGreen = UIColor(67, 160, 71, alpha100)
var bannerButtonBackground = UIColor(60, 140, 60, alpha70)
var facebookButtonBackground = UIColor(59, 89, 152, alpha100);
var facebookButtonBackgroundDisabled = UIColor(59, 89, 152, alpha70);
var allPassSubscriptionTitle = UIColor(0, 0, 0, alpha100)
var allPassSubscriptionSubTitle = UIColor(0, 0, 0, alpha87)
var allPassSubscriptionDescription = UIColor(255, 255, 255, alpha100)
var allPassSubscriptionMonthlyBackground = UIColor(224, 224, 224, alpha80)
var allPassSubscriptionYearlyBackground = UIColor(30, 150, 240, alpha100)
var allPassSubscriptionMonthlyTitle = UIColor(255, 255, 255, alpha100)
var allPassSubscriptionDiscountBackground = UIColor(245, 210, 12, alpha100)
var allPassSubscriptionTermsTitle = UIColor(255, 255, 255, alpha70)
var fadeBackground = UIColor(0, 0, 0, alpha80)
var blackStatusBarBackground = UIColor(0, 0, 0, alpha80)
var elevationPreviewTint = UIColor(193, 209, 224, alpha30)
var elevationPreviewSelector = UIColor(red: 0.757, green: 0.82, blue: 0.878, alpha: 1)
var shadow = UIColor(0, 0, 0, alpha100)
var chartLine = UIColor(red: 0.118, green: 0.588, blue: 0.941, alpha: 1)
var chartShadow = UIColor(red: 0.118, green: 0.588, blue: 0.941, alpha: 0.12)
var cityColor = UIColor(red: 0.4, green: 0.225, blue: 0.75, alpha: 1)
var outdoorColor = UIColor(red: 0.235, green: 0.549, blue: 0.235, alpha: 1)
}
class NightColors: IColors {
var clear = UIColor.clear
var primaryDark = UIColor(25, 30, 35, alpha100)
var primary = UIColor(45, 50, 55, alpha100)
var secondary = UIColor(0x25, 0x28, 0x2b, alpha100)
// Light green color
var primaryLight = UIColor(65, 70, 75, alpha100)
var menuBackground = UIColor(45, 50, 55, alpha90)
var downloadBadgeBackground = UIColor(230, 70, 60, alpha100)
// Background color && press color
var pressBackground = UIColor(50, 54, 58, alpha100)
// Red color (use for status closed in place page)
var red = UIColor(230, 70, 60, alpha100)
var errorPink = UIColor(246, 60, 51, alpha26)
// Orange color (use for status 15 min in place page)
var orange = UIColor(250, 190, 10, alpha100)
// Blue color (use for links and phone numbers)
var linkBlue = UIColor(80, 195, 240, alpha100)
var linkBlueHighlighted = UIColor(60, 155, 190, alpha30)
var linkBlueDark = UIColor(75, 185, 230, alpha100)
var buttonRed = UIColor(244, 67, 67, alpha100)
var buttonRedHighlighted = UIColor(183, 28, 28, alpha100)
var blackPrimaryText = UIColor(255, 255, 255, alpha90)
var blackSecondaryText = UIColor(255, 255, 255, alpha70)
var blackHintText = UIColor(255, 255, 255, alpha30)
var blackDividers = UIColor(255, 255, 255, alpha12)
var solidDividers = UIColor(84, 86, 90, alpha100)
var white = UIColor(60, 64, 68, alpha100)
var whitePrimaryText = UIColor(255, 255, 255, alpha87)
var whitePrimaryTextHighlighted = UIColor(255, 255, 255, alpha30)
var whiteSecondaryText = UIColor(0, 0, 0, alpha70)
var whiteHintText = UIColor(0, 0, 0, alpha26)
var buttonDisabledBlueText = UIColor(255, 230, 140, alpha30)
var alertBackground = UIColor(60, 64, 68, alpha90)
var blackOpaque = UIColor(255, 255, 255, alpha04)
var toastBackground = UIColor(0, 0, 0, alpha87)
var statusBarBackground = UIColor(0, 0, 0, alpha32)
var bannerBackground = UIColor(255, 255, 255, alpha54)
var searchPromoBackground = UIColor(71, 75, 79, alpha100)
var border = UIColor(255, 255, 255, alpha04)
var discountBackground = UIColor(240, 100, 60, alpha100)
var discountText = UIColor(60, 64, 68, alpha100)
var bookmarkSubscriptionBackground = UIColor(60, 64, 68, alpha100)
var bookmarkSubscriptionScrollBackground = UIColor(137, 217, 255, alpha100)
var bookmarkSubscriptionFooterBackground = UIColor(47, 58, 73, alpha100)
var bookingBackground = UIColor(25, 69, 125, alpha100)
var opentableBackground = UIColor(218, 55, 67, alpha100)
var transparentGreen = UIColor(233, 244, 233, alpha26)
var ratingRed = UIColor(229, 57, 53, alpha100)
var ratingOrange = UIColor(244, 81, 30, alpha100)
var ratingYellow = UIColor(245, 176, 39, alpha100)
var ratingLightGreen = UIColor(124, 179, 66, alpha100)
var ratingGreen = UIColor(67, 160, 71, alpha100)
var bannerButtonBackground = UIColor(89, 115, 128, alpha70)
var facebookButtonBackground = UIColor(59, 89, 152, alpha100);
var facebookButtonBackgroundDisabled = UIColor(59, 89, 152, alpha70);
var allPassSubscriptionTitle = UIColor(0, 0, 0, alpha100)
var allPassSubscriptionSubTitle = UIColor(0, 0, 0, alpha87)
var allPassSubscriptionDescription = UIColor(255, 255, 255, alpha100)
var allPassSubscriptionMonthlyBackground = UIColor(224, 224, 224, alpha80)
var allPassSubscriptionYearlyBackground = UIColor(30, 150, 240, alpha100)
var allPassSubscriptionMonthlyTitle = UIColor(255, 255, 255, alpha100)
var allPassSubscriptionDiscountBackground = UIColor(245, 210, 12, alpha100)
var allPassSubscriptionTermsTitle = UIColor(255, 255, 255, alpha70)
var fadeBackground = UIColor(0, 0, 0, alpha80)
var blackStatusBarBackground = UIColor(0, 0, 0, alpha80)
var elevationPreviewTint = UIColor(0, 0, 0, alpha54)
var elevationPreviewSelector = UIColor(red: 0.404, green: 0.439, blue: 0.475, alpha: 1)
var shadow = UIColor.clear
var chartLine = UIColor(red: 0.294, green: 0.725, blue: 0.902, alpha: 1)
var chartShadow = UIColor(red: 0.294, green: 0.725, blue: 0.902, alpha: 0.12)
var cityColor = UIColor(152, 103, 252, alpha100)
var outdoorColor = UIColor(147, 191, 57, alpha100)
}
| apache-2.0 | 1699f8bd7bddf18bc8690468439ca394 | 54.765101 | 89 | 0.728969 | 3.476569 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Steps4Impact/Settings/Cells/SettingsProfileCell.swift | 1 | 3330 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
struct SettingsProfileCellContext: CellContext {
let identifier: String = SettingsProfileCell.identifier
let imageURL: URL?
let name: String
let teamName: String
let membership: String
}
class SettingsProfileCell: ConfigurableTableViewCell {
static let identifier = "SettingsProfileCell"
private let profileImageView = WebImageView()
private let nameLabel = UILabel(typography: .title)
private let teamNameLabel = UILabel(typography: .smallRegular)
private let membershipLabel = UILabel(typography: .smallRegular)
override func commonInit() {
super.commonInit()
profileImageView.clipsToBounds = true
contentView.backgroundColor = Style.Colors.white
contentView.addSubview(profileImageView) {
$0.height.width.equalTo(Style.Size.s64)
$0.centerY.equalToSuperview()
$0.leading.equalToSuperview().inset(Style.Padding.p32)
}
let stackView = UIStackView()
stackView.axis = .vertical
stackView.addArrangedSubviews(nameLabel, teamNameLabel, membershipLabel)
contentView.addSubview(stackView) {
$0.top.bottom.trailing.equalToSuperview().inset(Style.Padding.p16)
$0.leading.equalTo(profileImageView.snp.trailing).offset(Style.Padding.p32)
}
}
override func layoutSubviews() {
super.layoutSubviews()
profileImageView.layer.cornerRadius = profileImageView.frame.height / 2
}
override func prepareForReuse() {
super.prepareForReuse()
profileImageView.stopLoading()
}
func configure(context: CellContext) {
guard let context = context as? SettingsProfileCellContext else { return }
nameLabel.text = context.name
teamNameLabel.text = context.teamName
membershipLabel.text = context.membership
profileImageView.fadeInImage(imageURL: context.imageURL, placeHolderImage: Assets.placeholder.image)
}
}
| bsd-3-clause | 116f9d10a9bf02737076c4ee7bc9fd1d | 36.829545 | 104 | 0.756984 | 4.776184 | false | false | false | false |
64characters/Telephone | UseCasesTests/CallHistoriesHistoryRemoveUseCaseTests.swift | 2 | 1424 | //
// CallHistoriesHistoryRemoveUseCaseTests.swift
// Telephone
//
// 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
import UseCasesTestDoubles
import XCTest
final class CallHistoriesHistoryRemoveUseCaseTests: XCTestCase {
func testCallsRemoveAllOnHistoryOnDidRemoveAccount() {
let uuid = "any-uuid"
let history = CallHistorySpy()
let sut = CallHistoriesHistoryRemoveUseCase(histories: CallHistoriesSpy(histories: [uuid: history]))
sut.didRemoveAccount(withUUID: uuid)
XCTAssertTrue(history.didCallRemoveAll)
}
func testRemovesHistoryOnDidRemoveAccount() {
let uuid = "any-uuid"
let histories = CallHistoriesSpy(histories: [uuid: CallHistorySpy()])
let sut = CallHistoriesHistoryRemoveUseCase(histories: histories)
sut.didRemoveAccount(withUUID: uuid)
XCTAssertTrue(histories.didCallRemove)
XCTAssertEqual(histories.invokedUUID, uuid)
}
}
| gpl-3.0 | b33035b08bf83bedccffefd6188920fb | 33.731707 | 108 | 0.735955 | 4.653595 | false | true | false | false |
arietis/codility-swift | 15.4.swift | 1 | 721 | public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2 (Linux)
let n = A.count
var back = 0
var front = n - 1
func absSum(a: Int, b: Int) -> Int {
return abs(a + b)
}
var mi = absSum(A[back], b: A[front])
A.sortInPlace()
func minAbsSum(a: Int, b: Int, min: Int) -> Int {
return absSum(a, b: b) < min ? absSum(a, b: b) : min
}
while back != front && mi > 0 {
mi = minAbsSum(A[back], b: A[front], min: mi)
if absSum(A[back + 1], b: A[front]) < absSum(A[back], b: A[front - 1]) {
back += 1
} else {
front -= 1
}
}
return minAbsSum(A[back], b: A[front], min: mi)
}
| mit | df8de5927e88f9e2e21144f05426f89b | 22.258065 | 80 | 0.477115 | 3.016736 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Nodes/Generators/Physical Models/Flute/AKFlute.swift | 1 | 4636 | //
// AKFlute.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// STK Flutee
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - amplitude: Amplitude
///
public class AKFlute: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKFluteAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
public var frequency: Double = 110 {
willSet {
if frequency != newValue {
frequencyParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Amplitude
public var amplitude: Double = 0.5 {
willSet {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the mandolin with defaults
override convenience init() {
self.init(frequency: 110)
}
/// Initialize the STK Flute model
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - amplitude: Amplitude
///
public init(
frequency: Double = 440,
amplitude: Double = 0.5) {
self.frequency = frequency
self.amplitude = amplitude
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x666c7574 /*'flut'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKFluteAudioUnit.self,
asComponentDescription: description,
name: "Local AKFlute",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKFluteAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Trigger the sound with an optional set of parameters
/// - frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
public func trigger(frequency frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.internalAU!.start()
self.internalAU!.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | 4c3d96b4b0d3aace24824c94bc335909 | 30.753425 | 128 | 0.624029 | 5.353349 | false | false | false | false |
CharlinFeng/Reflect | Reflect/Parse4.swift | 1 | 961 | //
// test4.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
let Student4Dict = ["id":1, "name": "jack", "age": 26,"func": "zoom"] as [String : Any]
/** 主要测试以下功能 */
// 模型中有多余的key
// 字段映射
// 字段忽略
class Student4: Reflect {
var hostID: Int
var name:String
var age: Int
var hobby: String
var funcType: String
required init() {
hostID = 0
name = ""
age = 0
hobby = ""
funcType = ""
}
override func mappingDict() -> [String : String]? {
return ["hostID": "id", "funcType": "func"]
}
override func ignorePropertiesForParse() -> [String]? {
return ["funcType"]
}
class func parse(){
let stu4 = Student4.parse(dict: Student4Dict as NSDictionary)
print(stu4)
}
}
| mit | c49f3771514faffa6203f584b17719d7 | 17.428571 | 87 | 0.528239 | 3.446565 | false | false | false | false |
gsempe/ADVOperation | Source/UserNotificationCondition.swift | 1 | 4262 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
#if os(iOS)
import UIKit
/**
A condition for verifying that we can present alerts to the user via
`UILocalNotification` and/or remote notifications.
*/
struct UserNotificationCondition: OperationCondition {
enum Behavior {
/// Merge the new `UIUserNotificationSettings` with the `currentUserNotificationSettings`.
case Merge
/// Replace the `currentUserNotificationSettings` with the new `UIUserNotificationSettings`.
case Replace
}
static let name = "UserNotification"
static let currentSettings = "CurrentUserNotificationSettings"
static let desiredSettings = "DesiredUserNotificationSettigns"
static let isMutuallyExclusive = false
let settings: UIUserNotificationSettings
let application: UIApplication
let behavior: Behavior
/**
The designated initializer.
- parameter settings: The `UIUserNotificationSettings` you wish to be
registered.
- parameter application: The `UIApplication` on which the `settings` should
be registered.
- parameter behavior: The way in which the `settings` should be applied
to the `application`. By default, this value is `.Merge`, which means
that the `settings` will be combined with the existing settings on the
`application`. You may also specify `.Replace`, which means the `settings`
will overwrite the exisiting settings.
*/
init(settings: UIUserNotificationSettings, application: UIApplication, behavior: Behavior = .Merge) {
self.settings = settings
self.application = application
self.behavior = behavior
}
func dependencyForOperation(operation: Operation) -> NSOperation? {
return UserNotificationPermissionOperation(settings: settings, application: application, behavior: behavior)
}
func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
let result: OperationConditionResult
let current = application.currentUserNotificationSettings()
switch (current, settings) {
case (let current?, let settings) where current.contains(settings):
result = .Satisfied
default:
let error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.currentSettings: current ?? NSNull(),
self.dynamicType.desiredSettings: settings
])
result = .Failed(error)
}
completion(result)
}
}
/**
A private `Operation` subclass to register a `UIUserNotificationSettings`
object with a `UIApplication`, prompting the user for permission if necessary.
*/
private class UserNotificationPermissionOperation: Operation {
let settings: UIUserNotificationSettings
let application: UIApplication
let behavior: UserNotificationCondition.Behavior
init(settings: UIUserNotificationSettings, application: UIApplication, behavior: UserNotificationCondition.Behavior) {
self.settings = settings
self.application = application
self.behavior = behavior
super.init()
addCondition(AlertPresentation())
}
override func execute() {
dispatch_async(dispatch_get_main_queue()) {
let current = self.application.currentUserNotificationSettings()
let settingsToRegister: UIUserNotificationSettings
switch (current, self.behavior) {
case (let currentSettings?, .Merge):
settingsToRegister = currentSettings.settingsByMerging(self.settings)
default:
settingsToRegister = self.settings
}
self.application.registerUserNotificationSettings(settingsToRegister)
}
}
}
#endif
| unlicense | fd8087cf6445309a790e59a450463083 | 33.918033 | 122 | 0.65939 | 5.991561 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Authentication/Interface/Helpers/UIAlertController+TOS.swift | 1 | 2403 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import SafariServices
import UIKit
extension UIAlertController {
static func requestTOSApproval(over controller: UIViewController, forTeamAccount: Bool, completion: @escaping (_ approved: Bool) -> Void) {
let alert = UIAlertController(title: "registration.terms_of_use.terms.title".localized,
message: "registration.terms_of_use.terms.message".localized,
preferredStyle: .alert)
let viewAction = UIAlertAction(title: "registration.terms_of_use.terms.view".localized, style: .default) { [weak controller] _ in
let url = URL.wr_termsOfServicesURL.appendingLocaleParameter
let webViewController: BrowserViewController
webViewController = BrowserViewController(url: url)
webViewController.completion = { [weak controller] in
if let controller = controller {
UIAlertController.requestTOSApproval(over: controller, forTeamAccount: forTeamAccount, completion: completion)
}
}
controller?.present(webViewController, animated: true)
}
alert.addAction(viewAction)
let cancelAction = UIAlertAction(title: "general.cancel".localized, style: .cancel) { _ in
completion(false)
}
alert.addAction(cancelAction)
let acceptAction = UIAlertAction(title: "registration.terms_of_use.accept".localized, style: .default) { _ in
completion(true)
}
alert.addAction(acceptAction)
alert.preferredAction = acceptAction
controller.present(alert, animated: true, completion: nil)
}
}
| gpl-3.0 | 55e71857f315a4697be9245f8867d3d8 | 42.690909 | 143 | 0.675822 | 4.844758 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/examples/BigHills/BigHills/Source/Controller/BigHillsViewController.swift | 1 | 5670 | //
// BigHillsViewController.swift
// BigHills
//
import CoreData
import MapKit
import UIKit
class BigHillsViewController: UIViewController, HillDetailViewControllerDelegate, MKMapViewDelegate, NSFetchedResultsControllerDelegate {
// MARK: IBAction
@IBAction private func addHill(_ sender: AnyObject) {
performSegue(withIdentifier: "CreateHillSegue", sender:self)
}
@IBAction private func deleteSelectedHill(_ sender: AnyObject) {
if let hill = mapView.selectedAnnotations.last as? Hill {
do {
try HillService.shared.deleteHill(hill)
}
catch let error {
fatalError("Failed to delete selected hill \(error)")
}
}
}
@IBAction private func connectTheDots(_ sender: AnyObject) {
if let somePolylineOverlay = polylineOverlay {
mapView.remove(somePolylineOverlay)
polylineOverlay = nil
connectTheDotsButton.title = "Connect the Dots"
}
else {
// Add the overlay
if let visibleHills = mapView.annotations(in: mapView.visibleMapRect) as? Set<Hill> {
if visibleHills.isEmpty {
let alertController = UIAlertController(title: "No Hills!", message: "There are no hills on screen to connect", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
else {
var points = visibleHills.reduce([]) { (workingPoints, element) in
return workingPoints + [element.coordinate]
}
let polylineOverlay = MKPolyline(coordinates: &points, count: points.count)
mapView.add(polylineOverlay)
self.polylineOverlay = polylineOverlay
connectTheDotsButton.title = "Remove Overlay"
}
}
}
}
// MARK: IBAction (Unwind Segue)
@IBAction private func createHillFinished(_ sender: UIStoryboardSegue) {
// Intentionally left blank
}
// MARK: HillDetailViewController
func hillDetailViewController(_ viewController: HillDetailViewController, didChange hill: Hill) {
mapView.deselectAnnotation(hill, animated: false)
mapView.selectAnnotation(hill, animated: false)
}
// MARK: MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView: MKAnnotationView
if let someAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "HillAnnotation") {
annotationView = someAnnotationView
}
else {
let pinAnnotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:"HillAnnotation")
pinAnnotationView.pinTintColor = .green
pinAnnotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
annotationView = pinAnnotationView
}
annotationView.annotation = annotation
annotationView.canShowCallout = true
annotationView.isDraggable = true
return annotationView;
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let somePolyline = overlay as! MKPolyline
let polyLineRenderer = MKPolylineRenderer(polyline: somePolyline)
polyLineRenderer.strokeColor = UIColor.green
polyLineRenderer.lineWidth = 5.0
polyLineRenderer.alpha = 0.5
return polyLineRenderer
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let someHill = view.annotation as? Hill {
selectedHill = someHill
performSegue(withIdentifier: "HillDetailSegue", sender:self)
}
}
// MARK: NSFetchedResultsControllerDelegate
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if let hill = anObject as? Hill {
if type == .delete {
mapView.removeAnnotation(hill)
}
else if type == .insert {
mapView.addAnnotation(hill)
}
}
}
// MARK: Private
func updateFetchedResultsController() {
fetchedResultsController = try? HillService.shared.hillsFetchedResultsController(with: self)
if let someObjects = fetchedResultsController?.fetchedObjects {
mapView.addAnnotations(someObjects)
}
}
// MARK: View Management
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case .some("HillDetailSegue"):
let hillDetailViewController = segue.destination as! HillDetailViewController
hillDetailViewController.selectedHill = selectedHill
hillDetailViewController.delegate = self
case .some("CreateHillSegue"):
let navigationController = segue.destination as! UINavigationController
let hillDetailViewController = navigationController.topViewController as! HillDetailViewController
hillDetailViewController.updateHill(withLatitude: mapView.centerCoordinate.latitude, andLongitude: mapView.centerCoordinate.longitude)
hillDetailViewController.delegate = self
default:
super.prepare(for: segue, sender: sender)
}
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
mapView.visibleMapRect = BigHillsViewController.defaultMapRect
updateFetchedResultsController()
}
// MARK: Properties (IBOutlet)
@IBOutlet private var mapView: MKMapView!
@IBOutlet private var connectTheDotsButton: UIBarButtonItem!
// MARK: Properties (Private)
private var fetchedResultsController: NSFetchedResultsController<Hill>?
private var polylineOverlay: MKPolyline?
private var selectedHill: Hill?
private var observationToken: AnyObject?
// MARK: Properties (Private Static Constant)
private static let defaultMapRect = MKMapRect(origin: MKMapPoint(x: 41984000.0, y: 97083392.0), size: MKMapSize(width: 655360.0, height: 942080.0))
}
| gpl-3.0 | b917b04bc7ccd1f272b0497ca4e49058 | 32.75 | 197 | 0.766138 | 4.398759 | false | false | false | false |
up-n-down/Up-N-Down | Finder Sync Extension/FIFinderSyncControllerExtensions.swift | 1 | 832 | //
// FIFinderSyncController.swift
// Up N Down
//
// Created by Thomas Paul Mann on 16/10/2016.
// Copyright © 2016 Thomas Paul Mann. All rights reserved.
//
import FinderSync
extension FIFinderSyncController {
/// Register the badge for further usage.
func register(_ badge: Badge) {
self.setBadgeImage(badge.image, label: badge.identifier, forBadgeIdentifier: badge.identifier)
}
var selectedItemsRepresentation: String {
var selectedItems = ""
if let selectedItemURLs = self.selectedItemURLs() {
if selectedItemURLs.count == 1 {
selectedItems = "”\(selectedItemURLs[0].lastPathComponent)”"
} else {
selectedItems.append("\(selectedItemURLs.count) Items")
}
}
return selectedItems
}
}
| gpl-3.0 | ed5ce6265f2b676337a6b37c9c81a819 | 24.84375 | 102 | 0.632406 | 4.47027 | false | false | false | false |
tsolomko/SWCompression | Sources/LZMA/LZMADecoder.swift | 1 | 11825 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import BitByteData
struct LZMADecoder {
private let byteReader: LittleEndianByteReader
var properties = LZMAProperties()
var uncompressedSize = -1
/// An array for storing output data.
var out = [UInt8]()
// `out` array also serves as dictionary and out window.
private var dictStart = 0
private var dictEnd = 0
private var dictSize: Int {
return self.properties.dictionarySize
}
private var lc: Int {
return self.properties.lc
}
private var lp: Int {
return self.properties.lp
}
private var pb: Int {
return self.properties.pb
}
private var rangeDecoder = LZMARangeDecoder()
private var posSlotDecoder = [LZMABitTreeDecoder]()
private var alignDecoder = LZMABitTreeDecoder(numBits: LZMAConstants.numAlignBits)
private var lenDecoder = LZMALenDecoder()
private var repLenDecoder = LZMALenDecoder()
/**
For literal decoding we need `1 << (lc + lp)` amount of tables.
Each table contains 0x300 probabilities.
*/
private var literalProbs = [[Int]]()
/**
Array with all probabilities:
- 0..<192: isMatch
- 193..<205: isRep
- 205..<217: isRepG0
- 217..<229: isRepG1
- 229..<241: isRepG2
- 241..<433: isRep0Long
*/
private var probabilities = [Int]()
private var posDecoders = [Int]()
// 'Distance history table'.
private var rep0 = 0
private var rep1 = 0
private var rep2 = 0
private var rep3 = 0
/// Used to select exact variable from 'IsRep', 'IsRepG0', 'IsRepG1' and 'IsRepG2' arrays.
private var state = 0
init(_ byteReader: LittleEndianByteReader) {
self.byteReader = byteReader
}
/// Resets state properties and various sub-decoders of LZMA decoder.
mutating func resetStateAndDecoders() {
self.state = 0
self.rep0 = 0
self.rep1 = 0
self.rep2 = 0
self.rep3 = 0
self.probabilities = Array(repeating: LZMAConstants.probInitValue, count: 2 * 192 + 4 * 12)
self.literalProbs = Array(repeating: Array(repeating: LZMAConstants.probInitValue, count: 0x300),
count: 1 << (lc + lp))
self.posSlotDecoder = []
for _ in 0..<LZMAConstants.numLenToPosStates {
self.posSlotDecoder.append(LZMABitTreeDecoder(numBits: 6))
}
self.alignDecoder = LZMABitTreeDecoder(numBits: LZMAConstants.numAlignBits)
self.posDecoders = Array(repeating: LZMAConstants.probInitValue,
count: 1 + LZMAConstants.numFullDistances - LZMAConstants.endPosModelIndex)
self.lenDecoder = LZMALenDecoder()
self.repLenDecoder = LZMALenDecoder()
}
mutating func resetDictionary() {
self.dictStart = self.dictEnd
}
/// Main LZMA (algorithm) decoder function.
mutating func decode() throws {
// First, we need to initialize Rande Decoder.
self.rangeDecoder = try LZMARangeDecoder(byteReader)
// Main decoding cycle.
while true {
// If uncompressed size was defined and everything is unpacked then stop.
if uncompressedSize == 0 && rangeDecoder.isFinishedOK {
break
}
let posState = out.count & ((1 << pb) - 1)
if rangeDecoder.decode(bitWithProb:
&probabilities[(state << LZMAConstants.numPosBitsMax) + posState]) == 0 {
if uncompressedSize == 0 {
throw LZMAError.exceededUncompressedSize
}
// DECODE LITERAL:
/// Previous literal (zero, if there was none).
let prevByte = dictEnd == 0 ? 0 : self.byte(at: 1).toInt()
/// Decoded symbol. Initial value is 1.
var symbol = 1
/**
Index of table with literal probabilities. It is based on the context which consists of:
- `lc` high bits of from previous literal.
If there were none, i.e. it is the first literal, then this part is skipped.
- `lp` low bits from current position in output.
*/
let litState = ((out.count & ((1 << lp) - 1)) << lc) + (prevByte >> (8 - lc))
// If state is greater than 7 we need to do additional decoding with 'matchByte'.
if state >= 7 {
/**
Byte in output at position that is the `distance` bytes before current position,
where the `distance` is the distance from the latest decoded match.
*/
var matchByte = self.byte(at: rep0 + 1)
repeat {
let matchBit = ((matchByte >> 7) & 1).toInt()
matchByte <<= 1
let bit = rangeDecoder.decode(bitWithProb:
&literalProbs[litState][((1 + matchBit) << 8) + symbol])
symbol = (symbol << 1) | bit
if matchBit != bit {
break
}
} while symbol < 0x100
}
while symbol < 0x100 {
symbol = (symbol << 1) | rangeDecoder.decode(bitWithProb: &literalProbs[litState][symbol])
}
let byte = (symbol - 0x100).toUInt8()
uncompressedSize -= 1
self.put(byte)
// END.
// Finally, we need to update `state`.
if state < 4 {
state = 0
} else if state < 10 {
state -= 3
} else {
state -= 6
}
continue
}
var len: Int
if rangeDecoder.decode(bitWithProb: &probabilities[193 + state]) != 0 {
// REP MATCH CASE
if uncompressedSize == 0 {
throw LZMAError.exceededUncompressedSize
}
if dictEnd == 0 {
throw LZMAError.windowIsEmpty
}
if rangeDecoder.decode(bitWithProb: &probabilities[205 + state]) == 0 {
// (We use last distance from 'distance history table').
if rangeDecoder.decode(bitWithProb:
&probabilities[241 + (state << LZMAConstants.numPosBitsMax) + posState]) == 0 {
// SHORT REP MATCH CASE
state = state < 7 ? 9 : 11
let byte = self.byte(at: rep0 + 1)
self.put(byte)
uncompressedSize -= 1
continue
}
} else { // REP MATCH CASE
// (It means that we use distance from 'distance history table').
// So the following code selectes one distance from history...
// based on the binary data.
let dist: Int
if rangeDecoder.decode(bitWithProb: &probabilities[217 + state]) == 0 {
dist = rep1
} else {
if rangeDecoder.decode(bitWithProb: &probabilities[229 + state]) == 0 {
dist = rep2
} else {
dist = rep3
rep3 = rep2
}
rep2 = rep1
}
rep1 = rep0
rep0 = dist
}
len = repLenDecoder.decode(with: &rangeDecoder, posState: posState)
state = state < 7 ? 8 : 11
} else { // SIMPLE MATCH CASE
// First, we need to move history of distance values.
rep3 = rep2
rep2 = rep1
rep1 = rep0
len = lenDecoder.decode(with: &rangeDecoder, posState: posState)
state = state < 7 ? 7 : 10
// DECODE DISTANCE:
/// Is used to define context for distance decoding.
var lenState = len
if lenState > LZMAConstants.numLenToPosStates - 1 {
lenState = LZMAConstants.numLenToPosStates - 1
}
/// Defines decoding scheme for distance value.
let posSlot = posSlotDecoder[lenState].decode(with: &rangeDecoder)
if posSlot < 4 {
// If `posSlot` is less than 4 then distance has defined value (no need to decode).
// And distance is actually equal to `posSlot`.
rep0 = posSlot
} else {
let numDirectBits = (posSlot >> 1) - 1
var dist = (2 | (posSlot & 1)) << numDirectBits
if posSlot < LZMAConstants.endPosModelIndex {
// In this case we need a sequence of bits decoded with bit tree...
// ...(separate trees for different `posSlot` values)...
// ...and 'Reverse' scheme to get distance value.
dist += LZMABitTreeDecoder.bitTreeReverseDecode(probs: &posDecoders,
startIndex: dist - posSlot,
bits: numDirectBits, &rangeDecoder)
} else {
// Middle bits of distance are decoded as direct bits from RangeDecoder.
dist += rangeDecoder.decode(directBits: (numDirectBits - LZMAConstants.numAlignBits))
<< LZMAConstants.numAlignBits
// Low 4 bits are decoded with a bit tree decoder (called 'AlignDecoder') using "Reverse" scheme.
dist += alignDecoder.reverseDecode(with: &rangeDecoder)
}
rep0 = dist
}
// END.
// Check if finish marker is encountered.
// Distance value of 2^32 is used to indicate 'End of Stream' marker.
if UInt32(rep0) == 0xFFFFFFFF {
guard rangeDecoder.isFinishedOK
else { throw LZMAError.rangeDecoderFinishError }
break
}
if uncompressedSize == 0 {
throw LZMAError.exceededUncompressedSize
}
if rep0 >= dictSize || (rep0 > dictEnd && dictEnd < dictSize) {
throw LZMAError.notEnoughToRepeat
}
}
// Converting from zero-based length of the match to the real one.
len += LZMAConstants.matchMinLen
if uncompressedSize > -1 && uncompressedSize < len {
throw LZMAError.repeatWillExceed
}
for _ in 0..<len {
let byte = self.byte(at: rep0 + 1)
self.put(byte)
uncompressedSize -= 1
}
}
}
// MARK: Dictionary (out window) related functions.
mutating func put(_ byte: UInt8) {
out.append(byte)
dictEnd += 1
if dictEnd - dictStart == dictSize {
dictStart += 1
}
}
private func byte(at distance: Int) -> UInt8 {
return out[distance <= dictEnd ? dictEnd - distance : dictSize - distance + dictEnd]
}
}
| mit | 5ab2ba131ee0d6fab1a0c98a57a2f99e | 38.285714 | 121 | 0.502156 | 5.202376 | false | false | false | false |
zitao0322/ShopCar | Shoping_Car/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift | 14 | 2123 | //
// UIGestureRecognizer+Rx.swift
// Touches
//
// Created by Carlos García on 10/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// This should be only used from `MainScheduler`
class GestureTarget<Recognizer: UIGestureRecognizer>: RxTarget {
typealias Callback = (Recognizer) -> Void
let selector = #selector(ControlTarget.eventHandler(_:))
weak var gestureRecognizer: Recognizer?
var callback: Callback?
init(_ gestureRecognizer: Recognizer, callback: Callback) {
self.gestureRecognizer = gestureRecognizer
self.callback = callback
super.init()
gestureRecognizer.addTarget(self, action: selector)
let method = self.methodForSelector(selector)
if method == nil {
fatalError("Can't find method")
}
}
func eventHandler(sender: UIGestureRecognizer!) {
if let callback = self.callback, gestureRecognizer = self.gestureRecognizer {
callback(gestureRecognizer)
}
}
override func dispose() {
super.dispose()
self.gestureRecognizer?.removeTarget(self, action: self.selector)
self.callback = nil
}
}
extension UIGestureRecognizer: Reactive { }
extension Reactive where Self: UIGestureRecognizer {
/**
Reactive wrapper for gesture recognizer events.
*/
public var rx_event: ControlEvent<Self> {
let source: Observable<Self> = Observable.create { [weak self] observer in
MainScheduler.ensureExecutingOnScheduler()
guard let control = self else {
observer.on(.Completed)
return NopDisposable.instance
}
let observer = GestureTarget(control) {
control in
observer.on(.Next(control))
}
return observer
}.takeUntil(rx_deallocated)
return ControlEvent(events: source)
}
}
#endif
| mit | a34b38f59df8b171f1fa93012e351c76 | 24.554217 | 85 | 0.608675 | 5.160584 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/Settings/UpdateDeparturesTableViewController.swift | 1 | 8013 | //
// UpdateDeparturesTableViewController.swift
// tpg offline
//
// Created by Rémy Da Costa Faro on 11/06/2018.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import UIKit
class UpdateDeparturesTableViewController: UITableViewController,
DownloadOfflineDeparturesDelegate {
override func viewDidLoad() {
super.viewDidLoad()
title = Text.offlineDepartures
OfflineDeparturesManager.shared.addDownloadOfflineDeparturesDelegate(self)
ColorModeManager.shared.addColorModeDelegate(self)
if App.darkMode {
self.tableView.backgroundColor = .black
self.navigationController?.navigationBar.barStyle = .black
self.tableView.separatorColor = App.separatorColor
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return section == 2 ? 2 : 1
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell =
tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell",
for: indexPath)
let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch
cell.backgroundColor = App.cellBackgroundColor
cell.textLabel?.text = Text.automatic
cell.textLabel?.textColor = App.textColor
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = Text.offlineDeparturesOnWifi
cell.detailTextLabel?.textColor = App.textColor
cell.detailTextLabel?.numberOfLines = 0
statusSwitch.isOn = App.automaticDeparturesDownload
statusSwitch.addTarget(self,
action: #selector(self.changeAutomatic),
for: .valueChanged)
cell.accessoryView = statusSwitch
if App.darkMode {
let selectedView = UIView()
selectedView.backgroundColor = .black
cell.selectedBackgroundView = selectedView
} else {
let selectedView = UIView()
selectedView.backgroundColor = UIColor.white.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
}
return cell
} else if indexPath.section == 1 {
guard let cell =
tableView.dequeueReusableCell(withIdentifier: "updateDeparturesButtonCell",
for: indexPath)
as? UpdateDeparturesButton else {
return UITableViewCell()
}
if App.darkMode {
let selectedView = UIView()
selectedView.backgroundColor = .black
cell.selectedBackgroundView = selectedView
} else {
let selectedView = UIView()
selectedView.backgroundColor = UIColor.white.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
}
cell.accessoryView = nil
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
cell.backgroundColor = App.cellBackgroundColor
return cell
} else {
if indexPath.row == 0 {
let cell =
tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell",
for: indexPath)
let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch
cell.backgroundColor = App.cellBackgroundColor
cell.textLabel?.text = Text.downloadMaps
cell.textLabel?.textColor = App.textColor
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = ""
statusSwitch.isOn = App.downloadMaps
statusSwitch.addTarget(self,
action: #selector(self.changeDownloadMaps),
for: .valueChanged)
cell.accessoryView = statusSwitch
if App.darkMode {
let selectedView = UIView()
selectedView.backgroundColor = .black
cell.selectedBackgroundView = selectedView
} else {
let selectedView = UIView()
selectedView.backgroundColor = UIColor.white.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
}
return cell
} else {
let cell =
tableView.dequeueReusableCell(withIdentifier: "updateDeparturesCell",
for: indexPath)
let statusSwitch = UISwitch(frame: CGRect.zero) as UISwitch
cell.backgroundColor = App.cellBackgroundColor
cell.textLabel?.text = Text.allowWithMobileData
cell.textLabel?.textColor = App.textColor
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = ""
statusSwitch.isOn = App.allowDownloadWithMobileData
statusSwitch.addTarget(self,
action: #selector(self.changeAllowDownloadWithMobileData),
for: .valueChanged)
cell.accessoryView = statusSwitch
if App.darkMode {
let selectedView = UIView()
selectedView.backgroundColor = .black
cell.selectedBackgroundView = selectedView
} else {
let selectedView = UIView()
selectedView.backgroundColor = UIColor.white.darken(by: 0.1)
cell.selectedBackgroundView = selectedView
}
return cell
}
}
}
override func tableView(_ tableView: UITableView,
titleForFooterInSection section: Int) -> String? {
if section == 1 {
if OfflineDeparturesManager.shared.status == .error {
return "An error occurred".localized
} else {
if UserDefaults.standard.bool(forKey: "offlineDeparturesUpdateAvailable") {
return Text.updateAvailable
} else if UserDefaults.standard.string(forKey: "departures.json.md5") == "" {
return Text.noDeparturesInstalled
} else {
return Text.offlineDeparturesVersion
}
}
} else {
return ""
}
}
@objc func changeAutomatic() {
App.automaticDeparturesDownload = !App.automaticDeparturesDownload
self.tableView.reloadData()
}
@objc func changeDownloadMaps() {
App.downloadMaps = !App.downloadMaps
self.tableView.reloadData()
}
@objc func changeAllowDownloadWithMobileData() {
App.allowDownloadWithMobileData = !App.allowDownloadWithMobileData
self.tableView.reloadData()
}
func updateDownloadStatus() {
if OfflineDeparturesManager.shared.status == .notDownloading {
self.tableView.reloadData()
}
}
deinit {
OfflineDeparturesManager.shared.removeDownloadOfflineDeparturesDelegate(self)
ColorModeManager.shared.removeColorModeDelegate(self)
}
}
class UpdateDeparturesButton: UITableViewCell, DownloadOfflineDeparturesDelegate {
func updateDownloadStatus() {
self.state = OfflineDeparturesManager.shared.status
}
@IBOutlet weak var button: UIButton!
override func draw(_ rect: CGRect) {
super.draw(rect)
OfflineDeparturesManager.shared.addDownloadOfflineDeparturesDelegate(self)
self.state = OfflineDeparturesManager.shared.status
}
deinit {
OfflineDeparturesManager.shared.removeDownloadOfflineDeparturesDelegate(self)
}
var state: OfflineDeparturesManager.OfflineDeparturesStatus = .notDownloading {
didSet {
switch state {
case .downloading:
self.button.setTitle("Downloading...".localized, for: .disabled)
self.button.isEnabled = false
case .processing:
self.button.setTitle("Saving...".localized, for: .disabled)
self.button.isEnabled = false
default:
self.button.setTitle("Download now".localized, for: .normal)
self.button.isEnabled = true
}
}
}
@IBAction func downloadButtonPushed() {
if OfflineDeparturesManager.shared.status == any(of: .notDownloading, .error) {
OfflineDeparturesManager.shared.download()
}
}
}
| mit | b1884862c387a61acbcbf40bbe42cc80 | 33.978166 | 89 | 0.653933 | 5.412162 | false | false | false | false |
iscriptology/swamp | Example/Pods/CryptoSwift/Sources/CryptoSwift/PKCS5/PBKDF1.swift | 2 | 2532 | //
// PBKDF1.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 07/06/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
public extension PKCS5 {
/// A key derivation function.
///
/// PBKDF1 is recommended only for compatibility with existing
/// applications since the keys it produces may not be large enough for
/// some applications.
public struct PBKDF1 {
public enum Error: Swift.Error {
case invalidInput
case derivedKeyTooLong
}
public enum Variant {
case md5, sha1
var size:Int {
switch (self) {
case .md5:
return MD5.digestSize
case .sha1:
return SHA1.digestSize
}
}
fileprivate func calculateHash(_ bytes:Array<UInt8>) -> Array<UInt8>? {
switch (self) {
case .sha1:
return Digest.sha1(bytes)
case .md5:
return Digest.md5(bytes)
}
}
}
private let iterations: Int // c
private let variant: Variant
private let keyLength: Int
private let t1: Array<UInt8>
/// - parameters:
/// - salt: salt, an eight-bytes
/// - variant: hash variant
/// - iterations: iteration count, a positive integer
/// - keyLength: intended length of derived key
public init(password: Array<UInt8>, salt: Array<UInt8>, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */) throws {
precondition(iterations > 0)
precondition(salt.count == 8)
let keyLength = keyLength ?? variant.size
if (keyLength > variant.size) {
throw Error.derivedKeyTooLong
}
guard let t1 = variant.calculateHash(password + salt) else {
throw Error.invalidInput
}
self.iterations = iterations
self.variant = variant
self.keyLength = keyLength
self.t1 = t1
}
/// Apply the underlying hash function Hash for c iterations
public func calculate() -> Array<UInt8> {
var t = t1
for _ in 2...self.iterations {
t = self.variant.calculateHash(t)!
}
return Array(t[0..<self.keyLength])
}
}
}
| mit | 9d8a194647544ac5e274ae393dbd955a | 29.130952 | 165 | 0.517977 | 4.802657 | false | false | false | false |
ivanbruel/SwipeIt | SwipeIt/Helpers/ShareHelper/ShareHelper.swift | 1 | 1019 | //
// ShareHelper.swift
// Reddit
//
// Created by Ivan Bruel on 09/08/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import UIKit
class ShareHelper {
private weak var viewController: UIViewController?
init(viewController: UIViewController) {
self.viewController = viewController
}
func share(text: String? = nil, URL: NSURL? = nil, image: UIImage? = nil,
fromView: UIView? = nil) {
let shareables: [AnyObject?] = [text, URL, image]
let activityViewController = UIActivityViewController(activityItems: shareables.flatMap { $0 },
applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop,
UIActivityTypeOpenInIBooks]
activityViewController.popoverPresentationController?.sourceView = fromView
viewController?.presentViewController(activityViewController, animated: true, completion: nil)
}
}
| mit | c1979b6cfdb453e9306c6e1eb7bfa9fb | 29.848485 | 99 | 0.660118 | 5.302083 | false | false | false | false |
nickfalk/BSImagePicker | Pod/Classes/View/SelectionView.swift | 2 | 3707 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
/**
Used as an overlay on selected cells
*/
@IBDesignable final class SelectionView: UIView {
var selectionString: String = "" {
didSet {
if selectionString != oldValue {
setNeedsDisplay()
}
}
}
var settings: BSImagePickerSettings = Settings()
override func draw(_ rect: CGRect) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Color Declarations
//// Shadow Declarations
let shadow2Offset = CGSize(width: 0.1, height: -0.1);
let shadow2BlurRadius: CGFloat = 2.5;
//// Frames
let checkmarkFrame = bounds;
//// Subframes
let group = CGRect(x: checkmarkFrame.minX + 3, y: checkmarkFrame.minY + 3, width: checkmarkFrame.width - 6, height: checkmarkFrame.height - 6)
//// CheckedOval Drawing
let checkedOvalPath = UIBezierPath(ovalIn: CGRect(x: group.minX + floor(group.width * 0.0 + 0.5), y: group.minY + floor(group.height * 0.0 + 0.5), width: floor(group.width * 1.0 + 0.5) - floor(group.width * 0.0 + 0.5), height: floor(group.height * 1.0 + 0.5) - floor(group.height * 0.0 + 0.5)))
context?.saveGState()
context?.setShadow(offset: shadow2Offset, blur: shadow2BlurRadius, color: settings.selectionShadowColor.cgColor)
settings.selectionFillColor.setFill()
checkedOvalPath.fill()
context?.restoreGState()
settings.selectionStrokeColor.setStroke()
checkedOvalPath.lineWidth = 1
checkedOvalPath.stroke()
context?.setFillColor(UIColor.white.cgColor)
//// Check mark for single assets
if (settings.maxNumberOfSelections == 1) {
context?.setStrokeColor(UIColor.white.cgColor)
let checkPath = UIBezierPath()
checkPath.move(to: CGPoint(x: 7, y: 12.5))
checkPath.addLine(to: CGPoint(x: 11, y: 16))
checkPath.addLine(to: CGPoint(x: 17.5, y: 9.5))
checkPath.stroke()
return;
}
//// Bezier Drawing (Picture Number)
let size = selectionString.size(attributes: settings.selectionTextAttributes)
selectionString.draw(in: CGRect(x: checkmarkFrame.midX - size.width / 2.0,
y: checkmarkFrame.midY - size.height / 2.0,
width: size.width,
height: size.height), withAttributes: settings.selectionTextAttributes)
}
}
| mit | 868ae287b43fe0fde1d7efafeceadaa9 | 40.177778 | 302 | 0.64544 | 4.592317 | false | false | false | false |
jpedrosa/sua_sdl | Sources/_Sua/file.swift | 1 | 15059 |
public class File: CustomStringConvertible {
var _fd: Int32
public let path: String
// Lower level constructor. The validity of the fd parameter is not checked.
public init(path: String, fd: Int32) {
self.path = path
self._fd = fd
}
public init(path: String, mode: FileOperation = .R) throws {
self.path = path
_fd = Sys.openFile(path, operation: mode)
if _fd == -1 {
throw FileError.Open
}
}
deinit { close() }
public func printList(string: String) {
// 10 - new line
write(string)
if string.isEmpty || string.utf16.codeUnitAt(string.utf16.count - 1) != 10 {
let a: [UInt8] = [10]
writeBytes(a, maxBytes: a.count)
}
}
public func print(v: String) {
write(v)
}
public func read(maxBytes: Int = -1) throws -> String? {
if maxBytes < 0 {
let a = try readAllCChar()
return String.fromCharCodes(a)
} else {
var a = [CChar](count: maxBytes, repeatedValue: 0)
try readCChar(&a, maxBytes: maxBytes)
return String.fromCharCodes(a)
}
}
public func readBytes(inout buffer: [UInt8], maxBytes: Int) throws -> Int {
return try doRead(&buffer, maxBytes: maxBytes)
}
public func readAllBytes() throws -> [UInt8] {
var a = [UInt8](count: length, repeatedValue: 0)
let n = try readBytes(&a, maxBytes: a.count)
if n != a.count {
throw FileError.Read
}
return a
}
public func readCChar(inout buffer: [CChar], maxBytes: Int) throws -> Int {
return try doRead(&buffer, maxBytes: maxBytes)
}
public func readAllCChar() throws -> [CChar] {
var a = [CChar](count: length, repeatedValue: 0)
let n = try readCChar(&a, maxBytes: a.count)
if n != a.count {
throw FileError.Read
}
return a
}
public func readLines() throws -> [String?] {
var r: [String?] = []
let a = try readAllCChar()
var si = 0
for i in 0..<a.count {
if a[i] == 10 {
r.append(String.fromCharCodes(a, start: si, end: i))
si = i + 1
}
}
return r
}
public func write(string: String) -> Int {
return Sys.writeString(_fd, string: string)
}
public func writeBytes(bytes: [UInt8], maxBytes: Int) -> Int {
return Sys.write(_fd, address: bytes, length: maxBytes)
}
public func writeCChar(bytes: [CChar], maxBytes: Int) -> Int {
return Sys.write(_fd, address: bytes, length: maxBytes)
}
public func flush() {
// Not implemented yet.
}
public func close() {
if _fd != -1 {
Sys.close(_fd)
}
_fd = -1
}
public var isOpen: Bool { return _fd != -1 }
public var fd: Int32 { return _fd }
public func doRead(address: UnsafeMutablePointer<Void>, maxBytes: Int) throws
-> Int {
assert(maxBytes >= 0)
let n = Sys.read(_fd, address: address, length: maxBytes)
if n == -1 {
throw FileError.Read
}
return n
}
func seek(offset: Int, whence: Int32) -> Int {
return Sys.lseek(_fd, offset: offset, whence: whence)
}
public var position: Int {
get {
return seek(0, whence: PosixSys.SEEK_CUR)
}
set(value) {
seek(value, whence: PosixSys.SEEK_SET)
}
}
public var length: Int {
let current = position
if current == -1 {
return -1
} else {
let end = seek(0, whence: PosixSys.SEEK_END)
position = current
return end
}
}
public var description: String { return "File(path: \(inspect(path)))" }
public static func open(path: String, mode: FileOperation = .R,
fn: (f: File) throws -> Void) throws {
let f = try File(path: path, mode: mode)
defer { f.close() }
try fn(f: f)
}
public static func exists(path: String) -> Bool {
var buf = Sys.statBuffer()
return Sys.stat(path, buffer: &buf) == 0
}
public static func stat(path: String) -> Stat? {
var buf = Sys.statBuffer()
return Sys.stat(path, buffer: &buf) == 0 ? Stat(buffer: buf) : nil
}
public static func delete(path: String) throws {
if Sys.unlink(path) == -1 {
throw FileError.Delete
}
}
public static func rename(oldPath: String, newPath: String) throws {
if Sys.rename(oldPath, newPath: newPath) == -1 {
throw FileError.Rename
}
}
// Aliases for handy FilePath methods.
public static func join(firstPath: String, _ secondPath: String) -> String {
return FilePath.join(firstPath, secondPath)
}
public static func baseName(path: String, suffix: String? = nil) -> String {
return FilePath.baseName(path, suffix: suffix)
}
public static func dirName(path: String) -> String {
return FilePath.dirName(path)
}
public static func extName(path: String) -> String {
return FilePath.extName(path)
}
public static func expandPath(path: String) throws -> String {
return try FilePath.expandPath(path)
}
}
public enum FileError: ErrorType {
case Open
case Delete
case Rename
case Read
}
// The file will be closed and removed automatically when it can be garbage
// collected.
//
// The file will be created with the file mode of read/write by the user.
//
// **Note**: If the process is cancelled (CTRL+C) or does not terminate
// normally, the files may not be removed automatically.
public class TempFile: File {
init(prefix: String = "", suffix: String = "", directory: String? = nil)
throws {
var d = "/tmp/"
if let ad = directory {
d = ad
let len = d.utf16.count
if len == 0 || d.utf16.codeUnitAt(len - 1) != 47 { // /
d += "/"
}
}
var fd: Int32 = -1
var attempts = 0
var path = ""
while fd == -1 {
path = "\(d)\(prefix)\(RNG().nextUInt64())\(suffix)"
fd = Sys.openFile(path, operation: .W, mode: PosixSys.USER_RW_FILE_MODE)
if attempts >= 100 {
throw TempFileError.Create(message: "Too many attempts.")
} else if attempts % 10 == 0 {
IO.sleep(0.00000001)
}
attempts += 1
}
super.init(path: path, fd: fd)
}
deinit {
closeAndUnlink()
}
public func closeAndUnlink() {
close()
Sys.unlink(path)
}
}
public enum TempFileError: ErrorType {
case Create(message: String)
}
public class FilePath {
public static func join(firstPath: String, _ secondPath: String) -> String {
let fpa = firstPath.bytes
let i = skipTrailingSlashes(fpa, lastIndex: fpa.count - 1)
let fps = String.fromCharCodes(fpa, start: 0, end: i) ?? ""
if !secondPath.isEmpty && secondPath.utf16.codeUnitAt(0) == 47 { // /
return "\(fps)\(secondPath)"
}
return "\(fps)/\(secondPath)"
}
public static func skipTrailingSlashes(bytes: [UInt8], lastIndex: Int)
-> Int {
var i = lastIndex
while i >= 0 && bytes[i] == 47 { // /
i -= 1
}
return i
}
public static func skipTrailingChars(bytes: [UInt8], lastIndex: Int) -> Int {
var i = lastIndex
while i >= 0 && bytes[i] != 47 { // /
i -= 1
}
return i
}
public static func baseName(path: String, suffix: String? = nil) -> String {
let bytes = path.bytes
let len = bytes.count
var ei = skipTrailingSlashes(bytes, lastIndex: len - 1)
if ei >= 0 {
var si = 0
if ei > 0 {
si = skipTrailingChars(bytes, lastIndex: ei - 1) + 1
}
if let sf = suffix {
ei = skipSuffix(bytes, suffix: sf, lastIndex: ei)
}
return String.fromCharCodes(bytes, start: si, end: ei) ?? ""
}
return "/"
}
public static func skipSuffix(bytes: [UInt8], suffix: String, lastIndex: Int)
-> Int {
var a = suffix.bytes
var i = lastIndex
var j = a.count - 1
while i >= 0 && j >= 0 && bytes[i] == a[j] {
i -= 1
j -= 1
}
return j < 0 ? i : lastIndex
}
public static func dirName(path: String) -> String {
let bytes = path.bytes
let len = bytes.count
var i = skipTrailingSlashes(bytes, lastIndex: len - 1)
if i > 0 {
//var ei = i
i = skipTrailingChars(bytes, lastIndex: i - 1)
let ci = i
i = skipTrailingSlashes(bytes, lastIndex: i - 1)
if i >= 0 {
return String.fromCharCodes(bytes, start: 0, end: i) ?? ""
} else if ci > 0 {
return String.fromCharCodes(bytes, start: ci - 1, end: len - 1) ?? ""
} else if ci == 0 {
return "/"
}
} else if i == 0 {
// Ignore.
} else {
return String.fromCharCodes(bytes,
start: len - (len > 1 ? 2 : 1), end: len) ?? ""
}
return "."
}
public static func extName(path: String) -> String {
let bytes = path.bytes
var i = bytes.count - 1
if bytes[i] != 46 {
while i >= 0 && bytes[i] != 46 { // Skip trailing chars.
i -= 1
}
return String.fromCharCodes(bytes, start: i) ?? ""
}
return ""
}
public static func skipSlashes(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> Int {
var i = startIndex
while i < maxBytes && bytes[i] == 47 {
i += 1
}
return i
}
public static func skipChars(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> Int {
var i = startIndex
while i < maxBytes && bytes[i] != 47 {
i += 1
}
return i
}
static func checkHome(path: String?) throws -> String {
if let hd = path {
return hd
} else {
throw FilePathError.ExpandPath(message: "Invalid home directory.")
}
}
public static func expandPath(path: String) throws -> String {
let bytes = path.bytes
let len = bytes.count
if len > 0 {
var i = 0
let fc = bytes[0]
if fc == 126 { // ~
var homeDir = ""
if len == 1 || bytes[1] == 47 { // /
homeDir = try checkHome(IO.env["HOME"])
i = 1
} else {
i = skipChars(bytes, startIndex: 1, maxBytes: len)
if let name = String.fromCharCodes(bytes, start: 1, end: i - 1) {
let ps = Sys.getpwnam(name)
if ps != nil {
homeDir = try checkHome(String.fromCString(ps.memory.pw_dir))
} else {
throw FilePathError.ExpandPath(message: "User does not exist.")
}
} else {
throw FilePathError.ExpandPath(message: "Invalid name.")
}
}
if i >= len {
return homeDir
}
return join(homeDir, doExpandPath(bytes, startIndex: i,
maxBytes: len))
} else if fc != 47 { // /
if let cd = Dir.cwd {
if fc == 46 { // .
let za = join(cd, path).bytes
return doExpandPath(za, startIndex: 0, maxBytes: za.count)
}
return join(cd, doExpandPath(bytes, startIndex: 0, maxBytes: len))
} else {
throw FilePathError.ExpandPath(message: "Invalid current directory.")
}
}
return doExpandPath(bytes, startIndex: i, maxBytes: len)
}
return ""
}
public static func doExpandPath(bytes: [UInt8], startIndex: Int,
maxBytes: Int) -> String {
var i = startIndex
var a = [String]()
var ai = -1
var sb = ""
func add() {
let si = i
i = skipChars(bytes, startIndex: i + 1, maxBytes: maxBytes)
ai += 1
let s = String.fromCharCodes(bytes, start: si, end: i - 1) ?? ""
if ai < a.count {
a[ai] = s
} else {
a.append(s)
}
i = skipSlashes(bytes, startIndex: i + 1, maxBytes: maxBytes)
}
func stepBack() {
if ai >= 0 {
ai -= 1
}
i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes)
}
if maxBytes > 0 {
let lasti = maxBytes - 1
while i < maxBytes && bytes[i] == 47 { //
sb += "/"
i += 1
}
if i >= maxBytes {
return sb
}
while i < maxBytes {
var c = bytes[i]
if c == 46 { // .
if i < lasti {
c = bytes[i + 1]
if c == 46 { // ..
if i < lasti - 1 {
c = bytes[i + 2]
if c == 47 { // /
stepBack()
} else {
add()
}
} else {
stepBack()
}
} else if c == 47 { // /
i = skipSlashes(bytes, startIndex: i + 2, maxBytes: maxBytes)
} else {
add()
}
} else {
break
}
} else {
add()
}
}
var slash = false
for i in 0...ai {
if slash {
sb += "/"
}
sb += a[i]
slash = true
}
if bytes[lasti] == 47 { // /
sb += "/"
}
}
return sb
}
}
enum FilePathError: ErrorType {
case ExpandPath(message: String)
}
public class FileStream {
public var fp: CFilePointer?
let SIZE = 80 // Starting buffer size.
public init(fp: CFilePointer) {
self.fp = fp
}
deinit { close() }
public func close() {
if let afp = fp {
Sys.fclose(afp)
}
fp = nil
}
public func readAllCChar(command: String) throws -> [CChar] {
guard let afp = fp else { return [CChar]() }
var a = [CChar](count: SIZE, repeatedValue: 0)
var buffer = [CChar](count: SIZE, repeatedValue: 0)
var alen = SIZE
var j = 0
while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil {
for i in 0..<SIZE {
let c = buffer[i]
if c == 0 {
break
}
if j >= alen {
var b = [CChar](count: alen * 8, repeatedValue: 0)
for m in 0..<alen {
b[m] = a[m]
}
a = b
alen = b.count
}
a[j] = c
j += 1
}
}
return a
}
public func readLines(command: String, fn: (string: String?)
-> Void) throws {
guard let afp = fp else { return }
var a = [CChar](count: SIZE, repeatedValue: 0)
var buffer = [CChar](count: SIZE, repeatedValue: 0)
var alen = SIZE
var j = 0
while Sys.fgets(&buffer, length: Int32(SIZE), fp: afp) != nil {
var i = 0
while i < SIZE {
let c = buffer[i]
if c == 0 {
break
}
if j >= alen {
var b = [CChar](count: alen * 8, repeatedValue: 0)
for m in 0..<alen {
b[m] = a[m]
}
a = b
alen = b.count
}
a[j] = c
if c == 10 {
fn(string: String.fromCharCodes(a, start: 0, end: j))
j = 0
} else {
j += 1
}
i += 1
}
}
if j > 0 {
fn(string: String.fromCharCodes(a, start: 0, end: j - 1))
}
}
public func readByteLines(command: String, maxBytes: Int = 80,
fn: (bytes: [UInt8], length: Int) -> Void) throws {
guard let afp = fp else { return }
var buffer = [UInt8](count: Int(maxBytes), repeatedValue: 0)
while true {
let n = Sys.fread(&buffer, size: 1, nmemb: maxBytes, fp: afp)
if n > 0 {
fn(bytes: buffer, length: n)
} else {
break
}
}
}
}
| apache-2.0 | 6928d961a31a2c92f56bea793df81f7a | 23.646481 | 80 | 0.536955 | 3.668453 | false | false | false | false |
adrfer/swift | test/Driver/embed-bitcode.swift | 20 | 3466 | // RUN: %target-swiftc_driver -driver-print-bindings -embed-bitcode %s 2>&1 | FileCheck -check-prefix=CHECK-%target-object-format %s
// CHECK-macho: "swift", inputs: ["{{.*}}embed-bitcode.swift"], output: {llvm-bc: "[[BC:.*\.bc]]"}
// CHECK-macho: "swift", inputs: ["[[BC]]"], output: {object: "[[OBJECT:.*\.o]]"}
// CHECK-macho: "ld", inputs: ["[[OBJECT]]"], output: {image: "embed-bitcode"}
// CHECK-elf: "swift", inputs: ["{{.*}}embed-bitcode.swift"], output: {llvm-bc: "[[BC:.*\.bc]]"}
// CHECK-elf: "swift", inputs: ["[[BC]]"], output: {object: "[[OBJECT:.*\.o]]"}
// CHECK-elf: "swift-autolink-extract", inputs: ["[[OBJECT]]"], output: {autolink: "[[AUTOLINK:.*\.autolink]]"}
// CHECK-elf: "clang++", inputs: ["[[OBJECT]]", "[[AUTOLINK]]"], output: {image: "main"}
// RUN: %target-swiftc_driver -embed-bitcode %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-FRONT -check-prefix=CHECK-FRONT-%target-object-format
// CHECK-FRONT: -frontend
// CHECK-FRONT: -emit-bc
// CHECK-FRONT: -frontend
// CHECK-FRONT: -c
// CHECK-FRONT: -embed-bitcode{{ }}
// CHECK-FRONT: -disable-llvm-optzns
// CHECK-FRONT-macho: ld{{"? }}
// CHECK-FRONT-macho: -bitcode_bundle
// RUN: %target-swiftc_driver -embed-bitcode-marker %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-MARKER -check-prefix=CHECK-MARKER-%target-object-format
// CHECK-MARKER: -frontend
// CHECK-MARKER: -c
// CHECK-MARKER: -embed-bitcode-marker
// CHECK-MARKER-NOT: -frontend
// CHECK-MARKER-macho: ld{{"? }}
// CHECK-MARKER-macho: -bitcode_bundle
// RUN: %target-swiftc_driver -embed-bitcode -Xcc -DDEBUG -Xllvm -fake-llvm-option -c -emit-module %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-MODULE
// CHECK-MODULE: -frontend
// CHECK-MODULE: -emit-bc
// CHECK-MODULE-DAG: -Xcc -DDEBUG
// CHECK-MODULE-DAG: -Xllvm -fake-llvm-option
// CHECK-MODULE-DAG: -emit-module-path
// CHECK-MODULE: -frontend
// CHECK-MODULE: -emit-module
// CHECK-MODULE: -frontend
// CHECK-MODULE: -c
// CHECK-MODULE-NOT: -Xcc
// CHECK-MODULE-NOT: -DDEBUG
// CHECK-MODULE-NOT: -fake-llvm-option
// CHECK-MODULE-NOT: -emit-module-path
// RUN: %target-swiftc_driver -embed-bitcode -force-single-frontend-invocation %s 2>&1 -### | FileCheck %s -check-prefix=CHECK-SINGLE
// CHECK-SINGLE: -frontend
// CHECK-SINGLE: -emit-bc
// CHECK-SINGLE: -frontend
// CHECK-SINGLE: -c
// CHECK-SINGLE: -embed-bitcode
// CHECK-SINGLE: -disable-llvm-optzns
// RUN: %target-swiftc_driver -embed-bitcode -c -parse-as-library -emit-module -force-single-frontend-invocation %s -parse-stdlib -module-name Swift 2>&1 -### | FileCheck %s -check-prefix=CHECK-LIB-WMO
// CHECK-LIB-WMO: -frontend
// CHECK-LIB-WMO: -emit-bc
// CHECK-LIB-WMO: -parse-stdlib
// CHECK-LIB-WMO: -frontend
// CHECK-LIB-WMO: -c
// CHECK-LIB-WMO: -parse-stdlib
// CHECK-LIB-WMO: -embed-bitcode
// CHECK-LIB-WMO: -disable-llvm-optzns
// RUN: %target-swiftc_driver -embed-bitcode -c -parse-as-library -emit-module %s %S/../Inputs/empty.swift -module-name ABC 2>&1 -### | FileCheck %s -check-prefix=CHECK-LIB
// CHECK-LIB: swift -frontend
// CHECK-LIB: -emit-bc
// CHECK-LIB: -primary-file
// CHECK-LIB: swift -frontend
// CHECK-LIB: -emit-bc
// CHECK-LIB: -primary-file
// CHECK-LIB: swift -frontend
// CHECK-LIB: -emit-module
// CHECK-LIB: swift -frontend
// CHECK-LIB: -c
// CHECK-LIB: -embed-bitcode
// CHECK-LIB: -disable-llvm-optzns
// CHECK-LIB: swift -frontend
// CHECK-LIB: -c
// CHECK-LIB: -embed-bitcode
// CHECK-LIB: -disable-llvm-optzns
// CHECK-LIB-NOT: swift -frontend
| apache-2.0 | 0a5cce1d4b22e82a0ef449a65e75584c | 42.873418 | 201 | 0.667917 | 3.02972 | false | false | true | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Database/Table/Schema/Table.swift | 1 | 3740 | //
// Table.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
class Table {
let name: String
let schemaType = "table"
// We have to make these vars so that we can create the Mirror in the initialiser
var columns: [Column]! = nil
var primaryKeys: [Column]? = nil
var indexes: [TableIndex]? = nil
init(name: String, indexes: [TableIndex]? = nil) {
self.name = name
let mirror = Mirror(reflecting: self)
var columns = [Column]()
columns.reserveCapacity(Int(mirror.children.count))
for child in mirror.children {
if let column = child.value as? Column {
column.table = self
columns.append(column)
}
}
self.columns = columns
let primaryKeys = columns.filter({ $0.isPrimaryKey })
self.primaryKeys = primaryKeys.isEmpty ? nil : primaryKeys
self.indexes = indexes
indexes?.forEach({ $0.table = self })
}
enum ColumnType: String {
case int = "INTEGER"
case float = "REAL"
case numeric = "NUMERIC"
case text = "TEXT"
case blob = "BLOB"
}
class Column {
let name: String
let type: ColumnType
let isNullable: Bool
let isPrimaryKey: Bool
let isUnique: Bool
weak var table: Table?
init(name: String, type: ColumnType, nullable: Bool = true, primaryKey: Bool = false, unique: Bool = false) {
self.name = name
self.type = type
self.isNullable = nullable
self.isPrimaryKey = primaryKey
self.isUnique = unique
}
}
class TableIndex {
let name: String
let columns: [Column]
let isUnique: Bool
weak var table: Table?
init(name: String, columns: [Column], unique: Bool = false) {
self.name = name
self.columns = columns
self.isUnique = unique
}
}
}
// MARK: - CustomStringConvertible
extension Table: CustomStringConvertible {
var description: String {
return name
}
}
extension Table.Column: CustomStringConvertible {
var description: String {
guard let table = table else { return name }
return "\(table.name).\(name)"
}
}
// MARK: - TableProtocol
extension Table: TableProtocol {
var sqlStatement: String {
var query = "CREATE TABLE \(name) ("
query += columns.lazy.map({ $0.sqlStatement }).joined(separator: ", ")
if let primaryKeys = primaryKeys {
query += ", PRIMARY KEY ("
query += primaryKeys.lazy.map({ $0.name }).joined(separator: ", ")
query += ")"
}
query += ");"
if let indexes = indexes, !indexes.isEmpty {
query += "\n"
query += indexes.lazy.map({ $0.sqlStatement }).joined(separator: "\n")
}
return query
}
}
// MARK: - ColumnProtocol
extension Table.Column: ColumnProtocol {
var sqlStatement: String {
var decl = "\(name) \(type.rawValue)"
if !isNullable {
decl += " NOT NULL"
}
if isUnique {
decl += " UNIQUE"
}
return decl
}
}
// MARK: - SQLConvertible
extension Table.TableIndex: SQLConvertible {
var sqlStatement: String {
guard let table = table else {
fatalError("Index not attached to a table!")
}
return (isUnique ? "CREATE UNIQUE INDEX" : "CREATE INDEX")
+ " \(name) ON \(table.name) (\(columns.lazy.map({ $0.name }).joined(separator: ", ")));"
}
}
| mit | 91da1846677b2becfc740f2d81706cfb | 26.696296 | 117 | 0.546135 | 4.521161 | false | false | false | false |
Vienta/kuafu | kuafu/kuafu/src/Controller/KFLisenceDetailViewController.swift | 1 | 944 | //
// KFLisenceDetailViewController.swift
// kuafu
//
// Created by Vienta on 15/7/18.
// Copyright (c) 2015年 www.vienta.me. All rights reserved.
//
import UIKit
class KFLisenceDetailViewController: UIViewController {
@IBOutlet weak var txvLisence: UITextView!
var lisenceName: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = self.lisenceName
var lisenceFileName: String = self.lisenceName + "_LICENSE"
let path = NSBundle.mainBundle().pathForResource(lisenceFileName, ofType: "txt")
var lisenceContent: String! = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
self.txvLisence.text = lisenceContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 1b309a839db64fcb64b0fb919651be63 | 28.4375 | 111 | 0.68896 | 4.464455 | false | false | false | false |
material-foundation/material-automation | Sources/main.swift | 1 | 5627 | /*
Copyright 2018 the Material Automation 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
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
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
import PerfectLogger
import PerfectThread
#if os(Linux)
srandom(UInt32(time(nil)))
#endif
// Create HTTP server.
let server = HTTPServer()
// Create the container variable for routes to be added to.
var routes = Routes()
// Create GitHub app config.
let config = GithubAppConfig()
routes.add(method: .get, uri: "/_ah/health", handler: { request, response in
LogFile.info("GET - /_ah/health route handler...")
response.setBody(string: "OK")
response.completed()
})
// Basic GET request
routes.add(method: .get, uri: "/hello", handler: { request, response in
LogFile.info("GET - /hello route handler...")
response.setBody(string: config.helloMessage)
response.completed()
})
routes.add(method: .post, uri: "/labels/updateall", handler: { request, response in
LogFile.info("/labels/updateall")
guard let password = request.header(.authorization),
GithubAuth.verifyGooglerPassword(googlerPassword: password) else {
response.completed(status: .unauthorized)
return
}
var json: [String: Any]
do {
json = try request.postBodyString?.jsonDecode() as? [String: Any] ?? [String: Any]()
} catch {
response.completed(status: .unauthorized)
return
}
guard let installationID = json["installation"] as? String,
let repoURL = json["repository_url"] as? String else {
LogFile.error("The incoming request is missing information: \(json.description)")
response.completed(status: .unauthorized)
return
}
guard let githubAPI = GithubManager.shared.getGithubAPI(for: installationID) else {
LogFile.error("could not get a github instance with an access token for \(installationID)")
response.completed(status: .unauthorized)
return
}
Threading.getDefaultQueue().dispatch {
githubAPI.setLabelsForAllIssues(repoURL: repoURL)
}
response.completed()
})
routes.add(method: .post, uri: "/webhook", handler: { request, response in
LogFile.info("/webhook")
Analytics.trackEvent(category: "Incoming", action: "/webhook")
guard let sig = request.header(.custom(name: "X-Hub-Signature")),
let bodyString = request.postBodyString,
GithubAuth.verifyGithubSignature(payload: bodyString, requestSig: sig) else {
LogFile.error("unauthorized request")
response.completed(status: .unauthorized)
return
}
guard let githubData = GithubData.createGithubData(from: bodyString),
let installationID = githubData.installationID else {
LogFile.error("couldn't parse incoming webhook request")
response.completed(status: .ok)
return
}
guard let githubAPI = GithubManager.shared.getGithubAPI(for: installationID) else {
LogFile.error("could not get a github instance with an access token for \(installationID)")
response.completed(status: .unauthorized)
return
}
if let PRData = githubData.PRData {
// Pull Request data received.
if githubData.action == "synchronize" || githubData.action == "opened" {
// Pull Request either opened or updated.
LabelAnalysis.addAndFixLabelsForPullRequests(PRData: PRData,
githubAPI: githubAPI)
}
} else if let issueData = githubData.issueData {
// Issue data received.
if githubData.action == "opened" {
// Issue opened.
LabelAnalysis.addAndFixLabelsForIssues(issueData: issueData,
githubAPI: githubAPI)
LabelAnalysis.addNeedsActionabilityReviewLabel(issueData: issueData,
githubAPI: githubAPI)
}
let isClientBlockingIssue = issueData.labels.contains(where: { $0 == "Client-blocking" })
if (githubData.action == "labeled" || githubData.action == "opened")
&& isClientBlockingIssue {
ProjectAnalysis.addIssueToCurrentSprint(githubData: githubData, githubAPI: githubAPI)
}
} else if githubData.projectCard != nil {
// Project card data received.
if githubData.action == "moved" {
// Card moved between columns.
ProjectAnalysis.didMoveCard(githubData: githubData,
githubAPI: githubAPI)
}
} else if githubData.project != nil {
if githubData.action == "closed" {
// Project closed
ProjectAnalysis.didCloseProject(githubData: githubData,
githubAPI: githubAPI)
}
}
var ret = ""
do {
ret = try githubData.jsonEncodedString()
} catch {
LogFile.error("\(error)")
}
response.setHeader(.contentType, value: "application/json")
response.appendBody(string: ret)
response.completed()
})
// Add the routes to the server.
server.addRoutes(routes)
// Set a listen port of 8080
server.serverPort = 8080
GithubData.registerModels()
do {
// Launch the HTTP server.
try server.start()
} catch PerfectError.networkError(let err, let msg) {
LogFile.error("Network error thrown: \(err) \(msg)")
}
| apache-2.0 | f32bda7aee94d321096c74150aebd17c | 31.33908 | 95 | 0.690066 | 4.311877 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/System.swift | 1 | 598 | //
// System.swift
// Podcast
//
// Created by Natasha Armbrust on 3/2/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
class System {
// TODO: CHANGE THIS
static let feedTab = 0
static let discoverSearchTab: Int = 1
static let bookmarkTab: Int = 2
static let profileTab: Int = 3
static var currentUser: User?
static var currentSession: Session?
static var endpointRequestQueue = EndpointRequestQueue()
static func isiPhoneX() -> Bool {
return UIScreen.main.nativeBounds.height == 2436
}
}
| mit | 89e3d73a8c20462512637115365bd199 | 21.111111 | 66 | 0.661642 | 4.174825 | false | false | false | false |
ustwo/videoplayback-ios | Source/Presenter/VPKVideoPlaybackPresenter.swift | 1 | 6061 | //
// VPKVideoViewPresenter.swift
// VideoPlaybackKit
//
// Created by Sonam on 4/21/17.
// Copyright © 2017 ustwo. All rights reserved.
//
import Foundation
import AVFoundation
public class VPKVideoPlaybackPresenter {
static let fadeOutTime: TimeInterval = 3.0
var videoView: VPKVideoViewProtocol? {
didSet {
observeVideoViewLifecycle()
}
}
var hasFadedOutControlView: Bool = false
var progressTime = 0.0
var playbackBarView: VPKPlaybackControlViewProtocol?
var interactor: VPKVideoPlaybackInteractorInputProtocol?
var builder: VPKVideoPlaybackBuilderProtocol?
var videoSizeState: VideoSizeState?
var playbackTheme: ToolBarTheme?
var shouldAutoplay: Bool?
var indexPath: NSIndexPath?
var duration: TimeInterval?
required public init(with autoPlay:Bool = false, showInCell indexPath: NSIndexPath?, playbackTheme theme: ToolBarTheme) {
self.shouldAutoplay = autoPlay
self.indexPath = indexPath
self.videoSizeState = .normal
self.playbackTheme = theme
}
private func observeVideoViewLifecycle() {
videoView?.viewWillAppearClosure = { () in
if self.shouldAutoplay == true {
self.didTapVideoView()
}
}
}
}
//MARK: VIEW --> Presenter
extension VPKVideoPlaybackPresenter: VPKVideoPlaybackPresenterProtocol {
//VIEW -> PRESENTER
func viewDidLoad() {
//Update the default image
if let localImage = interactor?.localImageName {
videoView?.localPlaceHolderName = localImage
} else if let remoteImageURL = interactor?.remoteImageURL {
videoView?.remotePlaceHolderURL = remoteImageURL
}
if self.shouldAutoplay == true {
didTapVideoView()
}
}
func reuseInCell() {
interactor?.didReuseInCell()
}
func didMoveOffScreen() {
interactor?.didMoveOffScreen()
}
func didTapVideoView() {
guard let safeVideoUrl = interactor?.videoType.videoUrl else { return }
interactor?.didTapVideo(videoURL: safeVideoUrl, at: self.indexPath)
}
public func didExpand() {
guard let state = videoSizeState else { return }
switch state {
case .normal:
videoView?.makeFullScreen()
case .fullScreen:
videoView?.makeNormalScreen()
}
videoSizeState?.toggle()
}
func didSkipBack(_ seconds: Float) {
didScrubTo(TimeInterval(seconds))
}
func didSkipForward(_ seconds: Float) {
didScrubTo(TimeInterval(seconds))
}
func didScrubTo(_ value: TimeInterval) {
interactor?.didScrubTo(value)
}
func formattedProgressTime(from seconds: TimeInterval) -> String {
return seconds.formattedTimeFromSeconds
}
}
//MARK: INTERACTOR --> Presenter
extension VPKVideoPlaybackPresenter: VPKVideoPlaybackInteractorOutputProtocol {
func onVideoResetPresentation() {
videoView?.reloadInterfaceWithoutPlayerlayer()
}
func onVideoDidStartPlayingWith(_ duration: TimeInterval) {
self.duration = duration
playbackBarView?.maximumSeconds = Float(duration)
playbackBarView?.showDurationWith(duration.formattedTimeFromSeconds)
playbackBarView?.toggleActionButton(PlayerState.playing.buttonImageName)
}
func onVideoPlayingFor(_ seconds: TimeInterval) {
playbackBarView?.progressValue = Float(seconds)
playbackBarView?.updateTimePlayingCompletedTo(seconds.formattedTimeFromSeconds)
self.progressTime = seconds
if videoIsReachingTheEnd() {
fadeInControlBarView()
hasFadedOutControlView = false
} else if videoHasBeenPlaying(for: VPKVideoPlaybackPresenter.fadeOutTime) && hasFadedOutControlView == false {
hasFadedOutControlView = true
fadeOutControlBarView()
}
}
func videoHasBeenPlaying(for seconds: TimeInterval) -> Bool {
return (seconds...seconds + 5).contains(progressTime)
}
func videoIsReachingTheEnd() -> Bool {
guard let safeDuration = duration else { return false }
let timeLeft = safeDuration - progressTime
return timeLeft <= 5.0
}
func fadeOutControlBarView() {
guard let playbackView = playbackBarView else { return }
PlaybackControlViewAnimator.fadeOut(playbackView)
}
func fadeInControlBarView() {
guard let playbackView = playbackBarView else { return }
PlaybackControlViewAnimator.fadeIn(playbackView)
}
func onVideoDidPlayToEnd() {
videoView?.showPlaceholder()
playbackBarView?.toggleActionButton(PlayerState.paused.buttonImageName)
playbackBarView?.progressValue = 0.0
}
func onVideoDidStopPlaying() {
playbackBarView?.toggleActionButton(PlayerState.paused.buttonImageName)
guard let controlView = playbackBarView else {
assertionFailure("control view is nil")
return
}
PlaybackControlViewAnimator.fadeIn(controlView)
}
func onVideoDidStartPlaying() {
videoView?.activityIndicator.stopAnimating()
playbackBarView?.toggleActionButton(PlayerState.playing.buttonImageName)
}
func onVideoLoadSuccess(_ playerLayer: AVPlayerLayer) {
videoView?.reloadInterface(with: playerLayer)
}
func onVideoLoadFail(_ error: String) {
//TODO: (SD) PASS ERROR
}
}
//MAK: Presenter transformers
fileprivate extension TimeInterval {
var formattedTimeFromSeconds: String {
let minutes = Int(self.truncatingRemainder(dividingBy: 3600))/60
let seconds = Int(self.truncatingRemainder(dividingBy: 60))
return String(format: "%02i:%02i", minutes, seconds)
}
}
| mit | aa8d967a82b22e0ba385d23aebe37e6f | 28.560976 | 125 | 0.65033 | 5.343915 | false | false | false | false |
Sharelink/Bahamut | Bahamut/BahamutServiceContainer/FileService/DownloadExtension.swift | 1 | 4629 | //
// DownloadBaseExtension.swift
// Bahamut
//
// Created by AlexChow on 15/11/25.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
//MARK: Id File Fetcher
class IdFileFetcher: FileFetcher
{
var fileType:FileType!;
func startFetch(_ fileId: String, delegate: ProgressTaskDelegate)
{
DispatchQueue.global().async { () -> Void in
if let path = Bundle.main.path(forResource: "\(fileId)", ofType:""){
if PersistentFileHelper.fileExists(path){
delegate.taskCompleted(fileId, result: path)
}
}else{
let fileService = ServiceContainer.getFileService()
if let path = fileService.getFilePath(fileId, type: self.fileType){
delegate.taskCompleted(fileId, result: path)
}else
{
ProgressTaskWatcher.sharedInstance.addTaskObserver(fileId, delegate: delegate)
fileService.fetchFile(fileId, fileType: self.fileType){ filePath in
}
}
}
}
}
}
extension FileService
{
func getFileFetcherOfFileId(_ fileType:FileType) -> FileFetcher
{
let fetcher = IdFileFetcher()
fetcher.fileType = fileType
return fetcher
}
}
//MARK: Download FileService Extension
extension FileService
{
func getCachedFileAccessInfo(_ fileId:String)->FileAccessInfo? {
return PersistentManager.sharedInstance.getModel(FileAccessInfo.self, idValue: fileId)
}
func fetchFileAccessInfo(_ fileId:String,callback:@escaping (FileAccessInfo?)->Void) {
let req = GetBahamutFireRequest()
req.fileId = fileId
let bahamutFireClient = BahamutRFKit.sharedInstance.getBahamutFireClient()
bahamutFireClient.execute(req) { (result:SLResult<FileAccessInfo>) -> Void in
if result.isSuccess{
if let fa = result.returnObject
{
fa.saveModel()
callback(fa)
return
}
}
self.fetchingFinished(fileId)
callback(nil)
}
}
fileprivate class CallbackTaskDelegate:NSObject,ProgressTaskDelegate {
var callback:((_ filePath:String?) -> Void)?
@objc func taskCompleted(_ taskIdentifier:String,result:Any!){
callback?(result as? String)
}
@objc func taskFailed(_ taskIdentifier:String,result:Any!){
callback?(nil)
}
}
func fetchFile(_ fileId:String,fileType:FileType,callback:@escaping (_ filePath:String?) -> Void)
{
if String.isNullOrWhiteSpace(fileId)
{
callback(nil)
return
}
let d = CallbackTaskDelegate()
d.callback = callback
ProgressTaskWatcher.sharedInstance.addTaskObserver(fileId, delegate: d)
if isFetching(fileId)
{
return
}
setFetching(fileId)
if let fa = getCachedFileAccessInfo(fileId)
{
if String.isNullOrWhiteSpace(fa.expireAt) || fa.expireAt.dateTimeOfString.timeIntervalSinceNow > 0
{
startFetch(fa,fileTyp: fileType)
return
}
}
fetchFileAccessInfo(fileId) { (fileAccessInfo) in
if let fa = fileAccessInfo
{
self.startFetch(fa,fileTyp: fileType)
}else{
self.fetchingFinished(fileId)
ProgressTaskWatcher.sharedInstance.missionFailed(fileId, result: nil)
}
}
}
fileprivate func startFetch(_ fa:FileAccessInfo,fileTyp:FileType)
{
func progress(_ fid:String,persent:Float)
{
ProgressTaskWatcher.sharedInstance.setProgress(fid, persent: persent)
}
func finishCallback(_ fid:String,absoluteFilePath:String?){
if String.isNullOrWhiteSpace(absoluteFilePath){
ProgressTaskWatcher.sharedInstance.missionFailed(fid, result: nil)
}else{
ProgressTaskWatcher.sharedInstance.missionCompleted(fid, result: absoluteFilePath)
}
}
if fa.isServerTypeAliOss()
{
self.fetchFromAliOSS(fa, fileType: fileTyp, progress:progress, callback: finishCallback)
}else
{
self.fetchBahamutFire(fa, fileType: fileTyp, progress:progress, callback: finishCallback)
}
}
}
| mit | 236f9f84275c8bd9c54203d4240569a0 | 30.04698 | 110 | 0.580415 | 5.077936 | false | false | false | false |
flow-ai/flowai-swift | FlowCore/Classes/FileTemplate.swift | 1 | 969 | import Foundation
/**
File response template
*/
public class FileTemplate : Template {
/// Title of the file
private(set) public var title:String!
/// URL that points to the file
private(set) public var url:URL!
/// Optional action
private(set) public var action:Action? = nil
override init(_ data: [String: Any]) throws {
try super.init(data)
guard let title = data["title"] as? String else {
throw Exception.Serialzation("file template has no title")
}
self.title = title
guard let url = data["url"] as? String else {
throw Exception.Serialzation("file template has no url")
}
self.url = URL(string: url)
if let action = data["action"] as? [String:Any] {
self.action = try Action(action)
}
}
public required init() {
super.init()
}
}
| mit | ecdeffeebd06f3b2b57eacfac5e5eb55 | 22.634146 | 70 | 0.544892 | 4.549296 | false | false | false | false |
Erickson0806/MySwiftPlayground | MySwiftPlayground/MyPlayground.playground/Contents.swift | 1 | 1020 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//
//
////let digitNames = [123,451,23]
//
////let dig = digitNames.sort(<)
////
////print(dig)
//
//
//
//let digitNames = [
// 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
// 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
//]
//
//
//let numbers = [16, 58, 510]
//
//
//let strings = numbers.map {
// (var number) -> String in
// var output = ""
// while number > 0 {
// output = digitNames[number % 10]! + output
// number /= 10
// }
// return output
//}
var dict = ["atk":"atk"]
dict["hah"] = "hah"
dict
dict
func swap<MyCustomType>(inout num1:MyCustomType , inout num2:MyCustomType){
let temp = num1
num1 = num2
num2 = temp
}
var n1 = 4
var n2 = 5
swap(&n1, num2: &n2)
n1
n2
let books :[String] = ["2","1"]
//strings
// strings 常量被推断为字符串类型数组,即 [String]
// 其值为 ["OneSix", "FiveEight", "FiveOneZero"]
| apache-2.0 | 3a275cad81285b84f4a0935921c1300b | 13.686567 | 75 | 0.542683 | 2.688525 | false | false | false | false |
chetca/Android_to_iOs | memuDemo/SideMenuSC/MenuCell.swift | 1 | 1194 | //
// MenuCell.swift
// memuDemo
//
// Created by Parth Changela on 09/10/16.
// Copyright © 2016 Parth Changela. All rights reserved.
//
import UIKit
class MenuCell: UITableViewCell {
@IBOutlet var lblMenuRightConstraint: NSLayoutConstraint!
@IBOutlet weak var lblMenuname: UILabel!
@IBOutlet weak var imgIcon: UIImageView!
var lblFont = UIFont()
override func awakeFromNib() {
super.awakeFromNib()
if let window = UIApplication.shared.keyWindow {
lblMenuRightConstraint.constant = -window.frame.width * 0.2
}
lblMenuname.sizeToFit()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected == true {
lblMenuname.textColor = UIColor.orange
lblMenuname.font = UIFont(name: "Helvetica-Bold", size: 11)
}
else {
lblMenuname.textColor = UIColor.black
lblMenuname.font = UIFont(name: "Helvetica-Light", size: 11.5)
}
// Configure the view for the selected state
}
}
| mit | c50e9c8a456b929917d61a48a0f5a923 | 26.744186 | 74 | 0.609388 | 4.791165 | false | false | false | false |
whitepaperclip/Exsilio-iOS | Exsilio/MapViewController.swift | 1 | 3050 | //
// MapViewController.swift
// Exsilio
//
// Created by Nick Kezhaya on 5/5/16.
//
//
import UIKit
import CoreLocation
import SwiftyJSON
import FontAwesome_swift
import Mapbox
protocol MapViewDelegate {
func mapView(_ mapView: MGLMapView, didTapAt: CLLocationCoordinate2D)
}
class MapViewController: UIViewController {
@IBOutlet var mapView: MGLMapView!
var delegate: MapViewDelegate?
var startingPoint: CLLocationCoordinate2D?
// Gets set when previewing a tour.
var tour: JSON?
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
if let startingPoint = startingPoint {
setCoordinate(startingPoint)
}
if let tour = tour {
title = "Tour Map"
MapHelper.drawTour(tour, mapView: mapView)
MapHelper.setMapBounds(for: tour, mapView: mapView)
} else {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped))
mapView.addGestureRecognizer(tapGestureRecognizer)
locationManager.delegate = self
if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done",
style: .done,
target: self,
action: #selector(done))
}
}
func setCoordinate(_ coordinate: CLLocationCoordinate2D) {
guard let delegate = delegate else { return }
delegate.mapView(mapView, didTapAt: coordinate)
mapView.setCenter(coordinate, zoomLevel: 15, animated: true)
}
func done() {
navigationController?.dismiss(animated: true, completion: nil)
}
@objc private func mapViewTapped(gestureRecognizer: UITapGestureRecognizer) {
guard let delegate = delegate else { return }
let coordinate = mapView.convert(gestureRecognizer.location(in: mapView), toCoordinateFrom: mapView)
delegate.mapView(mapView, didTapAt: coordinate)
}
}
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
if startingPoint != nil {
return
}
if let coordinate = locations.first?.coordinate {
setCoordinate(coordinate)
}
}
}
| mit | bf91cf4e21f4240ad5bd12b866b09206 | 31.105263 | 121 | 0.634754 | 5.809524 | false | false | false | false |
modocache/Gift | Gift/Commit/Commit+Merge.swift | 1 | 822 | import LlamaKit
public extension Commit {
/**
Merges another commit into this commit to produce an index.
:param: commit The commit to merge into this one.
:param: options A set of options to configure merge behavior.
:returns: A result that is either: the resulting index, or an error
indicating what went wrong.
*/
public func merge(commit: Commit, options: MergeOptions = MergeOptions()) -> Result<Index, NSError> {
var out = COpaquePointer.null()
var cOptions = options.cOptions
let errorCode = git_merge_commits(&out, cRepository, cCommit, commit.cCommit, &cOptions)
if errorCode == GIT_OK.value {
return success(Index(cIndex: out))
} else {
return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_merge_commits"))
}
}
}
| mit | eda301c4e1164c654199b9ea7b18c2b1 | 36.363636 | 103 | 0.693431 | 4.069307 | false | false | false | false |
jakehirzel/swift-tip-calculator | CheckPlease/ViewController.swift | 1 | 11136 | //
// ViewController.swift
// CheckPlease
//
// Created by Jake Hirzel on 7/2/16.
// Copyright © 2016 Jake Hirzel. All rights reserved.
//
import UIKit
import MessageUI
import Messages
class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {
// MARK: Properties
@IBOutlet weak var totalBillLabel: UILabel!
@IBOutlet weak var percentOne: UILabel!
@IBOutlet weak var percentTwo: UILabel!
@IBOutlet weak var percentThree: UILabel!
@IBOutlet weak var tipsView: UIView!
@IBOutlet weak var splitsView: UIView!
@IBOutlet var tipLines: [UIStackView]!
@IBOutlet weak var tipPercentLabelOne: UILabel!
@IBOutlet weak var tipPercentLabelTwo: UILabel!
@IBOutlet weak var tipPercentLabelThree: UILabel!
@IBOutlet weak var splitPercent: UILabel!
@IBOutlet weak var splitTotal: UILabel!
@IBOutlet weak var splitStepper: UIStepper!
@IBOutlet weak var splitNumber: UILabel!
@IBOutlet weak var splitPeople: UILabel!
@IBOutlet weak var splitButton: UIButton!
@IBOutlet weak var eachTotal: UILabel!
@IBOutlet weak var keyOne: UIButton!
@IBOutlet weak var keyTwo: UIButton!
@IBOutlet weak var keyThree: UIButton!
@IBOutlet weak var keyFour: UIButton!
@IBOutlet weak var keyFive: UIButton!
@IBOutlet weak var keySix: UIButton!
@IBOutlet weak var keySeven: UIButton!
@IBOutlet weak var keyEight: UIButton!
@IBOutlet weak var keyNine: UIButton!
@IBOutlet weak var keyZero: UIButton!
// @IBOutlet weak var keyPoint: UIButton!
@IBOutlet weak var keyDelete: UIButton!
@IBOutlet weak var cursor: UIView!
// MARK: Properties
// String to hold value of totalBillLabel without the $
var totalBillLabelValue = "0.00"
// Create instance of TipCalculator class
let tipCalculatorInstance = TipCalculator()
// Create instance of KeypadBehavior class
let keypadBehavior = KeypadBehavior()
// Set initial state of splitsView
var isSplitsViewShowing = false
// Set first split view toggle (for controlling pulse behavior on share button)
var isFirstSplitsView = true
// Variable to Track Tag of Tip Stack Item Tapped
var tipsStackTag = 0
// MARK: View Handling
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Make the cursor repeatedly blink
cursor.blink()
// Pulse the percentages
tipPercentLabelOne.pulseOnce(0.2)
tipPercentLabelTwo.pulseOnce(0.5)
tipPercentLabelThree.pulseOnce(0.8)
// Set up the stepper
splitStepper.tintColor = UIColor.white
splitStepper.minimumValue = 1
splitStepper.maximumValue = 100
splitStepper.value = 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Convenience
func processTipCalculation() {
let totalBillFloat: Float? = Float(totalBillLabelValue)
if totalBillFloat != nil {
let tipResults = tipCalculatorInstance.tipCalculator(totalBillFloat!, people: Float(splitStepper.value))
// Convert resulting floats to $0.00 format
percentOne.text = String(format: "$%.2f", tipResults.tipOne) + " / " + String(format: "$%.2f", tipResults.totalOne)
percentTwo.text = String(format: "$%.2f", tipResults.tipTwo) + " / " + String(format: "$%.2f", tipResults.totalTwo)
percentThree.text = String(format: "$%.2f", tipResults.tipThree) + " / " + String(format: "$%.2f", tipResults.totalThree)
// Update split number
splitNumber.text = String(Int(splitStepper.value))
if splitStepper.value == 1 {
splitPeople.text = "Person"
}
else {
splitPeople.text = "People"
}
// Set split total and each person total
switch tipsStackTag {
case 1:
splitPercent.text = String(Int(tipCalculatorInstance.tipPercentOne * 100)) + "%"
splitTotal.text = percentOne.text
eachTotal.text = String(format: "$%.2f", tipResults.splitTipOne) + " / " + String(format: "$%.2f", tipResults.splitTotalOne)
case 2:
splitPercent.text = String(Int(tipCalculatorInstance.tipPercentTwo * 100)) + "%"
splitTotal.text = percentTwo.text
eachTotal.text = String(format: "$%.2f", tipResults.splitTipTwo) + " / " + String(format: "$%.2f", tipResults.splitTotalTwo)
case 3:
splitPercent.text = String(Int(tipCalculatorInstance.tipPercentThree * 100)) + "%"
splitTotal.text = percentThree.text
eachTotal.text = String(format: "$%.2f", tipResults.splitTipThree) + " / " + String(format: "$%.2f", tipResults.splitTotalThree)
default:
splitPercent.text = "15%"
splitTotal.text = "$0.00 / $0.00"
eachTotal.text = "$0.00 / $0.00"
}
}
else {
percentOne.text = "$0.00 / $0.00"
percentTwo.text = "$0.00 / $0.00"
percentThree.text = "$0.00 / $0.00"
splitTotal.text = "$0.00 / $0.00"
eachTotal.text = "$0.00 / $0.00"
// Update split number
splitNumber.text = String(Int(splitStepper.value))
if splitStepper.value == 1 {
splitPeople.text = "Person"
}
else {
splitPeople.text = "People"
}
}
}
// MARK: MFMessageComposeViewControllerDelegate
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
self.dismiss(animated: true, completion: nil)
}
// MARK: Actions
@IBAction func numKeyTapped(sender: UIButton) {
// Process key press
let keypadOutput = keypadBehavior.keypadButtonTapped(sender, totalIn: totalBillLabelValue)
// Assign returned value to totalBillLabelValue
totalBillLabelValue = keypadOutput
// Change the color of the totalBillLabel text after first input
// UIView.animate(withDuration: 8) {
// totalBillLabel.textColor = UIColor(hue: 3.59, saturation: 0.0, brightness: 0.21, alpha: 1.0)
// }
totalBillLabel.textColor = UIColor(hue: 3.59, saturation: 0.0, brightness: 0.21, alpha: 1.0)
// Insert dollar sign and update totalBillLabel
// totalBillLabel.text = String(format: "$%.2f", totalBillLabelValue)
totalBillLabel.text = "$" + keypadOutput
// Process the tip
processTipCalculation()
}
@IBAction func delKeyTapped(sender: UIButton) {
// Process delete key press
let deleteButtonOutput = keypadBehavior.deleteButtonTapped(sender, totalIn: totalBillLabelValue)
// Assign returned value to totalBillLabelValue
totalBillLabelValue = deleteButtonOutput
// Insert dollar sign and update totalBillLabel
totalBillLabel.text = "$" + deleteButtonOutput
// Process the tip
processTipCalculation()
}
@IBAction func tipTapped(_ sender: UITapGestureRecognizer) {
tipsStackTag = (sender.view?.tag)!
if isSplitsViewShowing == false {
UIView.transition(
from: tipsView,
to: splitsView,
duration: 1.0,
options: [UIView.AnimationOptions.transitionFlipFromRight, UIView.AnimationOptions.showHideTransitionViews] ,
// Pulse the share button on completion the first view only
completion: {
(finished: Bool) -> Void in
if self.isFirstSplitsView == true {
self.splitButton.pulseOnce(0.1)
self.isFirstSplitsView = false
}
else {
return
}
})
processTipCalculation()
}
else {
UIView.transition(
from: splitsView,
to: tipsView,
duration: 1.0,
options: [UIView.AnimationOptions.transitionFlipFromLeft, UIView.AnimationOptions.showHideTransitionViews],
// Pulse the percentage labels on completion
completion: nil)
}
isSplitsViewShowing = !isSplitsViewShowing
}
@IBAction func splitStepperTapped(_ sender: UIStepper) {
processTipCalculation()
}
@IBAction func splitShareTapped(_ sender: AnyObject) {
let messageVC = MFMessageComposeViewController()
if MFMessageComposeViewController.canSendText() {
messageVC.messageComposeDelegate = self;
// // Use iMessage App Extension if supported
// if #available(iOS 10.0, *) {
// let message = MSMessage()
// let layout = MSMessageTemplateLayout()
// layout.caption = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text!
// layout.subcaption = "(" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill)."
//
// message.layout = layout
//
// messageVC.message = message
//
// }
//
// // Or fall back on regular text message
// else {
// messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!"
// }
messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!"
self.present(messageVC, animated: false, completion: nil)
}
// if MFMessageComposeViewController.canSendText() {
//
// messageVC.messageComposeDelegate = self;
//
// messageVC.body = "With " + splitNumber.text! + " of us, your Tip / Total should be: " + eachTotal.text! + " (" + splitPercent.text! + " tip on a " + totalBillLabel.text! + " bill). CkPls!"
//
// self.present(messageVC, animated: false, completion: nil)
//
// }
}
}
| mit | 20498a85f2f2ab215634f6d7dc0222eb | 35.749175 | 206 | 0.579344 | 4.970982 | false | false | false | false |
chromatic-seashell/weibo | 新浪微博/新浪微博/classes/main/GDWTabBarController.swift | 1 | 5197 | //
// GDWTabBarController.swift
// 新浪微博
//
// Created by apple on 15/11/6.
// Copyright © 2015年 apple. All rights reserved.
//
import UIKit
class GDWTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
/*
设置tabBar的显示样式:
1在当前控制器中设置主题颜色
2在AppDelegate中设置外观颜色
UITabBar.appearance().tintColor=UIColor.orangeColor()
*/
tabBar.tintColor = UIColor.orangeColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1.添加加号按钮到tabBar
tabBar.addSubview(plusButton)
//2.设置按钮的位置
let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
let height = tabBar.bounds.height
let rect = CGRect(x: 0, y: 0, width: width, height: height)
plusButton.frame = CGRectOffset(rect, 2 * width, 0)
}
/* +号按钮的懒加载 */
lazy var plusButton : UIButton={
let btn = UIButton(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
btn.addTarget(self, action: Selector("plusBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
/*
MARK: - 内部控制方法
如果给一个方法加上private, 那么这个方法就只能在当前文件中访问
private不光能够修饰方法, 还可以修改类/属性
注意: 按钮的点击事件是由运行循环动态派发的, 而如果将方法标记为私有的, 那这个方法在外界就拿不到, 所以动态派发时就找不到该方法
只要加上@objc, 那么就可以让私有方法支持动态派发
*/
@objc private func plusBtnClick(){
GDWLog("btn")
/* 使tabBarVc显示index对应的控制器 */
//selectedIndex = 2
}
/* 纯代码时添加自控制器 */
func setUpChildViewController(){
/* 通过字符串生成类名,来创建对象,添加自控制器 */
addChildViewControllerWithString("GDWHomeViewController", imageName: "tabbar_home", title: "首页")
addChildViewControllerWithString("GDWMessageViewController", imageName: "tabbar_message_center", title: "消息")
addChildViewControllerWithString("GDWDiscoverViewController", imageName: "tabbar_discover", title: "发现")
addChildViewControllerWithString("GDWMeViewController", imageName: "tabbar_profile", title: "我")
/*:通过控制器对象,添加自控制器
addChildViewController(GDWHomeViewController(), imageName: "tabbar_home", title: "首页")
addChildViewController(GDWMessageViewController(), imageName: "tabbar_message_center", title: "消息")
addChildViewController(GDWDiscoverViewController(), imageName: "tabbar_discover", title: "发现")
addChildViewController(GDWMeViewController(), imageName: "tabbar_profile", title: "我")
*/
}
/* 通过字符串生成类名,来创建对象,添加自控制器 */
func addChildViewControllerWithString(childVcName: String, imageName:String , title:String ){
//1.获取命名空间
guard let workSpaceName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
GDWLog("没有获取命名空间")
return
}
//2通过字符串创建一个类名
let childVcClass:AnyObject? = NSClassFromString(workSpaceName + "." + childVcName)
guard let childClass = childVcClass as? UIViewController.Type
else{
GDWLog("childClass类名没有创建成功")
return
}
//3创建自控制器
let childVc = childClass.init()
//3.1设置控制器属性
//设置图片
childVc.tabBarItem.image=UIImage(named: imageName)
childVc.tabBarItem.selectedImage = UIImage(named:imageName + "_highlighted")
//设置标题
childVc.title=title
//设置背景颜色
childVc.view.backgroundColor = UIColor.lightGrayColor()
//3.2导航控制器
let nav = UINavigationController(rootViewController: childVc)
//3.3添加自控制器
addChildViewController(nav)
}
/* 通过控制器对象,添加自控制器 */
func addChildViewController(childVc: UIViewController, imageName:String , title:String) {
//1.设置控制器属性
//设置图片
childVc.tabBarItem.image=UIImage(named: imageName)
childVc.tabBarItem.selectedImage = UIImage(named:imageName + "_highlighted")
//设置标题
childVc.title=title
//设置背景颜色
childVc.view.backgroundColor = UIColor.lightGrayColor()
//2.导航控制器
let nav = UINavigationController(rootViewController: childVc)
//3.添加自控制器
addChildViewController(nav)
}
}
| apache-2.0 | 849832e008139e1e204bee0bde37883a | 31.82963 | 117 | 0.623872 | 4.694915 | false | false | false | false |
achimk/Swift-Playgrounds | Playgrounds/Swift-SequenceType.playground/Contents.swift | 1 | 1581 | //: Playground - noun: a place where people can play
import UIKit
import Foundation
// MARK: Stack example
struct Stack<T>: CustomStringConvertible, SequenceType, CollectionType {
typealias Element = T
private var contents: [T] = []
// MARK: Init
init() { }
init<S: SequenceType where S.Generator.Element == T>(_ sequence: S) {
contents = Array<T>(sequence)
}
// MARK: Push / Pop
mutating func push(newElement: T) {
contents.append(newElement)
}
mutating func pop() {
if contents.count > 0 {
contents.removeLast()
}
}
// MARK: CustomStringConvertible
var description: String {
return "Stack {content: \(contents)}"
}
// MARK: SequenceType
typealias Generator = AnyGenerator<T>
func generate() -> Generator {
return AnyGenerator(contents.generate())
}
// MARK: CollectionType
typealias Index = Int
var startIndex: Int {
return 0
}
var endIndex: Int {
return contents.count
}
subscript(i: Int) -> T {
return contents[i]
}
}
// MARK: Example
let initial = [1, 2, 3]
var stack = Stack<Int>(initial)
print(stack)
stack.push(10)
print(stack)
stack.pop()
print(stack)
print("\nSequenceType enumeration:")
for (index, value) in stack.enumerate() {
print("[\(index)] -> \(value)")
}
print("\nCollectionType enumeration:")
for index in stack.startIndex ..< stack.endIndex {
print("[\(index)] -> \(stack[index])")
}
| mit | 306bf668c29ccc96bc5db71fca28e542 | 18.280488 | 73 | 0.585073 | 4.238606 | false | false | false | false |
imex94/compiler-swift | SwiftCompiler/SwiftCompiler/RegExp.swift | 1 | 3658 | //
// Regex.swift
// SwiftCompiler
//
// Created by Alex Telek on 27/12/2015.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import Cocoa
enum Regex {
case NULL
case EMPTY
case CHAR(Character)
indirect case ALT(Regex, Regex)
indirect case SEQ(Regex, Regex)
indirect case STAR(Regex)
indirect case NTIMES(Regex, Int)
indirect case NOT(Regex)
indirect case RECORD(String, Regex)
}
func ==(a: Regex, b: Regex) -> Bool {
switch (a, b) {
case (.NULL, .NULL): return true
case (.EMPTY, .EMPTY): return true
case (.CHAR(let c1), .CHAR(let c2)) where c1 == c2: return true
case (.ALT(let x, let y), .ALT(let z, let v)) where x == z && y == v: return true
case (.SEQ(let x, let y), .SEQ(let z, let v)) where x == z && y == v: return true
case (.STAR(let x), .STAR(let y)) where x == y: return true
case (.NTIMES(let x, let y), .NTIMES(let z, let v)) where x == z && y == v: return true
case (.NOT(let x), .NOT(let y)) where x == y: return true
case (.RECORD(let x, let y), .RECORD(let z, let v)) where x == z && y == v: return true
default: return false
}
}
class RegExp: NSObject {
class func nullable(r: Regex) -> Bool {
switch r {
case .NULL: return false
case .EMPTY: return true
case .CHAR(_): return false
case .ALT(let r1, let r2): return nullable(r1) || nullable(r2)
case .SEQ(let r1, let r2): return nullable(r1) && nullable(r2)
case .STAR(_): return true
case .NTIMES(let r1, let n): return n == 0 ? true : nullable(r1)
case .NOT(let r1): return !nullable(r1)
case .RECORD(_, let r1): return nullable(r1)
}
}
class func der(c: Character, _ r: Regex) -> Regex {
switch r {
case .NULL: return .NULL
case .EMPTY: return .NULL
case .CHAR(let d): return c == d ? .EMPTY : .NULL
case .ALT(let r1, let r2): return .ALT(der(c, r1), der(c, r2))
case .SEQ(let r1, let r2):
if nullable(r1) {
return .ALT(.SEQ(der(c, r1), r2), der(c, r2))
} else {
return .SEQ(der(c, r1), r2)
}
case .STAR(let r1): return .SEQ(der(c, r1), .STAR(r1))
case .NTIMES(let r1, let n): return n == 0 ? .NULL : .SEQ(der(c, r1), .NTIMES(r1, n - 1))
case .NOT(let r1): return .NOT(der(c, r1))
case .RECORD(_, let r1): return der(c, r1)
}
}
class func ders(s: Array<Character>, _ r: Regex) -> Regex {
switch s.count {
case 0: return r
//TODO: Simplification
default:
let (c, rest) = (s.first!, s.dropFirst())
return ders(Array(rest), RegExp.simp(der(c, r)))
}
}
class func matches(r: Regex, s: String) -> Bool {
return nullable(ders(Array(s.characters), r))
}
class func simp(r: Regex) -> Regex {
switch r {
case .ALT(let r1, let r2):
switch (simp(r1), simp(r2)) {
case (.NULL, let re2): return re2
case (let re1, .NULL): return re1
case (let re1, let re2): return re1 == r2 ? re1 : .ALT(re1, re2)
}
case .SEQ(let r1, let r2):
switch (simp(r1), simp(r2)) {
case (.NULL, _): return .NULL
case (_, .NULL): return .NULL
case (.EMPTY, let re2): return re2
case (let re1, .EMPTY): return re1
case (let re1, let re2): return .SEQ(re1, re2)
}
case .NTIMES(let re1, let n): return .NTIMES(simp(re1), n)
default: return r
}
}
} | mit | 095261116102244e929a65780083cb0e | 33.186916 | 97 | 0.527208 | 3.256456 | false | false | false | false |
AdilSoomro/ASBottomSheet | ASBottomSheet/Classes/ASBottomSheet.swift | 1 | 10291 | //
// ASBottomSheet.swift
// Imagitor
//
// Created by Adil Soomro on 3/13/17.
// Copyright © 2017 BooleanBites Ltd. All rights reserved.
//
import UIKit
/**
* `ASBottomSheet` is a UIActionSheet like menu controller that can be used to
* show custom menu from bottom of the presenting view controller.
* It uses UICollectionView to show menu options provided by the developer.
* It is greatly inspired by the FCVerticalMenu
*/
@objc open class ASBottomSheet: UIViewController{
var menuItems:[ASBottomSheetItem]? = nil
@IBOutlet var collectionView: UICollectionView!
public var tintColor:UIColor?
private var bottomConstraints: NSLayoutConstraint!
private var heigthConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewLeadingConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewTrailingConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewBottomConstraints: NSLayoutConstraint!
@objc public var isOpen = false
/**
* Makes a `ASBottomSheet` that can be shown from bottom of screen.
* - parameter array: the options to be shown in menu collection view
*/
@objc public static func menu(withOptions array:[ASBottomSheetItem]) -> ASBottomSheet?{
let podBundle:Bundle? = Bundle(for:ASBottomSheet.classForCoder())
let storyboard:UIStoryboard?
//FROM COCOAPOD
if let bundleURL = podBundle {
storyboard = UIStoryboard.init(name: "ASBottomSheetStoryBoard", bundle: bundleURL)
//FROM MANUAL INSTALL
}else {
storyboard = UIStoryboard.init(name: "ASBottomSheetStoryBoard", bundle: nil)
}
if let main = storyboard {
let bottomMenu:ASBottomSheet = main.instantiateViewController(withIdentifier: "ASBottomSheet") as! ASBottomSheet
bottomMenu.menuItems = array
bottomMenu.tintColor = UIColor.white
return bottomMenu
}
return nil
}
open override func viewDidLoad() {
super.viewDidLoad()
// collectionView.backgroundColor = UIColor.orange
}
/**
* Shows the menu from bottom of the provided view controller
* - parameter viewController: the host view controller
*/
@objc public func showMenu(fromViewController viewController:UIViewController) {
if isOpen {
return
}
let view = self.view // force to load the view
let parentView = viewController.view // force to load the view
self.collectionView.reloadData()
viewController.addChild(self)
viewController.view.addSubview(view!)
self.didMove(toParent: viewController)
// view?.removeConstraints(view!.constraints)
view?.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let insets = parentView!.safeAreaInsets
collectionViewTrailingConstraints.constant = 0 - insets.right
collectionViewLeadingConstraints.constant = insets.left
} else {
let margins = parentView!.layoutMargins
collectionViewTrailingConstraints.constant = 0 - margins.right
collectionViewLeadingConstraints.constant = margins.left
}
NSLayoutConstraint.activate([
view!.leadingAnchor.constraint(equalTo: parentView!.leadingAnchor),
view!.trailingAnchor.constraint(equalTo: parentView!.trailingAnchor)
])
var bottomPadding:CGFloat = 0.0
if #available(iOS 11.0, *) {
bottomPadding = viewController.view?.safeAreaInsets.bottom ?? 0.0
}
let viewHeight = (self.calculateHeight()) + bottomPadding + 10.0
bottomConstraints = NSLayoutConstraint(item: view!, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: parentView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: viewHeight)
bottomConstraints.isActive = true
collectionViewBottomConstraints.constant = 0 - bottomPadding - 10
if heigthConstraints == nil {
heigthConstraints = NSLayoutConstraint(item: view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: viewHeight)
heigthConstraints.isActive = true
} else {
heigthConstraints.constant = viewHeight
}
parentView?.layoutIfNeeded()
self.collectionView.reloadData()
bottomConstraints.constant = 0
UIView.animate(withDuration: 0.2, animations: {
self.setupHeight()
parentView?.layoutIfNeeded()
}) { (complettion) in
}
view?.backgroundColor = UIColor.clear
isOpen = true
}
/**
* Hides the bottom menu with animation.
*
*/
@objc open func hide() {
//first take the menu frame and set its y origin to its bottom by adding
//its current origin plus height
let frame = self.view.frame
UIView.animate(withDuration: 0.2, animations: {
self.bottomConstraints.constant = frame.origin.y + frame.size.height
self.parent?.view.layoutIfNeeded()
}) { (finished:Bool) in
//cleanup
self.willMove(toParent: nil)
self.view.removeFromSuperview()
self.removeFromParent()
self.didMove(toParent: nil)
self.isOpen = false
};
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.collectionViewLayout.invalidateLayout()
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
self.setupHeight()
}) { (UIViewControllerTransitionCoordinatorContext) in
self.collectionView.reloadData()
}
}
func setupHeight() {
var bottomPadding:CGFloat = 0.0
if #available(iOS 11.0, *) {
bottomPadding = self.parent!.view?.safeAreaInsets.bottom ?? 0.0
}
let viewHeight = (self.calculateHeight()) + bottomPadding + 10.0
heigthConstraints.constant = viewHeight
}
}
extension ASBottomSheet : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (menuItems?.count)!
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:ASBottomSheetCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ASBottomSheetCell", for: indexPath) as! ASBottomSheetCell
let menuItem: ASBottomSheetItem = menuItems![indexPath.row]
cell.itemImageView.image = menuItem.tintedImage(withColor: self.tintColor)
cell.itemTitleLabel.text = menuItem.title
cell.itemTitleLabel.textColor = tintColor
cell.itemImageView.tintColor = tintColor
// cell.backgroundColor = UIColor.red
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let menuItem: ASBottomSheetItem = menuItems![indexPath.row]
hide()
if menuItem.action != nil {
menuItem.action!()
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0;
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0;
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
let totalWidth = (numberOfItems * flowLayout.itemSize.width)
if totalWidth > collectionView.frame.width {
let numItemsInRow:CGFloat = CGFloat(Int(collectionView.frame.width / flowLayout.itemSize.width));
let totalWidthForRow = flowLayout.itemSize.width * numItemsInRow
let combinedWidthRow = totalWidthForRow + ((numItemsInRow - 1) * flowLayout.minimumInteritemSpacing)
let paddingRow = (collectionView.frame.width - combinedWidthRow) / 2
return UIEdgeInsets(top: 0, left: paddingRow, bottom: 0, right: paddingRow)
}
let combinedItemWidth = totalWidth + ((numberOfItems - 1) * flowLayout.minimumInteritemSpacing)
let padding = (collectionView.frame.width - combinedItemWidth) / 2
return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
}
/**
* Calculates and returns the height to be consumed by the menu
* - return menu height
*
*/
func calculateHeight() -> CGFloat {
let topPadding:CGFloat = 10.0; //40 is top padding of collection view.
let bottomPadding:CGFloat = 10.0 // 10 is bottom padding of collection view.
return topPadding + collectionView.collectionViewLayout.collectionViewContentSize.height + bottomPadding
}
}
| mit | 5400c49035f53d501a91d7dbdd595e17 | 37.252788 | 263 | 0.644704 | 5.797183 | false | false | false | false |
onekiloparsec/siesta | Examples/GithubBrowser/Source/UI/UserViewController.swift | 1 | 4200 | import UIKit
import Siesta
class UserViewController: UIViewController, UISearchBarDelegate, ResourceObserver {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var userInfoView: UIView!
@IBOutlet weak var usernameLabel, fullNameLabel: UILabel!
@IBOutlet weak var avatar: RemoteImageView!
var statusOverlay = ResourceStatusOverlay()
var repoListVC: RepositoryListViewController?
var userResource: Resource? {
didSet {
// One call to removeObservers() removes both self and statusOverlay as observers of the old resource,
// since both observers are owned by self (see below).
oldValue?.removeObservers(ownedBy: self)
oldValue?.cancelLoadIfUnobserved(afterDelay: 0.1)
// Adding ourselves as an observer triggers an immediate call to resourceChanged().
userResource?.addObserver(self)
.addObserver(statusOverlay, owner: self)
.loadIfNeeded()
}
}
func resourceChanged(resource: Resource, event: ResourceEvent) {
// typedContent() infers that we want a User from context: showUser() expects one. Our content tranformer
// configuation in GithubAPI makes it so that the userResource actually holds a User. It is up to a Siesta
// client to ensure that the transformer output and the expected content type line up like this.
//
// If there were a type mismatch, typedContent() would return nil. (We could also provide a default value with
// the ifNone: param.)
showUser(userResource?.typedContent())
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = SiestaTheme.darkColor
userInfoView.hidden = true
statusOverlay.embedIn(self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setNeedsStatusBarAppearanceUpdate()
updateLoginButton()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent;
}
override func viewDidLayoutSubviews() {
statusOverlay.positionToCover(userInfoView)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if let searchText = searchBar.text where !searchText.isEmpty {
// Setting userResource triggers a load and display of the new user data. Note that Siesta’s redunant
// request elimination and model caching make it reasonable to do this on every keystroke.
userResource = GithubAPI.user(searchText)
}
}
func showUser(user: User?) {
userInfoView.hidden = (user == nil)
// It's often easiest to make the same code path handle both the “data” and “no data” states.
// If this UI update were more expensive, we could choose to do it only on ObserverAdded or NewData.
usernameLabel.text = user?.login
fullNameLabel.text = user?.name
avatar.imageURL = user?.avatarURL
// Setting the reposResource property of the embedded VC triggers load & display of the user’s repos.
repoListVC?.reposResource =
userResource?
.optionalRelative(user?.repositoriesURL)?
.withParam("type", "all")
.withParam("sort", "updated")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "repos" {
repoListVC = segue.destinationViewController as? RepositoryListViewController
}
}
@IBAction func logInOrOut() {
if(GithubAPI.isAuthenticated) {
GithubAPI.logOut()
updateLoginButton()
} else {
performSegueWithIdentifier("login", sender: loginButton)
}
}
private func updateLoginButton() {
loginButton.setTitle(GithubAPI.isAuthenticated ? "Log Out" : "Log In", forState: .Normal)
userResource?.loadIfNeeded()
}
}
| mit | e68b0b4e049e9778dbe0f4d316e33560 | 36.061947 | 118 | 0.636103 | 5.467363 | false | false | false | false |
PlusR/AAMFeedback | Feedback/ViewController.swift | 1 | 1290 | //
// ViewController.swift
// Feedback
//
// Created by akuraru on 2020/04/12.
// Copyright © 2020 Art & Mobile. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func openModal(_ sender: Any) {
let viewController = createViewController()
let feedbackNavigation = UINavigationController(rootViewController: viewController)
present(feedbackNavigation, animated: true)
}
@IBAction func pushAsViewController(_ sender: Any) {
let viewController = createViewController()
navigationController?.pushViewController(viewController, animated: true)
}
func createViewController() -> UIViewController {
let viewController = FeedbackViewController()
viewController.context = Context(
toRecipients: ["[email protected]"],
descriptionPlaceHolder: "Please write for details in modal."
)
viewController.beforeShowAction = { (controller) in
controller.addAttachmentData("text".data(using: .utf8)!, mimeType: "text/plain", fileName: "example.text")
}
viewController.view.backgroundColor = .white
return viewController
}
}
| bsd-3-clause | d0d88fbf786eee4f7e598b831f577378 | 30.439024 | 118 | 0.671839 | 5.176707 | false | false | false | false |
bolshedvorsky/swift-corelibs-foundation | Foundation/Locale.swift | 9 | 19094 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool {
return false // Auto-updating is only on Darwin
}
internal func __NSLocaleCurrent() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
internal var _wrapped : NSLocale
internal var _autoupdating : Bool
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false)
}
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
// swift-corelibs-foundation does not yet support autoupdating, but we can return the current locale (which will not change).
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: true)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
internal init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = _wrapped.object(forKey: .usesMetricSystem) as? Bool {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var description: String {
return _wrapped.description
}
public var debugDescription : String {
return _wrapped.debugDescription
}
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSLocale.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension Locale : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.decode(String.self, forKey: .identifier)
self.init(identifier: identifier)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.identifier, forKey: .identifier)
}
}
| apache-2.0 | 4358f7294606213c69c0a9bb90a35b7b | 38.331959 | 282 | 0.65585 | 5.085577 | false | false | false | false |
Shirley0202/notes | 下载器/MZDownloadManager-master/Example/MZDownloadManager/MZDownloadingCell.swift | 2 | 2700 | //
// MZDownloadingCell.swift
// MZDownloadManager
//
// Created by Muhammad Zeeshan on 22/10/2014.
// Copyright (c) 2014 ideamakerz. All rights reserved.
//
import UIKit
import MZDownloadManager
class MZDownloadingCell: UITableViewCell {
@IBOutlet var lblTitle : UILabel?
@IBOutlet var lblDetails : UILabel?
@IBOutlet var progressDownload : UIProgressView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateCellForRowAtIndexPath(_ indexPath : IndexPath, downloadModel: MZDownloadModel) {
self.lblTitle?.text = "File Title: \(downloadModel.fileName!)"
self.progressDownload?.progress = downloadModel.progress
var remainingTime: String = ""
if downloadModel.progress == 1.0 {
remainingTime = "Please wait..."
} else if let _ = downloadModel.remainingTime {
if (downloadModel.remainingTime?.hours)! > 0 {
remainingTime = "\(downloadModel.remainingTime!.hours) Hours "
}
if (downloadModel.remainingTime?.minutes)! > 0 {
remainingTime = remainingTime + "\(downloadModel.remainingTime!.minutes) Min "
}
if (downloadModel.remainingTime?.seconds)! > 0 {
remainingTime = remainingTime + "\(downloadModel.remainingTime!.seconds) sec"
}
} else {
remainingTime = "Calculating..."
}
var fileSize = "Getting information..."
if let _ = downloadModel.file?.size {
fileSize = String(format: "%.2f %@", (downloadModel.file?.size)!, (downloadModel.file?.unit)!)
}
var speed = "Calculating..."
if let _ = downloadModel.speed?.speed {
speed = String(format: "%.2f %@/sec", (downloadModel.speed?.speed)!, (downloadModel.speed?.unit)!)
}
var downloadedFileSize = "Calculating..."
if let _ = downloadModel.downloadedFile?.size {
downloadedFileSize = String(format: "%.2f %@", (downloadModel.downloadedFile?.size)!, (downloadModel.downloadedFile?.unit)!)
}
let detailLabelText = NSMutableString()
detailLabelText.appendFormat("File Size: \(fileSize)\nDownloaded: \(downloadedFileSize) (%.2f%%)\nSpeed: \(speed)\nTime Left: \(remainingTime)\nStatus: \(downloadModel.status)" as NSString, downloadModel.progress * 100.0)
lblDetails?.text = detailLabelText as String
}
}
| mit | daeba44463342a2c06811c86c7b1dca7 | 37.571429 | 229 | 0.621481 | 5.05618 | false | false | false | false |
poodarchu/iDaily | iDaily/iDaily/PDProfile.swift | 1 | 3076 | //
// PDProfile.swift
// iDaily
//
// Created by P. Chu on 6/2/16.
// Copyright © 2016 Poodar. All rights reserved.
//
import Foundation
import UIKit
class PDProfile: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, self.view.frame.size.width, 54 * 5)
tableView.autoresizingMask = [.FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleWidth]
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
return tableView
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension PDProfile: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let titles: [String] = ["Home", "Diaries", "Profile", "Settings", "Log Out"]
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"]
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
sideMenuViewController?.contentViewController = PDNavController()
sideMenuViewController?.hideMenuViewController()
break
default:
sideMenuViewController?.hideMenuViewController()
break
}
}
} | gpl-3.0 | 59f2fbdf21e81191f1bcb877689c0453 | 29.455446 | 122 | 0.633496 | 5.481283 | false | false | false | false |
vincentherrmann/multilinear-math | FastWaveletTransform.playground/Contents.swift | 1 | 3269 | //: Playground - noun: a place where people can play
import Cocoa
import MultilinearMath
print("start")
let h0: [Float] = [-0.00252085552, 0.0188991688, 0.0510309711, -0.0490589067, 0.0589671507, 0.79271543, 1.0953089, 0.32142213, -0.227000564, -0.0872127786, 0.0242141522, 0.0032346386]
let g0: [Float] = [-0.000504171127, -0.000253534876, 0.0460915789, 0.0190168768, -0.0825454742, 0.388706058, 1.10255682, 0.764762938, -0.0572841614, -0.188405827, -0.00831478462, 0.0161731932]
//
//let cReal = Wavelet(h0: h0, f0: h0.reversed())
//let cImag = Wavelet(h0: g0, f0: g0.reversed())
//
//let count: Int = 1024
//let length: Float = 10
//let xArray = Array(0..<count).map({Float($0) * length / Float(count)})
//let signal = Array(0..<128).map({Float($0)/10}).map({sin(3*$0)})
//var currentSignal = signal
//var analysis: [[Float]] = []
//
//var a: (r0: [Float], r1: [Float]) = ([], [])
//for _ in 0..<4 {
// a = waveletTransformForwardStep(signal: currentSignal, h0: db4.h0, h1: db4.h1)
// currentSignal = a.r0
//
// analysis.append(a.r1)
//}
//
//analysis.append(a.r0)
//let h0: [Float] = [0.6830127, 1.1830127, 0.3169873, -0.1830127]
let wReal = Wavelet(h0: h0, f0: h0.reversed())
let wImag = Wavelet(h0: g0, f0: g0.reversed())
let count: Int = 2048
let sampleFrequency: Float = 1
let frequency: Float = 5.2 //64 * pow(2, 0.5) / 32
let xArray = Array(0..<count).map({Float($0) / sampleFrequency})
let signal = xArray.map({sin(2*Float.pi*frequency*$0)})
let (fSignalReal, fSignalImag) = waveletTransformForwardStep(signal: signal, h0: h0, h1: [0] + h0.dropLast())
var packetsReal: [WaveletPacket] = waveletPacketTransform(signal: fSignalReal, wavelet: wReal, innerCodes: [68])
var packetsImag: [WaveletPacket] = waveletPacketTransform(signal: fSignalImag, wavelet: wImag, innerCodes: [68])
var packetsAbs: [WaveletPacket] = zip(packetsReal, packetsImag).map({
WaveletPacket(values: zip($0.0.values, $0.1.values).map({($0.0 + i*$0.1).absoluteValue}), code: $0.0.code)})
print("plotting...")
FastWaveletPlot(packets: packetsAbs)
FastWaveletPlot(packets: packetsReal)
FastWaveletPlot(packets: packetsImag)
let dSignal: [Float] = [0] + signal.dropLast()
let (dfSignalReal, dfSignalImag) = waveletTransformForwardStep(signal: dSignal, h0: h0, h1: [0] + h0.dropLast())
var dPacketsReal: [WaveletPacket] = waveletPacketTransform(signal: dfSignalReal, wavelet: wReal, innerCodes: [68])
var dPacketsImag: [WaveletPacket] = waveletPacketTransform(signal: dfSignalImag, wavelet: wImag, innerCodes: [68])
//estimate frequency for code 17
let code: UInt = 68
let oReal = packetsReal.filter({$0.code == code})[0].values
let oImag = packetsImag.filter({$0.code == code})[0].values
let dReal = dPacketsReal.filter({$0.code == code})[0].values
let dImag = dPacketsImag.filter({$0.code == code})[0].values
var estimatedFrequencies: [Float] = []
for n in 0..<oReal.count {
let oR = oReal[n] / sampleFrequency
let oI = oImag[n] / sampleFrequency
let dR = dReal[n] / sampleFrequency
let dI = dImag[n] / sampleFrequency
let p1 = ((dR + i*dI) * (oR - i*oI)).imaginary
let p2 = p1 / (2 * Float.pi * pow((oR + i*oI).absoluteValue, 2))
estimatedFrequencies.append(p2*sampleFrequency)
}
QuickArrayPlot(array: estimatedFrequencies)
| apache-2.0 | 28a65062160793dd52483e42988d7fe2 | 37.458824 | 192 | 0.68859 | 2.75865 | false | false | false | false |
LedgerHQ/u2f-ble-test-ios | u2f-ble-test-ios/Managers/DeviceManager.swift | 1 | 9400 | //
// DeviceManager.swift
// u2f-ble-test-ios
//
// Created by Nicolas Bigot on 13/05/2016.
// Copyright © 2016 Ledger. All rights reserved.
//
import Foundation
import CoreBluetooth
enum DeviceManagerState: String {
case NotBound
case Binding
case Bound
}
final class DeviceManager: NSObject {
static let deviceServiceUUID = "0000FFFD-0000-1000-8000-00805F9B34FB"
static let writeCharacteristicUUID = "F1D0FFF1-DEAA-ECEE-B42F-C9BA7ED623BB"
static let notifyCharacteristicUUID = "F1D0FFF2-DEAA-ECEE-B42F-C9BA7ED623BB"
static let controlpointLengthCharacteristicUUID = "F1D0FFF3-DEAA-ECEE-B42F-C9BA7ED623BB"
let peripheral: CBPeripheral
var deviceName: String? { return peripheral.name }
var onStateChanged: ((DeviceManager, DeviceManagerState) -> Void)?
var onDebugMessage: ((DeviceManager, String) -> Void)?
var onAPDUReceived: ((DeviceManager, NSData) -> Void)?
private var chunksize = 0
private var pendingChunks: [NSData] = []
private var writeCharacteristic: CBCharacteristic?
private var notifyCharacteristic: CBCharacteristic?
private var controlpointLengthCharacteristic: CBCharacteristic?
private(set) var state = DeviceManagerState.NotBound {
didSet {
onStateChanged?(self, self.state)
}
}
init(peripheral: CBPeripheral) {
self.peripheral = peripheral
super.init()
self.peripheral.delegate = self
}
func bindForReadWrite() {
guard state == .NotBound else {
onDebugMessage?(self, "Trying to bind but alreay busy")
return
}
// discover services
onDebugMessage?(self, "Discovering services...")
state = .Binding
let serviceUUID = CBUUID(string: self.dynamicType.deviceServiceUUID)
peripheral.discoverServices([serviceUUID])
}
func exchangeAPDU(data: NSData) {
guard state == .Bound else {
onDebugMessage?(self, "Trying to send APDU \(data) but not bound yet")
return
}
// slice APDU
onDebugMessage?(self, "Trying to split APDU into chunks...")
if let chunks = TransportHelper.split(data, command: .Message, chuncksize: chunksize) where chunks.count > 0 {
onDebugMessage?(self, "Successfully split APDU into \(chunks.count) part(s)")
pendingChunks = chunks
writeNextPendingChunk()
}
else {
onDebugMessage?(self, "Unable to split APDU into chunks")
resetState()
}
}
private func writeNextPendingChunk() {
guard pendingChunks.count > 0 else {
onDebugMessage?(self, "Trying to write pending chunk but nothing left to write")
return
}
let chunk = pendingChunks.removeFirst()
onDebugMessage?(self, "Writing pending chunk = \(chunk)")
peripheral.writeValue(chunk, forCharacteristic: writeCharacteristic!, type: .WithResponse)
}
private func handleReceivedChunk(chunk: NSData) {
// get chunk type
switch TransportHelper.getChunkType(chunk) {
case .Continuation:
//onDebugMessage?(self, "Received CONTINUATION chunk")
break
case .Message:
//onDebugMessage?(self, "Received MESSAGE chunk")
break
case .Error:
//onDebugMessage?(self, "Received ERROR chunk")
return
case .KeepAlive:
//onDebugMessage?(self, "Received KEEPALIVE chunk")
return
default:
//onDebugMessage?(self, "Received UNKNOWN chunk")
break
}
// join APDU
pendingChunks.append(chunk)
if let APDU = TransportHelper.join(pendingChunks, command: .Message) {
onDebugMessage?(self, "Successfully joined APDU = \(APDU)")
pendingChunks.removeAll()
onAPDUReceived?(self, APDU)
}
}
private func resetState() {
writeCharacteristic = nil
notifyCharacteristic = nil
controlpointLengthCharacteristic = nil
chunksize = 0
state = .NotBound
}
}
extension DeviceManager: CBPeripheralDelegate {
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
guard state == .Binding else { return }
guard
let services = peripheral.services where services.count > 0,
let service = services.first
else {
onDebugMessage?(self, "Unable to discover services")
resetState()
return
}
// discover characteristics
onDebugMessage?(self, "Successfully discovered services")
let writeCharacteristicUUID = CBUUID(string: self.dynamicType.writeCharacteristicUUID)
let notifyCharacteristicUUID = CBUUID(string: self.dynamicType.notifyCharacteristicUUID)
let controlpointLengthCharacteristicUUID = CBUUID(string: self.dynamicType.controlpointLengthCharacteristicUUID)
onDebugMessage?(self, "Discovering characteristics...")
peripheral.discoverCharacteristics([writeCharacteristicUUID, notifyCharacteristicUUID, controlpointLengthCharacteristicUUID], forService: service)
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
guard state == .Binding else { return }
guard
let characteristics = service.characteristics where characteristics.count >= 3,
let writeCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.writeCharacteristicUUID }).first,
let notifyCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.notifyCharacteristicUUID }).first,
let controlpointLengthCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.controlpointLengthCharacteristicUUID }).first
else {
onDebugMessage?(self, "Unable to discover characteristics")
resetState()
return
}
// retain characteristics
onDebugMessage?(self, "Successfully discovered characteristics")
self.writeCharacteristic = writeCharacteristic
self.notifyCharacteristic = notifyCharacteristic
self.controlpointLengthCharacteristic = controlpointLengthCharacteristic
// ask for notifications
onDebugMessage?(self, "Enabling notifications...")
peripheral.setNotifyValue(true, forCharacteristic: notifyCharacteristic)
}
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Binding else { return }
guard characteristic == notifyCharacteristic && characteristic.isNotifying && error == nil else {
onDebugMessage?(self, "Unable to enable notifications, error = \(error)")
resetState()
return
}
// ask for chunksize
onDebugMessage?(self, "Successfully enabled notifications")
onDebugMessage?(self, "Reading chunksize...")
peripheral.readValueForCharacteristic(self.controlpointLengthCharacteristic!)
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Bound || state == .Binding else { return }
guard
(characteristic == notifyCharacteristic || characteristic == controlpointLengthCharacteristic) && error == nil,
let data = characteristic.value
else {
onDebugMessage?(self, "Unable to read data, error = \(error), data = \(characteristic.value)")
resetState()
return
}
// received data
onDebugMessage?(self, "Received data of size \(data.length) = \(data)")
if characteristic == controlpointLengthCharacteristic {
// extract chunksize
let reader = DataReader(data: data)
guard let chunksize = reader.readNextBigEndianUInt16() else {
onDebugMessage?(self, "Unable to read chunksize")
resetState()
return
}
// successfully bound
onDebugMessage?(self, "Successfully read chuncksize = \(chunksize)")
self.chunksize = Int(chunksize)
state = .Bound
}
else if characteristic == notifyCharacteristic {
// handle received data
handleReceivedChunk(data)
}
else {
// unknown characteristic
onDebugMessage?(self, "Received data from unknown characteristic, ignoring")
}
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Bound else { return }
guard characteristic == writeCharacteristic && error == nil else {
onDebugMessage?(self, "Unable to write data, error = \(error)")
resetState()
return
}
// write pending chunks
writeNextPendingChunk()
}
} | apache-2.0 | 5af217bf75ca3997e639e326578c3be7 | 38.166667 | 160 | 0.639004 | 5.607995 | false | false | false | false |
huonw/swift | test/Driver/Dependencies/fail-added.swift | 36 | 1862 | /// bad ==> main | bad --> other
// RUN: rm -rf %t && cp -r %S/Inputs/fail-simple/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// CHECK-INITIAL-NOT: warning
// CHECK-INITIAL: Handled main.swift
// CHECK-INITIAL: Handled other.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
// CHECK-ADDED-NOT: Handled
// CHECK-ADDED: Handled bad.swift
// CHECK-ADDED-NOT: Handled
// CHECK-RECORD-ADDED-DAG: "./bad.swift": !dirty [
// CHECK-RECORD-ADDED-DAG: "./main.swift": [
// CHECK-RECORD-ADDED-DAG: "./other.swift": [
// RUN: rm -rf %t && cp -r %S/Inputs/fail-simple/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
| apache-2.0 | a2cfca27ab5533b8f3f40347fbe8922f | 61.066667 | 291 | 0.704619 | 3.027642 | false | false | true | false |
matheusbc/virtus | VirtusApp/VirtusApp/ViewController/LocalViewController.swift | 1 | 2361 | //
// LocalViewController.swift
// VirtusApp
//
// Copyright © 2017 Matheus B Campos. All rights reserved.
//
import MapKit
/// The local map view controller.
class LocalViewController: UIViewController, Loadable {
// MARK: Outlets
/// The map view instance.
@IBOutlet weak var mapView: MKMapView!
// MARK: Properties
/// The local map view model.
let localViewModel = LocalViewModel()
override func viewDidLoad() {
super.viewDidLoad()
let loading = self.showLoading(self)
self.setupMap()
self.dismissLoading(loading)
}
// MARK: Private Methods
/**
Setup the map.
Sets the initial position, the delegate and the pin.
*/
private func setupMap() {
mapView.delegate = self
centerMapOnLocation(location: localViewModel.initialLocation)
mapView.addAnnotation(localViewModel.virtusPin)
}
/**
Center the map to the location point.
- Parameter location: The center location point.
*/
private func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
localViewModel.regionRadius * 2.0,
localViewModel.regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
}
extension LocalViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if let annotation = annotation as? MapLocal {
let identifier = "virtusPin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton.init(type: .detailDisclosure) as UIView
}
return view
}
return nil
}
}
| mit | 97727d89fb55536239f62678e69b3603 | 31.328767 | 105 | 0.616102 | 5.539906 | false | false | false | false |
361425281/swift-snia | Swift-Sina/Classs/Home/Controller/DQBaseTableViewController.swift | 1 | 2504 |
//
// DQBaseTableViewController.swift
// Swift - sina
//
// Created by 熊德庆 on 15/10/26.
// Copyright © 2015年 熊德庆. All rights reserved.
//
import UIKit
class DQBaseTableViewController: UITableViewController
{
let userLogin = false
override func loadView()
{
userLogin ? super.loadView():setupVistorView()
}
func setupVistorView()
{
let vistorView = DQVistorView()
view = vistorView
//设置代理
//vistorView.vistorViewDelegate = self
view.backgroundColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorViewRegistClick()")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style:UIBarButtonItemStyle.Plain, target: self, action: "vistorViewLoginClick()")
if self is DQHomeTabBarController
{
vistorView.startRotationAnimation()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
else if self is DQMessageTableViewController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQDiscoverTabBarController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQMeTableViewController
{
vistorView.setupVistorView("visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
func didEnterBackgroud()
{
(view as? DQVistorView)?.pauseAnimation()
}
func didBecomeActive()
{
(view as? DQVistorView)?.resumeAnimation()
}
}
extension DQBaseTableViewController : DQVistorViewDelegate
{
func vistViewRegistClick()
{
print(__FUNCTION__)
}
func vistorViewLoginClick()
{
print(__FUNCTION__)
}
}
| apache-2.0 | ee7dd94fc73868ed9d57eb8df2aa559a | 33.863636 | 162 | 0.661017 | 5.068282 | false | false | false | false |
kiwitechnologies/ServiceClientiOS | ServiceClient/ServiceClient/TSGServiceClient/External/ImageCaching/ImageDownloader.swift | 1 | 24319 | // ImageDownloader.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used
/// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests
/// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The
/// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads.
public class RequestReceipt {
/// The download request created by the `ImageDownloader`.
public let request: Request
/// The unique identifier for the image filters and completion handlers when duplicate requests are made.
public let receiptID: String
init(request: Request, receiptID: String) {
self.request = request
self.receiptID = receiptID
}
}
/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
/// By default, any download request with a cached image equivalent in the image cache will automatically be served the
/// cached image representation. Additional advanced features include supporting multiple image filters and completion
/// handlers for a single request.
public class ImageDownloader {
/// The completion handler closure used when an image download completes.
public typealias CompletionHandler = Response<Image, NSError> -> Void
/// The progress handler closure called periodically during an image download.
public typealias ProgressHandler = (bytesRead: Int64, totalBytesRead: Int64, totalExpectedBytesToRead: Int64) -> Void
/**
Defines the order prioritization of incoming download requests being inserted into the queue.
- FIFO: All incoming downloads are added to the back of the queue.
- LIFO: All incoming downloads are added to the front of the queue.
*/
public enum DownloadPrioritization {
case FIFO, LIFO
}
class ResponseHandler {
let identifier: String
let request: Request
var operations: [(id: String, filter: ImageFilter?, completion: CompletionHandler?)]
init(request: Request, id: String, filter: ImageFilter?, completion: CompletionHandler?) {
self.request = request
self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
self.operations = [(id: id, filter: filter, completion: completion)]
}
}
// MARK: - Properties
/// The image cache used to store all downloaded images in.
public let imageCache: ImageRequestCache?
/// The credential used for authenticating each download request.
public private(set) var credential: NSURLCredential?
/// The underlying Alamofire `Manager` instance used to handle all download requests.
public let sessionManager:Manager
let downloadPrioritization: DownloadPrioritization
let maximumActiveDownloads: Int
var activeRequestCount = 0
var queuedRequests: [Request] = []
var responseHandlers: [String: ResponseHandler] = [:]
private let synchronizationQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}()
private let responseQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
// MARK: - Initialization
/// The default instance of `ImageDownloader` initialized with default values.
public static let defaultInstance = ImageDownloader()
/**
Creates a default `NSURLSessionConfiguration` with common usage parameter values.
- returns: The default `NSURLSessionConfiguration` instance.
*/
public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
configuration.HTTPShouldSetCookies = true
configuration.HTTPShouldUsePipelining = false
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 60
configuration.URLCache = ImageDownloader.defaultURLCache()
return configuration
}
/**
Creates a default `NSURLCache` with common usage parameter values.
- returns: The default `NSURLCache` instance.
*/
public class func defaultURLCache() -> NSURLCache {
return NSURLCache(
memoryCapacity: 20 * 1024 * 1024, // 20 MB
diskCapacity: 150 * 1024 * 1024, // 150 MB
diskPath: "com.alamofire.imagedownloader"
)
}
/**
Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
download count and image cache.
- parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
`Manager` instance.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = Manager(configuration: configuration)
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
/**
Initializes the `ImageDownloader` instance with the given sesion manager, download prioritization, maximum
active download count and image cache.
- parameter sessionManager: The Alamofire `Manager` instance to handle all download requests.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
sessionManager: Manager,
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = sessionManager
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
// MARK: - Authentication
/**
Associates an HTTP Basic Auth credential with all future download requests.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
*/
public func addAuthentication(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
addAuthentication(usingCredential: credential)
}
/**
Associates the specified credential with all future download requests.
- parameter credential: The credential.
*/
public func addAuthentication(usingCredential credential: NSURLCredential) {
dispatch_sync(synchronizationQueue) {
self.credential = credential
}
}
// MARK: - Download
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the filter and completion
handler are appended to the already existing request. Once the request completes, all filters and completion
handlers attached to the request are executed in the order they were added. Additionally, any filters attached
to the request with the same identifiers are only executed once. The resulting image is then passed into each
completion handler paired with the filter.
You should not attempt to directly cancel the `request` inside the request receipt since other callers may be
relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the
returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active
callers.
- parameter URLRequest: The URL request.
- parameter receiptID: The `identifier` for the `RequestReceipt` returned. Defaults to a new, randomly
generated UUID.
- parameter filter: The image filter to apply to the image after the download is complete. Defaults
to `nil`.
- parameter progress: The closure to be executed periodically during the lifecycle of the request.
Defaults to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when the download request is complete. Defaults to `nil`.
- returns: The request receipt for the download request if available. `nil` if the image is stored in the image
cache and the URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
receiptID: String = NSUUID().UUIDString,
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler?)
-> RequestReceipt?
{
var request: Request!
dispatch_sync(synchronizationQueue) {
// 1) Append the filter and completion handler to a pre-existing request if it already exists
let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
if let responseHandler = self.responseHandlers[identifier] {
responseHandler.operations.append(id: receiptID, filter: filter, completion: completion)
request = responseHandler.request
return
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch URLRequest.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
if let image = self.imageCache?.imageForRequest(
URLRequest.URLRequest,
withAdditionalIdentifier: filter?.identifier)
{
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: URLRequest.URLRequest,
response: nil,
data: nil,
result: .Success(image)
)
completion?(response)
}
return
}
default:
break
}
// 3) Create the request and set up authentication, validation and response serialization
request = self.sessionManager.request(URLRequest)
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
request.validate()
if let progress = progress {
request.progress { bytesRead, totalBytesRead, totalExpectedBytesToRead in
dispatch_async(progressQueue) {
progress(
bytesRead: bytesRead,
totalBytesRead: totalBytesRead,
totalExpectedBytesToRead: totalExpectedBytesToRead
)
}
}
}
request.response(
queue: self.responseQueue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { [weak self] response in
guard let strongSelf = self, let request = response.request else { return }
let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
switch response.result {
case .Success(let image):
var filteredImages: [String: Image] = [:]
for (_, filter, completion) in responseHandler.operations {
var filteredImage: Image
if let filter = filter {
if let alreadyFilteredImage = filteredImages[filter.identifier] {
filteredImage = alreadyFilteredImage
} else {
filteredImage = filter.filter(image)
filteredImages[filter.identifier] = filteredImage
}
} else {
filteredImage = image
}
strongSelf.imageCache?.addImage(
filteredImage,
forRequest: request,
withAdditionalIdentifier: filter?.identifier
)
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: response.request,
response: response.response,
data: response.data,
result: .Success(filteredImage),
timeline: response.timeline
)
completion?(response)
}
}
case .Failure:
for (_, _, completion) in responseHandler.operations {
dispatch_async(dispatch_get_main_queue()) { completion?(response) }
}
}
strongSelf.safelyDecrementActiveRequestCount()
strongSelf.safelyStartNextRequestIfNecessary()
}
)
// 4) Store the response handler for use when the request completes
let responseHandler = ResponseHandler(
request: request,
id: receiptID,
filter: filter,
completion: completion
)
self.responseHandlers[identifier] = responseHandler
// 5) Either start the request or enqueue it depending on the current active request count
if self.isActiveRequestCountBelowMaximumLimit() {
self.startRequest(request)
} else {
self.enqueueRequest(request)
}
}
if let request = request {
return RequestReceipt(request: request, receiptID: receiptID)
}
return nil
}
/**
Creates a download request using the internal Alamofire `Manager` instance for each specified URL request.
For each request, if the same download request is already in the queue or currently being downloaded, the
filter and completion handler are appended to the already existing request. Once the request completes, all
filters and completion handlers attached to the request are executed in the order they were added.
Additionally, any filters attached to the request with the same identifiers are only executed once. The
resulting image is then passed into each completion handler paired with the filter.
You should not attempt to directly cancel any of the `request`s inside the request receipts array since other
callers may be relying on the completion of that request. Instead, you should call
`cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize
the cancellation on behalf of all active callers.
- parameter URLRequests: The URL requests.
- parameter filter The image filter to apply to the image after each download is complete.
- parameter progress: The closure to be executed periodically during the lifecycle of the request. Defaults
to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when each download request is complete.
- returns: The request receipts for the download requests if available. If an image is stored in the image
cache and the URL request cache policy allows the cache to be used, a receipt will not be returned
for that request.
*/
public func downloadImages(
URLRequests URLRequests: [URLRequestConvertible],
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler? = nil)
-> [RequestReceipt]
{
return URLRequests.flatMap {
downloadImage(
URLRequest: $0,
filter: filter,
progress: progress,
progressQueue: progressQueue,
completion: completion
)
}
}
/**
Cancels the request in the receipt by removing the response handler and cancelling the request if necessary.
If the request is pending in the queue, it will be cancelled if no other response handlers are registered with
the request. If the request is currently executing or is already completed, the response handler is removed and
will not be called.
- parameter requestReceipt: The request receipt to cancel.
*/
public func cancelRequestForRequestReceipt(requestReceipt: RequestReceipt) {
dispatch_sync(synchronizationQueue) {
let identifier = ImageDownloader.identifierForURLRequest(requestReceipt.request.request!)
guard let responseHandler = self.responseHandlers[identifier] else { return }
if let index = responseHandler.operations.indexOf({ $0.id == requestReceipt.receiptID }) {
let operation = responseHandler.operations.removeAtIndex(index)
let response: Response<Image, NSError> = {
let URLRequest = requestReceipt.request.request!
let error: NSError = {
let failureReason = "ImageDownloader cancelled URL request: \(URLRequest.URLString)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Error.Domain, code: NSURLErrorCancelled, userInfo: userInfo)
}()
return Response(request: URLRequest, response: nil, data: nil, result: .Failure(error))
}()
dispatch_async(dispatch_get_main_queue()) { operation.completion?(response) }
}
if responseHandler.operations.isEmpty && requestReceipt.request.task.state == .Suspended {
requestReceipt.request.cancel()
}
}
}
// MARK: - Internal - Thread-Safe Request Methods
func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
var responseHandler: ResponseHandler!
dispatch_sync(synchronizationQueue) {
responseHandler = self.responseHandlers.removeValueForKey(identifier)
}
return responseHandler
}
func safelyStartNextRequestIfNecessary() {
dispatch_sync(synchronizationQueue) {
guard self.isActiveRequestCountBelowMaximumLimit() else { return }
while (!self.queuedRequests.isEmpty) {
if let request = self.dequeueRequest() where request.task.state == .Suspended {
self.startRequest(request)
break
}
}
}
}
func safelyDecrementActiveRequestCount() {
dispatch_sync(self.synchronizationQueue) {
if self.activeRequestCount > 0 {
self.activeRequestCount -= 1
}
}
}
// MARK: - Internal - Non Thread-Safe Request Methods
func startRequest(request: Request) {
request.resume()
activeRequestCount += 1
}
func enqueueRequest(request: Request) {
switch downloadPrioritization {
case .FIFO:
queuedRequests.append(request)
case .LIFO:
queuedRequests.insert(request, atIndex: 0)
}
}
func dequeueRequest() -> Request? {
var request: Request?
if !queuedRequests.isEmpty {
request = queuedRequests.removeFirst()
}
return request
}
func isActiveRequestCountBelowMaximumLimit() -> Bool {
return activeRequestCount < maximumActiveDownloads
}
static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
return URLRequest.URLRequest.URLString
}
}
| mit | b850eb6a7cd43b3f12db2085addad888 | 43.056159 | 122 | 0.636498 | 6.07975 | false | false | false | false |
hshidara/iOS | Ready?/Ready?/Runner.swift | 1 | 3008 | //
// Run.swift
// Ready?
//
// Created by Hidekazu Shidara on 9/20/15.
// Copyright © 2015 Hidekazu Shidara. All rights reserved.
//
import UIKit
import MapKit
import CoreData
import HealthKit
import CoreLocation
class Runner: UIViewController, CLLocationManagerDelegate {
var managedObjectContext: NSManagedObjectContext?
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("RunningStart") as UIViewController!
self.presentViewController(vc, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.backgroundColor = UIColor(hex: "#283E51")
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
self.mapView.mapType = MKMapType.HybridFlyover
self.mapView.showsUserLocation = true
self.mapView.zoomEnabled = false
self.mapView.userInteractionEnabled = false
self.mapView.rotateEnabled = false
self.mapView.pitchEnabled = false
}
func setUserLocation(){
let userLocation = mapView.userLocation
let region = MKCoordinateRegionMakeWithDistance(
userLocation.location!.coordinate, 2000, 2000)
mapView.setRegion(region, animated: true)
}
override func viewWillAppear(animated: Bool) {
if self.mapView.userLocationVisible {
let region = MKCoordinateRegionMakeWithDistance((self.mapView.userLocation.location?.coordinate)!, 400 , 400)
self.mapView.setRegion(region, animated: false)
}
else{
//Warning, no internet connection.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.latitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
// print("Errors: " + error.localizedDescription)
}
}
| mit | 359295f4c1c7b4fd0e54b6f52491da0f | 33.170455 | 126 | 0.686731 | 5.652256 | false | false | false | false |
vikmeup/MDCSwipeToChoose | Examples/SwiftLikedOrNope/SwiftLikedOrNope/AppDelegate.swift | 1 | 6166 | //
// AppDelegate.swift
// SwiftLikedOrNope
//
// Created by richard burdish on 3/28/15.
// Copyright (c) 2015 Richard Burdish. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// 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 "MDCSwipeToChoose.SwiftLikedOrNope" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
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("SwiftLikedOrNope", 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("SwiftLikedOrNope.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// 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
error = 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 \(error), \(error!.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 let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 65bfa746c3db12294f36fad244ee130a | 54.54955 | 290 | 0.717645 | 5.735814 | false | false | false | false |
mcjcloud/Show-And-Sell | Show And Sell/ChooseLocationViewController.swift | 1 | 3861 | //
// ChooseLocationViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 2/1/17.
// Copyright © 2017 Brayden Cloud. All rights reserved.
//
import UIKit
import MapKit
class ChooseLocationViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate {
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var mapView: MKMapView!
@IBOutlet var searchBar: UISearchBar!
var selectedAnnotation: MKPointAnnotation?
override func viewDidLoad() {
super.viewDidLoad()
// setup searchbar
searchBar.delegate = self
// enable/disable button
doneButton.isEnabled = selectedAnnotation != nil
}
// MARK: Searchbar Delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// asign map delegate
mapView.delegate = self
// put down keyboard
searchBar.resignFirstResponder()
// remove any annotations
mapView.removeAnnotations(mapView.annotations)
// create search request
let localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
let localSearch = MKLocalSearch(request: localSearchRequest)
// start the search
localSearch.start { searchResponse, error in
if searchResponse == nil {
let alert = UIAlertController(title: nil, message: "Location not found", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
alert.addAction(dismiss)
self.present(alert, animated: true, completion: nil)
return
}
let pointAnnotation = MKPointAnnotation()
var annText: String? = searchBar.text
if let point = searchResponse?.mapItems[0] {
print("address dict: \(point.placemark.addressDictionary?["FormattedAddressLines"])")
annText = point.name
pointAnnotation.subtitle = self.concat(point.placemark.addressDictionary!["FormattedAddressLines"] as! [Any])
}
pointAnnotation.title = annText
let centerCoord = searchResponse!.boundingRegion.center
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: centerCoord.latitude, longitude: centerCoord.longitude)
// create the pin
let pinAnnotationView = MKPinAnnotationView(annotation: pointAnnotation, reuseIdentifier: nil)
pinAnnotationView.animatesDrop = true
self.mapView.setCenter(pointAnnotation.coordinate, animated: true)
self.mapView.addAnnotation(pinAnnotationView.annotation!)
// set zoom
var region = MKCoordinateRegion(center: pointAnnotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
region = self.mapView.regionThatFits(region)
self.mapView.setRegion(region, animated: true)
print("coordinate: \(pointAnnotation.coordinate)")
}
}
// MARK: MKMapView Delegate
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
selectedAnnotation = view.annotation as? MKPointAnnotation
doneButton.isEnabled = selectedAnnotation != nil
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
selectedAnnotation = nil
doneButton.isEnabled = selectedAnnotation != nil
}
func concat(_ arr: [Any]) -> String {
var result = ""
for i in 0..<arr.count {
result += i == arr.count - 1 ? "\(arr[i])" : "\(arr[i]) "
}
return result
}
}
| apache-2.0 | b89e8577d978f3f937b5b3e3010a7524 | 36.475728 | 144 | 0.626166 | 5.651537 | false | false | false | false |
Antondomashnev/Sourcery | Pods/SourceKittenFramework/Source/SourceKittenFramework/Module.swift | 3 | 5365 | //
// Module.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-07.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
import Yams
/// Represents source module to be documented.
public struct Module {
/// Module Name.
public let name: String
/// Compiler arguments required by SourceKit to process the source files in this Module.
public let compilerArguments: [String]
/// Source files to be documented in this Module.
public let sourceFiles: [String]
/// Documentation for this Module. Typically expensive computed property.
public var docs: [SwiftDocs] {
var fileIndex = 1
let sourceFilesCount = sourceFiles.count
return sourceFiles.flatMap {
let filename = $0.bridge().lastPathComponent
if let file = File(path: $0) {
fputs("Parsing \(filename) (\(fileIndex)/\(sourceFilesCount))\n", stderr)
fileIndex += 1
return SwiftDocs(file: file, arguments: compilerArguments)
}
fputs("Could not parse `\(filename)`. Please open an issue at https://github.com/jpsim/SourceKitten/issues with the file contents.\n", stderr)
return nil
}
}
public init?(spmName: String) {
let yamlPath = ".build/debug.yaml"
guard let yaml = try? Yams.compose(yaml: String(contentsOfFile: yamlPath, encoding: .utf8)),
let commands = yaml?["commands"]?.mapping?.values else {
fatalError("SPM build manifest does not exist at `\(yamlPath)` or does not match expected format.")
}
guard let moduleCommand = commands.first(where: { $0["module-name"]?.string == spmName }) else {
fputs("Could not find SPM module '\(spmName)'. Here are the modules available:\n", stderr)
let availableModules = commands.flatMap({ $0["module-name"]?.string })
fputs("\(availableModules.map({ " - " + $0 }).joined(separator: "\n"))\n", stderr)
return nil
}
guard let imports = moduleCommand["import-paths"]?.array(of: String.self),
let otherArguments = moduleCommand["other-args"]?.array(of: String.self),
let sources = moduleCommand["sources"]?.array(of: String.self) else {
fatalError("SPM build manifest does not match expected format.")
}
name = spmName
compilerArguments = {
var arguments = sources
arguments.append(contentsOf: ["-module-name", spmName])
arguments.append(contentsOf: otherArguments)
arguments.append(contentsOf: ["-I"])
arguments.append(contentsOf: imports)
return arguments
}()
sourceFiles = sources
}
/**
Failable initializer to create a Module by the arguments necessary pass in to `xcodebuild` to build it.
Optionally pass in a `moduleName` and `path`.
- parameter xcodeBuildArguments: The arguments necessary pass in to `xcodebuild` to build this Module.
- parameter name: Module name. Will be parsed from `xcodebuild` output if nil.
- parameter path: Path to run `xcodebuild` from. Uses current path by default.
*/
public init?(xcodeBuildArguments: [String], name: String? = nil, inPath path: String = FileManager.default.currentDirectoryPath) {
let xcodeBuildOutput = runXcodeBuild(arguments: xcodeBuildArguments, inPath: path) ?? ""
guard let arguments = parseCompilerArguments(xcodebuildOutput: xcodeBuildOutput.bridge(), language: .swift,
moduleName: name ?? moduleName(fromArguments: xcodeBuildArguments)) else {
fputs("Could not parse compiler arguments from `xcodebuild` output.\n", stderr)
fputs("Please confirm that `xcodebuild` is building a Swift module.\n", stderr)
let file = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("xcodebuild-\(NSUUID().uuidString).log")
try! xcodeBuildOutput.data(using: .utf8)?.write(to: file)
fputs("Saved `xcodebuild` log file: \(file.path)\n", stderr)
return nil
}
guard let moduleName = moduleName(fromArguments: arguments) else {
fputs("Could not parse module name from compiler arguments.\n", stderr)
return nil
}
self.init(name: moduleName, compilerArguments: arguments)
}
/**
Initializer to create a Module by name and compiler arguments.
- parameter name: Module name.
- parameter compilerArguments: Compiler arguments required by SourceKit to process the source files in this Module.
*/
public init(name: String, compilerArguments: [String]) {
self.name = name
self.compilerArguments = compilerArguments
sourceFiles = compilerArguments.filter({
$0.bridge().isSwiftFile() && $0.isFile
}).map {
return URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}
}
}
// MARK: CustomStringConvertible
extension Module: CustomStringConvertible {
/// A textual representation of `Module`.
public var description: String {
return "Module(name: \(name), compilerArguments: \(compilerArguments), sourceFiles: \(sourceFiles))"
}
}
| mit | 16f7968c97613eebd97a66c9fce8e8db | 45.25 | 154 | 0.635974 | 4.922018 | false | false | false | false |
google/flatbuffers | swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift | 4 | 2360 | import FlatBuffers
import Foundation
func run() {
// create a `FlatBufferBuilder`, which will be used to serialize objects
let builder = FlatBufferBuilder(initialSize: 1024)
let weapon1Name = builder.create(string: "Sword")
let weapon2Name = builder.create(string: "Axe")
// start creating the weapon by calling startWeapon
let weapon1Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon1Name, &builder)
Weapon.add(damage: 3, &builder)
// end the object by passing the start point for the weapon 1
let sword = Weapon.endWeapon(&builder, start: weapon1Start)
let weapon2Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon2Name, &builder)
Weapon.add(damage: 5, &builder)
let axe = Weapon.endWeapon(&builder, start: weapon2Start)
// Create a FlatBuffer `vector` that contains offsets to the sword and axe
// we created above.
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
// Name of the Monster.
let name = builder.create(string: "Orc")
let pathOffset = fbb.createVector(ofStructs: [
Vec3(x: 0, y: 0),
Vec3(x: 5, y: 5),
])
// startVector(len, elementSize: MemoryLayout<Offset>.size)
// for o in offsets.reversed() {
// push(element: o)
// }
// endVector(len: len)
let orc = Monster.createMonster(
&builder,
pos: Vec3(x: 1, y: 2),
hp: 300,
nameOffset: name,
color: .red,
weaponsVectorOffset: weaponsOffset,
equippedType: .weapon,
equippedOffset: axe,
pathOffset: pathOffset)
// let start = Monster.startMonster(&builder)
// Monster.add(pos: Vec3(x: 1, y: 2), &builder)
// Monster.add(hp: 300, &builder)
// Monster.add(name: name, &builder)
// Monster.add(color: .red, &builder)
// Monster.addVectorOf(weapons: weaponsOffset, &builder)
// Monster.add(equippedType: .weapon, &builder)
// Monster.addVectorOf(paths: weaponsOffset, &builder)
// Monster.add(equipped: axe, &builder)
// var orc = Monster.endMonster(&builder, start: start)
// Call `finish(offset:)` to instruct the builder that this monster is complete.
builder.finish(offset: orc)
// This must be called after `finish()`.
// `sizedByteArray` returns the finished buf of type [UInt8].
let buf = builder.sizedByteArray
// or you can use to get an object of type Data
let bufData = ByteBuffer(data: builder.sizedBuffer)
}
| apache-2.0 | 5e90282a987b1bed29860536cf6626f8 | 32.239437 | 82 | 0.694492 | 3.625192 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGAP/GAPLESecureConnectionsRandom.swift | 1 | 1506 | //
// GAPLESecureConnectionsRandom.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Specifies the LE Secure Connections Random Value
/// Size: 16 octets
/// Format defined in [Vol 3], Part H, Section 2.3.5.6.4
@frozen
public struct GAPLESecureConnectionsRandom: GAPData, Equatable, Hashable {
public static let dataType: GAPDataType = .lowEnergySecureConnectionsRandom
public let random: UInt16
public init(random: UInt16) {
self.random = random
}
}
public extension GAPLESecureConnectionsRandom {
init?(data: Data) {
guard data.count == 2
else { return nil }
let random = UInt16(littleEndian: UInt16(bytes: (data[0],
data[1])))
self.init(random: random)
}
func append(to data: inout Data) {
data += random.littleEndian
}
var dataLength: Int {
return 2
}
}
// MARK: - ExpressibleByIntegerLiteral
extension GAPLESecureConnectionsRandom: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt16) {
self.init(random: value)
}
}
// MARK: - CustomStringConvertible
extension GAPLESecureConnectionsRandom: CustomStringConvertible {
public var description: String {
return random.description
}
}
| mit | 91a59841cbc1c037f4ddd0afc9742f30 | 20.811594 | 79 | 0.608638 | 4.918301 | false | false | false | false |
trujillo138/MyExpenses | MyExpenses/Shared/Model/ExpensesBalance.swift | 1 | 2615 | //
// ExpensesBalance.swift
// MyExpenses
//
// Created by Tomas Trujillo on 7/15/18.
// Copyright © 2018 TOMApps. All rights reserved.
//
import Foundation
//
// ExpensesBalance.swift
// ExpenseManager
//
// Created by Tomas Trujillo on 6/21/18.
// Copyright © 2018 Tomas Trujillo. All rights reserved.
//
import Foundation
class ExpensesBalance: NSObject, NSCoding {
//MARK: Keys
private struct Keys {
static let LastExpenseKey = "LastExpense"
static let AmountSavedKey = "AmountSaved"
static let AmountSpentKey = "AmountSpent"
static let DateOfBalanceKey = "DateOfBalance"
static let GoalKey = "Goal"
}
//MARK: Properties
var lastExpense: Expense
var amountSaved: Double
var amountSpent: Double
var dateOfBalance: Date
var goal: Double
//MARK: Initializers
init(lastExpense: Expense, amountSaved: Double, amountSpent: Double, dateOfBalance: Date, goal: Double) {
self.lastExpense = lastExpense
self.amountSaved = amountSaved
self.amountSpent = amountSpent
self.dateOfBalance = dateOfBalance
self.goal = goal
}
//MARK: Coding
required init?(coder aDecoder: NSCoder) {
self.lastExpense = aDecoder.decodeObject(forKey: Keys.LastExpenseKey) as! Expense
self.amountSaved = aDecoder.decodeDouble(forKey: Keys.AmountSavedKey)
self.amountSpent = aDecoder.decodeDouble(forKey: Keys.AmountSpentKey)
self.dateOfBalance = aDecoder.decodeObject(forKey: Keys.DateOfBalanceKey) as? Date ?? Date()
self.goal = aDecoder.decodeDouble(forKey: Keys.GoalKey)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(lastExpense, forKey: Keys.LastExpenseKey)
aCoder.encode(amountSaved, forKey: Keys.AmountSavedKey)
aCoder.encode(amountSpent, forKey: Keys.AmountSpentKey)
aCoder.encode(dateOfBalance, forKey: Keys.DateOfBalanceKey)
}
//MARK: Helper methods
static func createBalanceFromExpenses(_ expenses: [Expense], goal: Double, income: Double) -> ExpensesBalance? {
guard let lastExpenseOfPeriod = expenses.last else { return nil }
let currentDate = Date()
let totalAmountSpent = expenses.reduce(0, { x, e in
x + e.amount
})
let totalAmountSaved = income - totalAmountSpent
return ExpensesBalance(lastExpense: lastExpenseOfPeriod, amountSaved: totalAmountSaved,
amountSpent: totalAmountSpent, dateOfBalance: currentDate, goal: goal)
}
}
| apache-2.0 | 73aad45bff61357d5b9bb30d577bd5c1 | 30.865854 | 116 | 0.667815 | 4.413851 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICore/Source/Validators/BSBNumber.swift | 1 | 1059 | //
// BSBNumber.swift
// StripeUICore
//
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
@_spi(STP) public struct BSBNumber {
private let number: String
private let pattern: String
public init(number: String) {
self.number = number
self.pattern = "###-###"
}
public var isComplete: Bool {
return formattedNumber().count >= pattern.count
}
public func formattedNumber() -> String {
guard let formatter = TextFieldFormatter(format: pattern) else {
return number
}
let allowedCharacterSet = CharacterSet.stp_asciiDigit
let result = formatter.applyFormat(
to: number.stp_stringByRemovingCharacters(from: allowedCharacterSet.inverted),
shouldAppendRemaining: true
)
guard result.count > 0 else {
return ""
}
return result
}
public func bsbNumberText() -> String {
return number.filter {$0 != "-"}
}
}
| mit | 98b297a955284fbff6528155e42a6c0b | 23.604651 | 90 | 0.601134 | 4.702222 | false | false | false | false |
tinypass/piano-sdk-for-ios | Sources/Composer/Composer/Models/CustomParams.swift | 1 | 1269 | import Foundation
@objcMembers
public class CustomParams: NSObject {
private var content: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
private var user: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
private var request: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
public func content(key: String, value: String) -> CustomParams {
put(dict: &content, key: key, value: value)
return self;
}
public func user(key: String, value: String) -> CustomParams {
put(dict: &user, key: key, value: value)
return self;
}
public func request(key: String, value: String) -> CustomParams {
put(dict: &request, key: key, value: value)
return self;
}
private func put(dict: inout Dictionary<String, Array<String>>, key: String, value: String) {
if dict[key] == nil {
dict[key] = [String]()
}
dict[key]?.append(value)
}
public func toDictionary() -> [String: Any] {
var dict = [String: Any]()
dict["content"] = content
dict["user"] = user
dict["request"] = request
return dict
}
}
| apache-2.0 | 4a460872d88faa9e7de107730cc02bd2 | 29.214286 | 97 | 0.588652 | 4.188119 | false | false | false | false |
fgengine/quickly | Quickly/Compositions/Standart/Placeholders/QPlaceholderImageTitleDetailValueComposition.swift | 1 | 8233 | //
// Quickly
//
open class QPlaceholderImageTitleDetailValueComposable : QComposable {
public var imageStyle: QImageViewStyleSheet
public var imageWidth: CGFloat
public var imageSpacing: CGFloat
public var titleStyle: QPlaceholderStyleSheet
public var titleHeight: CGFloat
public var titleSpacing: CGFloat
public var detailStyle: QPlaceholderStyleSheet
public var detailHeight: CGFloat
public var valueStyle: QPlaceholderStyleSheet
public var valueSize: CGSize
public var valueSpacing: CGFloat
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
imageStyle: QImageViewStyleSheet,
imageWidth: CGFloat = 96,
imageSpacing: CGFloat = 4,
titleStyle: QPlaceholderStyleSheet,
titleHeight: CGFloat,
titleSpacing: CGFloat = 4,
detailStyle: QPlaceholderStyleSheet,
detailHeight: CGFloat,
valueStyle: QPlaceholderStyleSheet,
valueSize: CGSize,
valueSpacing: CGFloat = 4
) {
self.imageStyle = imageStyle
self.imageWidth = imageWidth
self.imageSpacing = imageSpacing
self.titleStyle = titleStyle
self.titleHeight = titleHeight
self.titleSpacing = titleSpacing
self.detailStyle = detailStyle
self.detailHeight = detailHeight
self.valueStyle = valueStyle
self.valueSize = valueSize
self.valueSpacing = valueSpacing
super.init(edgeInsets: edgeInsets)
}
}
open class QPlaceholderImageTitleDetailValueComposition< Composable: QPlaceholderImageTitleDetailValueComposable > : QComposition< Composable > {
public private(set) lazy var imageView: QImageView = {
let view = QImageView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var titleView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var detailView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var valueView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _imageWidth: CGFloat?
private var _imageSpacing: CGFloat?
private var _titleHeight: CGFloat?
private var _titleSpacing: CGFloat?
private var _detailHeight: CGFloat?
private var _valueSize: CGSize?
private var _valueSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
private var _imageConstraints: [NSLayoutConstraint] = [] {
willSet { self.imageView.removeConstraints(self._imageConstraints) }
didSet { self.imageView.addConstraints(self._imageConstraints) }
}
private var _titleConstraints: [NSLayoutConstraint] = [] {
willSet { self.titleView.removeConstraints(self._titleConstraints) }
didSet { self.titleView.addConstraints(self._titleConstraints) }
}
private var _detailConstraints: [NSLayoutConstraint] = [] {
willSet { self.detailView.removeConstraints(self._detailConstraints) }
didSet { self.detailView.addConstraints(self._detailConstraints) }
}
private var _valueConstraints: [NSLayoutConstraint] = [] {
willSet { self.valueView.removeConstraints(self._valueConstraints) }
didSet { self.valueView.addConstraints(self._valueConstraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth))
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(imageSize.height, composable.titleHeight + composable.titleSpacing + composable.detailHeight, composable.valueSize.height) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing || self._valueSpacing != composable.valueSpacing {
self._edgeInsets = composable.edgeInsets
self._imageSpacing = composable.imageSpacing
self._titleSpacing = composable.titleSpacing
self._valueSpacing = composable.valueSpacing
self._constraints = [
self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.titleView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing),
self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.detailView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.valueView.topLayout >= self.contentView.topLayout.offset(composable.edgeInsets.top),
self.valueView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.valueView.bottomLayout <= self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.valueView.centerYLayout == self.contentView.centerYLayout
]
}
if self._imageWidth != composable.imageWidth {
self._imageWidth = composable.imageWidth
self._imageConstraints = [
self.imageView.widthLayout == composable.imageWidth
]
}
if self._titleHeight != composable.titleHeight {
self._titleHeight = composable.titleHeight
self._titleConstraints = [
self.titleView.heightLayout == composable.titleHeight
]
}
if self._detailHeight != composable.detailHeight {
self._detailHeight = composable.detailHeight
self._detailConstraints = [
self.detailView.heightLayout == composable.detailHeight
]
}
if self._valueSize != composable.valueSize {
self._valueSize = composable.valueSize
self._valueConstraints = [
self.valueView.widthLayout == composable.valueSize.width,
self.valueView.heightLayout == composable.valueSize.height
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.imageView.apply(composable.imageStyle)
self.titleView.apply(composable.titleStyle)
self.detailView.apply(composable.detailStyle)
self.valueView.apply(composable.valueStyle)
}
}
| mit | 9a2c605a95f5dd5bbd9f3201d98c2ab2 | 46.045714 | 205 | 0.685048 | 5.658419 | false | false | false | false |
hmtinc/Z80-Swift | Source/ports.swift | 1 | 645 | //
// ports.swift
// Z80-Swift
//
// Created by Harsh Mistry on 2017-12-15.
// Copyright © 2017 Harsh Mistry. All rights reserved.
//
import Foundation
class Ports {
var data : [UInt8] = [];
var NMI : Bool = false;
var MI : Bool = false;
var portData = [uint16 : uint8]()
func readPort(_ address : uint16) -> uint8{
print("Reading port at " + String(address))
return portData[address] ?? uint8(0)
}
func writePort(_ address : uint16, _ value : uint8){
print("Writing value = " + String(value) + " to port at " + String(address))
portData[address] = value
}
}
| mit | c9be941803ecd8776aed10dfed8d7d53 | 22.851852 | 84 | 0.576087 | 3.462366 | false | false | false | false |
Senspark/ee-x | src/ios/ee/facebook_ads/FacebookNativeAd.swift | 1 | 7244 | //
// FacebookNativeAd.swift
// Pods
//
// Created by eps on 6/25/20.
//
import FBAudienceNetwork
private let kTag = "\(FacebookNativeAd.self)"
internal class FacebookNativeAd:
NSObject, IBannerAd, FBNativeAdDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _adId: String
private let _layoutName: String
private let _messageHelper: MessageHelper
private var _helper: BannerAdHelper?
private let _viewHelper: ViewHelper
private var _isLoaded = false
private var _ad: FBNativeAd?
private var _view: EEFacebookNativeAdView?
init(_ bridge: IMessageBridge,
_ logger: ILogger,
_ adId: String,
_ layoutName: String) {
_bridge = bridge
_logger = logger
_adId = adId
_layoutName = layoutName
_messageHelper = MessageHelper("FacebookNativeAd", _adId)
_viewHelper = ViewHelper(CGPoint.zero, CGSize.zero, false)
super.init()
_helper = BannerAdHelper(_bridge, self, _messageHelper)
registerHandlers()
createInternalAd()
createView()
}
func destroy() {
deregisterHandlers()
destroyView()
destroyInternalAd()
}
func registerHandlers() {
_helper?.registerHandlers()
_bridge.registerHandler(_messageHelper.createInternalAd) { _ in
self.createInternalAd()
return ""
}
_bridge.registerHandler(_messageHelper.destroyInternalAd) { _ in
self.destroyInternalAd()
return ""
}
}
func deregisterHandlers() {
_helper?.deregisterHandlers()
_bridge.deregisterHandler(_messageHelper.createInternalAd)
_bridge.deregisterHandler(_messageHelper.destroyInternalAd)
}
func createInternalAd() {
Thread.runOnMainThread {
if self._ad != nil {
return
}
self._isLoaded = false
let ad = FBNativeAd(placementID: self._adId)
ad.delegate = self
self._ad = ad
}
}
func destroyInternalAd() {
Thread.runOnMainThread {
guard let ad = self._ad else {
return
}
self._isLoaded = false
ad.delegate = nil
ad.unregisterView()
self._ad = nil
}
}
func createAdView() -> EEFacebookNativeAdView? {
guard let nibObjects = Bundle(for: EEFacebookNativeAdView.self).loadNibNamed(_layoutName,
owner: nil,
options: nil) else {
assert(false, "Invalid layout")
return nil
}
guard let view = nibObjects[0] as? EEFacebookNativeAdView else {
assert(false, "Invalid layout class")
return nil
}
return view
}
func createView() {
Thread.runOnMainThread {
assert(self._view == nil)
guard let view = self.createAdView() else {
assert(false, "Cannot create ad view")
return
}
view.adchoicesView.corner = UIRectCorner.topRight
self._view = view
self._viewHelper.view = view
let rootView = Utils.getCurrentRootViewController()
rootView?.view.addSubview(view)
}
}
func destroyView() {
Thread.runOnMainThread {
guard let view = self._view else {
return
}
view.removeFromSuperview()
self._view = nil
self._viewHelper.view = nil
}
}
var isLoaded: Bool {
return _isLoaded
}
func load() {
Thread.runOnMainThread {
guard let ad = self._ad else {
assert(false, "Ad is not initialized")
return
}
ad.loadAd(withMediaCachePolicy: FBNativeAdsCachePolicy.all)
}
}
var position: CGPoint {
get { return _viewHelper.position }
set(value) { _viewHelper.position = value }
}
var size: CGSize {
get { return _viewHelper.size }
set(value) { _viewHelper.size = value }
}
var isVisible: Bool {
get { return _viewHelper.isVisible }
set(value) {
_viewHelper.isVisible = value
if value {
Thread.runOnMainThread {
self._view?.subviews.forEach { $0.setNeedsDisplay() }
}
}
}
}
func nativeAdDidLoad(_ ad: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
assert(ad == self._ad)
guard let view = self._view else {
assert(false, "Ad view is not initialized")
return
}
ad.unregisterView()
if view.callToActionButton != nil {
let rootView = Utils.getCurrentRootViewController()
ad.registerView(forInteraction: view,
mediaView: view.mediaView,
iconView: view.iconView,
viewController: rootView,
clickableViews: [view.callToActionButton])
}
view.adchoicesView.nativeAd = ad
view.bodyLabel.text = ad.bodyText
view.callToActionButton.setTitle(ad.callToAction,
for: UIControl.State.normal)
view.socialContextLabel.text = ad.socialContext
view.sponsorLabel.text = ad.sponsoredTranslation
view.titleLabel.text = ad.headline
self._isLoaded = true
self._bridge.callCpp(self._messageHelper.onLoaded)
}
}
func nativeAd(_ nativeAd: FBNativeAd, didFailWithError error: Error) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): \(error.localizedDescription)")
self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
}
func nativeAdWillLogImpression(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
}
}
func nativeAdDidClick(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
self._bridge.callCpp(self._messageHelper.onClicked)
}
}
func nativeAdDidFinishHandlingClick(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
}
}
func nativeAdDidDownloadMedia(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(#function)")
}
}
}
| mit | 5c6e12e83355213e878fbd25c51d07cd | 30.224138 | 110 | 0.53175 | 5.260712 | false | false | false | false |
apple/swift | test/Interop/SwiftToCxx/structs/resilient-struct-in-cxx.swift | 1 | 10566 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -module-name Structs -clang-header-expose-decls=all-public -emit-clang-header-path %t/structs.h
// RUN: %FileCheck %s < %t/structs.h
// RUN: %check-interop-cxx-header-in-clang(%t/structs.h)
public struct FirstSmallStruct {
public var x: UInt32
#if CHANGE_LAYOUT
public var y: UInt32 = 0
#endif
public func dump() {
print("find - small dump")
#if CHANGE_LAYOUT
print("x&y = \(x)&\(y)")
#else
print("x = \(x)")
#endif
}
public mutating func mutate() {
x = x * 2
#if CHANGE_LAYOUT
y = ~y
#endif
}
}
// CHECK: class FirstSmallStruct;
// CHECK: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::FirstSmallStruct> = true;
// CHECK: class FirstSmallStruct final {
// CHECK-NEXT: public:
// CHECK: inline FirstSmallStruct(const FirstSmallStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline FirstSmallStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline FirstSmallStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return FirstSmallStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_FirstSmallStruct;
// CHECK-NEXT:};
// CHECK: class _impl_FirstSmallStruct {
// CHECK: };
// CHECK-EMPTY:
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: } // end namespace
// CHECK-EMPTY:
// CHECK-NEXT: namespace swift {
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: struct TypeMetadataTrait<Structs::FirstSmallStruct> {
// CHECK-NEXT: inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return Structs::_impl::$s7Structs16FirstSmallStructVMa(0)._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isValueType<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isOpaqueLayout<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: struct implClassFor<Structs::FirstSmallStruct> { using type = Structs::_impl::_impl_FirstSmallStruct; };
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
// CHECK-NEXT: namespace Structs __attribute__((swift_private)) {
@frozen public struct FrozenStruct {
private let storedInt: Int32
}
// CHECK: class FrozenStruct final {
// CHECK: alignas(4) char _storage[4];
// CHECK-NEXT: friend class _impl::_impl_FrozenStruct;
// CHECK-NEXT: };
public struct LargeStruct {
public let x1: Int
let x2, x3, x4, x5, x6: Int
public var firstSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 65)
}
public func dump() {
print("x.1 = \(x1), .2 = \(x2), .3 = \(x3), .4 = \(x4), .5 = \(x5)")
}
}
// CHECK: class LargeStruct final {
// CHECK-NEXT: public:
// CHECK: inline LargeStruct(const LargeStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline LargeStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline LargeStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return LargeStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_LargeStruct;
// CHECK-NEXT: };
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
init(x: Int) {
storedRef = RefCountedClass(x: x)
}
public func dump() {
print("storedRef = \(storedRef.x)")
}
}
// CHECK: inline StructWithRefCountStoredProp(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
public func createLargeStruct(_ x: Int) -> LargeStruct {
return LargeStruct(x1: x, x2: -x, x3: x * 2, x4: x - 4, x5: 0, x6: 21)
}
public func printSmallAndLarge(_ x: FirstSmallStruct, _ y: LargeStruct) {
x.dump()
y.dump()
}
public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 0)
}
public func mutateSmall(_ x: inout FirstSmallStruct) {
#if CHANGE_LAYOUT
let y = x.y
x.y = x.x
x.x = y
#else
x.x += 1
#endif
}
// CHECK: inline LargeStruct createLargeStruct(swift::Int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs17createLargeStructyAA0cD0VSiF(result, x);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline StructWithRefCountStoredProp createStructWithRefCountStoredProp() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs34createStructWithRefCountStoredPropAA0cdefgH0VyF(result);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline void mutateSmall(FirstSmallStruct& x) noexcept {
// CHECK-NEXT: return _impl::$s7Structs11mutateSmallyyAA05FirstC6StructVzF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x));
// CHECK-NEXT: }
// CHECK: inline void printSmallAndLarge(const FirstSmallStruct& x, const LargeStruct& y) noexcept {
// CHECK-NEXT: return _impl::$s7Structs18printSmallAndLargeyyAA05FirstC6StructV_AA0eG0VtF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x), _impl::_impl_LargeStruct::getOpaquePointer(y));
// CHECK-NEXT: }
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void FirstSmallStruct::setX(uint32_t value) {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::mutate() {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV6mutateyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs11LargeStructV010firstSmallC0AA05FirsteC0Vvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void StructWithRefCountStoredProp::dump() const {
// CHECK-NEXT: return _impl::$s7Structs28StructWithRefCountStoredPropV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
| apache-2.0 | 39cad0bd5c78e4dcc6c0582178c65baf | 41.95122 | 231 | 0.699886 | 3.6841 | false | false | false | false |
muhlenXi/SwiftEx | projects/Swift4Demo/Swift4Demo/main.swift | 1 | 538 | //
// main.swift
// Swift4Demo
//
// Created by 席银军 on 2017/10/19.
// Copyright © 2017年 muhlenXi. All rights reserved.
//
import Foundation
struct JSON {
var data: [String: Any] = [:]
init(data: [String: Any]) {
self.data = data
}
subscript<T>(key: String) -> T? {
return data[key] as? T
}
}
let json = JSON(data: ["title": "Generic subscript", "duration": 300])
let title: String? = json["title"]
let duration: Int? = json["duration"]
print(title)
print(duration)
| mit | bc4b37e6615f4b43b30c6bf00ab30efd | 13.297297 | 70 | 0.57845 | 3.093567 | false | false | false | false |
maximveksler/Developing-iOS-8-Apps-with-Swift | lesson-013/Trax Segue/Trax/GPX.swift | 2 | 7403 | //
// GPX.swift
// Trax
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
// Very simple GPX file parser.
// Only verified to work for CS193p demo purposes!
import Foundation
class GPX: NSObject, Printable, NSXMLParserDelegate
{
// MARK: - Public API
var waypoints = [Waypoint]()
var tracks = [Track]()
var routes = [Track]()
typealias GPXCompletionHandler = (GPX?) -> Void
class func parse(url: NSURL, completionHandler: GPXCompletionHandler) {
GPX(url: url, completionHandler: completionHandler).parse()
}
// MARK: - Public Classes
class Track: Entry, Printable
{
var fixes = [Waypoint]()
override var description: String {
let waypointDescription = "fixes=[\n" + "\n".join(fixes.map { $0.description }) + "\n]"
return " ".join([super.description, waypointDescription])
}
}
class Waypoint: Entry, Printable
{
var latitude: Double
var longitude: Double
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
super.init()
}
var info: String? {
set { attributes["desc"] = newValue }
get { return attributes["desc"] }
}
lazy var date: NSDate? = self.attributes["time"]?.asGpxDate
override var description: String {
return " ".join(["lat=\(latitude)", "lon=\(longitude)", super.description])
}
}
class Entry: NSObject, Printable
{
var links = [Link]()
var attributes = [String:String]()
var name: String? {
set { attributes["name"] = newValue }
get { return attributes["name"] }
}
override var description: String {
var descriptions = [String]()
if attributes.count > 0 { descriptions.append("attributes=\(attributes)") }
if links.count > 0 { descriptions.append("links=\(links)") }
return " ".join(descriptions)
}
}
class Link: Printable
{
var href: String
var linkattributes = [String:String]()
init(href: String) { self.href = href }
var url: NSURL? { return NSURL(string: href) }
var text: String? { return linkattributes["text"] }
var type: String? { return linkattributes["type"] }
var description: String {
var descriptions = [String]()
descriptions.append("href=\(href)")
if linkattributes.count > 0 { descriptions.append("linkattributes=\(linkattributes)") }
return "[" + " ".join(descriptions) + "]"
}
}
// MARK: - Printable
override var description: String {
var descriptions = [String]()
if waypoints.count > 0 { descriptions.append("waypoints = \(waypoints)") }
if tracks.count > 0 { descriptions.append("tracks = \(tracks)") }
if routes.count > 0 { descriptions.append("routes = \(routes)") }
return "\n".join(descriptions)
}
// MARK: - Private Implementation
private let url: NSURL
private let completionHandler: GPXCompletionHandler
private init(url: NSURL, completionHandler: GPXCompletionHandler) {
self.url = url
self.completionHandler = completionHandler
}
private func complete(success success: Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.completionHandler(success ? self : nil)
}
}
private func fail() { complete(success: false) }
private func succeed() { complete(success: true) }
private func parse() {
let qos = Int(QOS_CLASS_USER_INITIATED.value)
dispatch_async(dispatch_get_global_queue(qos, 0)) {
if let data = NSData(contentsOfURL: self.url) {
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
} else {
self.fail()
}
}
}
func parserDidEndDocument(parser: NSXMLParser) { succeed() }
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { fail() }
func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) { fail() }
private var input = ""
func parser(parser: NSXMLParser!foundCharacters string: String!{
input += string
}
private var waypoint: Waypoint?
private var track: Track?
private var link: Link?
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
switch elementName {
case "trkseg":
if track == nil { fallthrough }
case "trk":
tracks.append(Track())
track = tracks.last
case "rte":
routes.append(Track())
track = routes.last
case "rtept", "trkpt", "wpt":
let latitude = (attributeDict["lat"] as! NSString).doubleValue
let longitude = (attributeDict["lon"] as! NSString).doubleValue
waypoint = Waypoint(latitude: latitude, longitude: longitude)
case "link":
link = Link(href: attributeDict["href"] as! String)
default: break
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
switch elementName {
case "wpt":
if waypoint != nil { waypoints.append(waypoint!); waypoint = nil }
case "trkpt", "rtept":
if waypoint != nil { track?.fixes.append(waypoint!); waypoint = nil }
case "trk", "trkseg", "rte":
track = nil
case "link":
if link != nil {
if waypoint != nil {
waypoint!.links.append(link!)
} else if track != nil {
track!.links.append(link!)
}
}
link = nil
default:
if link != nil {
link!.linkattributes[elementName] = input.trimmed
} else if waypoint != nil {
waypoint!.attributes[elementName] = input.trimmed
} else if track != nil {
track!.attributes[elementName] = input.trimmed
}
input = ""
}
}
}
// MARK: - Extensions
private extension String {
var trimmed: String {
return (self as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
extension String {
var asGpxDate: NSDate? {
get {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z"
return dateFormatter.dateFromString(self)
}
}
}
| apache-2.0 | f26c22da8d6d5dd405b09a330226d5c4 | 32.197309 | 181 | 0.554775 | 5.036054 | false | false | false | false |
GoodMorningCody/EverybodySwift | UIKitSample/UIKitSample/EasyTableViewController.swift | 1 | 3785 | //
// EasyTableViewController.swift
// UIKitSample
//
// Created by Cody on 2014. 12. 29..
// Copyright (c) 2014년 tiekle. All rights reserved.
//
import UIKit
class EasyTableViewController: UITableViewController {
var arrayOfStoryboardID : [String] = ["DatePickerTestViewController","WebViewTestViewController","MapViewTestViewController"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "모두의 Swift"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return arrayOfStoryboardID.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = arrayOfStoryboardID[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var storyboarId = arrayOfStoryboardID[indexPath.row]
var viewController = storyboard?.instantiateViewControllerWithIdentifier(storyboarId) as UIViewController
self.navigationController?.pushViewController(viewController, animated: true)
//self.presentViewController(viewController, animated: true, completion: nil)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 2c49730783b675ef2d4f419a792f82d3 | 36.77 | 157 | 0.70188 | 5.554412 | false | false | false | false |
gfjalar/pavo | Pavo/ImageHelpers.swift | 1 | 5178 | //
// ImageHelpers.swift
// Pavo
//
// Created by Piotr Galar on 01/05/2015.
// Copyright (c) 2015 Piotr Galar. All rights reserved.
//
import Cocoa
import ImageIO
import AVFoundation
public extension CGImage {
// ADD: async execution, completed callback
public func saveAsPNG(to dir: String, with name: String) {
let path = "\(dir)\(name).png"
let url = CFURLCreateWithFileSystemPath(nil, path, .CFURLPOSIXPathStyle,
false)
// TODO: catch
guard let destination = CGImageDestinationCreateWithURL(url, kUTTypePNG,
1, nil) else { return }
CGImageDestinationAddImage(destination, self, nil)
CGImageDestinationFinalize(destination)
}
func toCVPixelBuffer(width: Int, _ height: Int,
_ pixelFormat: OSType) -> CVPixelBuffer {
let settings = [
kCVPixelBufferCGImageCompatibilityKey as String: true,
kCVPixelBufferCGBitmapContextCompatibilityKey as String: true
]
let baseAddress = UnsafeMutablePointer<Void>(CFDataGetBytePtr(
CGDataProviderCopyData(CGImageGetDataProvider(self)))
)
let bytesPerRow = CGImageGetBytesPerRow(self)
var buffer : CVPixelBuffer?
CVPixelBufferCreateWithBytes(kCFAllocatorDefault, width, height,
pixelFormat, baseAddress, bytesPerRow, nil, nil, settings,
&buffer
)
return buffer!
}
func size() -> (Int, Int) {
return (CGImageGetWidth(self), CGImageGetHeight(self))
}
}
extension Array where Element:CGImage {
// ADD: async execution, completed callback
func saveAsPNG(to dir: String, with name: String) {
var count = 0
for image in self {
image.saveAsPNG(to: dir, with: "\(name)\(count)")
count++
}
}
// ADD: async execution, completed callback
func saveAsMPEG4(to dir: String, with name: String, _ fps: Int,
_ pixelFormat: Int, _ bitRate: Int, _ profileLevel: String) {
if self.count == 0 {
return
}
let url = NSURL(fileURLWithPath: "\(dir)\(name).mp4")
// TODO: catch
let video = try! AVAssetWriter(URL: url, fileType: AVFileTypeMPEG4)
let (width, height) = self.first!.size()
let osPixelFormat = OSType(pixelFormat)
let settings: [String : AnyObject] = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: width,
AVVideoHeightKey: height,
AVVideoCompressionPropertiesKey: [
AVVideoAverageBitRateKey: bitRate,
AVVideoProfileLevelKey: profileLevel,
AVVideoMaxKeyFrameIntervalKey: 1
]
]
let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo,
outputSettings: settings)
let adaptor = AVAssetWriterInputPixelBufferAdaptor(
assetWriterInput: input, sourcePixelBufferAttributes: nil)
input.expectsMediaDataInRealTime = false
video.addInput(input)
video.startWriting()
video.startSessionAtSourceTime(kCMTimeZero)
var count = 0
func isReady() -> Bool {
return adaptor.assetWriterInput.readyForMoreMediaData
}
func getTime() -> CMTime {
return CMTimeMake(Int64(count), Int32(fps))
}
for image in self {
let buffer = image.toCVPixelBuffer(width, height, osPixelFormat)
let time = getTime()
ExponentialBackoff(isReady, base: 0.1, multiplier: 2.0) {
adaptor.appendPixelBuffer(buffer,
withPresentationTime: time)
}
count++
}
input.markAsFinished()
video.endSessionAtSourceTime(getTime())
video.finishWritingWithCompletionHandler({})
}
}
extension Dictionary {
func get(key: Key, or defaultValue: Value) -> Value {
if let value = self[key] {
return value
}
return defaultValue
}
}
// ADD: maximum number of backoffs, error closure
func ExponentialBackoff(condition: () -> Bool, base: NSTimeInterval,
multiplier: NSTimeInterval, closure: () -> ()) {
var backoff = base
while !condition() {
NSRunLoop.currentRunLoop().runUntilDate(
NSDate(timeIntervalSinceNow: backoff))
backoff *= multiplier
}
closure()
}
public func SaveAsMPEG4(images: [CGImage], to dir: String, with name: String,
fps: Int,
_ pixelFormat: Int = Int(kCVPixelFormatType_32BGRA),
_ bitRate: Int = 20000*1000,
_ profileLevel: String = AVVideoProfileLevelH264HighAutoLevel) {
images.saveAsMPEG4(to: dir, with: name, fps, pixelFormat, bitRate,
profileLevel)
}
public func SaveAsPNG(images: [CGImage], to dir: String, with name: String) {
images.saveAsPNG(to: dir, with: name)
}
| mit | 5fa8bf9efedc5fe1b20da3e2304ceabe | 30.192771 | 80 | 0.589224 | 5.002899 | false | false | false | false |
sergdort/CleanArchitectureRxSwift | RealmPlatform/Entities/RMUser.swift | 1 | 2180 | //
// RMUser.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import QueryKit
import Domain
import RealmSwift
import Realm
final class RMUser: Object {
@objc dynamic var address: RMAddress?
@objc dynamic var company: RMCompany?
@objc dynamic var email: String = ""
@objc dynamic var name: String = ""
@objc dynamic var phone: String = ""
@objc dynamic var uid: String = ""
@objc dynamic var username: String = ""
@objc dynamic var website: String = ""
override class func primaryKey() -> String? {
return "uid"
}
}
extension RMUser {
static var website: Attribute<String> { return Attribute("website")}
static var email: Attribute<String> { return Attribute("email")}
static var name: Attribute<String> { return Attribute("name")}
static var phone: Attribute<String> { return Attribute("phone")}
static var username: Attribute<String> { return Attribute("username")}
static var uid: Attribute<String> { return Attribute("uid")}
static var address: Attribute<RMAddress> { return Attribute("address")}
static var company: Attribute<RMCompany> { return Attribute("company")}
}
extension RMUser: DomainConvertibleType {
typealias DomainType = Domain.User
func asDomain() -> Domain.User {
return User(address: address!.asDomain(),
company: company!.asDomain(),
email: email,
name: name,
phone: phone,
uid: uid,
username: username,
website: website)
}
}
extension Domain.User: RealmRepresentable {
typealias RealmType = RealmPlatform.RMUser
func asRealm() -> RealmPlatform.RMUser {
return RMUser.build { object in
object.uid = uid
object.address = address.asRealm()
object.company = company.asRealm()
object.email = email
object.name = name
object.phone = phone
object.username = username
object.website = website
}
}
}
| mit | 0223a684c6a33cf4a8f53465d0c17796 | 30.57971 | 75 | 0.618173 | 4.558577 | false | false | false | false |
nathan/hush | Hush/KeyboardEmulator.swift | 1 | 2566 | import Cocoa
class KeyboardEmulator {
class func pressAndReleaseChar(_ char: UniChar, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressChar(char, flags: flags, eventSource: es)
releaseChar(char, flags: flags, eventSource: es)
}
class func pressChar(_ char: UniChar, keyDown: Bool = true, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
var char = char
let event = CGEvent(keyboardEventSource: es, virtualKey: 0, keyDown: keyDown)
if !flags.isEmpty {
let flags = CGEventFlags(rawValue: UInt64(flags.rawValue))
event?.flags = flags
}
event?.keyboardSetUnicodeString(stringLength: 1, unicodeString: &char)
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
class func releaseChar(_ char: UniChar, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressChar(char, keyDown: false, flags: flags, eventSource: es)
}
}
extension KeyboardEmulator {
class func pressAndReleaseKey(_ key: CGKeyCode, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressKey(key, flags: flags, eventSource: es)
releaseKey(key, flags: flags, eventSource: es)
}
class func pressKey(_ key: CGKeyCode, keyDown: Bool = true, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
let event = CGEvent(keyboardEventSource: es, virtualKey: key, keyDown: keyDown)
if !flags.isEmpty {
let flags = CGEventFlags(rawValue: UInt64(flags.rawValue))
event?.flags = flags
}
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
class func releaseKey(_ key: CGKeyCode, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressKey(key, keyDown: false, flags: flags, eventSource: es)
}
}
extension KeyboardEmulator {
class func replaceText(_ text: String, eventSource es: CGEventSource) {
selectAll(eventSource: es)
OperationQueue.main.addOperation {self.typeText(text, eventSource: es)}
}
class func typeText(_ text: String, eventSource es: CGEventSource) {
for char in text.utf16 {
self.pressAndReleaseChar(char, eventSource: es)
}
}
class func deleteAll(eventSource es: CGEventSource) {
selectAll(eventSource: es)
OperationQueue.main.addOperation {
self.pressAndReleaseKey(CGKeyCode(kVK_Delete), eventSource: es)
}
}
class func selectAll(eventSource es: CGEventSource) {
pressKey(CGKeyCode(kVK_Command), eventSource: es)
pressAndReleaseKey(CGKeyCode(kVK_ANSI_A), flags: CGEventFlags_.Command, eventSource: es)
releaseKey(CGKeyCode(kVK_Command), eventSource: es)
}
}
| unlicense | ab73c8b8af40876d5b174e37eeced0ae | 40.387097 | 121 | 0.714341 | 4.079491 | false | false | false | false |
cookpad/Phakchi | Tests/Phakchi/InteractionBuilderTest.swift | 1 | 4912 | import XCTest
@testable import Phakchi
class InteractionBuilderTestCase: XCTestCase {
var builder: InteractionBuilder!
override func setUp() {
super.setUp()
self.builder = InteractionBuilder()
}
fileprivate func makeInteractionWithRequestHeaders(_ headers: Headers?) -> Interaction! {
self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates",
query: nil, headers:
headers,
body: nil)
.willRespondWith(status: 200)
return self.builder.makeInteraction()
}
fileprivate func makeInteractionWithResponseHeaders(_ headers: Headers?) -> Interaction! {
self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates")
.willRespondWith(status: 200, headers: headers, body: nil)
return self.builder.makeInteraction()
}
func testIsValid() {
XCTAssertFalse(self.builder.isValid)
XCTAssertFalse(self.builder.uponReceiving("Hello").isValid)
XCTAssertFalse(self.builder
.uponReceiving("Hello")
.with(.get, path: "/integrates/")
.isValid)
XCTAssertTrue(self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates/")
.willRespondWith(status: 200)
.isValid)
}
func testDefaultRequestHeader() {
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction0 = makeInteractionWithRequestHeaders(["Host": "example.com"])
XCTAssertEqual(interaction0?.request.headers?["Authorization"] as? String, "authtoken")
XCTAssertEqual(interaction0?.request.headers?["Host"] as? String, "example.com")
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction1 = makeInteractionWithRequestHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction1?.request.headers?["Content-Type"] as? String, "text/plain")
XCTAssertEqual(interaction1?.request.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction2 = makeInteractionWithRequestHeaders(nil)
XCTAssertEqual(interaction2?.request.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction2?.request.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultRequestHeaders = nil
let interaction3 = makeInteractionWithRequestHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction3?.request.headers?["Content-Type"] as? String, "text/plain")
self.builder.defaultRequestHeaders = nil
let interaction4 = makeInteractionWithRequestHeaders(nil)
XCTAssertNil(interaction4?.request.headers)
}
func testDefaultResponseHeader() {
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction0 = makeInteractionWithResponseHeaders(["Host": "example.com"])
XCTAssertEqual(interaction0?.response.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction0?.response.headers?["Authorization"] as? String, "authtoken")
XCTAssertEqual(interaction0?.response.headers?["Host"] as? String, "example.com")
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction1 = makeInteractionWithResponseHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction1?.response.headers?["Content-Type"] as? String, "text/plain")
XCTAssertEqual(interaction1?.response.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction2 = makeInteractionWithResponseHeaders(nil)
XCTAssertEqual(interaction2?.response.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction2?.response.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultResponseHeaders = nil
let interaction3 = makeInteractionWithResponseHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction3?.response.headers?["Content-Type"] as? String, "text/plain")
self.builder.defaultResponseHeaders = nil
let interaction4 = makeInteractionWithResponseHeaders(nil)
XCTAssertNil(interaction4?.response.headers)
}
}
| mit | bb4932aa430a57ecba1b3566f82c5bf5 | 40.982906 | 102 | 0.659406 | 5.100727 | false | true | false | false |
git-hushuai/MOMO | MMHSMeterialProject/UINavigationController/BusinessFile/ModelAnalysis/Reflect/Reflect.swift | 1 | 1999 | //
// Reflect.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
class Reflect: NSObject, NSCoding{
lazy var mirror: Mirror = {Mirror(reflecting: self)}()
required override init(){}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
assert(type.check(), "[Charlin Feng]: Property '\(name)' type can not be a '\(type.realType.rawValue)' Type,Please use 'NSNumber' instead!")
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
self.setValue(aDecoder.decodeObjectForKey(name), forKeyPath: name)
}
}else{
self.setValue(aDecoder.decodeObjectForKey(name), forKeyPath: name)
}
}
}
func encodeWithCoder(aCoder: NSCoder) {
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
print("name:\(name)--type:\(type)---value:\(value)");
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
aCoder.encodeObject(value as? AnyObject, forKey: name)
}
}else{
aCoder.encodeObject(value as? AnyObject, forKey: name)
}
}
}
func parseOver(){}
}
| mit | 35970ba9c8222c202080788917becb56 | 26.191781 | 153 | 0.507809 | 5.607345 | false | false | false | false |
lbkchen/cvicu-app | complicationsapp/Pods/CVCalendar/CVCalendar/CVCalendarManager.swift | 1 | 8355 | //
// CVCalendarManager.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
private let YearUnit = NSCalendarUnit.Year
private let MonthUnit = NSCalendarUnit.Month
private let WeekUnit = NSCalendarUnit.WeekOfMonth
private let WeekdayUnit = NSCalendarUnit.Weekday
private let DayUnit = NSCalendarUnit.Day
private let AllUnits = YearUnit.union(MonthUnit).union(WeekUnit).union(WeekdayUnit).union(DayUnit)
public final class CVCalendarManager {
// MARK: - Private properties
private var components: NSDateComponents
private unowned let calendarView: CalendarView
public var calendar: NSCalendar
// MARK: - Public properties
public var currentDate: NSDate
// MARK: - Private initialization
public var starterWeekday: Int
public init(calendarView: CalendarView) {
self.calendarView = calendarView
currentDate = NSDate()
calendar = NSCalendar.currentCalendar()
components = calendar.components(MonthUnit.union(DayUnit), fromDate: currentDate)
starterWeekday = calendarView.firstWeekday.rawValue
calendar.firstWeekday = starterWeekday
}
// MARK: - Common date analysis
public func monthDateRange(date: NSDate) -> (countOfWeeks: NSInteger, monthStartDate: NSDate, monthEndDate: NSDate) {
let units = (YearUnit.union(MonthUnit).union(WeekUnit))
let components = calendar.components(units, fromDate: date)
// Start of the month.
components.day = 1
let monthStartDate = calendar.dateFromComponents(components)!
// End of the month.
components.month += 1
components.day -= 1
let monthEndDate = calendar.dateFromComponents(components)!
// Range of the month.
let range = calendar.rangeOfUnit(WeekUnit, inUnit: MonthUnit, forDate: date)
let countOfWeeks = range.length
return (countOfWeeks, monthStartDate, monthEndDate)
}
public static func dateRange(date: NSDate) -> (year: Int, month: Int, weekOfMonth: Int, day: Int) {
let components = componentsForDate(date)
let year = components.year
let month = components.month
let weekOfMonth = components.weekOfMonth
let day = components.day
return (year, month, weekOfMonth, day)
}
public func weekdayForDate(date: NSDate) -> Int {
let units = WeekdayUnit
let components = calendar.components(units, fromDate: date)
//println("NSDate: \(date), Weekday: \(components.weekday)")
// let weekday = calendar.ordinalityOfUnit(units, inUnit: WeekUnit, forDate: date)
return Int(components.weekday)
}
// MARK: - Analysis sorting
public func weeksWithWeekdaysForMonthDate(date: NSDate) -> (weeksIn: [[Int : [Int]]], weeksOut: [[Int : [Int]]]) {
let countOfWeeks = self.monthDateRange(date).countOfWeeks
let totalCountOfDays = countOfWeeks * 7
let firstMonthDateIn = self.monthDateRange(date).monthStartDate
let lastMonthDateIn = self.monthDateRange(date).monthEndDate
let countOfDaysIn = Manager.dateRange(lastMonthDateIn).day
let countOfDaysOut = totalCountOfDays - countOfDaysIn
// Find all dates in.
var datesIn = [NSDate]()
for day in 1...countOfDaysIn {
let components = Manager.componentsForDate(firstMonthDateIn)
components.day = day
let date = calendar.dateFromComponents(components)!
datesIn.append(date)
}
// Find all dates out.
let firstMonthDateOut: NSDate? = {
let firstMonthDateInWeekday = self.weekdayForDate(firstMonthDateIn)
if firstMonthDateInWeekday == self.starterWeekday {
return firstMonthDateIn
}
let components = Manager.componentsForDate(firstMonthDateIn)
for _ in 1...7 {
components.day -= 1
let updatedDate = self.calendar.dateFromComponents(components)!
updatedDate
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
let diff = 7 - firstMonthDateInWeekday
for _ in diff..<7 {
components.day += 1
let updatedDate = self.calendar.dateFromComponents(components)!
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
return nil
}()
// Constructing weeks.
var firstWeekDates = [NSDate]()
var lastWeekDates = [NSDate]()
var firstWeekDate = (firstMonthDateOut != nil) ? firstMonthDateOut! : firstMonthDateIn
let components = Manager.componentsForDate(firstWeekDate)
components.day += 6
var lastWeekDate = calendar.dateFromComponents(components)!
func nextWeekDateFromDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
components.day += 7
let nextWeekDate = calendar.dateFromComponents(components)!
return nextWeekDate
}
for weekIndex in 1...countOfWeeks {
firstWeekDates.append(firstWeekDate)
lastWeekDates.append(lastWeekDate)
firstWeekDate = nextWeekDateFromDate(firstWeekDate)
lastWeekDate = nextWeekDateFromDate(lastWeekDate)
}
// Dictionaries.
var weeksIn = [[Int : [Int]]]()
var weeksOut = [[Int : [Int]]]()
let count = firstWeekDates.count
for i in 0..<count {
var weekdaysIn = [Int : [Int]]()
var weekdaysOut = [Int : [Int]]()
let firstWeekDate = firstWeekDates[i]
let lastWeekDate = lastWeekDates[i]
let components = Manager.componentsForDate(firstWeekDate)
for weekday in 1...7 {
let weekdate = calendar.dateFromComponents(components)!
components.day += 1
let day = Manager.dateRange(weekdate).day
func addDay(inout weekdays: [Int : [Int]]) {
var days = weekdays[weekday]
if days == nil {
days = [Int]()
}
days!.append(day)
weekdays.updateValue(days!, forKey: weekday)
}
if i == 0 && day > 20 {
addDay(&weekdaysOut)
} else if i == countOfWeeks - 1 && day < 10 {
addDay(&weekdaysOut)
} else {
addDay(&weekdaysIn)
}
}
if weekdaysIn.count > 0 {
weeksIn.append(weekdaysIn)
}
if weekdaysOut.count > 0 {
weeksOut.append(weekdaysOut)
}
}
return (weeksIn, weeksOut)
}
// MARK: - Util methods
public static func componentsForDate(date: NSDate) -> NSDateComponents {
let units = YearUnit.union(MonthUnit).union(WeekUnit).union(DayUnit)
let components = NSCalendar.currentCalendar().components(units, fromDate: date)
return components
}
public static func dateFromYear(year: Int, month: Int, week: Int, day: Int) -> NSDate? {
let comps = Manager.componentsForDate(NSDate())
comps.year = year
comps.month = month
comps.weekOfMonth = week
comps.day = day
return NSCalendar.currentCalendar().dateFromComponents(comps)
}
} | mit | 22bcddb6751f217f9e99350ba641a8d9 | 34.109244 | 121 | 0.571275 | 5.464356 | false | false | false | false |
fakerabbit/LucasBot | LucasBot/Utils.swift | 1 | 3441 | //
// Utils.swift
// LucasBot
//
// Created by Mirko Justiniano on 1/9/17.
// Copyright © 2017 LB. All rights reserved.
//
import Foundation
import UIKit
struct Utils {
/*
* MARK:- FONTS
*/
/*
** Avenir
Avenir-Medium
Avenir-HeavyOblique
Avenir-Book
Avenir-Light
Avenir-Roman
Avenir-BookOblique
Avenir-MediumOblique
Avenir-Black
Avenir-BlackOblique
Avenir-Heavy
Avenir-LightOblique
Avenir-Oblique
** San Francisco Display
SanFranciscoDisplay-Regular
SanFranciscoDisplay-Medium
SanFranciscoDisplay-Bold
*/
static func printFontNamesInSystem() {
for family in UIFont.familyNames {
print("*", family);
for name in UIFont.fontNames(forFamilyName: family ) {
print(name);
}
}
}
static func chatFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Regular", size: 18.0)!
}
static func LucasFont() -> UIFont {
return UIFont(name: "Avenir-Roman", size: 50.0)!
}
static func BotFont() -> UIFont {
return UIFont(name: "Avenir-Roman", size: 50.0)!
}
static func buttonFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Medium", size: 18.0)!
}
static func boldFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Bold", size: 18.0)!
}
/*
* MARK:- COLORS
*/
static func backgroundColor() -> UIColor {
return UIColor(colorLiteralRed: 209/255, green: 225/255, blue: 232/255, alpha: 1.0)
}
static func darkBackgroundColor() -> UIColor {
return UIColor(colorLiteralRed: 122/255, green: 178/255, blue: 206/255, alpha: 1.0)
}
static func lucasColor() -> UIColor {
return UIColor(colorLiteralRed: 209/255, green: 225/255, blue: 232/255, alpha: 1.0)
}
static func botColor() -> UIColor {
return UIColor(colorLiteralRed: 46/255, green: 62/255, blue: 70/255, alpha: 1.0)
}
static func chatBotColor() -> UIColor {
return UIColor.white
}
static func chatUserColor() -> UIColor {
return UIColor(colorLiteralRed: 47/255, green: 62/255, blue: 70/255, alpha: 1.0)
}
static func redColor() -> UIColor {
return UIColor(colorLiteralRed: 237/255, green: 20/255, blue: 91/255, alpha: 1.0)
}
static func botBubbleColor() -> UIColor {
return UIColor(colorLiteralRed: 177/255, green: 203/255, blue: 70/255, alpha: 1.0)
}
static func userBubbleColor() -> UIColor {
return UIColor.white
}
static func greenColor() -> UIColor {
return UIColor(colorLiteralRed: 177/255, green: 203/255, blue: 70/255, alpha: 1.0)
}
static func lineColor() -> UIColor {
return UIColor(colorLiteralRed: 227/255, green: 229/255, blue: 230/255, alpha: 1.0)
}
/*
* MARK:- IMAGES
*/
static let kDefaultGif:String = "wave-chat"
static let kSandwich:String = "sandwich"
static let kPopBg:String = "popBg"
/*
* MARK:- VALUES
*/
static var interBubbleSpace: CGFloat = 20.00
static var menuItemHeight = "40"
static var menuItemWidth = "200"
static var galleryItemHeight = "200"
static var galleryItemWidth = "200"
}
| gpl-3.0 | f33cf320781e30fe589a3c1add18b543 | 24.671642 | 91 | 0.587209 | 4.134615 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift | 1 | 2148 | /**
* Copyright IBM Corporation 2018
*
* 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
/** SpeakerLabelsResult. */
public struct SpeakerLabelsResult: Decodable {
/// The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array.
public var from: Double
/// The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array.
public var to: Double
/// The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered.
public var speaker: Int
/// A score that indicates the service's confidence in its identification of the speaker in the range of 0 to 1.
public var confidence: Double
/// An indication of whether the service might further change word and speaker-label results. A value of `true` means that the service guarantees not to send any further updates for the current or any preceding results; `false` means that the service might send further updates to the results.
public var finalResults: Bool
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case from = "from"
case to = "to"
case speaker = "speaker"
case confidence = "confidence"
case finalResults = "final"
}
}
| mit | db6e1d818b2128694500c669951d47f6 | 45.695652 | 337 | 0.731844 | 4.639309 | false | false | false | false |
MastodonKit/MastodonKit | Tests/MastodonKitTests/Foundation/URLComponentsTests.swift | 1 | 1519 | //
// URLComponentsTests.swift
// MastodonKit
//
// Created by Ornithologist Coder on 4/22/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import XCTest
@testable import MastodonKit
class URLComponentsTests: XCTestCase {
func testURLComponentsWithValidBaseURL() {
let request = Request<String>(path: "/string")
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertEqual(components?.url, URL(string: "https://mastodon.technology/string"))
}
func testURLComponentsWithInvalidBaseURL() {
let request = Request<String>(path: "/string")
let components = URLComponents(baseURL: "this is an invalid base url", request: request)
XCTAssertNil(components)
}
func testURLComponentsWithInValidRequestPath() {
let request = Request<String>(path: "invalid endpoint")
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertNil(components)
}
func testURLComponentsWithBaseURLAndQueryItems() {
let parameters = [
Parameter(name: "a", value: "0"),
Parameter(name: "b", value: "1")
]
let request = Request<String>(path: "/string", method: .get(.parameters(parameters)))
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertEqual(components?.url, URL(string: "https://mastodon.technology/string?a=0&b=1"))
}
}
| mit | 7bbea5fc1518554120fca3e50b9582f7 | 32.733333 | 98 | 0.673913 | 4.531343 | false | true | false | false |
rtoal/ple | swift/anagrams.swift | 2 | 561 | import Foundation
func generatePermutations(of a: inout [Character], upTo n: Int) {
if n == 0 {
print(String(a))
} else {
for i in 0..<n {
generatePermutations(of: &a, upTo: n-1)
a.swapAt(n % 2 == 0 ? 0 : i, n)
}
generatePermutations(of: &a, upTo: n-1)
}
}
if CommandLine.arguments.count != 2 {
fputs("Exactly one argument is required\n", stderr)
exit(1)
}
let word = CommandLine.arguments[1]
var charArray = Array(word)
generatePermutations(of: &charArray, upTo: charArray.count-1)
| mit | 5d43594d82554dd3eb4d4872eb81cb35 | 25.714286 | 65 | 0.59893 | 3.379518 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisXLowLayerDefault.swift | 6 | 1111 | //
// ChartAxisXLowLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisXLowLayerDefault: ChartAxisXLayerDefault {
override var low: Bool {return true}
override var lineP1: CGPoint {
return self.p1
}
override var lineP2: CGPoint {
return self.p2
}
override func chartViewDrawing(context context: CGContextRef, chart: Chart) {
super.chartViewDrawing(context: context, chart: chart)
}
override func initDrawers() {
self.lineDrawer = self.generateLineDrawer(offset: 0)
let labelsOffset = (self.settings.axisStrokeWidth / 2) + self.settings.labelsToAxisSpacingX
let labelDrawers = self.generateLabelDrawers(offset: labelsOffset)
let definitionLabelsOffset = labelsOffset + self.labelsTotalHeight + self.settings.axisTitleLabelsToLabelsSpacing
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: definitionLabelsOffset)
self.labelDrawers = labelDrawers
}
}
| mit | cae17a53b467d4e29ac2c24075c745fc | 30.742857 | 121 | 0.713771 | 4.707627 | false | false | false | false |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Helper/Alert.swift | 1 | 2124 | //
// Alert.swift
// Cap
//
// Created by Pantera Engineering on 20/12/2016.
// Copyright © 2016 Incubasys IT Solutions. All rights reserved.
//
import UIKit
public class Alert{
static public func showMessage(viewController:UIViewController?,title:String? = nil,msg:String? = nil,actions:[UIAlertAction]? = nil,showOnlyDismissBtn:Bool=true, dismissBtnTitle: String) {
guard viewController != nil else {
return
}
let alert = createAlert(viewController:viewController,title:title,msg:msg,actions:actions,showOnlyDismissBtn:showOnlyDismissBtn,dismissBtnTitle:dismissBtnTitle)
viewController!.present(alert, animated: true, completion: nil)
}//showError
static func createAlert(viewController:UIViewController?,title:String? = nil,msg:String? = nil,actions:[UIAlertAction]? = nil,showOnlyDismissBtn:Bool=true, dismissBtnTitle: String) -> UIAlertController {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
//dismiss button check
if showOnlyDismissBtn {
let actionDismiss = UIAlertAction(title: dismissBtnTitle, style: .cancel, handler: nil)
alert.addAction(actionDismiss)
return alert
}
if actions != nil{
for action in actions!{
alert.addAction(action)
}
}//if
return alert
}
static public func showImagePickerAlert(viewController:UIViewController,actionPhotoLibrary:UIAlertAction,actionCamera:UIAlertAction,actionRemove:UIAlertAction? = nil, cancelTitle: String, title: String) {
let actionCancel = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil)
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
alert.addAction(actionCancel)
alert.addAction(actionCamera)
alert.addAction(actionPhotoLibrary)
if actionRemove != nil{
alert.addAction(actionRemove!)
}
viewController.present(alert, animated: true, completion: nil)
}
}
| mit | d15c3275e1262ebb05371056d3d68587 | 39.056604 | 207 | 0.679699 | 4.717778 | false | false | false | false |
studyYF/YueShiJia | YueShiJia/YueShiJia/Classes/Main/YFNavigationController.swift | 1 | 1369 | //
// YFNavigationController.swift
// YueShiJia
//
// Created by YangFan on 2017/5/10.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFNavigationController: UINavigationController {
//MARK: 定义属性
//MARK: 生命周期函数
override func viewDidLoad() {
super.viewDidLoad()
// navigationBar.isTranslucent = false
// navigationBar.setBackgroundImage(UIImage.imageWithColor(color: UIColor.white), for: .default)
navigationBar.barTintColor = UIColor.white
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
navigationItem.hidesBackButton = true
if viewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.setImage(UIImage(named: "nav_return_normal"), for: .normal)
button.addTarget(self, action: #selector(YFNavigationController.back), for: .touchUpInside)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
super.pushViewController(viewController, animated: animated)
}
@objc private func back() {
popViewController(animated: true)
}
}
| apache-2.0 | 0b4e867abc05e71e54a05304f60baf66 | 29.590909 | 103 | 0.667162 | 4.841727 | false | false | false | false |
arvedviehweger/swift | test/decl/ext/protocol.swift | 1 | 22275 | // RUN: %target-typecheck-verify-swift
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
func extP1a() -> Bool { return !reqP1a() }
var extP1b: Bool {
return self.reqP1a()
}
var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
func extP2a() -> AssocP2? { return reqP2a() }
func extP2b() {
self.reqP2a().reqP1a()
}
func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
func extP2acceptsP1() { acceptsP1(reqP2a()) }
func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T {
return t
}
extension SelfP1 {
func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
func extP4a() { // expected-note 2 {{found this candidate}}
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int {
func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
func extP4a() -> Bool { return reqP4a() } // expected-note 2 {{found this candidate}}
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{'Bool' is not convertible to 'Int'}}
_ = b1
}
// ----------------------------------------------------------------------------
// Protocol extensions with a superclass constraint on Self
// ----------------------------------------------------------------------------
protocol ConformedProtocol {
typealias ConcreteConformanceAlias = Self
}
class BaseWithAlias<T> : ConformedProtocol {
typealias ConcreteAlias = T
func baseMethod(_: T) {}
}
class DerivedWithAlias : BaseWithAlias<Int> {}
protocol ExtendedProtocol {
typealias AbstractConformanceAlias = Self
}
extension ExtendedProtocol where Self : DerivedWithAlias {
func f0(x: T) {} // expected-error {{use of undeclared type 'T'}}
func f1(x: ConcreteAlias) {
let _: Int = x
baseMethod(x)
}
func f2(x: ConcreteConformanceAlias) {
let _: DerivedWithAlias = x
}
func f3(x: AbstractConformanceAlias) {
let _: DerivedWithAlias = x
}
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
func method() { }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
func method() -> Int { return 5 }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" }
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
func method() -> Self.Assoc { return Assoc() }
var property: Self.Assoc { return Assoc() }
subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
func order1() -> Int { return 0 }
}
extension PInherit2 {
func order1() -> Bool { return true }
}
extension PInherit3 {
func order1() -> Double { return 1.0 }
}
extension PInherit4 {
func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
func pc2() -> Bool { return true }
}
extension PConstrained3 {
func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
var prop1: Int { return 0 }
var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
subscript (key: Int) -> Int { return key }
subscript (key: Double) -> Double { return key } // expected-note{{'subscript' previously declared here}}
}
extension PConstrained6 {
var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop1: Int { return 0 } // okay
var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
subscript (key: Int) -> Int { return key } // ok
subscript (key: String) -> String { return key } // expected-note{{'subscript' previously declared here}}
func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript'}}
func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
var prop1: Int { return 0 } // okay
subscript (key: Int) -> Int { return key } // okay
func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
var prop4: Int { return 0 }
subscript (key: Character) -> Character { return key }
func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
var prop4: Int { return 0 } // okay
subscript (key: Character) -> Character { return key } // okay
func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}}
class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}}
enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // expected-error{{protocol 'BadProto3' in the module being compiled cannot be extended via a type alias}}{{11-20=BadProto3}}
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{'AnyObject' protocol cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
protocol BadProto5 {
associatedtype T1 // expected-note{{protocol requires nested type 'T1'}}
associatedtype T2 // expected-note{{protocol requires nested type 'T2'}}
associatedtype T3 // expected-note{{protocol requires nested type 'T3'}}
}
class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}}
typealias A = BadProto1
typealias B = BadProto1
extension A & B { // expected-error{{protocol 'BadProto1' in the module being compiled cannot be extended via a type alias}}
}
| apache-2.0 | fabd0ceffca3cb684d079faefdf24d52 | 22.373557 | 200 | 0.623165 | 3.686693 | false | false | false | false |
CoderLala/DouYZBTest | DouYZB/DouYZB/Classes/Home/Controller/RecommendViewController.swift | 1 | 6127 | //
// RecommendViewController.swift
// DouYZB
//
// Created by 黄金英 on 17/2/4.
// Copyright © 2017年 黄金英. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenWidth - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kCycleViewH = kScreenWidth * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var recommendVM = RecommendViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -kCycleViewH - kGameViewH, width: kScreenWidth, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenWidth, height: kGameViewH)
return gameView
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
// layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: kHeaderViewH)
//2.创建UICollectionVi
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
//MARK:- 系统回调函数
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
super.viewDidLoad()
//1. 设置UI界面
setupUI()
//2. 请求数据
loadData()
}
}
//MARK:- 请求数据
extension RecommendViewController {
fileprivate func loadData() {
//请求推荐数据
recommendVM.requestData {
self.collectionView.reloadData()
//将数据传递给gameView
self.gameView.groups = self.recommendVM.anchorGroups
}
//请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModel
}
}
}
//MARK:- 设置UI界面
extension RecommendViewController {
fileprivate func setupUI(){
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0)
}
}
//MARK:- 遵守UICollectionViewDataSource
extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//0. 取出模型
let group = recommendVM.anchorGroups[indexPath.section]
let anchors = group.anchors[indexPath.item]
//1. 定义cell
var cell : CollectionBaseCell!
//2. 取出cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
}
else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
}
//3. 将模型赋值给cell
cell.anchor = anchors
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1. 取出sectionHeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! HomeCollectionHeaderView
//2. 取出模型
headerView.group = recommendVM.anchorGroups[indexPath.section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
| mit | f4c3ebfba61d97f5dc0f5e0f666fe0e4 | 31.183784 | 190 | 0.663252 | 5.98392 | false | false | false | false |
mightydeveloper/swift | test/Constraints/dictionary_literal.swift | 10 | 2741 | // RUN: %target-parse-verify-swift
final class DictStringInt : DictionaryLiteralConvertible {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class Dictionary<K, V> : DictionaryLiteralConvertible {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(d: DictStringInt) {}
func useDict<K, V>(d: Dictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt([ "Hello" : 1 ])
useDictStringInt([ "Hello" : 1, "World" : 2])
useDictStringInt([ "Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
useDictStringInt([ 4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}}
useDictStringInt([ nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}}
useDictStringInt([ 7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [ 1 : 2, 1.5 : 2.5 ]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' (aka 'Dictionary<String, Int -> Int>') cannot be used with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}}
var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}}
var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
| apache-2.0 | 154fee28e8f7465752c573e50e270de2 | 43.934426 | 191 | 0.671653 | 3.536774 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CloudWatchLogs/CloudWatchLogs_Error.swift | 1 | 4318 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for CloudWatchLogs
public struct CloudWatchLogsErrorType: AWSErrorType {
enum Code: String {
case dataAlreadyAcceptedException = "DataAlreadyAcceptedException"
case invalidOperationException = "InvalidOperationException"
case invalidParameterException = "InvalidParameterException"
case invalidSequenceTokenException = "InvalidSequenceTokenException"
case limitExceededException = "LimitExceededException"
case malformedQueryException = "MalformedQueryException"
case operationAbortedException = "OperationAbortedException"
case resourceAlreadyExistsException = "ResourceAlreadyExistsException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case unrecognizedClientException = "UnrecognizedClientException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize CloudWatchLogs
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The event was already logged.
public static var dataAlreadyAcceptedException: Self { .init(.dataAlreadyAcceptedException) }
/// The operation is not valid on the specified resource.
public static var invalidOperationException: Self { .init(.invalidOperationException) }
/// A parameter is specified incorrectly.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// The sequence token is not valid. You can get the correct sequence token in the expectedSequenceToken field in the InvalidSequenceTokenException message.
public static var invalidSequenceTokenException: Self { .init(.invalidSequenceTokenException) }
/// You have reached the maximum number of resources that can be created.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The query string is not valid. Details about this error are displayed in a QueryCompileError object. For more information, see QueryCompileError. For more information about valid query syntax, see CloudWatch Logs Insights Query Syntax.
public static var malformedQueryException: Self { .init(.malformedQueryException) }
/// Multiple requests to update the same resource were in conflict.
public static var operationAbortedException: Self { .init(.operationAbortedException) }
/// The specified resource already exists.
public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) }
/// The specified resource does not exist.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The service cannot complete the request.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The most likely cause is an invalid AWS access key ID or secret key.
public static var unrecognizedClientException: Self { .init(.unrecognizedClientException) }
}
extension CloudWatchLogsErrorType: Equatable {
public static func == (lhs: CloudWatchLogsErrorType, rhs: CloudWatchLogsErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension CloudWatchLogsErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | bbd0bf122b9d112edec0d64a21e77ea9 | 48.632184 | 243 | 0.720241 | 5.507653 | false | false | false | false |
qingcai518/MenuReader | MenuReader/ResultController.swift | 1 | 9217 | //
// ResultController.swift
// MenuReader
//
// Created by RN-079 on 2017/01/04.
// Copyright © 2017年 RN-079. All rights reserved.
//
import UIKit
import RxSwift
class ResultController: ViewController {
@IBOutlet weak var tableView1 : UITableView!
@IBOutlet weak var tableView2 : UITableView!
@IBOutlet weak var indicator: UIActivityIndicatorView!
@IBOutlet weak var selectBtn: UIButton!
var bottomView = UIView()
var translatePartBtn = UIButton()
var translateAllBtn = UIButton()
let model = ResultModel()
let bottomHeight = CGFloat(118)
var results = [ResultInfo]()
var sources = [Int: String]()
var isSelectable = Variable(false)
var isTranslateAll = false
// params.
var image : UIImage!
@IBAction func doSelect() {
isSelectable.value = !isSelectable.value
if (!isSelectable.value) {
for result in results {
result.isSelected.value = false
}
hideBottomView()
} else {
// 選択ボタンが押下されたら、sourcesの内容をクリアする.
sources.removeAll()
showBottomView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
setBottomView()
// データを取得する.
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func getData() {
indicator.startAnimating()
model.createRequest(image: image)
}
private func setTableView() {
tableView1.tableFooterView = UIView()
tableView1.delegate = self
tableView1.dataSource = self
tableView2.tableFooterView = UIView()
tableView2.delegate = self
tableView2.dataSource = self
model.delegate = self
}
private func setBottomView() {
bottomView.frame = CGRect(x: 0, y : screenHeight, width: screenWidth, height : bottomHeight)
bottomView.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.view.addSubview(bottomView)
translatePartBtn.frame = CGRect(x: 30, y: 12, width: screenWidth - 2 * 30, height: 40)
translatePartBtn.rx.tap.asObservable().bindNext { [weak self] in
self?.isTranslateAll = false
self?.performSegue(withIdentifier: "ToTranslate", sender: nil)
}.addDisposableTo(disposeBag)
translatePartBtn.setBackgroundImage(UIImage(named: "btn_light_blue"), for: .normal)
translatePartBtn.setTitle("選択したレコードを翻訳", for: .normal)
translatePartBtn.setTitleColor(UIColor.white, for: .normal)
translatePartBtn.titleLabel?.font = UIFont.HelveticaBold16()
translatePartBtn.isEnabled = false
bottomView.addSubview(translatePartBtn)
translateAllBtn.frame = CGRect(x: 30, y: 64, width: screenWidth - 2 * 30, height: 40)
translateAllBtn.rx.tap.asObservable().bindNext { [unowned self] in
self.isTranslateAll = true
self.performSegue(withIdentifier: "ToTranslate", sender: nil)
}.addDisposableTo(disposeBag)
translateAllBtn.setBackgroundImage(UIImage(named: "btn_light_blue"), for: .normal)
translateAllBtn.setTitle("全件翻訳", for: .normal)
translateAllBtn.setTitleColor(UIColor.white, for: .normal)
translateAllBtn.titleLabel?.font = UIFont.HelveticaBold16()
bottomView.addSubview(translateAllBtn)
}
func showBottomView() {
UIView.animate(withDuration: 0.5, animations: { [unowned self] in
self.bottomView.frame = CGRect(x: 0, y: screenHeight - self.bottomHeight, width: screenWidth, height: self.bottomHeight)
}) { isFinished in
}
}
func hideBottomView() {
UIView.animate(withDuration: 0.5, animations: { [unowned self] in
self.bottomView.frame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: self.bottomHeight)
}) { isFinished in
}
}
}
extension ResultController : ResultModelDelegate {
func complete(result: String?) {
indicator.stopAnimating()
guard let contentArray = result?.components(separatedBy: "\n") else {return}
for content in contentArray {
if (content.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "") {
continue
}
let info = ResultInfo(result: content)
results.append(info)
}
print("results = \(results)")
tableView1.reloadData()
}
func failed(error: NSError) {
indicator.stopAnimating()
print("error = \(error.localizedDescription)")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ToTranslate") {
guard let next = segue.destination as? TranslateController else {return}
if (isTranslateAll) {
for result in results {
next.sources.append(result.result)
}
} else {
for (_, value) in sources {
next.sources.append(value)
}
}
}
}
}
extension ResultController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (tableView === tableView1) {
let info = results[indexPath.row]
if (isSelectable.value) {
info.isSelected.value = !info.isSelected.value
if (info.isSelected.value) {
sources[indexPath.row] = info.result
} else {
sources.removeValue(forKey: indexPath.row)
}
var flag = false
for result in results {
if (result.isSelected.value) {
flag = true
break
}
}
self.translatePartBtn.isEnabled = flag
} else {
isTranslateAll = false
let info = results[indexPath.row]
sources.removeAll()
sources[indexPath.row] = info.result
performSegue(withIdentifier: "ToTranslate", sender: nil)
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (tableView === tableView1) {
return 44
} else {
let width = screenWidth - 2 * 12
let height = (width / image.size.width ) * image.size.height
return height + 12
}
}
}
extension ResultController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView === tableView1) {
return results.count
} else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == tableView1) {
let info = results[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as! ResultCell
cell.resultTf.text = info.result
cell.editBtn.rx.tap.asObservable().bindNext { [weak self] in
if (cell.editBtn.currentImage == UIImage(named: "ok_green")) {
cell.editBtn.setImage(UIImage(named: "edit"), for: .normal)
self?.results[indexPath.row].result = cell.resultTf.text!
cell.resultTf.isEnabled = false
} else {
cell.editBtn.setImage(UIImage(named: "ok_green"), for: .normal)
cell.resultTf.isEnabled = true
cell.resultTf.becomeFirstResponder()
}
}.addDisposableTo(cell.disposeBag)
info.isSelected.asDriver().drive(onNext: { value in
cell.checkboxView.image = value ? UIImage(named: "checkbox") : UIImage(named: "checkbox_uncheck")
}, onCompleted: nil, onDisposed: nil).addDisposableTo(cell.disposeBag)
isSelectable.asDriver().drive(onNext: { [weak self] value in
self?.selectBtn.setTitle(value ? "キャンセル" : "選択", for: .normal)
cell.checkboxView.isHidden = !value
}, onCompleted: nil, onDisposed: nil).addDisposableTo(cell.disposeBag)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.pictureView.image = self.image
return cell
}
}
}
| mit | c6c8ce5da28930e93944873050dcd9e0 | 34.585938 | 132 | 0.57629 | 5.03037 | false | false | false | false |
rhx/SwiftGObject | Sources/GLibObject/GLibType.swift | 1 | 4456 | //
// GLibType.swift
// GLibObject
//
// Created by Rene Hexel on 17/4/17.
// Copyright © 2017, 2018, 2020 Rene Hexel. All rights reserved.
//
import CGLib
import GLib
//
// Unfortunately, the G_TYPE_* macros are not imported into Swift
// Therefore, rewe create them manually here
//
public extension GType {
static let invalid = GType( 0 << TYPE_FUNDAMENTAL_SHIFT)
static let none = GType( 1 << TYPE_FUNDAMENTAL_SHIFT)
static let interface = GType( 2 << TYPE_FUNDAMENTAL_SHIFT)
static let char = GType( 3 << TYPE_FUNDAMENTAL_SHIFT)
static let uchar = GType( 4 << TYPE_FUNDAMENTAL_SHIFT)
static let boolean = GType( 5 << TYPE_FUNDAMENTAL_SHIFT)
static let int = GType( 6 << TYPE_FUNDAMENTAL_SHIFT)
static let uint = GType( 7 << TYPE_FUNDAMENTAL_SHIFT)
static let long = GType( 8 << TYPE_FUNDAMENTAL_SHIFT)
static let ulong = GType( 9 << TYPE_FUNDAMENTAL_SHIFT)
static let int64 = GType(10 << TYPE_FUNDAMENTAL_SHIFT)
static let uint64 = GType(11 << TYPE_FUNDAMENTAL_SHIFT)
static let `enum` = GType(12 << TYPE_FUNDAMENTAL_SHIFT)
static let flags = GType(13 << TYPE_FUNDAMENTAL_SHIFT)
static let float = GType(14 << TYPE_FUNDAMENTAL_SHIFT)
static let double = GType(15 << TYPE_FUNDAMENTAL_SHIFT)
static let string = GType(16 << TYPE_FUNDAMENTAL_SHIFT)
static let pointer = GType(17 << TYPE_FUNDAMENTAL_SHIFT)
static let boxed = GType(18 << TYPE_FUNDAMENTAL_SHIFT)
static let param = GType(19 << TYPE_FUNDAMENTAL_SHIFT)
static let object = GType(20 << TYPE_FUNDAMENTAL_SHIFT)
static let variant = GType(21 << TYPE_FUNDAMENTAL_SHIFT)
static let max = GType(TYPE_FUNDAMENTAL_MAX)
}
public extension GType {
@inlinable func test(flags: TypeFundamentalFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
@inlinable func test(flags: TypeFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
/// Return the fundamental type which is the ancestor of `self`.
@inlinable var fundamental: GType { return g_type_fundamental(self) }
/// Return `true` iff `self` is a fundamental type.
@inlinable var isFundamental: Bool { return self <= GType.max }
/// Return `true` iff `self` is a derived type.
@inlinable var isDerived: Bool { return !self.isFundamental }
/// Return `true` iff `self` is an interface type.
@inlinable var isInterface: Bool { return self.fundamental == .interface }
/// Return `true` iff `self` is a classed type.
@inlinable var isClassed: Bool { return test(flags: .classed) }
/// Return `true` iff `self` is a derivable type.
@inlinable var isDerivable: Bool { return test(flags: .derivable) }
/// Return `true` iff `self` is a deep derivable type.
@inlinable var isDeepDerivable: Bool { return test(flags: .deepDerivable) }
/// Return `true` iff `self` is an instantiatable type.
@inlinable var isInstantiable: Bool { return test(flags: .instantiatable) }
/// Return `true` iff `self` is an abstract type.
@inlinable var isAbstract: Bool { return test(flags: .abstract) }
/// Return `true` iff `self` is an abstract value type.
@inlinable var isAbstractValue: Bool { return test(flags: .valueAbstract) }
/// Return `true` iff `self` is a value type.
@inlinable var isValueType: Bool { return g_type_check_is_value_type(self) != 0 }
/// Return `true` iff `self` has a value table.
@inlinable var hasValueTable: Bool { return g_type_value_table_peek(self) != nil }
/// Return `true` iff `a` is transformable into `b`
@inlinable static func transformable(from a: GType, to b: GType) -> Bool {
return g_value_type_transformable(a, b) != 0
}
}
//fileprivate struct _GTypeClass { let g_type: GType }
//fileprivate struct _GTypeInstance { let g_class: UnsafeMutablePointer<_GTypeClass>? }
/// Convenience extensions for Object types
public extension ObjectProtocol {
/// Underlying type
@inlinable var type: GType {
let typeInstance = ptr.assumingMemoryBound(to: Optional<UnsafeMutablePointer<GType>>.self)
guard let cls = typeInstance.pointee else { return .invalid }
return cls.pointee
}
/// Name of the underlying type
@inlinable var typeName: String {
return String(cString: g_type_name(type))
}
}
| bsd-2-clause | 5dade075d242f8fe9d76bd41fef35a77 | 46.393617 | 98 | 0.662402 | 3.807692 | false | true | false | false |
kesun421/firefox-ios | Client/Frontend/Widgets/ChevronView.swift | 3 | 4414 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
enum ChevronDirection {
case left
case up
case right
case down
}
enum ChevronStyle {
case angular
case rounded
}
class ChevronView: UIView {
fileprivate let Padding: CGFloat = 2.5
fileprivate var direction = ChevronDirection.right
fileprivate var lineCapStyle = CGLineCap.round
fileprivate var lineJoinStyle = CGLineJoin.round
var lineWidth: CGFloat = 3.0
var style: ChevronStyle = .rounded {
didSet {
switch style {
case .rounded:
lineCapStyle = CGLineCap.round
lineJoinStyle = CGLineJoin.round
case .angular:
lineCapStyle = CGLineCap.butt
lineJoinStyle = CGLineJoin.miter
}
}
}
init(direction: ChevronDirection) {
super.init(frame: CGRect.zero)
self.direction = direction
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
if direction == .left {
self.direction = .right
} else if direction == .right {
self.direction = .left
}
}
self.backgroundColor = UIColor.clear
self.contentMode = UIViewContentMode.redraw
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let strokeLength = (rect.size.height / 2) - Padding
let path: UIBezierPath
switch direction {
case .left:
path = drawLeftChevronAt(CGPoint(x: rect.size.width - (strokeLength + Padding), y: strokeLength + Padding), strokeLength: strokeLength)
case .up:
path = drawUpChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength / 2) + Padding), strokeLength: strokeLength)
case .right:
path = drawRightChevronAt(CGPoint(x: rect.size.width - Padding, y: strokeLength + Padding), strokeLength: strokeLength)
case .down:
path = drawDownChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength * 1.5) + Padding), strokeLength: strokeLength)
}
tintColor.set()
// The line thickness needs to be proportional to the distance from the arrow head to the tips. Making it half seems about right.
path.lineCapStyle = lineCapStyle
path.lineJoinStyle = lineJoinStyle
path.lineWidth = lineWidth
path.stroke()
}
fileprivate func drawUpChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength))
}
fileprivate func drawDownChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength))
}
fileprivate func drawLeftChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength))
}
fileprivate func drawRightChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength))
}
fileprivate func drawChevron(_ leftTip: CGPoint, head: CGPoint, rightTip: CGPoint) -> UIBezierPath {
let path = UIBezierPath()
// Left tip
path.move(to: leftTip)
// Arrow head
path.addLine(to: head)
// Right tip
path.addLine(to: rightTip)
return path
}
}
| mpl-2.0 | 4921afa5d407e2bdd593f48dcdb82bda | 34.886179 | 155 | 0.633439 | 4.536485 | false | false | false | false |
iandd0824/ri-ios | dsm5/MasterViewController.swift | 1 | 10948 | //
// MasterViewController.swift
// dsm5
//
// Created by Djanny on 10/5/15.
// Copyright © 2015 ptsd.ri.ucla. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
//let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
//self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
@IBAction func tapCreateClient(sender: AnyObject) {
/*let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
do {
try context.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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}*/
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
do {
try context.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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
print(object)
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
do {
try context.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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
if(editingStyle == .Delete) {
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
//cell.textLabel!.text = object.valueForKey("timeStamp")!.description
cell.textLabel!.text = object.valueForKey("name")!.description
cell.detailTextLabel!.text = object.valueForKey("id")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
//let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
let entity = NSEntityDescription.entityForName("Client", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
//let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
//let predicate = NSPredicate(format: "name == %@", "bbb")
// Set the predicate on the fetch request
//fetchRequest.predicate = predicate
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} 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.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit | 386078aff77ff1dd5d01f5da7198f2c4 | 44.803347 | 360 | 0.679456 | 6.195246 | false | false | false | false |
miracle-as/BasicComponents | BasicComponents/UIViewController+Alert.swift | 1 | 3231 | //
// UIViewController+Alert.swift
// Metronome
//
// Created by Lasse Løvdahl on 05/02/2016.
// Copyright © 2016 Miracle A/S. All rights reserved.
//
import Foundation
import UIKit
import Whisper
import DynamicColor
public func statusBarNotify(_ message: String, color: UIColor = .clear) {
let murmur = Murmur(title: message, backgroundColor: color, titleColor: color.isLight() ? .black : .white)
show(whistle: murmur, action: .show(2))
}
public extension UIViewController {
public func askUserFor(_ title: String, message: String, whenAsked: @escaping (_ ok: Bool) -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Annuller", style: .cancel) { _ in
whenAsked(false)
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
whenAsked(true)
}
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}
public func alert(_ title: String = "Error", message: String, whenAcknowledge: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
whenAcknowledge()
}
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}
public func close(animate animated: Bool) {
if let navigationController = navigationController {
navigationController.popViewController(animated: animated)
} else {
dismiss(animated: animated, completion: .none)
}
}
public var isVisible: Bool {
if isViewLoaded {
return view.window != nil
}
return false
}
public var contentViewController: UIViewController {
if let vc = self as? UINavigationController {
return vc.topViewController ?? self
} else {
return self
}
}
public var isTopViewController: Bool {
if self.navigationController != nil {
return self.navigationController?.visibleViewController === self
} else if self.tabBarController != nil {
return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
} else {
return self.presentedViewController == nil && self.isVisible
}
}
public var isRunningInFullScreen: Bool {
if let
delegate = UIApplication.shared.delegate,
let window = delegate.window,
let win = window {
return win.frame.equalTo(win.screen.bounds)
}
return true
}
class var className: String {
get {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
fileprivate class func instanceFromMainStoryboardHelper<T>() -> T? {
if let
appDelegate = UIApplication.shared.delegate,
let rvc = appDelegate.window??.rootViewController,
let controller = rvc.storyboard?.instantiateViewController(withIdentifier: className) as? T {
return controller
}
return .none
}
public class func instanceFromMainStoryboard() -> Self? {
return instanceFromMainStoryboardHelper()
}
}
| mit | 8c1295848151f9850a34cd8baf7d4a6e | 25.68595 | 108 | 0.686281 | 4.528752 | false | false | false | false |
milseman/swift | test/Sema/availability_nonoverlapping.swift | 23 | 11306 | // RUN: not %target-swift-frontend -typecheck %s -swift-version 3 2> %t.3.txt
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-3 %s < %t.3.txt
// RUN: %FileCheck -check-prefix=NEGATIVE -check-prefix=NEGATIVE-3 %s < %t.3.txt
// RUN: not %target-swift-frontend -typecheck %s -swift-version 4 2> %t.4.txt
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-4 %s < %t.4.txt
// RUN: %FileCheck -check-prefix=NEGATIVE -check-prefix=NEGATIVE-4 %s < %t.4.txt
class NonOptToOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonOptToOpt()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NonOptToOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonOptToOptReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class OptToNonOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = OptToNonOpt()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class OptToNonOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = OptToNonOptReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NoChange {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {}
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class NoChangeReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {}
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class OptToOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {}
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class OptToOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {}
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class ThreeWayA {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayB {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayC {
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayD {
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayE {
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayF {
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class DisjointThreeWay {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.1, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.1)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class OverlappingVersions {
@available(swift, obsoleted: 5.0)
public init(a: ()) {}
@available(swift 4.0)
public init?(a: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(a:)'
@available(swift 4.0)
public init?(b: ()) {}
@available(swift, obsoleted: 4.1)
public init(b: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(b:)'
public init(c: ()) {}
@available(swift 4.0)
public init?(c: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c:)'
@available(swift 4.0)
public init(c2: ()) {}
public init?(c2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c2:)'
@available(swift, obsoleted: 4.0)
public init(d: ()) {}
public init?(d: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d:)'
public init(d2: ()) {}
@available(swift, obsoleted: 4.0)
public init?(d2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d2:)'
@available(swift, obsoleted: 4.0)
public init(e: ()) {}
@available(swift 4.0)
public init?(e: ()) {}
@available(swift 4.0)
public init!(e: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(e:)'
@available(swift, obsoleted: 4.0)
public init(f: ()) {}
@available(swift 4.0)
public init?(f: ()) {}
@available(swift, obsoleted: 4.0)
public init!(f: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(f:)'
}
class NonThrowingToThrowing {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonThrowingToThrowing()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = NonThrowingToThrowing.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NonThrowingToThrowingReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonThrowingToThrowingReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = NonThrowingToThrowingReversed.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ThrowingToNonThrowing {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ThrowingToNonThrowing()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = ThrowingToNonThrowing.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ThrowingToNonThrowingReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ThrowingToNonThrowingReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = ThrowingToNonThrowingReversed.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ChangePropertyType {
// We don't allow this for stored properties.
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public var stored: Int16 = 0
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public var stored: Int8 = 0 // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'stored'
// OK for computed properties.
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public var computed: Int16 { get { } set { } }
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public var computed: Int8 { get { } set { } } // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ChangePropertyType().computed
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
| apache-2.0 | f6256c725650390ebee70ab5f42f2a07 | 30.06044 | 98 | 0.593844 | 3.467035 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 2 - Robot Maze 2/Boolean Expressions/Boolean Expressions.playground/Pages/The _ _ Operator.xcplaygroundpage/Contents.swift | 1 | 602 | //: [Previous](@previous)
import Foundation
// The || Operator
//: let compoundBool = <first boolean expression> | | <second boolean expression>
// If Jessica finishes her homework OR it's not a school night ...
let finishedHomework = true
let noSchoolTomorrow = false
let allowedToPlayVideoGames = finishedHomework || noSchoolTomorrow
// The || operator can also be used to combine multiple comparison operators
let audienceRating = 85
let criticsRating = 75
let recommendedByAFriend = true
let goWatchMovie = (audienceRating > 90 && criticsRating > 80) || recommendedByAFriend
//: [Next](@next)
| mit | 034bee1977e57209c9bb8159adaa0b2f | 30.684211 | 86 | 0.754153 | 4.067568 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.