repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
idapgroup/IDPDesign
|
refs/heads/master
|
Tests/iOS/iOSTests/Specs/Lens+UINavigationControllerSpec.swift
|
bsd-3-clause
|
1
|
//
// Lens+UINavigationControllerSpec.swift
// iOSTests
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import Quick
import Nimble
import UIKit
@testable import IDPDesign
extension UINavigationController: UINavigationControllerProtocol { }
class LensUINavigationControllerSpec: QuickSpec {
override func spec() {
describe("Lens+UINavigationControllerSpec") {
context("isNavigationBarHidden") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = isNavigationBarHidden()
let object = UINavigationController()
let value: Bool = !object.isNavigationBarHidden
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.isNavigationBarHidden).to(equal(value))
}
}
context("navigationBar") {
it("should get and set") {
let lens: Lens<UINavigationController, UINavigationBar> = navigationBar()
let object = UINavigationController()
let value: UINavigationBar = UINavigationBar()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).toNot(equal(value))
expect(resultObject.navigationBar).to(equal(resultValue))
}
}
context("isToolbarHidden") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = isToolbarHidden()
let object = UINavigationController()
let value: Bool = !object.isToolbarHidden
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.isToolbarHidden).to(equal(value))
}
}
context("toolbar") {
it("should get and set") {
let lens: Lens<UINavigationController, UIToolbar?> = toolbar()
let object = UINavigationController()
let value: UIToolbar = UIToolbar()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).toNot(equal(value))
expect(resultObject.toolbar).to(equal(resultValue))
}
}
context("delegate") {
it("should get and set") {
class Delegate: NSObject, UINavigationControllerDelegate { }
let lens: Lens<UINavigationController, UINavigationControllerDelegate?> = delegate()
let object = UINavigationController()
let value: UINavigationControllerDelegate = Delegate()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(beIdenticalTo(value))
expect(resultObject.delegate).to(beIdenticalTo(value))
}
}
context("interactivePopGestureRecognizer") {
it("should get and set") {
let lens: Lens<UINavigationController, UIGestureRecognizer?> = interactivePopGestureRecognizer()
let object = UINavigationController()
(0..<2).forEach {_ in
object.pushViewController(UIViewController(), animated: false)
}
let value: UIGestureRecognizer = UIGestureRecognizer()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).toNot(equal(value))
expect(resultObject.interactivePopGestureRecognizer).to(equal(resultValue))
}
}
context("hidesBarsWhenKeyboardAppears") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = hidesBarsWhenKeyboardAppears()
let object = UINavigationController()
let value: Bool = !object.hidesBarsWhenKeyboardAppears
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.hidesBarsWhenKeyboardAppears).to(equal(value))
}
}
context("hidesBarsOnSwipe") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = hidesBarsOnSwipe()
let object = UINavigationController()
let value: Bool = !object.hidesBarsOnSwipe
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.hidesBarsOnSwipe).to(equal(value))
}
}
context("barHideOnSwipeGestureRecognizer") {
it("should get and set") {
let lens: Lens<UINavigationController, UIPanGestureRecognizer> = barHideOnSwipeGestureRecognizer()
let object = UINavigationController()
let value: UIPanGestureRecognizer = UIPanGestureRecognizer()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).toNot(equal(value))
expect(resultObject.barHideOnSwipeGestureRecognizer).to(equal(resultValue))
}
}
context("hidesBarsWhenVerticallyCompact") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = hidesBarsWhenVerticallyCompact()
let object = UINavigationController()
let value: Bool = !object.hidesBarsWhenVerticallyCompact
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.hidesBarsWhenVerticallyCompact).to(equal(value))
}
}
context("hidesBarsOnTap") {
it("should get and set") {
let lens: Lens<UINavigationController, Bool> = hidesBarsOnTap()
let object = UINavigationController()
let value: Bool = !object.hidesBarsOnTap
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.hidesBarsOnTap).to(equal(value))
}
}
context("barHideOnTapGestureRecognizer") {
it("should get and set") {
let lens: Lens<UINavigationController, UITapGestureRecognizer> = barHideOnTapGestureRecognizer()
let object = UINavigationController()
let value: UITapGestureRecognizer = UITapGestureRecognizer()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).toNot(equal(value))
expect(resultObject.barHideOnTapGestureRecognizer).to(equal(resultValue))
}
}
}
}
}
|
1be3bcec55000860a6e2fdab4a097c5b
| 38.038462 | 118 | 0.545567 | false | false | false | false |
BigZhanghan/DouYuLive
|
refs/heads/master
|
DouYuLive/DouYuLive/Classes/Main/View/BaseCollectionViewCell.swift
|
mit
|
1
|
//
// BaseCollectionViewCell.swift
// DouYuLive
//
// Created by zhanghan on 2017/10/9.
// Copyright © 2017年 zhanghan. All rights reserved.
//
import UIKit
import Kingfisher
class BaseCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var sourceImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nicknameLabel: UILabel!
var anchor : AnchorModel? {
didSet {
guard let anchor = anchor else {
return
}
var onlineCount : String = ""
if anchor.online >= 10000 {
onlineCount = "\(Int(anchor.online / 1000))万在线"
} else {
onlineCount = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineCount, for: UIControlState.normal)
nicknameLabel.text = anchor.nickname
guard let iconURL = URL(string : anchor.vertical_src) else {
return
}
sourceImageView.kf.setImage(with: iconURL)
}
}
}
|
c90d63d3f6abf9cd08af2d7f9b491325
| 27.315789 | 72 | 0.565985 | false | false | false | false |
albinekcom/BitBay-Ticker-iOS
|
refs/heads/master
|
Codebase/Data Repository/DataRepository.swift
|
mit
|
1
|
import Combine
final class DataRepository {
enum State {
case initializing
case fetching
case fetchedSuccessfully
case fetchingFailed(error: Error)
}
private static let remoteDataFetchingIntervalInSeconds: Double = 10
@Published private(set) var tickers: [Ticker]
@Published var userTickerIds: [String]
@Published private(set) var state: State = .initializing
private let localDataRepository = LocalDataRepository()
private let remoteDataRepository = RemoteDataRepository()
private var cancellables = Set<AnyCancellable>()
init() {
tickers = localDataRepository.loadTickers() ?? []
userTickerIds = localDataRepository.loadUserTickerIds() ?? []
$tickers
.sink { [weak self] in self?.localDataRepository.saveTickers($0) }
.store(in: &cancellables)
$userTickerIds
.sink { [weak self] in self?.localDataRepository.saveUserTickerIds($0) }
.store(in: &cancellables)
Task {
await startAutomaticFetchingRemoteData()
}
}
@MainActor
private func startAutomaticFetchingRemoteData() async {
state = .fetching
do {
tickers = try await remoteDataRepository.fetch()
state = .fetchedSuccessfully
AnalyticsService.shared.trackUserTickersRefreshed(tickerIds: userTickerIds)
} catch {
state = .fetchingFailed(error: error)
AnalyticsService.shared.trackUserTickersRefreshingFailed(tickerIds: userTickerIds)
}
try? await Task.sleep(seconds: Self.remoteDataFetchingIntervalInSeconds)
await startAutomaticFetchingRemoteData()
}
}
private extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
try await Task.sleep(nanoseconds: UInt64(seconds) * 1_000_000_000)
}
}
|
ce03168b234347632ddeb3b35a4a7149
| 27.916667 | 94 | 0.613833 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
refs/heads/master
|
Liferay-Screens/Source/Base/BaseScreenlet+progress.swift
|
gpl-3.0
|
1
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
import Foundation
internal let BaseScreenletHudLock = "hud-lock"
internal struct MBProgressHUDInstance {
static var instance:MBProgressHUD?
static var touchHandler:HUDTouchHandler?
static var customView:UIView? {
didSet {
if instance != nil {
instance!.customView = customView
}
}
}
static var customColor:UIColor? {
didSet {
if instance != nil {
instance!.color = customColor
}
}
}
static var customOpacity:Float = 0.8 {
didSet {
if instance != nil {
instance!.opacity = customOpacity
}
}
}
}
internal class HUDTouchHandler {
internal dynamic func simpleTapDetected(recognizer:UIGestureRecognizer!) {
if let hud = recognizer.view as? MBProgressHUD {
hud.hide(true)
MBProgressHUDInstance.instance = nil
}
}
}
/*!
* This extension to BaseScreenlet adds methods to display an "In Progress" HUD.
*/
extension BaseScreenlet {
public enum CloseMode {
case ManualClose(Bool)
case AutocloseDelayed(Double, Bool)
case AutocloseComputedDelay(Bool)
internal func allowCloseOnTouch() -> Bool {
var result = false
switch self {
case .AutocloseComputedDelay(let touchClose):
result = touchClose
case .AutocloseDelayed(let delay, let touchClose):
result = touchClose
case .ManualClose(let touchClose):
result = touchClose
}
return result
}
}
public enum SpinnerMode {
case IndeterminateSpinner
case DeterminateSpinner
case NoSpinner
internal func toProgressModeHUD() -> MBProgressHUDMode {
switch self {
case IndeterminateSpinner:
return MBProgressHUDModeIndeterminate
case DeterminateSpinner:
return MBProgressHUDModeDeterminate
case NoSpinner:
return MBProgressHUDModeText
}
}
}
//MARK: Class methods
public class func setHUDCustomView(newValue:UIView?) {
MBProgressHUDInstance.customView = newValue
}
public class func setHUDCustomColor(newValue:UIColor?) {
MBProgressHUDInstance.customColor = newValue
}
/*
* showHUDWithMessage shows an animated Progress HUD with the message and details provided.
*/
public func showHUDWithMessage(message:String?,
details:String? = nil,
closeMode:CloseMode = .ManualClose(false),
spinnerMode:SpinnerMode = .IndeterminateSpinner) {
synchronized(BaseScreenletHudLock) {
if MBProgressHUDInstance.instance == nil {
MBProgressHUDInstance.instance =
MBProgressHUD.showHUDAddedTo(self.rootView(self), animated:true)
}
MBProgressHUDInstance.instance?.customView = MBProgressHUDInstance.customView
MBProgressHUDInstance.instance?.color = MBProgressHUDInstance.customColor
MBProgressHUDInstance.instance!.mode = spinnerMode.toProgressModeHUD()
MBProgressHUDInstance.instance!.minShowTime = 0.5
if closeMode.allowCloseOnTouch() {
MBProgressHUDInstance.touchHandler = HUDTouchHandler()
MBProgressHUDInstance.instance!.addGestureRecognizer(
UITapGestureRecognizer(
target: MBProgressHUDInstance.touchHandler!,
action: "simpleTapDetected:"))
}
if message != nil {
MBProgressHUDInstance.instance!.labelText = message
}
MBProgressHUDInstance.instance!.detailsLabelText = (details ?? "") as String
var closeDelay: Double?
switch closeMode {
case .AutocloseComputedDelay(_):
closeDelay = Double.infinity
case .AutocloseDelayed(let delay, _):
closeDelay = delay
default: ()
}
MBProgressHUDInstance.instance!.show(true)
if var delay = closeDelay {
if delay == Double.infinity {
// compute autodelay based on text's length
let len: Int =
count(MBProgressHUDInstance.instance!.labelText) +
count(MBProgressHUDInstance.instance!.detailsLabelText)
delay = 1.5 + (Double(len) * 0.01)
}
MBProgressHUDInstance.instance!.hide(true, afterDelay: delay)
MBProgressHUDInstance.instance = nil
}
}
}
public func showHUDAlert(#message: String, details: String? = nil) {
showHUDWithMessage(message,
details: details,
closeMode: .ManualClose(true),
spinnerMode: .NoSpinner)
}
/*
* hideHUDWithMessage hides an existing animated Progress HUD displaying the message and
* details provided first for a few seconds, calculated based on the length of the message.
*/
public func hideHUDWithMessage(message:String, details:String? = nil) {
showHUDWithMessage(message,
details: details,
closeMode: .AutocloseComputedDelay(true),
spinnerMode: .NoSpinner)
}
public func hideHUD() {
synchronized(BaseScreenletHudLock) {
if let instance = MBProgressHUDInstance.instance {
instance.hide(true)
MBProgressHUDInstance.instance = nil
}
}
}
//MARK: PRIVATE METHODS
private func rootView(currentView:UIView) -> UIView {
if currentView.superview == nil {
return currentView;
}
return rootView(currentView.superview!)
}
}
|
f552a0cc9bf4c6eeb100a812a1add448
| 24.087558 | 92 | 0.727223 | false | false | false | false |
someoneAnyone/Nightscouter
|
refs/heads/dev
|
Common/Protocols/Chartable.swift
|
mit
|
1
|
//
// Chartable.swift
// Nightscouter
//
// Created by Peter Ina on 1/15/16.
// Copyright © 2016 Nothingonline. All rights reserved.
//
import Foundation
public protocol Chartable {
var chartDictionary: String { get }
var chartColor: String { get }
var chartDateFormatter: DateFormatter { get }
var jsonForChart: String { get }
}
struct ChartPoint: Codable {
let color: String
let date: Date
let filtered: Double
let noise: Noise
let sgv: MgdlValue
let type: String
let unfiltered: Double
let y: Double
let direction: Direction
}
extension Chartable {
public var chartColor: String {
return "grey"
}
public var chartDateFormatter: DateFormatter {
let nsDateFormatter = DateFormatter()
nsDateFormatter.dateFormat = "EEE MMM d HH:mm:ss zzz yyy"
nsDateFormatter.timeZone = TimeZone.autoupdatingCurrent
nsDateFormatter.locale = Locale(identifier: "en_US")
return nsDateFormatter
}
public var jsonForChart: String {
// do {
// let jsObj = try JSONSerialization.data(withJSONObject: chartDictionary, options:[])
// guard let str = String(bytes: jsObj, encoding: .utf8) else {
// return ""
// }
//
// return str
// } catch {
// print(error)
// return ""
// }
return chartDictionary
}
}
extension SensorGlucoseValue: Chartable {
public var chartDictionary: String {
get{
let entry: SensorGlucoseValue = self
// let dateForJson = chartDateFormatter.string(from: entry.date)
let chartObject = ChartPoint(color: chartColor, date: entry.date, filtered: entry.filtered ?? 0, noise: entry.noise ?? .none, sgv: entry.mgdl, type: "sgv", unfiltered: entry.unfiltered ?? 0, y: entry.mgdl, direction: entry.direction ?? .none)
let jsonEncorder = JSONEncoder()
jsonEncorder.dateEncodingStrategy = .formatted(chartDateFormatter)
let item = try! jsonEncorder.encode(chartObject.self)
return String(data: item, encoding: .utf8) ?? "[{}]"
}
}
}
|
4493f471a6512f6470706e354606a90c
| 29.205479 | 254 | 0.61678 | false | false | false | false |
FromPointer/VPNOn
|
refs/heads/develop
|
VPNOn/VPNDownloader.swift
|
mit
|
21
|
//
// VPNDownloader.swift
// VPNOn
//
// Created by Lex Tang on 1/27/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
class VPNDownloader: NSObject
{
var queue: NSOperationQueue?
func download(URL: NSURL, callback: (NSURLResponse!, NSData!, NSError!) -> Void) {
let request = NSMutableURLRequest(URL: URL)
var agent = "VPN On"
if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String? {
agent = "\(agent) \(version)"
}
request.HTTPShouldHandleCookies = false
request.HTTPShouldUsePipelining = true
request.cachePolicy = NSURLRequestCachePolicy.ReloadRevalidatingCacheData
request.addValue(agent, forHTTPHeaderField: "User-Agent")
request.timeoutInterval = 20
if let q = queue {
q.suspended = true
queue = nil
}
queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: callback)
}
func cancel() {
if let q = queue {
q.suspended = true
queue = nil
}
}
}
|
09c782b23366b5f06db9e3ad4e048064
| 27.465116 | 117 | 0.609477 | false | false | false | false |
SereivoanYong/Charts
|
refs/heads/master
|
Source/Charts/Renderers/BarLineScatterCandleBubbleRenderer.swift
|
apache-2.0
|
1
|
//
// BarLineScatterCandleBubbleRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
open class BarLineScatterCandleBubbleRenderer: DataRenderer {
internal var _xBounds = XBounds() // Reusable XBounds object
/// Checks if the provided entry object is in bounds for drawing considering the current animation phase.
internal func isInBoundsX(entry e: Entry, dataSet: IBarLineScatterCandleBubbleChartDataSet) -> Bool {
let entryIndex = dataSet.entryIndex(entry: e)
return !(CGFloat(entryIndex) >= CGFloat(dataSet.entries.count) * animator.phaseX)
}
/// Calculates and returns the x-bounds for the given DataSet in terms of index in their values array.
/// This includes minimum and maximum visible x, as well as range.
internal func xBounds(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) -> XBounds {
return XBounds(chart: chart, dataSet: dataSet, animator: animator)
}
/// - returns: `true` if the DataSet values should be drawn, `false` if not.
internal func shouldDrawValues(forDataSet set: IChartDataSet) -> Bool {
return set.isVisible && (set.isDrawValuesEnabled || set.isDrawIconsEnabled)
}
/// Class representing the bounds of the current viewport in terms of indices in the values array of a DataSet.
open class XBounds {
/// minimum visible entry index
open var min: Int = 0
/// maximum visible entry index
open var max: Int = 0
/// range of visible entry indices
open var range: Int = 0
public init() {
}
public init(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) {
self.set(chart: chart, dataSet: dataSet, animator: animator)
}
/// Calculates the minimum and maximum x values as well as the range between them.
open func set(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) {
let phaseX = Swift.max(0.0, Swift.min(1.0, animator?.phaseX ?? 1.0))
let low = chart.lowestVisibleX
let high = chart.highestVisibleX
let entryFrom = dataSet.entryForXValue(low, closestToY: .nan, rounding: DataSetRounding.down)
let entryTo = dataSet.entryForXValue(high, closestToY: .nan, rounding: DataSetRounding.up)
self.min = entryFrom == nil ? 0 : dataSet.entryIndex(entry: entryFrom!)
self.max = entryTo == nil ? 0 : dataSet.entryIndex(entry: entryTo!)
range = Int(CGFloat(self.max - self.min) * phaseX)
}
}
}
|
10fc3a1cd9a6c22220adce8105646151
| 38.25 | 159 | 0.709837 | false | false | false | false |
DeepLearningKit/DeepLearningKit
|
refs/heads/master
|
tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/ImageUtilityFunctions.swift
|
apache-2.0
|
2
|
//
// ImageUtilityFunctions.swift
// iOSDeepLearningKitApp
//
// This code is a contribution from Maciej Szpakowski - https://github.com/several27
// with a minor fix by Stanislav Ashmanov https://github.com/ashmanov
// ref: issue - https://github.com/DeepLearningKit/DeepLearningKit/issues/8
//
// Copyright © 2016 DeepLearningKit. All rights reserved.
//
import Foundation
import UIKit
import Accelerate
func imageToMatrix(image: UIImage) -> ([Float], [Float], [Float], [Float])
{
let imageRef = image.CGImage
let width = CGImageGetWidth(imageRef)
let height = CGImageGetHeight(imageRef)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel = 4
let bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width)
let bitsPerComponent:UInt = 8
let pix = Int(width) * Int(height)
let count:Int = 4 * Int(pix)
// Pulling the color out of the image
let rawData = UnsafeMutablePointer<UInt8>.alloc(4 * width * height)
let temp = CGImageAlphaInfo.PremultipliedLast.rawValue
let context = CGBitmapContextCreate(rawData, Int(width), Int(height), Int(bitsPerComponent), Int(bytesPerRow), colorSpace, temp)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)
// Unsigned char to double conversion
var rawDataArray: [Float] = Array(count: count, repeatedValue: 0.0)
vDSP_vfltu8(rawData, vDSP_Stride(1), &rawDataArray, 1, vDSP_Length(count))
// Indices matrix
var i: [Float] = Array(count: pix, repeatedValue: 0.0)
var min: Float = 0.0
var step: Float = 4.0
vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count))
func increaseMatrix(var matrix: [Float]) -> [Float]
{
var increaser: Float = 1.0
vDSP_vsadd(&matrix, vDSP_Stride(1), &increaser, &matrix, vDSP_Stride(1), vDSP_Length(i.count))
return matrix
}
// Red matrix
var r: [Float] = Array(count: pix, repeatedValue: 0.0)
vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &r, vDSP_Stride(1), vDSP_Length(r.count))
increaseMatrix(i)
min = 1.0
vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count))
// Green matrix
var g: [Float] = Array(count: pix, repeatedValue: 0.0)
vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &g, vDSP_Stride(1), vDSP_Length(g.count))
increaseMatrix(i)
min = 2.0
vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count))
// Blue matrix
var b: [Float] = Array(count: pix, repeatedValue: 0.0)
vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &b, vDSP_Stride(1), vDSP_Length(b.count))
increaseMatrix(i)
min = 3.0
vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count))
// Alpha matrix
var a: [Float] = Array(count: pix, repeatedValue: 0.0)
vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &a, vDSP_Stride(1), vDSP_Length(a.count))
return (r, g, b, a)
}
|
23492cb216e2a8c8dcf87a69e2cbd5f3
| 36.935897 | 132 | 0.658553 | false | false | false | false |
SeptAi/Cooperate
|
refs/heads/master
|
Cooperate/Cooperate/Class/Tools/Network/NetworkManager.swift
|
mit
|
1
|
//
// NetworkManager.swift
// Cooperation
//
// Created by J on 2016/12/27.
// Copyright © 2016年 J. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
enum HTTPMethod{
case GET
case POST
}
private let NetworkRequestShareInstance = NetworkManager()
class NetworkManager {
static var sharedInstance : NetworkManager {
return NetworkRequestShareInstance
}
/// 用户账户的懒加载属性
lazy var userAccount = UserAccount()
/// 用户登录标记[计算型属性]
var userLogon: Bool {
// FIXME: - 测试
// return userAccount.access_token != nil
return true
}
}
extension NetworkManager{
/// 网络访问的中间对外入口
///
/// - Parameters:
/// - method: 方法
/// - URLString: 链接
/// - parameters: 参数
/// - type: 是否用户验证
/// - name: 图片名
/// - data: 数据
/// - completion: 完成回调
func tokenRequest(method: HTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,type:Bool = false,name:String? = nil,data:Data? = nil, completion: @escaping (_ json: [String:Any]?, _ isSuccess: Bool)->()){
// FIXME: - 关闭用户验证,ATS设置
/*
guard let _ = userAccount.access_token,let uid = userAccount.uid else {
// FIXME: - 获取到token未使用
// 发送通知,提示用户登录
print("没有 token! 需要登录")
// MARK: - 接收通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NoticeName.UserShouldLoginNotification), object: nil)
completion(nil, false)
return
}
*/
// 1> 判断 参数字典是否存在,如果为 nil,应该新建一个字典
var parameters = parameters
if parameters == nil {
// 实例化字典
parameters = [String: AnyObject]()
}
// 2> 设置参数字典,代码在此处字典一定有值 - 用户的编号
// parameters!["uid"] = uid as AnyObject?
// 判断是否属于用户验证操作
if type {
// 用户验证
return
}
// 判断name和data
if let name = name,let data = data{
// 调用 request 发起真正的网络请求方法,上传文件
upload(URLString: URLString, parameters: parameters, name: name, data: data, completion: completion)
}else{
// 调用 request 发起真正的网络请求方法
request(method: method,URLString: URLString, parameters: parameters, completion: completion)
}
}
/// 封装 AFN 的 GET / POST 请求
///
/// - parameter method: GET / POST
/// - parameter URLString: URLString
/// - parameter parameters: 参数字典
/// - parameter completion: 完成回调[json(字典/数组), 是否成功]
func request(method: HTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,completion:@escaping (_ json: [String:Any]?, _ isSuccess: Bool)->()) {
// 框架进行网络请求
if method == .GET{
Alamofire.request(URLString, method: .get, parameters: parameters).responseJSON { (response) in
switch response.result{
case .success(let vaule):
completion(JSON(vaule).dictionaryObject, true)
case .failure(let error as NSError):
// 针对 403 处理用户 token 过期
// 对于测试用户(应用程序还没有提交给新浪微博审核)每天的刷新量是有限的!
// 超出上限,token 会被锁定一段时间
// 解决办法,新建一个应用程序!
if error.code == 403 {
print("Token 过期了")
// 发送通知,提示用户再次登录(本方法不知道被谁调用,谁接收到通知,谁处理!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NoticeName.UserShouldLoginNotification), object: "bad token")
}
// error 通常比较吓人,例如编号:XXXX,错误原因一堆英文!
print("网络请求错误 \(error)")
completion(nil, false)
default:
print("网络请求错误")
}
}
} else{
//Editor placeholder in source file
Alamofire.request(URLString, method: .post, parameters: parameters).responseJSON { (response) in
switch response.result{
case .success(let vaule):
completion(JSON(vaule).dictionaryObject, true)
case .failure(let error as NSError):
// 针对 403 处理用户 token 过期
// 对于测试用户(应用程序还没有提交给新浪微博审核)每天的刷新量是有限的!
// 超出上限,token 会被锁定一段时间
// 解决办法,新建一个应用程序!
if error.code == 403 {
print("Token 过期了")
// 发送通知,提示用户再次登录(本方法不知道被谁调用,谁接收到通知,谁处理!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NoticeName.UserShouldLoginNotification), object: "bad token")
}
// error 通常比较吓人,例如编号:XXXX,错误原因一堆英文!
print("网络请求错误 \(error)")
completion(nil, false)
default:
print("网络请求错误")
}
}
}
}
// MARK: - 网络上传方法
// 上传文件
// 只能采用post
/// 上传文件
///
/// - Parameters:
/// - URLString: 地址
/// - parameters: 参数
/// - name: 接收上传数据的服务器字段
/// - data: 二进制数据
/// - completion: 回调
func upload(URLString: String, parameters: [String: AnyObject]?,name:String,data:Data,completion:@escaping (_ json: [String:Any]?, _ isSuccess: Bool)->()){
// 处理上传
}
}
|
32d78943d8af6679c313126507ec3828
| 32.39881 | 226 | 0.507574 | false | false | false | false |
hongdong/Gank
|
refs/heads/master
|
Pods/Action/Sources/Action/Action.swift
|
mit
|
1
|
import Foundation
import RxSwift
import RxCocoa
/// Typealias for compatibility with UIButton's rx.action property.
public typealias CocoaAction = Action<Void, Void>
/// Possible errors from invoking execute()
public enum ActionError: Error {
case notEnabled
case underlyingError(Error)
}
/**
Represents a value that accepts a workFactory which takes some Observable<Input> as its input
and produces an Observable<Element> as its output.
When this excuted via execute() or inputs subject, it passes its parameter to this closure and subscribes to the work.
*/
public final class Action<Input, Element> {
public typealias WorkFactory = (Input) -> Observable<Element>
public let _enabledIf: Observable<Bool>
public let workFactory: WorkFactory
/// Inputs that triggers execution of action.
/// This subject also includes inputs as aguments of execute().
/// All inputs are always appear in this subject even if the action is not enabled.
/// Thus, inputs count equals elements count + errors count.
public let inputs = PublishSubject<Input>()
/// Errors aggrevated from invocations of execute().
/// Delivered on whatever scheduler they were sent from.
public let errors: Observable<ActionError>
/// Whether or not we're currently executing.
/// Delivered on whatever scheduler they were sent from.
public let elements: Observable<Element>
/// Whether or not we're currently executing.
public let executing: Observable<Bool>
/// Observables returned by the workFactory.
/// Useful for sending results back from work being completed
/// e.g. response from a network call.
public let executionObservables: Observable<Observable<Element>>
/// Whether or not we're enabled. Note that this is a *computed* sequence
/// property based on enabledIf initializer and if we're currently executing.
/// Always observed on MainScheduler.
public let enabled: Observable<Bool>
private let disposeBag = DisposeBag()
public init(
enabledIf: Observable<Bool> = Observable.just(true),
workFactory: @escaping WorkFactory) {
self._enabledIf = enabledIf
self.workFactory = workFactory
let enabledSubject = BehaviorSubject<Bool>(value: false)
enabled = enabledSubject.asObservable()
let errorsSubject = PublishSubject<ActionError>()
errors = errorsSubject.asObservable()
executionObservables = inputs
.withLatestFrom(enabled) { $0 }
.flatMap { input, enabled -> Observable<Observable<Element>> in
if enabled {
return Observable.of(workFactory(input)
.do(onError: { errorsSubject.onNext(.underlyingError($0)) })
.shareReplay(1))
} else {
errorsSubject.onNext(.notEnabled)
return Observable.empty()
}
}
.share()
elements = executionObservables
.flatMap { $0.catchError { _ in Observable.empty() } }
executing = executionObservables.flatMap {
execution -> Observable<Bool> in
let execution = execution
.flatMap { _ in Observable<Bool>.empty() }
.catchError { _ in Observable.empty()}
return Observable.concat([Observable.just(true),
execution,
Observable.just(false)])
}
.startWith(false)
.shareReplay(1)
Observable
.combineLatest(executing, enabledIf) { !$0 && $1 }
.bindTo(enabledSubject)
.addDisposableTo(disposeBag)
}
@discardableResult
public func execute(_ value: Input) -> Observable<Element> {
defer {
inputs.onNext(value)
}
let subject = ReplaySubject<Element>.createUnbounded()
let work = executionObservables
.map { $0.catchError { throw ActionError.underlyingError($0) } }
let error = errors
.map { Observable<Element>.error($0) }
work.amb(error)
.take(1)
.flatMap { $0 }
.subscribe(subject)
.addDisposableTo(disposeBag)
return subject.asObservable()
}
}
|
f0abbc29772a670b108ea95a1a44b77f
| 33.698413 | 118 | 0.625572 | false | false | false | false |
oliverkulpakko/ATMs
|
refs/heads/master
|
ATMs/View/Controllers/MapViewController.swift
|
mit
|
1
|
//
// MapViewController.swift
// ATMs
//
// Created by Oliver Kulpakko on 5.12.2017.
// Copyright © 2017 East Studios. All rights reserved.
//
import UIKit
import MapKit
import PullUpController
import StoreKit
import GoogleMobileAds
class MapViewController: UIViewController {
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
#if DEBUG
adBannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
#else
adBannerView.adUnitID = "ca-app-pub-2929799728547191/6214864662"
#endif
adBannerView.adSize = kGADAdSizeBanner
adBannerView.rootViewController = self
adBannerView.load(GADRequest())
if #available(iOS 10.3, *) {
checkReviewStatus()
}
if let atmsViewController = storyboard?.instantiateViewController(withIdentifier: "ATMsViewController") as? ATMsViewController {
self.atmsViewController = atmsViewController
atmsViewController.delegate = self
addPullUpController(atmsViewController, initialStickyPointOffset: 100, animated: false)
if #available(iOS 11.0, *) {
atmsViewController.setupTrackingButton(mapView: mapView)
} else {
// TODO: Fallback on earlier versions
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapMap))
mapView.addGestureRecognizer(tapGestureRecognizer)
}
RemoteService.shared.fetchATMs(completion: { result in
switch result {
case .success(let atms):
self.atms = atms
case .failure(let error):
self.presentError(error)
}
})
}
@objc func didTapMap() {
atmsViewController?.dismiss()
}
@available(iOS 10.3, *)
func checkReviewStatus() {
if AnalyticsStore.appLaunchCount > 2 && !UserDefaults.standard.bool(forKey: "AskedForRating") {
RateHelper.showRatingPrompt()
UserDefaults.standard.set(true, forKey: "AskedForRating")
}
}
// MARK: Stored Properties
var atmsViewController: ATMsViewController?
var locationManager = CLLocationManager()
var atms = [ATM]() {
didSet {
mapView.addAnnotations(atms)
atmsViewController?.atms = atms
}
}
// MARK: IBOutlets
@IBOutlet var statusBarBlurView: UIVisualEffectView!
@IBOutlet var adBannerView: GADBannerView!
@IBOutlet var mapView: MKMapView!
}
extension MapViewController: ATMsViewControllerDelegate {
func didSelectATM(_ atm: ATM, in atmsViewController: ATMsViewController) {
atmsViewController.dismiss()
mapView.zoomTo(atm, animated: true)
analytics.logAction("OpenATM", data1: atm.name)
}
}
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
mapView.zoomToCoordinate(location.coordinate, animated: true)
atmsViewController?.location = location
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
presentError(error)
}
}
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
guard let atm = annotation as? ATM else {
return nil
}
if #available(iOS 11.0, *) {
let annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "ATM")
annotationView.markerTintColor = atm.modelColor()
annotationView.glyphText = atm.modelFormatted()
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "ATM")
annotationView.pinTintColor = atm.modelColor()
return annotationView
}
}
}
|
9d70491c2319c35aead4e88e62fe71c9
| 25.027397 | 130 | 0.743684 | false | false | false | false |
Yalantis/PixPic
|
refs/heads/master
|
PixPic/Classes/Flow/PhotoEditor/Stickers/StickersLayout.swift
|
mit
|
1
|
//
// EffectsLayout.swift
// PixPic
//
// Created by AndrewPetrov on 2/10/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import Foundation
private let cellSize = CGSize(width: 105, height: 105)
class StickersLayout: UICollectionViewFlowLayout {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
itemSize = cellSize
headerReferenceSize = cellSize
scrollDirection = UICollectionViewScrollDirection.Horizontal
sectionHeadersPinToVisibleBounds = true
minimumLineSpacing = 0
minimumInteritemSpacing = 0
}
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath)!
var newFrame = CGRect(origin: attributes.frame.origin, size: attributes.frame.size)
newFrame.origin.y = cellSize.height
attributes.frame = newFrame
attributes.alpha = 0
return attributes
}
override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath)!
attributes.alpha = 0
return attributes
}
}
|
3723b034d74098a5db6cc5ca622996d9
| 28.875 | 136 | 0.716876 | false | false | false | false |
wenghengcong/Coderpursue
|
refs/heads/master
|
BeeFun/BeeFun/View/Trending/ViewCell/InfoButton.swift
|
mit
|
1
|
//
// InfoButton.swift
// BeeFun
//
// Created by WengHengcong on 2017/3/10.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
class ObjInfo: NSObject {
var image: String?
var title: String?
var url: String?
init(image: String?, title: String?, url: String?) {
self.image = image
self.title = title
self.url = url
}
}
class InfoButton: UIButton {
var imageV: UIImageView?
var titleL: UILabel?
var url: String?
var objInfo: ObjInfo? {
didSet {
ib_fillData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
init(image: String?, title: String?, url: String?) {
super.init(frame:CGRect.zero)
self.objInfo = ObjInfo(image:image, title:title, url:url)
}
convenience init(info: ObjInfo) {
self.init(image:info.image, title:info.title, url:info.url)
self.objInfo = info
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func ib_customView() {
if imageV == nil {
imageV = UIImageView()
imageV?.backgroundColor = UIColor.red
self.addSubview(imageV!)
}
if titleL == nil {
titleL = UILabel()
titleL?.backgroundColor = UIColor.green
self.addSubview(titleL!)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if imageV != nil {
let imgw: CGFloat = 20
let imgx = self.width * 0.2
let imgy = (self.height - imgw)/2
imageV?.snp.makeConstraints({ (make) in
make.top.equalTo(imgy)
make.leading.equalTo(imgx)
make.width.equalTo(imgw)
make.height.equalTo(imgw)
})
}
if titleL != nil {
let titx = (imageV?.right)! + 10
let tity = 0
let tith = self.height
titleL?.snp.makeConstraints({ (make) in
make.top.equalTo(tity)
make.leading.equalTo(titx)
make.trailing.equalTo(0)
make.height.equalTo(tith)
})
}
}
func ib_fillData() {
ib_customView()
if let image = objInfo?.image {
imageV?.image = UIImage(named: image)
}
if let title = objInfo?.title {
titleL?.text = title
}
if let url = objInfo?.url {
self.url = url
}
self.setNeedsLayout()
}
}
|
1cf54cc055fa626a15de55d539875794
| 21.413793 | 67 | 0.518077 | false | false | false | false |
iOSDevLog/iOSDevLog
|
refs/heads/master
|
109. Cassini/Cassini/ImageViewController.swift
|
mit
|
6
|
//
// ImageViewController.swift
// Cassini
//
// Created by jiaxianhua on 15/9/28.
// Copyright © 2015年 com.jiaxh. All rights reserved.
//
import UIKit
class ImageViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
scrollView.contentSize = imageView.frame.size
scrollView.delegate = self
scrollView.minimumZoomScale = 0.03
scrollView.maximumZoomScale = 1.0
}
}
@IBOutlet weak var spinner: UIActivityIndicatorView!
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
var imageURL: NSURL? {
didSet {
image = nil
if view.window != nil {
fetchImage()
}
}
}
private func fetchImage() {
if let url = imageURL {
spinner?.startAnimating()
let qos = Int(QOS_CLASS_USER_INITIATED.rawValue)
dispatch_async(dispatch_get_global_queue(qos, 0), {
dispatch_async(dispatch_get_main_queue()) {
let imageData = NSData(contentsOfURL: url)
if imageData != nil {
self.image = UIImage(data: imageData!)
}
else {
self.image = nil
}
}
})
}
}
private var imageView = UIImageView()
private var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
imageView.sizeToFit()
scrollView?.contentSize = imageView.frame.size
spinner?.stopAnimating()
}
}
override func viewDidLoad() {
super.viewDidLoad()
scrollView.addSubview(imageView)
}
// for efficiency, we will only actually fetch the image
// when we know we are going to be on screen
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if image == nil {
fetchImage()
}
}
}
|
a8cba2f35ae7604e8b23f907df6dcf10
| 26.08642 | 74 | 0.532361 | false | false | false | false |
polymr/polymyr-api
|
refs/heads/master
|
Sources/App/Models/StripeMakerCustomer.swift
|
mit
|
1
|
//
// StripeMakerCustomer.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/3/17.
//
//
import Vapor
import Fluent
import FluentProvider
import Node
final class StripeMakerCustomer: Model, JSONConvertible, NodeConvertible, Preparation {
let storage = Storage()
var id: Identifier?
var exists: Bool = false
let customer_id: Identifier
let maker_id: Identifier
let stripeCustomerId: String
init(maker: Maker, customer: Customer, account: String) throws {
guard let maker_id = maker.id else {
throw Abort.custom(status: .internalServerError, message: "Missing maker id for StripeMakerCustomer link.")
}
guard let customer_id = customer.id else {
throw Abort.custom(status: .internalServerError, message: "Missing customer id for StripeMakerCustomer link.")
}
self.customer_id = customer_id
self.maker_id = maker_id
self.stripeCustomerId = account
}
init(node: Node) throws {
id = try? node.extract("id")
customer_id = try node.extract("customer_id")
maker_id = try node.extract("maker_id")
stripeCustomerId = try node.extract("stripeCustomerId")
}
func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"stripeCustomerId" : stripeCustomerId,
"customer_id" : customer_id.makeNode(in: context),
"maker_id" : maker_id.makeNode(in: context)
]).add(objects: [
"id" : id
])
}
static func prepare(_ database: Database) throws {
try database.create(StripeMakerCustomer.self) { stripeMakerCustomer in
stripeMakerCustomer.id()
stripeMakerCustomer.parent(Customer.self)
stripeMakerCustomer.parent(Maker.self)
stripeMakerCustomer.string("stripeCustomerId")
}
}
static func revert(_ database: Database) throws {
try database.delete(StripeMakerCustomer.self)
}
}
extension StripeMakerCustomer {
func vendor() -> Parent<StripeMakerCustomer, Maker> {
return parent(id: maker_id)
}
func customer() -> Parent<StripeMakerCustomer, Customer> {
return parent(id: customer_id)
}
}
|
2132684d633bd4b2175f5e32b257ae4b
| 27.85 | 122 | 0.62565 | false | false | false | false |
adafruit/Bluefruit_LE_Connect
|
refs/heads/master
|
BluetoothLE Test WatchKit Extension/BLEInterfaceController.swift
|
bsd-3-clause
|
4
|
//
// BLEInterfaceController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 6/27/15.
// Copyright (c) 2015 Adafruit Industries. All rights reserved.
//
import WatchKit
import Foundation
class BLEInterfaceController: WKInterfaceController {
@IBOutlet weak var noConnectionLabel: WKInterfaceLabel?
@IBOutlet weak var controllerModeGroup: WKInterfaceGroup?
@IBOutlet weak var debugLabel: WKInterfaceLabel?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.addMenuItemWithItemIcon(WKMenuItemIcon.Decline, title: "Disconnect", action: Selector("disconnectButtonTapped"))
}
func disconnectButtonTapped() {
sendRequest(["type":"command", "command":"disconnect"])
}
func sendRequest(message:[String:AnyObject]){
BLESessionManager.sharedInstance.sendRequest(message, sender: self)
}
func respondToConnected() {
self.noConnectionLabel?.setHidden(true)
self.controllerModeGroup?.setHidden(false)
}
func respondToNotConnected() {
self.noConnectionLabel?.setHidden(false)
self.controllerModeGroup?.setHidden(true)
WKInterfaceController.reloadRootControllersWithNames(["Root"], contexts: nil)
}
func showDebugInfo(message:String) {
self.debugLabel?.setText(message)
}
//OLD METHOD
// WKInterfaceController.openParentApplication(request,
// reply: { (replyInfo, error) -> Void in
// //parse reply info
// switch (replyInfo["connected"] as? Bool, error) { //received correctly formatted reply
// case let (connected, nil) where connected != nil:
// if connected == true { //app has connection to ble device
//// NSLog("reply received == connected")
// self.respondToConnected()
// }
// else { //app has NO connection to ble device
//// NSLog("reply received == not connected")
// self.respondToNotConnected()
// }
// case let (_, .Some(error)):
// print("reply received with error: \(error)") // received reply w error
// default:
// print("reply received with no error or data ...") // received reply with no data or error
// }
// })
// }
}
|
c77083a78b118e4c257b22308869bac1
| 29.101124 | 125 | 0.564763 | false | false | false | false |
sztoth/PodcastChapters
|
refs/heads/develop
|
PodcastChapters/Controllers/Coordinators/ContentCoordinator.swift
|
mit
|
1
|
//
// ContentCoordinator.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 06..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Cocoa
import RxSwift
class ContentCoordinator {
fileprivate let popover: Popover
fileprivate let podcastMonitor: PodcastMonitorType
fileprivate let chaptersController: ChaptersViewController
fileprivate let otherContentController: OtherContentViewController
fileprivate let disposeBag = DisposeBag()
init(popover: Popover, podcastMonitor: PodcastMonitorType) {
self.popover = popover
self.podcastMonitor = podcastMonitor
// TODO: - Rethink the force unwrap
let chaptersViewModel = ChaptersViewModel(podcastMonitor: self.podcastMonitor)
chaptersController = ChaptersViewController(viewModel: chaptersViewModel)!
otherContentController = OtherContentViewController()!
podcastMonitor.podcast
.subscribe(onNext: { isPodcast in
if isPodcast {
self.popover.content = self.chaptersController
}
else {
self.popover.content = self.otherContentController
}
})
.addDisposableTo(disposeBag)
}
}
|
c25515ceae3cdc93318c1a5ae990de77
| 31.275 | 86 | 0.666925 | false | false | false | false |
hellogaojun/Swift-coding
|
refs/heads/master
|
swift学习教材案例/Swifter.playground/Pages/pattern-match.xcplaygroundpage/Contents.swift
|
apache-2.0
|
1
|
import Foundation
let password = "akfuv(3"
switch password {
case "akfuv(3": print("密码通过")
default: print("验证失败")
}
let num: Int? = nil
switch num {
case nil: print("没值")
default: print("\(num!)")
}
let x = 0.5
switch x {
case -1.0...1.0: print("区间内")
default: print("区间外")
}
func ~=(pattern: NSRegularExpression, input: String) -> Bool {
return pattern.numberOfMatchesInString(input,
options: [],
range: NSRange(location: 0, length: input.characters.count)) > 0
}
prefix operator ~/ {}
prefix func ~/(pattern: String) throws -> NSRegularExpression {
return try NSRegularExpression(pattern: pattern, options: [])
}
let contact = ("http://onevcat.com", "[email protected]")
let mailRegex: NSRegularExpression
let siteRegex: NSRegularExpression
mailRegex = try ~/"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
siteRegex = try ~/"^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
switch contact {
case (siteRegex, mailRegex): print("同时拥有有效的网站和邮箱")
case (_, mailRegex): print("只拥有有效的邮箱")
case (siteRegex, _): print("只拥有有效的网站")
default: print("嘛都没有")
}
// 输出
// 同时拥有网站和邮箱
|
2de600adab89871dba12ef6f22b7051e
| 22.196078 | 92 | 0.597633 | false | false | false | false |
AlexMobile/AGChart
|
refs/heads/master
|
AGChart/AGChart/UI/AGChartView.swift
|
mit
|
1
|
//
// AGChartView.swift
// AGChart
//
// Created by Alexey Golovenkov on 19/12/14.
// Copyright (c) 2014 Alexey Golovenkov. All rights reserved.
//
import UIKit
@IBDesignable public class AGChartView: UIView {
@IBOutlet var dataSource: AGChartDataSource?
@IBOutlet var customizer: AGChartCustomizer? {
didSet {
dataLayer.customizer = customizer
}
}
var dataLayer = AGChartDataLayer()
let calculator = AGChartCalculator()
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.baseInit()
}
public required override init(frame: CGRect) {
super.init(frame: frame)
self.baseInit()
}
public override func awakeFromNib() {
super.awakeFromNib()
if (customizer == nil) {
self.customizer = AGChartCustomizer()
}
}
// MARK: - Private methods
func baseInit() {
self.addLayers()
calculator.chartView = self
}
func addLayers() {
self.layer.addSublayer(dataLayer)
dataLayer.frame = self.layer.bounds
dataLayer.datasource = self.dataSource
dataLayer.calculator = calculator
dataLayer.customizer = customizer
}
public override func layoutSublayersOfLayer(layer: CALayer!) {
if layer == self.layer {
dataLayer.frame = calculator.chartFrameForViewFrame(layer.bounds)
}
}
}
|
189adf225795daed47e3d6ffef1a7a47
| 24.135593 | 77 | 0.61336 | false | false | false | false |
xianglin123/douyuzhibo
|
refs/heads/master
|
douyuzhibo/douyuzhibo/Classes/Tools/common.swift
|
apache-2.0
|
1
|
//
// common.swift
// douyuzhibo
//
// Created by xianglin on 16/10/4.
// Copyright © 2016年 xianglin. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNaviBarH : CGFloat = 44
let kTabbarH : CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
2a42de3db31ad10199428904be919966
| 18.9375 | 52 | 0.714734 | false | false | false | false |
MadAppGang/MAGPagedScrollView
|
refs/heads/master
|
MAGPagedScrollView/PagedParallaxScrollView.swift
|
mit
|
1
|
//
// PagedParallaxScrollView.swift
// MAGPagedScrollViewDemo
//
// Created by Ievgen Rudenko on 26/08/15.
// Copyright (c) 2015 MadAppGang. All rights reserved.
//
import UIKit
@objc public protocol PagedScrollViewParallaxDelegate: class {
//parallax from -100 to 100. 0 is central position.
func parallaxProgressChanged(progress:Int)
}
public class PagedParallaxScrollView: PagedReusableScrollView {
override public func layoutSubviews() {
super.layoutSubviews()
for view in viewsOnScreen() {
if let parallaxView = view as? PagedScrollViewParallaxDelegate {
let oldTransform = view.layer.transform
view.layer.transform = CATransform3DIdentity
let centerDX = Int((view.frame.origin.x - contentOffset.x) * 100 / CGRectGetWidth(frame))
view.layer.transform = oldTransform
parallaxView.parallaxProgressChanged(centerDX)
}
}
}
}
|
25bed9ed8391a500a32ade61346adea9
| 30.741935 | 105 | 0.667683 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/DebugInfo/LoadableByAddress-allockstack.swift
|
apache-2.0
|
34
|
// Check we don't crash when verifying debug info.
// Ideally this should print the output after loadable by address runs
// but there's no way of doing this in SIL (for IRGen passes).
// RUN: %target-swift-frontend -emit-sil %s -Onone \
// RUN: -sil-verify-all -Xllvm -verify-di-holes -emit-ir \
// RUN: -Xllvm -sil-print-debuginfo -g -o - | %FileCheck %s
struct m {
let major: Int
let minor: Int
let n: Int
let o: [String]
let p: [String]
init(major: Int, minor: Int, n: Int, o: [String], p: [String]) {
self.major = major
self.minor = minor
self.n = n
self.o = o
self.p = p
}
}
enum a {
case any
case b(m)
}
struct c<e> {
enum f {
case g(a)
}
}
struct h<i>{
typealias j = i
typealias d = j
typealias f = c<d>.f
subscript(identifier: d) -> f {
return .g(.any)
}
func k(l: f, identifier: d) -> h {
switch (l, self[identifier]) {
default:
return self
}
}
}
// CHECK: define internal %swift.opaque* @"$s4main1mVwCP"
|
eaf6ae253a0daf13637ab492eaf6a286
| 19.632653 | 70 | 0.593472 | false | false | false | false |
salemoh/GoldenQuraniOS
|
refs/heads/master
|
GoldenQuranSwift/GoldenQuranSwift/GQTextField.swift
|
mit
|
1
|
//
// GQTextField.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 3/8/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
class GQTextField: UITextField {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var isBoldFont = false
@IBInspectable var isBold: Bool {
get {
return isBoldFont
}
set {
self.isBoldFont = newValue
updateToNewFont()
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateToNewFont()
}
func updateToNewFont(){
self.font = FontManager.fontWithSize(size: (self.font?.pointSize)!, isBold: self.isBoldFont)
if let _ = self.placeholder {
let attributes = [NSFontAttributeName : self.font!] as [String : Any]
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!,attributes:attributes)
}
}
}
|
7bf2db126c4e4c765c7b2586b530bfbe
| 23.319149 | 108 | 0.59755 | false | false | false | false |
vlribeiro/loja-desafio-ios
|
refs/heads/master
|
LojaDesafio/LojaDesafio/TransactionData.swift
|
mit
|
1
|
//
// File.swift
// LojaDesafio
//
// Created by Vinicius Ribeiro on 30/11/15.
// Copyright © 2015 Vinicius Ribeiro. All rights reserved.
//
import Foundation
import RealmSwift
class TransactionData {
class func insertOrUpdate(transaction: Transaction) -> Transaction {
let realm = try! Realm()
try! realm.write({
realm.add(transaction, update: true)
})
return transaction
}
class func insertOrUpdate(transaction: Transaction, withCreditCard creditCard: CreditCard) -> Transaction {
let realm = try! Realm()
try! realm.write({
transaction.creditCard = creditCard
realm.add(transaction, update: true)
})
return transaction
}
class func fetchActive() -> Transaction {
let realm = try! Realm()
if let transaction = realm.objects(Transaction).first {
return transaction
}
else {
let transaction = Transaction()
transaction.id = 1
try! realm.write({
realm.add(transaction, update: true)
})
return transaction
}
}
class func addTransactionProduct(transactionProduct: TransactionProduct, toTransaction transaction: Transaction) {
let realm = try! Realm()
try! realm.write({
transaction.transactionProducts.append(transactionProduct)
realm.add(transaction, update: true)
})
NSLog("Adicionando \(transactionProduct) na transação")
}
class func delete(transaction: Transaction) {
let realm = try! Realm()
try! realm.write({
realm.delete(transaction)
})
}
}
|
1e5b0fdf20768e089d0f8a224048ebbd
| 24.506849 | 118 | 0.554541 | false | false | false | false |
cschlessinger/dbc-civichack-artistnonprofit
|
refs/heads/master
|
iOS/DevBootcampHackathon/DevBootcampHackathon/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// DevBootcampHackathon
//
// Created by Lucas Farah on 1/23/16.
// Copyright © 2016 Lucas Farah. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ImagePickerDelegate {
var arrCat = ["Senior","Homeless","Children","Animals"]
var arrCatNum = ["109","230","59","90"]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource
{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrCat.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell!
if !(cell != nil)
{
cell = TableViewCell(style:.Default, reuseIdentifier: "cell")
}
let imgvName = arrCat[indexPath.row] + ".jpg"
// setup cell without force unwrapping it
cell.lblName.text = arrCat[indexPath.row]
cell.lblNumber.text = arrCatNum[indexPath.row]
cell.imgvCat.image = UIImage(named: imgvName)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
self.performSegueWithIdentifier("selected", sender: self)
}
func wrapperDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func doneButtonDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func cancelButtonDidPress()
{
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func butCamera(sender: AnyObject)
{
let imagePickerController = ImagePickerController()
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
}
|
88d8e5480ba8bf65c5399f28892386f1
| 23.755556 | 105 | 0.693447 | false | false | false | false |
robocopklaus/sportskanone
|
refs/heads/master
|
Sportskanone/Helpers/UIKitExtensions.swift
|
mit
|
1
|
//
// UIKitExtensions.swift
// Sportskanone
//
// Created by Fabian Pahl on 25/03/2017.
// Copyright © 2017 21st digital GmbH. All rights reserved.
//
import UIKit
extension UIImage {
// TODO: Refactor temporary helper
static func image(forRank rank: Int) -> UIImage? {
let scale = UIScreen.main.scale
let myString: NSString = "\(rank)." as NSString
let font = UIFont.boldSystemFont(ofSize: 26)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle]
let size = CGSize(width: 60, height: 60)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(origin: CGPoint(x: size.width * 0.5 - 26, y: size.height * 0.5 - 16), size: size)
myString.draw(in: rect, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIViewController {
func presentError(error: Error, title: String) {
let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Alert.Button.Cancel.Title".localized, style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
extension UIFont {
static var skHeadline: UIFont {
return UIFont.systemFont(ofSize: 32, weight: UIFontWeightHeavy)
}
static var skLabel: UIFont {
return UIFont.systemFont(ofSize: 18, weight: UIFontWeightBold)
}
static var skText: UIFont {
return UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)
}
static var skDetail: UIFont {
return UIFont.systemFont(ofSize: 12, weight: UIFontWeightLight)
}
static var skTextButton: UIFont {
return UIFont.systemFont(ofSize: 17, weight: UIFontWeightBold)
}
}
extension UIColor {
static var skGreen: UIColor {
return UIColor(red: 76, green: 183, blue: 147)
}
static var skBrown: UIColor {
return UIColor(red: 210, green: 151, blue: 113)
}
static var skBlack: UIColor {
return UIColor(red: 62, green: 67, blue: 71)
}
static var skGray: UIColor {
return UIColor(red: 148, green: 152, blue: 155)
}
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
}
extension UILabel {
@IBInspectable dynamic var fontColor: UIColor {
get {
return textColor
}
set {
textColor = newValue
}
}
dynamic var textFont: UIFont? {
get {
return font
}
set {
font = newValue
}
}
}
extension UIButton {
@IBInspectable dynamic var shadowColor: UIColor? {
get {
guard let shadowColor = layer.shadowColor else {
return nil
}
return UIColor(cgColor: shadowColor)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable dynamic var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable dynamic var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable dynamic var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable dynamic var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable dynamic var borderColor: UIColor? {
get {
guard let borderColor = layer.borderColor else {
return nil
}
return UIColor(cgColor: borderColor)
}
set {
layer.borderColor = newValue?.cgColor
}
}
var title: String? {
get {
return currentTitle
}
set {
setTitle(newValue, for: .normal)
}
}
dynamic var titleFont: UIFont? {
get {
guard let font = titleLabel?.font else {
return nil
}
return font
}
set {
titleLabel?.font = newValue
}
}
}
|
795aecf46575a3e419b52f19e3cbdcde
| 21.082524 | 118 | 0.64102 | false | false | false | false |
Jaelene/IQKeyboardManager
|
refs/heads/master
|
Demo/Swift_Demo/ViewController/TableViewInContainerViewController.swift
|
mit
|
19
|
//
// TableViewInContainerViewController.swift
// IQKeyboardManager
//
// Created by InfoEnum02 on 20/04/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
class TableViewInContainerViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "TestCell"
var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell?.backgroundColor = UIColor.clearColor()
let contentView : UIView! = cell?.contentView
let textField = UITextField(frame: CGRectMake(10,0,contentView.frame.size.width-20,33))
textField.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth
textField.center = contentView.center;
textField.backgroundColor = UIColor.clearColor()
textField.borderStyle = UITextBorderStyle.RoundedRect
textField.tag = 123
cell?.contentView.addSubview(textField)
}
let textField : UITextField = cell!.viewWithTag(123) as! UITextField;
textField.placeholder = "Cell \(indexPath.row)"
return cell!
}
override func shouldAutorotate() -> Bool {
return true
}
}
|
78e244607eac0cf64de6a5ade8c62404
| 34.714286 | 154 | 0.669143 | false | false | false | false |
sugimotoak/ExpressBusTimetable
|
refs/heads/master
|
ExpressBusTimetable/Models/Timetable.swift
|
mit
|
1
|
//
// Timetable.swift
// ExpressBusTimetable
//
// Created by akira on 2/5/17.
// Copyright © 2017 Spreadcontent G.K. All rights reserved.
//
import Foundation
import CSV
import SwiftDate
class Timetable {
enum BusStopStatus {
case ON
case OFF
}
let noneList = ["─", "―"]
let through = "↓"
func isNone(_ string: String) -> Bool {
for none in noneList {
if string == none {
return true
}
}
return false
}
var busStopList = [String]()
var onBusStopList = [String]()
var offBusStopList = [String]()
var busComList = [String]()
var timetable = [[String]]()
var countField = 0
init(fileName: String) {
loadTimetable(fileName)
}
func changeTimetable(fileName: String) {
busStopList = [String]()
onBusStopList = [String]()
offBusStopList = [String]()
busComList = [String]()
timetable = [[String]]()
countField = 0
loadTimetable(fileName)
}
func loadTimetable(_ fileName: String) {
let filePath = Bundle.main.path(forResource: fileName, ofType: "csv")!
let stream = InputStream(fileAtPath: filePath)!
log.debug("file : \(fileName)")
do {
var status: BusStopStatus = .ON
for row in try CSV(stream: stream) {
countField = row.count
log.debug("\(row[0])")
if row[0].isEmpty && onBusStopList.count != 0 {
status = .OFF
}
if !row[0].isEmpty {
switch status {
case .ON:
onBusStopList.append(row[0])
break
case .OFF:
offBusStopList.append(row[0])
break
}
}
if onBusStopList.count == 0 {
for field in row {
busComList.append(field)
}
busComList.remove(at: 0)
for _ in 1..<countField {
timetable.append([String]())
}
} else {
for i in 1..<countField {
timetable[i - 1].append(row[i])
}
}
}
} catch {
log.debug("error")
}
log.debug("\(onBusStopList)")
log.debug("\(offBusStopList)")
busStopList = onBusStopList + [""] + offBusStopList
log.debug("\(busStopList)")
log.debug(countField)
log.debug("\(busComList)")
log.debug("\(timetable)")
}
func getCommuteTimetable(_ onBusStop: String, _ offBusStop: String) -> SectionizedCommuteTimetable {
var onBusStopIndex: Int = 0
var offBusStopIndex: Int = 0
for (index, busStop) in busStopList.enumerated() {
if onBusStop == busStop {
onBusStopIndex = index
}
if offBusStop == busStop {
offBusStopIndex = index
}
}
log.debug("\(onBusStopIndex):\(onBusStop)")
log.debug("\(offBusStopIndex):\(offBusStop)")
var ctList = [CommuteTimetable]()
for row in timetable {
if !isNone(row[onBusStopIndex]) && !isNone(row[offBusStopIndex])
&& row[onBusStopIndex] != through && row[offBusStopIndex] != through {
var destinationBusStop: String = ""
for i in (0..<busStopList.count).reversed() {
if !isNone(row[i]) {
destinationBusStop = busStopList[i]
break
}
}
let ct = CommuteTimetable(row[onBusStopIndex], row[offBusStopIndex], destinationBusStop)
ctList.append(ct)
}
}
return SectionizedCommuteTimetable(ctList)
}
func checkUpDown(_ onBusStop: String, _ offBusStop: String) -> TimetableStatus.UpDown? {
let onBusStopIndex = busStopList.index(of: onBusStop)
let offBusStopIndex = busStopList.index(of: offBusStop)
if onBusStopIndex == nil || offBusStopIndex == nil {
return nil
} else if onBusStopIndex! < offBusStopIndex! {
return TimetableStatus.UpDown.Up
} else if offBusStopIndex! < onBusStopIndex! {
return TimetableStatus.UpDown.Down
}
return nil
}
}
public enum TimetableList: String {
case KIMITSU_TOKYO
case KIMITSU_HANEDA
public static let list: [TimetableList] = [.KIMITSU_TOKYO, .KIMITSU_HANEDA]
public static let nameList = ["青掘駅・君津駅〜東京駅・浜松町駅", "君津駅〜羽田空港"]
func getCsvList() -> [String] {
switch self {
case .KIMITSU_TOKYO:
return ["kimitsu_tokyo_weekday_up", "kimitsu_tokyo_weekday_down", "kimitsu_tokyo_weekend_up", "kimitsu_tokyo_weekend_down"]
case .KIMITSU_HANEDA:
return ["kimitsu_haneda_weekday_up", "kimitsu_haneda_weekday_down", "kimitsu_haneda_weekend_up", "kimitsu_haneda_weekend_down"]
}
}
func getName() -> String {
return TimetableList.nameList[TimetableList.list.index(of: self)!]
}
func getWeekdayUpTimetableCSVName() -> String {
return getCsvList()[0]
}
func getWeekdayDownTimetableCSVName() -> String {
return getCsvList()[1]
}
func getWeekendUpTimetableCSVName() -> String {
return getCsvList()[2]
}
func getWeekendDownTimetableCSVName() -> String {
return getCsvList()[3]
}
}
class WeekdayUpCommuteTimetable: Timetable {
static let sharedInstance = WeekdayUpCommuteTimetable()
private init() {
super.init(fileName: UserDefaults.timetableList.getWeekdayUpTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.timetableList.getWeekdayUpTimetableCSVName())
}
}
class WeekdayDownCommuteTimetable: Timetable {
static let sharedInstance = WeekdayDownCommuteTimetable()
private init() {
super.init(fileName: UserDefaults.timetableList.getWeekdayDownTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.timetableList.getWeekdayDownTimetableCSVName())
}
}
class WeekendUpCommuteTimetable: Timetable {
static let sharedInstance = WeekendUpCommuteTimetable()
private init() {
super.init(fileName: UserDefaults.timetableList.getWeekendUpTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.timetableList.getWeekendUpTimetableCSVName())
}
}
class WeekendDownCommuteTimetable: Timetable {
static let sharedInstance = WeekendDownCommuteTimetable()
private init() {
super.init(fileName: UserDefaults.timetableList.getWeekendDownTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.timetableList.getWeekendDownTimetableCSVName())
}
}
class WeekdayUpSearchTimetable: Timetable {
static let sharedInstance = WeekdayUpSearchTimetable()
private init() {
super.init(fileName: UserDefaults.searchTimetableList.getWeekdayUpTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.searchTimetableList.getWeekdayUpTimetableCSVName())
}
}
class WeekdayDownSearchTimetable: Timetable {
static let sharedInstance = WeekdayDownSearchTimetable()
private init() {
super.init(fileName: UserDefaults.searchTimetableList.getWeekdayDownTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.searchTimetableList.getWeekdayDownTimetableCSVName())
}
}
class WeekendUpSearchTimetable: Timetable {
static let sharedInstance = WeekendUpSearchTimetable()
private init() {
super.init(fileName: UserDefaults.searchTimetableList.getWeekendUpTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.searchTimetableList.getWeekendUpTimetableCSVName())
}
}
class WeekendDownSearchTimetable: Timetable {
static let sharedInstance = WeekendDownSearchTimetable()
private init() {
super.init(fileName: UserDefaults.searchTimetableList.getWeekendDownTimetableCSVName())
}
public func reload() {
super.changeTimetable(fileName: UserDefaults.searchTimetableList.getWeekendDownTimetableCSVName())
}
}
class SectionizedCommuteTimetable {
let commuteTimetableArray: [CommuteTimetable]
var sectionNames = [String]()
var sectionIndexes = [String]()
var array = [[CommuteTimetable]]()
init(_ commuteTimetableArray: [CommuteTimetable]) {
self.commuteTimetableArray = commuteTimetableArray
let now = Date().inRegion(region: Region.init(tz: TimeZoneName.asiaTokyo, cal: CalendarName.gregorian, loc: LocaleName.japaneseJapan))
var isNextBusStopTime = false
var preHour = ""
for ct in commuteTimetableArray {
let hour = ct.onBusStopHour
let minute = ct.onBusStopMinute
if !isNextBusStopTime {
if let time = now.atTime(hour: Int(hour)!, minute: Int(minute)!, second: 0) {
if now < time {
isNextBusStopTime = true
ct.isNext = true
}
}
}
if hour != preHour {
sectionNames.append(hour + ":00")
sectionIndexes.append(hour)
array.append([ct])
} else {
array[array.endIndex - 1].append(ct)
}
preHour = hour
}
}
}
class CommuteTimetable {
let onBusStopTime: String
let offBusStopTime: String
let destinationBusStop: String
var isNext = false
var onOffBusStopTime: String {
return "\(onBusStopTime) - \(offBusStopTime)"
}
var onBusStopHour: String {
return String(onBusStopTime.prefix(2))
}
var onBusStopMinute: String {
return String(onBusStopTime.suffix(2))
}
init(_ onBusStopTime: String, _ offBusStopTime: String, _ destinationBusStop: String) {
self.onBusStopTime = CommuteTimetable.formatTime(onBusStopTime)
self.offBusStopTime = CommuteTimetable.formatTime(offBusStopTime)
self.destinationBusStop = destinationBusStop
}
static func formatTime(_ time: String) -> String {
let addZero = "0" + time
if let range = addZero.range(of: "\\d{2}:\\d{2}", options: .regularExpression, range: nil, locale: .current) {
return String(addZero[range])
}
return time
}
}
|
ce317c0bd18c0e57f1fd1136d713e30e
| 30.874644 | 142 | 0.582588 | false | false | false | false |
dreamsxin/swift
|
refs/heads/master
|
test/decl/subscript/subscripting.swift
|
apache-2.0
|
3
|
// RUN: %target-parse-verify-swift
struct X { } // expected-note * {{did you mean 'X'?}}
// Simple examples
struct X1 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored : Int
subscript (_ : Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored : Int
subscript (i : Int, j : Int) -> Int {
get {
return stored + i + j
}
set(v) {
stored = v + i - j
}
}
}
// Semantic errors
struct Y1 {
var x : X
subscript(i: Int) -> Int {
get {
return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}}
}
set {
x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}}
}
}
}
struct Y2 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
class Y3 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
protocol ProtocolGetSet0 {
subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet1 {
subscript(i: Int) -> Int { get }
}
protocol ProtocolGetSet2 {
subscript(i: Int) -> Int { set } // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet3 {
subscript(i: Int) -> Int { get set }
}
protocol ProtocolGetSet4 {
subscript(i: Int) -> Int { set get }
}
protocol ProtocolWillSetDidSet1 {
subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
subscript(i: Int) -> Int { willSet didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
subscript(i: Int) -> Int { didSet willSet } // expected-error {{expected get or set in a protocol property}}
}
class DidSetInSubscript {
subscript(_: Int) -> Int {
didSet { // expected-error {{didSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
class WillSetInSubscript {
subscript(_: Int) -> Int {
willSet { // expected-error {{willSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
func f() { // expected-note * {{did you mean 'f'?}}
subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
}
struct NoSubscript { }
struct OverloadedSubscript {
subscript(i: Int) -> Int {
get {
return i
}
set {}
}
subscript(i: Int, j: Int) -> Int {
get { return i }
set {}
}
}
struct RetOverloadedSubscript {
subscript(i: Int) -> Int { // expected-note {{found this candidate}}
get { return i }
set {}
}
subscript(i: Int) -> Float { // expected-note {{found this candidate}}
get { return Float(i) }
set {}
}
}
struct MissingGetterSubscript1 {
subscript (i : Int) -> Int {
} // expected-error {{computed property must have accessors specified}}
}
struct MissingGetterSubscript2 {
subscript (i : Int, j : Int) -> Int { // expected-error{{subscript declarations must have a getter}}
set {}
}
}
func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript,
ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) {
no[i] = value // expected-error{{type 'NoSubscript' has no subscript members}}
value = x2[i]
x2[i] = value
value = ovl[i]
ovl[i] = value
value = ovl[(i, j)]
ovl[(i, j)] = value
value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}}
ret[i] // expected-error{{ambiguous use of 'subscript'}}
value = ret[i]
ret[i] = value
}
func subscript_rvalue_materialize(_ i: inout Int) {
i = X1(stored: 0)[i]
}
func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {}
func test_subscript_coerce() {
subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] })
}
struct no_index {
subscript () -> Int { return 42 }
func test() -> Int {
return self[]
}
}
struct tuple_index {
subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) }
func test() -> (Int, Int) {
return self[123, 456]
}
}
struct SubscriptTest1 {
subscript(keyword:String) -> Bool { return true } // expected-note 2 {{found this candidate}}
subscript(keyword:String) -> String? {return nil } // expected-note 2 {{found this candidate}}
}
func testSubscript1(_ s1 : SubscriptTest1) {
let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}}
if s1["hello"] {}
let _ = s1["hello"] // expected-error {{ambiguous use of 'subscript'}}
}
struct SubscriptTest2 {
subscript(a : String, b : Int) -> Int { return 0 }
subscript(a : String, b : String) -> Int { return 0 }
}
func testSubscript1(_ s2 : SubscriptTest2) {
_ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type 'String'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type '(String, Double)'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
// sr-114 & rdar://22007370
class Foo {
subscript(key: String) -> String { // expected-note {{'subscript' previously declared here}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript'}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
}
// <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please
protocol r23952125 {
associatedtype ItemType
var count: Int { get }
subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get set \}}}
var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
// <rdar://problem/16812341> QoI: Poor error message when providing a default value for a subscript parameter
struct S4 {
subscript(subs: Int = 0) -> Int { // expected-error {{default arguments are not allowed in subscripts}}
get {
return 1
}
}
}
|
50b0620146b5437ec5f55dee1f681295
| 24.771626 | 156 | 0.622449 | false | false | false | false |
kazuhiro4949/EditDistance
|
refs/heads/master
|
EditDistance/EditDistance.swift
|
mit
|
1
|
//
// EditDistance.swift
// EditDistance
//
// Copyright (c) 2017 Kazuhiro Hayashi
//
// 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
/// EditDistance calculates a difference between two arrays.
///
/// # Usage
///
/// ## 1. prepare two arrays.
/// ```
/// let a = [["Francis", "Woodruff"]]
/// let b = [["Francis", "Woodruff", "Stanton"]]
/// ```
///
/// ## 2. make EditDistance
/// ```
/// let editDistance = EditDistance(from: a, to: b)
/// ```
///
/// ## calculates edit distance
/// ```
/// editDistance.calculate() // [.common("Francis", [0, 0]), .common("Woodruff", [0, 1]), .add("Stanton", [0, 2])]
/// ```
public struct EditDistance<T: Equatable> {
private let _from: [[T]]
private let _to: [[T]]
/// Create an instance to calculate edit distance with two dimentional arrays.
///
/// - Parameters:
/// - from: starting two dimentional array
/// - to: distination two dimentional array
public init(from: [[T]], to: [[T]]) {
_from = from
_to = to
}
/// Create an instance to calculate edit distance with one dimentional arrays.
///
/// - Parameters:
/// - from: starting one dimentional array
/// - to: distination one dimentional array
public init(from: [T], to: [T]) {
_from = [from]
_to = [to]
}
/// Calculate EditScript with an algorithm defined by EditDistanceAlgorithm protocol.
/// In order to that, you can customize algoritm as you like.
///
/// - Parameter algorithm: how to calculate Edit Distance
/// - Returns: array of commn, insertion and deletion to each the element.
public func calculate<Algorithm: EditDistanceAlgorithm>(with algorithm: Algorithm) -> EditDistanceContainer<T> where Algorithm.Element == T {
return algorithm.calculate(from: _from, to: _to)
}
/// Calculate EditScript with Wu's algorithm.
/// The implementation is based on S.W.Maner, G.Myers, W.Miller, "An O(NP) Sequence Comparison Algorithm"
/// - Returns: array of commn, insertion, deletion to each the element.
public func calculate() -> EditDistanceContainer<T> {
return Wu().calculate(from: _from, to: _to)
}
}
/// proxy type to Array<T: Equatable>.
/// It receives a starting array, after that evaluate resutls with destination array and an algorithm.
public struct EditDistanceProxy<T: Equatable> {
private let _generator: ([T]) -> EditDistance<T>
/// Create object with a starting array
///
/// - Parameter from: starting array
public init(_ from: [T]) {
_generator = { (to: [T]) -> EditDistance<T> in
return EditDistance(from: from, to: to)
}
}
/// calculate Edit Distance with destination array and an algorithm.
///
/// - Parameters:
/// - ary: destination array
/// - algorithm: any algorithm following EditDistanceAlgorithm protocol
/// - Returns: array of commn, insertion and deletion to each the element.
public func compare<Algorithm: EditDistanceAlgorithm>(to ary: [T], with algorithm: Algorithm) -> EditDistanceContainer<T> where Algorithm.Element == T {
return _generator(ary).calculate(with: algorithm)
}
/// calculate Edit Distance with destination array and an algorithm.
///
/// - Parameters:
/// - ary: destination array
/// - algorithm: any algorithm following EditDistanceAlgorithm protocol
/// - Returns: array of commn, insertion and deletion to each the element.
public func compare(to ary: [T]) -> EditDistanceContainer<T> {
return _generator(ary).calculate(with: Wu())
}
}
// MARK: - Array Extension
public extension Array where Element: Equatable {
/// namespace for EditDistance. create EditDistanceProxy object with self.
var diff: EditDistanceProxy<Element> {
return EditDistanceProxy(self)
}
}
|
6366dcd5e73f2778144b7c84be8a9e63
| 35.588235 | 156 | 0.656953 | false | false | false | false |
CodaFi/swift-compiler-crashes
|
refs/heads/master
|
crashes-duplicates/21754-swift-abstractstoragedecl-makecomputed.swift
|
mit
|
11
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( ""
struct c<T where h: Int b. {
var d = .Element = b.e == (t e>: ? {
}
func a<T where h: Int = Swift = .c {
var d {
var d {
protocol c {
func
b T
|
ac95e92c54436b236508eea488729d6c
| 21.642857 | 87 | 0.656151 | false | true | false | false |
Minitour/WWDC-Collaborators
|
refs/heads/master
|
Macintosh.playground/Sources/Utils.swift
|
mit
|
1
|
import Foundation
import UIKit
public class Utils{
class func widthForView(_ text:String, font:UIFont, height:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: height))
label.numberOfLines = 1
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.textAlignment = .center
label.sizeToFit()
return label.frame.width
}
class func heightForView(_ text:String, font:UIFont, width:CGFloat,numberOfLines: Int = 1) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = numberOfLines
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.textAlignment = .center
label.sizeToFit()
return label.frame.height
}
class func getCurrentTime()->String{
let timeFormatter = DateFormatter()
timeFormatter.dateStyle = .none
timeFormatter.timeStyle = .short
return timeFormatter.string(from: Date())
}
class func getExtendTime()->String{
let timeFormatter = DateFormatter()
timeFormatter.dateStyle = .none
timeFormatter.timeStyle = .medium
return timeFormatter.string(from: Date())
}
}
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
public struct SpecificBezierPath{
var path:UIBezierPath
var stroke: Bool
var fill: Bool
var strokeColor: UIColor = .black
var fillColor: UIColor = .clear
}
extension UIImage {
public static func withBezierPath(_ paths: [SpecificBezierPath],
size: CGSize,
scale: CGFloat = UIScreen.main.scale)->UIImage? {
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(size, false, scale)
for item in paths{
if item.fill {
item.fillColor.setFill()
item.path.fill()
}
if item.stroke {
item.strokeColor.setStroke()
item.path.stroke()
}
}
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
public extension CGSize{
public static func + (left: CGSize, right: CGSize)->CGSize{
return CGSize(width: left.width + right.width, height: left.height + right.height)
}
}
|
b31dbf6ba057735de91d99dde1bb35ce
| 32.23913 | 118 | 0.621975 | false | false | false | false |
jverkoey/FigmaKit
|
refs/heads/main
|
Sources/FigmaKit/Hyperlink.swift
|
apache-2.0
|
1
|
/// A Figma hyperlink.
///
/// "A link to either a URL or another frame (node) in the document."
/// https://www.figma.com/developers/api#hyperlink-type
public enum Hyperlink: Codable {
case none
case url(String)
case node(String)
private enum CodingKeys: String, CodingKey {
case type
case url
case nodeID
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Self.CodingKeys)
if let type = try container.decodeIfPresent(HyperlinkType.self, forKey: .type) {
switch type {
case .url:
self = .url(try container.decode(String.self, forKey: .url))
case .node:
self = .node(try container.decode(String.self, forKey: .nodeID))
}
} else {
self = .none
}
}
public func encode(to encoder: Encoder) throws {
fatalError("Not implemented")
}
public enum HyperlinkType: String, Codable {
case url = "URL"
case node = "NODE"
}
}
|
e6b200b9d850788b9aac30de1fb85f20
| 23.225 | 84 | 0.644995 | false | false | false | false |
Witcast/witcast-ios
|
refs/heads/develop
|
Pods/PullToRefreshKit/Source/Classes/ElasticRefreshControl.swift
|
apache-2.0
|
1
|
//
// ElasticRefreshControl.swift
// SWTest
//
// Created by huangwenchen on 16/7/29.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class ElasticRefreshControl: UIView {
//目标,height 80, 高度 40
open let spinner:UIActivityIndicatorView = UIActivityIndicatorView()
var radius:CGFloat{
get{
return totalHeight / 4 - margin
}
}
open var progress:CGFloat = 0.0{
didSet{
setNeedsDisplay()
}
}
open var margin:CGFloat = 4.0{
didSet{
setNeedsDisplay()
}
}
var arrowRadius:CGFloat{
get{
return radius * 0.5 - 0.2 * radius * adjustedProgress
}
}
var adjustedProgress:CGFloat{
get{
return min(max(progress,0.0),1.0)
}
}
let totalHeight:CGFloat = 80
open var arrowColor = UIColor.white{
didSet{
setNeedsDisplay()
}
}
open var elasticTintColor = UIColor.init(white: 0.5, alpha: 0.6){
didSet{
setNeedsDisplay()
}
}
var animating = false{
didSet{
if animating{
spinner.startAnimating()
setNeedsDisplay()
}else{
spinner.stopAnimating()
setNeedsDisplay()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
self.isOpaque = false
addSubview(spinner)
sizeToFit()
spinner.hidesWhenStopped = true
spinner.activityIndicatorViewStyle = .gray
}
open override func layoutSubviews() {
super.layoutSubviews()
spinner.center = CGPoint(x: self.bounds.width / 2.0, y: 0.75 * totalHeight)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func sinCGFloat(_ angle:CGFloat)->CGFloat{
let result = sinf(Float(angle))
return CGFloat(result)
}
func cosCGFloat(_ angle:CGFloat)->CGFloat{
let result = cosf(Float(angle))
return CGFloat(result)
}
open override func draw(_ rect: CGRect) {
//如果在Animating,则什么都不做
if animating {
super.draw(rect)
return
}
let context = UIGraphicsGetCurrentContext()
let centerX = rect.width/2.0
let lineWidth = 2.5 - 1.0 * adjustedProgress
//上面圆的信息
let upCenter = CGPoint(x: centerX, y: (0.75 - 0.5 * adjustedProgress) * totalHeight)
let upRadius = radius - radius * 0.3 * adjustedProgress
//下面圆的信息
let downRadius:CGFloat = radius - radius * 0.75 * adjustedProgress
let downCenter = CGPoint(x: centerX, y: totalHeight - downRadius - margin)
//偏移的角度
let offSetAngle:CGFloat = CGFloat.pi / 2.0 / 12.0
//计算上面圆的左/右的交点坐标
let upP1 = CGPoint(x: upCenter.x - upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
let upP2 = CGPoint(x: upCenter.x + upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
//计算下面的圆左/右叫点坐标
let downP1 = CGPoint(x: downCenter.x - downRadius * cosCGFloat(offSetAngle), y: downCenter.y - downRadius * sinCGFloat(offSetAngle))
//计算Control Point
let controPonintLeft = CGPoint(x: downCenter.x - downRadius, y: (downCenter.y + upCenter.y)/2)
let controPonintRight = CGPoint(x: downCenter.x + downRadius, y: (downCenter.y + upCenter.y)/2)
//实际绘制
context?.setFillColor(elasticTintColor.cgColor)
context?.addArc(center: upCenter, radius: upRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: false)
context?.move(to: CGPoint(x: upP1.x, y: upP1.y))
context?.addQuadCurve(to: downP1, control: controPonintLeft)
context?.addArc(center: downCenter, radius: downRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: true)
context?.addQuadCurve(to: upP2, control: controPonintRight)
context?.fillPath()
//绘制箭头
context?.setStrokeColor(arrowColor.cgColor)
context?.setLineWidth(lineWidth)
context?.addArc(center: upCenter, radius: arrowRadius, startAngle: 0, endAngle: CGFloat.pi * 1.5, clockwise: false)
context?.strokePath()
context?.setFillColor(arrowColor.cgColor)
context?.setLineWidth(0.0)
context?.move(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius + lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x + lineWidth * 0.865 * 3, y: upCenter.y - arrowRadius))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.fillPath()
}
override open func sizeToFit() {
var width = frame.size.width
if width < 30.0{
width = 30.0
}
self.frame = CGRect(x: frame.origin.x, y: frame.origin.y,width: width, height: totalHeight)
}
}
|
e369f0ba0a2c5382b64a86a3cd639e6e
| 33.796053 | 142 | 0.599546 | false | false | false | false |
radu-costea/ATests
|
refs/heads/master
|
ATests/ATests/Model/ParseExamAnswer.swift
|
mit
|
1
|
//
// PFExamAnswer.swift
// ATests
//
// Created by Radu Costea on 18/06/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
class ParseExamAnswer: PFObject, PFSubclassing {
static func parseClassName() -> String {
return "ParseExamAnswer"
}
}
extension ParseExamAnswer {
@NSManaged var question: ParseExamQuestion
@NSManaged var parseAnswer: [PFObject]?
@NSManaged var result: Float
convenience init(question: ParseExamQuestion, answer: PFObject?) {
self.init()
self.question = question
self.answer = answer
}
var answer: PFObject? {
get { return parseAnswer?.first }
set {
guard let newContent = newValue else {
parseAnswer = nil
return
}
parseAnswer = [newContent]
}
}
}
|
888670e987207b2993f513d5b99f0640
| 21.717949 | 70 | 0.60226 | false | false | false | false |
lkuczborski/Beacon_Workshop
|
refs/heads/master
|
PorkKit/PorkKit/Pork.swift
|
mit
|
1
|
//
// Beacon.swift
// ProkKit
//
// Created by Lukasz Stocki on 10/02/16.
// Copyright © 2016 A.C.M.E. All rights reserved.
//
import Foundation
import CoreLocation;
public struct Pork {
public private(set) var major : CLBeaconMajorValue
public private(set) var minor : CLBeaconMinorValue
public private(set) var proximity: CLProximity
public private(set) var rssi : Int
public private(set) var uuid : String
public private(set) var accuracy: CLLocationAccuracy {
willSet {
if case let newAccuracy = newValue where newAccuracy != self.accuracy && newAccuracy != -1 {
self.accuracy = newAccuracy
}
}
}
init(uuid: String, major: CLBeaconMajorValue, minor: CLBeaconMinorValue) {
self.uuid = uuid
self.major = major
self.minor = minor
proximity = .unknown
rssi = 0
accuracy = -1;
}
init(beacon: CLBeacon) {
self.init(uuid: beacon.proximityUUID.uuidString,
major: CLBeaconMajorValue(beacon.major.intValue),
minor: CLBeaconMinorValue(beacon.minor.intValue))
proximity = beacon.proximity
accuracy = beacon.accuracy
rssi = beacon.rssi
}
}
extension Pork : Equatable {
}
public func ==(lhs: Pork, rhs: Pork) -> Bool {
if lhs.uuid != rhs.uuid {
return false
}
if lhs.major != lhs.major {
return false
}
if lhs.minor != rhs.minor {
return false
}
return true
}
extension Pork: CustomStringConvertible {
public var description: String {
return "UUID: \(self.uuid) Major: \(self.major) Minor: \(self.minor)"
}
}
extension Pork: CustomDebugStringConvertible {
public var debugDescription: String {
return self.description
}
}
extension CLBeacon {
var baseData: String {
return "UUID: \(self.proximityUUID.uuidString) Major: \(self.major) Minor: \(self.minor)"
}
}
|
dd1f0659ef1d9eec8491260700ba3bc5
| 22.453488 | 104 | 0.609817 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Constraints/operator_availability.swift
|
apache-2.0
|
56
|
// RUN: %target-typecheck-verify-swift -swift-version 4
// rdar://problem/31592529
infix operator <=< : BitwiseShiftPrecedence
infix operator >=> : BitwiseShiftPrecedence
public protocol P {}
extension P {
public static func <=< <Other : P>(_ x: Self, _ y: Other) { }
@available(swift, obsoleted: 4)
public static func >=> <Other : P>(_ x: Self, _ y: Other) { }
}
extension Int : P {}
extension Int32 : P {}
extension Int32 {
@available(swift, obsoleted: 4)
public static func <=< (_ x: Int32, _ y: Int32) {}
@available(swift, obsoleted: 4)
public static func >=> (_ x: Int32, _ y: Int32) {} // expected-note{{'>=>' was obsoleted in Swift 4}}
}
func testAvailability() {
_ = (1 as Int32) <=< (1 as Int32) // okay
_ = (1 as Int32) >=> (1 as Int32) // expected-error{{'>=>' is unavailable}}
}
|
455323d205c3b5fe48c52ad56e69309e
| 25.516129 | 103 | 0.615572 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothHCI/HCILEDataLengthChange.swift
|
mit
|
1
|
//
// HCILEDataLengthChange.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// LE Data Length Change Event
///
/// event notifies the Host of a change to either the maximum Payload length or the maximum transmission time of packets
/// in either direction. The values reported are the maximum that will actually be used on the connection following the change,
/// except that on the LE Coded PHY a packet taking up to 2704 μs to transmit may be sent even though the corresponding
/// parameter has a lower value.
@frozen
public struct HCILEDataLengthChange: HCIEventParameter {
public static let event = LowEnergyEvent.dataLengthChange // 0x07
public static let length: Int = 10
public let handle: UInt16 // Connection_Handle
/// The maximum number of payload octets in a Link Layer packet that the local Controller will send on this connection
/// (connEffectiveMaxTxOctets defined in [Vol 6] Part B, Section 4.5.10).
/// onnInitialMaxTxOctets - the value of connMaxTxOctets that the Controller will use for a new connection.
/// Range 0x001B-0x00FB (all other values reserved for future use)
public let maxTxOctets: UInt16
/// The maximum time that the local Controller will take to send a Link Layer packet on this connection
/// (connEffectiveMaxTxTime defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxTxTime - equal to connEffectiveMaxTxTimeUncoded while the connection is on an LE Uncoded PHY
/// and equal to connEffectiveMaxTxTimeCoded while the connection is on the LE Coded PHY.
public let maxTxTime: UInt16
/// The maximum number of payload octets in a Link Layer packet that the local Controller expects to receive on
/// this connection (connEffectiveMaxRxOctets defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxRxOctets - the lesser of connMaxRxOctets and connRemoteMaxTxOctets.
public let maxRxOctets: UInt16
/// The maximum time that the local Controller expects to take to receive a Link Layer packet on this
/// connection (connEffectiveMaxRxTime defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxRxTime - equal to connEffectiveMaxRxTimeUncoded while the connection is on an LE Uncoded PHY
/// and equal to connEffectiveMaxRxTimeCoded while the connection is on the LE Coded PHY.
public let maxRxTime: UInt16
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let handle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))
let maxTxOctets = UInt16(littleEndian: UInt16(bytes: (data[2], data[3])))
let maxTxTime = UInt16(littleEndian: UInt16(bytes: (data[4], data[5])))
let maxRxOctets = UInt16(littleEndian: UInt16(bytes: (data[6], data[7])))
let maxRxTime = UInt16(littleEndian: UInt16(bytes: (data[8], data[9])))
self.handle = handle
self.maxTxOctets = maxTxOctets
self.maxTxTime = maxTxTime
self.maxRxOctets = maxRxOctets
self.maxRxTime = maxRxTime
}
}
|
59d8591f78466387cbc179d673b2f68c
| 47.878788 | 127 | 0.708617 | false | false | false | false |
imryan/swifty-tinder
|
refs/heads/master
|
SwiftyTinder/Classes/Models/STProfile.swift
|
mit
|
1
|
//
// STProfile.swift
// SwiftyTinder
//
// Created by Ryan Cohen on 7/31/16.
// Copyright © 2016 Ryan Cohen. All rights reserved.
//
import Foundation
public class STProfile {
public enum STGenderType: Int {
case STGenderTypeMale = 0
case STGenderTypeFemale = 1
}
public struct STInterest {
var id: String
var name: String
}
public struct STJob {
var companyId: String?
var company: String?
var titleId: String?
var title: String?
}
public struct STSchool {
var id: String?
var name: String?
var year: String?
var type: String?
}
public struct STPhoto {
enum STPhotoSize: Int {
case Size640 = 0
case Size320 = 1
case Size172 = 2
case Size84 = 3
}
var photoURL: String?
// [640x640], 320x320, 172x172, 84x84 are resolutions
// => photos[i]["processed_files"][x]["url"]
func photoWithSize(size: STPhotoSize) -> STPhoto {
return STPhoto(photoURL: nil)
}
}
public var id: String
public var name: String
public var birthdate: String // => "1996-09-04T00:00:00.000Z"
public var distance: Int?
public var bio: String
public var gender: STGenderType
public var photos: [STPhoto] = []
public var jobs: [STJob]? = []
public var schools: [STSchool]? = []
init(dictionary: NSDictionary) {
self.id = dictionary["_id"] as! String
self.name = dictionary["name"] as! String
self.birthdate = dictionary["birth_date"] as! String
self.distance = dictionary["distance_mi"] as? Int
self.bio = dictionary["bio"] as! String
self.gender = STGenderType(rawValue: dictionary["gender"] as! Int)!
for photo in dictionary["photos"] as! [NSDictionary] {
let photoURL = photo["url"] as! String
let photoObject = STPhoto(photoURL: photoURL)
photos.append(photoObject)
}
for job in dictionary["jobs"] as! [NSDictionary] {
let companyId = job["company"]?["id"] as? String
let companyName = job["company"]?["name"] as? String
let jobId = job["title"]?["id"] as? String
let jobName = job["title"]?["name"] as? String
let job = STJob(companyId: companyId, company: companyName, titleId: jobId, title: jobName)
jobs?.append(job)
}
for school in dictionary["schools"] as! [NSDictionary] {
let schoolId = school["id"] as? String
let schoolName = school["name"] as? String
let schoolYear = school["year"] as? String
let schoolType = school["type"] as? String
let school = STSchool(id: schoolId, name: schoolName, year: schoolYear, type: schoolType)
schools?.append(school)
}
}
}
|
28858f901071594615bcca9c6a433e9b
| 28.825243 | 103 | 0.549658 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/ScrollViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ScrollViewDelegate
//
// Created by 伯驹 黄 on 2016/10/10.
// Copyright © 2016年 伯驹 黄. All rights reserved.
//
import UIKit
class ScrollViewController: UIViewController {
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: self.view.frame)
scrollView.backgroundColor = UIColor.groupTableViewBackground
scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height * 5)
scrollView.delegate = self
return scrollView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let plateView = UIView()
view.addSubview(plateView)
view.addSubview(scrollView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func logDraggingAndDecelerating() {
print(scrollView.isDragging ? "dragging" : "", scrollView.isDecelerating ? "decelerating" : "")
}
}
extension ScrollViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let velocityValue = NSValue(cgPoint: velocity)
let targetContentOffsetValue = NSValue(cgPoint: targetContentOffset.move())
print("velocityValue=\(velocityValue), targetContentOffsetValue=\(targetContentOffsetValue)")
logDraggingAndDecelerating()
print("🍀🍀🍀\(#function)🍀🍀🍀")
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
// 点击statusBar调用
return true
}
func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
print("🍀🍀🍀\(#function)🍀🍀🍀")
logDraggingAndDecelerating()
}
}
|
a0180da84e903d4e5597b827a8d4fc0d
| 30.655556 | 148 | 0.657424 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS
|
refs/heads/develop
|
WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Gutenberg/GutenpackConverter.swift
|
gpl-2.0
|
2
|
import Aztec
import Foundation
public extension Element {
static let gutenpack = Element("gutenpack")
}
public class GutenpackConverter: ElementConverter {
// MARK: - ElementConverter
public func convert(
_ element: ElementNode,
inheriting attributes: [NSAttributedString.Key: Any],
contentSerializer serialize: ContentSerializer) -> NSAttributedString {
precondition(element.type == .gutenpack)
let decoder = GutenbergAttributeDecoder()
guard let content = decoder.attribute(.selfCloser, from: element) else {
let serializer = HTMLSerializer()
let attachment = HTMLAttachment()
attachment.rootTagName = element.name
attachment.rawHTML = serializer.serialize(element)
let representation = NSAttributedString(attachment: attachment, attributes: attributes)
return serialize(element, representation, attributes, false)
}
let blockContent = String(content[content.startIndex ..< content.index(before: content.endIndex)])
let blockName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in
char != " "
}))
let attachment = GutenpackAttachment(name: blockName, content: blockContent)
let representation = NSAttributedString(attachment: attachment, attributes: attributes)
return serialize(element, representation, attributes, false)
}
}
|
30e1b31c78b975643e3c8b5f1a0d9561
| 35.511628 | 120 | 0.653503 | false | false | false | false |
spweau/Test_DYZB
|
refs/heads/master
|
Test_DYZB/Test_DYZB/Classes/Tool/Extention/UIBarButtonItem-Extention.swift
|
mit
|
1
|
//
// UIBarButtonItem-Extention.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/22.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
// // 1. 扩充 类方法
// class func createItem(imageName: String , hightImageName : String , size: CGSize) -> UIBarButtonItem {
//
// let btn = UIButton()
// btn.setImage(UIImage(named:imageName), for: .normal)
// btn.setImage(UIImage(named:hightImageName), for: .highlighted)
// btn.frame = CGRect(origin: CGPoint(x:0,y:0), size: size)
// btn.backgroundColor = UIColor.red
// return UIBarButtonItem(customView: btn)
// }
// 2. 扩充 构造方法
// 便利构造函数
// 1. convenience 开头
// 2. 在构造函数中必须明确为调用一个设计的构造函数(并且这个设计的构造函数是使用self来调用的)
convenience init(imageName: String , hightImageName : String = "" , size:CGSize = CGSize(width: 0, height: 0)) {
// 1. 创建UIButton
let btn = UIButton()
// 2. btn 的图片
btn.setImage(UIImage(named:imageName), for: .normal)
if hightImageName != "" {
btn.setImage(UIImage(named:hightImageName), for: .highlighted)
}
// 3. 设置 frame
if size == CGSize(width: 0, height: 0) {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint(x:0,y:0), size: size)
}
btn.backgroundColor = UIColor.red
// 4. 创建 UIBarButtonItem
self.init(customView: btn)
}
}
|
f667b3cc5c82c563ebbb71bc7c5ee165
| 24.645161 | 118 | 0.545283 | false | false | false | false |
radvansky-tomas/NutriFacts
|
refs/heads/master
|
nutri-facts/nutri-facts/Helpers/Globals.swift
|
gpl-2.0
|
1
|
// Created by Tomas Radvansky on 21/01/2015.
// Copyright (c) 2015 Tomas Radvansky. All rights reserved.//
import UIKit
//Icomoon enumeration
enum MoonIcons:String {case home = "\u{e900}"
case home2 = "\u{e901}"
case home3 = "\u{e902}"
case office = "\u{e903}"
case newspaper = "\u{e904}"
case pencil = "\u{e905}"
case pencil2 = "\u{e906}"
case quill = "\u{e907}"
case pen = "\u{e908}"
case blog = "\u{e909}"
case eyedropper = "\u{e90a}"
case droplet = "\u{e90b}"
case paint_format = "\u{e90c}"
case image = "\u{e90d}"
case images = "\u{e90e}"
case camera = "\u{e90f}"
case headphones = "\u{e910}"
case music = "\u{e911}"
case play = "\u{e912}"
case film = "\u{e913}"
case video_camera = "\u{e914}"
case dice = "\u{e915}"
case pacman = "\u{e916}"
case spades = "\u{e917}"
case clubs = "\u{e918}"
case diamonds = "\u{e919}"
case bullhorn = "\u{e91a}"
case connection = "\u{e91b}"
case podcast = "\u{e91c}"
case feed = "\u{e91d}"
case mic = "\u{e91e}"
case book = "\u{e91f}"
case books = "\u{e920}"
case library = "\u{e921}"
case file_text = "\u{e922}"
case profile = "\u{e923}"
case file_empty = "\u{e924}"
case files_empty = "\u{e925}"
case file_text2 = "\u{e926}"
case file_picture = "\u{e927}"
case file_music = "\u{e928}"
case file_play = "\u{e929}"
case file_video = "\u{e92a}"
case file_zip = "\u{e92b}"
case copy = "\u{e92c}"
case paste = "\u{e92d}"
case stack = "\u{e92e}"
case folder = "\u{e92f}"
case folder_open = "\u{e930}"
case folder_plus = "\u{e931}"
case folder_minus = "\u{e932}"
case folder_download = "\u{e933}"
case folder_upload = "\u{e934}"
case price_tag = "\u{e935}"
case price_tags = "\u{e936}"
case barcode = "\u{e937}"
case qrcode = "\u{e938}"
case ticket = "\u{e939}"
case cart = "\u{e93a}"
case coin_dollar = "\u{e93b}"
case coin_euro = "\u{e93c}"
case coin_pound = "\u{e93d}"
case coin_yen = "\u{e93e}"
case credit_card = "\u{e93f}"
case calculator = "\u{e940}"
case lifebuoy = "\u{e941}"
case phone = "\u{e942}"
case phone_hang_up = "\u{e943}"
case address_book = "\u{e944}"
case envelop = "\u{e945}"
case pushpin = "\u{e946}"
case location = "\u{e947}"
case location2 = "\u{e948}"
case compass = "\u{e949}"
case compass2 = "\u{e94a}"
case map = "\u{e94b}"
case map2 = "\u{e94c}"
case history = "\u{e94d}"
case clock = "\u{e94e}"
case clock2 = "\u{e94f}"
case alarm = "\u{e950}"
case bell = "\u{e951}"
case stopwatch = "\u{e952}"
case calendar = "\u{e953}"
case printer = "\u{e954}"
case keyboard = "\u{e955}"
case display = "\u{e956}"
case laptop = "\u{e957}"
case mobile = "\u{e958}"
case mobile2 = "\u{e959}"
case tablet = "\u{e95a}"
case tv = "\u{e95b}"
case drawer = "\u{e95c}"
case drawer2 = "\u{e95d}"
case box_add = "\u{e95e}"
case box_remove = "\u{e95f}"
case download = "\u{e960}"
case upload = "\u{e961}"
case floppy_disk = "\u{e962}"
case drive = "\u{e963}"
case database = "\u{e964}"
case undo = "\u{e965}"
case redo = "\u{e966}"
case undo2 = "\u{e967}"
case redo2 = "\u{e968}"
case forward = "\u{e969}"
case reply = "\u{e96a}"
case bubble = "\u{e96b}"
case bubbles = "\u{e96c}"
case bubbles2 = "\u{e96d}"
case bubble2 = "\u{e96e}"
case bubbles3 = "\u{e96f}"
case bubbles4 = "\u{e970}"
case user = "\u{e971}"
case users = "\u{e972}"
case user_plus = "\u{e973}"
case user_minus = "\u{e974}"
case user_check = "\u{e975}"
case user_tie = "\u{e976}"
case quotes_left = "\u{e977}"
case quotes_right = "\u{e978}"
case hour_glass = "\u{e979}"
case spinner = "\u{e97a}"
case spinner2 = "\u{e97b}"
case spinner3 = "\u{e97c}"
case spinner4 = "\u{e97d}"
case spinner5 = "\u{e97e}"
case spinner6 = "\u{e97f}"
case spinner7 = "\u{e980}"
case spinner8 = "\u{e981}"
case spinner9 = "\u{e982}"
case spinner10 = "\u{e983}"
case spinner11 = "\u{e984}"
case binoculars = "\u{e985}"
case search = "\u{e986}"
case zoom_in = "\u{e987}"
case zoom_out = "\u{e988}"
case enlarge = "\u{e989}"
case shrink = "\u{e98a}"
case enlarge2 = "\u{e98b}"
case shrink2 = "\u{e98c}"
case key = "\u{e98d}"
case key2 = "\u{e98e}"
case lock = "\u{e98f}"
case unlocked = "\u{e990}"
case wrench = "\u{e991}"
case equalizer = "\u{e992}"
case equalizer2 = "\u{e993}"
case cog = "\u{e994}"
case cogs = "\u{e995}"
case hammer = "\u{e996}"
case magic_wand = "\u{e997}"
case aid_kit = "\u{e998}"
case bug = "\u{e999}"
case pie_chart = "\u{e99a}"
case stats_dots = "\u{e99b}"
case stats_bars = "\u{e99c}"
case stats_bars2 = "\u{e99d}"
case trophy = "\u{e99e}"
case gift = "\u{e99f}"
case glass = "\u{e9a0}"
case glass2 = "\u{e9a1}"
case mug = "\u{e9a2}"
case spoon_knife = "\u{e9a3}"
case leaf = "\u{e9a4}"
case rocket = "\u{e9a5}"
case meter = "\u{e9a6}"
case meter2 = "\u{e9a7}"
case hammer2 = "\u{e9a8}"
case fire = "\u{e9a9}"
case lab = "\u{e9aa}"
case magnet = "\u{e9ab}"
case bin = "\u{e9ac}"
case bin2 = "\u{e9ad}"
case briefcase = "\u{e9ae}"
case airplane = "\u{e9af}"
case truck = "\u{e9b0}"
case road = "\u{e9b1}"
case accessibility = "\u{e9b2}"
case target = "\u{e9b3}"
case shield = "\u{e9b4}"
case power = "\u{e9b5}"
case power_cord = "\u{e9b7}"
case clipboard = "\u{e9b8}"
case list_numbered = "\u{e9b9}"
case list = "\u{e9ba}"
case list2 = "\u{e9bb}"
case tree = "\u{e9bc}"
case menu = "\u{e9bd}"
case menu2 = "\u{e9be}"
case menu3 = "\u{e9bf}"
case menu4 = "\u{e9c0}"
case cloud = "\u{e9c1}"
case cloud_download = "\u{e9c2}"
case cloud_upload = "\u{e9c3}"
case cloud_check = "\u{e9c4}"
case download2 = "\u{e9c5}"
case upload2 = "\u{e9c6}"
case download3 = "\u{e9c7}"
case upload3 = "\u{e9c8}"
case sphere = "\u{e9c9}"
case earth = "\u{e9ca}"
case link = "\u{e9cb}"
case flag = "\u{e9cc}"
case attachment = "\u{e9cd}"
case eye = "\u{e9ce}"
case eye_plus = "\u{e9cf}"
case eye_minus = "\u{e9d0}"
case eye_blocked = "\u{e9d1}"
case bookmark = "\u{e9d2}"
case bookmarks = "\u{e9d3}"
case sun = "\u{e9d4}"
case contrast = "\u{e9d5}"
case brightness_contrast = "\u{e9d6}"
case star_empty = "\u{e9d7}"
case star_half = "\u{e9d8}"
case star_full = "\u{e9d9}"
case heart = "\u{e9da}"
case heart_broken = "\u{e9db}"
case man = "\u{e9dc}"
case woman = "\u{e9dd}"
case man_woman = "\u{e9de}"
case happy = "\u{e9df}"
case happy2 = "\u{e9e0}"
case smile = "\u{e9e1}"
case smile2 = "\u{e9e2}"
case tongue = "\u{e9e3}"
case tongue2 = "\u{e9e4}"
case sad = "\u{e9e5}"
case sad2 = "\u{e9e6}"
case wink = "\u{e9e7}"
case wink2 = "\u{e9e8}"
case grin = "\u{e9e9}"
case grin2 = "\u{e9ea}"
case cool = "\u{e9eb}"
case cool2 = "\u{e9ec}"
case angry = "\u{e9ed}"
case angry2 = "\u{e9ee}"
case evil = "\u{e9ef}"
case evil2 = "\u{e9f0}"
case shocked = "\u{e9f1}"
case shocked2 = "\u{e9f2}"
case baffled = "\u{e9f3}"
case baffled2 = "\u{e9f4}"
case confused = "\u{e9f5}"
case confused2 = "\u{e9f6}"
case neutral = "\u{e9f7}"
case neutral2 = "\u{e9f8}"
case hipster = "\u{e9f9}"
case hipster2 = "\u{e9fa}"
case wondering = "\u{e9fb}"
case wondering2 = "\u{e9fc}"
case sleepy = "\u{e9fd}"
case sleepy2 = "\u{e9fe}"
case frustrated = "\u{e9ff}"
case frustrated2 = "\u{ea00}"
case crying = "\u{ea01}"
case crying2 = "\u{ea02}"
case point_up = "\u{ea03}"
case point_right = "\u{ea04}"
case point_down = "\u{ea05}"
case point_left = "\u{ea06}"
case warning = "\u{ea07}"
case notification = "\u{ea08}"
case question = "\u{ea09}"
case plus = "\u{ea0a}"
case minus = "\u{ea0b}"
case info = "\u{ea0c}"
case cancel_circle = "\u{ea0d}"
case blocked = "\u{ea0e}"
case cross = "\u{ea0f}"
case checkmark = "\u{ea10}"
case checkmark2 = "\u{ea11}"
case spell_check = "\u{ea12}"
case enter = "\u{ea13}"
case exit = "\u{ea14}"
case play2 = "\u{ea15}"
case pause = "\u{ea16}"
case stop = "\u{ea17}"
case previous = "\u{ea18}"
case next = "\u{ea19}"
case backward = "\u{ea1a}"
case forward2 = "\u{ea1b}"
case play3 = "\u{ea1c}"
case pause2 = "\u{ea1d}"
case stop2 = "\u{ea1e}"
case backward2 = "\u{ea1f}"
case forward3 = "\u{ea20}"
case first = "\u{ea21}"
case last = "\u{ea22}"
case previous2 = "\u{ea23}"
case next2 = "\u{ea24}"
case eject = "\u{ea25}"
case volume_high = "\u{ea26}"
case volume_medium = "\u{ea27}"
case volume_low = "\u{ea28}"
case volume_mute = "\u{ea29}"
case volume_mute2 = "\u{ea2a}"
case volume_increase = "\u{ea2b}"
case volume_decrease = "\u{ea2c}"
case loop = "\u{ea2d}"
case loop2 = "\u{ea2e}"
case infinite = "\u{ea2f}"
case shuffle = "\u{ea30}"
case arrow_up_left = "\u{ea31}"
case arrow_up = "\u{ea32}"
case arrow_up_right = "\u{ea33}"
case arrow_right = "\u{ea34}"
case arrow_down_right = "\u{ea35}"
case arrow_down = "\u{ea36}"
case arrow_down_left = "\u{ea37}"
case arrow_left = "\u{ea38}"
case arrow_up_left2 = "\u{ea39}"
case arrow_up2 = "\u{ea3a}"
case arrow_up_right2 = "\u{ea3b}"
case arrow_right2 = "\u{ea3c}"
case arrow_down_right2 = "\u{ea3d}"
case arrow_down2 = "\u{ea3e}"
case arrow_down_left2 = "\u{ea3f}"
case arrow_left2 = "\u{ea40}"
case circle_up = "\u{ea41}"
case circle_right = "\u{ea42}"
case circle_down = "\u{ea43}"
case circle_left = "\u{ea44}"
case tab = "\u{ea45}"
case move_up = "\u{ea46}"
case move_down = "\u{ea47}"
case sort_alpha_asc = "\u{ea48}"
case sort_alpha_desc = "\u{ea49}"
case sort_numeric_asc = "\u{ea4a}"
case sort_numberic_desc = "\u{ea4b}"
case sort_amount_asc = "\u{ea4c}"
case sort_amount_desc = "\u{ea4d}"
case command = "\u{ea4e}"
case shift = "\u{ea4f}"
case ctrl = "\u{ea50}"
case opt = "\u{ea51}"
case checkbox_checked = "\u{ea52}"
case checkbox_unchecked = "\u{ea53}"
case radio_checked = "\u{ea54}"
case radio_checked2 = "\u{ea55}"
case radio_unchecked = "\u{ea56}"
case crop = "\u{ea57}"
case make_group = "\u{ea58}"
case ungroup = "\u{ea59}"
case scissors = "\u{ea5a}"
case filter = "\u{ea5b}"
case font = "\u{ea5c}"
case ligature = "\u{ea5d}"
case ligature2 = "\u{ea5e}"
case text_height = "\u{ea5f}"
case text_width = "\u{ea60}"
case font_size = "\u{ea61}"
case bold = "\u{ea62}"
case underline = "\u{ea63}"
case italic = "\u{ea64}"
case strikethrough = "\u{ea65}"
case omega = "\u{ea66}"
case sigma = "\u{ea67}"
case page_break = "\u{ea68}"
case superscript = "\u{ea69}"
case superscript2 = "\u{ea6b}"
case subscript2 = "\u{ea6c}"
case text_color = "\u{ea6d}"
case pagebreak = "\u{ea6e}"
case clear_formatting = "\u{ea6f}"
case table = "\u{ea70}"
case table2 = "\u{ea71}"
case insert_template = "\u{ea72}"
case pilcrow = "\u{ea73}"
case ltr = "\u{ea74}"
case rtl = "\u{ea75}"
case section = "\u{ea76}"
case paragraph_left = "\u{ea77}"
case paragraph_center = "\u{ea78}"
case paragraph_right = "\u{ea79}"
case paragraph_justify = "\u{ea7a}"
case indent_increase = "\u{ea7b}"
case indent_decrease = "\u{ea7c}"
case share = "\u{ea7d}"
case new_tab = "\u{ea7e}"
case embed = "\u{ea7f}"
case embed2 = "\u{ea80}"
case terminal = "\u{ea81}"
case share2 = "\u{ea82}"
case mail = "\u{ea83}"
case mail2 = "\u{ea84}"
case mail3 = "\u{ea85}"
case mail4 = "\u{ea86}"
case google = "\u{ea87}"
case google_plus = "\u{ea88}"
case google_plus2 = "\u{ea89}"
case google_plus3 = "\u{ea8a}"
case google_drive = "\u{ea8b}"
case facebook = "\u{ea8c}"
case facebook2 = "\u{ea8d}"
case facebook3 = "\u{ea8e}"
case ello = "\u{ea8f}"
case instagram = "\u{ea90}"
case twitter = "\u{ea91}"
case twitter2 = "\u{ea92}"
case twitter3 = "\u{ea93}"
case feed2 = "\u{ea94}"
case feed3 = "\u{ea95}"
case feed4 = "\u{ea96}"
case youtube = "\u{ea97}"
case youtube2 = "\u{ea98}"
case youtube3 = "\u{ea99}"
case youtube4 = "\u{ea9a}"
case twitch = "\u{ea9b}"
case vimeo = "\u{ea9c}"
case vimeo2 = "\u{ea9d}"
case vimeo3 = "\u{ea9e}"
case lanyrd = "\u{ea9f}"
case flickr = "\u{eaa0}"
case flickr2 = "\u{eaa1}"
case flickr3 = "\u{eaa2}"
case flickr4 = "\u{eaa3}"
case picassa = "\u{eaa4}"
case picassa2 = "\u{eaa5}"
case dribbble = "\u{eaa6}"
case dribbble2 = "\u{eaa7}"
case dribbble3 = "\u{eaa8}"
case forrst = "\u{eaa9}"
case forrst2 = "\u{eaaa}"
case deviantart = "\u{eaab}"
case deviantart2 = "\u{eaac}"
case steam = "\u{eaad}"
case steam2 = "\u{eaae}"
case dropbox = "\u{eaaf}"
case onedrive = "\u{eab0}"
case github = "\u{eab1}"
case github2 = "\u{eab2}"
case github3 = "\u{eab3}"
case github4 = "\u{eab4}"
case github5 = "\u{eab5}"
case wordpress = "\u{eab6}"
case wordpress2 = "\u{eab7}"
case joomla = "\u{eab8}"
case blogger = "\u{eab9}"
case blogger2 = "\u{eaba}"
case tumblr = "\u{eabb}"
case tumblr2 = "\u{eabc}"
case yahoo = "\u{eabd}"
case tux = "\u{eabe}"
case apple = "\u{eabf}"
case finder = "\u{eac0}"
case android = "\u{eac1}"
case windows = "\u{eac2}"
case windows8 = "\u{eac3}"
case soundcloud = "\u{eac4}"
case soundcloud2 = "\u{eac5}"
case skype = "\u{eac6}"
case reddit = "\u{eac7}"
case linkedin = "\u{eac8}"
case linkedin2 = "\u{eac9}"
case lastfm = "\u{eaca}"
case lastfm2 = "\u{eacb}"
case delicious = "\u{eacc}"
case stumbleupon = "\u{eacd}"
case stumbleupon2 = "\u{eace}"
case stackoverflow = "\u{eacf}"
case pinterest = "\u{ead0}"
case pinterest2 = "\u{ead1}"
case xing = "\u{ead2}"
case xing2 = "\u{ead3}"
case flattr = "\u{ead4}"
case foursquare = "\u{ead5}"
case paypal = "\u{ead6}"
case paypal2 = "\u{ead7}"
case paypal3 = "\u{ead8}"
case yelp = "\u{ead9}"
case file_pdf = "\u{eada}"
case file_openoffice = "\u{eadb}"
case file_word = "\u{eadc}"
case file_excel = "\u{eadd}"
case libreoffice = "\u{eade}"
case html5 = "\u{eadf}"
case html52 = "\u{eae0}"
case css3 = "\u{eae1}"
case git = "\u{eae2}"
case svg = "\u{eae3}"
case codepen = "\u{eae4}"
case chrome = "\u{eae5}"
case firefox = "\u{eae6}"
case IE = "\u{eae7}"
case opera = "\u{eae8}"
case safari = "\u{eae9}"
case IcoMoon = "\u{eaea}"
case refresh = "\u{e600}"
case addPeople = "\u{e601}"
case testAttraction = "\u{e608}"
case backMenu = "\u{e609}"
case unchecked = "\u{e60a}"
case checked = "\u{e60b}"
case unknownchecked = "\u{e60c}"
case calendar2 = "\u{e60d}"
case messages = "\u{e60e}"
case check = "\u{e60f}"
case check2 = "\u{e610}"
case people = "\u{e612}"
case credits = "\u{e613}"
case edit = "\u{e616}"
case fb = "\u{e617}"
case flashpic = "\u{e618}"
case delete = "\u{e619}"
case gifts = "\u{e61a}"
case attraction1 = "\u{e61b}"
case attraction2 = "\u{e61c}"
case kiss = "\u{e61d}"
case back = "\u{e61e}"
case lock3 = "\u{e620}"
case lock2 = "\u{e621}"
case mapMarker = "\u{e622}"
case exit2 = "\u{e623}"
case sidemenu = "\u{e624}"
case rightArrowMenu = "\u{e626}"
case uniE627 = "\u{e627}"
case newMessage = "\u{e628}"
case user1 = "\u{e629}"
case camera1 = "\u{e62a}"
case uniE62B = "\u{e62b}"
case uniE62C = "\u{e62c}"
case bin3 = "\u{e62d}"
case deletePeople = "\u{e62e}"
case rightArrow = "\u{e630}"
case download4 = "\u{e631}"
case save = "\u{e632}"
case searchMenu = "\u{e633}"
case seach2 = "\u{e634}"
case lockmenu = "\u{e635}"
case settings = "\u{e636}"
case wine = "\u{e637}"
case time = "\u{e638}"
case male = "\u{e639}"
case female = "\u{e63a}"
case vip = "\u{e63b}"
case visits = "\u{e63c}"
case webcam = "\u{e63d}"
case lock1 = "\u{e63e}"
case lockChecked = "\u{e643}"
case pending = "\u{e644}"
case boosts = "\u{e645}"
case invisible = "\u{e646}"
case doubleAttraction = "\u{e61b}\u{e61c}"
static let allValues = [home,
home2,
home3,
office,
newspaper,
pencil,
pencil2,
quill,
pen,
blog,
eyedropper,
droplet,
paint_format,
image,
images,
camera,
headphones,
music,
play,
film,
video_camera,
dice,
pacman,
spades,
clubs,
diamonds,
bullhorn,
connection,
podcast,
feed,
mic,
book,
books,
library,
file_text,
profile,
file_empty,
files_empty,
file_text2,
file_picture,
file_music,
file_play,
file_video,
file_zip,
copy,
paste,
stack,
folder,
folder_open,
folder_plus,
folder_minus,
folder_download,
folder_upload,
price_tag,
price_tags,
barcode,
qrcode,
ticket,
cart,
coin_dollar,
coin_euro,
coin_pound,
coin_yen,
credit_card,
calculator,
lifebuoy,
phone,
phone_hang_up,
address_book,
envelop,
pushpin,
location,
location2,
compass,
compass2,
map,
map2,
history,
clock,
clock2,
alarm,
bell,
stopwatch,
calendar,
printer,
keyboard,
display,
laptop,
mobile,
mobile2,
tablet,
tv,
drawer,
drawer2,
box_add,
box_remove,
download,
upload,
floppy_disk,
drive,
database,
undo,
redo,
undo2,
redo2,
forward,
reply,
bubble,
bubbles,
bubbles2,
bubble2,
bubbles3,
bubbles4,
user,
users,
user_plus,
user_minus,
user_check,
user_tie,
quotes_left,
quotes_right,
hour_glass,
spinner,
spinner2,
spinner3,
spinner4,
spinner5,
spinner6,
spinner7,
spinner8,
spinner9,
spinner10,
spinner11,
binoculars,
search,
zoom_in,
zoom_out,
enlarge,
shrink,
enlarge2,
shrink2,
key,
key2,
lock,
unlocked,
wrench,
equalizer,
equalizer2,
cog,
cogs,
hammer,
magic_wand,
aid_kit,
bug,
pie_chart,
stats_dots,
stats_bars,
stats_bars2,
trophy,
gift,
glass,
glass2,
mug,
spoon_knife,
leaf,
rocket,
meter,
meter2,
hammer2,
fire,
lab,
magnet,
bin,
bin2,
briefcase,
airplane,
truck,
road,
accessibility,
target,
shield,
power,
power_cord,
clipboard,
list_numbered,
list,
list2,
tree,
menu,
menu2,
menu3,
menu4,
cloud,
cloud_download,
cloud_upload,
cloud_check,
download2,
upload2,
download3,
upload3,
sphere,
earth,
link,
flag,
attachment,
eye,
eye_plus,
eye_minus,
eye_blocked,
bookmark,
bookmarks,
sun,
contrast,
brightness_contrast,
star_empty,
star_half,
star_full,
heart,
heart_broken,
man,
woman,
man_woman,
happy,
happy2,
smile,
smile2,
tongue,
tongue2,
sad,
sad2,
wink,
wink2,
grin,
grin2,
cool,
cool2,
angry,
angry2,
evil,
evil2,
shocked,
shocked2,
baffled,
baffled2,
confused,
confused2,
neutral,
neutral2,
hipster,
hipster2,
wondering,
wondering2,
sleepy,
sleepy2,
frustrated,
frustrated2,
crying,
crying2,
point_up,
point_right,
point_down,
point_left,
warning,
notification,
question,
plus,
minus,
info,
cancel_circle,
blocked,
cross,
checkmark,
checkmark2,
spell_check,
enter,
exit,
play2,
pause,
stop,
previous,
next,
backward,
forward2,
play3,
pause2,
stop2,
backward2,
forward3,
first,
last,
previous2,
next2,
eject,
volume_high,
volume_medium,
volume_low,
volume_mute,
volume_mute2,
volume_increase,
volume_decrease,
loop,
loop2,
infinite,
shuffle,
arrow_up_left,
arrow_up,
arrow_up_right,
arrow_right,
arrow_down_right,
arrow_down,
arrow_down_left,
arrow_left,
arrow_up_left2,
arrow_up2,
arrow_up_right2,
arrow_right2,
arrow_down_right2,
arrow_down2,
arrow_down_left2,
arrow_left2,
circle_up,
circle_right,
circle_down,
circle_left,
tab,
move_up,
move_down,
sort_alpha_asc,
sort_alpha_desc,
sort_numeric_asc,
sort_numberic_desc,
sort_amount_asc,
sort_amount_desc,
command,
shift,
ctrl,
opt,
checkbox_checked,
checkbox_unchecked,
radio_checked,
radio_checked2,
radio_unchecked,
crop,
make_group,
ungroup,
scissors,
filter,
font,
ligature,
ligature2,
text_height,
text_width,
font_size,
bold,
underline,
italic,
strikethrough,
omega,
sigma,
page_break,
superscript,
superscript2,
subscript2,
text_color,
pagebreak,
clear_formatting,
table,
table2,
insert_template,
pilcrow,
ltr,
rtl,
section,
paragraph_left,
paragraph_center,
paragraph_right,
paragraph_justify,
indent_increase,
indent_decrease,
share,
new_tab,
embed,
embed2,
terminal,
share2,
mail,
mail2,
mail3,
mail4,
google,
google_plus,
google_plus2,
google_plus3,
google_drive,
facebook,
facebook2,
facebook3,
ello,
instagram,
twitter,
twitter2,
twitter3,
feed2,
feed3,
feed4,
youtube,
youtube2,
youtube3,
youtube4,
twitch,
vimeo,
vimeo2,
vimeo3,
lanyrd,
flickr,
flickr2,
flickr3,
flickr4,
picassa,
picassa2,
dribbble,
dribbble2,
dribbble3,
forrst,
forrst2,
deviantart,
deviantart2,
steam,
steam2,
dropbox,
onedrive,
github,
github2,
github3,
github4,
github5,
wordpress,
wordpress2,
joomla,
blogger,
blogger2,
tumblr,
tumblr2,
yahoo,
tux,
apple,
finder,
android,
windows,
windows8,
soundcloud,
soundcloud2,
skype,
reddit,
linkedin,
linkedin2,
lastfm,
lastfm2,
delicious,
stumbleupon,
stumbleupon2,
stackoverflow,
pinterest,
pinterest2,
xing,
xing2,
flattr,
foursquare,
paypal,
paypal2,
paypal3,
yelp,
file_pdf,
file_openoffice,
file_word,
file_excel,
libreoffice,
html5,
html52,
css3,
git,
svg,
codepen,
chrome,
firefox,
IE,
opera,
safari,
IcoMoon,
refresh,
addPeople,
testAttraction,
backMenu,
unchecked,
checked,
unknownchecked,
calendar2,
messages,
check,
check2,
people,
credits,
edit,
fb,
flashpic,
delete,
gifts,
attraction1,
attraction2,
kiss,
back,
lock3,
lock2,
mapMarker,
exit2,
sidemenu,
rightArrowMenu,
uniE627,
newMessage,
user1,
camera1,
uniE62B,
uniE62C,
bin3,
deletePeople,
rightArrow,
download4,
save,
searchMenu,
seach2,
lockmenu,
settings,
wine,
time,
male,
female,
vip,
visits,
webcam,
lock1,
lockChecked,
pending,
boosts,
invisible,
doubleAttraction]
}
//MARK: Daily income per item
let RTotalFat:Int = 65 //(g)
let RSaturatedFat:Int = 20 //g
let RCholesterol:Int = 300 //milligrams (mg)
let RSodium:Double = 2.4 //mg
let RPotassium:Double = 3.5 //mg
let RTotalCarbohydrate:Int = 300 //g
let RDietaryFiber:Int = 25 //g
let RProtein:Int = 50 //g
//Vitamin A 5,000 International Units (IU)
//Vitamin C 60 mg
//Calcium 1,000 mg
//Iron 18 mg
//Vitamin D 400 IU
//Vitamin E 30 IU
//Vitamin K 80 micrograms µg
//Thiamin 1.5 mg
//Riboflavin 1.7 mg
//Niacin 20 mg
//Vitamin B6 2 mg
//Folate 400 µg
//Vitamin B12 6 µg
//Biotin 300 µg
//Pantothenic acid 10 mg
//Phosphorus 1,000 mg
//Iodine 150 µg
//Magnesium 400 mg
//Zinc 15 mg
//Selenium 70 µg
//Copper 2 mg
//Manganese 2 mg
//Chromium 120 µg
//Molybdenum 75 µg
//Chloride 3,400 mg
class Globals: NSObject {
//MARK: Icomoon helper functions
class func GetMoonIcon(index:Int)->MoonIcons
{
return MoonIcons.allValues[index]
}
class func IndexOfMoonIcon(icon:MoonIcons)->Int
{
if let index:Int = find(MoonIcons.allValues,icon)
{
return index
}
else
{
return -1
}
}
class func GetUIImageFromIcoMoon(icon:MoonIcons, size:CGSize, highlight:Bool)->UIImage
{
// Create a context to render into.
UIGraphicsBeginImageContext(size)
// Work out where the origin of the drawn string should be to get it in
// the centre of the image.
let textOrigin:CGPoint = CGPointMake(5, 5)
let tmpString:NSString = NSString(string: icon.rawValue)
// Draw the string into out image!
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.Center
if !highlight
{
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: size.height-10)!,
NSForegroundColorAttributeName : ControlBcgSolidColor,
NSParagraphStyleAttributeName : style
]
tmpString.drawAtPoint(textOrigin, withAttributes: textFontAttributes)
}
else
{
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: size.height-10)!,
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSParagraphStyleAttributeName : style
]
tmpString.drawAtPoint(textOrigin, withAttributes: textFontAttributes)
}
let retImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return retImage
}
class func GetAttributedTextForIcon(iconAlignment:NSTextAlignment,iconSize:CGFloat,iconColor:UIColor,icon:String)->NSAttributedString
{
//Prepare Navigation Controller Item
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = iconAlignment
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: iconSize)!,
NSForegroundColorAttributeName : iconColor,
NSParagraphStyleAttributeName : style
]
return NSAttributedString(string: icon , attributes: textFontAttributes)
}
//MARK: Storyboard helper
class func getViewController(identifier:String!)->UIViewController?
{
// get your storyboard
let storyboard = UIStoryboard(name: "Main", bundle: nil)
return storyboard.instantiateViewControllerWithIdentifier(identifier) as? UIViewController
}
//MARK: BMI
class func BMI(gender:Bool, height:Float, weight:Float, age:Int)->Float
{
//BMI = weight(kg)/height2(m2) (Metric Units)
var inMeters = height / 100
return weight/(inMeters*inMeters)
}
class func WeightForBMI(gender:Bool, height:Float, BMI:Float, age:Int)->Float
{
//BMI = weight(kg)/height2(m2) (Metric Units)
var inMeters = height / 100
return BMI * (inMeters*inMeters)
}
}
|
fe41d9cfb74ba4e91bbbd093aa1e2c46
| 24.020358 | 137 | 0.51546 | false | false | false | false |
anhnc55/fantastic-swift-library
|
refs/heads/master
|
Example/Example/AppLeftViewController.swift
|
mit
|
1
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
The following is an example of setting a UITableView as the LeftViewController
within a SideNavigationController.
*/
import UIKit
import Material
private struct Item {
var text: String
var imageName: String
}
class AppLeftViewController: UIViewController {
/// A tableView used to display navigation items.
private let tableView: UITableView = UITableView()
/// A list of all the navigation items.
private var items: Array<Item> = Array<Item>()
override func viewDidLoad() {
super.viewDidLoad()
prepareView()
prepareCells()
prepareTableView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
/*
The dimensions of the view will not be updated by the side navigation
until the view appears, so loading a dyanimc width is better done here.
The user will not see this, as it is hidden, by the drawer being closed
when launching the app. There are other strategies to mitigate from this.
This is one approach that works nicely here.
*/
prepareProfileView()
}
/// General preparation statements.
private func prepareView() {
view.backgroundColor = MaterialColor.grey.darken4
}
/// Prepares the items that are displayed within the tableView.
private func prepareCells() {
items.append(Item(text: "Feed", imageName: "ic_today"))
items.append(Item(text: "Recipes", imageName: "ic_inbox"))
}
/// Prepares profile view.
private func prepareProfileView() {
let backgroundView: MaterialView = MaterialView()
backgroundView.image = UIImage(named: "MaterialBackground")
let profileView: MaterialView = MaterialView()
profileView.image = UIImage(named: "Profile9")?.resize(toWidth: 72)
profileView.backgroundColor = MaterialColor.clear
profileView.shape = .Circle
profileView.borderColor = MaterialColor.white
profileView.borderWidth = 3
view.addSubview(profileView)
let nameLabel: UILabel = UILabel()
nameLabel.text = "Michael Smith"
nameLabel.textColor = MaterialColor.white
nameLabel.font = RobotoFont.mediumWithSize(18)
view.addSubview(nameLabel)
MaterialLayout.alignFromTopLeft(view, child: profileView, top: 30, left: (view.bounds.width - 72) / 2)
MaterialLayout.size(view, child: profileView, width: 72, height: 72)
MaterialLayout.alignFromTop(view, child: nameLabel, top: 130)
MaterialLayout.alignToParentHorizontally(view, child: nameLabel, left: 20, right: 20)
}
/// Prepares the tableView.
private func prepareTableView() {
tableView.registerClass(MaterialTableViewCell.self, forCellReuseIdentifier: "MaterialTableViewCell")
tableView.backgroundColor = MaterialColor.clear
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .None
// Use MaterialLayout to easily align the tableView.
view.addSubview(tableView)
MaterialLayout.alignToParent(view, child: tableView, top: 170)
}
}
/// TableViewDataSource methods.
extension AppLeftViewController: UITableViewDataSource {
/// Determines the number of rows in the tableView.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count;
}
/// Prepares the cells within the tableView.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MaterialTableViewCell = tableView.dequeueReusableCellWithIdentifier("MaterialTableViewCell", forIndexPath: indexPath) as! MaterialTableViewCell
let item: Item = items[indexPath.row]
cell.textLabel!.text = item.text
cell.textLabel!.textColor = MaterialColor.grey.lighten2
cell.textLabel!.font = RobotoFont.medium
cell.imageView!.image = UIImage(named: item.imageName)?.imageWithRenderingMode(.AlwaysTemplate)
cell.imageView!.tintColor = MaterialColor.grey.lighten2
cell.backgroundColor = MaterialColor.clear
return cell
}
}
/// UITableViewDelegate methods.
extension AppLeftViewController: UITableViewDelegate {
/// Sets the tableView cell height.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64
}
/// Select item at row in tableView.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// print("Selected")
}
}
|
1751cba16866352b793df3c2c72e1325
| 36.101911 | 155 | 0.76824 | false | false | false | false |
Festify/cordova-spotify-oauth
|
refs/heads/develop
|
src/ios/SpotifyOAuthPlugin.swift
|
mit
|
1
|
import Foundation
import SafariServices
extension URL {
subscript(queryParam: String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
return url.queryItems?.first(where: { $0.name == queryParam })?.value
}
}
@objc(SpotifyOAuthPlugin) class SpotifyOAuthPlugin: CDVPlugin, SFSafariViewControllerDelegate {
private var currentCommand: CDVInvokedUrlCommand?
private var currentNsObserver: AnyObject?
@objc(getCode:) func getCode(_ command: CDVInvokedUrlCommand) {
let clientid = command.argument(at: 0) as! String
let redirectURL = command.argument(at: 1) as! String
let requestedScopes = command.argument(at: 4) as! [String]
var components = URLComponents()
components.scheme = "https"
components.host = "accounts.spotify.com"
components.path = "/authorize"
components.queryItems = [
URLQueryItem(name: "client_id", value: clientid),
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(name: "redirect_uri", value: redirectURL),
URLQueryItem(name: "show_dialog", value: "true"),
URLQueryItem(name: "scope", value: requestedScopes.joined(separator: " ")),
URLQueryItem(name: "utm_source", value: "spotify-sdk"),
URLQueryItem(name: "utm_medium", value: "ios-sdk"),
URLQueryItem(name: "utm_campaign", value: "ios-sdk")
]
let svc = SFSafariViewController(url: components.url!)
svc.delegate = self;
svc.modalPresentationStyle = .overFullScreen
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.CDVPluginHandleOpenURL,
object: nil,
queue: nil
) { note in
let url = note.object as! URL
guard url.absoluteString.contains("code") else { return }
svc.presentingViewController!.dismiss(animated: true, completion: nil)
NotificationCenter.default.removeObserver(observer!)
self.currentNsObserver = nil
self.currentCommand = nil
let res = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: [
"code": url["code"]
]
)
self.commandDelegate.send(res, callbackId: command.callbackId)
}
self.currentCommand = command
self.currentNsObserver = observer
self.viewController.present(svc, animated: true)
}
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
guard self.currentNsObserver != nil && self.currentCommand != nil else { return }
let res = CDVPluginResult(
status: CDVCommandStatus_ERROR,
messageAs: [
"type": "auth_canceled",
"msg": "The user cancelled the authentication process."
]
)
self.commandDelegate.send(res, callbackId: self.currentCommand!.callbackId)
NotificationCenter.default.removeObserver(self.currentNsObserver!)
self.currentCommand = nil
self.currentNsObserver = nil
}
}
|
06af0363dda3506fde754d50e2f4d2c7
| 38.423529 | 95 | 0.609967 | false | false | false | false |
jeffreybergier/Cartwheel
|
refs/heads/master
|
Cartwheel/Cartwheel/Source/CWSwiftGlobals.swift
|
mit
|
1
|
//
// CWSwiftGlobals.swift
// Cartwheel
//
// Created by Jeffrey Bergier on 5/10/15.
//
// Copyright (c) 2015 Jeffrey Bergier
//
// 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 COwNTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import AppKit
import XCGLogger
// MARK: Class for Subcontrollers
class DependencyDefinableListChildController: NSObject {
weak var controller: protocol<DependencyDefinablesControllable, DependencyDefinableListModelControllable, CartfileWindowControllable>?
weak var windowObserver: DependencyDefinableListWindowObserver?
}
// MARK: Extend NSRange
extension NSIndexSet {
var ranges: [Range<Int>] {
var ranges = [Range<Int>]()
self.enumerateRangesUsingBlock() { (range, stop) in
let swiftRange = range.location ..< range.location + range.length
ranges += [swiftRange]
}
return ranges
}
}
// MARK: Extending NSURL
extension NSURL {
func extractFilesRecursionDepth(recursionDepth: Int) -> [NSURL]? {
let files = self.recurseFilesByEnumeratingURLWithInitialURLs([NSURL](), maxDepth: recursionDepth, currentDepth: 0)
if files.count > 0 { return files } else { return .None }
}
private func recurseFilesByEnumeratingURLWithInitialURLs(startingFiles: [NSURL], maxDepth: Int, currentDepth: Int) -> [NSURL] {
let files: [NSURL]
if let filesAndDirectories = self.filesAndDirectories() where currentDepth <= maxDepth {
let recursionFiles = filesAndDirectories.remainingDirectories.map { directory -> [NSURL] in
return directory.recurseFilesByEnumeratingURLWithInitialURLs(startingFiles, maxDepth: maxDepth, currentDepth: currentDepth + 1)
}
let mergedRecursionFiles = Array.merge(recursionFiles)
files = startingFiles + filesAndDirectories.files + mergedRecursionFiles
} else {
files = startingFiles
}
return files
}
func filesAndDirectories() -> URLEnumeration? {
let fileManager = NSFileManager.defaultManager()
let urlKeys = [NSURLIsDirectoryKey]
let enumeratorOptions: NSDirectoryEnumerationOptions = [.SkipsHiddenFiles, .SkipsPackageDescendants, .SkipsSubdirectoryDescendants]
let enumerator = fileManager.enumeratorAtURL(self, includingPropertiesForKeys: urlKeys, options: enumeratorOptions) {
(url: NSURL, error: NSError) -> Bool in
XCGLogger.defaultInstance().error("NSEnumerator Error: \(error) with URL: \(url)")
return true
}
if let enumeratorObjects = enumerator?.allObjects {
let files = enumeratorObjects.filter() { object -> Bool in
if let url = object as? NSURL,
let urlResources = try? url.resourceValuesForKeys(urlKeys),
let urlIsDirectory = urlResources[NSURLIsDirectoryKey] as? Bool
where urlIsDirectory == false {
return true
} else {
return false
}
}.map() { object -> NSURL in
return object as! NSURL
}
let directories = enumeratorObjects.filter() { object -> Bool in
if let url = object as? NSURL,
let urlResources = try? url.resourceValuesForKeys(urlKeys),
let urlIsDirectory = urlResources[NSURLIsDirectoryKey] as? Bool
where urlIsDirectory == true {
return true
} else {
return false
}
}.map() { object -> NSURL in
return object as! NSURL
}
if files.isEmpty && directories.isEmpty {
// this returns the original URL if no other files and directories were found
// this happens when the user drags a file rather than a URL
return URLEnumeration(files: [self], remainingDirectories: directories)
} else {
return URLEnumeration(files: files, remainingDirectories: directories)
}
}
return .None
}
class func URLsFromPasteboard(pasteboard: NSPasteboard) -> [NSURL]? {
let URLs = pasteboard.readObjectsForClasses([NSURL.self], options: nil)?.filter() { object -> Bool in
if let url = object as? NSURL { return true } else { return false }
}.map() { object -> NSURL in
return object as! NSURL
}
// fixes a bug where we were sometimes returning an empty array
if let URLs = URLs where URLs.isEmpty == false { return URLs } else { return .None }
}
var parentDirectory: NSURL {
var components = self.pathComponents!
components.removeLast()
return NSURL.fileURLWithPathComponents(components)!
}
}
struct URLEnumeration {
var files = [NSURL]()
var remainingDirectories = [NSURL]()
}
// MARK: Fixing Broken AppKit Stuff
extension NSProgressIndicator {
enum IndicatorState {
case Indeterminate, Determinate
}
}
struct CWLayoutPriority {
static var Required: NSLayoutPriority = 1000
static var DefaultHigh: NSLayoutPriority = 750
static var DragThatCanResizeWindow: NSLayoutPriority = 510
static var WindowSizeStayPut: NSLayoutPriority = 500
static var DragThatCannotResizeWindow: NSLayoutPriority = 490
static var DefaultLow: NSLayoutPriority = 250
static var FittingSizeCompression: NSLayoutPriority = 50
}
//extension NSView {
// func writeScreenShotToDiskWithName(name: String) -> NSError? {
// // Capture original invisibility state
// let originalHiddenState = self.hidden
// let originalAlphaState = self.alphaValue
//
// // change view to be fully visible for screenshot
// self.hidden = false
// self.alphaValue = 1.0
//
// // create URL in App Support directory
// let appSupport = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true).last! + "/Cartwheel"
// let appSupportURL = NSURL(fileURLWithPath: appSupport, isDirectory: true)
// let screenshotFileURL = appSupportURL.URLByAppendingPathComponent(name + ".tiff")
//
// // capture screenshot
// let screenshot = NSImage(data: self.dataWithPDFInsideRect(self.bounds))
//
// // save to disk
// var error: NSError?
// do {
// try screenshot?.TIFFRepresentation?.writeToURL(screenshotFileURL, options: NSDataWritingOptions.AtomicWrite)
// } catch var error1 as NSError {
// error = error1
// }
//
// // Restore invisiblity state
// self.hidden = originalHiddenState
// self.alphaValue = originalAlphaState
//
// // return error (if any)
// return error
// }
//}
// MARK: Extensions of Built in Types
func indexOfItem<T: Equatable>(item: T, inCollection collection: [T]) -> Int? {
// TODO: remove this in swift 2.0
for (index, collectionItem) in collection.enumerate() {
if item == collectionItem { return index }
}
return .None
}
extension Array {
static func arrayByExcludingItemsInArray<E: Hashable>(lhs: [E], andArray rhs: [E]) -> [E]? {
let lhsSet = Set(lhs)
let rhsSet = Set(rhs)
var outputArray = [E]()
func checkItem(item: E, lhs: Set<E>, rhs: Set<E>) -> [E] {
if !(lhs.contains(item) && rhs.contains(item)) { return [item] } else { return [] }
}
for leftItem in lhs {
outputArray += checkItem(leftItem, lhs: lhsSet, rhs: rhsSet)
}
for rightItem in rhs {
outputArray += checkItem(rightItem, lhs: lhsSet, rhs: rhsSet)
}
if outputArray.count > 0 { return outputArray } else { return .None }
}
static func flatten<T>(array: [[T]]) -> [T] {
return array.reduce([T](), combine: +)
}
static func merge(input: [[Element]]) -> [Element] {
var output = [Element]()
for inputItem in input {
output += inputItem
}
return output
}
static func merge(input: [[Element]?]) -> [Element] {
var output = [Element]()
for inputItem in input {
if let inputItem = inputItem {
output += inputItem
}
}
return output
}
subscript (safe index: Int) -> Element? {
return index < count && index >= 0 ? self[index] : nil
}
subscript (unsafe index: Int) -> Element {
return self[index]
}
subscript (yolo index: Int) -> Element { // YOLO! Crashes if out of range
return self[index]
}
func lastIndex() -> Int {
return self.count - 1
}
}
extension Set {
func map<U>(transform: (Element) -> U) -> Set<U> {
return Set<U>(self.map(transform))
}
}
extension NSButton {
enum Style {
case Default, Cancel, Warning, Retry
}
convenience init(style: Style) {
self.init(frame: NSRect(x: 0, y: 0, width: 0, height: 0))
switch style {
case .Default:
self.bezelStyle = .RoundedBezelStyle
case .Cancel:
self.bezelStyle = .TexturedRoundedBezelStyle
self.title = ""
self.bordered = false
self.image = NSImage(named: NSImageNameStopProgressFreestandingTemplate)
case .Retry:
self.bezelStyle = .TexturedRoundedBezelStyle
self.title = ""
self.bordered = false
self.image = NSImage(named: NSImageNameRefreshFreestandingTemplate)
case .Warning:
self.title = ""
self.bordered = false
self.bezelStyle = .TexturedRoundedBezelStyle
self.image = NSImage(named: NSImageNameCaution)
(self.cell as? NSButtonCell)?.imageScaling = NSImageScaling.ScaleProportionallyDown
}
}
}
extension NSOpenPanel {
enum Style {
case AddCartfiles
case CreatBlankCartfile(delegate: NSOpenSavePanelDelegate)
}
enum Response: Int {
case CancelButton = 0, SuccessButton
}
convenience init(style: Style) {
self.init()
switch style {
case .AddCartfiles:
self.canChooseFiles = true
self.canChooseDirectories = true
self.allowsMultipleSelection = true
self.title = NSLocalizedString("Add Cartfiles", comment: "Title of add cartfiles open panel")
case .CreatBlankCartfile(let delegate):
self.delegate = delegate
self.canChooseDirectories = true
self.canCreateDirectories = true
self.canChooseFiles = false
self.allowsMultipleSelection = false
self.title = NSLocalizedString("Create New Cartfile", comment: "Title of the create new cartfile save dialog.")
self.prompt = CartListOpenPanelDelegate.savePanelOriginalButtonTitle
}
}
}
extension NSAlert {
enum Style {
case CartfileRemoveConfirm
enum CartfileRemoveConfirmResponse: Int {
case RemoveButton = 1000
case CancelButton = 1001
}
enum CartfileBuildErrorDismissResponse: Int {
case DismissButton = 1001
case DismissAndClearButton = 1000
}
}
convenience init(style: Style) {
self.init()
switch style {
case .CartfileRemoveConfirm:
self.addButtonWithTitle("Remove")
self.addButtonWithTitle("Cancel")
self.messageText = NSLocalizedString("Remove Selected Cartfiles?", comment: "Description for alert that is shown when the user tries to delete Cartfiles from the main list")
self.alertStyle = NSAlertStyle.WarningAlertStyle
}
}
}
extension NSTextField {
enum Style {
case TableRowCellTitle
}
convenience init(style: Style) {
self.init()
switch style {
case .TableRowCellTitle:
self.bordered = false
(self.cell as? NSTextFieldCell)?.backgroundColor = NSColor.clearColor()
self.editable = false
}
}
}
// MARK: Operator Overloads
infix operator !! { associativity right precedence 110 }
// AssertingNilCoalescing operator crashes when LHS is nil when App is in Debug Build.
// When App is in release build, it performs ?? operator
// Crediting http://blog.human-friendly.com/theanswer-equals-maybeanswer-or-a-good-alternative
public func !!<A>(lhs:A?, @autoclosure rhs:()->A)->A {
assert(lhs != nil)
return lhs ?? rhs()
}
|
96d28fb6e806fae211891cf249a8527b
| 34.681234 | 185 | 0.618921 | false | false | false | false |
che1404/RGViperChat
|
refs/heads/master
|
vipergenTemplate/che1404/swift/Presenter/VIPERPresenterSpec.swift
|
mit
|
1
|
//
// Created by AUTHOR
// Copyright (c) YEAR AUTHOR. All rights reserved.
//
import Quick
import Nimble
import Cuckoo
@testable import ProjectName
class VIPERPresenterSpec: QuickSpec {
var presenter: VIPERPresenter!
var mockView: MockVIPERViewProtocol!
var mockWireframe: MockVIPERWireframeProtocol!
var mockInteractor: MockVIPERInteractorInputProtocol!
override func spec() {
beforeEach {
self.mockInteractor = MockVIPERInteractorInputProtocol()
self.mockView = MockVIPERViewProtocol()
self.mockWireframe = MockVIPERWireframeProtocol()
self.presenter = VIPERPresenter()
self.presenter.view = self.mockView
self.presenter.wireframe = self.mockWireframe
self.presenter.interactor = self.mockInteractor
}
it("Todo") {
}
afterEach {
self.mockInteractor = nil
self.mockView = nil
self.mockWireframe = nil
self.presenter.view = nil
self.presenter.wireframe = nil
self.presenter.interactor = nil
self.presenter = nil
}
}
}
|
d2f4f4a6d73b42a395fe1488c3647998
| 26.714286 | 68 | 0.63488 | false | false | false | false |
breadwallet/breadwallet
|
refs/heads/master
|
BreadWallet/BRTar.swift
|
mit
|
5
|
//
// BRTar.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
//
// 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
enum BRTarError: Error {
case unknown
case fileDoesntExist
}
enum BRTarType {
case file
case directory
case nullBlock
case headerBlock
case unsupported
case invalid
init(fromData: Data) {
if fromData.count < 1 {
BRTar.log("invalid data")
self = .invalid
return
}
let byte = (fromData as NSData).bytes.bindMemory(to: CChar.self, capacity: fromData.count)[0]
switch byte {
case CChar(48): // "0"
self = .file
case CChar(53): // "5"
self = .directory
case CChar(0):
self = .nullBlock
case CChar(120): // "x"
self = .headerBlock
case CChar(49), CChar(50), CChar(51), CChar(52), CChar(53), CChar(54), CChar(55), CChar(103):
// "1, 2, 3, 4, 5, 6, 7, g"
self = .unsupported
default:
BRTar.log("invalid block type: \(byte)")
self = .invalid
}
}
}
class BRTar {
static let tarBlockSize: UInt64 = 512
static let tarTypePosition: UInt64 = 156
static let tarNamePosition: UInt64 = 0
static let tarNameSize: UInt64 = 100
static let tarSizePosition: UInt64 = 124
static let tarSizeSize: UInt64 = 12
static let tarMaxBlockLoadInMemory: UInt64 = 100
static let tarLogEnabled: Bool = false
static func createFilesAndDirectoriesAtPath(_ path: String, withTarPath tarPath: String) throws {
let fm = FileManager.default
if !fm.fileExists(atPath: tarPath) {
log("tar file \(tarPath) does not exist")
throw BRTarError.fileDoesntExist
}
let attrs = try fm.attributesOfItem(atPath: tarPath)
guard let tarFh = FileHandle(forReadingAtPath: tarPath) else {
log("could not open tar file for reading")
throw BRTarError.unknown
}
var loc: UInt64 = 0
guard let sizee = attrs[FileAttributeKey.size] as? Int else {
log("could not read tar file size")
throw BRTarError.unknown
}
let size = UInt64(sizee)
while loc < size {
var blockCount: UInt64 = 1
let tarType = readTypeAtLocation(loc, fromHandle: tarFh)
switch tarType {
case .file:
// read name
let name = try readNameAtLocation(loc, fromHandle: tarFh)
log("got file name from tar \(name)")
let newFilePath = (path as NSString).appendingPathComponent(name)
log("will write to \(newFilePath)")
var size = readSizeAtLocation(loc, fromHandle: tarFh)
log("its size is \(size)")
if fm.fileExists(atPath: newFilePath) {
try fm.removeItem(atPath: newFilePath)
}
if size == 0 {
// empty file
try "" .write(toFile: newFilePath, atomically: true, encoding: String.Encoding.utf8)
break
}
blockCount += (size - 1) / tarBlockSize + 1
// write file
fm.createFile(atPath: newFilePath, contents: nil, attributes: nil)
guard let destFh = FileHandle(forWritingAtPath: newFilePath) else {
log("unable to open destination file for writing")
throw BRTarError.unknown
}
tarFh.seek(toFileOffset: loc + tarBlockSize)
let maxSize = tarMaxBlockLoadInMemory * tarBlockSize
while size > maxSize {
autoreleasepool(invoking: { () -> () in
destFh.write(tarFh.readData(ofLength: Int(maxSize)))
size -= maxSize
})
}
destFh.write(tarFh.readData(ofLength: Int(size)))
destFh.closeFile()
log("success writing file")
break
case .directory:
let name = try readNameAtLocation(loc, fromHandle: tarFh)
log("got new directory name \(name)")
let dirPath = (path as NSString).appendingPathComponent(name)
log("will create directory at \(dirPath)")
if fm.fileExists(atPath: dirPath) {
try fm.removeItem(atPath: dirPath) // will automatically recursively remove directories if exists
}
try fm.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil)
log("success creating directory")
break
case .nullBlock:
break
case .headerBlock:
blockCount += 1
break
case .unsupported:
let size = readSizeAtLocation(loc, fromHandle: tarFh)
blockCount += size / tarBlockSize
break
case .invalid:
log("Invalid block encountered")
throw BRTarError.unknown
}
loc += blockCount * tarBlockSize
log("new location \(loc)")
}
}
static fileprivate func readTypeAtLocation(_ location: UInt64, fromHandle handle: FileHandle) -> BRTarType {
log("reading type at location \(location)")
handle.seek(toFileOffset: location + tarTypePosition)
let typeDat = handle.readData(ofLength: 1)
let ret = BRTarType(fromData: typeDat)
log("type: \(ret)")
return ret
}
static fileprivate func readNameAtLocation(_ location: UInt64, fromHandle handle: FileHandle) throws -> String {
handle.seek(toFileOffset: location + tarNamePosition)
let dat = handle.readData(ofLength: Int(tarNameSize))
guard let ret = String(bytes: dat, encoding: String.Encoding.ascii) else {
log("unable to read name")
throw BRTarError.unknown
}
return ret
}
static fileprivate func readSizeAtLocation(_ location: UInt64, fromHandle handle: FileHandle) -> UInt64 {
handle.seek(toFileOffset: location + tarSizePosition)
let sizeDat = handle.readData(ofLength: Int(tarSizeSize))
let octal = NSString(data: sizeDat, encoding: String.Encoding.ascii.rawValue)!
log("size octal: \(octal)")
let dec = strtoll(octal.utf8String, nil, 8)
log("size decimal: \(dec)")
return UInt64(dec)
}
static fileprivate func log(_ string: String) {
if tarLogEnabled {
print("[BRTar] \(string)")
}
}
}
|
7ddcbdfe7ca216f4a9ad51907073b2d3
| 38.572139 | 117 | 0.581217 | false | false | false | false |
googlearchive/science-journal-ios
|
refs/heads/master
|
ScienceJournal/ActionArea/CrossDissolveTransitionAnimation.swift
|
apache-2.0
|
1
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
// A custom cross dissolve transition for `UINavigationController`.
final class CrossDissolveTransitionAnimation: NSObject, UIViewControllerAnimatedTransitioning {
private let operation: UINavigationController.Operation
private let transitionDuration: TimeInterval
init(operation: UINavigationController.Operation, transitionDuration: TimeInterval) {
self.operation = operation
self.transitionDuration = transitionDuration
}
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?
) -> TimeInterval {
return transitionDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch operation {
case .none:
// TODO: When does this happen?
transitionContext.completeTransition(true)
case .push:
animatePush(using: transitionContext)
case .pop:
animatePop(using: transitionContext)
}
}
func animatePush(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromView = transitionContext.view(forKey: .from),
let toView = transitionContext.view(forKey: .to) else {
transitionContext.completeTransition(false)
return
}
let duration = transitionDuration(using: transitionContext)
transitionContext.containerView.addSubview(toView)
UIView.transition(
from: fromView,
to: toView,
duration: duration,
options: .transitionCrossDissolve
) { completed in
transitionContext.completeTransition(completed)
}
}
func animatePop(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromView = transitionContext.view(forKey: .from),
let toView = transitionContext.view(forKey: .to) else {
transitionContext.completeTransition(false)
return
}
let duration = transitionDuration(using: transitionContext)
transitionContext.containerView.insertSubview(toView, belowSubview: fromView)
UIView.transition(
from: fromView,
to: toView,
duration: duration,
options: .transitionCrossDissolve
) { completed in
transitionContext.completeTransition(completed)
}
}
}
|
f3543012f1afc0eff848ddcb5dcb6e9f
| 32.364706 | 95 | 0.740127 | false | false | false | false |
mownier/photostream
|
refs/heads/master
|
Photostream/UI/User Post/UserPostViewDataSource.swift
|
mit
|
1
|
//
// UserPostViewDataSource.swift
// Photostream
//
// Created by Mounir Ybanez on 09/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
extension UserPostViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
switch sceneType {
case .grid:
return 1
case .list:
return presenter.postCount
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch sceneType {
case .grid:
return presenter.postCount
case .list:
return 1
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch sceneType {
case .grid:
let cell = PostGridCollectionCell.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.row) as? PostGridCollectionCellItem
cell.configure(with: item)
return cell
case .list:
let cell = PostListCollectionCell.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.section) as? PostListCollectionCellItem
cell.configure(with: item)
cell.delegate = self
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader where sceneType == .list:
let header = PostListCollectionHeader.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.section) as? PostListCollectionHeaderItem
header.configure(with: item)
return header
default:
return UICollectionReusableView()
}
}
}
|
ea6c94fcdc469ec28e3416d31a635bef
| 32.650794 | 171 | 0.626415 | false | false | false | false |
Blackjacx/SwiftTrace
|
refs/heads/master
|
Sources/Image.swift
|
mit
|
1
|
//
// Image.swift
// SwiftTrace
//
// Created by Stefan Herold on 13/08/16.
//
//
import Foundation
enum FileIOError: Error {
case writeError(String)
}
public class Image: CustomStringConvertible {
private(set)var pixel: [Color]
private(set) var width: UInt
private(set) var height: UInt
var size: UInt { return width * height }
var backgroundColor: Color = Color(gray: 0)
private let syncAccessQueue = DispatchQueue(label: "com.swiftTrace.imageSerialSynchAccessQueue")
// Custom String Convertible
public var description: String {
return pixel.description
}
init(width: UInt, height: UInt) {
self.width = width
self.height = height
self.pixel = Array(repeating: backgroundColor, count: Int(width*height))
}
/// Normalized accessors for bumpmapping. Uses green component. Returns dx and dy.
func derivativeAt(x: Double, y: Double) -> (Double, Double) {
let ix = UInt(x * Double(width-1))
let iy = UInt(y * Double(height-1))
let dx = pixel[Int(windex(x: ix, y: iy+1))].green - pixel[Int(index(x: ix, y: iy))].green
let dy = pixel[Int(windex(x: ix+1, y: iy))].green - pixel[Int(index(x: ix, y: iy))].green
return (dx, dy)
}
/// Handy accessors: color = img[x, y]; img[x, y] = color
subscript(x: UInt, y: UInt) -> Color {
get {
assert(indexIsValidFor(x: x, y: y), "Index out of range")
var pixel: Color!
syncAccessQueue.sync {
pixel = self.pixel[Int(index(x: x, y: y))]
}
return pixel
}
set(newValue) {
assert(indexIsValidFor(x: x, y: y), "Index out of range")
syncAccessQueue.async {
self.pixel[Int(self.index(x: x, y: y))] = newValue
}
}
}
/// Handy accessors: color = img[x, y]; img[x, y] = color
subscript(x: Double, y: Double) -> Color {
get {
assert(indexIsValidFor(x: x, y: y), "Index out of range")
var pixel: Color!
syncAccessQueue.sync {
pixel = self.pixel[Int(findex(x: x, y: y))]
}
return pixel
}
set(newValue) {
assert(indexIsValidFor(x: x, y: y), "Index out of range")
syncAccessQueue.async {
self.pixel[Int(self.findex(x: x, y: y))] = newValue
}
}
}
// MARK: - Index
/// Integer index
private func index(x: UInt, y: UInt) -> UInt {
return y * width + x
}
/// Wrapped index
private func windex(x: UInt, y: UInt) -> UInt {
return index(x: x % width, y: y % height)
}
/// Double index: x(0...1), y(0...1)
private func findex(x: Double, y: Double) -> UInt {
return index(x: UInt(x * Double(width-1)), y: UInt(y * Double(height-1)))
}
private func indexIsValidFor(x: UInt, y: UInt) -> Bool {
return x < width && y < height && x <= UInt(Int.max) && y <= UInt(Int.max)
}
private func indexIsValidFor(x: Double, y: Double) -> Bool {
return x >= 0 && x <= 1 && y >= 0 && y <= 1
}
// MARK: - I/O
func write(to filepath: String) throws {
guard let out = OutputStream(toFileAtPath: filepath, append: false) else {
throw FileIOError.writeError(filepath)
}
let writer = { (text: String, os: OutputStream)->() in
guard let data = text.data(using: .utf8) else {
return
}
_ = data.withUnsafeBytes { os.write($0, maxLength: data.count) }
}
out.open()
let header = "P3 \(width) \(height) \(255)\n"
writer(header, out)
var row: UInt = 0
for index: Int in 0..<Int(size) {
let c = pixel[index] * 255
var message = "\(Int(c.red)) \(Int(c.green)) \(Int(c.blue))"
if row != 0 {
message = ((row % 10) == 0 ? "\n" : " ") + message
}
row += 1
writer(message, out)
}
writer(header, out)
out.close()
}
}
|
3e2f1c89d34d0d65f6e82751ef9b0544
| 29.248175 | 100 | 0.527027 | false | false | false | false |
Fidetro/SwiftFFDB
|
refs/heads/master
|
Swift-FFDBTests/ReadmeTests.swift
|
apache-2.0
|
1
|
//
// ReadmeTests.swift
// Swift-FFDBTests
//
// Created by Fidetro on 13/02/2018.
// Copyright © 2018 Fidetro. All rights reserved.
//
import XCTest
import Foundation
class ReadmeTests: XCTestCase {
override func setUp() {
super.setUp()
}
func testReadme() {
Person.registerTable()
let person = Person()
person.name = "fidetro"
person.insert()
// find all Object
guard let _ = Person.select(where: nil) as? [Person] else {
// no object in database
return
}
// find name is 'fidetro'
guard let _ = Person.select(where: "name = 'fidetro'") as? [Person] else {
// no object in database
return
}
guard let personList = Person.select(where: "name = 'fidetro'") as? [Person] else {
// no object in database
return
}
for p1 in personList {
// delete this person in database
Person.delete(where: "primaryID = ?", values: [p1.primaryID!])
}
do{
try FFDBManager.delete(Person.self, where: "name = 'fidetro'")
}catch{
XCTFail()
print(error)
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
8443b714b70da1a87ad123fbfb9f1447
| 25.898551 | 111 | 0.541487 | false | true | false | false |
ahmetabdi/SwiftCrunch
|
refs/heads/master
|
Crunch/Cookie.swift
|
mit
|
1
|
//
// Cookie.swift
// Crunch
//
// Created by Ahmet Abdi on 29/09/2014.
// Copyright (c) 2014 Ahmet Abdi. All rights reserved.
//
import SpriteKit
enum CookieType: Int, Printable{
case Unknown = 0, Croissant, Cupcake, Danish, Donut, Macaroon, SugarCookie
var spriteName: String {
let spriteNames = [
"Croissant",
"Cupcake",
"Danish",
"Donut",
"Macaroon",
"SugarCookie"]
return spriteNames[toRaw() - 1]
}
var highlightedSpriteName: String {
return spriteName + "-Highlighted"
}
static func random() -> CookieType {
return CookieType.fromRaw(Int(arc4random_uniform(6)) + 1)!
}
var description: String {
return spriteName
}
}
class Cookie: Printable, Hashable {
var column: Int
var row: Int
let cookieType: CookieType
var sprite: SKSpriteNode?
init(column: Int, row: Int, cookieType: CookieType) {
self.column = column
self.row = row
self.cookieType = cookieType
}
var hashValue: Int{
return row*10 + column
}
var description: String {
return "type:\(cookieType) square:(\(column),\(row))"
}
}
func ==(lhs: Cookie, rhs: Cookie) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row
}
|
23bf98fa8eaab32164e8f0b748ce863c
| 21.459016 | 78 | 0.570073 | false | false | false | false |
Czajnikowski/TrainTrippin
|
refs/heads/master
|
LibrarySample/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift
|
mit
|
3
|
//
// KVORepresentable+Swift.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Int : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.int32Value)
}
}
extension Int32 : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.int32Value)
}
}
extension Int64 : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.int64Value)
}
}
extension UInt : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.uintValue)
}
}
extension UInt32 : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.uint32Value)
}
}
extension UInt64 : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.uint64Value)
}
}
extension Bool : KVORepresentable {
public typealias KVOType = NSNumber
/**
Constructs `Self` using KVO value.
*/
public init?(KVOValue: KVOType) {
self.init(KVOValue.boolValue)
}
}
extension RawRepresentable where RawValue: KVORepresentable {
/**
Constructs `Self` using optional KVO value.
*/
init?(KVOValue: RawValue.KVOType?) {
guard let KVOValue = KVOValue else {
return nil
}
guard let rawValue = RawValue(KVOValue: KVOValue) else {
return nil
}
self.init(rawValue: rawValue)
}
}
|
52e887d4a4d85529060a6097486fcb46
| 19.25 | 64 | 0.625831 | false | false | false | false |
Tuslareb/JBDatePicker
|
refs/heads/master
|
JBDatePicker/Classes/JBDatePickerView.swift
|
mit
|
1
|
//
// JBDatePickerView.swift
// JBDatePicker
//
// Created by Joost van Breukelen on 09-10-16.
// Copyright © 2016 Joost van Breukelen. All rights reserved.
//
import UIKit
typealias ContentController = JBDatePickerContentVC
typealias Manager = JBDatePickerManager
typealias MonthView = JBDatePickerMonthView
typealias WeekDaysView = JBDatePickerWeekDaysView
public final class JBDatePickerView: UIView {
// MARK: - Properties
var contentController: ContentController!
var manager: Manager!
var weekViewSize: CGSize!
var dayViewSize: CGSize!
var dateToPresent: Date!
var weekdaysView: WeekDaysView!
fileprivate var dateFormatter = DateFormatter()
public weak var delegate: JBDatePickerViewDelegate? {
didSet{
commonInit()
}
}
public var presentedMonthView: JBDatePickerMonthView! {
didSet {
delegate?.didPresentOtherMonth(presentedMonthView)
layoutIfNeeded()
}
}
public var selectedDateView: JBDatePickerDayView! {
willSet {
selectedDateView?.deselect()
}
didSet {
selectedDateView.select()
dateToPresent = selectedDateView.date
}
}
// MARK: - Initialization
private func commonInit() {
//initialize datePickerManager
manager = Manager(datePickerView: self)
//initialize contentController with preferred (or current) date
dateToPresent = delegate?.dateToShow ?? Date()
contentController = ContentController(datePickerView: self, frame: bounds, presentedDate: dateToPresent)
//add scrollView
addSubview(contentController.scrollView)
contentController.scrollView.translatesAutoresizingMaskIntoConstraints = false
//create and add weekdayView
weekdaysView = WeekDaysView(datePickerView: self)
addSubview(weekdaysView)
weekdaysView.translatesAutoresizingMaskIntoConstraints = false
//pin datePickerView to left, right and bottom of scrollView.
leftAnchor.constraint(equalTo: contentController.scrollView.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: contentController.scrollView.rightAnchor).isActive = true
bottomAnchor.constraint(equalTo: contentController.scrollView.bottomAnchor).isActive = true
//pin weekDaysView to left, right and top of datePickerView
weekdaysView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
weekdaysView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
weekdaysView.topAnchor.constraint(equalTo: topAnchor).isActive = true
//add heightconstraint for weekDaysview
weekdaysView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: (delegate?.weekDaysViewHeightRatio)!).isActive = true
}
}
extension JBDatePickerView {
/**
Updates the layout of JBDatePicker. This makes sure that elements in JBDatePicker that need a frame, will get their frame.
*/
public func updateLayout() {
guard delegate != nil else {
print("JBDatePickerView warning: there is no delegate set. This is needed for JBDatePickerView to work correctly")
return
}
guard weekdaysView != nil else { return }
let width = bounds.size.width
let availableRectForScrollView = CGRect(x: bounds.origin.x, y: weekdaysView.bounds.height, width: width, height: bounds.size.height - weekdaysView.bounds.height)
//adjust scrollView frame to available space
contentController.updateScrollViewFrame(availableRectForScrollView)
}
public override func layoutSubviews() {
super.layoutSubviews()
updateLayout()
}
}
extension JBDatePickerView {
func monthDescriptionForDate(_ date: Date) -> String {
let monthFormatString = "MMMM yyyy"
dateFormatter.dateFormat = monthFormatString
if let preferredLanguage = Bundle.main.preferredLocalizations.first {
if delegate?.shouldLocalize == true {
dateFormatter.locale = Locale(identifier: preferredLanguage)
}
}
return dateFormatter.string(from: date)
}
func dateIsSelectable(date: Date?) -> Bool {
//default true, pass check to delegate if exists
return delegate?.shouldAllowSelectionOfDay(date) ?? true
}
///this will call the delegate as well as set the selectedDate on the datePicker.
func didTapDayView(dayView: JBDatePickerDayView) {
selectedDateView = dayView
delegate?.didSelectDay(dayView)
}
}
extension JBDatePickerView {
///scrolls the next month into the visible area and creates an new 'next' month waiting in line.
public func loadNextView() {
contentController.presentNextView()
}
///scrolls the previous month into the visible area and creates an new 'previous' month waiting in line.
public func loadPreviousView() {
contentController.presentPreviousView()
}
}
|
e95338c8d5b8a17363ea72c5a1a5f0bf
| 31.308642 | 169 | 0.674054 | false | false | false | false |
apple/swift-nio
|
refs/heads/main
|
Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// The result of an ALPN negotiation.
///
/// In a system expecting an ALPN negotiation to occur, a wide range of
/// possible things can happen. In the best case scenario it is possible for
/// the server and client to agree on a protocol to speak, in which case this
/// will be `.negotiated` with the relevant protocol provided as the associated
/// value. However, if for any reason it was not possible to negotiate a
/// protocol, whether because one peer didn't support ALPN or because there was no
/// protocol overlap, we should `fallback` to a default choice of some kind.
///
/// Exactly what to do when falling back is the responsibility of a specific
/// implementation.
public enum ALPNResult: Equatable, Sendable {
/// ALPN negotiation succeeded. The associated value is the ALPN token that
/// was negotiated.
case negotiated(String)
/// ALPN negotiation either failed, or never took place. The application
/// should fall back to a default protocol choice or close the connection.
case fallback
}
/// A helper `ChannelInboundHandler` that makes it easy to swap channel pipelines
/// based on the result of an ALPN negotiation.
///
/// The standard pattern used by applications that want to use ALPN is to select
/// an application protocol based on the result, optionally falling back to some
/// default protocol. To do this in SwiftNIO requires that the channel pipeline be
/// reconfigured based on the result of the ALPN negotiation. This channel handler
/// encapsulates that logic in a generic form that doesn't depend on the specific
/// TLS implementation in use by using `TLSUserEvent`
///
/// The user of this channel handler provides a single closure that is called with
/// an `ALPNResult` when the ALPN negotiation is complete. Based on that result
/// the user is free to reconfigure the `ChannelPipeline` as required, and should
/// return an `EventLoopFuture` that will complete when the pipeline is reconfigured.
///
/// Until the `EventLoopFuture` completes, this channel handler will buffer inbound
/// data. When the `EventLoopFuture` completes, the buffered data will be replayed
/// down the channel. Then, finally, this channel handler will automatically remove
/// itself from the channel pipeline, leaving the pipeline in its final
/// configuration.
public final class ApplicationProtocolNegotiationHandler: ChannelInboundHandler, RemovableChannelHandler {
public typealias InboundIn = Any
public typealias InboundOut = Any
private let completionHandler: (ALPNResult, Channel) -> EventLoopFuture<Void>
private var waitingForUser: Bool
private var eventBuffer: [NIOAny]
/// Create an `ApplicationProtocolNegotiationHandler` with the given completion
/// callback.
///
/// - Parameter alpnCompleteHandler: The closure that will fire when ALPN
/// negotiation has completed.
public init(alpnCompleteHandler: @escaping (ALPNResult, Channel) -> EventLoopFuture<Void>) {
self.completionHandler = alpnCompleteHandler
self.waitingForUser = false
self.eventBuffer = []
}
/// Create an `ApplicationProtocolNegotiationHandler` with the given completion
/// callback.
///
/// - Parameter alpnCompleteHandler: The closure that will fire when ALPN
/// negotiation has completed.
public convenience init(alpnCompleteHandler: @escaping (ALPNResult) -> EventLoopFuture<Void>) {
self.init { result, _ in
alpnCompleteHandler(result)
}
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard let tlsEvent = event as? TLSUserEvent else {
context.fireUserInboundEventTriggered(event)
return
}
if case .handshakeCompleted(let p) = tlsEvent {
handshakeCompleted(context: context, negotiatedProtocol: p)
} else {
context.fireUserInboundEventTriggered(event)
}
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
if waitingForUser {
eventBuffer.append(data)
} else {
context.fireChannelRead(data)
}
}
private func handshakeCompleted(context: ChannelHandlerContext, negotiatedProtocol: String?) {
waitingForUser = true
let result: ALPNResult
if let negotiatedProtocol = negotiatedProtocol {
result = .negotiated(negotiatedProtocol)
} else {
result = .fallback
}
let switchFuture = self.completionHandler(result, context.channel)
switchFuture.whenComplete { (_: Result<Void, Error>) in
self.unbuffer(context: context)
context.pipeline.removeHandler(self, promise: nil)
}
}
private func unbuffer(context: ChannelHandlerContext) {
for datum in eventBuffer {
context.fireChannelRead(datum)
}
let buffer = eventBuffer
eventBuffer = []
waitingForUser = false
if buffer.count > 0 {
context.fireChannelReadComplete()
}
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension ApplicationProtocolNegotiationHandler: Sendable {}
#endif
|
c7acae41eb33499aa0a55388d5d0cff1
| 39.167832 | 106 | 0.684714 | false | false | false | false |
alvarorgtr/swift_data_structures
|
refs/heads/master
|
DataStructures/WeightedDigraph.swift
|
gpl-3.0
|
1
|
//
// Graph.swift
// DataStructures
//
// Created by Álvaro Rodríguez García on 27/5/17.
// Copyright © 2017 DeltaApps. All rights reserved.
//
import Foundation
struct WeightedDigraph<Weight: Comparable> {
public typealias Vertex = Int
public typealias Edge = DirectedWeightedGraphEdge<Vertex, Weight>
internal var edges: [List<Edge>]
public var edgeCount: Int = 0
public private(set) var vertexCount: Int
init<E: Sequence>(vertexCount: Int, edges: E) where E.Iterator.Element == Edge {
self.vertexCount = vertexCount
self.edges = Array(repeating: List<Edge>(), count: vertexCount)
for edge in edges {
if edge.from < vertexCount && edge.to < vertexCount {
add(edge: edge)
}
}
}
// MARK: Accessors
public func degree(of vertex: Vertex) -> Int {
precondition(vertex < vertexCount, "The vertex must be in the graph")
return edges[vertex].count
}
public func adjacentVertices(to vertex: Vertex) -> AnySequence<Vertex> {
precondition(vertex < vertexCount, "The vertex must be in the graph")
return AnySequence<Vertex>(self.edges[vertex].map({ (edge) -> Vertex in
return edge.to
}))
}
public func adjacentEdges(to vertex: Vertex) -> AnySequence<Edge> {
precondition(vertex < vertexCount, "The vertex must be in the graph")
return AnySequence<Edge>(self.edges[vertex].map({ (edge) -> Edge in
return edge
}))
}
// MARK: Mutators
/** Adds a vertex to the graph if it isn't already there.
- parameter vertex: the vertex to be added.
- returns: the index of the vertex.
- complexity: Amortized O(1)
*/
@discardableResult
public mutating func addVertex() -> Int {
vertexCount += 1
edges.append(List<Edge>())
return vertexCount - 1
}
/** Adds the edge from-to to the graph and the corresponding vertices if needed. Since the graph is not directed the to-from edge is also added.
- parameter from: the first vertex
- parameter to: the second vertex
- warning: this function doesn't check for parallel vertices.
*/
public mutating func addEdge(from: Vertex, to: Vertex, weight: Weight) {
precondition(from < vertexCount && to < vertexCount, "The edge has an endpoint that does not exist.")
let edge = Edge(from: from, to: to, weight: weight)
add(edge: edge)
}
/** Adds the edge from-to to the graph and the corresponding vertices if needed. Since the graph is not directed the to-from edge is also added.
- parameter edge: the edge.
- warning: this function doesn't check for parallel vertices.
*/
public mutating func add(edge: Edge) {
edges[edge.from].appendLast(edge)
edgeCount += 1
}
}
|
299e507257b4fc51d44d8298ac4eb365
| 28.303371 | 145 | 0.703988 | false | false | false | false |
psharanda/adocgen
|
refs/heads/master
|
adocgen/SourceKittenOutputParser.swift
|
mit
|
1
|
//
// Copyright © 2016 Pavel Sharanda. All rights reserved.
//
import Foundation
import SwiftyJSON
/* SAMPLE JSON
{
"\/Users\/psharanda\/Work\/adocgen\/adocgen\/CellModel.swift":{
"key.substructure":[
{
"key.kind":"source.lang.swift.decl.class",
"key.doc.comment":"Simplest type of cell. Has optional title and icon. Corresponds to cell of .Default style.",
"key.name":"DefaultCellModel",
"key.inheritedtypes":[
{
"key.name":"CellModel"
}
],
"key.substructure":[
{
"key.kind":"source.lang.swift.decl.var.instance",
"key.doc.comment":"The name of a book, chapter, poem, essay, picture, statue, piece of music, play, film, etc",
"key.typename":"String?",
"key.name":"title"
}
]
}
]
}
}
*/
struct SKField {
let comment: String?
let typename: String?
let name: String?
static func makeFromDict(_ dict: [String: JSON]) -> SKField {
return SKField(comment: dict["key.doc.comment"]?.string, typename: dict["key.typename"]?.string, name: dict["key.name"]?.string)
}
}
struct SKType {
let comment: String?
let name: String?
let inheritedTypes: [String]
let fields: [SKField]
static func makeFromDict(_ dict: [String: JSON]) -> SKType {
var inheritedTypes = [String]()
if let a = dict["key.inheritedtypes"]?.array {
for d in a {
if let t = d["key.name"].string {
inheritedTypes.append(t)
}
}
}
var fields = [SKField]()
if let a = dict["key.substructure"]?.array {
for d in a {
if let dd = d.dictionary, dd["key.kind"] == "source.lang.swift.decl.var.instance" {
fields.append(SKField.makeFromDict(dd))
}
}
}
return SKType(comment: dict["key.doc.comment"]?.string, name: dict["key.name"]?.string, inheritedTypes: inheritedTypes, fields: fields)
}
}
func parseSourceKittenOutput(_ jsonPath: String) throws -> [SKType] {
var types = [SKType]()
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) {
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
let json = JSON(jsonObject)
if let (_,jsonDict) = json.dictionary?.first,
let structure = jsonDict["key.substructure"].array {
for substr in structure {
if let substrDict = substr.dictionary {
if substrDict["key.kind"] == "source.lang.swift.decl.class" {
types.append(SKType.makeFromDict(substrDict))
}
}
}
}
}
return types
}
|
705bb3fbb4d2cc304eb0a8b7fa56dde2
| 29.213592 | 143 | 0.507712 | false | false | false | false |
jkereako/local-notifications
|
refs/heads/master
|
LocalNotifications/LocalNotifications/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// LocalNotifications
//
// Created by Jeff Kereakoglow on 9/13/15.
// Copyright © 2015 Alexis Digital. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var count = 0
private var localNotificationsAllowed = true
@IBOutlet weak var allowedTypes: UILabel?
deinit {
// Don't forget to stop observing!
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK: - View controller life cycle
extension ViewController {
override func viewDidLoad() {
super.viewDidLoad()
// The settings may not be defined at the point. For example, it's the first time the user has
// launched the app.
if let settings = UIApplication.sharedApplication().currentUserNotificationSettings() {
updateNotificationPrivilegesLabel(notificationSettings: settings)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// When the user first selects whether to allow notifications or not
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "notificationSettingsRegistered:",
name:"notificationSettingsRegistered",
object: nil
)
// When the application receives a local notification
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "applicationDidReceiveLocalNotification:",
name:"applicationDidReceiveLocalNotification",
object: nil
)
// When the application is in the foreground
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "applicationDidBecomeActive:",
name:"applicationDidBecomeActive",
object: nil
)
}
}
// MARK: - Observers
extension ViewController {
// Respond to the user's notification settings. This will only happen 1 time.
func notificationSettingsRegistered(note: NSNotification) {
if let settings = note.object as? UIUserNotificationSettings {
updateNotificationPrivilegesLabel(notificationSettings: settings)
}
}
func applicationDidReceiveLocalNotification(note: NSNotification) {
guard let notification = note.object as? UILocalNotification else {
return
}
let controller = UIAlertController(title: notification.alertTitle,
message: notification.alertBody,
preferredStyle: .Alert)
let action = UIAlertAction(title: notification.alertAction, style: .Cancel, handler: nil)
controller.addAction(action)
presentViewController(controller, animated: true, completion: nil)
}
// We have to check the user's notification settings each time this app becomes active. The
// possible scenario is when the user 1) sends this app into the background, 2) opens the Settings
// app, 3) changes his notification settings for this app, and 4) re-opens this app.
// We can't rely on the delegate methods `viewDidLoad()` and `viewDidAppear()` to be invoked
// each time the app is visible because although the app is in the background, it is still
// executing. Hence, we must respond to `applicationDidBecomeActive`.
func applicationDidBecomeActive(note: NSNotification) {
if let settings = UIApplication.sharedApplication().currentUserNotificationSettings() {
updateNotificationPrivilegesLabel(notificationSettings: settings)
}
}
}
// MARK: - Actions
extension ViewController {
@IBAction func postNotificationNowAction(_: UIButton) {
// Before building the notification, make sure you have the rights to show local notifications.
guard localNotificationsAllowed else {
showError()
return
}
// Post the local notification right away
UIApplication.sharedApplication().presentLocalNotificationNow(notification())
}
@IBAction func postNotificationLaterAction(_: UIButton) {
guard localNotificationsAllowed else {
showError()
return
}
let aNotification = notification()
// Post the local notification 5 seconds from now. The point of this is 1) to prove that the
// scheduling feature works and 2) to allow you to view the notification as a banner.
aNotification.fireDate = NSDate().dateByAddingTimeInterval(5.0)
UIApplication.sharedApplication().scheduleLocalNotification(aNotification)
}
}
// MARK: - Private helpers
extension ViewController {
private func updateNotificationPrivilegesLabel(notificationSettings settings: UIUserNotificationSettings) {
allowedTypes?.text = ""
// The best way to inspect `notificationSettings.types` is to use the Boolean expression below.
if settings.types == .None {
allowedTypes?.text = "none"
localNotificationsAllowed = false
}
else {
allowedTypes?.text?.appendContentsOf("alert, badge, sound")
localNotificationsAllowed = true
}
}
// Generate a local notification
private func notification() -> UILocalNotification {
let notification = UILocalNotification()
notification.applicationIconBadgeNumber = ++count
notification.alertTitle = "Hello"
notification.alertBody = "This is a test notification"
notification.alertAction = "Okay"
notification.soundName = UILocalNotificationDefaultSoundName
return notification
}
private func showError() {
let controller = UIAlertController(title: "Notifications prohibited",
message: "Go to Settings > LocalNotifications to change your notification preferences.",
preferredStyle: .Alert)
let action = UIAlertAction(title: "Okay", style: .Cancel, handler: nil)
controller.addAction(action)
presentViewController(controller, animated: true, completion: nil)
}
}
|
f11d77b972683c3478a4973e789c08b1
| 33.018072 | 109 | 0.732956 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
refs/heads/master
|
Sources/772_BasicCalculatorIII.swift
|
mit
|
1
|
//
// 772_BasicCalculatorIII.swift
// LeetcodeSwift
//
// Created by yansong li on 2018-04-15.
// Copyright © 2018 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:772 Basic Calculator III
URL: https://leetcode.com/problems/basic-calculator-iii/description/
Space: O(n)
Time: O(n)
*/
class BasicCalculatorIII {
func calculate(_ s: String) -> Int {
guard s.count > 0 else {
return 0
}
let (result, _) = calculate(s, startIndex: s.startIndex)
return result
}
func calculate(_ s: String, startIndex: String.Index) -> (Int, String.Index) {
guard s.count > 0 && startIndex < s.endIndex else {
return (0, s.startIndex)
}
var numbers: [Int] = []
var signs: [Character] = []
var index: String.Index = startIndex
while index < s.endIndex {
if s[index] == "+" {
signs.append("+")
} else if s[index] == "-" {
signs.append("-")
} else if s[index] == "*" {
signs.append("*")
} else if s[index] == "/" {
signs.append("/")
} else if s[index] == "(" {
let (result, updatedIndex) = calculate(s, startIndex: s.index(after:index))
handleResult(result, signs: &signs, numbers: &numbers)
index = updatedIndex
} else if s[index] == ")" {
return (numbers.reduce(0){ $0 + $1 }, index)
} else if s[index] != " " {
var localIndex = index
var numberString = ""
while localIndex < s.endIndex && s[localIndex] >= "0" && s[localIndex] <= "9" {
numberString += String(s[localIndex])
localIndex = s.index(after: localIndex)
}
let number = Int(numberString)!
handleResult(number, signs: &signs, numbers: &numbers)
index = s.index(before: localIndex)
}
index = s.index(after: index)
}
return (numbers.reduce(0){ $0 + $1 }, index)
}
func handleResult(_ number: Int, signs: inout [Character], numbers: inout [Int]) {
if signs.count > 0 {
let previousSign = signs.removeLast()
if previousSign == "+" {
numbers.append(number)
} else if previousSign == "-" {
numbers.append(number * -1)
} else if previousSign == "*" {
let previous = numbers.removeLast()
numbers.append(previous * number)
} else if previousSign == "/" {
let previous = numbers.removeLast()
numbers.append(previous / number)
}
} else {
numbers.append(number)
}
}
}
|
ee1860b2eb40a26440e7d086bc79facb
| 28.987952 | 87 | 0.568501 | false | false | false | false |
cotsog/BricBrac
|
refs/heads/master
|
BricBracPlay.playground/Contents.swift
|
mit
|
1
|
import BricBrac
//: The core element of the Bric-a-Brac framework is the `Bric` type, which is an enumeration that represents a piece of valid JSON.
//: ### Reading from a JSON String
//: A bit of `Bric` can be created from a Swift String with the `parse` function, which will throw an error if the JSON is malformed.
let parsed: Bric = try Bric.parse("[1, 2.3, true, false, null, {\"key\": \"value\"}]") // parsing a string
//: You can also create a bit of `Bric` manually using a Swift-fluent API, where literal strings, numbers, booleans, arrays, and dictionaries are specified inline.
var bric: Bric = [1, 2.3, true, false, nil, ["key": "value"]] // fluent API for building the same as above
assert(bric == parsed)
//: Elements of `Bric` arrays and objects can be accessed via their numeric and string keys, respectively.
let e0: Int? = bric[0] // 1
//: Note that accessing an array index that is out-of-bounds returns `nil` rather than raising an error
let missingElement: Bric? = bric[999] // nil (not an error when index out of bounds)
let e1: Double? = bric[1] // 2.3
let e2: Bool? = bric[2] // true
let e3: Bool? = bric[3] // false
let e4: String? = bric[4] // nil
let e5: [String: Bric]? = bric[5] // ["key": "value"]
let missingKey: String? = bric[5]?["XXX"] // nil
let keyValue: String? = bric[5]?["key"] // "value"
bric[5]?["key"] = "newValue" // same API can be used to modify Bric
let keyValue2: String? = bric[5]?["key"] // "newValue"
//: ### Writing to a JSON String
//: A bit of `Bric` can be saved out to a JSON-compliant string with the `stringify` function, outputting:
//: `[1,2.3,true,false,null,{"key":"newValue"}]`
let compact: String = bric.stringify() // compact: "[1,2.3,true,false,null,{"key":"newValue"}]"
let compact2 = String(bric) // same as above (Bric conforms to Streamable)
/*:
You can also pretty-print the bric with the `space` parameter.
*/
let pretty: String = bric.stringify(space: 2) // pretty-printed
/*:
Collections and Optionals are automatically wrapped when parsing `Bric`.
*/
let arrayOfOptionalNumbers = try Array<Optional<UInt8>>.brac(Bric.parse("[1, 2, null]"))
let arrayOfOptionalNumbers2 = try [UInt8?].brac(Bric.parse("[1, 2, null]")) // same as above
/*:
Optionality must be explicitly included in the type, or else an error will be thrown.
*/
do {
let arrayOfNonOptionalNumbers = try [UInt8].brac(Bric.parse("[1, 2, null]"))
} catch {
String(error) // "Invalid type: expected Int8, found nil"
}
/*:
When a numeric type is out of range, it will throw an error.
*/
do {
let arrayOfUnsignedInts = try [UInt8].brac(Bric.parse("[-2]"))
} catch {
String(error) // "Numeric overflow: UInt8 cannot contain -2.0"
}
/*:
Automatic rounding, however, is performed:
*/
let arrayOfRoundedUInts = try [UInt8].brac(Bric.parse("[2.345]")) // [2]
/*:
### Serializing custom types
Many of the built-in Swift types can be read/written to/from Bric via the framework adopting
the `Bricable` and `Bracable` protocols for raw types (`String`, `Int`, `Bool`, etc.)
User-defined types can also handle JSON (de-)serialization by adopting these protocols. No
requirements are made about the optionality or mutability of the given properties.
*/
/// A custom struct; no requirements about optionality or mutability of properties
struct Product : BricBrac {
let name: String
let weight: Double
var description: String?
var tags: Set<String>
func bric() -> Bric {
return ["name": name.bric(), "weight": weight.bric(), "description": description.bric(), "tags": tags.bric()]
}
static func brac(bric: Bric) throws -> Product {
return try Product(name: bric.bracKey("name"), weight: bric.bracKey("weight"), description: bric.bracKey("description"), tags: bric.bracKey("tags"))
}
}
// Create an instance from some Bric
let macbook = try Product.brac(["name": "MacBook", "weight": 2.0, "description": "A Nice Laptop", "tags": ["laptop", "computer"]])
var newMacbook = macbook // copying the stuct makes a new instance
assert(newMacbook == macbook) // equatability comes for free by adopting BricBrac
newMacbook.tags.insert("fanless")
assert(newMacbook != macbook) // no longer the same data
newMacbook.bric().stringify() // "{"name":"MacBook","weight":2,"tags":["fanless","laptop","computer"],"description":"A Nice Laptop"}"
import CoreGraphics
/// Extending an existing struct provides serialization capabilities
extension CGPoint : Bricable, Bracable {
public func bric() -> Bric {
return ["x": Bric(x.native), "y": Bric(y.native)]
}
public static func brac(bric: Bric) throws -> CGPoint {
return try CGPoint(x: bric.bracKey("x") as CGFloat.NativeType, y: bric.bracKey("y") as CGFloat.NativeType)
}
}
let points = ["first": [CGPoint(x: 1, y: 2), CGPoint(x: 4, y: 5)], "second": [CGPoint(x: 9, y: 10)]]
// Collections, Dictionaries, & Optional wrapping come for free with BricBrac
points.bric().stringify() // {"first":[{"y":2,"x":1},{"y":5,"x":4}],"second":[{"y":10,"x":9}]}
do {
try CGPoint.brac(["x": 1])
} catch {
error // Missing key for Double: «y»
}
do {
try CGPoint.brac(["x": 1, "y": false])
} catch {
error // Invalid type: expected Double, found Bool at /y
}
import Foundation
/// Example of conferring JSON serialization on an existing non-final class
extension NSDate : Bricable, Bracable {
/// ISO-8601 is the de-facto date format for JSON
private static let ISO8601Formatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter
}()
/// NSDate will be saved as a ISO-8601 string
public func bric() -> Bric {
return Bric.Str(NSDate.ISO8601Formatter.stringFromDate(self) as String)
}
/// Restore an NSDate from a "time" field
public static func brac(bric: Bric) throws -> Self {
var parsed: AnyObject?
try ISO8601Formatter.getObjectValue(&parsed, forString: bric.bracStr(), range: nil)
if let parsed = parsed as? NSDate {
return self.init(timeIntervalSinceReferenceDate: parsed.timeIntervalSinceReferenceDate)
} else {
throw BracError.InvalidType(type: NSDate.self, actual: String(parsed), path: [])
}
}
}
try NSDate.brac("2015-09-14T13:31:20-04:00") // "Sep 14, 2015, 1:31 PM"
do {
try NSDate.brac("2015-13-14T99:31:20-04:00")
} catch {
String(error) // Error Domain=NSCocoaErrorDomain Code=2048 "The value “2015-13-14T99:31:20-04:00” is invalid." UserInfo={NSInvalidValue=2015-13-14T99:31:20-04:00}
}
let dates = [
"past": [NSDate(timeIntervalSinceNow: -600), NSDate(timeIntervalSinceNow: -60)],
"present": [NSDate()],
"future": [NSDate(timeIntervalSinceNow: +60), NSDate(timeIntervalSinceNow: +600)]
]
/*:
{
"future": [
"2015-09-14T13:31:20-04:00",
"2015-09-14T13:40:20-04:00"
],
"present": [
"2015-09-14T13:30:20-04:00"
],
"past": [
"2015-09-14T13:20:20-04:00",
"2015-09-14T13:29:20-04:00"
]
}
*/
dates.bric().stringify(space: 2)
enum OrderType : String { case direct, web, phone }
/// BricBrac is automatically implemented for simple String & primitive enums
extension OrderType : BricBrac { }
let orders = try [OrderType?].brac(["direct", "web", nil]) // direct, web, nil
do {
let badOrder = try [OrderType?].brac(["phone", "fax", nil])
} catch let error as BracError {
String(error) // error: "Invalid value for OrderType: fax"
}
struct Order {
var date: NSDate
let type: OrderType
var products: [Product]
var location: CGPoint?
}
extension Order : BricBrac {
func bric() -> Bric {
return ["date": date.bric(), "type": type.bric(), "products": products.bric(), "location": location.bric()]
}
static func brac(bric: Bric) throws -> Order {
return try Order(date: bric.bracKey("date"), type: bric.bracKey("type"), products: bric.bracKey("products"), location: bric.bracKey("location"))
}
}
var order = Order(date: NSDate(), type: .direct, products: [], location: nil)
order.bric() // {"type":"direct","location":null,"date":"2015-09-14T13:31:15-04:00","products":[]}
order.products += [macbook]
order.bric() // {"type":"direct","location":null,"date":"2015-09-14T13:31:40-04:00","products":[{"name":"MacBook","weight":2,"tags":["laptop","computer"],"description":"A Nice Laptop"}]}
order.location = CGPoint(x: 1043, y: 433)
order.bric() // {"type":"direct","location":{"y":433,"x":1043},"date":"2015-09-14T13:33:16-04:00","products":[{"name":"MacBook","weight":2,"tags":["laptop","computer"],"description":"A Nice Laptop"}]}
// {"args":{},"origin":"61.46.1.98","headers":{"Accept-Encoding":"gzip, deflate","Accept-Language":"en-us","Accept":"*/*","User-Agent":"BricBracPlay/1 CFNetwork/760.0.5 Darwin/15.0.0 (x86_64)","Host":"httpbin.org"},"url":"http://httpbin.org/get"}
let rest = try Bric.parse(String(contentsOfURL: NSURL(string: "http://httpbin.org/get")!, encoding: NSUTF8StringEncoding))
|
4a53975641257b25d3a6a5a1f885e30b
| 34.9375 | 246 | 0.658696 | false | false | false | false |
petroladkin/SwiftyBluetooth
|
refs/heads/master
|
SwiftyBluetooth/Source/CBExtensions.swift
|
mit
|
1
|
//
// CBExtensions.swift
//
// Copyright (c) 2016 Jordane Belanger
//
// 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 CoreBluetooth
extension CBPeripheral {
public func serviceWithUUID(_ uuid: CBUUID) -> CBService? {
guard let services = self.services else {
return nil
}
return services.filter { $0.uuid == uuid }.first
}
public func servicesWithUUIDs(_ servicesUUIDs: [CBUUID]) -> (foundServices: [CBService], missingServicesUUIDs: [CBUUID]) {
assert(servicesUUIDs.count > 0)
guard let currentServices = self.services , currentServices.count > 0 else {
return (foundServices: [], missingServicesUUIDs: servicesUUIDs)
}
let currentServicesUUIDs = currentServices.map { $0.uuid }
let currentServicesUUIDsSet = Set(currentServicesUUIDs)
let requestedServicesUUIDsSet = Set(servicesUUIDs)
let foundServicesUUIDsSet = requestedServicesUUIDsSet.intersection(currentServicesUUIDsSet)
let missingServicesUUIDsSet = requestedServicesUUIDsSet.subtracting(currentServicesUUIDsSet)
let foundServices = currentServices.filter { foundServicesUUIDsSet.contains($0.uuid) }
return (foundServices: foundServices, missingServicesUUIDs: Array(missingServicesUUIDsSet))
}
public var uuidIdentifier: UUID {
#if os(OSX)
if #available(OSX 10.13, *) {
return self.identifier
} else {
let description: String = self.description
//<CBPeripheral: 0x6080000c3fe0 identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, Name = "(null)", state = disconnected>
guard let range = description.range(of:"identifier = .+?,", options:.regularExpression) else {
return UUID(uuidString: "11111111-1111-1111-1111-111111111111")!
}
var uuid = description.substring(with: range)
//identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67,
uuid = uuid.substring(from: uuid.index(uuid.startIndex, offsetBy: 13))
//7E33A1DD-7E65-4162-89A4-F44A2B4F9D67,
uuid = uuid.substring(to: uuid.index(before: uuid.endIndex))
//7E33A1DD-7E65-4162-89A4-F44A2B4F9D67
return UUID(uuidString: uuid)!
}
#else
return self.identifier
#endif
}
}
extension CBService {
public func characteristicWithUUID(_ uuid: CBUUID) -> CBCharacteristic? {
guard let characteristics = self.characteristics else {
return nil
}
return characteristics.filter { $0.uuid == uuid }.first
}
public func characteristicsWithUUIDs(_ characteristicsUUIDs: [CBUUID]) -> (foundCharacteristics: [CBCharacteristic], missingCharacteristicsUUIDs: [CBUUID]) {
assert(characteristicsUUIDs.count > 0)
guard let currentCharacteristics = self.characteristics , currentCharacteristics.count > 0 else {
return (foundCharacteristics: [], missingCharacteristicsUUIDs: characteristicsUUIDs)
}
let currentCharacteristicsUUID = currentCharacteristics.map { $0.uuid }
let currentCharacteristicsUUIDSet = Set(currentCharacteristicsUUID)
let requestedCharacteristicsUUIDSet = Set(characteristicsUUIDs)
let foundCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.intersection(currentCharacteristicsUUIDSet)
let missingCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.subtracting(currentCharacteristicsUUIDSet)
let foundCharacteristics = currentCharacteristics.filter { foundCharacteristicsUUIDSet.contains($0.uuid) }
return (foundCharacteristics: foundCharacteristics, missingCharacteristicsUUIDs: Array(missingCharacteristicsUUIDSet))
}
}
extension CBCharacteristic {
public func descriptorWithUUID(_ uuid: CBUUID) -> CBDescriptor? {
guard let descriptors = self.descriptors else {
return nil
}
return descriptors.filter { $0.uuid == uuid }.first
}
public func descriptorsWithUUIDs(_ descriptorsUUIDs: [CBUUID]) -> (foundDescriptors: [CBDescriptor], missingDescriptorsUUIDs: [CBUUID]) {
assert(descriptorsUUIDs.count > 0)
guard let currentDescriptors = self.descriptors , currentDescriptors.count > 0 else {
return (foundDescriptors: [], missingDescriptorsUUIDs: descriptorsUUIDs)
}
let currentDescriptorsUUIDs = currentDescriptors.map { $0.uuid }
let currentDescriptorsUUIDsSet = Set(currentDescriptorsUUIDs)
let requestedDescriptorsUUIDsSet = Set(descriptorsUUIDs)
let foundDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.intersection(currentDescriptorsUUIDsSet)
let missingDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.subtracting(currentDescriptorsUUIDsSet)
let foundDescriptors = currentDescriptors.filter { foundDescriptorsUUIDsSet.contains($0.uuid) }
return (foundDescriptors: foundDescriptors, missingDescriptorsUUIDs: Array(missingDescriptorsUUIDsSet))
}
}
|
74425c98fddec6ce61b10acde25ebd6c
| 44.013986 | 161 | 0.675781 | false | false | false | false |
NUKisZ/MyTools
|
refs/heads/master
|
MyTools/MyTools/Class/FirstVC/Controllers/GalleryViewController.swift
|
mit
|
1
|
//
// GalleryViewController.swift
// MyTools
//
// Created by gongrong on 2017/7/14.
// Copyright © 2017年 zhangk. All rights reserved.
//
import UIKit
class GalleryViewController: BaseViewController {
//普通的flow流式布局
var flowLayout:UICollectionViewFlowLayout!
//自定义的线性布局
var linearLayput:LinearCollectionViewLayout!
var collectionView:UICollectionView!
//重用的单元格的Identifier
let CellIdentifier = "myCell"
//所有书籍数据
var images = ["c#.png", "html.png", "java.png", "js.png", "php.png",
"react.png", "ruby.png", "swift.png", "xcode.png"]
override func viewDidLoad() {
super.viewDidLoad()
let changBtn = ZKTools.createButton(CGRect(x: 0, y: 0, w: 40, h: 25), title: "切换", imageName: nil, bgImageName: nil, target: self, action: #selector(changeClick(_:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: changBtn)
automaticallyAdjustsScrollViewInsets = false;
//初始化Collection View
initCollectionView()
//注册tap点击事件
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(handleTap(_:)))
collectionView.addGestureRecognizer(tapRecognizer)
}
private func initCollectionView() {
//初始化flow布局
flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: 60, height: 60)
flowLayout.sectionInset = UIEdgeInsets(top: 74, left: 0, bottom: 0, right: 0)
//初始化自定义布局
linearLayput = LinearCollectionViewLayout()
//初始化Collection View
collectionView = UICollectionView(frame: view.bounds,
collectionViewLayout: linearLayput)
//Collection View代理设置
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .white
//注册重用的单元格
collectionView.register(GalleryCollectionViewCell.self, forCellWithReuseIdentifier: CellIdentifier)
//将Collection View添加到主视图中
view.addSubview(collectionView)
}
//点击手势响应
func handleTap(_ sender:UITapGestureRecognizer){
if sender.state == UIGestureRecognizerState.ended{
let tapPoint = sender.location(in: self.collectionView)
//点击的是单元格元素
if let indexPath = self.collectionView.indexPathForItem(at: tapPoint) {
//通过performBatchUpdates对collectionView中的元素进行批量的插入,删除,移动等操作
//同时该方法触发collectionView所对应的layout的对应的动画。
self.collectionView.performBatchUpdates({ () -> Void in
self.collectionView.deleteItems(at: [indexPath])
self.images.remove(at: indexPath.row)
}, completion: nil)
}
//点击的是空白位置
else{
//新元素插入的位置(开头)
let index = 0
images.insert("xcode.png", at: index)
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}
}
}
//切换布局样式
func changeClick(_ sender: Any) {
self.collectionView.collectionViewLayout.invalidateLayout()
//交替切换新布局
let newLayout = collectionView.collectionViewLayout
.isKind(of: LinearCollectionViewLayout.self) ? flowLayout : linearLayput
collectionView.setCollectionViewLayout(newLayout!, animated: true)
collectionView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//Collection View数据源协议相关方法
extension GalleryViewController: UICollectionViewDataSource,UICollectionViewDelegate {
//获取分区数
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//获取每个分区里单元格数量
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return images.count
}
//返回每个单元格视图
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//获取重用的单元格
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:
CellIdentifier, for: indexPath) as! GalleryCollectionViewCell
//设置内部显示的图片
cell.imageView.image = UIImage(named: images[indexPath.item])
return cell
}
}
|
8b07d6861b3e499f55edbd116d5575b1
| 34.123077 | 174 | 0.621332 | false | false | false | false |
lobodart/ExtenSwift
|
refs/heads/master
|
ExtenSwift/ExtenSwift.swift
|
mit
|
1
|
//
// ExtenSwift.swift
// ExtenSwift
//
// Started by Louis BODART on 19/09/2015.
// Enjoy !
//
import Foundation
import UIKit
// MARK: Put all your class extensions below
extension Array {
/// Retrieve an element at index as optional
///
/// - author: Louis BODART
/// - parameters:
/// - Int: The index of the element to retrieve
/// - returns:
/// The element which is located at index or `nil` if index doesn't exist
func get(index: Int) -> Element? {
if index < 0 || index >= self.count {
return nil
}
return self[index]
}
}
extension Dictionary {
/// Remove the provided keys of the dictionary
///
/// - author: Louis BODART
/// - parameters:
/// - Array<Key>: An array of keys to exclude
mutating func exclude(keys: [Key]) {
for pair in self {
if keys.contains(pair.0) {
self[pair.0] = nil
}
}
}
/// Returns the current dictionary without the provided keys
///
/// - author: Louis BODART
/// - parameters:
/// - Array<Key>: An array of keys to exclude
/// - returns:
/// The instance dictionary without the provided keys
func excluded(keys: [Key]) -> Dictionary {
var excluded: Dictionary = [:]
for pair in self {
if !keys.contains(pair.0) {
excluded[pair.0] = pair.1
}
}
return excluded
}
}
extension NSDate {
/// Convert a string to date using format
///
/// - author: Louis BODART
/// - parameters:
/// - String: The string date (eg. 2015-01-01 10:00:00)
/// - String: The string date format (eg. yyyy-MM-dd HH:mm:ss)
/// - returns:
/// A NSDate object which corresponds to the string date or nil
class func dateFromString(stringDate: String, format: String) -> NSDate! {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = format
return dateFormat.dateFromString(stringDate)
}
/// Check if a date is anterior to another
///
/// - author: Louis BODART
/// - parameters:
/// - NSDate: The date to compare with
/// - returns:
/// `true` if the instance date is anterior to the provided one, `false` otherwise
func isAnteriorToDate(date: NSDate) -> Bool {
return self.compare(date) == NSComparisonResult.OrderedAscending
}
/// Check if a date is posterior to another
///
/// - author: Louis BODART
/// - parameters:
/// - NSDate: The date to compare with
/// - returns:
/// `true` if the instance date is posterior to the provided one, `false` otherwise
func isPosteriorToDate(date: NSDate) -> Bool {
return self.compare(date) == NSComparisonResult.OrderedDescending
}
/// Convert a date to string using format
///
/// - author: Louis BODART
/// - parameters:
/// - NSDate: The date to convert
/// - String: The string date format (eg. yyyy-MM-dd HH:mm:ss)
/// - returns:
/// A String which represents the provided date
class func stringFromDate(date: NSDate, format: String) -> String {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = format
return dateFormat.stringFromDate(date)
}
/// Convert date to string using format
///
/// - author: Louis BODART
/// - parameters:
/// - String: The string date format (eg. yyyy-MM-dd HH:mm:ss)
/// - returns:
/// A String which represents the instance date
func toString(format: String) -> String {
return NSDate.stringFromDate(self, format: format)
}
}
extension UIColor {
/// Create an UIColor from a hexadecimal value
///
/// - author: Louis BODART
/// - parameters:
/// - UInt32: The hexadecimal value like 0xFFFFFF
/// - Double: The alpha component of the color
/// - returns:
/// An UIColor that represents your hexadecimal color
class func colorFromHex(hexaValue: UInt32, alpha: Double = 1.0) -> UIColor {
let red = CGFloat((hexaValue & 0xFF0000) >> 16) / 256.0
let green = CGFloat((hexaValue & 0xFF00) >> 8) / 256.0
let blue = CGFloat(hexaValue & 0xFF) / 256.0
return UIColor(red: red, green: green, blue: blue, alpha: CGFloat(alpha))
}
}
extension UIViewController {
/// Instantiate a storyboard UIViewController using its identifier.
///
/// - author: Remi TELENCZAK
/// - parameters:
/// - String: The indentifier of the UIViewController
/// - String: The name of the Storyboard
/// - returns:
/// An UIViewController or nil if it doesn't exist
class func initFromStoryBoard(identifier : String, storyBoardName : String = "Main") -> UIViewController? {
let mainStoryboard = UIStoryboard(name: storyBoardName, bundle: NSBundle.mainBundle())
let view = mainStoryboard.instantiateViewControllerWithIdentifier(identifier)
return view
}
}
|
6bdf0fe547c11ba523f299c1ebb636bf
| 31.449367 | 111 | 0.592744 | false | false | false | false |
kalanyuz/SwiftR
|
refs/heads/master
|
CommonSource/macOS/NSTextLabel.swift
|
apache-2.0
|
1
|
//
// NSTextLabel.swift
// SwiftSigV
//
// Created by Kalanyu Zintus-art on 2017/02/15.
// Copyright © 2017 kalanyuz. All rights reserved.
//
open class NSTextLabel: NSTextField {
required override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.isBezeled = false
self.drawsBackground = false
self.isEditable = false
self.isSelectable = false
self.font = NSFont.systemFont(ofSize: 15)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
}
|
c40ead32644fe7b5a3ee6b22283d8512
| 20.125 | 57 | 0.712032 | false | false | false | false |
duycao2506/SASCoffeeIOS
|
refs/heads/master
|
Pods/String+Extensions/Sources/StringExtensions.swift
|
gpl-3.0
|
1
|
//
// SwiftString.swift
// SwiftString
//
// Created by Andrew Mayne on 30/01/2016.
// Copyright © 2016 Red Brick Labs. All rights reserved.
//
import Foundation
public extension String {
/// Finds the string between two bookend strings if it can be found.
///
/// - parameter left: The left bookend
/// - parameter right: The right bookend
///
/// - returns: The string between the two bookends, or nil if the bookends cannot be found, the bookends are the same or appear contiguously.
func between(_ left: String, _ right: String) -> String? {
guard
let leftRange = range(of:left), let rightRange = range(of: right, options: .backwards),
left != right && leftRange.upperBound != rightRange.lowerBound
else { return nil }
return self[leftRange.upperBound...index(before: rightRange.lowerBound)]
}
// https://gist.github.com/stevenschobert/540dd33e828461916c11
func camelize() -> String {
let source = clean(with: " ", allOf: "-", "_")
if source.characters.contains(" ") {
let first = self[self.startIndex...self.index(after: startIndex)] //source.substringToIndex(source.index(after: startIndex))
let cammel = source.capitalized.replacingOccurrences(of: " ", with: "")
// let cammel = String(format: "%@", strip)
let rest = String(cammel.characters.dropFirst())
return "\(first)\(rest)"
} else {
let first = source[self.startIndex...self.index(after: startIndex)].lowercased()
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
func capitalize() -> String {
return capitalized
}
// func contains(_ substring: String) -> Bool {
// return range(of: substring) != nil
// }
func chompLeft(_ prefix: String) -> String {
if let prefixRange = range(of: prefix) {
if prefixRange.upperBound >= endIndex {
return self[startIndex..<prefixRange.lowerBound]
} else {
return self[prefixRange.upperBound..<endIndex]
}
}
return self
}
func chompRight(_ suffix: String) -> String {
if let suffixRange = range(of: suffix, options: .backwards) {
if suffixRange.upperBound >= endIndex {
return self[startIndex..<suffixRange.lowerBound]
} else {
return self[suffixRange.upperBound..<endIndex]
}
}
return self
}
func collapseWhitespace() -> String {
let thecomponents = components(separatedBy: NSCharacterSet.whitespacesAndNewlines).filter { !$0.isEmpty }
return thecomponents.joined(separator: " ")
}
func clean(with: String, allOf: String...) -> String {
var string = self
for target in allOf {
string = string.replacingOccurrences(of: target, with: with)
}
return string
}
func count(_ substring: String) -> Int {
return components(separatedBy: substring).count-1
}
func endsWith(_ suffix: String) -> Bool {
return hasSuffix(suffix)
}
func ensureLeft(_ prefix: String) -> String {
if startsWith(prefix) {
return self
} else {
return "\(prefix)\(self)"
}
}
func ensureRight(_ suffix: String) -> String {
if endsWith(suffix) {
return self
} else {
return "\(self)\(suffix)"
}
}
@available(*, deprecated, message: "Use `index(of:)` instead")
func indexOf(_ substring: String) -> Int? {
if let range = range(of: substring) {
return self.distance(from: startIndex, to: range.lowerBound)
// return startIndex.distanceTo(range.lowerBound)
}
return nil
}
func initials() -> String {
let words = self.components(separatedBy: " ")
return words.reduce(""){$0 + $1[startIndex...startIndex]}
// return words.reduce(""){$0 + $1[0...0]}
}
func initialsFirstAndLast() -> String {
let words = self.components(separatedBy: " ")
return words.reduce("") { ($0 == "" ? "" : $0[startIndex...startIndex]) + $1[startIndex...startIndex]}
}
func isAlpha() -> Bool {
for chr in characters {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
func isAlphaNumeric() -> Bool {
let alphaNumeric = NSCharacterSet.alphanumerics
let output = self.unicodeScalars.split { !alphaNumeric.contains($0)}.map(String.init)
if output.count == 1 {
if output[0] != self {
return false
}
}
return output.count == 1
// return componentsSeparatedByCharactersInSet(alphaNumeric).joinWithSeparator("").length == 0
}
func isEmpty() -> Bool {
return self.trimmingCharacters(in: .whitespacesAndNewlines).length == 0
}
func isNumeric() -> Bool {
if let _ = defaultNumberFormatter().number(from: self) {
return true
}
return false
}
private func join<S: Sequence>(_ elements: S) -> String {
return elements.map{String(describing: $0)}.joined(separator: self)
}
func latinize() -> String {
return self.folding(options: .diacriticInsensitive, locale: .current)
// stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
}
func lines() -> [String] {
return self.components(separatedBy: NSCharacterSet.newlines)
}
var length: Int {
get {
return self.characters.count
}
}
func pad(_ n: Int, _ string: String = " ") -> String {
return "".join([string.times(n), self, string.times(n)])
}
func padLeft(_ n: Int, _ string: String = " ") -> String {
return "".join([string.times(n), self])
}
func padRight(_ n: Int, _ string: String = " ") -> String {
return "".join([self, string.times(n)])
}
func slugify(withSeparator separator: Character = "-") -> String {
let slugCharacterSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(separator)")
return latinize()
.lowercased()
.components(separatedBy: slugCharacterSet.inverted)
.filter { $0 != "" }
.joined(separator: String(separator))
}
/// split the string into a string array by white spaces
func tokenize() -> [String] {
return self.components(separatedBy: .whitespaces)
}
func split(_ separator: Character = " ") -> [String] {
return characters.split{$0 == separator}.map(String.init)
}
func startsWith(_ prefix: String) -> Bool {
return hasPrefix(prefix)
}
func stripPunctuation() -> String {
return components(separatedBy: .punctuationCharacters)
.joined(separator: "")
.components(separatedBy: " ")
.filter { $0 != "" }
.joined(separator: " ")
}
func times(_ n: Int) -> String {
return (0..<n).reduce("") { $0.0 + self }
}
func toFloat() -> Float? {
if let number = defaultNumberFormatter().number(from: self) {
return number.floatValue
}
return nil
}
func toInt() -> Int? {
if let number = defaultNumberFormatter().number(from: self) {
return number.intValue
}
return nil
}
func toBool() -> Bool? {
let trimmed = self.trimmed().lowercased()
if Int(trimmed) != 0 {
return true
}
switch trimmed {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return false
}
}
func toDate(_ format: String = "yyyy-MM-dd") -> Date? {
return dateFormatter(format).date(from: self) as Date?
}
func toDateTime(_ format: String = "yyyy-MM-dd HH:mm:ss") -> Date? {
return toDate(format)
}
func trimmedLeft() -> String {
if let range = rangeOfCharacter(from: NSCharacterSet.whitespacesAndNewlines.inverted) {
return self[range.lowerBound..<endIndex]
}
return self
}
func trimmedRight() -> String {
if let range = rangeOfCharacter(from: NSCharacterSet.whitespacesAndNewlines.inverted, options: NSString.CompareOptions.backwards) {
return self[startIndex..<range.upperBound]
}
return self
}
func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
subscript(_ r: CountableRange<Int>) -> String {
get {
let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex..<endIndex]
}
}
subscript(_ range: CountableClosedRange<Int>) -> String {
get {
return self[range.lowerBound..<range.upperBound + 1]
}
}
subscript(safe range: CountableRange<Int>) -> String {
get {
if length == 0 { return "" }
let lower = range.lowerBound < 0 ? 0 : range.lowerBound
let upper = range.upperBound < 0 ? 0 : range.upperBound
let s = index(startIndex, offsetBy: lower, limitedBy: endIndex) ?? endIndex
let e = index(startIndex, offsetBy: upper, limitedBy: endIndex) ?? endIndex
return self[s..<e]
}
}
subscript(safe range: CountableClosedRange<Int>) -> String {
get {
if length == 0 { return "" }
let closedEndIndex = index(endIndex, offsetBy: -1, limitedBy: startIndex) ?? startIndex
let lower = range.lowerBound < 0 ? 0 : range.lowerBound
let upper = range.upperBound < 0 ? 0 : range.upperBound
let s = index(startIndex, offsetBy: lower, limitedBy: closedEndIndex) ?? closedEndIndex
let e = index(startIndex, offsetBy: upper, limitedBy: closedEndIndex) ?? closedEndIndex
return self[s...e]
}
}
func substring(_ startIndex: Int, length: Int) -> String {
let start = self.characters.index(self.startIndex, offsetBy: startIndex)
let end = self.characters.index(self.startIndex, offsetBy: startIndex + length)
return self[start..<end]
}
subscript(i: Int) -> Character {
get {
let index = self.characters.index(self.startIndex, offsetBy: i)
return self[index]
}
}
// /// get the left part of the string before the index
// func left(_ range:Range<String.Index>?) -> String {
// return self.substring(to: (range?.lowerBound)!)
// }
// /// get the right part of the string after the index
// func right(_ range:Range<String.Index>?) -> String {
// return self.substring(from: self.index((range?.lowerBound)!, offsetBy:1))
// }
/// The first index of the given string
public func indexRaw(of str: String, after: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> String.Index? {
guard str.length > 0 else {
// Can't look for nothing
return nil
}
guard (str.length + after) <= self.length else {
// Make sure the string you're searching for will actually fit
return nil
}
let startRange = self.index(self.startIndex, offsetBy: after)..<self.endIndex
return self.range(of: str, options: options.removing(.backwards), range: startRange, locale: locale)?.lowerBound
}
public func index(of str: String, after: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> Int {
guard let index = indexRaw(of: str, after: after, options: options, locale: locale) else {
return -1
}
return self.distance(from: self.startIndex, to: index)
}
/// The last index of the given string
public func lastIndexRaw(of str: String, before: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> String.Index? {
guard str.length > 0 else {
// Can't look for nothing
return nil
}
guard (str.length + before) <= self.length else {
// Make sure the string you're searching for will actually fit
return nil
}
let startRange = self.startIndex..<self.index(self.endIndex, offsetBy: -before)
return self.range(of: str, options: options.inserting(.backwards), range: startRange, locale: locale)?.lowerBound
}
public func lastIndex(of str: String, before: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> Int {
guard let index = lastIndexRaw(of: str, before: before, options: options, locale: locale) else {
return -1
}
return self.distance(from: self.startIndex, to: index)
}
}
private enum ThreadLocalIdentifier {
case dateFormatter(String)
case defaultNumberFormatter
case localeNumberFormatter(Locale)
var objcDictKey: String {
switch self {
case .dateFormatter(let format):
return "SS\(self)\(format)"
case .localeNumberFormatter(let l):
return "SS\(self)\(l.identifier)"
default:
return "SS\(self)"
}
}
}
private func threadLocalInstance<T: AnyObject>(_ identifier: ThreadLocalIdentifier, initialValue: @autoclosure () -> T) -> T {
#if os(Linux)
var storage = Thread.current.threadDictionary
#else
let storage = Thread.current.threadDictionary
#endif
let k = identifier.objcDictKey
let instance: T = storage[k] as? T ?? initialValue()
if storage[k] == nil {
storage[k] = instance
}
return instance
}
private func dateFormatter(_ format: String) -> DateFormatter {
return threadLocalInstance(.dateFormatter(format), initialValue: {
let df = DateFormatter()
df.dateFormat = format
return df
}())
}
private func defaultNumberFormatter() -> NumberFormatter {
return threadLocalInstance(.defaultNumberFormatter, initialValue: NumberFormatter())
}
private func localeNumberFormatter(_ locale: Locale) -> NumberFormatter {
return threadLocalInstance(.localeNumberFormatter(locale), initialValue: {
let nf = NumberFormatter()
nf.locale = locale
return nf
}())
}
/// Add the `inserting` and `removing` functions
private extension OptionSet where Element == Self {
/// Duplicate the set and insert the given option
func inserting(_ newMember: Self) -> Self {
var opts = self
opts.insert(newMember)
return opts
}
/// Duplicate the set and remove the given option
func removing(_ member: Self) -> Self {
var opts = self
opts.remove(member)
return opts
}
}
public extension String {
func isValidEmail() -> Bool {
#if os(Linux)
let regex = try? RegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
#else
let regex = try? NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
#endif
return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil
}
/// Encode a String to Base64
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
/// Decode a String from Base64. Returns nil if unsuccessful.
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else { return nil }
return String(data: data, encoding: .utf8)
}
}
|
5883353bf53652e2c29fea111bec7523
| 31.952083 | 211 | 0.604982 | false | false | false | false |
antitypical/Manifold
|
refs/heads/master
|
Manifold/Module+Sigma.swift
|
mit
|
1
|
// Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var sigma: Module {
let Sigma = Declaration("Sigma", Datatype("A", .Type,
Datatype.Argument("B", "A" --> .Type,
[ "sigma": Telescope.Argument("a", "A", .Argument("b", ("B" as Term)["a" as Term], .End)) ]
)
))
let first = Declaration("first",
type: nil => { A in (A --> .Type) => { B in Sigma.ref[A, B] --> A } },
value: nil => { A in nil => { B in nil => { v in v[A, nil => { x in B[x] => const(x) }] } } })
let second = Declaration("second",
type: nil => { A in (A --> .Type) => { B in Sigma.ref[A, B] => { v in B[first.ref[A, B, v]] } } },
value: nil => { A in nil => { B in nil => { v in v[nil, nil => { x in B[x] => id }] } } })
return Module("Sigma", [ Sigma, first, second ])
}
}
import Prelude
|
169a016e12a716fecfb68c4a68bd8019
| 33.375 | 101 | 0.521212 | false | false | false | false |
zoulinzhya/GLTools
|
refs/heads/master
|
GLTools/Classes/UITableViewCellExtention.swift
|
mit
|
1
|
//
// UITableViewCellExtention.swift
// SwiftLearn
//
// Created by zoulin on 2017/6/30.
// Copyright © 2017年 zoulin. All rights reserved.
//
import Foundation
import UIKit
extension UITableViewCell {
//返回cell所在的UITableView
func superTableView() -> UITableView? {
for view in sequence(first: self.superview, next: { $0?.superview }) {
if let tableView = view as? UITableView {
return tableView
}
}
return nil
}
}
//UITableViewCell 里面获取UITableView 和indexPath
/*
//单元格类
class MyTableCell: UITableViewCell {
var button:UIButton!
//初始化
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
button = UIButton(frame:CGRect(x:0, y:0, width:40, height:25))
button.setTitle("点击", for:.normal) //普通状态下的文字
button.backgroundColor = UIColor.orange
button.layer.cornerRadius = 5
button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
//按钮点击
button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)
self.addSubview(button)
}
//布局
override func layoutSubviews() {
super.layoutSubviews()
button.center = CGPoint(x: bounds.size.width - 35, y: bounds.midY)
}
//按钮点击事件响应
func tapped(_ button:UIButton){
let tableView = superTableView()
let indexPath = tableView?.indexPath(for: self)
print("indexPath:\(indexPath!)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}*/
//获取任意类型的父View
extension UIView {
//返回该view所在的父view
func superView<T: UIView>(of: T.Type) -> T? {
for view in sequence(first: self.superview, next: { $0?.superview }) {
if let father = view as? T {
return father
}
}
return nil
}
}
/*
使用样例
这里对上面样例代码做个修改,之前我们在单元格中这么得到该 cell 所在的 tableView:
1
let tableView = superTableView()
现在改成这样:
1
let tableView = superView(of: UITableView.self)
*/
//MARK: - Swift - 在单元格里的按钮点击事件中获取对应的cell以及indexPath
/*
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
//总数
var sum = 0
override func loadView() {
super.loadView()
self.title = "总数:\(sum)"
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.allowsSelection = false
}
//返回表格行数(也就是返回控件数)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
//创建各单元显示内容(创建参数indexPath指定的单元)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
//创建一个重用的单元格
let cell = tableView
.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
let label = cell.viewWithTag(1) as! UILabel
label.text = "\(indexPath.row)"
return cell
}
//单元格中的按钮点击
@IBAction func tapAddButton(_ sender: AnyObject) {
let btn = sender as! UIButton
let cell = superUITableViewCell(of: btn)!
let label = cell.viewWithTag(1) as! UILabel
sum = sum + (label.text! as NSString).integerValue
self.title = "总数:\(sum)"
}
//返回button所在的UITableViewCell
func superUITableViewCell(of: UIButton) -> UITableViewCell? {
for view in sequence(first: of.superview, next: { $0?.superview }) {
if let cell = view as? UITableViewCell {
return cell
}
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}*/
/*
2,功能改进
(1)我们可以通过扩展 UIView,让我们可以获得任意视图对象(View)所在的指定类型的父视图。
extension UIView {
//返回该view所在的父view
func superView<T: UIView>(of: T.Type) -> T? {
for view in sequence(first: self.superview, next: { $0?.superview }) {
if let father = view as? T {
return father
}
}
return nil
}
}
(2)在 button 点击事件中可以这么获取到对应的 cell:
//单元格中的按钮点击
@IBAction func tapAddButton(_ sender: AnyObject) {
let btn = sender as! UIButton
let cell = btn.superView(of: UITableViewCell.self)!
let label = cell.viewWithTag(1) as! UILabel
sum = sum + (label.text! as NSString).integerValue
self.title = "总数:\(sum)"
}
3,在点击事件中获取对应的indexPath
获取到 cell 后,通过 tableView 的 indexPath(for:) 方法即可得到对应的 indexPath。
//单元格中的按钮点击
@IBAction func tapAddButton(_ sender: AnyObject) {
let btn = sender as! UIButton
let cell = btn.superView(of: UITableViewCell.self)!
let indexPath = tableView.indexPath(for: cell)
print("indexPath:\(indexPath!)")
}*/
|
e2b3333cfa6631740e37f288d67aa442
| 25.252632 | 89 | 0.615878 | false | false | false | false |
smogun/KVLAnimatedLoader
|
refs/heads/master
|
Pods/KVLHelpers/KVLHelpers/KVLHelpers/Extensions/UIView+Extension.swift
|
mit
|
1
|
//
// UIView+Extension.swift
// KVLArounder
//
// Created by Misha Koval on 9/18/15.
// Copyright (c) 2015 Misha Koval. All rights reserved.
//
import UIKit
public extension UIView
{
/**
* Shortcut for frame.origin
*/
public var origin:CGPoint{get{return self.frame.origin}}
/**
* Shortcut for frame.size
*/
public var size:CGSize{get{return self.frame.size}}
/**
* Shortcut for frame.origin.x + width
*/
public var endX:CGFloat{get{return self.frame.origin.x + self.frame.size.width}}
/**
* Shortcut for frame.origin.y + frame.size.height
*/
public var endY:CGFloat{get{return self.frame.origin.y + self.frame.size.height}}
/**
* Shortcut to add subview at center of view
*/
public func addSubviewAtCenter(subView: UIView?)
{
if (subView == nil)
{
return;
}
var subViewFrame = subView!.frame;
subViewFrame.origin.x = self.size.width / 2 - subViewFrame.size.width / 2;
subViewFrame.origin.y = self.size.height / 2 - subViewFrame.size.height / 2;
subView!.frame = subViewFrame;
self.addSubview(subView!);
}
/**
* Shortcut to add subview at center of view horizontally
*/
public func addSubviewAtCenterHorizontally(subView: UIView?, originY: CGFloat)
{
if (subView == nil)
{
return;
}
var subViewFrame = subView!.frame;
subViewFrame.origin.x = self.size.width / 2 - subViewFrame.size.width / 2;
subViewFrame.origin.y = originY;
subView!.frame = subViewFrame;
self.addSubview(subView!);
}
}
|
fa2332de64329a4d9eb0505cf67a6cbc
| 20.925926 | 85 | 0.570704 | false | false | false | false |
Bajocode/ExploringModerniOSArchitectures
|
refs/heads/master
|
Architectures/VIPER/View/DetailViewController.swift
|
mit
|
1
|
//
// DetailViewController.swift
// Architectures
//
// Created by Fabijan Bajo on 31/05/2017.
//
//
import UIKit
class DetailViewController: UIViewController {
// MARK: - Properties
var presentableObject: Transportable!
// Use lazy to access self.view when instantiated
private lazy var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.center = self.view.center
indicator.hidesWhenStopped = true
return indicator
}()
private lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: self.view.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
// MARK: - Methods
private func configure() {
// View setup
view.backgroundColor = .black
view.addSubview(imageView)
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
// Image fetching
var imageURL: URL!
switch presentableObject {
case let moviePresentable as MovieResultsInteractor.PresentableInstance:
tabBarController?.navigationItem.title = moviePresentable.title
imageURL = moviePresentable.fullSizeURL
case let actorPresentable as ActorResultsInteractor.PresentableInstance:
tabBarController?.navigationItem.title = actorPresentable.name
imageURL = actorPresentable.fullSizeURL
default: break
}
imageView.downloadImage(from: imageURL) {
self.activityIndicator.stopAnimating()
}
}
}
|
baf19aa4f9d34fd723808bc10778f44b
| 27.384615 | 80 | 0.650407 | false | false | false | false |
picaso/parrot-zik-status
|
refs/heads/master
|
ParrotStatus/controllers/ZikMenuViewController.swift
|
mit
|
1
|
import Cocoa
import FlatUIColors
import ITSwitch
import Swinject
class ZikMenuViewController: NSViewController {
@IBOutlet weak var header: NSView!
@IBOutlet weak var footer: Footer!
@IBOutlet weak var swVersion: NSTextField!
@IBOutlet weak var percentage: NSTextField!
@IBOutlet weak var batteryStatus: NSImageView!
@IBOutlet weak var noiseControlStatus: ITSwitch!
@IBOutlet weak var equalizerStatus: ITSwitch!
@IBOutlet weak var concertHallStatus: ITSwitch!
@IBOutlet weak var headDetectionStatus: ITSwitch!
@IBOutlet weak var flightMode: ITSwitch!
var service: BTCommunicationServiceInterface?
var deviceState: DeviceState! = nil
var about: AboutProtocol?
var notification = ParrotNotification()
fileprivate var enableNotification = true
let notificationCenter = NotificationCenter.default
override func viewDidLoad() {
super.viewDidLoad()
NSApplication.shared().activate(ignoringOtherApps: true)
}
override func viewWillAppear() {
preferredContentSize = view.fittingSize
makeViewPretty()
notificationCenter
.addObserver(
self, selector: #selector(refreshView),
name: NSNotification.Name(rawValue: "refreshDataState"),
object: nil
)
refreshView()
}
fileprivate func makeViewPretty() {
header.backgroundColor = FlatUIColors.midnightBlue()
view.backgroundColor = FlatUIColors.wetAsphalt()
}
fileprivate func updateBatteryStatus() {
if deviceState.batteryStatus == "in_use" {
switch Int(self.deviceState.batteryLevel)! {
case 5..<20:
self.batteryStatus.image = NSImage(named: "battery1")
allowNotification()
case 20..<51:
self.batteryStatus.image = NSImage(named: "battery2")
case 51..<90:
self.batteryStatus.image = NSImage(named: "battery3")
case 90..<101:
self.batteryStatus.image = NSImage(named: "battery4")
default:
self.batteryStatus.image = NSImage(named: "batteryDead")
if enableNotification {
ParrotNotification.show(
"Headphone battery is about to die",
informativeText: "Please connect to an outlet to charge")
}
enableNotification = false
}
} else {
self.batteryStatus.image = NSImage(named: "batteryCharging")
}
}
@objc fileprivate func refreshView() {
DispatchQueue.main.async {
self.updateBatteryStatus()
self.noiseControlStatus.checked = self.deviceState.noiseCancellationEnabled
self.equalizerStatus.checked = self.deviceState.equalizerEnabled
self.concertHallStatus.checked = self.deviceState.concertHallEnabled
self.swVersion.stringValue = "Version: \(self.deviceState.version)"
self.percentage.stringValue = "\(self.deviceState.batteryLevel)%"
self.footer.deviceName.stringValue = self.deviceState.name
self.headDetectionStatus.checked = self.deviceState.headDetectionEnabled
self.flightMode.checked = self.deviceState.flightModeEnabled
}
}
fileprivate func allowNotification() {
if !enableNotification {
enableNotification = true
}
}
@IBAction func noiseControlSwitch(_ sender: ITSwitch) {
let _ = service?.toggleAsyncNoiseCancellation(sender.checked)
}
@IBAction func equalizerSwitch(_ sender: ITSwitch) {
let _ = service?.toggleAsyncEqualizerStatus(sender.checked)
}
@IBAction func concertHallSwitch(_ sender: ITSwitch) {
let _ = service?.toggleAsyncConcertHall(sender.checked)
}
@IBAction func headDetectionSwitch(_ sender: ITSwitch) {
let _ = service?.toggleAsyncHeadDetection(sender.checked)
}
@IBAction func flightModeSwitch(_ sender: ITSwitch) {
let _ = service?.toggleAsyncFlightMode(sender.checked)
}
}
|
e9cedbf59d8c1bcdb40f07dfc55794e0
| 33.413223 | 87 | 0.645053 | false | false | false | false |
rvanmelle/LeetSwift
|
refs/heads/master
|
Problems.playground/Pages/Coin Change 2.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
import XCTest
/*
https://leetcode.com/problems/coin-change-2/#/description
518. Coin Change 2
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Note: You can assume that
0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer
Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
*/
func descend(_ coins:[Int], _ idx:Int, _ amount:Int, _ total:Int) -> Int {
let denomination = coins[idx]
if total + denomination == amount {
return 1
}
if total + denomination < amount {
if idx + 1 < coins.count {
return descend(coins, idx, amount, total + denomination)
+ descend(coins, idx+1, amount, total + coins[idx+1])
} else {
return descend(coins, idx, amount, total + denomination)
}
}
return 0
}
func change(_ amount: Int, _ coins: [Int]) -> Int {
var result = 0
for i in 0...coins.count - 1 {
result += descend(coins, i, amount, 0)
}
return result
}
change(5, [1,2,5])
//XCTAssert( change(5, [1,2,5]) == 4 )
change(3, [2])
change(10, [10])
change(10, [5,2,1])
change(10, [1,2])
//: [Next](@next)
|
6dd926418bd7ef7aa20bd26871832187
| 23.169014 | 224 | 0.622378 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/ClangImporter/experimental_diagnostics_cstructs.swift
|
apache-2.0
|
9
|
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s 2>&1 | %FileCheck %s --strict-whitespace
import ctypes
let s: PartialImport
s.c = 5
// CHECK: experimental_diagnostics_cstructs.swift:{{[0-9]+}}:3: error: value of type 'PartialImport' has no member 'c'
// CHECK-NEXT: s.c = 5
// CHECK-NEXT: ~ ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: field 'c' not imported
// CHECK-NEXT: int _Complex c;
// CHECK-NEXT: ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: built-in type 'Complex' not supported
// CHECK-NEXT: int _Complex c;
// CHECK-NEXT: ^
partialImport.c = 5
// CHECK: experimental_diagnostics_cstructs.swift:{{[0-9]+}}:15: error: value of type 'PartialImport' has no member 'c'
// CHECK-NEXT: partialImport.c = 5
// CHECK-NEXT: ~~~~~~~~~~~~~ ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: field 'c' not imported
// CHECK-NEXT: int _Complex c;
// CHECK-NEXT: ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: built-in type 'Complex' not supported
// CHECK-NEXT: int _Complex c;
// CHECK-NEXT: ^
var newPartialImport = PartialImport()
newPartialImport.a = 5
newPartialImport.b = 5
newPartialImport.d = 5
// CHECK: experimental_diagnostics_cstructs.swift:{{[0-9]+}}:18: error: value of type 'PartialImport' has no member 'd'
// CHECK-NEXT: newPartialImport.d = 5
// CHECK-NEXT: ~~~~~~~~~~~~~~~~ ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: field 'd' not imported
// CHECK-NEXT: int _Complex d;
// CHECK-NEXT: ^
// CHECK-NEXT: ctypes.h:{{[0-9]+}}:3: note: built-in type 'Complex' not supported
// CHECK-NEXT: int _Complex d;
// CHECK-NEXT: ^
|
1bab21d3a108ce08245266295d19c5f4
| 39.225 | 124 | 0.633313 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
stdlib/public/core/UnicodeData.swift
|
apache-2.0
|
10
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
internal typealias ScalarAndNormData = (
scalar: Unicode.Scalar,
normData: Unicode._NormData
)
extension Unicode {
// A wrapper type over the normalization data value we receive when we
// lookup a scalar's normalization information. The layout of the underlying
// 16 bit value we receive is as follows:
//
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// └───┬───┘ └──── CCC ────┘ └─┘ │
// │ │ └── NFD_QC
// │ └── NFC_QC
// └── Unused
//
// NFD_QC: This is a simple Yes/No on whether the scalar has canonical
// decomposition. Note: Yes is indicated via 0 instead of 1.
//
// NFC_QC: This is either Yes/No/Maybe on whether the scalar is NFC quick
// check. Yes, represented as 0, means the scalar can NEVER compose
// with another scalar previous to it. No, represented as 1, means the
// scalar can NEVER appear within a well formed NFC string. Maybe,
// represented as 2, means the scalar could appear with an NFC string,
// but further information is required to determine if that is the
// case. At the moment, we really only care about Yes/No.
//
// CCC: This is the canonical combining class property of a scalar that is
// used when sorting scalars of a normalization segment after NFD
// computation. A scalar with a CCC value of 128 can NEVER appear before
// a scalar with a CCC value of 100, unless there are normalization
// boundaries between them.
//
internal struct _NormData {
var rawValue: UInt16
var ccc: UInt8 {
UInt8(truncatingIfNeeded: rawValue >> 3)
}
var isNFCQC: Bool {
rawValue & 0x6 == 0
}
var isNFDQC: Bool {
rawValue & 0x1 == 0
}
init(_ scalar: Unicode.Scalar, fastUpperbound: UInt32 = 0xC0) {
if _fastPath(scalar.value < fastUpperbound) {
// CCC = 0, NFC_QC = Yes, NFD_QC = Yes
rawValue = 0
} else {
rawValue = _swift_stdlib_getNormData(scalar.value)
// Because we don't store precomposed hangul in our NFD_QC data, these
// will return true for NFD_QC when in fact they are not.
if (0xAC00 ... 0xD7A3).contains(scalar.value) {
// NFD_QC = false
rawValue |= 0x1
}
}
}
init(rawValue: UInt16) {
self.rawValue = rawValue
}
}
}
extension Unicode {
// A wrapper type for normalization buffers in the NFC and NFD iterators.
// This helps remove some of the buffer logic like removal and sorting out of
// the iterators and into this type.
internal struct _NormDataBuffer {
var storage: [ScalarAndNormData] = []
// This is simply a marker denoting that we've built up our storage, and
// now everything within it needs to be emitted. We reverse the buffer and
// pop elements from the back as a way to remove them.
var isReversed = false
var isEmpty: Bool {
storage.isEmpty
}
var last: ScalarAndNormData? {
storage.last
}
mutating func append(_ scalarAndNormData: ScalarAndNormData) {
_internalInvariant(!isReversed)
storage.append(scalarAndNormData)
}
// Removes the first element from the buffer. Note: it is not safe to append
// to the buffer after this function has been called. We reverse the storage
// internally for everything to be emitted out, so appending would insert
// into the storage at the wrong location. One must continue to call this
// function until a 'nil' return value has been received before appending.
mutating func next() -> ScalarAndNormData? {
guard !storage.isEmpty else {
isReversed = false
return nil
}
// If our storage hasn't been reversed yet, do so now.
if !isReversed {
storage.reverse()
isReversed = true
}
return storage.removeLast()
}
// Sort the entire buffer based on the canonical combining class.
mutating func sort() {
storage._insertionSort(within: storage.indices) {
$0.normData.ccc < $1.normData.ccc
}
}
}
}
extension Unicode {
// A wrapper type over the decomposition entry value we receive when we
// lookup a scalar's canonical decomposition. The layout of the underlying
// 32 bit value we receive is as follows:
//
// Top 14 bits Bottom 18 bits
//
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// └───────── Index ─────────┘ └───────── Hashed Scalar ─────────┘
//
// Index: This is the direct index into '_swift_stdlib_nfd_decompositions'
// that points to a size byte indicating the overall size of the
// UTF-8 decomposition string. Following the size byte is said string.
//
// Hashed Scalar: Because perfect hashing doesn't know the original set of
// keys it was hashed with, we store the original scalar in the
// decomposition entry so that we can guard against scalars
// who happen to hash to the same index.
//
internal struct _DecompositionEntry {
let rawValue: UInt32
// Our original scalar is stored in the first 18 bits of this entry.
var hashedScalar: Unicode.Scalar {
Unicode.Scalar(_value: (rawValue << 14) >> 14)
}
// The index into the decomposition array is stored in the top 14 bits.
var index: Int {
Int(truncatingIfNeeded: rawValue >> 18)
}
// A buffer pointer to the UTF8 decomposition string.
var utf8: UnsafeBufferPointer<UInt8> {
let decompPtr = _swift_stdlib_nfd_decompositions._unsafelyUnwrappedUnchecked
// This size is the utf8 length of the decomposition.
let size = Int(truncatingIfNeeded: decompPtr[index])
return UnsafeBufferPointer(
// We add 1 here to skip the size byte.
start: decompPtr + index + 1,
count: size
)
}
init(_ scalar: Unicode.Scalar) {
rawValue = _swift_stdlib_getDecompositionEntry(scalar.value)
}
}
}
|
bdae1f42f567d0c6b7d06526ce480c2d
| 33.952381 | 82 | 0.621405 | false | false | false | false |
KarlWarfel/nutshell-ios
|
refs/heads/roll-back
|
Nutshell/DataModel/CoreData/Status.swift
|
bsd-2-clause
|
1
|
//
// Status.swift
// Nutshell
//
// Created by Brian King on 9/15/15.
// Copyright © 2015 Tidepool. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
class Status: DeviceMetadata {
override class func fromJSON(json: JSON, moc: NSManagedObjectContext) -> Status? {
if let entityDescription = NSEntityDescription.entityForName("Status", inManagedObjectContext: moc) {
let me = Status(entity: entityDescription, insertIntoManagedObjectContext: nil)
me.status = json["status"].string
me.reason = json["reason"].string
me.duration = json["duration"].number
return me
}
return nil
}
}
|
db116a088567618801f83584d484cd49
| 26.37037 | 109 | 0.625169 | false | false | false | false |
ortizraf/macsoftwarecenter
|
refs/heads/master
|
Mac Application Store/CategoriesController.swift
|
gpl-3.0
|
1
|
//
// CategoriesController.swift
// Mac Software Center
//
// Created by Rafael Ortiz.
// Copyright © 2017 Nextneo. All rights reserved.
//
import Cocoa
class CategoriesController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource {
@IBOutlet weak var collectionView: NSCollectionView!
@IBOutlet weak var buttonFeaturedView: NSButton!
@IBOutlet weak var spinnerView: NSProgressIndicator!
static func instantiate() -> CategoriesController {
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let categoriesViewController = mainStoryboard.instantiateController(withIdentifier: "categoriesViewController") as! CategoriesController
return categoriesViewController
}
var categories: [Category]?
override func viewDidLoad() {
super.viewDidLoad()
let dbCategory = CategoryDB()
self.categories = dbCategory.getAllCategory()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func clickFeaturedButton(){
self.buttonFeaturedView.target = self
self.buttonFeaturedView.action = #selector(CategoriesController.clickActionToFeaturedController)
}
@IBAction func clickActionToFeaturedController(sender: AnyObject) {
print("click button Featured")
actionToFeaturedController(categorySelected: nil)
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return categories?.count ?? 0
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "LabelCollectionViewCategory") , for: indexPath) as! LabelCollectionViewCategory
item.buildCategory = categories?[indexPath.item]
return item
}
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
print("category selected")
for indexPath in indexPaths {
print(indexPath.description)
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "LabelCollectionViewCategory") , for: indexPath) as! LabelCollectionViewCategory
item.buildCategory = categories?[indexPath.item]
getCategorySelected(item)
}
}
func getCategorySelected(_ item: LabelCollectionViewCategory) {
actionToFeaturedController(categorySelected: item.buildCategory)
}
func actionToFeaturedController(categorySelected: Category?) {
showProgressIndicator()
self.view.wantsLayer = true
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let productViewController = mainStoryboard.instantiateController(withIdentifier: "productViewController") as! ProductController
if(categorySelected != nil){
productViewController.taskName = "category"
productViewController.categoryId = (categorySelected?.id)!
}
for view in self.view.subviews {
view.removeFromSuperview()
}
self.insertChild(productViewController, at: 0)
self.view.addSubview(productViewController.view)
self.view.frame = productViewController.view.frame
}
func showProgressIndicator(){
spinnerView.isHidden = false
spinnerView.startAnimation(spinnerView)
}
}
|
10714f26149663627c695b0ad10a8707
| 33.044643 | 183 | 0.672961 | false | false | false | false |
russbishop/swift
|
refs/heads/master
|
validation-test/compiler_crashers_2_fixed/0022-rdar21625478.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend %s -emit-silgen
import StdlibUnittest
public struct MyRange<Bound : ForwardIndex> {
var startIndex: Bound
var endIndex: Bound
}
public protocol ForwardIndex : Equatable {
associatedtype Distance : SignedNumber
func successor() -> Self
}
public protocol MySequence {
associatedtype Iterator : IteratorProtocol
associatedtype SubSequence = Void
func makeIterator() -> Iterator
var underestimatedCount: Int { get }
func map<T>(
_ transform: @noescape (Iterator.Element) -> T
) -> [T]
func filter(
_ includeElement: @noescape (Iterator.Element) -> Bool
) -> [Iterator.Element]
func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool?
func _preprocessingPass<R>(
_ preprocess: @noescape (Self) -> R
) -> R?
func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Iterator.Element>
func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element>
}
extension MySequence {
var underestimatedCount: Int {
return 0
}
public func map<T>(
_ transform: @noescape (Iterator.Element) -> T
) -> [T] {
return []
}
public func filter(
_ includeElement: @noescape (Iterator.Element) -> Bool
) -> [Iterator.Element] {
return []
}
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}
public func _preprocessingPass<R>(
_ preprocess: @noescape (Self) -> R
) -> R? {
return nil
}
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Iterator.Element> {
fatalError()
}
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element> {
fatalError()
}
}
public protocol MyIndexable : MySequence {
associatedtype Index : ForwardIndex
var startIndex: Index { get }
var endIndex: Index { get }
associatedtype _Element
subscript(_: Index) -> _Element { get }
}
public protocol MyCollection : MyIndexable {
associatedtype Iterator : IteratorProtocol = IndexingIterator<Self>
associatedtype SubSequence : MySequence
subscript(_: Index) -> Iterator.Element { get }
subscript(_: MyRange<Index>) -> SubSequence { get }
var first: Iterator.Element? { get }
var isEmpty: Bool { get }
var count: Index.Distance { get }
func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index??
}
extension MyCollection {
public var isEmpty: Bool {
return startIndex == endIndex
}
public func _preprocessingPass<R>(
_ preprocess: @noescape (Self) -> R
) -> R? {
return preprocess(self)
}
public var count: Index.Distance { return 0 }
public func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? {
return nil
}
}
public struct IndexingIterator<I : MyIndexable> : IteratorProtocol {
public func next() -> I._Element? {
return nil
}
}
protocol Resettable : AnyObject {
func reset()
}
internal var _allResettables: [Resettable] = []
public class TypeIndexed<Value> : Resettable {
public init(_ value: Value) {
self.defaultValue = value
_allResettables.append(self)
}
public subscript(t: Any.Type) -> Value {
get {
return byType[ObjectIdentifier(t)] ?? defaultValue
}
set {
byType[ObjectIdentifier(t)] = newValue
}
}
public func reset() { byType = [:] }
internal var byType: [ObjectIdentifier:Value] = [:]
internal var defaultValue: Value
}
//===--- LoggingWrappers.swift --------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public protocol Wrapper {
associatedtype Base
init(_: Base)
var base: Base {get set}
}
public protocol LoggingType : Wrapper {
associatedtype Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return self.dynamicType
}
}
public class IteratorLog {
public static func dispatchTester<G : IteratorProtocol>(
_ g: G
) -> LoggingIterator<LoggingIterator<G>> {
return LoggingIterator(LoggingIterator(g))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base: IteratorProtocol>
: IteratorProtocol, LoggingType {
public typealias Log = IteratorLog
public init(_ base: Base) {
self.base = base
}
public mutating func next() -> Base.Element? {
Log.next[selfType] += 1
return base.next()
}
public var base: Base
}
public class SequenceLog {
public static func dispatchTester<S: MySequence>(
_ s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(LoggingSequence(s))
}
public static var iterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var map = TypeIndexed(0)
public static var filter = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _preprocessingPass = TypeIndexed(0)
public static var _copyToNativeArrayBuffer = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
}
public protocol LoggingSequenceType : MySequence, LoggingType {
associatedtype Base : MySequence
associatedtype Log : AnyObject = SequenceLog
associatedtype Iterator : IteratorProtocol = LoggingIterator<Base.Iterator>
}
extension LoggingSequenceType {
public var underestimatedCount: Int {
SequenceLog.underestimatedCount[selfType] += 1
return base.underestimatedCount
}
}
extension LoggingSequenceType
where Log == SequenceLog, Iterator == LoggingIterator<Base.Iterator> {
public func makeIterator() -> LoggingIterator<Base.Iterator> {
Log.iterator[selfType] += 1
return LoggingIterator(base.makeIterator())
}
public func map<T>(
_ transform: @noescape (Base.Iterator.Element) -> T
) -> [T] {
Log.map[selfType] += 1
return base.map(transform)
}
public func filter(
_ includeElement: @noescape (Base.Iterator.Element) -> Bool
) -> [Base.Iterator.Element] {
Log.filter[selfType] += 1
return base.filter(includeElement)
}
public func _customContainsEquatableElement(
_ element: Base.Iterator.Element
) -> Bool? {
Log._customContainsEquatableElement[selfType] += 1
return base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(
_ preprocess: @noescape (Self) -> R
) -> R? {
Log._preprocessingPass[selfType] += 1
return base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
Log._copyToNativeArrayBuffer[selfType] += 1
return base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) -> UnsafeMutablePointer<Base.Iterator.Element> {
Log._copyContents[selfType] += 1
return base._copyContents(initializing: ptr)
}
}
public struct LoggingSequence<
Base_: MySequence
> : LoggingSequenceType, MySequence {
public typealias Log = SequenceLog
public typealias Base = Base_
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public class CollectionLog : SequenceLog {
public class func dispatchTester<C: MyCollection>(
_ c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(LoggingCollection(c))
}
static var startIndex = TypeIndexed(0)
static var endIndex = TypeIndexed(0)
static var subscriptIndex = TypeIndexed(0)
static var subscriptRange = TypeIndexed(0)
static var isEmpty = TypeIndexed(0)
static var count = TypeIndexed(0)
static var _customIndexOfEquatableElement = TypeIndexed(0)
static var first = TypeIndexed(0)
}
public protocol LoggingCollectionType : LoggingSequenceType, MyCollection {
associatedtype Base : MyCollection
associatedtype Index : ForwardIndex = Base.Index
}
extension LoggingCollectionType
where Index == Base.Index {
public var startIndex: Base.Index {
CollectionLog.startIndex[selfType] += 1
return base.startIndex
}
public var endIndex: Base.Index {
CollectionLog.endIndex[selfType] += 1
return base.endIndex
}
public subscript(position: Base.Index) -> Base.Iterator.Element {
CollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
public subscript(_prext_bounds: MyRange<Base.Index>) -> Base.SubSequence {
CollectionLog.subscriptRange[selfType] += 1
return base[_prext_bounds]
}
public var isEmpty: Bool {
CollectionLog.isEmpty[selfType] += 1
return base.isEmpty
}
public var count: Base.Index.Distance {
CollectionLog.count[selfType] += 1
return base.count
}
public func _customIndexOfEquatableElement(_ element: Base.Iterator.Element) -> Base.Index?? {
CollectionLog._customIndexOfEquatableElement[selfType] += 1
return base._customIndexOfEquatableElement(element)
}
public var first: Base.Iterator.Element? {
CollectionLog.first[selfType] += 1
return base.first
}
}
public struct LoggingCollection<Base_ : MyCollection> : LoggingCollectionType {
public typealias Iterator = LoggingIterator<Base.Iterator>
public typealias Log = CollectionLog
public typealias Base = Base_
public typealias SubSequence = Base.SubSequence
public func makeIterator() -> Iterator {
return Iterator(base.makeIterator())
}
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public func expectCustomizable<
T : Wrapper where
T : LoggingType,
T.Base : Wrapper, T.Base : LoggingType,
T.Log == T.Base.Log
>(_: T, _ counters: TypeIndexed<Int>,
stackTrace: SourceLocStack? = nil,
file: String = #file, line: UInt = #line,
collectMoreInfo: (()->String)? = nil
) {
expectNotEqual(
0, counters[T.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
expectEqual(
counters[T.self], counters[T.Base.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
}
public func expectNotCustomizable<
T : Wrapper where
T : LoggingType,
T.Base : Wrapper, T.Base : LoggingType,
T.Log == T.Base.Log
>(_: T, _ counters: TypeIndexed<Int>,
stackTrace: SourceLocStack? = nil,
file: String = #file, line: UInt = #line,
collectMoreInfo: (()->String)? = nil
) {
expectNotEqual(
0, counters[T.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
expectEqual(
0, counters[T.Base.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
}
|
c34e0db195f7e3ad3b2fe71f66535c73
| 25.761124 | 96 | 0.690032 | false | false | false | false |
22377832/swiftdemo
|
refs/heads/master
|
BitcoinSwift/Sources/3rd/CryptoSwift/Cipher.swift
|
apache-2.0
|
13
|
//
// Cipher.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 29/05/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
public enum CipherError: Error {
case encrypt
case decrypt
}
public protocol Cipher: class {
/// Encrypt given bytes at once
///
/// - parameter bytes: Plaintext data
/// - returns: Encrypted data
func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int, C.SubSequence: Collection, C.SubSequence.Iterator.Element == C.Iterator.Element, C.SubSequence.Index == C.Index, C.SubSequence.IndexDistance == C.IndexDistance
/// Decrypt given bytes at once
///
/// - parameter bytes: Ciphertext data
/// - returns: Plaintext data
func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int, C.SubSequence: Collection, C.SubSequence.Iterator.Element == C.Iterator.Element, C.SubSequence.Index == C.Index, C.SubSequence.IndexDistance == C.IndexDistance
}
|
9ef985644e645168f7b5a604f2dc7e48
| 41.461538 | 301 | 0.692935 | false | false | false | false |
ViennaRSS/vienna-rss
|
refs/heads/master
|
Vienna/Sources/Shared/WebKitContextMenuCustomizer.swift
|
apache-2.0
|
3
|
//
// WebKitContextMenuCustomizer.swift
// Vienna
//
// Copyright 2021 Tassilo Karge
//
// 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 Cocoa
class WebKitContextMenuCustomizer: BrowserContextMenuDelegate {
func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] {
var menuItems = existingMenuItems
switch purpose {
case .page(url: _):
break
case .link(let url):
addLinkMenuCustomizations(&menuItems, url)
case .picture:
break
case .pictureLink(image: _, link: let link):
addLinkMenuCustomizations(&menuItems, link)
case .text:
break
}
return menuItems
}
func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) {
guard var index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) else {
return
}
if let openInBackgroundIndex = menuItems.firstIndex(where: { $0.identifier == NSUserInterfaceItemIdentifier.WKMenuItemOpenLinkInBackground }) {
// Swap open link in new tab and open link in background items if
// necessary/
let openInBackground = Preferences.standard.openLinksInBackground
if openInBackground && index < openInBackgroundIndex
|| !openInBackground && openInBackgroundIndex < index {
menuItems.swapAt(index, openInBackgroundIndex)
}
index = max(index, openInBackgroundIndex)
}
let defaultBrowser = getDefaultBrowser() ?? NSLocalizedString("External Browser", comment: "")
let openInExternalBrowserTitle = String(format: NSLocalizedString("Open Link in %@", comment: ""), defaultBrowser)
let openInDefaultBrowserItem = NSMenuItem(title: openInExternalBrowserTitle,
action: #selector(contextMenuItemAction(menuItem:)), keyEquivalent: "")
openInDefaultBrowserItem.identifier = .WKMenuItemOpenLinkInSystemBrowser
openInDefaultBrowserItem.representedObject = url
menuItems.insert(openInDefaultBrowserItem, at: menuItems.index(after: index + 1))
}
@objc
func contextMenuItemAction(menuItem: NSMenuItem) {
if menuItem.identifier == .WKMenuItemOpenLinkInSystemBrowser {
openLinkInDefaultBrowser(menuItem: menuItem)
}
}
func openLinkInDefaultBrowser(menuItem: NSMenuItem) {
if let url = menuItem.representedObject as? URL {
NSApp.appController.openURL(inDefaultBrowser: url)
}
}
}
|
2951484b6e3e6ca8806058cffbacb637
| 39.468354 | 151 | 0.66969 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Mac/Scriptability/Folder+Scriptability.swift
|
mit
|
1
|
//
// Folder+Scriptability.swift
// NetNewsWire
//
// Created by Olof Hellman on 1/10/18.
// Copyright © 2018 Olof Hellman. All rights reserved.
//
import Foundation
import Account
import Articles
import RSCore
@objc(ScriptableFolder)
class ScriptableFolder: NSObject, UniqueIdScriptingObject, ScriptingObjectContainer {
let folder:Folder
let container:ScriptingObjectContainer
init (_ folder:Folder, container:ScriptingObjectContainer) {
self.folder = folder
self.container = container
}
@objc(objectSpecifier)
override var objectSpecifier: NSScriptObjectSpecifier? {
let scriptObjectSpecifier = self.container.makeFormUniqueIDScriptObjectSpecifier(forObject:self)
return (scriptObjectSpecifier)
}
// MARK: --- ScriptingObject protocol ---
var scriptingKey: String {
return "folders"
}
// MARK: --- UniqueIdScriptingObject protocol ---
// I am not sure if account should prefer to be specified by name or by ID
// but in either case it seems like the accountID would be used as the keydata, so I chose ID
@objc(uniqueId)
var scriptingUniqueId:Any {
return folder.folderID
}
// MARK: --- ScriptingObjectContainer protocol ---
var scriptingClassDescription: NSScriptClassDescription {
return self.classDescription as! NSScriptClassDescription
}
func deleteElement(_ element:ScriptingObject) {
if let scriptableFeed = element as? ScriptableWebFeed {
BatchUpdate.shared.perform {
folder.account?.removeWebFeed(scriptableFeed.webFeed, from: folder) { result in }
}
}
}
// MARK: --- handle NSCreateCommand ---
/*
handle an AppleScript like
make new folder in account X with properties {name:"new folder name"}
or
tell account X to make new folder at end with properties {name:"new folder name"}
*/
class func handleCreateElement(command:NSCreateCommand) -> Any? {
guard command.isCreateCommand(forClass:"fold") else { return nil }
let name = command.property(forKey:"name") as? String ?? ""
// some combination of the tell target and the location specifier ("in" or "at")
// identifies where the new folder should be created
let (account, folder) = command.accountAndFolderForNewChild()
guard folder == nil else {
print("support for folders within folders is NYI");
return nil
}
command.suspendExecution()
account.addFolder(name) { result in
switch result {
case .success(let folder):
let scriptableAccount = ScriptableAccount(account)
let scriptableFolder = ScriptableFolder(folder, container:scriptableAccount)
command.resumeExecution(withResult:scriptableFolder.objectSpecifier)
case .failure:
command.resumeExecution(withResult:nil)
}
}
return nil
}
// MARK: --- Scriptable elements ---
@objc(webFeeds)
var webFeeds:NSArray {
let feeds = Array(folder.topLevelWebFeeds)
return feeds.map { ScriptableWebFeed($0, container:self) } as NSArray
}
// MARK: --- Scriptable properties ---
@objc(name)
var name:String {
return self.folder.name ?? ""
}
@objc(opmlRepresentation)
var opmlRepresentation:String {
return self.folder.OPMLString(indentLevel:0)
}
}
|
2a24096a2e3664725007a845222a4c47
| 28.655172 | 104 | 0.668605 | false | false | false | false |
SPECURE/rmbt-ios-client
|
refs/heads/main
|
Sources/SpeedMeasurementResponse.swift
|
apache-2.0
|
1
|
/*****************************************************************************************************
* Copyright 2016 SPECURE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************************************/
import Foundation
import ObjectMapper
///
open class SpeedMeasurementResponse: BasicResponse {
///
open var testToken: String?
///
open var testUuid: String?
///
open var clientRemoteIp: String?
///
var duration: Double = 7 // TODO: int instead of double?
///
var pretestDuration: Double = RMBT_TEST_PRETEST_DURATION_S // TODO: int instead of double?
///
var pretestMinChunkCountForMultithreading: Int = RMBT_TEST_PRETEST_MIN_CHUNKS_FOR_MULTITHREADED_TEST
///
var numThreads: Int = 3
///
var numPings: Int = 10
///
var testWait: Double = 0 // TODO: int instead of double?
///
open var measurementServer: TargetMeasurementServer?
open var testServerType: String?
open var isRmbtHTTP: Bool { return testServerType == "RMBThttp" }
///
open func add(details:TargetMeasurementServer) {
self.measurementServer = details
}
///
override open func mapping(map: Map) {
super.mapping(map: map)
testToken <- map["test_token"]
testUuid <- map["test_uuid"]
clientRemoteIp <- map["client_remote_ip"]
duration <- map["duration"]
pretestDuration <- map["duration_pretest"]
numThreads <- map["num_threads"]
numPings <- map["num_pings"]
testWait <- map["test_wait"]
measurementServer <- map["target_measurement_server"]
measurementServer <- map["test_server_type"]
}
///
override open var description: String {
return "SpeedMeasurmentResponse: testToken: \(String(describing: testToken)), testUuid: \(String(describing: testUuid)), clientRemoteIp: \n\(String(describing: clientRemoteIp))"
}
class func createAndFill(from response: SpeedMeasurementResponse_Old) -> SpeedMeasurementResponse {
let r = SpeedMeasurementResponse()
r.clientRemoteIp = response.clientRemoteIp
r.duration = response.duration
r.pretestDuration = response.pretestDuration
r.numPings = Int(response.numPings)!
r.numThreads = Int(response.numThreads)!
r.testToken = response.testToken
r.testUuid = response.testUuid
let measure = TargetMeasurementServer()
measure.port = response.port?.intValue
measure.address = response.serverAddress
measure.name = response.serverName
measure.encrypted = response.serverEncryption
measure.uuid = response.testUuid
r.add(details:measure)
return r
}
}
///
open class TargetMeasurementServer: Mappable {
///
var address: String?
///
var encrypted = false
///
open var name: String?
///
var port: Int?
///
var uuid: String?
///
var ip: String? // TODO: drop this?
///
init() {
}
///
required public init?(map: Map) {
}
///
open func mapping(map: Map) {
address <- map["address"]
encrypted <- map["is_encrypted"]
name <- map["name"]
port <- map["port"]
uuid <- map["uuid"]
ip <- map["ip"]
}
}
|
caeeded500fa829cf7147184bf2082b5
| 26.870748 | 185 | 0.571882 | false | true | false | false |
memmons/Columns
|
refs/heads/master
|
Columns/MEColumnTableViewCell.swift
|
mit
|
1
|
//
// ColumnTableViewCell.swift
// Columns
//
// Created by Michael Emmons on 4/26/15.
import UIKit
public class MEColumnTableViewCell: UITableViewCell {
let kColumnLabelBaseTag = 100
let kColumnGlyphBaseTag = 150
let kRightPaddingViewTag = 80
let kBottomPaddingViewBaseTag = 81
let kRightPaddingViewKey = "rightPaddingView"
let kRootContainerViewKey = "rootContainerView"
let kExpandedContainerViewKey = "expandedContainerView"
let kExpandedImageViewKey = "expandedImageView"
var isExpanded = false
var hasUpdatedConstraints = false
var columnConfigurations : Array<MEColumnConfiguration> = []
var metricDictionary = Dictionary<NSObject, AnyObject>()
var viewsDictionary = Dictionary<NSObject, AnyObject>()
var rootContainerView = UIView()
var expandedContainerView = UIView()
var expandedImageView = UIImageView(image:UIImage(named: "arrow"))
var titleValueViews : METitleValueViews?
var expandedConstraints = [AnyObject]()
var collapsedConstraints = [AnyObject]()
// MARK: - Initialization
init(columns: Array<MEColumnConfiguration>, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
}
required public init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported. Class must be created programatically.")
}
required override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
clipsToBounds = true
expandedContainerView.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addSubview(expandedContainerView)
rootContainerView.setTranslatesAutoresizingMaskIntoConstraints(false)
rootContainerView.backgroundColor = UIColor(white:0.95, alpha:1)
contentView.addSubview(rootContainerView)
expandedImageView.setTranslatesAutoresizingMaskIntoConstraints(false)
expandedImageView.contentMode = UIViewContentMode.Center
contentView.addSubview(expandedImageView)
}
public override func prepareForReuse() {
contentView.removeConstraints(expandedConstraints)
contentView.removeConstraints(collapsedConstraints)
expandedContainerView.removeConstraints(expandedContainerView.constraints())
isExpanded = false
hasUpdatedConstraints = false;
columnConfigurations = []
metricDictionary = [:]
viewsDictionary = [:]
expandedConstraints = []
collapsedConstraints = []
super.prepareForReuse()
}
public func configure(columns: Array<MEColumnConfiguration>, titleValueViews: METitleValueViews?, isExpanded: Bool) -> () {
columnConfigurations = columns
self.titleValueViews = titleValueViews
self.isExpanded = isExpanded
rootContainerView.subviews.map({ $0.removeFromSuperview() })
expandedContainerView.subviews.map({ $0.removeFromSuperview() })
for (index, element) in enumerate(columns) {
element.view.setTranslatesAutoresizingMaskIntoConstraints(false)
rootContainerView.addSubview(element.view)
let columnGlyph = UIView()
columnGlyph.setTranslatesAutoresizingMaskIntoConstraints(false)
columnGlyph.tag = index+kColumnGlyphBaseTag
columnGlyph.backgroundColor = element.separatorColor ?? .grayColor()
rootContainerView.addSubview(columnGlyph)
}
let rightPaddingView = UIView()
rightPaddingView.backgroundColor = .greenColor()
rightPaddingView.setTranslatesAutoresizingMaskIntoConstraints(false)
rightPaddingView.tag = kRightPaddingViewTag
rootContainerView.addSubview(rightPaddingView)
if let titleValueViews = titleValueViews {expandedContainerView.addSubview(titleValueViews) }
hasUpdatedConstraints = false
expand(isExpanded, animated:false)
}
// MARK: - Public Methods
public func expand(isExpanded : Bool, animated: Bool) {
self.isExpanded = isExpanded
let interval = animated == true ? 0.35 : 0.0
setNeedsUpdateConstraints()
UIView.animateWithDuration(interval) {
self.transformImageViewForExpansion(isExpanded)
self.layoutIfNeeded()
}
}
// MARK: - Private helpers
private func transformImageViewForExpansion(isExpanded : Bool) {
let transform : CGAffineTransform
if (isExpanded == true) {
transform = CGAffineTransformMakeRotation(CGFloat((angle:90 * M_PI / 180)))
} else {
transform = CGAffineTransformIdentity
}
expandedImageView.transform = transform;
}
private func changeAlphaForExpansion(isExpanded: Bool) {
expandedContainerView.alpha = isExpanded ? 1.0 : 0.0
}
private func configureConstraintDictionaries() -> () {
var metricDictionary = Dictionary<NSObject, AnyObject>()
var viewDictionary = Dictionary<NSObject, AnyObject>()
for (index, element) in enumerate(columnConfigurations) {
let keys = keysForColumnIndex(index)
let glyphView = rootContainerView.viewWithTag(index+kColumnGlyphBaseTag)
let bPaddingView = rootContainerView.viewWithTag(index+kBottomPaddingViewBaseTag)
metricDictionary[keys.viewKey] = element.minWidth
metricDictionary[keys.columnGlyphKey] = element.separatorWidth ?? NSNumber(float:1)
viewDictionary[keys.viewKey] = element.view
viewDictionary[keys.columnGlyphKey] = glyphView!
// viewDictionary[keys.paddingKey] = bPaddingView!
}
let rPaddingView = rootContainerView.viewWithTag(kRightPaddingViewTag)
viewDictionary[kRootContainerViewKey] = rootContainerView
viewDictionary[kExpandedContainerViewKey] = expandedContainerView
viewDictionary[kExpandedImageViewKey] = expandedImageView
viewDictionary[kRightPaddingViewKey] = rPaddingView!
viewDictionary["titleValueViews"] = titleValueViews
self.metricDictionary = metricDictionary
self.viewsDictionary = viewDictionary
}
private func keysForColumnIndex(index: Int) -> (viewKey: String, columnGlyphKey: String, paddingKey: String) {
return (String(format: "view%i", index), String(format: "columnGlyph%i", index), String(format: "paddingView%i", index))
}
// MARK: - Autolayout
private func constraintsWithVisualFormat(visualFormat: String) -> Array<AnyObject> {
return NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: .allZeros, metrics: metricDictionary, views: viewsDictionary)
}
public override func updateConstraints() {
if (hasUpdatedConstraints == false) {
hasUpdatedConstraints = true
contentView.removeConstraints(constraints())
rootContainerView.removeConstraints(rootContainerView.constraints())
configureConstraintDictionaries()
expandedConstraints = constraintsWithVisualFormat("V:|[rootContainerView][expandedContainerView]|")
collapsedConstraints = constraintsWithVisualFormat("V:|[rootContainerView][expandedContainerView(==0)]|")
var rootConstraints = Array<AnyObject>()
rootConstraints += constraintsWithVisualFormat("V:|-5-[expandedImageView(==12)]")
rootConstraints += constraintsWithVisualFormat("H:|-5-[expandedImageView(==9)][rootContainerView]|")
rootConstraints += constraintsWithVisualFormat("H:|-5-[expandedImageView][expandedContainerView]|")
contentView.addConstraints(rootConstraints)
var hFormatString = "H:|"
var containerConstraints = Array<AnyObject>()
for (index, element) in enumerate(columnConfigurations) {
let keys = keysForColumnIndex(index)
containerConstraints += constraintsWithVisualFormat(String(format:"V:|[%@]|", keys.viewKey))
containerConstraints += constraintsWithVisualFormat(String(format:"V:|[%@]|", keys.columnGlyphKey))
hFormatString += String(format:"[%@(==%@@999)][%@(==%@@999)]", keys.viewKey, keys.viewKey, keys.columnGlyphKey, keys.columnGlyphKey)
}
hFormatString += String(format: "[%@]|", kRightPaddingViewKey)
containerConstraints += constraintsWithVisualFormat(hFormatString)
rootContainerView.addConstraints(containerConstraints)
var tvConstraints = Array<AnyObject>()
tvConstraints += constraintsWithVisualFormat("H:|[titleValueViews]|")
tvConstraints += constraintsWithVisualFormat("V:|[titleValueViews]|")
expandedContainerView.addConstraints(tvConstraints)
}
contentView.removeConstraints(expandedConstraints)
contentView.removeConstraints(collapsedConstraints)
contentView.addConstraints(isExpanded == true ? expandedConstraints : collapsedConstraints)
super.updateConstraints()
}
}
|
e4e48389e5bf62a72125cc3fc9040b1d
| 38.669903 | 140 | 0.785854 | false | true | false | false |
GENG-GitHub/weibo-gd
|
refs/heads/master
|
GDWeibo/Class/Module/Compose/View/GDPlaceHolderTextView.swift
|
apache-2.0
|
1
|
//
// GDPlaceHolderTextView.swift
// GDWeibo
//
// Created by geng on 15/11/6.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDPlaceHolderTextView: UITextView {
//MARK: - 属性
var placeholder: String? {
didSet {
//设置占位文本
placeholderLabel.text = placeholder
placeholderLabel.sizeToFit()
}
}
//MARK: - 构造方法
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
//设置UI
prepareUI()
//设置通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange:", name: UITextViewTextDidChangeNotification, object: self)
}
//注销通知
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK: - 准备UI
private func prepareUI()
{
//添加子控件
addSubview(placeholderLabel)
//设置约束
placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: 5, y: 8))
}
//MARK: - 懒加载
//添加占位文本
private lazy var placeholderLabel: UILabel =
{
let label = UILabel()
//设置占位label属性
label.textColor = UIColor.lightGrayColor()
label.font = UIFont.systemFontOfSize(18)
label.sizeToFit()
return label
}()
}
//MARK: - UITextViewDelegate
extension GDPlaceHolderTextView: UITextViewDelegate
{
func textViewDidChange(textView: UITextView) {
//如果文本框有文字时,就隐藏label
placeholderLabel.hidden = hasText()
}
}
|
e71ef71ab32ff2fb526a21bdad3ba39b
| 19.775281 | 151 | 0.583559 | false | false | false | false |
kykim/SwiftCheck
|
refs/heads/master
|
Sources/Compose.swift
|
mit
|
1
|
//
// Compose.swift
// SwiftCheck
//
// Created by Robert Widmann on 8/25/16.
// Copyright © 2016 Typelift. All rights reserved.
//
extension Gen {
/// Construct a `Gen`erator suitable for initializing an aggregate value.
///
/// When using SwiftCheck with most classes and structures that contain more
/// than one field that conforms to `Arbitrary`, the monadic and applicative
/// syntax can be unwieldy. `Gen.compose` simplifies the construction of
/// these values by exposing a simple, natural, and imperative interface to
/// instance generation. For example:
///
/// public static var arbitrary : Gen<MyClass> {
/// return Gen<MyClass>.compose { c in
/// return MyClass(
/// // Use the nullary method to get an `arbitrary` value.
/// a: c.generate(),
///
/// // or pass a custom generator
/// b: c.generate(Bool.suchThat { $0 == false }),
///
/// // .. and so on, for as many values & types as you need
/// c: c.generate(), ...
/// )
/// }
/// }
///
/// - parameter build: A closure with a `GenComposer` that uses an
/// underlying `Gen`erator to construct arbitrary values.
///
/// - returns: A generator which uses the `build` function to build
/// instances of `A`.
public static func compose(build: @escaping (GenComposer) -> A) -> Gen<A> {
return Gen(unGen: { (stdgen, size) -> A in
let composer = GenComposer(stdgen, size)
return build(composer)
})
}
}
/// `GenComposer` presents an imperative interface over top of `Gen`.
///
/// Instances of this class may not be constructed manually.
/// Use `Gen.compose` instead.
///
/// - seealso: Gen.compose
public final class GenComposer {
private var stdgen: StdGen
private var size: Int
fileprivate init(_ stdgen : StdGen, _ size : Int) {
self.stdgen = stdgen
self.size = size
}
/// Generate a new `T` with a specific generator.
///
/// - parameter gen: The generator used to create a random value.
///
/// - returns: A random value of type `T` using the given `Gen`erator
/// for that type.
public func generate<T>(using gen : Gen<T>) -> T {
return gen.unGen(self.split, size)
}
/// Generate a new value of type `T` with the default `Gen`erator
/// for that type.
///
/// - returns: An arbitrary value of type `T`.
///
/// - seealso: generate\<T\>(gen:)
public func generate<T>() -> T
where T: Arbitrary
{
return generate(using: T.arbitrary)
}
private var split : StdGen {
let old = stdgen
stdgen = old.split.0
return old
}
}
|
6feb6bb19c23159db59d7cc38da2f29f
| 28.685393 | 77 | 0.612793 | false | false | false | false |
double-y/ios_swift_practice
|
refs/heads/master
|
ios_swift_practice_watch Extension/YYFirstInterfaceController.swift
|
mit
|
1
|
//
// YYFirstViewController.swift
// ios_swift_practice
//
// Created by 安田洋介 on 10/19/15.
// Copyright © 2015 安田洋介. All rights reserved.
//
import WatchKit
import WatchConnectivity
class YYFirstInterfaceController: WKInterfaceController{
var emotionIndex = 0
var values: [Int] = []
var value = 5
@IBOutlet var nextButton: WKInterfaceButton!
@IBOutlet var valuePicker: WKInterfacePicker!
@IBAction func changeValue(value: Int) {
self.value = value
}
// image generator: http://hmaidasani.github.io/RadialChartImageGenerator/
@IBAction func next() {
values.append(value)
if(getExtensionDelegate().emotionNames?.count == emotionIndex+1){
var contextDict = Dictionary<String, Int>()
for (index, name) in getExtensionDelegate().emotionNames!.enumerate(){
contextDict[name] = values[index]
}
pushControllerWithName("YYSaveInterfaceController", context:
contextDict
)
}else{
let nextIndex = self.emotionIndex+1
let emotionNames = getExtensionDelegate().emotionNames
var contentDict = Dictionary<String, AnyObject>()
contentDict["emotionName"] = emotionNames?[nextIndex]
contentDict["emotionIndex"] = nextIndex
contentDict["values"] = values
pushControllerWithName("YYFirstInterfaceController", context:contentDict)
}
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let delegate = getExtensionDelegate()
let session = getExtensionDelegate().session
session?.activateSession()
if(context == nil){
session?.sendMessage([ExtensionDelegate.flagForMessage: "start"], replyHandler: {(response: [String:AnyObject]) -> Void in
print(response)
delegate.emotionNames = response["emotionNames"] as! [String]?
delegate.emotionColors = response["emotionColors"] as! [String]?
self.nextButton.setHidden(false)
self.setTitle(self.getExtensionDelegate().emotionNames?[self.emotionIndex])
let color = delegate.emotionColors![self.emotionIndex]
let items = self.getPickerItems(color)
self.valuePicker.setItems(items)
self.valuePicker.setSelectedItemIndex(self.value)
self.valuePicker.focus()
}, errorHandler: {(error:NSError) -> Void in
print("error")
})
}else{
let contextDict = context as? Dictionary<String, AnyObject>
let title = contextDict?["emotionName"] as! String
self.setTitle(title)
emotionIndex = (contextDict?["emotionIndex"])! as! Int
let color = (delegate.emotionColors?[emotionIndex])!
let items = self.getPickerItems(color)
self.valuePicker.setItems(items)
self.valuePicker.setSelectedItemIndex(self.value)
self.valuePicker.focus()
values = contextDict?["values"] as! [Int]
self.nextButton.setHidden(false)
}
if(getExtensionDelegate().emotionNames?.count == emotionIndex+1){
self.nextButton.setTitle("Finish")
}
}
override func willActivate() {
super.willActivate()
}
func getPickerItems(colorString:String?) -> [WKPickerItem]{
let items: [WKPickerItem] = (0...10).map {(index) -> WKPickerItem in
let pickerItem = WKPickerItem()
let fileName = colorString.flatMap{"single\(index)\($0).png"} ?? "single#ffff00.png"
print(fileName)
pickerItem.contentImage = WKImage(imageName: fileName)
return pickerItem
}
return items
}
func getExtensionDelegate() -> ExtensionDelegate{
return WKExtension.sharedExtension().delegate as! ExtensionDelegate
}
}
|
7b2259cde28f7ecd4ac43716be8735a2
| 34.470085 | 134 | 0.598313 | false | false | false | false |
Scorocode/scorocode-SDK-swift
|
refs/heads/master
|
todolist/User.swift
|
mit
|
1
|
//
// User.swift
// todolist
//
// Created by Alexey Kuznetsov on 06/11/2016.
// Copyright © 2016 ProfIT. All rights reserved.
//
import Foundation
class User {
static let sharedInstance = User() //singletone
var id : String = ""
var email : String = ""
var password : String = ""
var name : String = ""
var token : String = ""
var isBoss = false
fileprivate init() {} //singletone
func parseUser(userDictionary: [String:Any]?) {
if let name = userDictionary?["username"] as? String,
let id = userDictionary?["_id"] as? String,
let email = userDictionary?["email"] as? String,
let roles = userDictionary?["roles"] as? [String] {
self.name = name
self.id = id
self.email = email
if let roleId = roles.first {
var scQuery = SCQuery(collection: "roles")
scQuery.equalTo("_id", SCString(roleId))
scQuery.find({ (success, error, result) in
if success, let role = (result?.values.first as? [String: Any])?["name"] as? String, role == "boss" {
self.isBoss = true
}
})
} else {
self.isBoss = false
}
}
}
func saveTokenToServer() {
var scQuery = SCQuery(collection: "devices")
scQuery.equalTo("deviceId", SCString(token)) // one device - one user.
scQuery.remove() {
success, error, result in
if success {
let scObject = SCObject(collection: "devices")
scObject.set(["userId": SCString(self.id),
"deviceType": SCString("ios"),
"deviceId": SCString(self.token)
])
scObject.save() {
success, error, result in
if success {
print("token saved.")
} else if error != nil {
print("token didnt saved! Error: \(error.debugDescription)")
}
}
} else {
print("Error while updating device token, Error: \(error!)")
}
}
}
func removeTokenFromServer() {
var scQuery = SCQuery(collection: "devices")
scQuery.equalTo("deviceId", SCString(self.token)) // one device - one user.
scQuery.remove() {
success, error, result in
if success {
print("token removed")
} else if error != nil {
print("Error while updating device token, Error: \(error!)")
}
}
}
func clear() {
id = ""
email = ""
password = ""
name = ""
isBoss = false
token = ""
UserDefaults.standard.set("", forKey: "email")
UserDefaults.standard.set("", forKey: "password")
//remove token from server:
removeTokenFromServer()
}
func saveCredentials(email: String, password: String) {
self.email = email
self.password = password
UserDefaults.standard.set(email, forKey: "email")
UserDefaults.standard.set(password, forKey: "password")
}
func getCredentials() -> Bool {
guard let email = UserDefaults.standard.object(forKey: "email") as? String, email != "",
let password = UserDefaults.standard.object(forKey: "password") as? String, password != "" else {
return false
}
self.email = email
self.password = password
return true
}
}
class IdAndName {
var id : String = ""
var name : String = ""
init(id: String, name: String) {
self.id = id
self.name = name
}
}
|
cf502a955cbcf47d95ff4892fc4a1fc7
| 29.904762 | 121 | 0.498716 | false | false | false | false |
Dimillian/SwiftHN
|
refs/heads/master
|
SwiftHN/ViewControllers/NewsViewController.swift
|
gpl-2.0
|
1
|
//
// NewsViewController.swift
// SwiftHN
//
// Created by Thomas Ricouard on 05/06/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import UIKit
import SwiftHNShared
import HackerSwifter
class NewsViewController: HNTableViewController, NewsCellDelegate, CategoriesViewControllerDelegate {
var filter: Post.PostFilter = .Top
var loadMoreEnabled = false
var infiniteScrollingView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "HN:News"
self.setupInfiniteScrollingView()
self.setupNavigationItems()
}
private func setupInfiniteScrollingView() {
self.infiniteScrollingView = UIView(frame: CGRectMake(0, self.tableView.contentSize.height, self.tableView.bounds.size.width, 60))
self.infiniteScrollingView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.infiniteScrollingView!.backgroundColor = UIColor.LoadMoreLightGrayColor()
let activityViewIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityViewIndicator.color = UIColor.darkGrayColor()
activityViewIndicator.frame = CGRectMake(self.infiniteScrollingView!.frame.size.width/2-activityViewIndicator.frame.width/2, self.infiniteScrollingView!.frame.size.height/2-activityViewIndicator.frame.height/2, activityViewIndicator.frame.width, activityViewIndicator.frame.height)
activityViewIndicator.startAnimating()
self.infiniteScrollingView!.addSubview(activityViewIndicator)
}
func onPullToFresh() {
self.refreshing = true
Post.fetch(self.filter, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in
if let realDatasource = posts {
self.datasource = realDatasource
if (self.datasource.count % 30 == 0) {
self.loadMoreEnabled = true
} else {
self.loadMoreEnabled = false
}
}
if (!local) {
self.refreshing = false
}
})
}
func loadMore() {
let fetchPage = Int(ceil(Double(self.datasource.count)/30))+1
Post.fetch(self.filter, page:fetchPage, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in
if let realDatasource = posts {
let tempDatasource:NSMutableArray = NSMutableArray(array: self.datasource)
let postsNotFromNewPageCount = ((fetchPage-1)*30)
if (tempDatasource.count - postsNotFromNewPageCount > 0) {
tempDatasource.removeObjectsInRange(NSMakeRange(postsNotFromNewPageCount, tempDatasource.count-postsNotFromNewPageCount))
}
tempDatasource.addObjectsFromArray(realDatasource)
self.datasource = tempDatasource
if (self.datasource.count % 30 == 0) {
self.loadMoreEnabled = true
} else {
self.loadMoreEnabled = false
}
}
if (!local) {
self.refreshing = false
self.tableView.tableFooterView = nil
}
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.onPullToFresh()
self.showFirstTimeEditingCellAlert()
}
func setupNavigationItems() {
let rightButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: "onRightButton")
self.navigationItem.rightBarButtonItem = rightButton
}
func onRightButton() {
let navCategories = self.storyboard?.instantiateViewControllerWithIdentifier("categoriesNavigationController") as! UINavigationController
let categoriesVC = navCategories.visibleViewController as! CategoriesViewController
categoriesVC.delegate = self
navCategories.modalPresentationStyle = UIModalPresentationStyle.Popover
if (navCategories.popoverPresentationController != nil) {
navCategories.popoverPresentationController?.sourceView = self.view
navCategories.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
}
self.presentViewController(navCategories, animated: true, completion: nil)
}
//MARK: Alert management
func showFirstTimeEditingCellAlert() {
if (!Preferences.sharedInstance.firstTimeLaunch) {
let alert = UIAlertController(title: "Quick actions",
message: "By swiping a cell you can quickly send post to the Safari Reading list, or use the more button to share it and access other functionalities",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: {(action: UIAlertAction) in
Preferences.sharedInstance.firstTimeLaunch = true
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func showActionSheetForPost(post: Post) {
var titles = ["Share", "Open", "Open in Safari", "Cancel"]
let sheet = UIAlertController(title: post.title, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let handler = {(action: UIAlertAction?) -> () in
self.tableView.setEditing(false, animated: true)
if let _ = action {
if (action!.title == titles[0]) {
Helper.showShareSheet(post, controller: self, barbutton: nil)
}
else if (action!.title == titles[1]) {
let webview = self.storyboard?.instantiateViewControllerWithIdentifier("WebviewController") as! WebviewController
webview.post = post
self.showDetailViewController(webview, sender: nil)
}
else if (action!.title == titles[2]) {
UIApplication.sharedApplication().openURL(post.url!)
}
}
}
for title in titles {
var type = UIAlertActionStyle.Default
if (title == "Cancel") {
type = UIAlertActionStyle.Cancel
}
sheet.addAction(UIAlertAction(title: title, style: type, handler: handler))
}
self.presentViewController(sheet, animated: true, completion: nil)
}
//MARK: TableView Management
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
if (self.datasource != nil) {
return self.datasource.count
}
return 0
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let title: NSString = (self.datasource[indexPath.row] as! Post).title!
return NewsCell.heightForText(title, bounds: self.tableView.bounds)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(NewsCellsId) as? NewsCell
cell!.post = self.datasource[indexPath.row] as! Post
cell!.cellDelegate = self
if (loadMoreEnabled && indexPath.row == self.datasource.count-3) {
self.tableView.tableFooterView = self.infiniteScrollingView
loadMore()
}
return cell!
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if #available(iOS 9, *) {
if identifier == "toWebview" {
if let url = (sender as? NewsCell)?.post.url {
presentViewController(SafariViewController(URL: url), animated: true, completion: nil)
return false
}
}
}
return super.shouldPerformSegueWithIdentifier(identifier, sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toWebview") {
let destination = segue.destinationViewController as! WebviewController
if let selectedRows = self.tableView.indexPathsForSelectedRows {
destination.post = self.datasource[selectedRows[0].row] as? Post
}
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]
{
let readingList = UITableViewRowAction(style: UITableViewRowActionStyle.Normal,
title: "Read\nLater",
handler: {(action: UITableViewRowAction, indexpath: NSIndexPath) -> Void in
if (Helper.addPostToReadingList(self.datasource[indexPath.row] as! Post)) {
}
_ = self.datasource
Preferences.sharedInstance.addToReadLater(self.datasource[indexPath.row] as! Post)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! NewsCell
cell.readLaterIndicator.hidden = false
self.tableView.setEditing(false, animated: true)
})
readingList.backgroundColor = UIColor.ReadingListColor()
let more = UITableViewRowAction(style: UITableViewRowActionStyle.Normal,
title: "More",
handler: {(action: UITableViewRowAction, indexpath: NSIndexPath) -> Void in
self.showActionSheetForPost(self.datasource[indexPath.row] as! Post)
})
return [readingList, more]
}
//MARK: NewsCellDelegate
func newsCellDidSelectButton(cell: NewsCell, actionType: Int, post: Post) {
let indexPath = self.tableView.indexPathForCell(cell)
if let realIndexPath = indexPath {
let delay = 0.2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.tableView.selectRowAtIndexPath(realIndexPath, animated: false, scrollPosition: .None)
}
}
if (actionType == NewsCellActionType.Comment.rawValue) {
let detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController
detailVC.post = post
self.showDetailViewController(detailVC, sender: self)
}
else if (actionType == NewsCellActionType.Username.rawValue) {
if let realUsername = post.username {
let detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("UserViewController") as! UserViewController
detailVC.user = realUsername
self.showDetailViewController(detailVC, sender: self)
}
}
}
//MARK: CategoriesDelegate
func categoriesViewControllerDidSelecteFilter(controller: CategoriesViewController, filer: Post.PostFilter, title: String) {
self.filter = filer
self.datasource = nil
self.onPullToFresh()
self.title = title
}
func delayedSelection(indexpath: NSIndexPath) {
}
}
|
c46f979c58e9123777a91be583846267
| 42.586081 | 289 | 0.638877 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io
|
refs/heads/develop
|
Carthage/Checkouts/Alamofire/Source/AFError.swift
|
apache-2.0
|
41
|
//
// AFError.swift
//
// Copyright (c) 2014-2018 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
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
///
/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`.
/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process.
/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails.
/// - responseValidationFailed: Returned when a `validate()` call fails.
/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process.
public enum AFError: Error {
/// The underlying reason the parameter encoding error occurred.
///
/// - missingURL: The URL request did not have a URL to encode.
/// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the
/// encoding process.
/// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during
/// encoding process.
public enum ParameterEncodingFailureReason {
case missingURL
case jsonEncodingFailed(error: Error)
case propertyListEncodingFailed(error: Error)
}
/// The underlying reason the multipart encoding error occurred.
///
/// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
/// file URL.
/// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
/// `lastPathComponent` or `pathExtension.
/// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
/// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
/// an error.
/// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
/// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
/// the system.
/// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
/// threw an error.
/// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
/// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
/// encoded data to disk.
/// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
/// already exists at the provided `fileURL`.
/// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
/// not a file URL.
/// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
/// underlying error.
/// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
/// underlying system error.
public enum MultipartEncodingFailureReason {
case bodyPartURLInvalid(url: URL)
case bodyPartFilenameInvalid(in: URL)
case bodyPartFileNotReachable(at: URL)
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
case bodyPartFileIsDirectory(at: URL)
case bodyPartFileSizeNotAvailable(at: URL)
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
case bodyPartInputStreamCreationFailed(for: URL)
case outputStreamCreationFailed(for: URL)
case outputStreamFileAlreadyExists(at: URL)
case outputStreamURLInvalid(url: URL)
case outputStreamWriteFailed(error: Error)
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the response validation error occurred.
///
/// - dataFileNil: The data file containing the server response did not exist.
/// - dataFileReadFailed: The data file containing the server response could not be read.
/// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
/// provided did not contain wildcard type.
/// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
/// `acceptableContentTypes`.
/// - unacceptableStatusCode: The response status code was not acceptable.
public enum ResponseValidationFailureReason {
case dataFileNil
case dataFileReadFailed(at: URL)
case missingContentType(acceptableContentTypes: [String])
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
case unacceptableStatusCode(code: Int)
}
/// The underlying reason the response serialization error occurred.
///
/// - inputDataNil: The server response contained no data.
/// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
/// - inputFileNil: The file containing the server response did not exist.
/// - inputFileReadFailed: The file containing the server response could not be read.
/// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
/// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
/// - propertyListSerializationFailed: Property list serialization failed with an underlying system error.
public enum ResponseSerializationFailureReason {
case inputDataNil
case inputDataNilOrZeroLength
case inputFileNil
case inputFileReadFailed(at: URL)
case stringSerializationFailed(encoding: String.Encoding)
case jsonSerializationFailed(error: Error)
case propertyListSerializationFailed(error: Error)
}
case invalidURL(url: URLConvertible)
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
case responseValidationFailed(reason: ResponseValidationFailureReason)
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}
// MARK: - Adapt Error
struct AdaptError: Error {
let error: Error
}
extension Error {
var underlyingAdaptError: Error? { return (self as? AdaptError)?.error }
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the AFError is an invalid URL error.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
/// will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
switch self {
case .invalidURL(let url):
return url
default:
return nil
}
}
/// The `URL` associated with the error.
public var url: URL? {
switch self {
case .multipartEncodingFailed(let reason):
return reason.url
default:
return nil
}
}
/// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
/// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
public var underlyingError: Error? {
switch self {
case .parameterEncodingFailed(let reason):
return reason.underlyingError
case .multipartEncodingFailed(let reason):
return reason.underlyingError
case .responseSerializationFailed(let reason):
return reason.underlyingError
default:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
switch self {
case .responseValidationFailed(let reason):
return reason.acceptableContentTypes
default:
return nil
}
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseContentType
default:
return nil
}
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseCode
default:
return nil
}
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
switch self {
case .responseSerializationFailed(let reason):
return reason.failedStringEncoding
default:
return nil
}
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
.bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
.bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
.outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
.bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
return url
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
.outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case .missingContentType(let types), .unacceptableContentType(let types, _):
return types
default:
return nil
}
}
var responseContentType: String? {
switch self {
case .unacceptableContentType(_, let responseType):
return responseType
default:
return nil
}
}
var responseCode: Int? {
switch self {
case .unacceptableStatusCode(let code):
return code
default:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case .stringSerializationFailed(let encoding):
return encoding
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
return error
default:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidURL(let url):
return "URL is not valid: \(url)"
case .parameterEncodingFailed(let reason):
return reason.localizedDescription
case .multipartEncodingFailed(let reason):
return reason.localizedDescription
case .responseValidationFailed(let reason):
return reason.localizedDescription
case .responseSerializationFailed(let reason):
return reason.localizedDescription
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case .jsonEncodingFailed(let error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case .propertyListEncodingFailed(let error):
return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case .bodyPartURLInvalid(let url):
return "The URL provided is not a file URL: \(url)"
case .bodyPartFilenameInvalid(let url):
return "The URL provided does not have a valid filename: \(url)"
case .bodyPartFileNotReachable(let url):
return "The URL provided is not reachable: \(url)"
case .bodyPartFileNotReachableWithError(let url, let error):
return (
"The system returned an error while checking the provided URL for " +
"reachability.\nURL: \(url)\nError: \(error)"
)
case .bodyPartFileIsDirectory(let url):
return "The URL provided is a directory: \(url)"
case .bodyPartFileSizeNotAvailable(let url):
return "Could not fetch the file size from the provided URL: \(url)"
case .bodyPartFileSizeQueryFailedWithError(let url, let error):
return (
"The system returned an error while attempting to fetch the file size from the " +
"provided URL.\nURL: \(url)\nError: \(error)"
)
case .bodyPartInputStreamCreationFailed(let url):
return "Failed to create an InputStream for the provided URL: \(url)"
case .outputStreamCreationFailed(let url):
return "Failed to create an OutputStream for URL: \(url)"
case .outputStreamFileAlreadyExists(let url):
return "A file already exists at the provided URL: \(url)"
case .outputStreamURLInvalid(let url):
return "The provided OutputStream URL is invalid: \(url)"
case .outputStreamWriteFailed(let error):
return "OutputStream write failed with error: \(error)"
case .inputStreamReadFailed(let error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNil:
return "Response could not be serialized, input data was nil."
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case .inputFileReadFailed(let url):
return "Response could not be serialized, input file could not be read: \(url)."
case .stringSerializationFailed(let encoding):
return "String could not be serialized with encoding: \(encoding)."
case .jsonSerializationFailed(let error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case .propertyListSerializationFailed(let error):
return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case .dataFileReadFailed(let url):
return "Response could not be validated, data file could not be read: \(url)."
case .missingContentType(let types):
return (
"Response Content-Type was missing and acceptable content types " +
"(\(types.joined(separator: ","))) do not match \"*/*\"."
)
case .unacceptableContentType(let acceptableTypes, let responseType):
return (
"Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
"\(acceptableTypes.joined(separator: ","))."
)
case .unacceptableStatusCode(let code):
return "Response status code was unacceptable: \(code)."
}
}
}
|
f699d91dedf927e30ab57c55595986e7
| 41.945652 | 122 | 0.647836 | false | false | false | false |
mariotaku/ALSLayouts
|
refs/heads/master
|
ALSLayouts/Sources/UIView+LayoutParams.swift
|
apache-2.0
|
1
|
//
// UIView+LayoutParams.swift
// Pods
//
// Created by Mariotaku Lee on 16/9/1.
//
//
import UIKit
public extension UIView {
// Size modes
@IBInspectable internal var layoutWidthMode: String {
get { return self.layoutParams.widthMode.rawValue }
set { self.layoutParams.widthMode = ALSLayoutParams.SizeMode(rawValue: newValue)! }
}
@IBInspectable internal var layoutHeightMode: String {
get { return self.layoutParams.heightMode.rawValue }
set { self.layoutParams.heightMode = ALSLayoutParams.SizeMode(rawValue: newValue)! }
}
// Layout visibility
@IBInspectable internal var layoutHidden: Bool {
get { return self.layoutParams.hidden }
set { self.layoutParams.hidden = newValue }
}
// Layout gravity
@IBInspectable internal var layoutGravity: String {
get { return ALSGravity.format(self.layoutParams.gravity) }
set { self.layoutParams.gravity = ALSGravity.parse(newValue) }
}
// Layout gravity
@IBInspectable internal var layoutWeight: CGFloat {
get { return self.layoutParams.weight }
set { self.layoutParams.weight = newValue }
}
// Layout Margins
@IBInspectable internal var layoutMarginTop: CGFloat {
get { return self.layoutParams.marginTop }
set { self.layoutParams.marginTop = newValue }
}
@IBInspectable internal var layoutMarginBottom: CGFloat {
get { return self.layoutParams.marginBottom }
set { self.layoutParams.marginBottom = newValue }
}
@IBInspectable internal var layoutMarginLeft: CGFloat {
get { return self.layoutParams.marginLeft }
set { self.layoutParams.marginLeft = newValue }
}
@IBInspectable internal var layoutMarginRight: CGFloat {
get { return self.layoutParams.marginRight }
set { self.layoutParams.marginRight = newValue }
}
@IBInspectable internal var layoutMarginLeading: CGFloat {
get { return self.layoutParams.marginLeading }
set { self.layoutParams.marginLeading = newValue }
}
@IBInspectable internal var layoutMarginTrailing: CGFloat {
get { return self.layoutParams.marginTrailing }
set { self.layoutParams.marginTrailing = newValue }
}
// Relative Layout params
@IBInspectable internal var layoutAlignParentTop: Bool {
get { return self.layoutParams.alignParentTop }
set { self.layoutParams.alignParentTop = newValue }
}
@IBInspectable internal var layoutAlignParentBottom: Bool {
get { return self.layoutParams.alignParentBottom }
set { self.layoutParams.alignParentBottom = newValue }
}
@IBInspectable internal var layoutAlignParentLeft: Bool {
get { return self.layoutParams.alignParentLeft }
set { self.layoutParams.alignParentRight = newValue }
}
@IBInspectable internal var layoutAlignParentRight: Bool {
get { return self.layoutParams.alignParentRight }
set { self.layoutParams.alignParentRight = newValue }
}
@IBInspectable internal var layoutAlignParentLeading: Bool {
get { return self.layoutParams.alignParentLeading }
set { self.layoutParams.alignParentLeading = newValue }
}
@IBInspectable internal var layoutAlignParentTrailing: Bool {
get { return self.layoutParams.alignParentTrailing }
set { self.layoutParams.alignParentTrailing = newValue }
}
// Relative alignment
@IBInspectable internal var layoutAlignTop: String? {
get { return self.layoutParams.alignTopTag }
set { self.layoutParams.alignTopTag = newValue }
}
@IBInspectable internal var layoutAlignBottom: String? {
get { return self.layoutParams.alignBottomTag }
set { self.layoutParams.alignBottomTag = newValue }
}
@IBInspectable internal var layoutAlignLeft: String? {
get { return self.layoutParams.alignLeftTag }
set { self.layoutParams.alignRightTag = newValue }
}
@IBInspectable internal var layoutAlignRight: String? {
get { return self.layoutParams.alignRightTag }
set { self.layoutParams.alignRightTag = newValue }
}
@IBInspectable internal var layoutAlignLeading: String? {
get { return self.layoutParams.alignLeadingTag }
set { self.layoutParams.alignLeadingTag = newValue }
}
@IBInspectable internal var layoutAlignTrailing: String? {
get { return self.layoutParams.alignTrailingTag }
set { self.layoutParams.alignTrailingTag = newValue }
}
@IBInspectable internal var layoutAlignBaseline: String? {
get { return self.layoutParams.alignBaselineTag }
set { self.layoutParams.alignBaselineTag = newValue }
}
// Relative position
@IBInspectable internal var layoutAbove: String? {
get { return self.layoutParams.aboveTag }
set { self.layoutParams.aboveTag = newValue }
}
@IBInspectable internal var layoutBelow: String? {
get { return self.layoutParams.belowTag }
set { self.layoutParams.belowTag = newValue }
}
@IBInspectable internal var layoutToLeftOf: String? {
get { return self.layoutParams.toLeftOfTag }
set { self.layoutParams.toLeftOfTag = newValue }
}
@IBInspectable internal var layoutToRightOf: String? {
get { return self.layoutParams.toRightOfTag }
set { self.layoutParams.toRightOfTag = newValue }
}
@IBInspectable internal var layoutToLeadingOf: String? {
get { return self.layoutParams.toLeadingOfTag }
set { self.layoutParams.toLeadingOfTag = newValue }
}
@IBInspectable internal var layoutToTrailingOf: String? {
get { return self.layoutParams.toTrailingOfTag }
set { self.layoutParams.toTrailingOfTag = newValue }
}
@IBInspectable internal var layoutAlignWithParentIfMissing: Bool {
get { return self.layoutParams.alignWithParentIfMissing }
set { self.layoutParams.alignWithParentIfMissing = newValue }
}
// Centering
@IBInspectable internal var layoutCenterInParent: Bool {
get { return self.layoutParams.centerInParent }
set { self.layoutParams.centerInParent = newValue }
}
@IBInspectable internal var layoutCenterVertical: Bool {
get { return self.layoutParams.centerVertical }
set { self.layoutParams.centerVertical = newValue }
}
@IBInspectable internal var layoutCenterHorizontal: Bool {
get { return self.layoutParams.centerHorizontal }
set { self.layoutParams.centerHorizontal = newValue }
}
/**
Returns layout parameters of this view, if no parameter set, obtain a new one.
*/
public var layoutParams: ALSLayoutParams {
return (superview as! ALSBaseLayout).obtainLayoutParams(self)
}
internal var layoutParamsOrNull: ALSLayoutParams? {
return (superview as? ALSBaseLayout)?.getLayoutParams(self)
}
}
|
abc21c8571edf4c45aeff56ac7468d30
| 32.933962 | 92 | 0.670142 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothHCI/HCIReadDataBlockSize.swift
|
mit
|
1
|
//
// HCIReadDataBlockSize.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/6/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// Read Data Block Size
///
/// The Read_Data_Block_Size command is used to read values regarding the maximum permitted data transfers over the Controller and the data buffering available in the Controller.
/// The Host uses this information when fragmenting data for transmission, and when performing block-based flow control, based on the Number Of Completed Data Blocks event. The Read_Data_Block_Size command shall be issued by the Host before it sends any data to the Controller.
func readDataBlockSize(timeout: HCICommandTimeout = .default) async throws -> HCIReadDataBlockSizeReturn {
return try await deviceRequest(HCIReadDataBlockSizeReturn.self, timeout: timeout)
}
}
// MARK: - Return Parameter
/// Read Data Block Size
///
/// The Read_Data_Block_Size command is used to read values regarding the maximum permitted data transfers over the Controller and the data buffering available in the Controller.
/// The Host uses this information when fragmenting data for transmission, and when performing block-based flow control, based on the Number Of Completed Data Blocks event. The Read_Data_Block_Size command shall be issued by the Host before it sends any data to the Controller.
@frozen
public struct HCIReadDataBlockSizeReturn: HCICommandReturnParameter {
public static let command = InformationalCommand.readDataBlockSize
public static let length = 7
public let status: HCIStatus
/// Maximum length (in octets) of the data portion of an HCI ACL Data Packet that the Controller is able to accept for transmission. For AMP Controllers this always equals to Max_PDU_Size.
public let maxACLDataPacketLength: UInt16
/// Maximum length (in octets) of the data portion of each HCI ACL Data Packet that the Controller is able to hold in each of its data block buffers.
public let dataBlockLength: UInt16
/// Total number of data block buffers available in the Controller for the storage of data packets scheduled for transmission.
public let dataBlocksTotalNumber: UInt16
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let status = HCIStatus(rawValue: data[0])
else { return nil }
self.status = status
self.maxACLDataPacketLength = UInt16(littleEndian: UInt16(bytes: (data[1], data[2])))
self.dataBlockLength = UInt16(littleEndian: UInt16(bytes: (data[3], data[4])))
self.dataBlocksTotalNumber = UInt16(littleEndian: UInt16(bytes: (data[5], data[6])))
}
}
|
b25d7eeda44871dbf2d2a9b7a7eb049d
| 43.661538 | 281 | 0.717189 | false | false | false | false |
ben-ng/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/01294-getselftypeforcontainer.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var m: Int -> Int = {
n $0
o: Int = { d, l f
}(k, m)
protocol j {
typealias l = d}
class g<q : l, m : l p q.g == m> : j {
class k {
protocol c : b { func b
|
51aa515121cecb64c810bc311e25a9fd
| 31.588235 | 79 | 0.68231 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS
|
refs/heads/master
|
PlayaKit/Models/PlayaLocation.swift
|
mpl-2.0
|
1
|
//
// PlayaLocation.swift
// PlayaKit
//
// Created by Chris Ballinger on 9/30/17.
// Copyright © 2017 Burning Man Earth. All rights reserved.
//
import Foundation
import CoreLocation
public protocol PlayaLocation {
/// e.g. "J & 4:15" for camps or "10:20 3200', Open Playa" for art
var address: String { get }
var coordinate: CLLocationCoordinate2D { get }
}
public struct ArtLocation: PlayaLocation, Codable {
/// e.g. "10:20 3200', Open Playa"
public let address: String
public var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2DMake(latitude, longitude)
}
private let latitude: CLLocationDegrees
private let longitude: CLLocationDegrees
/// e.g. "5"
public let hour: Int
/// e.g. "19"
public let minute: Int
/// e.g. "2260" in meters
public let distance: CLLocationDistance
// MARK: Codable
public enum CodingKeys: String, CodingKey {
case address = "string"
case hour
case minute
case distance
case latitude = "gps_latitude"
case longitude = "gps_longitude"
}
}
public struct CampLocation: PlayaLocation, Codable {
/// e.g. "J & 4:15"
public let address: String
public var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2DMake(latitude, longitude)
}
private let latitude: CLLocationDegrees
private let longitude: CLLocationDegrees
/// e.g. "J"
public let frontage: String?
/// e.g. "4:15"
public let intersection: String?
/// e.g. "100 x 50"
public let dimensions: String?
public enum IntersectionType: String, Codable {
case and = "&"
case at = "@"
}
/// e.g. "&" or "@"
public let intersectionType: IntersectionType?
// MARK: Codable
public enum CodingKeys: String, CodingKey {
case address = "string"
case frontage
case intersection
case intersectionType = "intersection_type"
case dimensions
case latitude = "gps_latitude"
case longitude = "gps_longitude"
}
}
|
4f2a23bd557d9348f220f6f0c68c46a2
| 26.205128 | 70 | 0.633365 | false | false | false | false |
Ezimetzhan/Design-Patterns-In-Swift
|
refs/heads/master
|
source/creational/abstract_factory.swift
|
gpl-3.0
|
22
|
/*:
🌰 Abstract Factory
-------------------
The abstract factory pattern is used to provide a client with a set of related or dependant objects.
The "family" of objects created by the factory are determined at run-time.
### Example
*/
/*:
Protocols
*/
protocol Decimal {
func stringValue() -> String
// factory
static func make(string : String) -> Decimal
}
typealias NumberFactory = (String) -> Decimal
// Number implementations with factory methods
struct NextStepNumber : Decimal {
private var nextStepNumber : NSNumber
func stringValue() -> String { return nextStepNumber.stringValue }
// factory
static func make(string : String) -> Decimal {
return NextStepNumber(nextStepNumber:NSNumber(longLong:(string as NSString).longLongValue))
}
}
struct SwiftNumber : Decimal {
private var swiftInt : Int
func stringValue() -> String { return "\(swiftInt)" }
// factory
static func make(string : String) -> Decimal {
return SwiftNumber(swiftInt:(string as NSString).integerValue)
}
}
/*:
Abstract factory
*/
enum NumberType {
case NextStep, Swift
}
class NumberHelper {
class func factoryFor(type : NumberType) -> NumberFactory {
switch type {
case .NextStep:
return NextStepNumber.make
case .Swift:
return SwiftNumber.make
}
}
}
/*:
### Usage
*/
let factoryOne = NumberHelper.factoryFor(.NextStep)
let numberOne = factoryOne("1")
numberOne.stringValue()
let factoryTwo = NumberHelper.factoryFor(.Swift)
let numberTwo = factoryTwo("2")
numberTwo.stringValue()
|
82c57d72fa091327408de8555ef004fa
| 22.057143 | 101 | 0.671623 | false | false | false | false |
adrfer/swift
|
refs/heads/master
|
test/Constraints/invalid_archetype_constraint.swift
|
apache-2.0
|
4
|
// RUN: %target-parse-verify-swift
protocol Empty {}
protocol P {
associatedtype Element
init()
}
struct A<T> : P {
typealias Element = T
}
struct A1<T> : P {
typealias Element = T
}
struct A2<T> : P {
typealias Element = T
}
func toA<S: Empty, AT:P where AT.Element == S.Generator.Element>(s: S) -> AT { // expected-error{{'Generator' is not a member type of 'S'}}
return AT()
}
|
f1cd6c4f8bfe574fb558ebc11fbba4d0
| 15.583333 | 139 | 0.633166 | false | false | false | false |
EstebanVallejo/sdk-ios
|
refs/heads/master
|
MercadoPagoSDK/MercadoPagoSDK/SavedCardToken.swift
|
mit
|
2
|
//
// SavedCard.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 31/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class SavedCardToken : NSObject {
public var cardId : String?
public var securityCode : String?
public var device : Device?
public var securityCodeRequired : Bool = true
public init(cardId : String, securityCode : String) {
super.init()
self.cardId = cardId
self.securityCode = securityCode
}
public init(cardId : String, securityCode : String?, securityCodeRequired: Bool) {
super.init()
self.cardId = cardId
self.securityCode = securityCode
self.securityCodeRequired = securityCodeRequired
}
public func validate() -> Bool {
return validateCardId() && (!securityCodeRequired || validateSecurityCode())
}
public func validateCardId() -> Bool {
return !String.isNullOrEmpty(cardId) && String.isDigitsOnly(cardId!)
}
public func validateSecurityCode() -> Bool {
let isEmptySecurityCode : Bool = String.isNullOrEmpty(self.securityCode)
return !isEmptySecurityCode && count(self.securityCode!) >= 3 && count(self.securityCode!) <= 4
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"card_id": String.isNullOrEmpty(self.cardId) ? JSON.null : self.cardId!,
"security_code" : String.isNullOrEmpty(self.securityCode) ? JSON.null : self.securityCode!,
"device" : self.device == nil ? JSON.null : self.device!.toJSONString()
]
return JSON(obj).toString()
}
}
|
a699564cbd477e086e3fccb6992f5d40
| 32.215686 | 103 | 0.640284 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/Distributed/Runtime/distributed_actor_func_calls_remoteCall_echo.swift
|
apache-2.0
|
5
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift
// RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574
// UNSUPPORTED: OS=windows-msvc
import Distributed
import FakeDistributedActorSystems
typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem
distributed actor Greeter {
distributed func echo(name: String) -> String {
return "Echo: \(name)"
}
}
func test() async throws {
let system = DefaultDistributedActorSystem()
let local = Greeter(actorSystem: system)
let ref = try Greeter.resolve(id: local.id, using: system)
let reply = try await ref.echo(name: "Caplin")
// CHECK: >> remoteCall: on:main.Greeter, target:main.Greeter.echo(name:), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Caplin"], returnType: Optional(Swift.String), errorType: nil), throwing:Swift.Never, returning:Swift.String
// CHECK: << remoteCall return: Echo: Caplin
print("reply: \(reply)")
// CHECK: reply: Echo: Caplin
}
@main struct Main {
static func main() async {
try! await test()
}
}
|
9b7714b6f5b5debf3dd892ba6d5ead32
| 36.191489 | 247 | 0.740847 | false | true | false | false |
AndrejJurkin/nova-osx
|
refs/heads/master
|
Nova/view/menubar/MenuBarView.swift
|
apache-2.0
|
1
|
//
// Copyright 2017 Andrej Jurkin.
//
// 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.
//
//
// MenuBarView.swift
// Nova
//
// Created by Andrej Jurkin on 9/3/17.
import Foundation
import Cocoa
import RxSwift
import RxCocoa
/// Menu bar view displays selected tickers in menu bar
class MenuBarView: NSObject {
/// Status item used to display coin tickers
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
/// Content wrapper
let popover = NSPopover()
let viewModel = Injector.inject(type: MenuBarViewModel.self)
let disposeBag = DisposeBag()
private var eventMonitor: EventMonitor?
override init() {
super.init()
self.statusItem.button?.action = #selector(togglePopover)
self.statusItem.button?.target = self
self.bindUi()
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let popoverViewController = storyboard.instantiateController(
withIdentifier: "popover") as! TickerListViewController
self.popover.contentViewController = popoverViewController
// Close popover on any click outside of the app
self.eventMonitor = EventMonitor(
mask: [.leftMouseDown, .rightMouseDown],
handler: { [weak self] event in
self?.hidePopover()
})
}
func togglePopover() {
if popover.isShown {
self.hidePopover()
} else {
self.showPopover()
}
}
func showPopover() {
if let button = statusItem.button {
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.eventMonitor?.start()
}
}
func hidePopover() {
self.popover.performClose(nil)
self.eventMonitor?.stop()
}
func setStatusItemTitle(title: String) {
let title = NSAttributedString(string: title, attributes: R.Font.menuBarTitleAttributes)
self.statusItem.attributedTitle = title
}
func refresh() {
self.viewModel.subscribe()
}
func pause() {
self.viewModel.unsubscribe()
}
func resume() {
self.viewModel.subscribe()
}
private func bindUi() {
self.viewModel.subscribe()
self.viewModel.menuBarText.asObservable().subscribe(onNext: { text in
self.setStatusItemTitle(title: text)
})
.addDisposableTo(disposeBag)
}
}
|
f99d35ca9d17ef67b2d1436a507533f4
| 27.254545 | 100 | 0.627413 | false | false | false | false |
rockgarden/swift_language
|
refs/heads/swift3
|
Playground/Temp.playground/Pages/Generics Functions.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
//: # Generic Functions 泛型函数
import UIKit
let s: Optional<String> = "howdy"
func takeAndReturnSameThing<T> (t: T) -> T {
return t
}
let thing = takeAndReturnSameThing("howdy")
struct HolderOfTwoSameThings<T> {
var firstThing: T
var secondThing: T
init(thingOne: T, thingTwo: T) {
self.firstThing = thingOne
self.secondThing = thingTwo
}
}
let holder = HolderOfTwoSameThings(thingOne: "howdy", thingTwo: "getLost")
func flockTwoTogether<T, U>(f1: T, _ f2: U) { }
let vd: Void = flockTwoTogether("hey", 1)
func myMin<T: Comparable>(things: T...) -> T {
var minimum = things[0]
for ix in 1..<things.count {
if things[ix] < minimum { // compile error if you remove Comparable constraint
minimum = things[ix]
}
}
return minimum
}
protocol Flier4 {
associatedtype Other
}
struct Bird4: Flier4 {
typealias Other = String
}
class Dog<T> {
var name: T?
}
let d = Dog<String>()
protocol Flier5 {
init()
}
struct Bird5: Flier5 {
init() { }
}
struct FlierMaker<T: Flier5> {
static func makeFlier() -> T {
return T() // a little surprising I don't have to say T.init(), but I guess it is a real type
}
}
let f = FlierMaker<Bird5>.makeFlier() // returns a Bird5
class NoisyDog: Dog<String> { } // yes! This is new in Swift 2.0
class NoisyDog2<T>: Dog<T> { } // and this is also legal!
// class NoisyDog3 : Dog<T> {} // but this is not; the superclass generic must be resolved somehow
struct Wrapper<T> { }
struct Wrapper2<T> {
var thing: T
}
class Cat { }
class CalicoCat: Cat { }
protocol Flier6 {
associatedtype Other
func fly()
}
/*
func flockTwoTogether6(f1:Flier6, _ f2:Flier6) { // compile error
f1.fly()
f2.fly()
}
*/
func flockTwoTogether6<T1: Flier6, T2: Flier6>(f1: T1, _ f2: T2) {
f1.fly()
f2.fly()
}
// just testing: this one actually segfaults
// but not any more! In Swift 2.2 (Xcode 7.3b) this is fine; not sure when that happened
class Dog2<T: Dog2> { }
let min = myMin(4, 1, 5, 2)
(min)
do {
// let w : Wrapper<Cat> = Wrapper<CalicoCat>() // error
var w2: Wrapper2<Cat> = Wrapper2(thing: CalicoCat()) // fine
let w3 = Wrapper2(thing: CalicoCat())
// w2 = w3 // error
// ==== shut up the compiler
w2 = Wrapper2(thing: CalicoCat())
_ = w2
_ = w3
}
//: ## Basic example - 栈(Stack)的操作
func swapTwoValues<T>(inout a: T, inout _ b: T) { // "_"方法调用时可不申明参数b
let temporaryA = a
a = b
b = temporaryA
(a,b)=(b,a)
}
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
/*:
The swapTwoValues(_:_:) function defined above is inspired by a generic function called swap, which is part of the Swift standard library, and is automatically made available for you to use in your apps.
If you need the behavior of the swapTwoValues(_:_:) function in your own code, you can use Swift’s existing swap(_:_:) function rather than providing your own implementation.
You can provide more than one type parameter by writing multiple type parameter names within the angle brackets, separated by commas.
*/
/*:
## Naming Type Parameters
In most cases, type parameters have descriptive names, such as Key and Value in Dictionary<Key, Value>
and Element in Array<Element>, which tells the reader about the relationship between the type parameter
and the generic type or function it’s used in. However, when there isn’t a meaningful relationship between them,
it’s traditional to name them using single letters such as T, U, and V, such as T in the swapTwoValues(_:_:) function above.
- NOTE:
Always give type parameters upper camel case names (such as T and MyTypeParameter) to indicate
that they are a placeholder for a type, not a value.
*/
/*:
## Generic Types
Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary.
*/
struct Stack<Element> {
var items = [Element]()
// 入栈操作 即Push 添加最新数据到容器最顶部
mutating func push(item: Element) {
items.append(item)
}
// 出栈操作 即Pop 将容器最顶部数据移除
mutating func pop() -> Element {
return items.removeLast()
}
}
/*:
- Note:
How the generic version of Stack is essentially the same as the non-generic version,
but with a type parameter called Element instead of an actual type of Int.
This type parameter is written within a pair of angle brackets (<Element>) immediately after the structure’s name.
Element defines a placeholder name for “some type Element” to be provided later on.
This future type can be referred to as “Element” anywhere within the structure’s definition.
*/
var stackOfStrings = Stack<String> ()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
/*
## Extending a Generic Type
When you extend a generic type, you do not provide a type parameter list as part of the extension’s definition.
Instead, the type parameter list from the original type definition is available within the body of the extension,
and the original type parameter names are used to refer to the type parameters from the original definition.
*/
extension Stack {
var topItem: Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
/*
- Note:
that this extension does not define a type parameter list.
Instead, the Stack type’s existing type parameter name, Element,
is used within the extension to indicate the optional type of the topItem computed property.
*/
/*
## Type Constraints 类型约束
T占位符后面添加冒号和协议类型,这种表示方式被称为泛型约束
*/
protocol SomeProtocol {}
class SomeClass {}
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
/*:
The hypothetical function above has two type parameters. The first type parameter, T,
has a type constraint that requires T to be a subclass of SomeClass.
The second type parameter, U, has a type constraint that requires U to conform to the protocol SomeProtocol.
*/
func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
}
return nil
}
func isEquals<T: Comparable>(a: T, b: T) -> Bool {
return (a == b)
}
//: [Next](@next)
|
f9e13c2e83900d052f31cefe1617b55b
| 27.884444 | 204 | 0.687337 | false | false | false | false |
lquigley/Game
|
refs/heads/master
|
Game/Game/SpriteKit/Nodes/SKYLevelRope.swift
|
mit
|
1
|
//
// SKYLevelRope.swift
// Sky High
//
// Created by Luke Quigley on 2/20/15.
// Copyright (c) 2015 VOKAL. All rights reserved.
//
import SpriteKit
class SKYLevelRope: SKShapeNode {
var _level:Int = 0
override init() {
super.init()
let bezierPath = UIBezierPath()
let startPoint = CGPointMake(0,250)
let endPoint = CGPointMake(450,250)
bezierPath.moveToPoint(startPoint)
bezierPath.addLineToPoint(endPoint)
var pattern : [CGFloat] = [10.0,5.0];
let dashed = CGPathCreateCopyByDashingPath(bezierPath.CGPath, nil, 0, pattern, 2);
let backNode = SKShapeNode(path: dashed, centered: true)
self.addChild(backNode)
self.physicsBody = SKPhysicsBody()
self.physicsBody?.affectedByGravity = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var level:Int {
get {
return _level
}
set {
let numberNode = SKSpriteNode()
}
}
}
|
826725909e2daa9426fd80c871ee0e69
| 22.782609 | 90 | 0.575868 | false | false | false | false |
digoreis/swift-proposal-analyzer
|
refs/heads/master
|
page-generator/main.swift
|
mit
|
1
|
#!/usr/bin/swift
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// GitHub
// https://github.com/jessesquires/swift-proposal-analyzer
//
//
// License
// Copyright © 2016 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
print("Generating playground pages from proposals...")
func proposalFiles(inDirectory directory: URL) -> [URL : String] {
let fm = FileManager.default
let proposalNames = try! fm.contentsOfDirectory(atPath: directory.path)
var proposals = [URL : String]()
for eachName in proposalNames {
let url = directory.appendingPathComponent(eachName)
let fileContents = try! String(contentsOf: url, encoding: String.Encoding.utf8)
proposals[url] = fileContents
}
return proposals
}
if #available(OSX 10.11, *) {
let process = Process()
let currentDir = URL(fileURLWithPath: process.currentDirectoryPath)
let proposalDir = currentDir
.appendingPathComponent("swift-evolution", isDirectory: true)
.appendingPathComponent("proposals", isDirectory: true)
let basePlaygroundDir = currentDir
.appendingPathComponent("swift-proposal-analyzer.playground", isDirectory: true)
.appendingPathComponent("Pages", isDirectory: true)
let proposals = proposalFiles(inDirectory: proposalDir)
let fm = FileManager.default
for (url, contents) in proposals {
let path = url.lastPathComponent
let range = path.index(path.startIndex, offsetBy: 4)
let seNumber = "SE-" + path.substring(to: range)
let pageDir = basePlaygroundDir
.appendingPathComponent(seNumber + ".xcplaygroundpage", isDirectory: true)
try! fm.createDirectory(at: pageDir, withIntermediateDirectories: true, attributes: nil)
let pageFile = pageDir
.appendingPathComponent("Contents", isDirectory: false)
.appendingPathExtension("swift")
let pageContents = "/*:\n"
+ contents
+ "\n\n----------\n\n"
+ "[Previous](@previous) | [Next](@next)\n"
+ "*/\n"
let pageData = pageContents.data(using: .utf8)
let success = fm.createFile(atPath: pageFile.path, contents: pageData, attributes: nil)
if !success {
print("** Error: failed to generate playground page for " + seNumber)
}
}
} else {
print("** Error: Must use OSX 10.11 or higher.")
}
print("Done! 🎉")
|
50474ccc265e4c0524d5a3bb0af15299
| 30.3125 | 96 | 0.65509 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.