repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baottran/nSURE | nSURE/IntakeViewController.swift | 1 | 4335 | //
// IntakeViewController.swift
// NSURE5
//
// Created by Bao Tran on 6/10/15.
// Copyright (c) 2015 Bao Tran. All rights reserved.
//
import UIKit
//protocol IntakeViewControllerDelegate: class {
// func intakeViewController(controller: IntakeViewController,
//}
class IntakeViewController: UIViewController, CustomerSelectionDelegate {
var customer: PFObject?
var customers: [PFObject]?
var userCompany: PFObject?
@IBOutlet weak var openSideBarButton: UIBarButtonItem!
@IBOutlet weak var greetingLabel: UILabel!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let user = PFUser.currentUser()
print("current user: \(user)", terminator: "")
if let currentUser = user as PFUser? {
// println("currentUser: \(currentUser)")
let firstName = currentUser["firstName"] as! String
let lastName = currentUser["lastName"] as! String
greetingLabel.text = "Welcome \(firstName) \(lastName)"
}
// prepareData()
}
// func prepareData(){
//
// }
override func viewDidLoad() {
super.viewDidLoad()
openSideBarButton.target = self.revealViewController()
openSideBarButton.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
@IBAction func logOut(){
PFUser.logOut()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "Embed"
{
let splitViewController = segue.destinationViewController as! UISplitViewController
let leftNavController = splitViewController.viewControllers.first as! UINavigationController
let masterViewController = leftNavController.topViewController as! PFCustomerList
let rightNavController = splitViewController.viewControllers.last as! UINavigationController
let detailViewController = rightNavController.topViewController as! CustomerDetailViewController
masterViewController.delegate = detailViewController
masterViewController.intakeDelegate = self
} else if segue.identifier == "Schedule Assessment"
{
let navController = segue.destinationViewController as! UINavigationController
let viewController = navController.viewControllers.first as! ScheduleViewController
viewController.customer = customer
} else if segue.identifier == "ListAssessments" {
let navController = segue.destinationViewController as! UINavigationController
let tableViewController = navController.viewControllers.first as! AssessmentListViewController
let query = PFQuery(className: "Repair")
// query.includeKey("customer")
let result = query.findObjects() as? Array<PFObject>
tableViewController.assessmentArray = result
} else if segue.identifier == "ViewCalendar" {
let navController = segue.destinationViewController as! UINavigationController
let calendarController = navController.viewControllers.first as! IntakeMonthViewController
calendarController.customerObj = customer
let query = PFQuery(className: "Repair")
let result = query.findObjects() as? Array<PFObject>
calendarController.assessmentArray = result
}
}
func customerSelected(newCustomer: PFObject) {
customer = newCustomer
}
@IBAction func showSchedule(){
if customer != nil {
self.performSegueWithIdentifier("ViewCalendar", sender: nil)
} else {
let alert = UIAlertController(title: "Error", message: "Please select a customer before scheduling an assessment.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
| mit | ee9fb5f30a8589283e658fd65c314c8a | 36.051282 | 173 | 0.647059 | 5.826613 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Calling/WireCallCenterV3Mock.swift | 1 | 6699 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@testable import WireSyncEngine
@objcMembers
public class MockAVSWrapper: AVSWrapperType {
public var muted: Bool = false
public var startCallArguments: (uuid: AVSIdentifier, callType: AVSCallType, conversationType: AVSConversationType, useCBR: Bool)?
public var answerCallArguments: (uuid: AVSIdentifier, callType: AVSCallType, useCBR: Bool)?
public var setVideoStateArguments: (uuid: AVSIdentifier, videoState: VideoState)?
public var requestVideoStreamsArguments: (uuid: AVSIdentifier, videoStreams: AVSVideoStreams)?
public var didCallEndCall = false
public var didCallRejectCall = false
public var didCallClose = false
public var answerCallShouldFail = false
public var startCallShouldFail = false
public var didUpdateCallConfig = false
public var callError: CallError?
public var hasOngoingCall = false
public var mockMembers: [AVSCallMember] = []
var receivedCallEvents: [CallEvent] = []
public required init(userId: AVSIdentifier, clientId: String, observer: UnsafeMutableRawPointer?) {
// do nothing
}
public func startCall(conversationId: AVSIdentifier, callType: AVSCallType, conversationType: AVSConversationType, useCBR: Bool) -> Bool {
startCallArguments = (conversationId, callType, conversationType, useCBR)
return !startCallShouldFail
}
public func answerCall(conversationId: AVSIdentifier, callType: AVSCallType, useCBR: Bool) -> Bool {
answerCallArguments = (conversationId, callType, useCBR)
return !answerCallShouldFail
}
public func endCall(conversationId: AVSIdentifier) {
didCallEndCall = true
}
public func rejectCall(conversationId: AVSIdentifier) {
didCallRejectCall = true
}
public func close() {
didCallClose = true
}
public func setVideoState(conversationId: AVSIdentifier, videoState: VideoState) {
setVideoStateArguments = (conversationId, videoState)
}
public func received(callEvent: CallEvent) -> CallError? {
receivedCallEvents.append(callEvent)
return callError
}
public func handleResponse(httpStatus: Int, reason: String, context: WireCallMessageToken) {
// do nothing
}
public func handleSFTResponse(data: Data?, context: WireCallMessageToken) {
// do nothing
}
public func update(callConfig: String?, httpStatusCode: Int) {
didUpdateCallConfig = true
}
public func requestVideoStreams(_ videoStreams: AVSVideoStreams, conversationId: AVSIdentifier) {
requestVideoStreamsArguments = (conversationId, videoStreams)
}
}
final class WireCallCenterV3IntegrationMock: WireCallCenterV3 {
public let mockAVSWrapper: MockAVSWrapper
public required init(userId: AVSIdentifier, clientId: String, avsWrapper: AVSWrapperType? = nil, uiMOC: NSManagedObjectContext, flowManager: FlowManagerType, analytics: AnalyticsType? = nil, transport: WireCallCenterTransport) {
mockAVSWrapper = MockAVSWrapper(userId: userId, clientId: clientId, observer: nil)
super.init(userId: userId, clientId: clientId, avsWrapper: mockAVSWrapper, uiMOC: uiMOC, flowManager: flowManager, transport: transport)
}
}
@objcMembers
public class WireCallCenterV3Mock: WireCallCenterV3 {
public let mockAVSWrapper: MockAVSWrapper
var mockMembers: [AVSCallMember] {
get {
return mockAVSWrapper.mockMembers
}
set {
mockAVSWrapper.mockMembers = newValue
}
}
// MARK: Initialization
public required init(userId: AVSIdentifier, clientId: String, avsWrapper: AVSWrapperType? = nil, uiMOC: NSManagedObjectContext, flowManager: FlowManagerType, analytics: AnalyticsType? = nil, transport: WireCallCenterTransport) {
mockAVSWrapper = MockAVSWrapper(userId: userId, clientId: clientId, observer: nil)
super.init(userId: userId, clientId: clientId, avsWrapper: mockAVSWrapper, uiMOC: uiMOC, flowManager: flowManager, transport: transport)
}
// MARK: AVS Integration
public var startCallShouldFail: Bool = false {
didSet {
(avsWrapper as! MockAVSWrapper).startCallShouldFail = startCallShouldFail
}
}
public var answerCallShouldFail: Bool = false {
didSet {
(avsWrapper as! MockAVSWrapper).answerCallShouldFail = answerCallShouldFail
}
}
public var didCallStartCall: Bool {
return (avsWrapper as! MockAVSWrapper).startCallArguments != nil
}
public var didCallAnswerCall: Bool {
return (avsWrapper as! MockAVSWrapper).answerCallArguments != nil
}
public var didCallRejectCall: Bool {
return (avsWrapper as! MockAVSWrapper).didCallRejectCall
}
// MARK: Mock Call State
func setMockCallState(_ state: CallState, conversationId: AVSIdentifier, callerId: AVSIdentifier, isVideo: Bool) {
clearSnapshot(conversationId: conversationId)
createSnapshot(callState: state, members: [], callStarter: callerId, video: isVideo, for: conversationId, isConferenceCall: false)
}
func removeMockActiveCalls() {
activeCalls.keys.forEach(clearSnapshot)
}
func update(callState: CallState, conversationId: AVSIdentifier, callerId: AVSIdentifier, isVideo: Bool) {
setMockCallState(callState, conversationId: conversationId, callerId: callerId, isVideo: isVideo)
WireCallCenterCallStateNotification(context: uiMOC!, callState: callState, conversationId: conversationId, callerId: callerId, messageTime: nil, previousCallState: nil).post(in: uiMOC!.notificationContext)
}
// MARK: Call Initiator
func setMockCallInitiator(callerId: AVSIdentifier, conversationId: AVSIdentifier) {
clearSnapshot(conversationId: conversationId)
createSnapshot(callState: .established, members: [], callStarter: callerId, video: false, for: conversationId, isConferenceCall: false)
}
}
| gpl-3.0 | cae7329474c4e8a64bbbf8cc1f65f3b8 | 37.0625 | 232 | 0.725481 | 4.63278 | false | false | false | false |
arsonik/AKTrakt | Source/shared/Enums/TraktImageType.swift | 1 | 2273 | //
// TraktImageType.swift
// AKTrakt
//
// Created by Florian Morello on 30/10/15.
// Copyright © 2015 Florian Morello. All rights reserved.
//
import Foundation
/// Represents the possible image type
public enum TraktImageType: String {
/// Banner
case Banner = "banner"
/// ClearArt
case ClearArt = "clearart"
/// FanArt
case FanArt = "fanart"
/// HeadShot (person's face)
case HeadShot = "headshot"
/// Logo
case Logo = "logo"
/// Poster
case Poster = "poster"
/// Thumb
case Thumb = "thumb"
/// Avatar
case Avatar = "avatar"
/// Screenshot
case Screenshot = "screenshot"
/// Return available sizes for type
var sizes: [TraktImageSize: CGSize] {
switch self {
case .Poster:
return [
.Full: CGSize(width: 1000, height: 1500),
.Medium: CGSize(width: 600, height: 900),
.Thumb: CGSize(width: 300, height: 450),
]
case .FanArt:
return [
.Full: CGSize(width: 1920, height: 1080),
.Medium: CGSize(width: 1280, height: 720),
.Thumb: CGSize(width: 853, height: 480),
]
case .Screenshot:
return [
.Full: CGSize(width: 1920, height: 1080),
.Medium: CGSize(width: 1280, height: 720),
.Thumb: CGSize(width: 853, height: 480),
]
case .HeadShot:
return [
.Full: CGSize(width: 1000, height: 1500),
.Medium: CGSize(width: 600, height: 900),
.Thumb: CGSize(width: 300, height: 450),
]
case .Banner:
return [
.Full: CGSize(width: 1000, height: 185),
]
case .Logo:
return [
.Full: CGSize(width: 800, height: 310),
]
case .ClearArt:
return [
.Full: CGSize(width: 1000, height: 562),
]
case .Thumb:
return [
.Full: CGSize(width: 1000, height: 562),
]
case .Avatar:
return [
.Full: CGSize(width: 256, height: 256),
]
}
}
}
| mit | 8cdf6105c54c197dbb0cf35b618f59ed | 27.049383 | 58 | 0.483715 | 4.270677 | false | false | false | false |
jianghongbing/APIReferenceDemo | UIKit/UISplitViewController/UISplitViewController/DetailViewController.swift | 1 | 1081 | //
// DetailViewController.swift
// UISplitViewController
//
// Created by pantosoft on 2017/6/15.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "DetailViewController"
let indicatorLabel = UILabel()
indicatorLabel.translatesAutoresizingMaskIntoConstraints = false
indicatorLabel.textColor = .orange
indicatorLabel.text = "DetailViewController"
view.addSubview(indicatorLabel)
indicatorLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
indicatorLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
//将navigationItem的left button item 设置为 splitViewController的displayModeButtonItem.点击会呈现splitViewController的masterViewController
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
}
}
| mit | ef47cbf1db098f2529d4dd98f3935e82 | 35.344828 | 134 | 0.732448 | 5.823204 | false | false | false | false |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/Pods/Moya/Endpoint.swift | 3 | 3147 | //
// Endpoint.swift
// Moya
//
// Created by Ash Furrow on 2014-08-16.
// Copyright (c) 2014 Ash Furrow. All rights reserved.
//
import Foundation
import Alamofire
/// Used for stubbing responses.
public enum EndpointSampleResponse {
case Success(Int, () -> NSData)
case Error(Int?, NSError?, (() -> NSData)?)
case Closure(() -> EndpointSampleResponse)
func evaluate() -> EndpointSampleResponse {
switch self {
case Success, Error: return self
case Closure(let closure):
return closure().evaluate()
}
}
}
/// Class for reifying a target of the T enum unto a concrete Endpoint
public class Endpoint<T> {
public let URL: String
public let method: Moya.Method
public let sampleResponse: EndpointSampleResponse
public let parameters: [String: AnyObject]
public let parameterEncoding: Moya.ParameterEncoding
public let httpHeaderFields: [String: AnyObject]
/// Main initializer for Endpoint.
public init(URL: String, sampleResponse: EndpointSampleResponse, method: Moya.Method = Moya.Method.GET, parameters: [String: AnyObject] = [String: AnyObject](), parameterEncoding: Moya.ParameterEncoding = .URL, httpHeaderFields: [String: AnyObject] = [String: AnyObject]()) {
self.URL = URL
self.sampleResponse = sampleResponse
self.method = method
self.parameters = parameters
self.parameterEncoding = parameterEncoding
self.httpHeaderFields = httpHeaderFields
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added parameters.
public func endpointByAddingParameters(parameters: [String: AnyObject]) -> Endpoint<T> {
var newParameters = self.parameters ?? [String: AnyObject]()
for (key, value) in parameters {
newParameters[key] = value
}
return Endpoint(URL: URL, sampleResponse: sampleResponse, method: method, parameters: newParameters, parameterEncoding: parameterEncoding, httpHeaderFields: httpHeaderFields)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added HTTP header fields.
public func endpointByAddingHTTPHeaderFields(httpHeaderFields: [String: AnyObject]) -> Endpoint<T> {
var newHTTPHeaderFields = self.httpHeaderFields ?? [String: AnyObject]()
for (key, value) in httpHeaderFields {
newHTTPHeaderFields[key] = value
}
return Endpoint(URL: URL, sampleResponse: sampleResponse, method: method, parameters: parameters, parameterEncoding: parameterEncoding, httpHeaderFields: newHTTPHeaderFields)
}
}
/// Extension for converting an extension into an NSURLRequest.
extension Endpoint {
public var urlRequest: NSURLRequest {
var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = method.method().rawValue
request.allHTTPHeaderFields = httpHeaderFields
return parameterEncoding.parameterEncoding().encode(request, parameters: parameters).0
}
}
| mit | ec9563d169e27f2b243f8ce8b6acf124 | 40.407895 | 279 | 0.700667 | 5.227575 | false | false | false | false |
isnine/HutHelper-Open | HutHelper/Vendor/EachNavigationBar_Objc/EachNavigationBar/Classes/Configuration.swift | 1 | 1846 | //
// UINavigationController+Configuration.swift
// EachNavigationBar
//
// Created by Pircate([email protected]) on 2018/6/26.
// Copyright © 2018年 Pircate. All rights reserved.
//
import UIKit
@objcMembers
public class Configuration: NSObject {
public var isEnabled = false
public var isHidden = false
public var alpha: CGFloat = 1
public var barTintColor: UIColor?
public var tintColor: UIColor?
public var shadowImage: UIImage?
// Hides shadow image.
public var isShadowHidden: Bool = false
public var titleTextAttributes: [NSAttributedString.Key: Any]?
public var isTranslucent: Bool = true
public var barStyle: UIBarStyle = .default
public var statusBarStyle: UIStatusBarStyle = .default
/// Additional height for the navigation bar.
public var additionalHeight: CGFloat = 0
@available(iOS 11.0, *)
/// Padding of navigation bar content view.
public lazy var layoutPaddings: UIEdgeInsets = {
Const.NavigationBar.layoutPaddings
}()
public var shadow: Shadow?
var _largeTitleTextAttributes: [NSAttributedString.Key: Any]?
var backgroundImage: UIImage?
var barMetrics: UIBarMetrics = .default
var barPosition: UIBarPosition = .any
}
extension Configuration {
@available(iOS 11.0, *)
@objc public var largeTitleTextAttributes: [NSAttributedString.Key: Any]? {
get { return _largeTitleTextAttributes }
set { _largeTitleTextAttributes = newValue }
}
}
extension Configuration {
@objc public func setBackgroundImage(
_ backgroundImage: UIImage?,
for barPosition: UIBarPosition = .any,
barMetrics: UIBarMetrics = .default) {
self.backgroundImage = backgroundImage
self.barPosition = barPosition
self.barMetrics = barMetrics
}
}
| lgpl-2.1 | c40e6184b562f2eeb9fa4c9a87ff44ef | 23.25 | 79 | 0.695605 | 4.81201 | false | true | false | false |
LoopKit/LoopKit | LoopKit/GlucoseKit/CachedGlucoseObject+CoreDataClass.swift | 1 | 7538 | //
// CachedGlucoseObject+CoreDataClass.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
//
import Foundation
import CoreData
import HealthKit
class CachedGlucoseObject: NSManagedObject {
var syncVersion: Int? {
get {
willAccessValue(forKey: "syncVersion")
defer { didAccessValue(forKey: "syncVersion") }
return primitiveSyncVersion?.intValue
}
set {
willChangeValue(forKey: "syncVersion")
defer { didChangeValue(forKey: "syncVersion") }
primitiveSyncVersion = newValue.map { NSNumber(value: $0) }
}
}
var device: HKDevice? {
get {
willAccessValue(forKey: "device")
defer { didAccessValue(forKey: "device") }
return primitiveDevice.flatMap { try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKDevice.self, from: $0) }
}
set {
willChangeValue(forKey: "device")
defer { didChangeValue(forKey: "device") }
primitiveDevice = newValue.flatMap { try? NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: false) }
}
}
var condition: GlucoseCondition? {
get {
willAccessValue(forKey: "condition")
defer { didAccessValue(forKey: "condition") }
return primitiveCondition.flatMap { GlucoseCondition(rawValue: $0) }
}
set {
willChangeValue(forKey: "condition")
defer { didChangeValue(forKey: "condition") }
primitiveCondition = newValue.map { $0.rawValue }
}
}
var trend: GlucoseTrend? {
get {
willAccessValue(forKey: "trend")
defer { didAccessValue(forKey: "trend") }
return primitiveTrend.flatMap { GlucoseTrend(rawValue: $0.intValue) }
}
set {
willChangeValue(forKey: "trend")
defer { didChangeValue(forKey: "trend") }
primitiveTrend = newValue.map { NSNumber(value: $0.rawValue) }
}
}
var hasUpdatedModificationCounter: Bool { changedValues().keys.contains("modificationCounter") }
func updateModificationCounter() { setPrimitiveValue(managedObjectContext!.modificationCounter!, forKey: "modificationCounter") }
override func awakeFromInsert() {
super.awakeFromInsert()
updateModificationCounter()
}
override func willSave() {
if isUpdated && !hasUpdatedModificationCounter {
updateModificationCounter()
}
super.willSave()
}
}
// MARK: - Helpers
extension CachedGlucoseObject {
var quantity: HKQuantity { HKQuantity(unit: HKUnit(from: unitString), doubleValue: value) }
var quantitySample: HKQuantitySample {
var metadata: [String: Any] = [:]
metadata[HKMetadataKeySyncIdentifier] = syncIdentifier
metadata[HKMetadataKeySyncVersion] = syncVersion
if isDisplayOnly {
metadata[MetadataKeyGlucoseIsDisplayOnly] = true
}
if wasUserEntered {
metadata[HKMetadataKeyWasUserEntered] = true
}
metadata[MetadataKeyGlucoseCondition] = condition?.rawValue
metadata[MetadataKeyGlucoseTrend] = trend?.symbol
metadata[MetadataKeyGlucoseTrendRateUnit] = trendRateUnit
metadata[MetadataKeyGlucoseTrendRateValue] = trendRateValue
return HKQuantitySample(
type: HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!,
quantity: quantity,
start: startDate,
end: startDate,
device: device,
metadata: metadata
)
}
var trendRate: HKQuantity? {
get {
guard let trendRateUnit = trendRateUnit, let trendRateValue = trendRateValue else {
return nil
}
return HKQuantity(unit: HKUnit(from: trendRateUnit), doubleValue: trendRateValue.doubleValue)
}
set {
if let newValue = newValue {
let unit = HKUnit(from: unitString).unitDivided(by: .minute())
trendRateUnit = unit.unitString
trendRateValue = NSNumber(value: newValue.doubleValue(for: unit))
} else {
trendRateUnit = nil
trendRateValue = nil
}
}
}
}
// MARK: - Operations
extension CachedGlucoseObject {
/// Creates (initializes) a `CachedGlucoseObject` from a new CGM sample from Loop.
/// - parameters:
/// - sample: A new glucose (CGM) sample to copy data from.
/// - provenanceIdentifier: A string uniquely identifying the provenance (origin) of the sample.
/// - healthKitStorageDelay: The amount of time (seconds) to delay writing this sample to HealthKit. A `nil` here means this sample is not eligible (i.e. authorized) to be written to HealthKit.
func create(from sample: NewGlucoseSample, provenanceIdentifier: String, healthKitStorageDelay: TimeInterval?) {
self.uuid = nil
self.provenanceIdentifier = provenanceIdentifier
self.syncIdentifier = sample.syncIdentifier
self.syncVersion = sample.syncVersion
self.value = sample.quantity.doubleValue(for: .milligramsPerDeciliter)
self.unitString = HKUnit.milligramsPerDeciliter.unitString
self.startDate = sample.date
self.isDisplayOnly = sample.isDisplayOnly
self.wasUserEntered = sample.wasUserEntered
self.device = sample.device
self.condition = sample.condition
self.trend = sample.trend
self.trendRate = sample.trendRate
self.healthKitEligibleDate = healthKitStorageDelay.map { sample.date.addingTimeInterval($0) }
}
// HealthKit
func create(from sample: HKQuantitySample) {
self.uuid = sample.uuid
self.provenanceIdentifier = sample.provenanceIdentifier
self.syncIdentifier = sample.syncIdentifier
self.syncVersion = sample.syncVersion
self.value = sample.quantity.doubleValue(for: .milligramsPerDeciliter)
self.unitString = HKUnit.milligramsPerDeciliter.unitString
self.startDate = sample.startDate
self.isDisplayOnly = sample.isDisplayOnly
self.wasUserEntered = sample.wasUserEntered
self.device = sample.device
self.condition = sample.condition
self.trend = sample.trend
self.trendRate = sample.trendRate
// The assumption here is that if this is created from a HKQuantitySample, it is coming out of HealthKit, and
// therefore does not need to be written to HealthKit.
self.healthKitEligibleDate = nil
}
}
// MARK: - Watch Synchronization
extension CachedGlucoseObject {
func update(from sample: StoredGlucoseSample) {
self.uuid = sample.uuid
self.provenanceIdentifier = sample.provenanceIdentifier
self.syncIdentifier = sample.syncIdentifier
self.syncVersion = sample.syncVersion
self.value = sample.quantity.doubleValue(for: .milligramsPerDeciliter)
self.unitString = HKUnit.milligramsPerDeciliter.unitString
self.startDate = sample.startDate
self.isDisplayOnly = sample.isDisplayOnly
self.wasUserEntered = sample.wasUserEntered
self.device = sample.device
self.condition = sample.condition
self.trend = sample.trend
self.trendRate = sample.trendRate
self.healthKitEligibleDate = sample.healthKitEligibleDate
}
}
| mit | a2a44391e4a3ef460030465b3b3baaa0 | 36.497512 | 200 | 0.650657 | 4.878317 | false | false | false | false |
Molbie/Outlaw | Sources/Outlaw/Core/IndexExtractable/IndexExtractable+ValueWithContext.swift | 1 | 5982 | //
// IndexExtractable+ValueWithContext.swift
// Outlaw
//
// Created by Brian Mullen on 11/23/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
// MARK: -
// MARK: ValueWithContext
public extension IndexExtractable {
func value<V: ValueWithContext>(for index: Index, using context: V.Context) throws -> V {
let any = try self.any(for: index)
do {
guard let result = try V.value(from: any, using: context) as? V else {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: V.self, actual: any)
}
return result
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<V: ValueWithContext>(for index: Index, using context: V.Context) -> V? {
return try? self.value(for: index, using: context)
}
func value<V: ValueWithContext>(for index: Index, using context: V.Context, or value: V) -> V {
guard let result: V = self.optional(for: index, using: context) else { return value }
return result
}
}
// MARK: -
// MARK: ValueWithContext Array
public extension IndexExtractable {
func value<V: ValueWithContext>(for index: Index, using context: V.Context) throws -> [V] {
let any = try self.any(for: index)
do {
return try Array<V>.mappedValue(from: any, using: context)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<V: ValueWithContext>(for index: Index, using context: V.Context) -> [V]? {
return try? self.value(for: index, using: context)
}
func value<V: ValueWithContext>(for index: Index, using context: V.Context, or value: [V]) -> [V] {
guard let result: [V] = self.optional(for: index, using: context) else { return value }
return result
}
}
// MARK: -
// MARK: Optional ValueWithContext Array
public extension IndexExtractable {
func value<V: ValueWithContext>(for index: Index, using context: V.Context) throws -> [V?] {
let any = try self.any(for: index)
do {
return try Array<V?>.mappedValue(from: any, using: context)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<V: ValueWithContext>(for index: Index, using context: V.Context) -> [V?]? {
return try? self.value(for: index, using: context)
}
func value<V: ValueWithContext>(for index: Index, using context: V.Context, or value: [V?]) -> [V?] {
guard let result: [V?] = self.optional(for: index, using: context) else { return value }
return result
}
}
// MARK: -
// MARK: ValueWithContext Dictionary
public extension IndexExtractable {
func value<K, V: ValueWithContext>(for index: Index, using context: V.Context) throws -> [K: V] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V>.mappedValue(from: any, using: context)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<K, V: ValueWithContext>(for index: Index, using context: V.Context) -> [K: V]? {
return try? self.value(for: index, using: context)
}
func value<K, V: ValueWithContext>(for index: Index, using context: V.Context, or value: [K: V]) -> [K: V] {
guard let result: [K: V] = self.optional(for: index, using: context) else { return value }
return result
}
}
// MARK: -
// MARK: Optional ValueWithContext Dictionary
public extension IndexExtractable {
func value<K, V: ValueWithContext>(for index: Index, using context: V.Context) throws -> [K: V?] {
let any = try self.any(for: index)
do {
return try Dictionary<K, V?>.mappedValue(from: any, using: context)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<K, V: ValueWithContext>(for index: Index, using context: V.Context) -> [K: V?]? {
return try? self.value(for: index, using: context)
}
func value<K, V: ValueWithContext>(for index: Index, using context: V.Context, or value: [K: V?]) -> [K: V?] {
guard let result: [K: V?] = self.optional(for: index, using: context) else { return value }
return result
}
}
// MARK: -
// MARK: ValueWithContext Set
public extension IndexExtractable {
func value<V: ValueWithContext>(for index: Index, using context: V.Context) throws -> Set<V> {
let any = try self.any(for: index)
do {
return try Set<V>.mappedValue(from: any, using: context)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual)
}
}
func optional<V: ValueWithContext>(for index: Index, using context: V.Context) -> Set<V>? {
return try? self.value(for: index, using: context)
}
func value<V: ValueWithContext>(for index: Index, using context: V.Context, or value: Set<V>) -> Set<V> {
guard let result: Set<V> = self.optional(for: index, using: context) else { return value }
return result
}
}
| mit | 6c6ca0678d5985e7f5239c8582b6fe0c | 37.095541 | 114 | 0.634008 | 3.940053 | false | false | false | false |
nuudles/CacheIsKing | Source/KingCache.swift | 1 | 4807 | //
// KingCache.swift
// CacheIsKing
//
// Created by Christopher Luu on 1/26/16.
//
//
import Foundation
/// `KingCache` is a simple cache that can hold anything, including Swift structs, enums, and values.
/// It is designed to work similar to the `NSCache`, but with native Swift support.
///
open class KingCache {
// MARK: - Private variables
/// An array of `NSNotificationCenter` observers that need to be removed upon deinitialization
fileprivate var notificationObservers: [NSObjectProtocol] = []
// MARK: - Internal variables
/// The dictionary that holds the cached values
var cacheDictionary: [AnyKey: Any] = [:]
// MARK: - Public variables
/// The number of items in the cache
open var count: Int {
return cacheDictionary.count
}
/// The limit of the amount of items that can be held in the cache. This defaults to 0, which means there is no limit.
open var countLimit: UInt = 0 {
didSet {
evictItemsIfNeeded()
}
}
// MARK: - Initialization methods
public init() {
let removalBlock = { [unowned self] (_: Notification) in
self.cacheDictionary.removeAll()
}
var notificationObserver = NotificationCenter.default
.addObserver(forName: NSNotification.Name.UIApplicationDidReceiveMemoryWarning,
object: UIApplication.shared,
queue: nil,
using: removalBlock)
notificationObservers.append(notificationObserver)
notificationObserver = NotificationCenter.default
.addObserver(forName: NSNotification.Name.UIApplicationDidEnterBackground,
object: UIApplication.shared,
queue: nil,
using: removalBlock)
notificationObservers.append(notificationObserver)
}
deinit {
notificationObservers.forEach {
NotificationCenter.default.removeObserver($0)
}
}
// MARK: - Internal methods
/// Evicts items if the `countLimit` has been reached.
/// This currently uses a random eviction policy, kicking out random items until the `countLimit` is satisfied.
///
func evictItemsIfNeeded() {
if countLimit > 0 && cacheDictionary.count > Int(countLimit) {
// TODO: Evict items with more rhyme or reason
var keys = Array(cacheDictionary.keys)
while cacheDictionary.count > Int(countLimit) {
let randomIndex = Int(arc4random_uniform(UInt32(keys.count)))
let key = keys.remove(at: randomIndex)
cacheDictionary.removeValue(forKey: key)
}
}
}
// MARK: - Public methods
/// Adds an item to the cache for any given `Hashable` key.
///
/// - parameter item: The item to be cached
/// - parameter key: The key with which to cache the item
///
open func set<K: Hashable>(item: Any, for key: K) {
cacheDictionary[AnyKey(key)] = item
evictItemsIfNeeded()
}
/// Gets an item from the cache if it exists for a given `Hashable` key.
/// This method uses generics to infer the type that should be returned.
///
/// Note: Even if an item exists for the key, but does not match the given type, it will return `nil`.
///
/// - parameter key: The key whose item should be fetched
/// - returns: The item from the cache if it exists, or `nil` if an item could not be found
///
open func item<T, K: Hashable>(for key: K) -> T? {
if let item = cacheDictionary[AnyKey(key)] as? T {
return item
}
return nil
}
/// Discards an item for a given `Hashable` key.
///
/// - parameter key: The key whose item should be removed
///
open func remove<K: Hashable>(for key: K) {
cacheDictionary[AnyKey(key)] = nil
}
/// Discards all items for any key that matches the given filter.
///
/// - parameter filter: Closure that returns true for keys that should be removed
///
open func remove<K: Hashable>(matching filter: (K) -> Bool) {
for key in cacheDictionary.keys {
guard let key = key.underlying as? K else { continue }
if filter(key) {
remove(for: key)
}
}
}
/// Clears the entire cache.
///
open func removeAll() {
cacheDictionary.removeAll()
}
// MARK: - Subscript methods
// TODO: Consolidate these subscript methods once subscript generics with constraints are supported
/// A subscript method that allows `Int` key subscripts.
///
open subscript(key: Int) -> Any? {
get {
return item(for: key)
}
set {
if let newValue = newValue {
set(item: newValue, for: key)
} else {
remove(for: key)
}
}
}
/// A subscript method that allows `Float` key subscripts.
///
open subscript(key: Float) -> Any? {
get {
return item(for: key)
}
set {
if let newValue = newValue {
set(item: newValue, for: key)
} else {
remove(for: key)
}
}
}
/// A subscript method that allows `String` key subscripts.
///
open subscript(key: String) -> Any? {
get {
return item(for: key)
}
set {
if let newValue = newValue {
set(item: newValue, for: key)
} else {
remove(for: key)
}
}
}
}
| mit | cf6ce1895615369f5bf2c8d2eabda26c | 26.3125 | 119 | 0.682754 | 3.5062 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Models/Congrats/PXPaymentCongrats.swift | 1 | 15972 | import Foundation
/**
This class holds all the information a congrats' view needs to consume (specified at `PXNewResultViewModelInterface`).
This also acts as an entry point for congrats withouth having to go through the entire checkout flow.
*/
@objcMembers
public final class PXPaymentCongrats: NSObject {
// Header
private(set) var type: PXCongratsType = .rejected
private(set) var headerColor: UIColor?
private(set) var headerTitle: String = ""
private(set) var headerURL: String?
private(set) var headerCloseAction: (() -> Void)?
private(set) var headerImage: UIImage?
private(set) var headerBadgeImage: UIImage?
// Receipt
private(set) var shouldShowReceipt: Bool = false
private(set) var receiptId: String?
private(set) var receiptAction: PXRemoteAction?
// Points
private(set) var points: PXPoints?
// Discounts
private(set) var discounts: PXDiscounts?
// Expense split
private(set) var expenseSplit: PXExpenseSplit?
// CrossSelling
private(set) var crossSelling: [PXCrossSellingItem]?
// Place receipt view and payment view over points and crosselling? Default is false
private(set) var hasCustomSorting: Bool = false
// Instructions
private(set) var instructions: PXInstruction?
// Footer Buttons
private(set) var mainAction: PXAction?
private(set) var secondaryAction: PXAction?
// CustomViews
private(set) var topView: UIView?
private(set) var importantView: UIView?
private(set) var bottomView: UIView?
// Remedies
private(set) var remedyViewData: PXRemedyViewData?
private(set) var creditsExpectationView: UIView?
// Payment Info
private(set) var shouldShowPaymentMethod: Bool = false
private(set) var paymentInfo: PXCongratsPaymentInfo?
private(set) var statementDescription: String?
// Split
private(set) var splitPaymentInfo: PXCongratsPaymentInfo?
// Tracking
private(set) var internalTrackingValues: [String: Any]?
private(set) var externalTrackingValues: PXPaymentCongratsTracking?
private(set) var internalTrackingPath: TrackingEvents?
private(set) var internalFlowBehaviourResult: PXResultKey?
private(set) var bankTransferProperties: [String: Any]?
// Error
private(set) var errorBodyView: UIView?
// URLs
private(set) var shouldAutoReturn: Bool = false
private(set) var redirectURL: URL?
private(set) var autoReturn: PXAutoReturn?
// Buttons
private(set) var primaryButton: PXButton?
// AndesMessage
private(set) var infoOperation: InfoOperation?
// MARK: Initializer
override public init() {
super.init()
}
}
// MARK: Internal API
extension PXPaymentCongrats {
/**
Any color for showing in the congrats' header. This should be used ONLY internally
- parameter color: a color
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withHeaderColor(_ color: UIColor) -> PXPaymentCongrats {
self.headerColor = color
return self
}
/**
Collector image shown in congrats' header. Can receive an `UIImage` or a `URL`.
- parameter image: an image in `UIImage` format
- parameter url: an `URL` for the image
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withHeaderImage(_ image: UIImage?) -> PXPaymentCongrats {
self.headerImage = image
return self
}
@discardableResult
func withBankTransferTrackingProperties(properties: [String: Any]) -> PXPaymentCongrats {
self.bankTransferProperties = properties
return self
}
/**
Collector badge image shown in congrats' header. This should be used ONLY internally
- parameter image: an image in `UIImage` format
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withHeaderBadgeImage(_ image: UIImage?) -> PXPaymentCongrats {
self.headerBadgeImage = image
return self
}
/**
This is used in paymentResult on checkout Process, define
- parameter view: some UIView
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withInstructions(_ instruction: PXInstruction?) -> PXPaymentCongrats {
self.instructions = instruction
return self
}
@discardableResult
func withInfoOperation(_ infoOperation: InfoOperation?) -> PXPaymentCongrats {
self.infoOperation = infoOperation
return self
}
/**
If the congrats has remedy, recieves a custom view to be displayed.
- Parameters:
- remedyView: some `UIView`
- remedyButtonAction: some `closure`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withRemedyViewData(_ remedyViewData: PXRemedyViewData?) -> PXPaymentCongrats {
self.remedyViewData = remedyViewData
return self
}
/**
This is used to track how the flow finished,
- parameter result: some PXResultKey
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withFlowBehaviorResult(_ result: PXResultKey) -> PXPaymentCongrats {
self.internalFlowBehaviourResult = result
return self
}
/**
The data that will be requested for tracking
- parameter trackingProperties: a `[String:Any]`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withTrackingProperties(_ trackingProperties: [String: Any]) -> PXPaymentCongrats {
self.internalTrackingValues = trackingProperties
return self
}
@discardableResult
func withTrackingPath(_ event: TrackingEvents?) -> PXPaymentCongrats {
self.internalTrackingPath = event
return self
}
/**
Navigate to another place when closing Congrats
- parameter redirectURL: a `URL`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withRedirectURLs(_ redirectURL: URL?) -> PXPaymentCongrats {
self.redirectURL = redirectURL
return self
}
/**
Close the congrats automatically after a period of time
- parameter shouldAutoReturn: a `Bool`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func shouldAutoReturn(_ shouldAutoReturn: Bool) -> PXPaymentCongrats {
self.shouldAutoReturn = shouldAutoReturn
return self
}
/**
Sets the navigation handler used by checkout. Internal use only.
- parameter navHandler: a `PXNavigationHandler`
*/
func start(using navHandler: PXNavigationHandler, with finishButtonAnimation: (() -> Void)?) {
let viewModel = PXPaymentCongratsViewModel(paymentCongrats: self)
viewModel.launch(navigationHandler: navHandler, showWithAnimation: false, finishButtonAnimation: finishButtonAnimation)
}
}
// MARK: Public API
extension PXPaymentCongrats {
/**
Indicates status Success, Failure, for more info check `PXCongratsType`.
- parameter type: the result status
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withCongratsType(_ type: PXCongratsType) -> PXPaymentCongrats {
self.type = type
return self
}
/**
Fills the header view with a message.
- parameter title: some message
- parameter imageURL: an `URL` for the image
- parameter action: a closure to excecute when the top exit button is pressed.
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withHeader(title: String, imageURL: String?, closeAction: @escaping () -> Void) -> PXPaymentCongrats {
self.headerTitle = title
self.headerURL = imageURL
self.headerCloseAction = closeAction
return self
}
/**
Defines if the receipt view should be shown, in affirmative case, the receiptId must be supplied.
- parameter shouldShowReceipt: a boolean indicating if the receipt view is displayed.
- parameter receiptId: ID of the receipt
- parameter action: action when the receipt view is pressed.
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withReceipt(shouldShowReceipt: Bool, receiptId: String?, action: PXRemoteAction?) -> PXPaymentCongrats {
self.shouldShowReceipt = shouldShowReceipt
self.receiptId = receiptId
self.receiptAction = action
return self
}
/**
Defines the points data in the points seccions of the congrats.
- parameter points: some PXPoints
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withLoyalty(_ points: PXPoints?) -> PXPaymentCongrats {
self.points = points
return self
}
/**
Defines the discounts data in the discounts seccions of the congrats.
- parameter discounts: some PXDiscounts
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withDiscounts(_ discounts: PXDiscounts?) -> PXPaymentCongrats {
self.discounts = discounts
return self
}
@discardableResult
public func withAutoReturn(_ autoReturn: PXAutoReturn?) -> PXPaymentCongrats {
self.autoReturn = autoReturn
return self
}
@discardableResult
public func withPrimaryButton(_ primaryButton: PXButton?) -> PXPaymentCongrats {
self.primaryButton = primaryButton
return self
}
/**
Defines the Expense Split data in the expense split seccions of the congrats.
- parameter expenseSplit: some PXExpenseSplit
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withExpenseSplit(_ expenseSplit: PXExpenseSplit? ) -> PXPaymentCongrats {
self.expenseSplit = expenseSplit
return self
}
/**
Defines the cross selling data in the cross selling seccions of the congrats.
- parameter crossSellingItems: an array of PXCrossSellingItem
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withCrossSelling(_ items: [PXCrossSellingItem]? ) -> PXPaymentCongrats {
self.crossSelling = items
return self
}
/**
Defines how will be the sort of the component in the Congrats
- parameter customSorting: a boolean
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withCustomSorting(_ customSorting: Bool?) -> PXPaymentCongrats {
self.hasCustomSorting = customSorting ?? false
return self
}
/**
Top button configuration.
- parameter label: button display text
- parameter action: a closure to excecute
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withFooterMainAction(_ action: PXAction?) -> PXPaymentCongrats {
self.mainAction = action
return self
}
/**
Bottom button configuration.
- parameter label: button display text
- parameter action: a closure to excecute
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withFooterSecondaryAction(_ action: PXAction?) -> PXPaymentCongrats {
self.secondaryAction = action
return self
}
/**
Top Custom view to be displayed.
- parameter view: some `UIView`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withTopView(_ view: UIView?) -> PXPaymentCongrats {
self.topView = view
return self
}
/**
Important Custom view to be displayed.
- parameter view: some `UIView`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withImportantView(_ view: UIView?) -> PXPaymentCongrats {
self.importantView = view
return self
}
/**
Bottom Custom view to be displayed.
- parameter view: some `UIView`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withBottomView(_ view: UIView?) -> PXPaymentCongrats {
self.bottomView = view
return self
}
/**
This view is shown if there has been a payment with credit.
- parameter view: some `UIView`
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withCreditsExpectationView(_ view: UIView?) -> PXPaymentCongrats {
self.creditsExpectationView = view
return self
}
/**
Defines if the payment method (or split payment method) should be shown.
- parameter shouldShowPaymentMethod: a `boolean` indication if it should be shown.
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func shouldShowPaymentMethod(_ shouldShowPaymentMethod: Bool) -> PXPaymentCongrats {
self.shouldShowPaymentMethod = shouldShowPaymentMethod
return self
}
/**
Data containing all of the information for displaying the payment method .
- parameter paymentInfo: a DTO for creating a `PXCongratsPaymentInfo` representing the payment method
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withPaymentMethodInfo(_ paymentInfo: PXCongratsPaymentInfo) -> PXPaymentCongrats {
self.paymentInfo = paymentInfo
return self
}
/**
Data containing all of the information for displaying the split payment method .
- parameter paymentInfo: a DTO for creating a `PXCongratsPaymentInfo` representing the payment method
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withSplitPaymentInfo(_ splitPaymentInfo: PXCongratsPaymentInfo) -> PXPaymentCongrats {
self.splitPaymentInfo = splitPaymentInfo
return self
}
/**
If the paymentMehotd will be shown, and it is a credit card, this statemetnDescrption will be shown on the payment method view.
- parameter statementDescription: some String
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
func withStatementDescription(_ statementDescription: String?) -> PXPaymentCongrats {
self.statementDescription = statementDescription
return self
}
/**
An error view to be displayed when a failure congrats is shown
- parameter shouldShow: a `Bool` indicating if the error screen should be shown.
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withErrorBodyView(_ view: UIView?) -> PXPaymentCongrats {
self.errorBodyView = view
return self
}
/**
The data and the configuration that will be requested for tracking
- parameter trackingProperties: a `PXPaymentCongratsTracking`
- parameter trackingConfiguration: a `PXTrackingConfiguration` with the following properties:
flowName: The name of the flow using the congrats.
flowDetail: Extradata that the user of the congrats wants to track
trackListener: a Class that conform the protocol TrackListener.
sessionId: Optional if the user want to use the sessionId.
- returns: this builder `PXPaymentCongrats`
*/
@discardableResult
public func withTracking(trackingProperties: PXPaymentCongratsTracking) -> PXPaymentCongrats {
self.externalTrackingValues = trackingProperties
return self
}
/**
Shows the congrats' view.
- parameter navController: a `UINavigationController`
*/
public func start(using navController: UINavigationController) {
let viewModel = PXPaymentCongratsViewModel(paymentCongrats: self)
viewModel.launch(navigationHandler: PXNavigationHandler(navigationController: navController), showWithAnimation: true)
}
}
| mit | 9df619d34189d80685f5c2588332c41f | 32.484277 | 131 | 0.687015 | 4.859142 | false | false | false | false |
kartikpatel211/KTCalc | KTCalc/Calculation.swift | 1 | 3248 | //
// Calculation.swift
// KTCalc
//
// Created by Paresh Patel on 12/10/16.
// Copyright © 2016 Kartik Patel. All rights reserved.
//
import UIKit
class Calculation: NSObject {
var val1 = "0"
var val2 = "0"
var oper = ""
var txtCalc = "0"
func calcResult(val1: String, oper : String, val2 : String)-> String{
var res = ""
if isIntValue(val: val1) && isIntValue(val: val2) {
// perform Int Operation
switch oper {
case "+":
res = "\( ((val1 as NSString).intValue) + ((val2 as NSString).intValue))"
case "-":
res = "\( ((val1 as NSString).intValue) - ((val2 as NSString).intValue))"
case "*":
res = "\( ((val1 as NSString).intValue) * ((val2 as NSString).intValue))"
case "/":
res = "\( ((val1 as NSString).intValue) / ((val2 as NSString).intValue))"
default:
res = ""
}
} else {
// perform Double Operation
switch oper {
case "+":
res = "\( ((val1 as NSString).doubleValue) + ((val2 as NSString).doubleValue))"
case "-":
res = "\( ((val1 as NSString).doubleValue) - ((val2 as NSString).doubleValue))"
case "*":
res = "\( ((val1 as NSString).doubleValue) * ((val2 as NSString).doubleValue))"
case "/":
res = "\( ((val1 as NSString).doubleValue) / ((val2 as NSString).doubleValue))"
default:
res = ""
}
}
return res
}
func isIntValue(val : String) -> Bool {
return (val as NSString).doubleValue.truncatingRemainder(dividingBy: 1) == 0
}
func plus(){
val1 = txtCalc
oper = "+"
txtCalc = "0"
}
func minus(){
val1 = txtCalc
oper = "-"
txtCalc = "0"
}
func multiply(){
val1 = txtCalc
oper = "*"
txtCalc = "0"
}
func division(){
val1 = txtCalc
oper = "/"
txtCalc = "0"
}
func isEqualCalc(){
val2 = txtCalc
txtCalc = calcResult(val1: val1, oper: oper, val2: val2)
}
func clear(){
val1 = "0"
val2 = "0"
oper = ""
txtCalc = "0"
}
func plusMinus(){
if isIntValue(val: txtCalc) {
txtCalc = "\((txtCalc as NSString).intValue * -1)"
} else {
txtCalc = "\((txtCalc as NSString).doubleValue * -1)"
}
}
func percentage(){
if (val1 as NSString).intValue != 0 {
/*if isIntValue(val: txtCalc) {
txtCalc = "\((val1 as NSString).intValue * (txtCalc as NSString).intValue / 100)"
} else {*/
txtCalc = "\((val1 as NSString).doubleValue * (txtCalc as NSString).doubleValue / 100)"
/*}*/
} else {
if isIntValue(val: txtCalc) {
txtCalc = "\((txtCalc as NSString).intValue / 100)"
} else {
txtCalc = "\((txtCalc as NSString).doubleValue / 100)"
}
}
}
}
| mit | 56ed69ca056c2c575928924d6f240e1e | 27.482456 | 99 | 0.459809 | 4.329333 | false | false | false | false |
KittenYang/A-GUIDE-TO-iOS-ANIMATION | Swift Version/JumpStarDemo-Swift/JumpStarDemo-Swift/Classes/JumpStarView.swift | 1 | 5176 | //
// JumpStarView.swift
// JumpStarDemo-Swift
//
// Created by Kitten Yang on 1/6/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
import UIKit
enum SelectState {
case NotMarked;
case Marked
}
struct JumpStarOptions {
var markedImage: UIImage
var notMarkedImage: UIImage
var jumpDuration: NSTimeInterval
var downDuration: NSTimeInterval
}
class JumpStarView: UIView {
var option: JumpStarOptions?
var state: SelectState = .NotMarked {
didSet{
starView.image = state == .Marked ? option?.markedImage : option?.notMarkedImage
}
}
private var starView: UIImageView!
private var shadowView: UIImageView!
private var animating: Bool = false
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = UIColor.clearColor()
if starView == nil {
starView = UIImageView(frame: CGRect(x: bounds.width/2 - (bounds.width-6)/2, y: 0, width: bounds.width-6, height: bounds.height-6))
starView.contentMode = .ScaleToFill
addSubview(starView)
}
if shadowView == nil {
shadowView = UIImageView(frame: CGRect(x: bounds.width/2 - 10/2, y: bounds.height - 3, width: 10, height: 3))
shadowView.alpha = 0.4
shadowView.image = UIImage(named: "shadow_new")
addSubview(shadowView)
}
}
func animate() {
if animating {
return
}
animating = true
let transformAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
transformAnimation.fromValue = 0.0
transformAnimation.toValue = M_PI_2
transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let positionAnimation = CABasicAnimation(keyPath: "position.y")
positionAnimation.fromValue = starView.center.y
positionAnimation.toValue = starView.center.y - 14.0
positionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let animationGroup = CAAnimationGroup()
if let duration = option?.jumpDuration {
animationGroup.duration = duration
}
animationGroup.fillMode = kCAFillModeForwards
animationGroup.removedOnCompletion = false
animationGroup.delegate = self
animationGroup.animations = [transformAnimation, positionAnimation]
starView.layer.addAnimation(animationGroup, forKey: "jumpUp")
}
}
// MARK : CAAnimationDelegate
extension JumpStarView {
override func animationDidStart(anim: CAAnimation) {
guard let _ = option else {
return
}
if anim == starView.layer.animationForKey("jumpUp") {
UIView.animateWithDuration(option!.jumpDuration, delay: 0.0, options: .CurveEaseOut, animations: { () -> Void in
self.shadowView.alpha = 0.2
self.shadowView.bounds = CGRect(x: 0, y: 0, width: self.shadowView.bounds.width*1.6, height: self.shadowView.bounds.height)
}, completion: nil)
} else if anim == starView.layer.animationForKey("jumpDown") {
UIView.animateWithDuration(option!.jumpDuration, delay: 0.0, options: .CurveEaseOut, animations: { () -> Void in
self.shadowView.alpha = 0.4
self.shadowView.bounds = CGRect(x: 0, y: 0, width: self.shadowView.bounds.width/1.6, height: self.shadowView.bounds.height)
}, completion: nil)
}
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if anim == starView.layer.animationForKey("jumpUp") {
state = state == .Marked ? .NotMarked : .Marked
let transformAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
transformAnimation.fromValue = M_PI_2
transformAnimation.toValue = M_PI
transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let positionAnimation = CABasicAnimation(keyPath: "position.y")
positionAnimation.fromValue = starView.center.y - 14
positionAnimation.toValue = starView.center.y
positionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
let animationGroup = CAAnimationGroup()
if let duration = option?.downDuration {
animationGroup.duration = duration
}
animationGroup.fillMode = kCAFillModeForwards
animationGroup.removedOnCompletion = false
animationGroup.delegate = self
animationGroup.animations = [transformAnimation, positionAnimation]
starView.layer.addAnimation(animationGroup, forKey: "jumpDown")
} else if anim == starView.layer.animationForKey("jumpDown") {
starView.layer.removeAllAnimations()
animating = false
}
}
}
| gpl-2.0 | 0c7791aa693b9693648a0fbfcd9db7ad | 35.443662 | 143 | 0.631498 | 5.21148 | false | false | false | false |
hyacinthxinxin/Apprentice | Checklist/Checklist/ListDetailViewController.swift | 1 | 3156 | //
// ListDetailViewController.swift
// Checklist
//
// Created by 新 范 on 16/3/9.
// Copyright © 2016年 fanxin. All rights reserved.
//
import UIKit
protocol ListDetailViewControllerDelegate: class {
func listDetailViewControllerDidCancel(controller: ListDetailViewController)
func listDetailViewController(controller: ListDetailViewController,didFinishAddingChecklist checklist: Checklist)
func listDetailViewController(controller: ListDetailViewController,
didFinishEditingChecklist checklist: Checklist)
}
class ListDetailViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var doneBarButton: UIBarButtonItem!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var iconImageView: UIImageView!
weak var delegate: ListDetailViewControllerDelegate?
var checklistToEdit: Checklist?
var iconName = "Folder"
override func viewDidLoad() {
super.viewDidLoad()
if let checklist = checklistToEdit {
title = "Edit Checklist"
textField.text = checklist.name
doneBarButton.enabled = true
iconName = checklist.iconName
}
iconImageView.image = UIImage(named: iconName)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textField.becomeFirstResponder()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PickIcon" {
let controller = segue.destinationViewController as! IconPickerViewController
controller.delegate = self
}
}
@IBAction func cancel() {
delegate?.listDetailViewControllerDidCancel(self)
}
@IBAction func done() {
if let checklist = checklistToEdit {
checklist.name = textField.text!
checklist.iconName = iconName
delegate?.listDetailViewController(self, didFinishEditingChecklist: checklist)
} else {
let checklist = Checklist(name: textField.text!, iconName: iconName)
delegate?.listDetailViewController(self, didFinishAddingChecklist: checklist)
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) ->NSIndexPath? {
if indexPath.section == 1 {
return indexPath
} else {
return nil
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let oldText: NSString = textField.text!
let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
doneBarButton.enabled = (newText.length > 0)
return true
}
}
extension ListDetailViewController: IconPickerViewControllerDelegate {
func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) {
self.iconName = iconName
iconImageView.image = UIImage(named: iconName)
navigationController?.popViewControllerAnimated(true)
}
}
| mit | ec5eef01206ba0847af227347c45c669 | 34.784091 | 132 | 0.692283 | 5.820702 | false | false | false | false |
clevertrevor/VideoChatDemo | Chatter/ProfileViewController.swift | 1 | 2108 | //
// ProfileViewController.swift
// Chatter
//
// Created on 2/23/15.
//
//
/*
The MIT License (MIT)
Copyright (c) 2015 Eddy Borja
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import Parse
class ProfileViewController : UIViewController {
@IBOutlet weak var profilePhoto: UIImageView!
override func viewDidLoad() {
var facebookId = PFUser.currentUser().objectForKey("facebookId") as String
var imageURLString = "http://graph.facebook.com/" + facebookId + "/picture?type=large"
var imageURL = NSURL(string: imageURLString)
profilePhoto.sd_setImageWithURL(imageURL)
}
@IBAction func unwindToProfile(segue : UIStoryboardSegue){
var svc = slidingViewController()
if svc.currentTopViewPosition == ECSlidingViewControllerTopViewPosition.Centered {
svc.anchorTopViewToRightAnimated(true)
} else {
svc.resetTopViewAnimated(true)
}
}
@IBAction func logout(sender : AnyObject) {
performSegueWithIdentifier("logout", sender: self)
}
} | mit | 37952f63e28672cd10de7869db0b4c01 | 31.953125 | 94 | 0.722486 | 4.801822 | false | false | false | false |
sarahspins/Loop | Loop/Managers/KeychainManager+Loop.swift | 2 | 2127 | //
// KeychainManager+Loop.swift
// Loop
//
// Created by Nate Racklyeft on 6/26/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
private let AmplitudeAPIKeyService = "AmplitudeAPIKey"
private let DexcomShareURL = NSURL(string: "https://share1.dexcom.com")!
private let NightscoutAccount = "NightscoutAPI"
extension KeychainManager {
func setAmplitudeAPIKey(key: String?) throws {
try replaceGenericPassword(key, forService: AmplitudeAPIKeyService)
}
func getAmplitudeAPIKey() -> String? {
return try? getGenericPasswordForService(AmplitudeAPIKeyService)
}
func setDexcomShareUsername(username: String?, password: String?) throws {
let credentials: InternetCredentials?
if let username = username, password = password {
credentials = InternetCredentials(username: username, password: password, URL: DexcomShareURL)
} else {
credentials = nil
}
try replaceInternetCredentials(credentials, forURL: DexcomShareURL)
}
func getDexcomShareCredentials() -> (username: String, password: String)? {
do {
let credentials = try getInternetCredentials(URL: DexcomShareURL)
return (username: credentials.username, password: credentials.password)
} catch {
return nil
}
}
func setNightscoutURL(URL: NSURL?, secret: String?) {
let credentials: InternetCredentials?
if let URL = URL, secret = secret {
credentials = InternetCredentials(username: NightscoutAccount, password: secret, URL: URL)
} else {
credentials = nil
}
do {
try replaceInternetCredentials(credentials, forAccount: NightscoutAccount)
} catch {
}
}
func getNightscoutCredentials() -> (URL: NSURL, secret: String)? {
do {
let credentials = try getInternetCredentials(account: NightscoutAccount)
return (URL: credentials.URL, secret: credentials.password)
} catch {
return nil
}
}
} | apache-2.0 | 29a630e435a9de35a486f610b9511b76 | 28.541667 | 106 | 0.650047 | 4.831818 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV1/Models/DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo.swift | 1 | 3909 | /**
* (C) Copyright IBM Corp. 2022.
*
* 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 IBMSwiftSDKCore
/**
DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo.
Enums with an associated value of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo:
DialogNodeOutputGeneric
*/
public struct DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo: Codable, Equatable {
/**
The type of response returned by the dialog node. The specified response type must be supported by the client
application or channel.
*/
public var responseType: String
/**
The `https:` URL of the video.
*/
public var source: String
/**
An optional title to show before the response.
*/
public var title: String?
/**
An optional description to show with the response.
*/
public var description: String?
/**
An array of objects specifying channels for which the response is intended. If **channels** is present, the
response is intended for a built-in integration and should not be handled by an API client.
*/
public var channels: [ResponseGenericChannel]?
/**
For internal use only.
*/
public var channelOptions: [String: JSON]?
/**
Descriptive text that can be used for screen readers or other situations where the video cannot be seen.
*/
public var altText: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
case source = "source"
case title = "title"
case description = "description"
case channels = "channels"
case channelOptions = "channel_options"
case altText = "alt_text"
}
/**
Initialize a `DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo` with member variables.
- parameter responseType: The type of response returned by the dialog node. The specified response type must be
supported by the client application or channel.
- parameter source: The `https:` URL of the video.
- parameter title: An optional title to show before the response.
- parameter description: An optional description to show with the response.
- parameter channels: An array of objects specifying channels for which the response is intended. If
**channels** is present, the response is intended for a built-in integration and should not be handled by an API
client.
- parameter channelOptions: For internal use only.
- parameter altText: Descriptive text that can be used for screen readers or other situations where the video
cannot be seen.
- returns: An initialized `DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo`.
*/
public init(
responseType: String,
source: String,
title: String? = nil,
description: String? = nil,
channels: [ResponseGenericChannel]? = nil,
channelOptions: [String: JSON]? = nil,
altText: String? = nil
)
{
self.responseType = responseType
self.source = source
self.title = title
self.description = description
self.channels = channels
self.channelOptions = channelOptions
self.altText = altText
}
}
| apache-2.0 | 5d6a8ca98a2a9935b2c145de75e90b97 | 33.901786 | 120 | 0.690714 | 4.808118 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/DAO/DAOAssembly.swift | 1 | 2549 | //
// CreationUploadMapper.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public protocol APIClientDAO: class {
init(dependencies: DAODependencies)
}
public class DAODependencies {
public let requestSender: RequestSender
public init(requestSender: RequestSender) {
self.requestSender = requestSender
}
}
public class DAOAssembly {
private var store: Dictionary<String, AnyObject>
private let dependencies: DAODependencies
init(dependencies: DAODependencies) {
self.dependencies = dependencies
store = Dictionary<String, AnyObject>()
}
public func register(dao: APIClientDAO) {
let identifier = identifierFrom(daoClass: type(of: dao))
store[identifier] = dao
}
public func assembly<T: APIClientDAO>(_ type: T.Type) -> T {
let identifier = identifierFrom(daoClass: type)
if let dao = store[identifier] as? T {
return dao
} else {
assertionFailure("DAO with identifier: \(identifier) was not registered yet.")
return T(dependencies: dependencies)
}
}
public func isDAORegistered<T: APIClientDAO>(_ type: T.Type) -> Bool {
let identifier = identifierFrom(daoClass: type)
return store[identifier] as? T != nil
}
private func identifierFrom(daoClass: AnyClass) -> String {
return String(describing: daoClass)
}
}
| mit | 7f647ed236224d21f88a1674067046a3 | 34.901408 | 90 | 0.702628 | 4.433043 | false | false | false | false |
grehujt/learningSwift | chapter-2-4 Display Image/DemoApp/DemoApp/ViewController.swift | 1 | 827 | //
// ViewController.swift
// DemoApp
//
// Created by kris on 6/5/16.
// Copyright © 2016 kris. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let image = UIImage(named: "pic")
let imageView = UIImageView(image: image)
imageView.frame = self.view.frame
imageView.contentMode = .ScaleAspectFit
imageView.layer.borderWidth = 10
imageView.layer.borderColor = UIColor.grayColor().CGColor
self.view.addSubview(imageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 9ff4d1d5399d5f36618fe44b8bfde17c | 24.030303 | 80 | 0.654964 | 4.666667 | false | false | false | false |
GongChengKuangShi/DYZB | DouYuTV/DouYuTV/Classes/Mains/View/PageTitleView.swift | 1 | 6241 | //
// PageTitleView.swift
// DouYuTV
//
// Created by xiangronghua on 2017/9/4.
// Copyright © 2017年 xiangronghua. All rights reserved.
//
import UIKit
// 定义协议
protocol PageTitleViewDelegate: class {//表示协议只能被类接受
func pageTitleView(titleView: PageTitleView, selectedIndex index: Int)// (selectedIndex:外部参数, index:内部参数)
}
//定义常量
private let kScrollLineH: CGFloat = 2
private let kNormalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor: (CGFloat, CGFloat, CGFloat) = (255, 120, 8)
class PageTitleView: UIView {
var titles: [String]
var currnentIndex: Int = 0
weak var delegate : PageTitleViewDelegate?
//懒加载属性
lazy var titleLabel: [UILabel] = [UILabel]()
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
lazy var scrollViewLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//MARK:- 自定义构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
func setupUI() {
addSubview(scrollView)
scrollView.frame = bounds
// 通过title设置label
setupTitleLabels()
//设置底线和滚动的滑块
setipBottomLineAndScrollViewLine()
}
func setupTitleLabels() {
let labelW: CGFloat = frame.width / CGFloat(titles.count)
let labelH: CGFloat = frame.height - kScrollLineH
let labelY: CGFloat = 0
for (index, title) in titles.enumerated() {
//创建label
let label = UILabel()
// 设置label属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
//将label添加到scrollView上
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabel.append(label)
// 给label设置手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
func setipBottomLineAndScrollViewLine() {
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH: CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//添加scrollviewLine
//获取第一个label
guard let firtLabel = titleLabel.first else {//guard 判断第一个值是否为空
return
}
firtLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
scrollView.addSubview(scrollViewLine)
scrollViewLine.frame = CGRect(x: firtLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firtLabel.frame.width, height: kScrollLineH)
}
}
// MARK: --监听Label的点击事件
extension PageTitleView {
@objc func titleLabelClick(tapGes: UITapGestureRecognizer) {
// 获取当前label的下标值
guard let currentLabel = tapGes.view as? UILabel else {
return
}
// 2、获取之前的Label
let oldLabel = titleLabel[currnentIndex]
//如果是点击同一个Label的话,就不变
if oldLabel.text == currentLabel.text {
return
}
// 切换文字颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//保存最新的Label的下标值
currnentIndex = currentLabel.tag
// 滚动条的位置
let scrollLineX = CGFloat(currentLabel.tag) * scrollViewLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollViewLine.frame.origin.x = scrollLineX
}
//通知代理
delegate?.pageTitleView(titleView: self, selectedIndex: currnentIndex)
}
}
// MARK: - 对外公开接口
extension PageTitleView {
func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndx: Int) {
// 1、取出sourceLabel、targetLabel
let sourceLabel = titleLabel[sourceIndex]
let targetLabel = titleLabel[targetIndx]
//2、处理滑块逻辑
let moveTotelX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotelX * progress
scrollViewLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//3、颜色的渐变
//3.1、取出变化范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
//3.2先变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
//3.2再变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
//4、记录最新的index
currnentIndex = targetIndx
}
}
| mit | 8d1c2dbb579f62d1fc0e5501f6578596 | 31.175824 | 174 | 0.61373 | 4.550117 | false | false | false | false |
fernandocastor/SillyShapes | SillyShapes/GameOverScene.swift | 1 | 2621 | //
// GameOverScene.swift
// SillyShapes
//
// Created by Fernando Castor on 04/02/15.
// Copyright (c) 2015 UFPE. All rights reserved.
//
import SpriteKit
class GameOverScene : SKScene {
let ITEM_SPACE:CGFloat = -50
let BORDER_SPACE:CGFloat = 35
var score:UInt32 = 0
var scores:ScoreKeeper = ScoreKeeper(numScores:10)
init(size:CGSize, playerWon:Bool, playerScore:UInt32, scoreKeeper:ScoreKeeper) {
super.init(size:size)
// let background = SKSpriteNode(imageNamed: "bg")
// background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
// self.addChild(background)
self.scores = scoreKeeper
self.score = playerScore
self.backgroundColor = UIColor.whiteColor()
let scoreLabel:SKLabelNode = SKLabelNode(text: "Score: \(self.score)")
scoreLabel.fontColor = UIColor.blackColor()
scoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.size.height - (CGRectGetMidY(scoreLabel.frame) + BORDER_SPACE)) //CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) + (-ITEM_SPACE))
self.addChild(scoreLabel)
placeTrophyIfHighScore(playerScore)
let gameOverLabel = SKLabelNode(fontNamed: "Avenir-Black")
gameOverLabel.fontSize = 40
gameOverLabel.fontColor = UIColor.blackColor()
gameOverLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
if playerWon {
gameOverLabel.text = "YOU WIN"
}
else {
gameOverLabel.text = "GAME OVER"
}
self.addChild(gameOverLabel)
let playAgainLabel:SKLabelNode = SKLabelNode(text: "Tap to play again.")
playAgainLabel.fontColor = UIColor.redColor()
playAgainLabel.fontSize = 28
playAgainLabel.position = CGPointMake(CGRectGetMidX(self.frame), gameOverLabel.position.y + 1.5*ITEM_SPACE)
self.addChild(playAgainLabel)
let withSoundAction = SKAction.playSoundFileNamed("gameoverSound.aiff", waitForCompletion:false)
self.runAction(withSoundAction)
}
func placeTrophyIfHighScore(score:UInt32) {
if self.scores.isHighScore(score) {
let trophy = SKSpriteNode(imageNamed: "trophy")
trophy.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.size.height - trophy.frame.size.height - BORDER_SPACE)
self.addChild(trophy)
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let newGameScene = GameScene(size: self.size, scoreKeeper:scores)
self.view?.presentScene(newGameScene)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
}
| gpl-3.0 | 3d073cf82017e0acf3ce9f275f4f3174 | 32.602564 | 224 | 0.715757 | 4.007645 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Killboard/zKillboard/LocationPickerSolarSystems.swift | 2 | 1962 | //
// LocationPickerSolarSystems.swift
// Neocom
//
// Created by Artem Shimanski on 4/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
import CoreData
struct LocationPickerSolarSystems: View {
var region: SDEMapRegion
var completion: (NSManagedObject) -> Void
@FetchRequest(sortDescriptors: [])
private var solarSystems: FetchedResults<SDEMapSolarSystem>
init(region: SDEMapRegion, completion: @escaping (NSManagedObject) -> Void) {
self.region = region
self.completion = completion
_solarSystems = FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \SDEMapSolarSystem.solarSystemName, ascending: true)], predicate: (/\SDEMapSolarSystem.constellation?.region == region).predicate(), animation: nil)
}
var body: some View {
List(solarSystems, id: \.objectID) { solarSystem in
Button(action: {self.completion(solarSystem)}) {
SolarSystemCell(solarSystem: solarSystem)
}.buttonStyle(PlainButtonStyle())
}.listStyle(GroupedListStyle())
.navigationBarTitle(region.regionName ?? "")
}
}
struct SolarSystemCell: View {
var solarSystem: SDEMapSolarSystem
var body: some View {
HStack {
Text(String(format: "%.1f", solarSystem.security)).foregroundColor(Color.security(solarSystem.security))
Text(solarSystem.solarSystemName ?? "")
Spacer()
}.frame(minHeight: 30).contentShape(Rectangle())
}
}
#if DEBUG
struct LocationPickerSolarSystems_Previews: PreviewProvider {
static var previews: some View {
let region = try! Storage.testStorage.persistentContainer.viewContext.from(SDEMapRegion.self).first()!
return NavigationView {
LocationPickerSolarSystems(region: region) { _ in }
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | ba29dadf166622dcdddc8794e36664e8 | 32.237288 | 229 | 0.676186 | 4.702638 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Database/Table/ReadingTable.swift | 1 | 676 | //
// ReadingTable.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
final class ReadingTable: Table {
let subjectID = Column(name: "subject_id", type: .int, nullable: false, primaryKey: true)
let index = Column(name: "idx", type: .int, nullable: false, primaryKey: true)
let readingType = Column(name: "type", type: .text)
let reading = Column(name: "reading", type: .text, nullable: false)
let isPrimary = Column(name: "is_primary", type: .int, nullable: false)
let isAcceptedAnswer = Column(name: "is_accepted_answer", type: .int, nullable: false)
init() {
super.init(name: "readings")
}
}
| mit | cf7140d9ef73e9cc4d597471aec34fb9 | 34.526316 | 93 | 0.654815 | 3.515625 | false | false | false | false |
victorwon/SwiftBus | Pod/Classes/TransitAgency.swift | 1 | 3794 | //
// TransitAgency.swift
// SwiftBus
//
// Created by Adam on 2015-08-29.
// Copyright (c) 2017 Adam Boyd. All rights reserved.
//
import Foundation
private let agencyTagEncoderString = "kAgencyTagEncoder"
private let agencyTitleEncoderString = "kAgencyTitleEncoder"
private let agencyShortTitleEncoderString = "kAgencyShortTitleEncoder"
private let agencyRegionEncoderString = "kAgencyRegionEncoder"
private let agencyRoutesEncoderString = "kAgencyRoutesEncoder"
open class TransitAgency: NSObject, NSCoding {
open var agencyTag: String = ""
open var agencyTitle: String = ""
open var agencyShortTitle: String = ""
open var agencyRegion: String = ""
open var agencyRoutes: [String : TransitRoute] = [:] //[routeTag: Route]
//Convenvience
public override init() { }
//User initialization, only need the agencyTag, everything else can be downloaded
public init(agencyTag:String) {
self.agencyTag = agencyTag
}
public init(agencyTag:String, agencyTitle:String, agencyRegion:String) {
self.agencyTag = agencyTag
self.agencyTitle = agencyTitle
self.agencyRegion = agencyRegion
}
/**
Downloads all agency data from provided agencytag
- parameter completion: Code that is called when the data is finished loading
- parameter success: Whether or not the call was successful
- parameter agency: The agency when the data is loaded
*/
open func download(_ completion: ((_ success: Bool, _ agency: TransitAgency) -> Void)?) {
//We need to load the transit agency data
let connectionHandler = SwiftBusConnectionHandler()
//Need to request agency data first because only this call has the region and full name
connectionHandler.requestAllAgencies() { agencies in
//Getting the current agency
if let thisAgency = agencies[self.agencyTag] {
self.agencyTitle = thisAgency.agencyTitle
self.agencyShortTitle = thisAgency.agencyShortTitle
self.agencyRegion = thisAgency.agencyRegion
connectionHandler.requestAllRouteData(self.agencyTag) { (newAgencyRoutes: [String: TransitRoute]) in
self.agencyRoutes = newAgencyRoutes
completion?(true, self)
}
} else {
//This agency doesn't exist
completion?(false, self)
}
}
}
//MARK : NSCoding
required public init(coder aDecoder: NSCoder) {
guard let tag = aDecoder.decodeObject(forKey: agencyTagEncoderString) as? String,
let title = aDecoder.decodeObject(forKey: agencyTitleEncoderString) as? String else {
//Make sure at least the tag and title exist
return
}
self.agencyTag = tag
self.agencyTitle = title
self.agencyShortTitle = aDecoder.decodeObject(forKey: agencyShortTitleEncoderString) as? String ?? ""
self.agencyRegion = aDecoder.decodeObject(forKey: agencyRegionEncoderString) as? String ?? ""
self.agencyRoutes = aDecoder.decodeObject(forKey: agencyRoutesEncoderString) as? [String : TransitRoute] ?? [:]
}
open func encode(with aCoder: NSCoder) {
aCoder.encode(self.agencyTag, forKey: agencyTagEncoderString)
aCoder.encode(self.agencyTitle, forKey: agencyTitleEncoderString)
aCoder.encode(self.agencyShortTitle, forKey: agencyShortTitleEncoderString)
aCoder.encode(self.agencyRegion, forKey: agencyRegionEncoderString)
aCoder.encode(self.agencyRoutes, forKey: agencyRoutesEncoderString)
}
}
| mit | ea1f286bed9c1b796da1623b3fb64985 | 38.936842 | 119 | 0.655245 | 4.766332 | false | false | false | false |
HYT2016/app | test/test/ShareVCViewController.swift | 1 | 3504 | //
// ShareVCViewController.swift
// test
//
// Created by Root HSZ HSU on 2017/8/16.
// Copyright © 2017年 Root HSZ HSU. All rights reserved.
//
import UIKit
import Social
class ShareVCViewController: UIViewController {
@IBOutlet weak var shareTextView: UITextView!
@IBAction func shareBtn(_ sender: Any) {
// Alert
let alert = UIAlertController(title: "Share", message: "Share cougar", preferredStyle: .actionSheet)
// first action
let actionOne = UIAlertAction(title: "Share on Facebook", style: .default) { (action) in
// check if users connect to facebook
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook){
let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
post.setInitialText("")
// 分享專業
post.add(URL(string: "https://sites.google.com/view/cougarbot"))
// post.add(UIImage(named: "details.png"))
self.present(post, animated: true, completion: nil)
}else{
self.showAlert(service: "Facebook")
}
}
// second action
let actionTwo = UIAlertAction(title: "Share on Twitter", style: .default) { (action) in
// check if users connect to facebook
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter){
let post = SLComposeViewController(forServiceType: SLServiceTypeTwitter)!
post.setInitialText("")
post.add(URL(string: "https://sites.google.com/view/cougarbot"))
// post.add(UIImage(named: "details.png"))
self.present(post, animated: true, completion: nil)
}else{
self.showAlert(service: "Twitter")
}
}
let actionThree = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
// Add action to action sheet
alert.addAction(actionOne)
alert.addAction(actionTwo)
alert.addAction(actionThree)
// present Alert
self.present(alert, animated: true, completion: nil)
}
func showAlert(service:String){
let alert = UIAlertController(title: "Error", message: "You are not connected to \(service)", preferredStyle: .alert)
let action = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
configureNoteTextView()
// self.view.backgroundColor = UIColor(patternImage: UIImage(named: "背景 04")!)
// shareTextView.backgroundColor=UIColor(patternImage: UIImage(named: "背景 04")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//將keyboard向下收起
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//
func configureNoteTextView() {
shareTextView.layer.cornerRadius = 8.0
shareTextView.layer.borderColor = UIColor(white: 0.75, alpha: 0.5).cgColor
shareTextView.layer.borderWidth = 1.2
}
}
| mit | 7ddd9bbe32e73da3b6e1b068c83a58a6 | 33.75 | 125 | 0.599424 | 4.760274 | false | false | false | false |
tkremenek/swift | test/ModuleInterface/inlinable-function.swift | 13 | 9003 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule -emit-module-interface-path %t/Test.swiftinterface -module-name Test %s
// RUN: %FileCheck %s --check-prefix FROMSOURCE --check-prefix CHECK < %t/Test.swiftinterface
// RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-module-interface-path %t/TestFromModule.swiftinterface -module-name Test
// RUN: %FileCheck %s --check-prefix FROMMODULE --check-prefix CHECK < %t/TestFromModule.swiftinterface
// FIXME: These shouldn't be different, or we'll get different output from
// WMO and non-WMO builds.
// CHECK-LABEL: public struct Foo : Swift.Hashable {
public struct Foo: Hashable {
// CHECK: public var inlinableGetPublicSet: Swift.Int {
public var inlinableGetPublicSet: Int {
// FROMSOURCE: @inlinable get {
// FROMMODULE: @inlinable get{{$}}
// FROMSOURCE-NEXT: return 3
// FROMSOURCE-NEXT: }
@inlinable
get {
return 3
}
// CHECK-NEXT: set[[NEWVALUE:(\(newValue\))?]]{{$}}
set {
print("I am set to \(newValue)")
}
// CHECK-NEXT: {{^}} }
}
// CHECK: public var noAccessors: Swift.Int{{$}}
public var noAccessors: Int
// CHECK: public var hasDidSet: Swift.Int {
public var hasDidSet: Int {
// CHECK-NEXT: get{{$}}
// CHECK-NEXT: set{{(\(value\))?}}{{$}}
// CHECK-NOT: didSet
didSet {
print("b set to \(hasDidSet)")
}
// CHECK-NEXT: {{^}} }
}
// CHECK: @_transparent public var transparent: Swift.Int {
// FROMMODULE-NEXT: get{{$}}
// FROMSOURCE-NEXT: get {
// FROMSOURCE-NEXT: return 34
// FROMSOURCE-NEXT: }
// CHECK-NEXT: }
@_transparent
public var transparent: Int {
return 34
}
// CHECK: public var transparentSet: Swift.Int {
public var transparentSet: Int {
// CHECK-NEXT: get{{$}}
get {
return 34
}
// FROMMODULE-NEXT: @_transparent set[[NEWVALUE]]{{$}}
// FROMSOURCE-NEXT: @_transparent set[[NEWVALUE]] {
// FROMSOURCE-NOT: #if false
// FROMSOURCE-NOT: print("I should not appear")
// FROMSOURCE-NOT: #else
// FROMSOURCE-NOT: #if false
// FROMSOURCE-NOT: print("I also should not")
// FROMSOURCE-NOT: #else
// FROMSOURCE: print("I am set to \(newValue)")
// FROMSOURCE-NOT: #endif
// FROMSOURCE-NOT: #endif
// FROMSOURCE-NEXT: }
@_transparent
set {
#if false
print("I should not appear")
#else
#if false
print("I also should not")
#else
print("I am set to \(newValue)")
#endif
#endif
}
}
// CHECK: @inlinable public var inlinableProperty: Swift.Int {
@inlinable
public var inlinableProperty: Int {
// FROMMODULE: get{{$}}
// FROMSOURCE: get {
// FROMSOURCE-NEXT: return 32
// FROMSOURCE-NEXT: }
get {
return 32
}
// FROMMODULE: set[[NEWVALUE]]{{$}}
// FROMSOURCE: set[[NEWVALUE]] {
// FROMSOURCE-NOT: #if true
// FROMSOURCE: print("I am set to \(newValue)")
// FROMSOURCE-NOT: #else
// FROMSOURCE-NOT: print("I should not appear")
// FROMSOURCE-NOT #endif
// FROMSOURCE: }
set {
#if true
print("I am set to \(newValue)")
#else
print("I should not appear")
#endif
}
// CHECK-NEXT: }
}
// CHECK: @inlinable public var inlinableReadAndModify: Swift.Int {
@inlinable
public var inlinableReadAndModify: Int {
// FROMMODULE: _read{{$}}
// FROMSOURCE: _read {
// FROMSOURCE-NEXT: yield 0
// FROMSOURCE-NEXT: }
_read {
yield 0
}
// FROMMODULE: _modify{{$}}
// FROMSOURCE: _modify {
// FROMSOURCE-NEXT: var x = 0
// FROMSOURCE-NEXT: yield &x
// FROMSOURCE-NEXT: }
_modify {
var x = 0
yield &x
}
// CHECK-NEXT: }
}
// CHECK: public var inlinableReadNormalModify: Swift.Int {
public var inlinableReadNormalModify: Int {
// FROMMODULE: @inlinable _read{{$}}
// FROMSOURCE: @inlinable _read {
// FROMSOURCE-NEXT: yield 0
// FROMSOURCE-NEXT: }
@inlinable _read {
yield 0
}
// CHECK: _modify{{$}}
// CHECK-NOT: var x = 0
// CHECK-NOT: yield &x
// CHECK-NOT: }
_modify {
var x = 0
yield &x
}
// CHECK-NEXT: }
}
// CHECK: public var normalReadInlinableModify: Swift.Int {
public var normalReadInlinableModify: Int {
// CHECK: _read{{$}}
// CHECK-NOT: yield 0
// CHECK-NOT: }
_read {
yield 0
}
// FROMMODULE: @inlinable _modify{{$}}
// FROMSOURCE: @inlinable _modify {
// FROMSOURCE-NEXT: var x = 0
// FROMSOURCE-NEXT: yield &x
// FROMSOURCE-NEXT: }
@inlinable _modify {
var x = 0
yield &x
}
// CHECK-NEXT: }
}
// CHECK: public var normalReadAndModify: Swift.Int {
public var normalReadAndModify: Int {
// CHECK-NEXT: _read{{$}}
_read { yield 0 }
// CHECK-NEXT: _modify{{$}}
_modify {
var x = 0
yield &x
}
// CHECK-NEXT: }
}
// FROMMODULE: @inlinable public func inlinableMethod(){{$}}
// FROMSOURCE: @inlinable public func inlinableMethod() {
// FROMSOURCE-NOT: #if NO
// FROMSOURCE-NOT: print("Hello, world!")
// FROMSOURCE-NOT: #endif
// FROMSOURCE: print("Goodbye, world!")
// FROMSOURCE-NEXT: }
@inlinable
public func inlinableMethod() {
#if NO
print("Hello, world!")
#endif
print("Goodbye, world!")
}
// FROMMODULE: @_transparent [[ATTRS:(mutating public|public mutating)]] func transparentMethod(){{$}}
// FROMSOURCE: @_transparent [[ATTRS:(mutating public|public mutating)]] func transparentMethod() {
// FROMSOURCE-NEXT: inlinableProperty = 4
// FROMSOURCE-NEXT: }
@_transparent
mutating public func transparentMethod() {
inlinableProperty = 4
}
// CHECK: public func nonInlinableMethod(){{$}}
// CHECK-NOT: print("Not inlinable")
public func nonInlinableMethod() {
print("Not inlinable")
}
// CHECK: public subscript(i: Swift.Int) -> Swift.Int {
// CHECK-NEXT: get{{$}}
// FROMSOURCE-NEXT: @inlinable set[[NEWVALUE]] { print("set") }
// FROMMODULE-NEXT: @inlinable set[[NEWVALUE]]{{$}}
// CHECK-NEXT: }
public subscript(i: Int) -> Int {
get { return 0 }
@inlinable set { print("set") }
}
// CHECK: public subscript(j: Swift.Int, k: Swift.Int) -> Swift.Int {
// FROMMODULE-NEXT: @inlinable get{{$}}
// FROMSOURCE-NEXT: @inlinable get { return 0 }
// CHECK-NEXT: set[[NEWVALUE]]{{$}}
// CHECK-NEXT: }
public subscript(j: Int, k: Int) -> Int {
@inlinable get { return 0 }
set { print("set") }
}
// CHECK: @inlinable public subscript(l: Swift.Int, m: Swift.Int, n: Swift.Int) -> Swift.Int {
// FROMMODULE-NEXT: get{{$}}
// FROMSOURCE-NEXT: get { return 0 }
// FROMMODULE-NEXT: set[[NEWVALUE]]{{$}}
// FROMSOURCE-NEXT: set[[NEWVALUE]] { print("set") }
// CHECK-NEXT: }
@inlinable
public subscript(l: Int, m: Int, n: Int) -> Int {
get { return 0 }
set { print("set") }
}
// FROMMODULE: @inlinable public init(value: Swift.Int){{$}}
// FROMSOURCE: @inlinable public init(value: Swift.Int) {
// FROMSOURCE-NEXT: topLevelUsableFromInline()
// FROMSOURCE-NEXT: noAccessors = value
// FROMSOURCE-NEXT: hasDidSet = value
// FROMSOURCE-NEXT: }
@inlinable public init(value: Int) {
topLevelUsableFromInline()
noAccessors = value
hasDidSet = value
}
// CHECK: public init(){{$}}
// CHECK-NOT: noAccessors = 0
// CHECK-NOT: hasDidSet = 0
public init() {
noAccessors = 0
hasDidSet = 0
}
// CHECK: {{^}}}
}
// CHECK-NOT: private func topLevelPrivate()
private func topLevelPrivate() {
print("Ssshhhhh")
}
// CHECK: internal func topLevelUsableFromInline(){{$}}
@usableFromInline
internal func topLevelUsableFromInline() {
topLevelPrivate()
}
// FROMMODULE: @inlinable public func topLevelInlinable(){{$}}
// FROMSOURCE: @inlinable public func topLevelInlinable() {
// FROMSOURCE-NEXT: topLevelUsableFromInline()
// FROMSOURCE-NEXT: }
@inlinable public func topLevelInlinable() {
topLevelUsableFromInline()
}
// CHECK: public class HasInlinableDeinit {
public class HasInlinableDeinit {
// CHECK: public init(){{$}}
public init() {}
// FROMMODULE: [[OBJC:(@objc )?]]@inlinable deinit{{$}}
// FROMSOURCE: [[OBJC:(@objc )?]]@inlinable deinit {
// FROMSOURCE-NEXT: print("goodbye")
// FROMSOURCE-NEXT: }
@inlinable deinit {
print("goodbye")
}
// CHECK-NEXT: }
}
// CHECK: public class HasStandardDeinit {
public class HasStandardDeinit {
// CHECK: public init(){{$}}
public init() {}
// CHECK: [[OBJC]]deinit{{$}}
deinit {
print("goodbye")
}
// CHECK-NEXT: }
}
// CHECK: public class HasDefaultDeinit {
public class HasDefaultDeinit {
// CHECK: public init(){{$}}
public init() {}
// CHECK: [[OBJC]]deinit{{$}}
// CHECK-NEXT: }
}
| apache-2.0 | 283510aba8b8fa97bf194f6263cd1d75 | 26.199396 | 216 | 0.604021 | 3.814831 | false | false | false | false |
tkremenek/swift | test/IRGen/class_update_callback_with_stub.swift | 5 | 8843 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -I %t %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module-path %t/resilient_class.swiftmodule -enable-library-evolution %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module-path %t/resilient_objc_class.swiftmodule -enable-library-evolution %S/../Inputs/resilient_objc_class.swift
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %t -emit-ir -enable-library-evolution -target %target-next-stable-abi-triple %s > %t/out
// RUN: %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-runtime -DINT=i%target-ptrsize < %t/out
// RUN: %FileCheck %s --check-prefix=NEGATIVE < %t/out
import Foundation
import resilient_class
import resilient_objc_class
// REQUIRES: objc_interop
// REQUIRES: swift_stable_abi
// -- Nominal type descriptor for ResilientSubclass
// the interesting part is the 'extra class flags' field has a value of 1.
// CHECK-LABEL: @"$s31class_update_callback_with_stub17ResilientSubclassCMn" = constant <{
// -- flags
// CHECK-SAME: i32 1644232784,
// -- parent
// CHECK-SAME: @"$s31class_update_callback_with_stubMXM"
// -- name
// CHECK-SAME: @1
// -- access function
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMa"
// -- field descriptor
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMF"
// -- superclass
// CHECK-SAME: @"symbolic{{[^"]*}}15resilient_class22ResilientOutsideParentC"
// -- metadata bounds
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMo"
// -- extra class flags -- has Objective-C resilient class stub
// CHECK-SAME: i32 1,
// -- number of immediate members
// CHECK-SAME: i32 0,
// -- number of fields
// CHECK-SAME: i32 0,
// -- field offset vector offset
// CHECK-SAME: i32 0,
// -- resilient superclass
// CHECK-SAME: @"got.$s15resilient_class22ResilientOutsideParentCMn"
// -- singleton metadata initialization
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMl"
// -- resilient class metadata pattern
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMP"
// -- metadata completion callback
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMr"
// -- method override
// CHECK-SAME: @"got.$s15resilient_class22ResilientOutsideParentCMn"
// CHECK-SAME: @"got.$s15resilient_class22ResilientOutsideParentCACycfCTq"
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCACycfC"
// -- class stub
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMt"
// CHECK-SAME: }>, section "__TEXT,__const", align 4
// -- Symbols for full stubs; the address point is one word in, and defined below
// CHECK-LABEL: @"$s31class_update_callback_with_stub17ResilientSubclassCMt" =
// CHECK-SAME: internal global %objc_full_class_stub {
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: [[INT]] 1,
// CHECK-SAME: %objc_class* (%objc_class*, i8*)* {{.*}}@"$s31class_update_callback_with_stub17ResilientSubclassCMU{{(\.ptrauth)?}}"
// CHECK-SAME: }
// CHECK-LABEL: @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMt" =
// CHECK-SAME: internal global %objc_full_class_stub {
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: [[INT]] 1,
// CHECK-SAME: %objc_class* (%objc_class*, i8*)* {{.*}}@"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMU{{(\.ptrauth)?}}"
// CHECK-SAME: }
// CHECK-LABEL: @"$s31class_update_callback_with_stub27FixedLayoutNSObjectSubclassCMt" =
// CHECK-SAME: internal global %objc_full_class_stub {
// CHECK-SAME: [[INT]] 0,
// CHECK-SAME: [[INT]] 1,
// CHECK-SAME: %objc_class* (%objc_class*, i8*)* {{.*}}@"$s31class_update_callback_with_stub27FixedLayoutNSObjectSubclassCMU{{(\.ptrauth)?}}"
// CHECK-SAME: }
// -- Categories reference the stubs
// CHECK-LABEL: @"_CATEGORY__TtC31class_update_callback_with_stub17ResilientSubclass_$_class_update_callback_with_stub" = internal constant
// CHECK-SAME: @"$s31class_update_callback_with_stub17ResilientSubclassCMs"
// CHECK-LABEL: @"_CATEGORY__TtC31class_update_callback_with_stub25ResilientNSObjectSubclass_$_class_update_callback_with_stub" = internal constant
// CHECK-SAME: @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMs"
// CHECK-LABEL: @"_CATEGORY__TtC31class_update_callback_with_stub27FixedLayoutNSObjectSubclass_$_class_update_callback_with_stub" = internal constant
// CHECK-SAME: @"$s31class_update_callback_with_stub27FixedLayoutNSObjectSubclassCMs"
// -- But not if the entire inheritance chain is in a single module
// CHECK-LABEL: @"_CATEGORY__TtC15resilient_class22ResilientOutsideParent_$_class_update_callback_with_stub" = internal constant
// CHECK-SAME: @"$s15resilient_class22ResilientOutsideParentCN"
// -- Class stubs do not appear in the class list
// NEGATIVE-NOT: @objc_classes =
// -- ... but they do appear in the stub list
// CHECK-LABEL: @objc_class_stubs = internal global
// CHECK-SAME: @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMt"
// CHECK-SAME: , section "__DATA,__objc_stublist,regular,no_dead_strip"
// -- The category list
// CHECK-LABEL: @objc_categories = internal global
// CHECK-SAME: @"_CATEGORY__TtC15resilient_class22ResilientOutsideParent_$_class_update_callback_with_stub"
// CHECK-SAME: , section "__DATA,__objc_catlist,regular,no_dead_strip"
// CHECK-LABEL: @objc_categories_stubs = internal global
// CHECK-SAME: @"_CATEGORY__TtC31class_update_callback_with_stub17ResilientSubclass_$_class_update_callback_with_stub"
// CHECK-SAME: @"_CATEGORY__TtC31class_update_callback_with_stub25ResilientNSObjectSubclass_$_class_update_callback_with_stub"
// CHECK-SAME: @"_CATEGORY__TtC31class_update_callback_with_stub27FixedLayoutNSObjectSubclass_$_class_update_callback_with_stub"
// CHECK-SAME: , section "__DATA,__objc_catlist2,regular,no_dead_strip"
// -- Address point for class stubs
// CHECK: @"$s31class_update_callback_with_stub17ResilientSubclassCMs" = alias %objc_class_stub, bitcast (i8* getelementptr inbounds (i8, i8* bitcast (%objc_full_class_stub* @"$s31class_update_callback_with_stub17ResilientSubclassCMt" to i8*), [[INT]] {{4|8}}) to %objc_class_stub*)
// CHECK: @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMs" = alias %objc_class_stub, bitcast (i8* getelementptr inbounds (i8, i8* bitcast (%objc_full_class_stub* @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMt" to i8*), [[INT]] {{4|8}}) to %objc_class_stub*)
// -- Class symbol for NSObject-derived class points at the class stub
// CHECK: @"OBJC_CLASS_$__TtC31class_update_callback_with_stub25ResilientNSObjectSubclass" = alias %objc_class_stub, {{.*}} @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMt"
// -- Metadata update callbacks referenced from class stubs
// CHECK-LABEL: define internal %objc_class* @"$s31class_update_callback_with_stub17ResilientSubclassCMU"(%objc_class* %0, i8* %1)
// CHECK: entry:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s31class_update_callback_with_stub17ResilientSubclassCMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[CLASS:%.*]] = bitcast %swift.type* [[METADATA]] to %objc_class*
// CHECK-NEXT: ret %objc_class* [[CLASS]]
// CHECK-NEXT: }
// CHECK-LABEL: define internal %objc_class* @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMU"(%objc_class* %0, i8* %1)
// CHECK: entry:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s31class_update_callback_with_stub25ResilientNSObjectSubclassCMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[CLASS:%.*]] = bitcast %swift.type* [[METADATA]] to %objc_class*
// CHECK-NEXT: ret %objc_class* [[CLASS]]
// CHECK-NEXT: }
open class ResilientSubclass : ResilientOutsideParent {}
open class ResilientNSObjectSubclass : ResilientNSObjectOutsideParent {}
// Note: @_fixed_layout on a class only applies to the storage layout and
// not metadata, which remains resilient.
@_fixed_layout
open class FixedLayoutNSObjectSubclass : FixedLayoutNSObjectOutsideParent {}
extension ResilientSubclass {
@objc public func objcMethod() {}
}
extension ResilientNSObjectSubclass {
@objc public func objcMethod() {}
}
extension FixedLayoutNSObjectSubclass {
@objc public func objcMethod() {}
}
extension ResilientOutsideParent {
@objc public func anObjcMethod() {}
}
| apache-2.0 | 3a22e3e199a2d2798d410421d5660271 | 49.531429 | 298 | 0.730974 | 3.48974 | false | false | false | false |
danielgindi/Charts | Source/Charts/Highlight/ChartHighlighter.swift | 2 | 6080 | //
// ChartHighlighter.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 Algorithms
import Foundation
import CoreGraphics
open class ChartHighlighter : NSObject, Highlighter
{
/// instance of the data-provider
@objc open weak var chart: ChartDataProvider?
@objc public init(chart: ChartDataProvider)
{
self.chart = chart
}
open func getHighlight(x: CGFloat, y: CGFloat) -> Highlight?
{
let xVal = Double(getValsForTouch(x: x, y: y).x)
return getHighlight(xValue: xVal, x: x, y: y)
}
/// - Parameters:
/// - x:
/// - Returns: The corresponding x-pos for a given touch-position in pixels.
@objc open func getValsForTouch(x: CGFloat, y: CGFloat) -> CGPoint
{
guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return .zero }
// take any transformer to determine the values
return chart.getTransformer(forAxis: .left).valueForTouchPoint(x: x, y: y)
}
/// - Parameters:
/// - xValue:
/// - x:
/// - y:
/// - Returns: The corresponding ChartHighlight for a given x-value and xy-touch position in pixels.
@objc open func getHighlight(xValue xVal: Double, x: CGFloat, y: CGFloat) -> Highlight?
{
guard let chart = chart else { return nil }
let closestValues = getHighlights(xValue: xVal, x: x, y: y)
guard !closestValues.isEmpty else { return nil }
let leftAxisMinDist = getMinimumDistance(closestValues: closestValues, y: y, axis: .left)
let rightAxisMinDist = getMinimumDistance(closestValues: closestValues, y: y, axis: .right)
let axis: YAxis.AxisDependency = leftAxisMinDist < rightAxisMinDist ? .left : .right
let detail = closestSelectionDetailByPixel(closestValues: closestValues, x: x, y: y, axis: axis, minSelectionDistance: chart.maxHighlightDistance)
return detail
}
/// - Parameters:
/// - xValue: the transformed x-value of the x-touch position
/// - x: touch position
/// - y: touch position
/// - Returns: A list of Highlight objects representing the entries closest to the given xVal.
/// The returned list contains two objects per DataSet (closest rounding up, closest rounding down).
@objc open func getHighlights(xValue: Double, x: CGFloat, y: CGFloat) -> [Highlight]
{
var vals = [Highlight]()
guard let data = self.data else { return vals }
for (i, set) in data.indexed() where set.isHighlightEnabled
{
// extract all y-values from all DataSets at the given x-value.
// some datasets (i.e bubble charts) make sense to have multiple values for an x-value. We'll have to find a way to handle that later on. It's more complicated now when x-indices are floating point.
vals.append(contentsOf: buildHighlights(dataSet: set, dataSetIndex: i, xValue: xValue, rounding: .closest))
}
return vals
}
/// - Returns: An array of `Highlight` objects corresponding to the selected xValue and dataSetIndex.
internal func buildHighlights(
dataSet set: ChartDataSetProtocol,
dataSetIndex: Int,
xValue: Double,
rounding: ChartDataSetRounding) -> [Highlight]
{
guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return [] }
var entries = set.entriesForXValue(xValue)
if entries.isEmpty, let closest = set.entryForXValue(xValue, closestToY: .nan, rounding: rounding)
{
// Try to find closest x-value and take all entries for that x-value
entries = set.entriesForXValue(closest.x)
}
return entries.map { e in
let px = chart.getTransformer(forAxis: set.axisDependency)
.pixelForValues(x: e.x, y: e.y)
return Highlight(x: e.x, y: e.y, xPx: px.x, yPx: px.y, dataSetIndex: dataSetIndex, axis: set.axisDependency)
}
}
// - MARK: - Utilities
/// - Returns: The `ChartHighlight` of the closest value on the x-y cartesian axes
internal func closestSelectionDetailByPixel(
closestValues: [Highlight],
x: CGFloat,
y: CGFloat,
axis: YAxis.AxisDependency?,
minSelectionDistance: CGFloat) -> Highlight?
{
var distance = minSelectionDistance
var closest: Highlight?
for high in closestValues
{
if axis == nil || high.axis == axis
{
let cDistance = getDistance(x1: x, y1: y, x2: high.xPx, y2: high.yPx)
if cDistance < distance
{
closest = high
distance = cDistance
}
}
}
return closest
}
/// - Returns: The minimum distance from a touch-y-value (in pixels) to the closest y-value (in pixels) that is displayed in the chart.
internal func getMinimumDistance(
closestValues: [Highlight],
y: CGFloat,
axis: YAxis.AxisDependency
) -> CGFloat {
var distance = CGFloat.greatestFiniteMagnitude
for high in closestValues where high.axis == axis
{
let tempDistance = abs(getHighlightPos(high: high) - y)
if tempDistance < distance
{
distance = tempDistance
}
}
return distance
}
internal func getHighlightPos(high: Highlight) -> CGFloat
{
return high.yPx
}
internal func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat
{
return hypot(x1 - x2, y1 - y2)
}
internal var data: ChartData?
{
return chart?.data
}
}
| apache-2.0 | 65abdef888c375d0ce312f7cb7da045a | 33.742857 | 210 | 0.60477 | 4.527178 | false | false | false | false |
qualaroo/QualarooSDKiOS | QualarooTests/Filters/PropertyInjectorSpec.swift | 1 | 4132 | //
// PropertyInjectorSpec.swift
// QualarooTests
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class TextConverterSpec: QuickSpec {
override func spec() {
super.spec()
describe("PropertyInjector") {
var injector: PropertyInjector!
var customProperties: CustomProperties!
beforeEach {
customProperties = CustomProperties(["property": "value",
"name": "Jake"])
injector = PropertyInjector(customProperties: customProperties)
}
context("TextConverter") {
it("replaces placeholder with value") {
let text = "Text with ${property}."
let result = injector.convert(text)
expect(result).to(equal("Text with value."))
}
it("replaces two different placeholders with values") {
let text = "${name} with ${property}."
let result = injector.convert(text)
expect(result).to(equal("Jake with value."))
}
it("replaces two same placeholders with values") {
let text = "${name} with ${name}."
let result = injector.convert(text)
expect(result).to(equal("Jake with Jake."))
}
it("removes missing properties") {
let text = "${surname} with ${name}."
let result = injector.convert(text)
expect(result).to(equal(" with Jake."))
}
}
context("FilterProtocol") {
var survey: Survey!
it("passes when survey has no personalized titles and descriptions") {
let questions = [JsonLibrary.question(),
JsonLibrary.question(),
JsonLibrary.question()]
survey = try! SurveyFactory(with: JsonLibrary.survey(questionList: ["en": questions])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beTrue())
}
it("passes when all custom properties used in titles are set") {
let questions = [JsonLibrary.question(title: "Hi ${name}.",
description: "${property}")]
survey = try! SurveyFactory(with: JsonLibrary.survey(questionList: ["en": questions])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beTrue())
}
it("fails when there is property missing in message description") {
let messages = [JsonLibrary.message(description: "Bye ${unknown}.")]
survey = try! SurveyFactory(with: JsonLibrary.survey(messagesList: ["en": messages])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beFalse())
}
it("fails when there is property missing in leadGen description") {
let leadGens = [JsonLibrary.leadGenForm(description: "${unknown}")]
survey = try! SurveyFactory(with: JsonLibrary.survey(leadGenFormList: ["en": leadGens])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beFalse())
}
it("fails when there is property missing in question title") {
let questions = [JsonLibrary.question(title: "Hi ${name} ${surname}.")]
survey = try! SurveyFactory(with: JsonLibrary.survey(questionList: ["en": questions])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beFalse())
}
it("fails when there is property missing in message description") {
let questions = [JsonLibrary.question(title: "Hi Jake.",
description: "${unknown}")]
survey = try! SurveyFactory(with: JsonLibrary.survey(questionList: ["en": questions])).build()
let result = injector.shouldShow(survey: survey)
expect(result).to(beFalse())
}
}
}
}
}
| mit | 660fdf82d25c3db608a6e4b87d36aa3d | 42.494737 | 106 | 0.595111 | 4.6271 | false | false | false | false |
hyperoslo/AsyncWall | Source/Models/Post.swift | 1 | 880 | import Foundation
public protocol PostConvertible {
var wallModel: Post { get }
}
public class Post {
public var id = 0
public var publishDate = NSDate()
public var text = ""
public var liked = false
public var seen = false
public var likeCount = 0
public var seenCount = 0
public var commentCount = 0
public var author: UserConvertible?
public var parent: PostConvertible?
public var attachments = [AttachmentConvertible]()
public var comments = [PostConvertible]()
public init(text: String = "", publishDate: NSDate, author: UserConvertible? = nil,
attachments: [AttachmentConvertible] = []) {
self.text = text
self.publishDate = publishDate
self.author = author
self.attachments = attachments
}
}
// MARK: - PostConvertible
extension Post: PostConvertible {
public var wallModel: Post {
return self
}
}
| mit | 069b3d5555a03ebf0aff046d9dd43363 | 21.564103 | 85 | 0.695455 | 4.378109 | false | false | false | false |
WeMadeCode/ZXPageView | Example/Pods/SwifterSwift/Sources/SwifterSwift/AppKit/NSViewExtensions.swift | 1 | 3571 | //
// NSViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 3/3/17.
// Copyright © 2017 SwifterSwift
//
#if canImport(Cocoa)
import Cocoa
// MARK: - Properties
public extension NSView {
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
@IBInspectable
var borderColor: NSColor? {
get {
guard let color = layer?.borderColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.borderColor = newValue?.cgColor
}
}
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
@IBInspectable
var borderWidth: CGFloat {
get {
return layer?.borderWidth ?? 0
}
set {
wantsLayer = true
layer?.borderWidth = newValue
}
}
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer?.cornerRadius ?? 0
}
set {
wantsLayer = true
layer?.masksToBounds = true
layer?.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
@IBInspectable
var shadowColor: NSColor? {
get {
guard let color = layer?.shadowColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.shadowColor = newValue?.cgColor
}
}
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
@IBInspectable
var shadowOffset: CGSize {
get {
return layer?.shadowOffset ?? CGSize.zero
}
set {
wantsLayer = true
layer?.shadowOffset = newValue
}
}
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
@IBInspectable
var shadowOpacity: Float {
get {
return layer?.shadowOpacity ?? 0
}
set {
wantsLayer = true
layer?.shadowOpacity = newValue
}
}
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer?.shadowRadius ?? 0
}
set {
wantsLayer = true
layer?.shadowRadius = newValue
}
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
}
// MARK: - Methods
extension NSView {
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
func addSubviews(_ subviews: [NSView]) {
subviews.forEach { addSubview($0) }
}
/// SwifterSwift: Remove all subviews in view.
func removeSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
}
#endif
| mit | 6bc72d5563d2fc5329fae0fa60c7e32e | 22.486842 | 79 | 0.546218 | 5.08547 | false | false | false | false |
kevintulod/CascadeKit-iOS | CascadeKit/CascadeKit/Cascade Controller/CascadeController.swift | 1 | 5803 | //
// CascadeController.swift
// CascadeKit
//
// Created by Kevin Tulod on 1/7/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
public class CascadeController: UIViewController {
@IBOutlet weak var leftViewContainer: UIView!
@IBOutlet weak var rightViewContainer: UIView!
@IBOutlet weak var dividerView: CascadeDividerView!
@IBOutlet weak var dividerViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var dividerViewPositionConstraint: NSLayoutConstraint!
internal var controllers = [UINavigationController]()
internal weak var leftController: UINavigationController? {
didSet {
guard let leftController = leftController else {
return
}
addChildViewController(leftController)
leftViewContainer.fill(with: leftController.view)
leftController.rootViewController?.navigationItem.leftBarButtonItem = nil
}
}
internal weak var rightController: UINavigationController? {
didSet {
guard let rightController = rightController else {
return
}
addChildViewController(rightController)
rightViewContainer.fill(with: rightController.view)
if controllers.count > 0 {
rightController.rootViewController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(CascadeController.popLastViewController))
}
}
}
/// Minimum size for left and right views
public var minimumViewSize = CGFloat(250)
/// Duration of cascade animations in seconds
public var animationDuration = TimeInterval(0.25)
// MARK: - Creation
private static let storyboardName = "Cascade"
private static let storyboardIdentifier = "CascadeController"
public static func create() -> CascadeController {
let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle(for: CascadeController.self))
guard let controller = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? CascadeController else {
fatalError("`Cascade` storyboard is missing required reference to `CascadeController`")
}
let _ = controller.view
return controller
}
public override func viewDidLoad() {
super.viewDidLoad()
dividerView.delegate = self
setupStyling()
}
public override func addChildViewController(_ childController: UIViewController) {
super.addChildViewController(childController)
}
/// Sets up the cascade controller with the initial view controllers
public func setup(first: UINavigationController, second: UINavigationController) {
leftController = first
rightController = second
}
/// Cascades the view controller to the top of the stack
public func cascade(viewController cascadeController: UINavigationController, sender: UINavigationController? = nil) {
if sender === leftController {
// If the provided sender is the second-to-last in the stack, replace the last controller
popLastController()
addControllerToStack(cascadeController)
rightController = cascadeController
} else {
// All other cases, push the controller to the end
animate(withForwardCascadeController: cascadeController, preAnimation: { Void in
self.addControllerToStack(self.leftController)
self.leftController = self.rightController
}, postAnimation: { Void in
self.rightController = cascadeController
}, completion: nil)
}
}
/// Pops the last controller off the top of the stack
public func popLastViewController() {
guard let poppedController = popLastController() else {
NSLog("No controller in stack to pop.")
return
}
let newRightController = self.leftController
let dismissingController = self.rightController
animate(withBackwardCascadeController: poppedController, preAnimation: { Void in
self.rightController = newRightController
}, postAnimation: { Void in
self.leftController = poppedController
}, completion: { Void in
dismissingController?.view.removeFromSuperview()
dismissingController?.removeFromParentViewController()
})
}
internal func addControllerToStack(_ controller: UINavigationController?) {
if let controller = controller {
controllers.append(controller)
}
}
@discardableResult internal func popLastController() -> UINavigationController? {
return controllers.popLast()
}
}
extension CascadeController: CascadeDividerDelegate {
func divider(_ divider: CascadeDividerView, shouldTranslateToCenter center: CGPoint) -> Bool {
// Only allow the divider to translate if the minimum view sizes are met on the left and right
return center.x >= minimumViewSize && center.x <= view.frame.width-minimumViewSize
}
func divider(_ divider: CascadeDividerView, didTranslateToCenter center: CGPoint) {
dividerViewPositionConstraint.constant = center.x
}
}
// MARK: - Styling
extension CascadeController {
func setupStyling() {
leftViewContainer.backgroundColor = .white
rightViewContainer.backgroundColor = .white
dividerViewWidthConstraint.constant = UIScreen.main.onePx
}
}
| mit | 0423828a4b8a253609d1b5c77a9bc399 | 35.2625 | 207 | 0.660634 | 5.790419 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Sources/AppFeature/NetworkConnectionObserver.swift | 1 | 1179 | import ComposableArchitecture
import Foundation
import Logger
import PathMonitorClient
import SharedDependencies
public struct NetworkConnectionObserver: ReducerProtocol {
public init() {}
@Dependency(\.pathMonitorClient) public var pathMonitorClient
public struct State: Equatable {
var isNetworkAvailable = true
}
public enum Action: Equatable {
case observeConnection
case observeConnectionResponse(NetworkPath)
}
public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> {
switch action {
case .observeConnection:
return .run { send in
for await path in await pathMonitorClient.networkPathPublisher() {
await send(.observeConnectionResponse(path))
}
}
.cancellable(id: ObserveConnectionIdentifier())
case let .observeConnectionResponse(networkPath):
state.isNetworkAvailable = networkPath.status == .satisfied
SharedDependencies._isNetworkAvailable = state.isNetworkAvailable
logger.info("Is network available: \(state.isNetworkAvailable)")
return .none
}
}
}
struct ObserveConnectionIdentifier: Hashable {}
| mit | 869c24c6c1f6c4391257f2a1ef212e71 | 27.756098 | 88 | 0.724343 | 5.103896 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Helpers/StatsPeriodHelper.swift | 2 | 9453 | import Foundation
class StatsPeriodHelper {
private lazy var calendar: Calendar = {
var cal = Calendar(identifier: .iso8601)
cal.timeZone = .autoupdatingCurrent
return cal
}()
func dateAvailableBeforeDate(_ dateIn: Date, period: StatsPeriodUnit, backLimit: Int, mostRecentDate: Date? = nil) -> Bool {
// Use dates without time
let currentDate = mostRecentDate?.normalizedDate() ?? StatsDataHelper.currentDateForSite().normalizedForSite()
guard var oldestDate = calendar.date(byAdding: period.calendarComponent, value: backLimit, to: currentDate) else {
return false
}
let date = dateIn.normalizedDate()
oldestDate = oldestDate.normalizedDate()
switch period {
case .day:
return date > oldestDate
case .week:
let week = weekIncludingDate(date)
guard let weekStart = week?.weekStart,
let oldestWeekStart = weekIncludingDate(oldestDate)?.weekStart else {
return false
}
return weekStart > oldestWeekStart
case .month:
guard let month = monthFromDate(date),
let oldestMonth = monthFromDate(oldestDate) else {
return false
}
return month > oldestMonth
case .year:
let year = yearFromDate(date)
return year > yearFromDate(oldestDate)
}
}
func dateAvailableAfterDate(_ dateIn: Date, period: StatsPeriodUnit, mostRecentDate: Date? = nil) -> Bool {
// Use dates without time
let currentDate = mostRecentDate?.normalizedDate() ?? StatsDataHelper.currentDateForSite().normalizedForSite()
let date = dateIn.normalizedDate()
switch period {
case .day:
return date < currentDate.normalizedDate()
case .week:
let week = weekIncludingDate(date)
guard let weekEnd = week?.weekEnd,
let currentWeekEnd = weekIncludingDate(currentDate)?.weekEnd else {
return false
}
return weekEnd < currentWeekEnd
case .month:
guard let month = monthFromDate(date),
let currentMonth = monthFromDate(currentDate) else {
return false
}
return month < currentMonth
case .year:
let year = yearFromDate(date)
return year < yearFromDate(currentDate)
}
}
func endDate(from intervalStartDate: Date, period: StatsPeriodUnit, offsetBy count: Int = 1) -> Date {
switch period {
case .day:
return intervalStartDate.normalizedDate()
case .week:
guard let week = weekIncludingDate(intervalStartDate) else {
DDLogError("[Stats] Couldn't determine the right week. Returning original value.")
return intervalStartDate.normalizedDate()
}
return week.weekEnd.normalizedDate()
case .month:
guard let endDate = intervalStartDate.lastDayOfTheMonth(in: calendar) else {
DDLogError("[Stats] Couldn't determine number of days in a given month in Stats. Returning original value.")
return intervalStartDate.normalizedDate()
}
return endDate.normalizedDate()
case .year:
guard let endDate = intervalStartDate.lastDayOfTheYear(in: calendar) else {
DDLogError("[Stats] Couldn't determine number of months in a given year, or days in a given monthin Stats. Returning original value.")
return intervalStartDate.normalizedDate()
}
return endDate.normalizedDate()
}
}
func calculateEndDate(from currentDate: Date, offsetBy count: Int = 1, unit: StatsPeriodUnit) -> Date? {
let calendar = Calendar.autoupdatingCurrent
guard let adjustedDate = calendar.date(byAdding: unit.calendarComponent, value: count, to: currentDate) else {
DDLogError("[Stats] Couldn't do basic math on Calendars in Stats. Returning original value.")
return currentDate
}
switch unit {
case .day:
return adjustedDate.normalizedDate()
case .week:
// The hours component here is because the `dateInterval` returned by Calendar is a closed range
// — so the "end" of a specific week is also simultenously a 'start' of the next one.
// This causes problem when calling this math on dates that _already are_ an end/start of a week.
// This doesn't work for our calculations, so we force it to rollover using this hack.
// (I *think* that's what's happening here. Doing Calendar math on this method has broken my brain.
// I spend like 10h on this ~50 LoC method. Beware.)
let components = DateComponents(day: 7 * count, hour: -12)
guard let weekAdjusted = calendar.date(byAdding: components, to: currentDate.normalizedDate()) else {
DDLogError("[Stats] Couldn't add a multiple of 7 days and -12 hours to a date in Stats. Returning original value.")
return currentDate
}
return calendar.dateInterval(of: .weekOfYear, for: weekAdjusted)?.end.normalizedDate()
case .month:
guard let endDate = adjustedDate.lastDayOfTheMonth(in: calendar) else {
DDLogError("[Stats] Couldn't determine number of days in a given month in Stats. Returning original value.")
return currentDate
}
return endDate.normalizedDate()
case .year:
guard let endDate = adjustedDate.lastDayOfTheYear(in: calendar) else {
DDLogError("[Stats] Couldn't determine number of months in a given year, or days in a given monthin Stats. Returning original value.")
return currentDate
}
return endDate.normalizedDate()
}
}
// MARK: - Date Helpers
func weekIncludingDate(_ date: Date) -> (weekStart: Date, weekEnd: Date)? {
// Note: Week is Monday - Sunday
guard let weekStart = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date)),
let weekEnd = calendar.date(byAdding: .day, value: 6, to: weekStart) else {
return nil
}
return (weekStart, weekEnd)
}
func monthFromDate(_ date: Date) -> Date? {
let dateComponents = calendar.dateComponents([.month, .year], from: date)
return calendar.date(from: dateComponents)
}
func yearFromDate(_ date: Date) -> Int {
return calendar.component(.year, from: date)
}
}
private extension Date {
func adjusted(for period: StatsPeriodUnit, in calendar: Calendar, value: Int) -> Date {
guard let adjustedDate = calendar.date(byAdding: period.calendarComponent, value: value, to: self) else {
DDLogError("[Stats] Couldn't do basic math on Calendars in Stats. Returning original value.")
return self
}
return adjustedDate
}
func lastDayOfTheWeek(in calendar: Calendar, with offset: Int) -> Date? {
// The hours component here is because the `dateInterval` returnd by Calendar is a closed range
// — so the "end" of a specific week is also simultenously a 'start' of the next one.
// This causes problem when calling this math on dates that _already are_ an end/start of a week.
// This doesn't work for our calculations, so we force it to rollover using this hack.
// (I *think* that's what's happening here. Doing Calendar math on this method has broken my brain.
// I spend like 10h on this ~50 LoC method. Beware.)
let components = DateComponents(day: 7 * offset, hour: -12)
guard let weekAdjusted = calendar.date(byAdding: components, to: normalizedDate()),
let endOfAdjustedWeek = calendar.dateInterval(of: .weekOfYear, for: weekAdjusted)?.end else {
DDLogError("[Stats] Couldn't add a multiple of 7 days and -12 hours to a date in Stats. Returning original value.")
return nil
}
return endOfAdjustedWeek
}
func lastDayOfTheMonth(in calendar: Calendar) -> Date? {
guard let maxComponent = calendar.range(of: .day, in: .month, for: self)?.max() else {
DDLogError("[Stats] Couldn't determine number of days in a given month in Stats. Returning original value.")
return nil
}
return calendar.date(bySetting: .day, value: maxComponent, of: self)?.normalizedDate()
}
func lastDayOfTheYear(in calendar: Calendar) -> Date? {
guard
let maxMonth = calendar.range(of: .month, in: .year, for: self)?.max(),
let adjustedMonthDate = calendar.date(bySetting: .month, value: maxMonth, of: self),
let maxDay = calendar.range(of: .day, in: .month, for: adjustedMonthDate)?.max() else {
DDLogError("[Stats] Couldn't determine number of months in a given year, or days in a given monthin Stats. Returning original value.")
return nil
}
let adjustedDayDate = calendar.date(bySetting: .day, value: maxDay, of: adjustedMonthDate)
return adjustedDayDate?.normalizedDate()
}
}
| gpl-2.0 | e7472784fe7486ff485838bbb7529a43 | 44.647343 | 150 | 0.62377 | 4.833248 | false | false | false | false |
calleerlandsson/Tofu | Tofu/Data.swift | 1 | 2766 | import Foundation
private enum DecodedByte {
case valid(UInt8)
case invalid
case padding
}
private let padding: UInt8 = 61 // =
private let byteMappings: [CountableRange<UInt8>] = [
65 ..< 91, // A-Z
50 ..< 56, // 2-7
]
private func decode(byte encodedByte: UInt8) -> DecodedByte {
if encodedByte == padding { return .padding }
var decodedStart: UInt8 = 0
for range in byteMappings {
if range.contains(encodedByte) {
let result = decodedStart + (encodedByte - range.lowerBound)
return .valid(result)
}
decodedStart += range.upperBound - range.lowerBound
}
return .invalid
}
private func decoded(bytes encodedBytes: [UInt8]) -> [UInt8]? {
var decodedBytes = [UInt8]()
decodedBytes.reserveCapacity(encodedBytes.count / 8 * 5)
var decodedByte: UInt8 = 0
var characterCount = 0
var paddingCount = 0
var index = 0
for encodedByte in encodedBytes {
let value: UInt8
switch decode(byte: encodedByte) {
case .valid(let v):
value = v
characterCount += 1
case .invalid:
return nil
case .padding:
paddingCount += 1
continue
}
// Only allow padding at the end of the sequence
if paddingCount > 0 { return nil }
switch index % 8 {
case 0:
decodedByte = value << 3
case 1:
decodedByte |= value >> 2
decodedBytes.append(decodedByte)
decodedByte = value << 6
case 2:
decodedByte |= value << 1
case 3:
decodedByte |= value >> 4
decodedBytes.append(decodedByte)
decodedByte = value << 4
case 4:
decodedByte |= value >> 1
decodedBytes.append(decodedByte)
decodedByte = value << 7
case 5:
decodedByte |= value << 2
case 6:
decodedByte |= value >> 3
decodedBytes.append(decodedByte)
decodedByte = value << 5
case 7:
decodedByte |= value
decodedBytes.append(decodedByte)
default:
fatalError()
}
index += 1
}
let characterCountIsValid = [0, 2, 4, 5, 7].contains(characterCount % 8)
let paddingCountIsValid = paddingCount == 0 || (characterCount + paddingCount) % 8 == 0
guard characterCountIsValid && paddingCountIsValid else { return nil }
return decodedBytes
}
extension Data {
init?(base32Encoded string: String) {
let encodedBytes = Array(string.uppercased().utf8)
guard let decodedBytes = decoded(bytes: encodedBytes) else { return nil }
self.init(decodedBytes)
}
}
| isc | f22e6b174102e78ca68e4e0f1fd47ceb | 26.386139 | 91 | 0.571945 | 4.571901 | false | false | false | false |
rudedogg/TiledSpriteKit | Sources/SKTilemapTileData.swift | 1 | 4299 | /*
SKTilemap
SKTilemapTileData.swift
Created by Thomas Linthwaite on 07/04/2016.
GitHub: https://github.com/TomLinthwaite/SKTilemap
Website (Guide): http://tomlinthwaite.com/
Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki
YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw
Twitter: https://twitter.com/Mr_Tomoso
-----------------------------------------------------------------------------------------------------------------------
MIT License
Copyright (c) 2016 Tom Linthwaite
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 SpriteKit
// MARK: SKTileData
public class SKTilemapTileData : Equatable, Hashable {
// MARK: Properties
public var hashValue: Int { get { return self.id.hashValue } }
/** Properties shared by all TMX object types. */
var properties: [String : String] = [:]
/** The tile datas ID. */
let id: Int
/** Returns the Tile ID you would see in Tiled. */
var rawID: Int { get { return self.id - self.tileset.firstGID } }
/** Weak pointer to the tileset this data belongs to. */
weak var tileset: SKTilemapTileset!
/** The texture used to draw tiles with this data. */
let texture: SKTexture
/** The filename of the texture used for this data. If it is empty the tileset used a spritesheet to create the
the texture for this data. */
let source: String
/** The tile IDs and durations used for animating this tile. */
var animationFrames: [(id: Int, duration: CGFloat)] = []
// MARK: Initialization
init(id: Int, texture: SKTexture, source: String = "", tileset: SKTilemapTileset) {
self.id = id
self.tileset = tileset
self.source = source
self.texture = texture
texture.filteringMode = .nearest
}
init(id: Int, imageNamed source: String, tileset: SKTilemapTileset) {
self.id = id
self.tileset = tileset
self.source = source
texture = SKTexture(imageNamed: source)
texture.filteringMode = .nearest
}
// MARK: Debug
func printDebugDescription() {
print("TileData: \(id), Source: \(source), Properties: \(properties)")
}
// MARK: Animation
/** Returns the animation for this tileData if it has one. The animation is created from the animationFrames property. */
func getAnimation(_ tilemap: SKTilemap) -> SKAction? {
if animationFrames.isEmpty {
return nil
}
var frames: [SKAction] = []
for frameData in animationFrames {
if let texture = tilemap.getTileData(id: frameData.id)?.texture {
let textureAction = SKAction.setTexture(texture)
let delayAction = SKAction.wait(forDuration: TimeInterval(frameData.duration / 1000))
frames.append(SKAction.group([textureAction, delayAction]))
}
}
return SKAction.sequence(frames)
}
}
public func ==(lhs: SKTilemapTileData, rhs: SKTilemapTileData) -> Bool {
return (lhs.hashValue == rhs.hashValue)
}
| mit | 97e402fac1013e18eb7fd44875a379b8 | 35.432203 | 125 | 0.629681 | 4.592949 | false | false | false | false |
denmanboy/IQKeyboardManager | IQKeybordManagerSwift/Categories/IQUIWindow+Hierarchy.swift | 19 | 2246 | //
// IQUIWindow+Hierarchy.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/** @abstract UIWindow hierarchy category. */
extension UIWindow {
/** @return Returns the current Top Most ViewController in hierarchy. */
override func topMostController()->UIViewController? {
var topController = rootViewController
while let presentedController = topController?.presentedViewController {
topController = presentedController
}
return topController
}
/** @return Returns the topViewController in stack of topMostController. */
func currentViewController()->UIViewController? {
var currentViewController = topMostController()
while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil {
currentViewController = (currentViewController as! UINavigationController).topViewController
}
return currentViewController
}
}
| mit | 57b612169387f80088e3cb02d0cc4c21 | 40.592593 | 174 | 0.729742 | 5.615 | false | false | false | false |
zom/Zom-iOS | Zom/Zom/Classes/View Controllers/ZomStickerPackTableViewController.swift | 1 | 4158 | //
// ZomStickerPackListViewController.swift
// Zom
//
// Created by N-Pex on 2015-11-12.
//
//
import UIKit
import ChatSecureCore
import Photos
open class ZomStickerPackTableViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
private var stickerPacks: Array<String> = [];
private(set) lazy var orderedViewControllers: [UIViewController] = []
open override func viewDidLoad() {
super.viewDidLoad()
let docsPath = Bundle.main.resourcePath! + "/Stickers"
let fileManager = FileManager.default
do {
// Sticker packs are sorted by a three character prefix of the file folders, like 00 losar
stickerPacks = try fileManager.contentsOfDirectory(atPath: docsPath).sorted { (s1, s2) -> Bool in
return s1.compare(s2) != .orderedDescending
}
} catch {
print(error)
}
// Create view controllers
for stickerPack in stickerPacks {
let vc:ZomPickStickerViewController = self.storyboard?.instantiateViewController(withIdentifier: "pickStickerViewController") as! ZomPickStickerViewController
vc.stickerPackFileName = stickerPack
// Remove prefix
vc.stickerPack = String(stickerPack[stickerPack.index(stickerPack.startIndex, offsetBy: 3)...])
orderedViewControllers.append(vc)
}
dataSource = self
delegate = self
if let firstViewController:ZomPickStickerViewController = orderedViewControllers.first as? ZomPickStickerViewController {
self.navigationItem.title = firstViewController.stickerPack
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
open func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
open func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
open func presentationCount(for pageViewController: UIPageViewController) -> Int {
return orderedViewControllers.count
}
open func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = orderedViewControllers.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
open func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let vc:ZomPickStickerViewController = pageViewController.viewControllers?[0] as? ZomPickStickerViewController {
self.navigationItem.title = vc.stickerPack
}
}
}
| mpl-2.0 | 0d3c5707f5150a713f6a759092024260 | 37.146789 | 195 | 0.647667 | 6.6528 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/Courses/CertificatesListViewController.swift | 1 | 7022 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import SafariServices
import UIKit
class CertificatesListViewController: UICollectionViewController {
var course: Course!
var certificates: [Course.Certificate] = [] {
didSet {
self.collectionView?.reloadData()
}
}
weak var scrollDelegate: CourseAreaScrollDelegate?
override func viewDidLoad() {
self.collectionView?.register(R.nib.certificateCell)
super.viewDidLoad()
self.certificates = self.course.availableCertificates
self.addRefreshControl()
self.refresh()
self.setupEmptyState()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.collectionView.performBatchUpdates(nil)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.scrollDelegate?.scrollViewDidScroll(scrollView)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.scrollDelegate?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.scrollDelegate?.scrollViewDidEndDecelerating(scrollView)
}
func stateOfCertificate(withURL certificateURL: URL?) -> String {
guard self.course.enrollment != nil else {
return NSLocalizedString("course.certificates.not-enrolled", comment: "the current state of a certificate")
}
guard certificateURL != nil else {
return NSLocalizedString("course.certificates.not-achieved", comment: "the current state of a certificate")
}
return NSLocalizedString("course.certificates.achieved", comment: "the current state of a certificate")
}
}
extension CertificatesListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInsets = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
let boundingWidth = collectionView.bounds.width - sectionInsets.left - sectionInsets.right
let minimalCardWidth = CertificateCell.minimalWidth(for: self.traitCollection)
let numberOfColumns = max(1, floor(boundingWidth / minimalCardWidth))
let columnWidth = boundingWidth / numberOfColumns
let certificate = self.certificates[indexPath.item]
let height = CertificateCell.height(for: certificate, forWidth: columnWidth, delegate: self)
return CGSize(width: columnWidth, height: height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
let leftPadding = collectionView.layoutMargins.left - CertificateCell.cardInset - collectionView.safeAreaInsets.left
let rightPadding = collectionView.layoutMargins.right - CertificateCell.cardInset - collectionView.safeAreaInsets.right
return UIEdgeInsets(top: 0, left: leftPadding, bottom: collectionView.layoutMargins.bottom, right: rightPadding)
}
}
extension CertificatesListViewController { // CollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.certificates.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellReuseIdentifier = R.reuseIdentifier.certificateCell.identifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath)
let certificate = self.certificates[indexPath.item]
let stateOfCertificate = self.stateOfCertificate(withURL: certificate.url)
if let cell = cell as? CertificateCell {
cell.configure(certificate.name, explanation: certificate.explanation, url: certificate.url, stateOfCertificate: stateOfCertificate)
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let certificate = self.certificates[indexPath.item]
guard let url = certificate.url else { return }
let pdfViewController = R.storyboard.pdfWebViewController.instantiateInitialViewController().require()
let filename = [self.course.title, certificate.name].compactMap { $0 }.joined(separator: " - ")
pdfViewController.configure(for: url, filename: filename)
self.show(pdfViewController, sender: self)
}
}
extension CertificatesListViewController: RefreshableViewController {
func refreshingAction() -> Future<Void, XikoloError> {
return CourseHelper.syncCourse(self.course).onSuccess { _ in
self.certificates = self.course.availableCertificates
}.asVoid()
}
}
extension CertificatesListViewController: EmptyStateDataSource, EmptyStateDelegate {
var emptyStateTitleText: String {
return NSLocalizedString("empty-view.certificates.no-certificates.title", comment: "title for empty certificates list")
}
func didTapOnEmptyStateView() {
self.refresh()
}
func setupEmptyState() {
self.collectionView?.emptyStateDataSource = self
self.collectionView?.emptyStateDelegate = self
}
}
extension CertificatesListViewController: CertificateCellDelegate {
func maximalHeightForTitle(withWidth width: CGFloat) -> CGFloat {
return self.certificates.map { certificate -> CGFloat in
return CertificateCell.heightForTitle(certificate.name, withWidth: width)
}.max() ?? 0
}
func maximalHeightForStatus(withWidth width: CGFloat) -> CGFloat {
return self.certificates.map { certificate -> CGFloat in
let statusText = self.stateOfCertificate(withURL: certificate.url)
return CertificateCell.heightForStatus(statusText, withWidth: width)
}.max() ?? 0
}
}
extension CertificatesListViewController: CourseAreaViewController {
var area: CourseArea {
return .certificates
}
func configure(for course: Course, with area: CourseArea, delegate: CourseAreaViewControllerDelegate) {
assert(area == self.area)
self.course = course
self.scrollDelegate = delegate
}
}
| gpl-3.0 | cc0627c2e1eafcf409d51208b4e105a7 | 37.36612 | 160 | 0.721122 | 5.657534 | false | false | false | false |
jinseokpark6/u-team | Code/Controllers/CVCalendarDayViewControlCoordinator.swift | 1 | 2632 | //
// CVCalendarDayViewControlCoordinator.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/27/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVCalendarDayViewControlCoordinator {
// MARK: - Non public properties
private var selectionSet = Set<DayView>()
private unowned let calendarView: CalendarView
// MARK: - Public properties
weak var selectedDayView: CVCalendarDayView?
var animator: CVCalendarViewAnimator! {
get {
return calendarView.animator
}
}
// MARK: - initialization
init(calendarView: CalendarView) {
self.calendarView = calendarView
}
}
// MARK: - Animator side callback
extension CVCalendarDayViewControlCoordinator {
func selectionPerformedOnDayView(dayView: DayView) {
// TODO:
}
func deselectionPerformedOnDayView(dayView: DayView) {
if dayView != selectedDayView {
selectionSet.remove(dayView)
dayView.setDayLabelDeselectedDismissingState(true)
}
}
func dequeueDayView(dayView: DayView) {
selectionSet.remove(dayView)
}
func flush() {
selectionSet.removeAll()
}
}
// MARK: - Animator reference
private extension CVCalendarDayViewControlCoordinator {
func presentSelectionOnDayView(dayView: DayView) {
animator.animateSelectionOnDayView(dayView)
//animator?.animateSelection(dayView, withControlCoordinator: self)
}
func presentDeselectionOnDayView(dayView: DayView) {
animator.animateDeselectionOnDayView(dayView)
//animator?.animateDeselection(dayView, withControlCoordinator: self)
}
}
// MARK: - Coordinator's control actions
extension CVCalendarDayViewControlCoordinator {
func performDayViewSingleSelection(dayView: DayView) {
selectionSet.insert(dayView)
if selectionSet.count > 1 {
let count = selectionSet.count-1
for dayViewInQueue in selectionSet {
if dayView != dayViewInQueue {
if dayView.calendarView != nil {
presentDeselectionOnDayView(dayViewInQueue)
}
}
}
}
if let animator = animator {
if selectedDayView != dayView {
selectedDayView = dayView
presentSelectionOnDayView(dayView)
}
}
}
func performDayViewRangeSelection(dayView: DayView) {
print("Day view range selection found")
}
} | apache-2.0 | f9dbd8480ec1325ba281e03210f73a37 | 26.14433 | 77 | 0.62728 | 5.317172 | false | false | false | false |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Views/ZXCTextView.swift | 1 | 2361 | //
// ZXCTextView.swift
// WeiBo
//
// Created by Aioria on 2017/4/5.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
class ZXCTextView: UITextView {
private lazy var labPlaceHolder: UILabel = {
let lab = UILabel()
lab.text = "111"
lab.numberOfLines = 0
lab.textColor = UIColor.lightGray
lab.font = UIFont.systemFont(ofSize: 14)
return lab
}()
var placeHolder: String? {
didSet {
labPlaceHolder.text = placeHolder
}
}
override var font: UIFont? {
didSet {
if font != nil {
labPlaceHolder.font = font
}
}
}
override var text: String? {
didSet {
labPlaceHolder.isHidden = hasText
}
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupUI() {
NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: Notification.Name.UITextViewTextDidChange, object: nil)
addSubview(labPlaceHolder)
labPlaceHolder.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: labPlaceHolder, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: labPlaceHolder, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: labPlaceHolder, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -8))
}
@objc private func textChange() {
labPlaceHolder.isHidden = hasText
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | e33ae41eb27cd4827447c3749566d620 | 22.58 | 163 | 0.54665 | 5.359091 | false | false | false | false |
borchero/WebParsing | WebParsing/WPEncoder.swift | 1 | 4250 | // MIT License
//
// Copyright (c) 2017 Oliver Borchert ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// The `WPEnocoder` protocol is adapted by all coders that encode
/// `WPCodable` objects as portable web formats like JSON and XML.
public protocol WPEncoder {
/// Encodes a `WPEncodable` object for no key.
///
/// - Parameter value: The `WPEncodable` object to encode.
func encode<T: WPEncodable>(_ value: T) throws
/// Encodes a `WPEncodable` object for a specified key.
///
/// - parameter value: The `WPEncodable` object to encode.
/// - parameter key: The key to encode the object for. In JSON
/// for example it is used as the key for values
/// of an object. The adopting class might
/// however decide how to use the key. In a
/// single class, the keys need to be distinct.
/// Otherwise, only the last value for the
/// specified key is encoded.
func encode<T: WPEncodable>(_ value: T, for key: String) throws
}
public protocol WPTypedEncoder: WPEncoder {
associatedtype Element: WPElement
static func encode<T: WPEncodable>(_ object: T) throws -> Element
}
/// This class is used to encode `WPCodable` objects as Json.
/// When attributes are tried to encode, the class simply does
/// nothing as Json doesn't support element attributes.
public class WPJsonEncoder: WPTypedEncoder {
internal var json: WPJson
internal init(json: WPJson) {
self.json = json
}
public static func encodeToDictionary<T: WPEncodable>(_ object: T) throws -> [String: Any] {
return try encode(object).anyDictionary()
}
/// Encodes a `WPCodable` object as JSON.
///
/// - parameter object: The object to encode.
///
/// - returns: The JSON value.
public static func encode<T: WPEncodable>(_ object: T) throws -> WPJson {
let encoder = WPJsonEncoder(json: WPJson())
try encoder.encode(object)
return encoder.json
}
public func unsafeEncode<T>(_ value: T) throws {
let encoder = WPJsonEncoder(json: WPJson())
do {
try (value as! WPEncodable).encode(to: encoder)
} catch WPInternalError.optionalNone {
return
} catch let error {
throw error
}
self.json = encoder.json
}
public func encode<T: WPEncodable>(_ value: T) throws {
let encoder = WPJsonEncoder(json: WPJson())
do {
try value.encode(to: encoder)
} catch WPInternalError.optionalNone {
return
} catch let error {
throw error
}
self.json = encoder.json
}
public func encode<T: WPEncodable>(_ value: T, for key: String) throws {
let encoder = WPJsonEncoder(json: WPJson())
do {
try value.encode(to: encoder)
} catch WPInternalError.optionalNone {
return
} catch let error {
throw error
}
self.json[key] = encoder.json
}
}
| mit | 6d59a8b93ea74ef160451696388d4f2c | 35.324786 | 96 | 0.633176 | 4.454927 | false | false | false | false |
AudioY/iOSTutorialOverlay | iOSTutorialOverlay/ViewController.swift | 1 | 4134 | //
// ViewController.swift
// iOSTutorialOverlay
//
// Created by Jonathan Neumann on 20/02/2015.
// Copyright (c) 2015 Audio Y. All rights reserved.
// www.audioy.co
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = ColourConstants.brightTurquoise
let screen1 = JNTutorialOverlay(overlayName: "Screen1", width: 300, opacity: 0.8, title: "Screen 1", message: "This is the default overlay.\n The default overlay comes with a dark theme, rounded corners and is centered, but you can change that.")
screen1.showWithBlock(){ hidden in
println("Screen 1 has been hidden")
let screen2 = JNTutorialOverlay(overlayName: "Screen2", frame: CGRectMake(0, 100, ScreenConstants.width - 100, 200), opacity: 0.6, title: "Screen 2", message: "This one for example does not have a centered frame, and the opacity is less.")
screen2.showWithBlock(){ hidden in
println("Screen 2 has been hidden")
let screen3 = JNTutorialOverlay(overlayName: "Screen3", frame: CGRectMake(100, ScreenConstants.height - 200, ScreenConstants.width - 100, 200), opacity: 0.8, title: "Screen 3", message: "This one also has a custom frame but with a light theme and straight corners.")
screen3.theme = .Light
screen3.corners = .Straight
screen3.showWithBlock(){ hidden in
println("Screen 3 has been hidden")
let screen4 = JNTutorialOverlay(overlayName: "Screen4", width: 250, opacity: 0.7, title: "Screen 4", message: "Overlays can also include a picture under the text, like this one.", image: UIImage(named: "Birdcast"))
screen4.showWithBlock(){ hidden in
println("Screen 4 has been hidden")
let screen5 = JNTutorialOverlay(overlayName: "Screen5", frame: CGRectMake(0, 200, ScreenConstants.width, 200), opacity: 0.8, title: nil, message: nil)
screen5.title = "Screen 5"
screen5.message = "Of course all the optional values such as title, message, picture, corners and theme can be modified after the overlay has been created."
screen5.theme = .Light
screen5.corners = .Straight
screen5.showWithBlock(){ hidden in
println("Screen 5 has been hidden")
let screen6 = JNTutorialOverlay(overlayName: "Screen6", width: 300, opacity: 0.8, title: "Screen 6", message: "And because these overlays are supposed to be shown to a first-time user only, they will only appear once!")
screen6.showWithBlock(){ hidden in
println("Screen 6 has been hidden")
let screen7 = JNTutorialOverlay(overlayName: "Screen7", width: 300, opacity: 0.8, title: "Final screen", message: "You can see these overlays in action in our apps Birdcast and Q-Beat (available for free on the App Store).\n\nWe hope you enjoyed this run-through.\nLet us know if you end up using our tutorial overlays in your apps! :)")
screen7.show()
}
}
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a9ab50cc31a088973a905032678adfe6 | 50.675 | 369 | 0.541848 | 5.186951 | false | false | false | false |
robinckanatzar/mcw | my-core-wellness/Pods/JTAppleCalendar/Sources/GlobalFunctionsAndExtensions.swift | 2 | 1886 | //
// GlobalFunctionsAndExtensions.swift
// Pods
//
// Created by JayT on 2016-06-26.
//
//
func delayRunOnMainThread(_ delay: Double, closure: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() +
Double(Int64(delay * Double(NSEC_PER_SEC))) /
Double(NSEC_PER_SEC), execute: closure)
}
func delayRunOnGlobalThread(_ delay: Double,
qos: DispatchQoS.QoSClass,
closure: @escaping () -> ()) {
DispatchQueue.global(qos: qos).asyncAfter(
deadline: DispatchTime.now() +
Double(Int64(delay * Double(NSEC_PER_SEC))) /
Double(NSEC_PER_SEC), execute: closure
)
}
extension Date {
static let formatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy MM dd"
return dateFormatter
}()
static func startOfMonth(for date: Date, using calendar: Calendar) -> Date? {
let dayOneComponents = calendar.dateComponents([.year, .month], from: date)
guard
let month = dayOneComponents.month,
let year = dayOneComponents.year else {
return nil
}
return Date.formatter.date(from: "\(year) \(month) 01")
}
static func endOfMonth(for date: Date, using calendar: Calendar) -> Date? {
var lastDayComponents = calendar.dateComponents([.era, .year, .month, .day, .hour], from: date)
lastDayComponents.month = lastDayComponents.month! + 1
lastDayComponents.day = 0
return calendar.date(from: lastDayComponents)
}
}
extension Dictionary where Value: Equatable {
func key(for value: Value) -> Key? {
guard let index = index(where: { $0.1 == value }) else {
return nil
}
return self[index].0
}
}
| apache-2.0 | e8639adf6da5eeae6b673b5da2ab97a1 | 30.966102 | 103 | 0.592259 | 4.286364 | false | false | false | false |
Yoseob/Trevi | Lime/Lime/Middleware/ServeStatic.swift | 1 | 1381 | //
// ServeStatic.swift
// Trevi
//
// Created by SeungHyun Lee on 2015. 12. 27..
// Copyright © 2015년 LeeYoseob. All rights reserved.
//
import Foundation
import Trevi
/**
A Middleware for serving static files in server like .css, .js, .html, etc.
*/
public class ServeStatic: Middleware {
public var name: MiddlewareName
private let basePath: String
public init (path: String) {
name = .ServeStatic
if let last = path.characters.last where last == "/" {
basePath = path[path.startIndex ..< path.endIndex.advancedBy(-1)]
} else {
basePath = path
}
}
public func handle(req: IncomingMessage, res: ServerResponse, next: NextCallback?) {
var entirePath = req.url
#if os(Linux)
entirePath = "\(basePath)/\(req.url)"
#else
if let bundlePath = NSBundle.mainBundle().pathForResource(NSURL(fileURLWithPath: req.url).lastPathComponent!, ofType: nil) {
entirePath = bundlePath
}
#endif
let file = FileSystem.ReadStream(path: entirePath)
let buf = NSMutableData()
file?.onClose() { handle in
return res.send(buf)
}
file?.readStart() { error, data in
buf.appendData(data)
}
next!()
}
}
| apache-2.0 | d1edb82a2aed890b4da06625b9b61cb8 | 25.5 | 136 | 0.567489 | 4.430868 | false | false | false | false |
Johennes/firefox-ios | Telemetry/CorePing.swift | 1 | 4047 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import UIKit
private let PrefKeyProfileDate = "PrefKeyProfileDate"
private let PrefKeyPingCount = "PrefKeyPingCount"
private let PrefKeyClientID = "PrefKeyClientID"
private let PrefKeyModel = "PrefKeyModel"
// See https://gecko.readthedocs.org/en/latest/toolkit/components/telemetry/telemetry/core-ping.html
private let PingVersion = 7
class CorePing: TelemetryPing {
let payload: JSON
let prefs: Prefs
init(profile: Profile) {
self.prefs = profile.prefs
let version = NSProcessInfo.processInfo().operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let pingCount = profile.prefs.intForKey(PrefKeyPingCount) ?? 0
profile.prefs.setInt(pingCount + 1, forKey: PrefKeyPingCount)
let profileDate: Int
if let date = profile.prefs.intForKey(PrefKeyProfileDate) {
profileDate = Int(date)
} else if let attributes = try? NSFileManager.defaultManager().attributesOfItemAtPath(profile.files.rootPath as String),
let date = attributes[NSFileCreationDate] as? NSDate {
let seconds = date.timeIntervalSince1970
profileDate = Int(UInt64(seconds) * OneSecondInMilliseconds / OneDayInMilliseconds)
profile.prefs.setInt(Int32(profileDate), forKey: PrefKeyProfileDate)
} else {
profileDate = 0
}
let clientID: String
if let id = profile.prefs.stringForKey(PrefKeyClientID) {
clientID = id
} else {
clientID = NSUUID().UUIDString
profile.prefs.setString(clientID, forKey: PrefKeyClientID)
}
let model: String
if let modelString = profile.prefs.stringForKey(PrefKeyModel) {
model = modelString
} else {
var sysinfo = utsname()
uname(&sysinfo)
let rawModel = NSString(bytes: &sysinfo.machine, length: Int(_SYS_NAMELEN), encoding: NSASCIIStringEncoding)!
model = rawModel.stringByTrimmingCharactersInSet(NSCharacterSet.controlCharacterSet())
profile.prefs.setString(model, forKey: PrefKeyModel)
}
let locale = NSBundle.mainBundle().preferredLocalizations.first!.stringByReplacingOccurrencesOfString("_", withString: "-")
let defaultEngine = profile.searchEngines.defaultEngine
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.stringFromDate(NSDate())
let timezoneOffset = NSTimeZone.localTimeZone().secondsFromGMT / 60
let usageCount = UsageTelemetry.getCount(prefs)
let usageTime = UsageTelemetry.getTime(prefs)
UsageTelemetry.reset(prefs)
var out: [String: AnyObject] = [
"v": PingVersion,
"clientId": clientID,
"seq": Int(pingCount),
"locale": locale,
"os": "iOS",
"osversion": versionString,
"device": "Apple-" + model,
"arch": "arm",
"profileDate": profileDate,
"defaultSearch": defaultEngine.engineID ?? JSON.null,
"created": date,
"tz": timezoneOffset,
"sessions": usageCount,
"durations": usageTime,
]
if let searches = SearchTelemetry.getData(profile.prefs) {
out["searches"] = searches
SearchTelemetry.resetCount(profile.prefs)
}
if let newTabChoice = self.prefs.stringForKey(NewTabAccessors.PrefKey) {
out["defaultNewTabExperience"] = newTabChoice
if let chosenEmailClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) {
out["defaultMailClient"] = chosenEmailClient
}
payload = JSON(out)
}
}
| mpl-2.0 | 06d3f59833b2af1b99640920f4e4176e | 37.542857 | 131 | 0.646652 | 4.744431 | false | false | false | false |
fqhuy/minimind | minimind/gaussian_process/gplvm.swift | 1 | 4315 | //
// gplvm.swift
// minimind
//
// Created by Phan Quoc Huy on 6/28/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
//
import Foundation
//MARK: This class is dedicated to inferring new latent X given new (possible with missing dimensions) Y, mostly borrowed from GPy (InferenceX)
public class GPLVMLikelihood<K: Kernel>: ObjectiveFunction where K.ScalarT == Float {
public typealias ScalarT = Float
public typealias MatrixT = Matrix<ScalarT>
public typealias KernelT = K
public var dims: Int
public var XNew: MatrixT
public var YNew: MatrixT
public var likelihood: GPLikelihood<K>
public var Z: MatrixT
public var missingData: Bool
public var validDims: [IndexType] = []
public var kernel: KernelT
var dPsi0: MatrixT = MatrixT()
var dPsi1: MatrixT = MatrixT()
var dPsi2: MatrixT = MatrixT()
public init(_ model: GaussianProcessRegressor<K>, _ Y: MatrixT) {
self.dims = Y.columns
XNew = zeros(1, dims)
YNew = Y
self.likelihood = model.likelihood
kernel = model.kernel
self.Z = model.Xtrain
missingData = isnan(Y).any()
validDims = nonzero(Y.grid.map{ !$0.isNaN })
XNew = initX(model, Y)
precompute()
}
func precompute() {
// make sure finite precision
// TODO: assuming scalar noise here. beta can be a NxN matrix, depending on the noise model
let beta = 1.0 / likelihood.noise[0, 0]
let D = ScalarT(YNew.columns)
// update stored values in the likelihood
likelihood.update()
var wv = likelihood.woodburyVector
if missingData {
wv = wv[forall, validDims]
dPsi0 = -0.5 * (beta * ones(1, YNew.rows))
dPsi1 = beta * (YNew[forall, validDims] * wv.t)
dPsi2 = 0.5 * beta * (D * likelihood.woodburyInv - wv * wv.t)
} else {
dPsi0 = -0.5 * D * (beta * ones(1, YNew.rows))
dPsi1 = beta * (YNew * wv.t)
dPsi2 = beta * (D * likelihood.woodburyInv - (wv * wv.t))
}
}
public func initX(_ model: GaussianProcessRegressor<K>, _ Y: MatrixT) -> MatrixT {
// init Xnew
var YTrain = model.ytrain
var dist = MatrixT()
if missingData {
YTrain = YTrain[forall, validDims]
let YNew_ = Y[forall, validDims]
//WARNING: This is dangerous, consider the order of *
let xy = -2.0 * YNew_ * YTrain.t
dist = (xy |+ pow(YNew_, 2).sum(axis: 1)) .+ pow(YTrain, 2).sum(axis: 1).t
} else {
let xy = -2.0 * YNew * YTrain.t
dist = (xy |+ pow(YNew, 2).sum(axis: 1)) .+ pow(YTrain, 2).sum(axis: 1).t
}
let idx = argmin(dist, 1).t //[0, 0]
return model.Xtrain[idx.grid]
}
public func compute(_ x: Matrix<Float>) -> Float {
XNew = x
let psi1 = kernel.K(x, Z)
let psi0 = diag(kernel.K(x, x))
let psi2 = psi1.t * psi1
let v2 = (dPsi2 ∘ psi2).sum()
let v1 = (dPsi1 ∘ psi1).sum()
let v0 = (dPsi0 ∘ psi0).sum()
return v0 + v1 + v2
}
public func gradient(_ x: Matrix<Float>) -> Matrix<Float> {
let psi1 = kernel.K(x, Z)
let dPsi1 = self.dPsi1 + 2.0 * (psi1 * dPsi2)
var XGrad = kernel.gradientX(x, Z, dPsi1)
// TODO: ONLY WORKS FOR STATIONARY!
// XGrad += kernel.gradientXDiag(x, dPsi0)
return XGrad
}
public func hessian(_ x: Matrix<Float>) -> Matrix<Float> {
return MatrixT()
}
}
public class GPLVM<K: Kernel>: GaussianProcessRegressor<K> where K.ScalarT == Float {
var predictXModel: GPLVMLikelihood<K>? = nil
public override init(kernel: KernelT, alpha: ScalarT) {
super.init(kernel: kernel, alpha: alpha)
}
/// predict latent point X from observation YStar
public func predictX(_ YStar: MatrixT, _ verbose: Bool=false) -> MatrixT {
predictXModel = GPLVMLikelihood(self, YStar)
let opt = SCG(objective: predictXModel!, learningRate: 0.01, initX: predictXModel!.XNew, maxIters: 50)
let (x, _, _) = opt.optimize(verbose: verbose)
return x
}
}
| mit | a26753b63a70b3a803a7482e393b9953 | 32.65625 | 143 | 0.568709 | 3.331787 | false | false | false | false |
edragoev1/pdfjet | Sources/PDFjet/GS1_128.swift | 1 | 2080 | /**
* GS1_128.swift
*
Copyright 2020 Innovatics Inc.
*/
class GS1_128 {
public static let TABLE = [
212222, // 0
222122, // 1
222221, // 2
121223, // 3
121322, // 4
131222, // 5
122213, // 6
122312, // 7
132212, // 8
221213, // 9
221312, // 10
231212, // 11
112232, // 12
122132, // 13
122231, // 14
113222, // 15
123122, // 16
123221, // 17
223211, // 18
221132, // 19
221231, // 20
213212, // 21
223112, // 22
312131, // 23
311222, // 24
321122, // 25
321221, // 26
312212, // 27
322112, // 28
322211, // 29
212123, // 30
212321, // 31
232121, // 32
111323, // 33
131123, // 34
131321, // 35
112313, // 36
132113, // 37
132311, // 38
211313, // 39
231113, // 40
231311, // 41
112133, // 42
112331, // 43
132131, // 44
113123, // 45
113321, // 46
133121, // 47
313121, // 48
211331, // 49
231131, // 50
213113, // 51
213311, // 52
213131, // 53
311123, // 54
311321, // 55
331121, // 56
312113, // 57
312311, // 58
332111, // 59
314111, // 60
221411, // 61
431111, // 62
111224, // 63
111422, // 64
121124, // 65
121421, // 66
141122, // 67
141221, // 68
112214, // 69
112412, // 70
122114, // 71
122411, // 72
142112, // 73
142211, // 74
241211, // 75
221114, // 76
413111, // 77
241112, // 78
134111, // 79
111242, // 80
121142, // 81
121241, // 82
114212, // 83
124112, // 84
124211, // 85
411212, // 86
421112, // 87
421211, // 88
212141, // 89
214121, // 90
412121, // 91
111143, // 92
111341, // 93
131141, // 94
114113, // 95
114311, // 96
411113, // 97
411311, // 98 - SHIFT
113141, // 99 - Code C
114131, // 100 - FNC 4
311141, // 101 - Code A
411131, // 102
211412, // 103 - Start A
211214, // 104 - Start B
211232, // 105 - Start C
2331112 // 106 - Stop
]
// Shifts from SET_A -> SET_B or SET_B -> SET_A for a single char
public static let SHIFT = 98
public static let CODE_C = 99 // Latch to SET_C
public static let FNC_4 = 100 // FNC 4
public static let CODE_A = 101 // Latch to SET_A
public static let START_A = 103
public static let START_B = 104
public static let START_C = 105
public static let STOP = 106
} // End of GS1_128.swift
| mit | d09d798f4fc17993f61189ee4d2e5441 | 14.877863 | 65 | 0.591346 | 2.444183 | false | false | false | false |
JohnnyHao/ForeignChat | ForeignChat/TabVCs/Friends/GroupsViewController.swift | 1 | 4969 | //
// GroupViewController.swift
// ForeignChat
//
// Created by Tonny Hao on 2/20/15.
// Copyright (c) 2015 Tonny Hao. All rights reserved.
//
import UIKit
// Parse loaded from ForeignChat-Bridging-Header.h
class GroupsViewController: UITableViewController, UIAlertViewDelegate {
var groups: [PFObject]! = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() != nil {
self.loadGroups()
}
else {
Utilities.loginUser(self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadGroups() {
var query = PFQuery(className: PF_GROUPS_CLASS_NAME)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) in
if error == nil {
self.groups.removeAll()
self.groups.extend(objects as [PFObject]!)
self.tableView.reloadData()
} else {
ProgressHUD.showError("Network error")
println(error)
}
}
}
@IBAction func newButtonPressed(sender: UIBarButtonItem) {
self.actionNew()
}
func actionNew() {
var alert = UIAlertView(title: "Please enter a name for your group", message: "", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex != alertView.cancelButtonIndex {
var textField = alertView.textFieldAtIndex(0);
if let text = textField!.text {
if countElements(text) > 0 {
var object = PFObject(className: PF_GROUPS_CLASS_NAME)
object[PF_GROUPS_NAME] = text
object.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in
if success {
self.loadGroups()
} else {
ProgressHUD.showError("Network error")
println(error)
}
})
}
}
}
}
// MARK: - TableView Data Source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.groups.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var group = self.groups[indexPath.row]
cell.textLabel?.text = group[PF_GROUPS_NAME] as? String
var query = PFQuery(className: PF_CHAT_CLASS_NAME)
query.whereKey(PF_CHAT_GROUPID, equalTo: group.objectId)
query.orderByDescending(PF_CHAT_CREATEDAT)
query.limit = 1000
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if let chat = objects.first as? PFObject {
let date = NSDate()
let seconds = date.timeIntervalSinceDate(chat.createdAt)
let elapsed = Utilities.timeElapsed(seconds);
let countString = (objects.count > 1) ? "\(objects.count) messages" : "\(objects.count) message"
cell.detailTextLabel?.text = "\(countString) \(elapsed)"
} else {
cell.detailTextLabel?.text = "0 messages"
}
cell.detailTextLabel?.textColor = UIColor.lightGrayColor()
}
return cell
}
// MARK: - TableView Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var group = self.groups[indexPath.row]
let groupId = group.objectId as String
Messages.createMessageItem(PFUser(), groupId: groupId, description: group[PF_GROUPS_NAME] as String)
//self.performSegueWithIdentifier("groupChatSegue", sender: groupId)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "groupChatSegue" {
let chatVC = segue.destinationViewController as ChatViewController
chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as String
chatVC.groupId = groupId
}
}
}
| apache-2.0 | 3c0be89a6b6d5115036ac5b1ba6184d4 | 35.007246 | 159 | 0.590461 | 5.360302 | false | false | false | false |
nathawes/swift | test/decl/protocol/req/associated_type_inference.swift | 7 | 16448 | // RUN: %target-typecheck-verify-swift
protocol P0 {
associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
// expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
func f0(_: Assoc1)
func g0(_: Assoc1)
}
protocol PSimple { }
extension Int : PSimple { }
extension Double : PSimple { }
struct X0a : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Int) { }
}
struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}}
}
struct X0c : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0d : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Double) { } // viable, but no corresponding f0
func g0(_: Int) { }
}
struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}}
func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { }
func g0(_: Int) { }
}
struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple
func f0(_: Float) { }
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}}
func f0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0h<T : PSimple> : P0 {
func f0(_: T) { }
}
extension X0h {
func g0(_: T) { }
}
struct X0i<T : PSimple> {
}
extension X0i {
func g0(_: T) { }
}
extension X0i : P0 { }
extension X0i {
func f0(_: T) { }
}
// Protocol extension used to infer requirements
protocol P1 {
}
extension P1 {
func f0(_ x: Int) { }
func g0(_ x: Int) { }
}
struct X0j : P0, P1 { }
protocol P2 {
associatedtype P2Assoc
func h0(_ x: P2Assoc)
}
extension P2 where Self.P2Assoc : PSimple {
func f0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0k : P0, P2 {
func h0(_ x: Int) { }
}
struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}}
func h0(_ x: Float) { }
}
// Prefer declarations in the type to those in protocol extensions
struct X0m : P0, P2 {
func f0(_ x: Double) { }
func g0(_ x: Double) { }
func h0(_ x: Double) { }
}
// Inference from properties.
protocol PropertyP0 {
associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}}
var property: Prop { get }
}
struct XProp0a : PropertyP0 { // okay PropType = Int
var property: Int
}
struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}}
var property: Float // expected-note{{candidate would match and infer 'Prop' = 'Float' if 'Float' conformed to 'PSimple'}}
}
// Inference from subscripts
protocol SubscriptP0 {
associatedtype Index
// expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element : PSimple
// expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}}
// expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}}
subscript (i: Index) -> Element { get }
}
struct XSubP0a : SubscriptP0 {
subscript (i: Int) -> Int { get { return i } }
}
struct XSubP0b : SubscriptP0 {
// expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}}
subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{candidate would match and infer 'Element' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct XSubP0c : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}}
subscript (i: Index) -> Element { get { } }
}
struct XSubP0d : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}}
subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } }
}
// Inference from properties and subscripts
protocol CollectionLikeP0 {
associatedtype Index
// expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element
// expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}}
var startIndex: Index { get }
var endIndex: Index { get }
subscript (i: Index) -> Element { get }
}
struct SomeSlice<T> { }
struct XCollectionLikeP0a<T> : CollectionLikeP0 {
var startIndex: Int
var endIndex: Int
subscript (i: Int) -> T { get { fatalError("blah") } }
subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } }
}
struct XCollectionLikeP0b : CollectionLikeP0 {
// expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}}
var startIndex: XCollectionLikeP0b.Index
// There was an error @-1 ("'startIndex' used within its own type"),
// but it disappeared and doesn't seem like much of a loss.
var startElement: XCollectionLikeP0b.Element
}
// rdar://problem/21304164
public protocol Thenable {
associatedtype T // expected-note{{protocol requires nested type 'T'}}
func then(_ success: (_: T) -> T) -> Self
}
public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}}
public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self {
return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}}
return success(t: t, self)
// expected-error@-1 {{extraneous argument label 't:' in call}}
}
}
}
// rdar://problem/21559670
protocol P3 {
associatedtype Assoc = Int
associatedtype Assoc2
func foo(_ x: Assoc2) -> Assoc?
}
protocol P4 : P3 { }
extension P4 {
func foo(_ x: Int) -> Float? { return 0 }
}
extension P3 where Assoc == Int {
func foo(_ x: Int) -> Assoc? { return nil }
}
struct X4 : P4 { }
// rdar://problem/21738889
protocol P5 {
associatedtype A = Int
}
struct X5<T : P5> : P5 {
typealias A = T.A
}
protocol P6 : P5 {
associatedtype A : P5 = X5<Self>
}
extension P6 where A == X5<Self> { }
// rdar://problem/21774092
protocol P7 {
associatedtype A
associatedtype B
func f() -> A
func g() -> B
}
struct X7<T> { }
extension P7 {
func g() -> X7<A> { return X7() }
}
struct Y7<T> : P7 {
func f() -> Int { return 0 }
}
struct MyAnySequence<Element> : MySequence {
typealias SubSequence = MyAnySequence<Element>
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
struct MyAnyIterator<T> : MyIteratorType {
typealias Element = T
}
protocol MyIteratorType {
associatedtype Element
}
protocol MySequence {
associatedtype Iterator : MyIteratorType
associatedtype SubSequence
func foo() -> SubSequence
func makeIterator() -> Iterator
}
extension MySequence {
func foo() -> MyAnySequence<Iterator.Element> {
return MyAnySequence()
}
}
struct SomeStruct<Element> : MySequence {
let element: Element
init(_ element: Element) {
self.element = element
}
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
// rdar://problem/21883828 - ranking of solutions
protocol P8 {
}
protocol P9 : P8 {
}
protocol P10 {
associatedtype A
func foo() -> A
}
struct P8A { }
struct P9A { }
extension P8 {
func foo() -> P8A { return P8A() }
}
extension P9 {
func foo() -> P9A { return P9A() }
}
struct Z10 : P9, P10 {
}
func testZ10() -> Z10.A {
var zA: Z10.A
zA = P9A()
return zA
}
// rdar://problem/21926788
protocol P11 {
associatedtype A
associatedtype B
func foo() -> B
}
extension P11 where A == Int {
func foo() -> Int { return 0 }
}
protocol P12 : P11 {
}
extension P12 {
func foo() -> String { return "" }
}
struct X12 : P12 {
typealias A = String
}
// Infinite recursion -- we would try to use the extension
// initializer's argument type of 'Dough' as a candidate for
// the associated type
protocol Cookie {
associatedtype Dough
// expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}}
init(t: Dough)
}
extension Cookie {
init(t: Dough?) {}
}
struct Thumbprint : Cookie {}
// expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}}
// Looking through typealiases
protocol Vector {
associatedtype Element
typealias Elements = [Element]
func process(elements: Elements)
}
struct Int8Vector : Vector {
func process(elements: [Int8]) { }
}
// SR-4486
protocol P13 {
associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}}
func foo(arg: Arg)
}
struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}}
func foo(arg: inout Int) {}
}
// "Infer" associated type from generic parameter.
protocol P14 {
associatedtype Value
}
struct P14a<Value>: P14 { }
struct P14b<Value> { }
extension P14b: P14 { }
// Associated type defaults in overridden associated types.
struct X15 { }
struct OtherX15 { }
protocol P15a {
associatedtype A = X15
}
protocol P15b : P15a {
associatedtype A
}
protocol P15c : P15b {
associatedtype A
}
protocol P15d {
associatedtype A = X15
}
protocol P15e : P15b, P15d {
associatedtype A
}
protocol P15f {
associatedtype A = OtherX15
}
protocol P15g: P15c, P15f {
associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
}
struct X15a : P15a { }
struct X15b : P15b { }
struct X15c : P15c { }
struct X15d : P15d { }
// Ambiguity.
// FIXME: Better diagnostic here?
struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
// Associated type defaults in overidden associated types that require
// substitution.
struct X16<T> { }
protocol P16 {
associatedtype A = X16<Self>
}
protocol P16a : P16 {
associatedtype A
}
protocol P16b : P16a {
associatedtype A
}
struct X16b : P16b { }
// Refined protocols that tie associated types to a fixed type.
protocol P17 {
associatedtype T
}
protocol Q17 : P17 where T == Int { }
struct S17 : Q17 { }
// Typealiases from protocol extensions should not inhibit associated type
// inference.
protocol P18 {
associatedtype A
}
protocol P19 : P18 {
associatedtype B
}
extension P18 where Self: P19 {
typealias A = B
}
struct X18<A> : P18 { }
// rdar://problem/16316115
protocol HasAssoc {
associatedtype Assoc
}
struct DefaultAssoc {}
protocol RefinesAssocWithDefault: HasAssoc {
associatedtype Assoc = DefaultAssoc
}
struct Foo: RefinesAssocWithDefault {
}
protocol P20 {
associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
typealias TT = T?
}
struct S19 : P20 { // expected-error{{type 'S19' does not conform to protocol 'P20'}}
typealias TT = Int?
}
// rdar://problem/44777661
struct S30<T> where T : P30 {}
protocol P30 {
static func bar()
}
protocol P31 {
associatedtype T : P30
}
extension S30 : P31 where T : P31 {}
extension S30 {
func foo() {
T.bar()
}
}
protocol P32 {
associatedtype A
associatedtype B
associatedtype C
func foo(arg: A) -> C
var bar: B { get }
}
protocol P33 {
associatedtype A
var baz: A { get } // expected-note {{protocol requires property 'baz' with type 'S31<T>.A' (aka 'Never'); do you want to add a stub?}}
}
protocol P34 {
associatedtype A
func boo() -> A // expected-note {{protocol requires function 'boo()' with type '() -> S31<T>.A' (aka '() -> Never'); do you want to add a stub?}}
}
struct S31<T> {}
extension S31: P32 where T == Int {} // OK
extension S31 where T == Int {
func foo(arg: Never) {}
}
extension S31 where T: Equatable {
var bar: Bool { true }
}
extension S31: P33 where T == Never {} // expected-error {{type 'S31<T>' does not conform to protocol 'P33'}}
extension S31 where T == String {
var baz: Bool { true } // expected-note {{candidate has non-matching type 'Bool' [with A = S31<T>.A]}}
}
extension S31: P34 {} // expected-error {{type 'S31<T>' does not conform to protocol 'P34'}}
extension S31 where T: P32 {
func boo() -> Void {} // expected-note {{candidate has non-matching type '<T> () -> Void' [with A = S31<T>.A]}}
}
// SR-12707
class SR_12707_C<T> {}
// Inference in the adoptee
protocol SR_12707_P1 {
associatedtype A
associatedtype B: SR_12707_C<(A, Self)>
func foo(arg: B)
}
struct SR_12707_Conform_P1: SR_12707_P1 {
typealias A = Never
func foo(arg: SR_12707_C<(A, SR_12707_Conform_P1)>) {}
}
// Inference in protocol extension
protocol SR_12707_P2: SR_12707_P1 {}
extension SR_12707_P2 {
func foo(arg: SR_12707_C<(A, Self)>) {}
}
struct SR_12707_Conform_P2: SR_12707_P2 {
typealias A = Never
}
// SR-13172: Inference when witness is an enum case
protocol SR_13172_P1 {
associatedtype Bar
static func bar(_ value: Bar) -> Self
}
enum SR_13172_E1: SR_13172_P1 {
case bar(String) // Okay
}
protocol SR_13172_P2 {
associatedtype Bar
static var bar: Bar { get }
}
enum SR_13172_E2: SR_13172_P2 {
case bar // Okay
}
/** References to type parameters in type witnesses. */
// Circular reference through a fixed type witness.
protocol P35a {
associatedtype A = Array<B> // expected-note {{protocol requires nested type 'A'}}
associatedtype B // expected-note {{protocol requires nested type 'B'}}
}
protocol P35b: P35a where B == A {}
// expected-error@+2 {{type 'S35' does not conform to protocol 'P35a'}}
// expected-error@+1 {{type 'S35' does not conform to protocol 'P35b'}}
struct S35: P35b {}
// Circular reference through a value witness.
protocol P36a {
associatedtype A // expected-note {{protocol requires nested type 'A'}}
func foo(arg: A)
}
protocol P36b: P36a {
associatedtype B = (Self) -> A // expected-note {{protocol requires nested type 'B'}}
}
// expected-error@+2 {{type 'S36' does not conform to protocol 'P36a'}}
// expected-error@+1 {{type 'S36' does not conform to protocol 'P36b'}}
struct S36: P36b {
func foo(arg: Array<B>) {}
}
// Test that we can resolve abstract type witnesses that reference
// other abstract type witnesses.
protocol P37 {
associatedtype A = Array<B>
associatedtype B: Equatable = Never
}
struct S37: P37 {}
protocol P38a {
associatedtype A = Never
associatedtype B: Equatable
}
protocol P38b: P38a where B == Array<A> {}
struct S38: P38b {}
protocol P39 where A: Sequence {
associatedtype A = Array<B>
associatedtype B
}
struct S39<B>: P39 {}
// Test that we can handle an analogous complex case involving all kinds of
// type witness resolution.
protocol P40a {
associatedtype A
associatedtype B: P40a
func foo(arg: A)
}
protocol P40b: P40a {
associatedtype C = (A, B.A, D.D, E) -> Self
associatedtype D: P40b
associatedtype E: Equatable
}
protocol P40c: P40b where D == S40<Never> {}
struct S40<E: Equatable>: P40c {
func foo(arg: Never) {}
typealias B = Self
}
// Fails to find the fixed type witness B == FIXME_S1<A>.
protocol FIXME_P1a {
associatedtype A: Equatable = Never // expected-note {{protocol requires nested type 'A'}}
associatedtype B: FIXME_P1a // expected-note {{protocol requires nested type 'B'}}
}
protocol FIXME_P1b: FIXME_P1a where B == FIXME_S1<A> {}
// expected-error@+2 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1a'}}
// expected-error@+1 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1b'}}
struct FIXME_S1<T: Equatable>: FIXME_P1b {}
| apache-2.0 | c0a3779abe86c67750bc04ae0a7271cc | 22.941776 | 167 | 0.66695 | 3.255096 | false | false | false | false |
Shuangzuan/Pew | Pew/SKTUtils/Vector3.swift | 19 | 2810 | /*
* Copyright (c) 2013-2014 Razeware 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 CoreGraphics
public struct Vector3: Equatable {
var x: CGFloat
var y: CGFloat
var z: CGFloat
public init(x: CGFloat, y: CGFloat, z: CGFloat) {
self.x = x
self.y = y
self.z = z
}
}
public func == (lhs: Vector3, rhs: Vector3) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
extension Vector3 {
/**
* Returns true if all the vector elements are equal to the provided value.
*/
public func equalToScalar(value: CGFloat) -> Bool {
return x == value && y == value && z == value
}
/**
* Returns the magnitude of the vector.
**/
public func length() -> CGFloat {
return sqrt(x*x + y*y + z*z)
}
/**
* Normalizes the vector and returns the result as a new vector.
*/
public func normalized() -> Vector3 {
let scale = 1.0/length()
return Vector3(x: x * scale, y: y * scale, z: z * scale)
}
/**
* Normalizes the vector described by this Vector3 object.
*/
public mutating func normalize() {
let scale = 1.0/length()
x *= scale
y *= scale
z *= scale
}
/**
* Calculates the dot product of two vectors.
*/
public static func dotProduct(left: Vector3, right: Vector3) -> CGFloat {
return left.x * right.x + left.y * right.y + left.z * right.z
}
/**
* Calculates the cross product of two vectors.
*/
public static func crossProduct(left: Vector3, right: Vector3) -> Vector3 {
let crossProduct = Vector3(x: left.y * right.z - left.z * right.y,
y: left.z * right.x - left.x * right.z,
z: left.x * right.y - left.y * right.x)
return crossProduct
}
}
| mit | 535175b9f53aca676dc6551e827f8d36 | 30.222222 | 80 | 0.649822 | 3.886584 | false | false | false | false |
czechboy0/Buildasaur | BuildaGitServer/GitHub/GitHubEndpoints.swift | 2 | 5151 | //
// GitHubURLFactory.swift
// Buildasaur
//
// Created by Honza Dvorsky on 13/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
class GitHubEndpoints {
enum Endpoint {
case Users
case Repos
case PullRequests
case Issues
case Branches
case Commits
case Statuses
case IssueComments
case Merges
}
enum MergeResult {
case Success(NSDictionary)
case NothingToMerge
case Conflict
case Missing(String)
}
private let baseURL: String
private let auth: ProjectAuthenticator?
init(baseURL: String, auth: ProjectAuthenticator?) {
self.baseURL = baseURL
self.auth = auth
}
private func endpointURL(endpoint: Endpoint, params: [String: String]? = nil) -> String {
switch endpoint {
case .Users:
if let user = params?["user"] {
return "/users/\(user)"
} else {
return "/user"
}
//FYI - repo must be in its full name, e.g. czechboy0/Buildasaur, not just Buildasaur
case .Repos:
if let repo = params?["repo"] {
return "/repos/\(repo)"
} else {
let user = self.endpointURL(.Users, params: params)
return "\(user)/repos"
}
case .PullRequests:
assert(params?["repo"] != nil, "A repo must be specified")
let repo = self.endpointURL(.Repos, params: params)
let pulls = "\(repo)/pulls"
if let pr = params?["pr"] {
return "\(pulls)/\(pr)"
} else {
return pulls
}
case .Issues:
assert(params?["repo"] != nil, "A repo must be specified")
let repo = self.endpointURL(.Repos, params: params)
let issues = "\(repo)/issues"
if let issue = params?["issue"] {
return "\(issues)/\(issue)"
} else {
return issues
}
case .Branches:
let repo = self.endpointURL(.Repos, params: params)
let branches = "\(repo)/branches"
if let branch = params?["branch"] {
return "\(branches)/\(branch)"
} else {
return branches
}
case .Commits:
let repo = self.endpointURL(.Repos, params: params)
let commits = "\(repo)/commits"
if let commit = params?["commit"] {
return "\(commits)/\(commit)"
} else {
return commits
}
case .Statuses:
let sha = params!["sha"]!
let method = params?["method"]
if let method = method {
if method == HTTP.Method.POST.rawValue {
//POST, we need slightly different url
let repo = self.endpointURL(.Repos, params: params)
return "\(repo)/statuses/\(sha)"
}
}
//GET, default
let commits = self.endpointURL(.Commits, params: params)
return "\(commits)/\(sha)/statuses"
case .IssueComments:
let issues = self.endpointURL(.Issues, params: params)
let comments = "\(issues)/comments"
if let comment = params?["comment"] {
return "\(comments)/\(comment)"
} else {
return comments
}
case .Merges:
assert(params?["repo"] != nil, "A repo must be specified")
let repo = self.endpointURL(.Repos, params: params)
return "\(repo)/merges"
}
}
func createRequest(method:HTTP.Method, endpoint:Endpoint, params: [String : String]? = nil, query: [String : String]? = nil, body:NSDictionary? = nil) throws -> NSMutableURLRequest {
let endpointURL = self.endpointURL(endpoint, params: params)
let queryString = HTTP.stringForQuery(query)
let wholePath = "\(self.baseURL)\(endpointURL)\(queryString)"
let url = NSURL(string: wholePath)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method.rawValue
if let auth = self.auth {
switch auth.type {
case .PersonalToken, .OAuthToken:
request.setValue("token \(auth.secret)", forHTTPHeaderField:"Authorization")
}
}
if let body = body {
let data = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions())
request.HTTPBody = data
}
return request
}
}
| mit | aefeafc5622beaf3ac437952c36eb0d5 | 29.3 | 186 | 0.482236 | 5.439282 | false | false | false | false |
zgorawski/LoLSkins | LoLSkins/APIGateway/StaticDataAPI.swift | 1 | 1876 | //
// StaticDataAPI.swift
// LoLSkins
//
// Created by Zbigniew Górawski on 07/05/2017.
// Copyright © 2017 Zbigniew Górawski. All rights reserved.
//
import SOLIDNetworking
import ReactiveSwift
class StaticDataAPI {
private let engine: NetworkingEngine
private let plistStorage: PListStorage
init(plistStorage: PListStorage = PListStorage(), engine: NetworkingEngine = NetworkingEngine()) {
self.plistStorage = plistStorage
self.engine = engine
// warm up
fetchChampions()
fetchLatestVersion()
}
// MARK: Rx
let champions = MutableProperty<[LoLChampion]?>(nil)
let latestVersion = MutableProperty<LoLVersion?>(nil)
let error = MutableProperty<APIError?>(nil)
// MARK: API
func fetchChampions() {
guard let apiKey = apiKey else { return }
let request = GetChampionsRequest(apiKey: apiKey)
engine.performRequest(request: request) { [weak self] result in
switch result {
case .success(let champions):
self?.champions.value = champions
case .error(let error):
self?.error.value = error
}
}
}
func fetchLatestVersion() {
guard let apiKey = apiKey else { return }
let request = GetVersionsRequest(apiKey: apiKey)
engine.performRequest(request: request) { [weak self] result in
switch result {
case .success(let version):
self?.latestVersion.value = version
case .error(let error):
self?.error.value = error
}
}
}
// MARK: Private
private var apiKey: String? { return plistStorage.readValue(forKey: "APIKey", inPlist: "APIKey") }
}
| mit | 1fbfbce945e8bf0c1409278df65f9d4e | 25.757143 | 102 | 0.579285 | 4.802564 | false | true | false | false |
janslow/qlab-from-csv | QLab From CSV/QLabFromCsv/CueCreators/CueQLabConnector.swift | 1 | 2064 | //
// CueCreator.swift
// QLab From CSV
//
// Created by Jay Anslow on 28/12/2014.
// Copyright (c) 2014 Jay Anslow. All rights reserved.
//
import Foundation
class CueQLabConnector {
private let _workspace : QLKWorkspace
private let _groupCueConnector : GroupCueQLabConnector
private let _startCueConnector : StartCueQLabConnector
private let _oscUdpCueConnector : OscUdpCueQLabConnector
private let _scriptCueConnector : ScriptCueQLabConnector
init(workspace : QLKWorkspace) {
_workspace = workspace
_groupCueConnector = GroupCueQLabConnector(workspace: workspace)
_startCueConnector = StartCueQLabConnector(workspace: workspace)
_oscUdpCueConnector = OscUdpCueQLabConnector(workspace: workspace)
_scriptCueConnector = ScriptCueQLabConnector(workspace: workspace)
_groupCueConnector.cueConnector = self
}
func appendCues(var cues : [Cue], completion : (uids : [String]) -> ()) {
if cues.isEmpty {
completion(uids: [])
} else {
var nextCue = cues.removeAtIndex(0)
appendCue(nextCue) {
(uid : String) in
log.debug("Created \(nextCue) with UID \(uid)")
self.appendCues(cues) {
(uids : [String]) in
completion(uids: [uid] + uids)
}
}
}
}
func appendCue(cue : Cue, completion : (uid : String) -> ()) {
if (cue is GroupCue) {
_groupCueConnector.appendCue(cue as GroupCue, completion: completion)
} else if (cue is StartCue) {
_startCueConnector.appendCue(cue as StartCue, completion: completion)
} else if (cue is OscUdpCue) {
_oscUdpCueConnector.appendCue(cue as OscUdpCue, completion: completion)
} else if (cue is ScriptCue) {
_scriptCueConnector.appendCue(cue as ScriptCue, completion: completion)
} else {
log.error("No QLab connector for \(cue)")
}
}
} | mit | 262a88bedab5564383320e3f2c45c699 | 35.22807 | 83 | 0.610465 | 3.961612 | false | false | false | false |
wikimedia/apps-ios-wikipedia | WMF Framework/NavigationState.swift | 1 | 3557 | public struct NavigationState: Codable {
static let libraryKey = "nav_state"
public var viewControllers: [ViewController]
public var shouldAttemptLogin: Bool
public init(viewControllers: [ViewController], shouldAttemptLogin: Bool) {
self.viewControllers = viewControllers
self.shouldAttemptLogin = shouldAttemptLogin
}
public struct ViewController: Codable {
public var kind: Kind
public var presentation: Presentation
public var info: Info?
public var children: [ViewController]
public mutating func updateChildren(_ children: [ViewController]) {
self.children = children
}
public init?(kind: Kind?, presentation: Presentation, info: Info? = nil, children: [ViewController] = []) {
guard let kind = kind else {
return nil
}
self.kind = kind
self.presentation = presentation
self.info = info
self.children = children
}
public enum Kind: Int, Codable {
case tab
case article
case random
case themeableNavigationController
case settings
case account
case talkPage
case talkPageReplyList
case readingListDetail
case detail
init?(from rawValue: Int?) {
guard let rawValue = rawValue else {
return nil
}
self.init(rawValue: rawValue)
}
}
public enum Presentation: Int, Codable {
case push
case modal
}
public struct Info: Codable {
public var selectedIndex: Int?
public var articleKey: String?
public var articleSectionAnchor: String?
public var talkPageSiteURLString: String?
public var talkPageTitle: String?
public var talkPageTypeRawValue: Int?
public var currentSavedViewRawValue: Int?
public var readingListURIString: String?
public var searchTerm: String?
public var contentGroupIDURIString: String?
// TODO: Remove after moving to Swift 5.1 -
// https://github.com/apple/swift-evolution/blob/master/proposals/0242-default-values-memberwise.md
public init(selectedIndex: Int? = nil, articleKey: String? = nil, articleSectionAnchor: String? = nil, talkPageSiteURLString: String? = nil, talkPageTitle: String? = nil, talkPageTypeRawValue: Int? = nil, currentSavedViewRawValue: Int? = nil, readingListURIString: String? = nil, searchTerm: String? = nil, contentGroupIDURIString: String? = nil) {
self.selectedIndex = selectedIndex
self.articleKey = articleKey
self.articleSectionAnchor = articleSectionAnchor
self.talkPageSiteURLString = talkPageSiteURLString
self.talkPageTitle = talkPageTitle
self.talkPageTypeRawValue = talkPageTypeRawValue
self.currentSavedViewRawValue = currentSavedViewRawValue
self.readingListURIString = readingListURIString
self.searchTerm = searchTerm
self.contentGroupIDURIString = contentGroupIDURIString
}
}
}
}
| mit | 8559e36d8673339c90a3aa3ac32c9f48 | 36.442105 | 360 | 0.576047 | 5.898839 | false | false | false | false |
AdySan/HomeKit-Demo | BetterHomeKit/TriggerDetailViewController.swift | 4 | 3529 | //
// TriggerDetailViewController.swift
// BetterHomeKit
//
// Created by Khaos Tian on 8/6/14.
// Copyright (c) 2014 Oltica. All rights reserved.
//
import UIKit
import HomeKit
class TriggerDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var actionSetTableView: UITableView!
weak var currentTrigger:HMTrigger?
var actionSets = [HMActionSet]()
override func viewDidLoad() {
super.viewDidLoad()
if let currentTrigger = currentTrigger {
self.title = "\(currentTrigger.name)"
}
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
updateActionSets()
}
func updateActionSets () {
actionSets.removeAll(keepCapacity: false)
if let currentTrigger = currentTrigger {
actionSets += currentTrigger.actionSets as! [HMActionSet]
}
actionSetTableView.reloadData()
}
@IBAction func addActionSet(sender: AnyObject) {
self.performSegueWithIdentifier("showActionSetsSelection", sender: currentTrigger)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showActionSetsSelection" {
let actionVC = segue.destinationViewController as! ActionSetsViewController
actionVC.pendingTrigger = sender as? HMTrigger
}
if segue.identifier == "showActionSetDetails" {
let actionVC = segue.destinationViewController as! ActionSetViewController
actionVC.currentActionSet = sender as? HMActionSet
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actionSets.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ActionSetCell", forIndexPath: indexPath) as! UITableViewCell
let actionSet = actionSets[indexPath.row] as HMActionSet
cell.textLabel?.text = "\(actionSet.name)"
cell.detailTextLabel?.text = "Actions:\(actionSet.actions.count)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let actionSet = actionSets[indexPath.row]
self.performSegueWithIdentifier("showActionSetDetails", sender: actionSet)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let actionSet = actionSets[indexPath.row]
currentTrigger?.removeActionSet(actionSet) {
error in
if error != nil {
NSLog("Failed to remove action set from Trigger, error:\(error)")
} else {
self.updateActionSets()
}
}
}
}
} | mit | c4df821347ca1069d4c4bd56bcf7a3c2 | 33.607843 | 148 | 0.65401 | 5.471318 | false | false | false | false |
MikeThomas1/RDICalculator | RDICalculator/Public/UnitsOfMeasure/Weight/Kilogram.swift | 1 | 886 | //
// Kilogram.swift
// RDICalculator
//
// Created by Michael Thomas on 8/25/17.
// Copyright © 2017 Vault-Tec. All rights reserved.
//
import Foundation
public struct Kilogram: WeightUnit {
public let value: Double
public let symbol = "kg"
public var name = "kilogram"
public init(value: Double) {
self.value = value
}
public init(value: Int) {
let dbl = Double(value)
self.value = dbl
}
public init(value: Float) {
let dbl = Double(value)
self.value = dbl
}
}
// TODO: document these
public extension Double {
var kilogram: Kilogram {
return Kilogram(value: self)
}
}
public extension Float {
var kilogram: Kilogram {
return Kilogram(value: self)
}
}
public extension Int {
var kilogram: Kilogram {
return Kilogram(value: self)
}
}
| mit | 6969114ce5a0d659b5b98e6f9d84cead | 16.7 | 52 | 0.59887 | 3.672199 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/Homework 12/Homework 12/AlamofireThreeWeather.swift | 1 | 2293 | //
// AlamofireThreeWeather.swift
// Homework 12
//
// Created by Ivan Krylov on 19.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import Foundation
class AlamofireThreeWeather {
var weatherCondition: String = ""
var temp: Int = 0
var date: String = ""
init?(weatherJson: NSDictionary) {
if let listJson = weatherJson["list"] as? NSArray {
for item in listJson {
if let main = item as? NSDictionary {
if let date = main["dt_txt"] as? String {
self.date = date
print(date)
}
if let temp = main["main"] as? NSDictionary {
if let temperature = temp["temp"] as? Double {
self.temp = Int(round(temperature - 273.15))
print(temp)
}
}
if let nestedJson = main["weather"] as? NSArray {
if let desc = nestedJson[0] as? NSDictionary {
if let weathCond = desc["description"] as? String {
self.weatherCondition = weathCond
print(weatherCondition)
}
}
}
}
}
}
// guard let listJson = weatherJson["list"] as? NSArray else { return nil }
// guard let zeroMain = listJson[0] as? NSDictionary else { return nil }
// guard let date = zeroMain["dt_txt"] as? String else { return nil }
// self.date = date
// guard let temp = zeroMain["main"] as? NSDictionary else { return nil }
// guard let temperature = temp["temp"] as? Double else { return nil }
// self.temp = Int(round(temperature - 273.15))
// guard let weather = zeroMain["weather"] as? NSArray else { return nil }
// guard let desc = weather[0] as? NSDictionary else { return nil }
// guard let weatherCondition = desc["description"] as? String else { return nil }
// self.weatherCondition = weatherCondition.capitalized
}
}
| apache-2.0 | 074d2a4979ab268129654758ba5d92d2 | 42.245283 | 97 | 0.484729 | 4.929032 | false | false | false | false |
bouwman/LayoutResearch | LayoutResearch/Activities/StudyActivity.swift | 1 | 3062 | //
// StudyActivity.swift
// LayoutResearch
//
// Created by Tassilo Bouwman on 05.08.17.
// Copyright © 2017 Tassilo Bouwman. All rights reserved.
//
import UIKit
import GameplayKit
enum ActivityType {
case search, survey, reward
var iconName: String {
return "activity " + String(describing: self)
}
var title: String {
switch self {
case .search:
return "Search task"
case .survey:
return "Survey"
case .reward:
return "Win a £20 Amazon voucher"
}
}
}
class StudyActivity {
var startDate: Date
var number: Int
var type: ActivityType
var stateMachine = ActivityStateMachine()
init(startDate: Date, number: Int, type: ActivityType) {
self.startDate = startDate
self.number = number
self.type = type
}
var isStartable: Bool {
switch type {
case .reward:
return isStudyCompleted && isRewardSignupComplete == false
case .survey:
return isAllSearchTasksComplete && isSurveyComplete == false
case .search:
return timeRemaining <= 0 && stateMachine.currentState is DataAvailableState
}
}
var isStudyCompleted: Bool {
return UserDefaults.standard.object(forKey: SettingsString.preferredLayout.rawValue) != nil
}
var isRewardSignupComplete: Bool {
return UserDefaults.standard.object(forKey: SettingsString.participantEmail.rawValue) != nil
}
var isAllSearchTasksComplete: Bool {
let lastActivityNumber = UserDefaults.standard.integer(forKey: SettingsString.lastActivityNumber.rawValue)
return lastActivityNumber == Const.StudyParameters.searchActivityCount - 1
}
var isSurveyComplete: Bool {
return UserDefaults.standard.string(forKey: SettingsString.preferredLayout.rawValue) != nil
}
var daysRemaining: Int {
return Int(timeRemaining) / (60*60*24)
}
var timeRemaining: TimeInterval {
return startDate.timeIntervalSince(Date())
}
var timeRemainingString: String {
switch type {
case .search:
let days = daysRemaining
if days > 0 {
return days == 1 ? "Available in \(days) day" : "Available in \(days) days"
} else {
return timeToString(time: timeRemaining)
}
case .survey:
return "Available after last search task"
case .reward:
return "Available after survey"
}
}
private func timeToString(time: TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format: "Available in %02d:%02d:%02d", hours, minutes, seconds)
}
var description: String {
return type.title
}
var identifier: String {
return ("Activity \(number) " + description)
}
}
| mit | d3b8a06594e0baeab038c908d655a029 | 26.818182 | 114 | 0.602288 | 4.643399 | false | false | false | false |
ming1016/smck | smck/Lib/RxSwift/Zip+Collection.swift | 16 | 4753 | //
// Zip+Collection.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class ZipCollectionTypeSink<C: Collection, O: ObserverType>
: Sink<O> where C.Iterator.Element : ObservableConvertibleType {
typealias R = O.E
typealias Parent = ZipCollectionType<C, R>
typealias SourceElement = C.Iterator.Element.E
private let _parent: Parent
private let _lock = RecursiveLock()
// state
private var _numberOfValues = 0
private var _values: [Queue<SourceElement>]
private var _isDone: [Bool]
private var _numberOfDone = 0
private var _subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_values = [Queue<SourceElement>](repeating: Queue(capacity: 4), count: parent.count)
_isDone = [Bool](repeating: false, count: parent.count)
_subscriptions = Array<SingleAssignmentDisposable>()
_subscriptions.reserveCapacity(parent.count)
for _ in 0 ..< parent.count {
_subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceElement>, atIndex: Int) {
_lock.lock(); defer { _lock.unlock() } // {
switch event {
case .next(let element):
_values[atIndex].enqueue(element)
if _values[atIndex].count == 1 {
_numberOfValues += 1
}
if _numberOfValues < _parent.count {
let numberOfOthersThatAreDone = _numberOfDone - (_isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == _parent.count - 1 {
self.forwardOn(.completed)
self.dispose()
}
return
}
do {
var arguments = [SourceElement]()
arguments.reserveCapacity(_parent.count)
// recalculate number of values
_numberOfValues = 0
for i in 0 ..< _values.count {
arguments.append(_values[i].dequeue()!)
if _values[i].count > 0 {
_numberOfValues += 1
}
}
let result = try _parent.resultSelector(arguments)
self.forwardOn(.next(result))
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
if _isDone[atIndex] {
return
}
_isDone[atIndex] = true
_numberOfDone += 1
if _numberOfDone == _parent.count {
self.forwardOn(.completed)
self.dispose()
}
else {
_subscriptions[atIndex].dispose()
}
}
// }
}
func run() -> Disposable {
var j = 0
for i in _parent.sources {
let index = j
let source = i.asObservable()
let disposable = source.subscribe(AnyObserver { event in
self.on(event, atIndex: index)
})
_subscriptions[j].setDisposable(disposable)
j += 1
}
return Disposables.create(_subscriptions)
}
}
final class ZipCollectionType<C: Collection, R> : Producer<R> where C.Iterator.Element : ObservableConvertibleType {
typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R
let sources: C
let resultSelector: ResultSelector
let count: Int
init(sources: C, resultSelector: @escaping ResultSelector) {
self.sources = sources
self.resultSelector = resultSelector
self.count = Int(self.sources.count.toIntMax())
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R {
let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 2898293c3dff652e0a546fc6f0a038ee | 33.434783 | 139 | 0.506734 | 5.297659 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Client/QSAPI.swift | 1 | 13823 | //
// QSAPI.swift
// zhuishushenqi
//
// Created by yung on 2017/6/29.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
public protocol TargetType {
var baseURLString:String { get }
var path:String { get }
var parameters:[String:Any]? { get }
}
enum BaseType {
case normal
case chapter
}
enum QSAPI {
///首次进入根据性别推荐书籍
case genderRecommend(gender:String)
///追书书架信息
case shelfMSG(_ shelf:Any)
///书架更新信息
case update(id:String)
///热门搜索
case hotwords(_ shelf:Any)
///联想搜索
case autoComplete(query:String)
///搜索书籍
case searchBook(id:String,start:String,limit:String)
///排行榜
case ranking(_ shelf:Any)
///榜单数据
case rankList(id:String)
///分类
case category(_ shelf:Any)
///分类详细
case categoryList(gender:String,type:String,major:String,minor:String,start:String,limit:String)
///tag过滤
case tagType(_ shelf:Any)
///主题书单
case themeTopic(sort:String,duration:String,start:String,gender:String,tag:String)
///主题书单详细
case themeDetail(key:String)
///热门评论
case hotComment(key:String)
///普通评论
case normalComment(key:String,start:String,limit:String)
///热门动态
case hotUser(key:String)
///都是热门,忘记干嘛的了
case hotPost(key:String,start:String,limit:String)
///评论详情
case commentDetail(key:String)
///社区
case community(key:String,start:String)
///社区评论
case communityComment(key:String,start:String)
///所有来源
case allResource(key:String)
///所有章节
case allChapters(key:String)
///某一章节
case chapter(key:String,type:BaseType)
///书籍信息
case book(key:String)
///详情页热门评论
case bookHot(key:String)
///详情页可能感兴趣
case interested(key:String)
///详情页推荐书单
case recommend(key:String)
//随机看书
case mysteryBook(_ shelf:Any)
///登录
case login(idfa:String,platform_code:String,platform_token:String,platform_uid:String,version:String,tag:String)
///账户信息
case account(token:String)
///金币信息
case golden(token:String)
///账户详情
case userDetail(token:String)
///个人信息绑定账户
case userBind(token:String)
///退出登录
case logout(token:String)
///书架列表
case bookshelf(token:String)
///获取手机验证码
case SMSCode(mobile:String,Randstr:String,Ticket:String,captchaType:String,type:String)
///手机号登录
case mobileLogin(mobile:String,idfa:String,platform_code:String,smsCode:String,version:String)
///书架书籍删除
case booksheldDelete(books:String, token:String)
///书架书籍添加
case bookshelfAdd(books:String,token:String)
///用户昵称修改
case nicknameChange(nickname:String,token:String)
///
case blessing_bag(token:String)
///查询活动
case judgeSignIn(token:String)
///签到领金币
case signIn(token:String,activityId:String,version:String,type:String)
///编写评论
case reviewPost(token:String,id:String,content:String)
///已购章节信息
case boughtChapters(id:String,token:String)
///书架信息diff
case bookshelfdiff(books:String,token:String)
///追书券列表
case voucherList(token:String, type:String, start:Int, limit:Int)
}
extension QSAPI:TargetType{
var path: String {
var pathComponent = ""
switch self {
case .genderRecommend(_):
pathComponent = "/book/recommend"
break
case .shelfMSG(_):
pathComponent = "/notification/shelfMessage"
break
case .update(_):
pathComponent = "/book"
break
case .hotwords(_):
pathComponent = "/book/hot-word"
break
case .autoComplete(_):
pathComponent = "/book/auto-complete"
break
case .searchBook(_,_,_):
pathComponent = "/book/fuzzy-search"
break
case .ranking(_):
pathComponent = "/ranking/gender"
break
case let .rankList(id):
pathComponent = "/ranking/\(id)"
break
case .category(_):
pathComponent = "/cats/lv2/statistics"
break
case .categoryList(_,_,_,_,_,_):
pathComponent = "/book/by-categories"
break
case .tagType(_):
pathComponent = "/book-list/tagType"
break
case .themeTopic(_,_,_,_,_):
pathComponent = "/book-list"
break
case let .themeDetail(key):
pathComponent = "/book-list/\(key)"
break
case let .hotComment(key):
pathComponent = "/post/\(key)/comment/best"
break
case let .normalComment(key,_,_):
pathComponent = "/post/review/\(key)/comment"
break
case let .hotUser(key):
pathComponent = "/user/twitter/\(key)/comments"
break
case let .hotPost(key,_,_):
pathComponent = "/post/\(key)/comment"
break
case let .commentDetail(key):
pathComponent = "/post/review/\(key)"
break
case let .community(key,start):
pathComponent = "/post/by-book?book=\(key)&sort=updated&type=normal,vote&start=\(start)&limit=20"
break
case let .communityComment(key, start):
pathComponent = "/post/review/by-book?book=\(key)&sort=updated&start=\(start)&limit=20"
break
case .allResource(_):
pathComponent = "/toc"
break
case let .allChapters(key):
pathComponent = "/mix-toc/\(key)"
break
case let .chapter(key,_):
pathComponent = "/\(key)?k=22870c026d978c75&t=1489933049"
break
case let .book(key):
pathComponent = "/book/\(key)"
break
case let .bookHot(key):
pathComponent = "/post/review/best-by-book?book=\(key)"
break
case let .interested(key):
pathComponent = "/book/\(key)/recommend"
break
case let .recommend(key):
pathComponent = "/book-list/\(key)/recommend?limit=3"
break
case .mysteryBook(_):
pathComponent = "/book/mystery-box"
break
case .login(_,_,_,_,_,_):
pathComponent = "/user/login"
break
case .account(_):
pathComponent = "/user/account"
break
case .golden(_):
pathComponent = "/account"
break
case .userDetail(_):
pathComponent = "/user/detail-info"
break
case .userBind(_):
pathComponent = "/user/loginBind"
break
case .logout(_):
pathComponent = "/user/logout"
break
case .bookshelf(_):
pathComponent = "/v3/user/bookshelf"
break
case .SMSCode(_, _, _, _, _):
pathComponent = "/v2/sms/sendSms"
break
case .mobileLogin(_, _, _, _, _):
pathComponent = "/user/login"
break
case .booksheldDelete(_, _):
pathComponent = "/v3/user/bookshelf"
break
case .bookshelfAdd(_, _):
pathComponent = "/v3/user/bookshelf"
break
case .nicknameChange(_, _):
pathComponent = "/user/change-nickname"
break
case let .blessing_bag(token):
// https://goldcoin.zhuishushenqi.com/tasks/blessing-bag/detail?token=WupdmBZpkuzehCqdtDZF9IJR
pathComponent = "/tasks/blessing-bag/detail?token=\(token)"
break
// https://api.zhuishushenqi.com/user/v2/judgeSignIn?token=Abrv3NbHCuKKJSVzeSglLXns
case .judgeSignIn(_):
pathComponent = "/user/v2/judgeSignIn"
break
// https://api.zhuishushenqi.com/user/signIn?token=Abrv3NbHCuKKJSVzeSglLXns&activityId=57eb9278b7b0f6fc1f2e1bc0&version=2&type=2
case .signIn(_, _, _, _):
pathComponent = "/user/signIn"
break
case let .reviewPost(_,id,_):
// https://api.zhuishushenqi.com/post/review/5be2ac16f6459891448e9b46/comment
pathComponent = "/post/review/\(id)/comment"
break
case let .boughtChapters(id,_):
// https://api.zhuishushenqi.com/v2/purchase/book/5b10fd1b5d144d1b68581805/chapters/bought?token=rPcCW1GGh1hFPnSRJDjkwjtS
pathComponent = "/v2/purchase/book/\(id)/chapters/bought"
break
case .bookshelfdiff(_, _):
// https://api.zhuishushenqi.com/v3/user/bookshelf/diff
pathComponent = "/v3/user/bookshelf/diff"
break
case .voucherList(_, _, _, _):
pathComponent = "/voucher"
break
default:
break
}
return "\(baseURLString)\(pathComponent)"
}
var baseURLString: String{
var urlString = "http://api.zhuishushenqi.com"
switch self {
case let .chapter(_, type):
switch type {
case .chapter:
urlString = "http://chapter2.zhuishushenqi.com/chapter"
default:
urlString = "http://api.zhuishushenqi.com"
}
case .golden(_):
urlString = "http://goldcoin.zhuishushenqi.com"
case .blessing_bag(_):
urlString = "https://goldcoin.zhuishushenqi.com"
default:
urlString = "http://api.zhuishushenqi.com"
}
return urlString
}
var parameters: [String : Any]?{
switch self {
case let .genderRecommend(gender):
return ["gender":gender]
case let .update(id):
return ["view":"updated","id":id]
case let .autoComplete(query):
return ["query":query]
case let .searchBook(id,start,limit):
return ["query":id,"start":start,"limit":limit]
case .shelfMSG(_):
return ["platform":"ios"]
case let .categoryList(gender,type,major,minor,start,limit):
return ["gender":gender,"type":type,"major":major,"minor":minor,"start":start,"limit":limit]
case let .themeTopic(sort,duration,start,gender,tag):
return ["sort":sort,"duration":duration,"start":start,"gender":gender,"tag":tag]
case let .normalComment(_,start,limit):
return ["start":start,"limit":limit]
case let .hotPost(_,start,limit):
return ["start":start,"limit":limit]
case let .allResource(key):
return ["view":"summary","book":key]
case .allChapters(_):
return ["view":"chapters"]
case let .login(idfa, platform_code, platform_token, platform_uid, version, tag):
return ["idfa":idfa,
"platform_code":platform_code,
"platform_token":platform_token,
"platform_uid":platform_uid,
"version":version,
"tag":tag]
case let .account(token):
return ["token":token]
case let .golden(token):
return ["token":token]
case let .userDetail(token):
return ["token":token]
case let .userBind(token):
return ["token":token]
case let .logout(token):
return ["token":token]
case let .bookshelf(token):
return ["token":token]
case let .SMSCode(mobile,Randstr,Ticket,captchaType,type):
return ["mobile":mobile,
"Randstr":Randstr,
"Ticket":Ticket,
"captchaType":captchaType,
"type":type]
case let .mobileLogin(mobile, idfa, platform_code, smsCode, version):
return ["mobile":mobile,
"idfa":idfa,
"platform_code":platform_code,
"smsCode":smsCode,
"version":version]
case let .booksheldDelete(books, token):
return ["books":books,
"token":token]
case let .bookshelfAdd(books, token):
return ["books":books,
"token":token]
case let .nicknameChange(nickname,token):
return ["nickname":nickname,
"token":token]
case let .judgeSignIn(token):
return ["token":token]
case let .signIn(token, activityId, version, type):
return ["token": token,
"activityId": activityId,
"version": version,
"type": type]
case let .reviewPost(token, _, content):
return ["token":token,
"content":content]
case let .boughtChapters(_, token):
return ["token":token,
]
case let .bookshelfdiff(books, token):
return ["books":books,
"token":token]
case let .voucherList(token, type, start, limit):
return ["token":token,
"type":"\(type)",
"start":"\(start)",
"limit":"\(limit)"]
default:
return nil
}
}
}
//https://api.zhuishushenqi.com/v3/user/bookshelf?token=oRSd5bVUCpSunbwiKe5NOpOM
//https://api.zhuishushenqi.com/v2/purchase/book/5b10fd1b5d144d1b68581805/chapters/bought?token=rPcCW1GGh1hFPnSRJDjkwjtS
| mit | fa35a7fdc59f4c00f938af146eb09600 | 33.463918 | 143 | 0.554218 | 4.061968 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Private/ConcreteSession.swift | 1 | 7729 | import Foundation
class ConcreteSession: EurofurenceSession {
private let eventBus = EventBus()
private let sessionStateService: ConcreteSessionStateService
private let refreshService: ConcreteRefreshService
private let remoteNotificationRegistrationController: RemoteNotificationRegistrationController
private let authenticationService: ConcreteAuthenticationService
private let privateMessagesService: ConcretePrivateMessagesService
private let conventionCountdownService: ConcreteConventionCountdownService
private let announcementsRepository: ConcreteAnnouncementsRepository
private let knowledgeService: ConcreteKnowledgeService
private let scheduleRepository: ConcreteScheduleRepository
private let dealersService: ConcreteDealersService
private let significantTimeObserver: SignificantTimeObserver
private let collectThemAllService: ConcreteCollectThemAllService
private let mapsService: ConcreteMapsService
private let notificationService: ConcreteNotificationService
private let contentLinksService: ConcreteContentLinksService
private let additionalServicesRepository: ConcreteAdditionalServicesRepository
private let eventFeedbackService: EventFeedbackService
// swiftlint:disable function_body_length
init(
conventionIdentifier: ConventionIdentifier,
api: API,
userPreferences: UserPreferences,
dataStoreFactory: DataStoreFactory,
remoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration?,
clock: Clock,
credentialRepository: CredentialRepository,
conventionStartDateRepository: ConventionStartDateRepository,
timeIntervalForUpcomingEventsSinceNow: TimeInterval,
imageRepository: ImageRepository,
significantTimeChangeAdapter: SignificantTimeChangeAdapter?,
urlOpener: URLOpener?,
collectThemAllRequestFactory: CollectThemAllRequestFactory,
longRunningTaskManager: LongRunningTaskManager?,
mapCoordinateRender: MapCoordinateRender?,
forceRefreshRequired: ForceRefreshRequired,
companionAppURLRequestFactory: CompanionAppURLRequestFactory,
refreshCollaboration: RefreshCollaboration,
shareableURLFactory: ShareableURLFactory
) {
let dataStore = dataStoreFactory.makeDataStore(for: conventionIdentifier)
remoteNotificationRegistrationController = RemoteNotificationRegistrationController(
eventBus: eventBus,
remoteNotificationsTokenRegistration: remoteNotificationsTokenRegistration
)
privateMessagesService = ConcretePrivateMessagesService(eventBus: eventBus, api: api)
additionalServicesRepository = ConcreteAdditionalServicesRepository(
eventBus: eventBus,
companionAppURLRequestFactory: companionAppURLRequestFactory
)
authenticationService = ConcreteAuthenticationService(
eventBus: eventBus,
clock: clock,
credentialRepository: credentialRepository,
remoteNotificationsTokenRegistration: remoteNotificationsTokenRegistration,
api: api
)
conventionCountdownService = ConcreteConventionCountdownService(
eventBus: eventBus,
conventionStartDateRepository: conventionStartDateRepository,
clock: clock
)
announcementsRepository = ConcreteAnnouncementsRepository(
eventBus: eventBus,
dataStore: dataStore,
imageRepository: imageRepository
)
knowledgeService = ConcreteKnowledgeService(
eventBus: eventBus,
dataStore: dataStore,
imageRepository: imageRepository,
shareableURLFactory: shareableURLFactory
)
let imageCache = ImagesCache(
eventBus: eventBus,
imageRepository: imageRepository
)
scheduleRepository = ConcreteScheduleRepository(
eventBus: eventBus,
dataStore: dataStore,
imageCache: imageCache,
clock: clock,
timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow,
shareableURLFactory: shareableURLFactory
)
let imageDownloader = ImageDownloader(
eventBus: eventBus,
api: api,
imageRepository: imageRepository
)
significantTimeObserver = SignificantTimeObserver(
significantTimeChangeAdapter: significantTimeChangeAdapter,
eventBus: eventBus
)
dealersService = ConcreteDealersService(
eventBus: eventBus,
dataStore: dataStore,
imageCache: imageCache,
mapCoordinateRender: mapCoordinateRender,
shareableURLFactory: shareableURLFactory,
urlOpener: urlOpener
)
collectThemAllService = ConcreteCollectThemAllService(
eventBus: eventBus,
collectThemAllRequestFactory: collectThemAllRequestFactory,
credentialRepository: credentialRepository
)
mapsService = ConcreteMapsService(
eventBus: eventBus,
dataStore: dataStore,
imageRepository: imageRepository,
dealers: dealersService
)
let dataStoreBridge = DataStoreSyncBridge(
dataStore: dataStore,
clock: clock,
imageCache: imageCache,
imageRepository: imageRepository,
eventBus: eventBus
)
refreshService = ConcreteRefreshService(
conventionIdentifier: conventionIdentifier,
longRunningTaskManager: longRunningTaskManager,
dataStore: dataStore,
api: api,
imageDownloader: imageDownloader,
privateMessagesController: privateMessagesService,
forceRefreshRequired: forceRefreshRequired,
refreshCollaboration: refreshCollaboration,
dataStoreBridge: dataStoreBridge
)
notificationService = ConcreteNotificationService(eventBus: eventBus)
let urlEntityProcessor = URLEntityProcessor(
eventsService: scheduleRepository,
dealersService: dealersService, dataStore: dataStore
)
contentLinksService = ConcreteContentLinksService(urlEntityProcessor: urlEntityProcessor)
eventFeedbackService = EventFeedbackService(api: api, eventBus: eventBus)
sessionStateService = ConcreteSessionStateService(
eventBus: eventBus,
forceRefreshRequired: forceRefreshRequired,
userPreferences: userPreferences,
dataStore: dataStore
)
privateMessagesService.refreshMessages()
}
lazy var services = Services(
notifications: notificationService,
refresh: refreshService,
authentication: authenticationService,
dealers: dealersService,
knowledge: knowledgeService,
contentLinks: contentLinksService,
conventionCountdown: conventionCountdownService,
collectThemAll: collectThemAllService,
maps: mapsService,
sessionState: sessionStateService,
privateMessages: privateMessagesService
)
lazy var repositories = Repositories(
additionalServices: additionalServicesRepository,
announcements: announcementsRepository,
events: scheduleRepository
)
}
| mit | 4f74479efc0019f8b760a206435d1317 | 37.839196 | 98 | 0.688058 | 7.333017 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYStickersEditorViewController.swift | 1 | 10312 | //
// IMGLYStickersEditorViewController.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 10/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
let StickersCollectionViewCellSize = CGSize(width: 90, height: 90)
let StickersCollectionViewCellReuseIdentifier = "StickersCollectionViewCell"
public class IMGLYStickersEditorViewController: IMGLYSubEditorViewController {
// MARK: - Properties
public let stickersDataSource = IMGLYStickersDataSource()
public private(set) lazy var stickersClipView: UIView = {
let view = UIView()
view.clipsToBounds = true
return view
}()
private var draggedView: UIView?
// MARK: - SubEditorViewController
public override func tappedDone(sender: UIBarButtonItem?) {
var addedStickers = false
for view in stickersClipView.subviews as! [UIView] {
if let view = view as? UIImageView {
if let image = view.image {
let stickerFilter = IMGLYInstanceFactory.stickerFilter()
stickerFilter.sticker = image
let center = CGPoint(x: view.center.x / stickersClipView.frame.size.width, y: view.center.y / stickersClipView.frame.size.height)
var size = initialSizeForStickerImage(image)
size.width = size.width / stickersClipView.bounds.size.width
size.height = size.height / stickersClipView.bounds.size.height
stickerFilter.center = center
stickerFilter.size = size
stickerFilter.transform = view.transform
fixedFilterStack.stickerFilters.append(stickerFilter)
addedStickers = true
}
}
}
if addedStickers {
updatePreviewImageWithCompletion {
self.stickersClipView.removeFromSuperview()
super.tappedDone(sender)
}
} else {
super.tappedDone(sender)
}
}
// MARK: - Helpers
private func initialSizeForStickerImage(image: UIImage) -> CGSize {
let initialMaxStickerSize = CGRectGetWidth(stickersClipView.bounds) * 0.3
let widthRatio = initialMaxStickerSize / image.size.width
let heightRatio = initialMaxStickerSize / image.size.height
let scale = min(widthRatio, heightRatio)
return CGSize(width: image.size.width * scale, height: image.size.height * scale)
}
// MARK: - UIViewController
override public func viewDidLoad() {
super.viewDidLoad()
let bundle = NSBundle(forClass: self.dynamicType)
navigationItem.title = NSLocalizedString("stickers-editor.title", tableName: nil, bundle: bundle, value: "", comment: "")
configureStickersCollectionView()
configureStickersClipView()
configureGestureRecognizers()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
stickersClipView.frame = view.convertRect(previewImageView.visibleImageFrame, fromView: previewImageView)
}
// MARK: - Configuration
private func configureStickersCollectionView() {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = StickersCollectionViewCellSize
flowLayout.scrollDirection = .Horizontal
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 10
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
collectionView.dataSource = stickersDataSource
collectionView.delegate = self
collectionView.registerClass(IMGLYStickerCollectionViewCell.self, forCellWithReuseIdentifier: StickersCollectionViewCellReuseIdentifier)
let views = [ "collectionView" : collectionView ]
bottomContainerView.addSubview(collectionView)
bottomContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[collectionView]|", options: nil, metrics: nil, views: views))
bottomContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[collectionView]|", options: nil, metrics: nil, views: views))
}
private func configureStickersClipView() {
view.addSubview(stickersClipView)
}
private func configureGestureRecognizers() {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "panned:")
panGestureRecognizer.minimumNumberOfTouches = 1
panGestureRecognizer.maximumNumberOfTouches = 1
stickersClipView.addGestureRecognizer(panGestureRecognizer)
let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: "pinched:")
pinchGestureRecognizer.delegate = self
stickersClipView.addGestureRecognizer(pinchGestureRecognizer)
let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: "rotated:")
rotationGestureRecognizer.delegate = self
stickersClipView.addGestureRecognizer(rotationGestureRecognizer)
}
// MARK: - Gesture Handling
@objc private func panned(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(stickersClipView)
let translation = recognizer.translationInView(stickersClipView)
switch recognizer.state {
case .Began:
draggedView = stickersClipView.hitTest(location, withEvent: nil) as? UIImageView
if let draggedView = draggedView {
stickersClipView.bringSubviewToFront(draggedView)
}
case .Changed:
if let draggedView = draggedView {
draggedView.center = CGPoint(x: draggedView.center.x + translation.x, y: draggedView.center.y + translation.y)
}
recognizer.setTranslation(CGPointZero, inView: stickersClipView)
case .Cancelled, .Ended:
draggedView = nil
default:
break
}
}
@objc private func pinched(recognizer: UIPinchGestureRecognizer) {
if recognizer.numberOfTouches() == 2 {
let point1 = recognizer.locationOfTouch(0, inView: stickersClipView)
let point2 = recognizer.locationOfTouch(1, inView: stickersClipView)
let midpoint = CGPoint(x:(point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2)
let scale = recognizer.scale
switch recognizer.state {
case .Began:
if draggedView == nil {
draggedView = stickersClipView.hitTest(midpoint, withEvent: nil) as? UIImageView
}
if let draggedView = draggedView {
stickersClipView.bringSubviewToFront(draggedView)
}
case .Changed:
if let draggedView = draggedView {
draggedView.transform = CGAffineTransformScale(draggedView.transform, scale, scale)
}
recognizer.scale = 1
case .Cancelled, .Ended:
draggedView = nil
default:
break
}
}
}
@objc private func rotated(recognizer: UIRotationGestureRecognizer) {
if recognizer.numberOfTouches() == 2 {
let point1 = recognizer.locationOfTouch(0, inView: stickersClipView)
let point2 = recognizer.locationOfTouch(1, inView: stickersClipView)
let midpoint = CGPoint(x:(point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2)
let rotation = recognizer.rotation
switch recognizer.state {
case .Began:
if draggedView == nil {
draggedView = stickersClipView.hitTest(midpoint, withEvent: nil) as? UIImageView
}
if let draggedView = draggedView {
stickersClipView.bringSubviewToFront(draggedView)
}
case .Changed:
if let draggedView = draggedView {
draggedView.transform = CGAffineTransformRotate(draggedView.transform, rotation)
}
recognizer.rotation = 0
case .Cancelled, .Ended:
draggedView = nil
default:
break
}
}
}
}
extension IMGLYStickersEditorViewController: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let sticker = stickersDataSource.stickers[indexPath.row]
let imageView = UIImageView(image: sticker.image)
imageView.userInteractionEnabled = true
imageView.frame.size = initialSizeForStickerImage(sticker.image)
imageView.center = CGPoint(x: CGRectGetMidX(stickersClipView.bounds), y: CGRectGetMidY(stickersClipView.bounds))
stickersClipView.addSubview(imageView)
imageView.transform = CGAffineTransformMakeScale(0, 0)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
imageView.transform = CGAffineTransformIdentity
}, completion: nil)
}
}
extension IMGLYStickersEditorViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if (gestureRecognizer is UIPinchGestureRecognizer && otherGestureRecognizer is UIRotationGestureRecognizer) || (gestureRecognizer is UIRotationGestureRecognizer && otherGestureRecognizer is UIPinchGestureRecognizer) {
return true
}
return false
}
} | apache-2.0 | ae6ed58d0e24bb06fdf9f33b70d4607b | 41.266393 | 225 | 0.641777 | 5.950375 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYFilterCollectionViewCell.swift | 1 | 2611 | //
// IMGLYFilterCollectionViewCell.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 08/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
class IMGLYFilterCollectionViewCell: IMGLYImageCaptionCollectionViewCell {
// MARK: - Properties
lazy var activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView()
view.hidesWhenStopped = true
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}()
lazy var tickImageView: UIImageView = {
let imageView = UIImageView()
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
imageView.contentMode = .Center
imageView.alpha = 0
imageView.image = UIImage(named: "icon_tick", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection:nil)
return imageView
}()
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
configureViews()
}
// MARK: - Configuration
func showTick() {
tickImageView.alpha = 1
imageView.alpha = 0.4
}
func hideTick() {
tickImageView.alpha = 0
imageView.alpha = 1
}
// MARK: - Helpers
private func configureViews() {
imageView.addSubview(activityIndicator)
imageView.addSubview(tickImageView)
let views = [
"tickImageView" : tickImageView
]
imageView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[tickImageView]|", options: nil, metrics: nil, views: views))
imageView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[tickImageView]|", options: nil, metrics: nil, views: views))
imageView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: imageView, attribute: .CenterX, multiplier: 1, constant: 0))
imageView.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: imageView, attribute: .CenterY, multiplier: 1, constant: 0))
}
// MARK: - ImageCaptionCollectionViewCell
override var imageSize: CGSize {
return CGSize(width: 56, height: 56)
}
override var imageCaptionMargin: CGFloat {
return 3
}
}
| apache-2.0 | 6f63192d84bde75683b356c5ca1aebb0 | 30.083333 | 184 | 0.652241 | 5.211577 | false | false | false | false |
brave/browser-ios | brave/src/frontend/BraveTermsViewController.swift | 1 | 7547 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Foundation
protocol BraveTermsViewControllerDelegate {
func braveTermsAcceptedTermsAndOptIn() -> Void
func braveTermsAcceptedTermsAndOptOut() -> Void
}
class BraveTermsViewController: UIViewController {
var delegate: BraveTermsViewControllerDelegate?
fileprivate var braveLogo: UIImageView!
fileprivate var termsLabel: UITextView!
fileprivate var optLabel: UILabel!
fileprivate var checkButton: UIButton!
fileprivate var continueButton: UIButton!
override func loadView() {
super.loadView()
braveLogo = UIImageView(image: UIImage(named: "braveLogoLarge"))
braveLogo.contentMode = .center
view.addSubview(braveLogo)
termsLabel = UITextView()
termsLabel.backgroundColor = UIColor.clear
termsLabel.isScrollEnabled = false
termsLabel.isSelectable = true
termsLabel.isEditable = false
termsLabel.dataDetectorTypes = [.all]
let attributedString = NSMutableAttributedString(string: NSLocalizedString("By using this application, you agree to Brave’s Terms of Use.", comment: ""))
let linkRange = (attributedString.string as NSString).range(of: NSLocalizedString("Terms of Use.", comment: ""))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let fontAttributes = [
NSAttributedStringKey.foregroundColor: UIColor.white,
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.medium),
NSAttributedStringKey.paragraphStyle: paragraphStyle ]
attributedString.addAttributes(fontAttributes, range: NSMakeRange(0, (attributedString.string.characters.count - 1)))
attributedString.addAttribute(NSAttributedStringKey.link, value: "https://brave.com/terms_of_use.html", range: linkRange)
let linkAttributes = [
NSAttributedStringKey.foregroundColor.rawValue: UIColor(red: 255/255.0, green: 80/255.0, blue: 0/255.0, alpha: 1.0) ]
termsLabel.linkTextAttributes = linkAttributes
termsLabel.attributedText = attributedString
termsLabel.delegate = self
view.addSubview(termsLabel)
optLabel = UILabel()
optLabel.text = NSLocalizedString("Help make Brave better by sending usage statistics and crash reports to us.", comment: "")
optLabel.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.medium)
optLabel.textColor = UIColor(white: 1.0, alpha: 0.5)
optLabel.numberOfLines = 0
optLabel.lineBreakMode = .byWordWrapping
view.addSubview(optLabel)
checkButton = UIButton(type: .custom)
checkButton.setImage(UIImage(named: "sharedata_uncheck"), for: .normal)
checkButton.setImage(UIImage(named: "sharedata_check"), for: .selected)
checkButton.addTarget(self, action: #selector(checkUncheck(_:)), for: .touchUpInside)
checkButton.isSelected = true
view.addSubview(checkButton)
continueButton = UIButton(type: .system)
continueButton.titleLabel?.font = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.medium)
continueButton.setTitle(NSLocalizedString("Accept & Continue", comment: ""), for: .normal)
continueButton.setTitleColor(UIColor.white, for: .normal)
continueButton.addTarget(self, action: #selector(acceptAndContinue(_:)), for: .touchUpInside)
continueButton.backgroundColor = UIColor(red: 255/255.0, green: 80/255.0, blue: 0/255.0, alpha: 1.0)
continueButton.layer.cornerRadius = 4.5
continueButton.layer.masksToBounds = true
view.addSubview(continueButton)
continueButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.bottom.equalTo(self.view).offset(-30)
make.height.equalTo(40)
let width = self.continueButton.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).width
make.width.equalTo(width + 40)
}
optLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view).offset(36/2)
let width = min(UIScreen.main.bounds.width * 0.65, 350)
make.width.equalTo(width)
if UIDevice.current.userInterfaceIdiom == .pad {
make.bottom.equalTo(continueButton.snp.top).offset(-60).priorityHigh()
}
else {
make.bottom.lessThanOrEqualTo(continueButton.snp.top).offset(-60).priorityHigh()
}
}
checkButton.snp.makeConstraints { (make) in
make.left.equalTo(optLabel.snp.left).offset(-36)
make.top.equalTo(optLabel.snp.top).offset(4).priorityHigh()
}
termsLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
let width = min(UIScreen.main.bounds.width * 0.70, 350)
make.width.equalTo(width)
make.bottom.equalTo(optLabel.snp.top).offset(-35).priorityMedium()
}
braveLogo.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.top.equalTo(10)
if UIDevice.current.userInterfaceIdiom == .pad {
make.bottom.equalTo(termsLabel.snp.top)
}
else {
make.height.equalTo(UIScreen.main.bounds.width > UIScreen.main.bounds.height ? UIScreen.main.bounds.height : UIScreen.main.bounds.width)
}
}
view.backgroundColor = UIColor(red: 63/255.0, green: 63/255.0, blue: 63/255.0, alpha: 1.0)
}
// override var prefersStatusBarHidden : Bool {
// return true
// }
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
if UIDevice.current.userInterfaceIdiom == .pad {
return
}
if toInterfaceOrientation == .landscapeLeft || toInterfaceOrientation == .landscapeRight {
UIView.animate(withDuration: 0.2, animations: {
self.braveLogo.alpha = 0.15
})
}
else {
UIView.animate(withDuration: 0.2, animations: {
self.braveLogo.alpha = 1.0
})
}
self.view.setNeedsUpdateConstraints()
}
// MARK: Actions
@objc func checkUncheck(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
@objc func acceptAndContinue(_ sender: UIButton) {
if checkButton.isSelected {
delegate?.braveTermsAcceptedTermsAndOptIn()
}
else {
delegate?.braveTermsAcceptedTermsAndOptOut()
}
dismiss(animated: false, completion: nil)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)?) {
super.dismiss(animated: flag, completion: completion)
}
}
extension BraveTermsViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
return true
}
}
| mpl-2.0 | a274de4109b75d9ba28902f0618ac9d6 | 40.685083 | 198 | 0.639231 | 4.766267 | false | false | false | false |
huyphung1602/MyTip | MyTip/MyTip/FirstScreen.swift | 1 | 1388 | //
// FirstScreen.swift
// MyTip
//
// Created by Quoc Huy on 9/25/16.
// Copyright © 2016 Huy Phung. All rights reserved.
//
import UIKit
class FirstScreen: UIViewController {
@IBOutlet weak var background_firstview: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Apply current seletected theme
let defaults = NSUserDefaults.standardUserDefaults()
let checkNil = defaults.objectForKey("theme_flag")
if checkNil != nil {
let themeFlag = Int(defaults.objectForKey("theme_flag") as! NSNumber)
if (themeFlag == 0) {
background_firstview.image = image1
} else {
background_firstview.image = image2
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 4f2a8cd9025fea896f53075c04cabd58 | 27.306122 | 106 | 0.62509 | 4.883803 | false | false | false | false |
KyoheiG3/RxSwift | RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift | 8 | 7462 | //
// PartialUpdatesViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 6/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
let generateCustomSize = true
let runAutomatically = false
let useAnimatedUpdateForCollectionView = false
/**
Code for reactive data sources is packed in [RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) project.
*/
class PartialUpdatesViewController : ViewController {
@IBOutlet weak var reloadTableViewOutlet: UITableView!
@IBOutlet weak var partialUpdatesTableViewOutlet: UITableView!
@IBOutlet weak var partialUpdatesCollectionViewOutlet: UICollectionView!
var timer: Foundation.Timer? = nil
static let initialValue: [AnimatableSectionModel<String, Int>] = [
NumberSection(model: "section 1", items: [1, 2, 3]),
NumberSection(model: "section 2", items: [4, 5, 6]),
NumberSection(model: "section 3", items: [7, 8, 9]),
NumberSection(model: "section 4", items: [10, 11, 12]),
NumberSection(model: "section 5", items: [13, 14, 15]),
NumberSection(model: "section 6", items: [16, 17, 18]),
NumberSection(model: "section 7", items: [19, 20, 21]),
NumberSection(model: "section 8", items: [22, 23, 24]),
NumberSection(model: "section 9", items: [25, 26, 27]),
NumberSection(model: "section 10", items: [28, 29, 30])
]
static let firstChange: [AnimatableSectionModel<String, Int>]? = nil
var generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue)
var sections = Variable([NumberSection]())
/**
Code for reactive data sources is packed in [RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) project.
*/
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem?.accessibilityLabel = "Randomize"
// For UICollectionView, if another animation starts before previous one is finished, it will sometimes crash :(
// It's not deterministic (because Randomizer generates deterministic updates), and if you click fast
// It sometimes will and sometimes wont crash, depending on tapping speed.
// I guess you can maybe try some tricks with timeout, hard to tell :( That's on Apple side.
if generateCustomSize {
let nSections = UIApplication.isInUITest ? 10 : 10
let nItems = UIApplication.isInUITest ? 20 : 100
var sections = [AnimatableSectionModel<String, Int>]()
for i in 0 ..< nSections {
sections.append(AnimatableSectionModel(model: "Section \(i + 1)", items: Array(i * nItems ..< (i + 1) * nItems)))
}
generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: sections)
}
#if runAutomatically
timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "randomize", userInfo: nil, repeats: true)
#endif
self.sections.value = generator.sections
let tvAnimatedDataSource = RxTableViewSectionedAnimatedDataSource<NumberSection>()
let reloadDataSource = RxTableViewSectionedReloadDataSource<NumberSection>()
skinTableViewDataSource(tvAnimatedDataSource)
skinTableViewDataSource(reloadDataSource)
self.sections.asObservable()
.bindTo(partialUpdatesTableViewOutlet.rx.items(dataSource: tvAnimatedDataSource))
.addDisposableTo(disposeBag)
self.sections.asObservable()
.bindTo(reloadTableViewOutlet.rx.items(dataSource: reloadDataSource))
.addDisposableTo(disposeBag)
// Collection view logic works, but when clicking fast because of internal bugs
// collection view will sometimes get confused. I know what you are thinking,
// but this is really not a bug in the algorithm. The generated changes are
// pseudorandom, and crash happens depending on clicking speed.
//
// More info in `RxDataSourceStarterKit/README.md`
//
// If you want, turn this to true, just click slow :)
//
// While `useAnimatedUpdateForCollectionView` is false, you can click as fast as
// you want, table view doesn't seem to have same issues like collection view.
#if useAnimatedUpdateForCollectionView
let cvAnimatedDataSource = RxCollectionViewSectionedAnimatedDataSource<NumberSection>()
skinCollectionViewDataSource(cvAnimatedDataSource)
updates
.bindTo(partialUpdatesCollectionViewOutlet.rx.itemsWithDataSource(cvAnimatedDataSource))
.addDisposableTo(disposeBag)
#else
let cvReloadDataSource = RxCollectionViewSectionedReloadDataSource<NumberSection>()
skinCollectionViewDataSource(cvReloadDataSource)
self.sections.asObservable()
.bindTo(partialUpdatesCollectionViewOutlet.rx.items(dataSource: cvReloadDataSource))
.addDisposableTo(disposeBag)
#endif
// touches
partialUpdatesCollectionViewOutlet.rx.itemSelected
.subscribe(onNext: { [weak self] i in
print("Let me guess, it's .... It's \(self?.generator.sections[i.section].items[i.item]), isn't it? Yeah, I've got it.")
})
.addDisposableTo(disposeBag)
Observable.of(partialUpdatesTableViewOutlet.rx.itemSelected, reloadTableViewOutlet.rx.itemSelected)
.merge()
.subscribe(onNext: { [weak self] i in
print("I have a feeling it's .... \(self?.generator.sections[i.section].items[i.item])?")
})
.addDisposableTo(disposeBag)
}
func skinTableViewDataSource(_ dataSource: TableViewSectionedDataSource<NumberSection>) {
dataSource.configureCell = { (_, tv, ip, i) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")
?? UITableViewCell(style:.default, reuseIdentifier: "Cell")
cell.textLabel!.text = "\(i)"
return cell
}
dataSource.titleForHeaderInSection = { (ds, section: Int) -> String in
return dataSource[section].model
}
}
func skinCollectionViewDataSource(_ dataSource: CollectionViewSectionedDataSource<NumberSection>) {
dataSource.configureCell = { (_, cv, ip, i) in
let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: ip) as! NumberCell
cell.value!.text = "\(i)"
return cell
}
dataSource.supplementaryViewFactory = { (dataSource, cv, kind, ip) in
let section = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Section", for: ip) as! NumberSectionView
section.value!.text = "\(dataSource[ip.section].model)"
return section
}
}
override func viewWillDisappear(_ animated: Bool) {
self.timer?.invalidate()
}
@IBAction func randomize() {
generator.randomize()
var values = generator.sections
// useful for debugging
if PartialUpdatesViewController.firstChange != nil {
values = PartialUpdatesViewController.firstChange!
}
//print(values)
sections.value = values
}
}
| mit | edfe806f04eaf969a55a8e605d54aa97 | 38.268421 | 138 | 0.659831 | 5.027628 | false | false | false | false |
Holmusk/HMRequestFramework-iOS | HMRequestFramework/database/coredata/stack/HMCDManager+Version+Rx.swift | 1 | 8757 | //
// HMCDManager+Version+Rx.swift
// HMRequestFramework
//
// Created by Hai Pham on 8/9/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import CoreData
import RxSwift
import SwiftUtilities
// Just a bit of utility here, not going to expose publicly.
fileprivate extension HMVersionUpdateRequest where VC == HMCDVersionableType {
/// Check if the current request possesses an edited object.
///
/// - Parameter obj: A HMCDIdentifiableType instance.
/// - Returns: A Bool value.
fileprivate func ownsEditedVC(_ obj: HMCDIdentifiableType) -> Bool {
return (try? editedVC().identifiable(as: obj)) ?? false
}
}
public extension HMCDManager {
/// Resolve version conflict using the specified strategy. This operation
/// is not thread-safe.
///
/// - Parameters:
/// - context: A Context instance.
/// - request: A HMVersionUpdateRequest instance.
/// - Throws: Exception if the operation fails.
func resolveVersionConflictUnsafely(_ context: Context,
_ request: HMCDVersionUpdateRequest) throws
{
let original = try request.originalVC()
let edited = try request.editedVC()
switch request.conflictStrategy() {
case .error:
throw VersionConflict.Exception.builder()
.with(editedRepr: edited.stringRepresentationForResult())
.with(originalRepr: original.stringRepresentationForResult())
.with(existingVersion: original.currentVersion())
.with(conflictVersion: edited.currentVersion())
.build()
case .merge(let fn):
try fn?(edited, original) ?? edited.mergeWithOriginalVersion(original)
try attempVersionUpdateUnsafely(context, request)
case .overwrite:
try attempVersionUpdateUnsafely(context, request)
case .takePreferable:
if try edited.hasPreferableVersion(over: original) {
try attempVersionUpdateUnsafely(context, request)
}
}
}
/// Perform version update and delete existing object in the DB. This step
/// assumes that version comparison has been carried out and all conflicts
/// have been resolved.
///
/// This operation is not thread-safe.
///
/// - Parameters:
/// - context: A Context instance.
/// - request: A HMCDVersionUpdateRequest instance.
/// - Throws: Exception if the operation fails.
func attempVersionUpdateUnsafely(_ context: Context,
_ request: HMCDVersionUpdateRequest) throws
{
let original = try request.originalVC()
let edited = try request.editedVC()
let newVersion = edited.oneVersionHigher()
// The original object should be managed by the parameter context.
// We update the original object by mutating it - under other circumstances,
// this is not recommended.
try original.update(from: edited)
try original.updateVersion(newVersion)
}
/// Update some object with version bump. Resolve any conflict if necessary.
/// This operation is not thread-safe.
///
/// - Parameters:
/// - context: A Context instance.
/// - request: A HMVersionUpdateRequest instance.
/// - Throws: Exception if the operation fails.
func updateVersionUnsafely(_ context: Context,
_ request: HMCDVersionUpdateRequest) throws {
let originalVersion = try request.originalVC().currentVersion()
let editedVersion = try request.editedVC().currentVersion()
if originalVersion == editedVersion {
try attempVersionUpdateUnsafely(context, request)
} else {
try resolveVersionConflictUnsafely(context, request)
}
}
}
public extension HMCDManager {
/// Perform update on the identifiables, insert them into the specified
/// context and and get the results back.
///
/// - Parameters:
/// - context: A Context instance.
/// - entityName: A String value representing the entity's name.
/// - requests: A Sequence of HMVersionUpdateRequest.
/// - Throws: Exception if the operation fails.
func convert<S>(_ context: Context,
_ entityName: String,
_ requests: S) throws -> [HMCDResult] where
S: Sequence, S.Element == HMCDVersionUpdateRequest
{
var requests = requests.sorted(by: {$0.compare(against: $1)})
// It's ok for these requests not to have the original object. We will
// get them right below.
let versionables = requests.flatMap({try? $0.editedVC()})
let ids = versionables as [HMCDIdentifiableType]
var originals = try self.blockingFetchIdentifiables(context, entityName, ids)
var results: [HMCDResult] = []
// We also need an Array of VC to store items that cannot be found in
// the DB yet.
var nonExisting: [HMCDObjectConvertibleType] = []
for item in versionables {
if
let oIndex = originals.index(where: item.identifiable),
let rIndex = requests.index(where: {($0.ownsEditedVC(item))}),
let original = originals.element(at: oIndex),
let request = requests.element(at: rIndex)?
.cloneBuilder()
// The cast here is unfortunate, but we have to do it to
// avoid having to define a concrete class that extends
// NSManagedObject and implements HMCDVersionableType.
// When the object is fetched from database, it retains its
// original type (thanks to entityName), but is masked under
// NSManagedObject. We should expect it to be a subtype of
// HMCDVersionableType.
.with(original: original as? HMCDVersionableType)
.build()
{
let result: HMCDResult
let representation = item.stringRepresentationForResult()
do {
try self.updateVersionUnsafely(context, request)
result = HMCDResult.just(representation)
} catch let e {
result = HMCDResult.builder()
.with(object: representation)
.with(error: e)
.build()
}
results.append(result)
originals.remove(at: oIndex)
requests.remove(at: rIndex)
} else {
nonExisting.append(item)
}
}
// For items that do not exist in the DB yet, simply save them. Since
// these objects are convertible, we can reconstruct them as NSManagedObject
// instances and insert into the specified context.
results.append(contentsOf: convert(context, nonExisting))
return results
}
}
public extension HMCDManager {
/// Update a Sequence of versioned objects and save to memory. It is better
/// not to call this method on too many objects, because context.save()
/// will be called just as many times.
///
/// - Parameters:
/// - context: A Context instance.
/// - entityName: A String value representing the entity's name.
/// - requests: A Sequence of HMVersionUpdateRequest.
/// - opMode: A HMCDOperationMode instance.
/// - obs: An ObserverType instance.
/// - Returns: A Disposable instance.
func updateVersion<S,O>(_ context: Context,
_ entityName: String,
_ requests: S,
_ opMode: HMCDOperationMode,
_ obs: O) -> Disposable where
S: Sequence,
S.Element == HMCDVersionUpdateRequest,
O: ObserverType,
O.E == [HMCDResult]
{
Preconditions.checkNotRunningOnMainThread(requests)
performOperation(opMode, {
let requests = requests.map({$0})
if !requests.isEmpty {
do {
let results = try self.convert(context, entityName, requests)
try self.saveUnsafely(context)
obs.onNext(results)
obs.onCompleted()
} catch let e {
obs.onError(e)
}
} else {
obs.onNext([])
obs.onCompleted()
}
})
return Disposables.create()
}
}
extension Reactive where Base == HMCDManager {
/// Update a Sequence of versioned objects and save to memory.
///
/// - Parameters:
/// - context: A Context instance.
/// - entityName: A String value representing the entity's name.
/// - requests: A Sequence of HMVersionUpdateRequest.
/// - opMode: A HMCDOperationMode instance.
/// - Return: An Observable instance.
/// - Throws: Exception if the operation fails.
public func updateVersion<S>(_ context: HMCDManager.Context,
_ entityName: String,
_ requests: S,
_ opMode: HMCDOperationMode = .queued)
-> Observable<[HMCDResult]> where
S: Sequence, S.Element == HMCDVersionUpdateRequest
{
return Observable.create({
self.base.updateVersion(context, entityName, requests, opMode, $0)
})
}
}
| apache-2.0 | 97dd94ddfe96dc105af9448dd631311d | 33.746032 | 81 | 0.645614 | 4.532091 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK | LGKKCoreLib/LGKKCoreLib/CoreUI/SPBaseTabBarViewController.swift | 1 | 1649 | //
// SPBaseTabBarViewController.swift
// drivethrough
//
// Created by Duc iOS on 3/17/17.
// Copyright © 2017 SP. All rights reserved.
//
import UIKit
open class SPBaseTabBarViewController: UITabBarController {
open func goto(classVC: AnyClass, animated: Bool) {
if let arrayVc = self.viewControllers {
// BFS
for (index, vc) in arrayVc.enumerated() {
if vc.isKind(of: classVC) {
self.selectedIndex = index
return
}
}
for (index, vc) in arrayVc.enumerated() {
if let vc = vc as? UINavigationController {
for vcLv1 in vc.viewControllers {
if vcLv1.isKind(of: classVC) {
self.selectedIndex = index
vc.popToViewController(vcLv1, animated: animated)
return
}
}
} else if let vc = vc as? UIPageViewController {
if let arrayLv1 = vc.viewControllers {
for vcLv1 in arrayLv1 {
if vcLv1.isKind(of: classVC) {
self.selectedIndex = index
vc.setViewControllers([vcLv1], direction: .forward, animated: animated, completion: nil)
return
}
}
}
}
}
} else {
print("Invalid viewcontroller class")
}
}
}
| mit | 35c3a5b94c5c73bdecf0ceeb23ef1172 | 33.333333 | 120 | 0.442354 | 5.438944 | false | false | false | false |
CharlesVu/Smart-iPad | MKHome/Settings/CityChooserViewController.swift | 1 | 3023 | //
// CityChooserTableViewController.swift
// MKHome
//
// Created by Charles Vu on 24/12/2016.
// Copyright © 2016 charles. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import Persistance
class CityChooserViewController: UIViewController {
@IBOutlet var searchBar: UISearchBar?
@IBOutlet var tableView: UITableView?
@IBOutlet var spinner: UIActivityIndicatorView?
fileprivate let appSettings = NationalRail.AppData.sharedInstance
fileprivate var searchResults: [CLPlacemark] = []
fileprivate let geocoder = CLGeocoder()
func lookup(name: String, completion: @escaping (Error?, [CLPlacemark]?) -> Void) {
geocoder.cancelGeocode()
spinner?.startAnimating()
geocoder.geocodeAddressString(name) { (placemarks, error) in
self.spinner?.stopAnimating()
if error != nil {
completion(error, nil)
} else {
completion(nil, placemarks)
}
}
}
}
extension CityChooserViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let placemark = searchResults[indexPath.row]
if let name = placemark.name,
let coordinate = placemark.location?.coordinate {
UserSettings.sharedInstance.weather.addCity(WeatherCity(name: name,
longitude: coordinate.longitude,
latitude: coordinate.latitude))
}
_ = self.navigationController?.popViewController(animated: true)
}
}
extension CityChooserViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let placemark = searchResults[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CityCell")!
cell.textLabel?.text = placemark.name! + ", " + placemark.country!
if UIDevice.current.userInterfaceIdiom == .pad {
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = .zero
cell.separatorInset = .zero
}
return cell
}
}
extension CityChooserViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText != "" {
lookup(name: searchText, completion: { (_, placemarks) in
if let placemarks = placemarks {
self.searchResults = placemarks
} else {
self.searchResults.removeAll()
}
self.tableView?.reloadData()
})
} else {
searchResults = []
self.tableView?.reloadData()
}
}
}
| mit | 514c03fb26aa6022ce5f3d9d6764f6d7 | 31.847826 | 100 | 0.615156 | 5.596296 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Settings/FxAContentViewController.swift | 1 | 10029 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import SnapKit
import UIKit
import WebKit
import SwiftyJSON
protocol FxAContentViewControllerDelegate: AnyObject {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags: FxALoginFlags)
func contentViewControllerDidCancel(_ viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
fileprivate enum RemoteCommand: String {
case canLinkAccount = "can_link_account"
case loaded = "loaded"
case login = "login"
case changePassword = "change_password"
case sessionStatus = "session_status"
case signOut = "sign_out"
}
weak var delegate: FxAContentViewControllerDelegate?
let profile: Profile
init(profile: Profile, fxaOptions: FxALaunchParams? = nil) {
self.profile = profile
super.init(backgroundColor: UIColor.Photon.Grey20, title: NSAttributedString(string: "Firefox Accounts"))
self.url = self.createFxAURLWith(fxaOptions, profile: profile)
NotificationCenter.default.addObserver(self, selector: #selector(userDidVerify), name: .FirefoxAccountVerified, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
profile.getAccount()?.updateProfile()
// If the FxAContentViewController was launched from a FxA deferred link
// onboarding might not have been shown. Check to see if it needs to be
// displayed and don't animate.
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(false, animated: false)
}
}
override func makeWebView() -> WKWebView {
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.add(LeakAvoider(delegate: self), name: "accountsCommandHandler")
// Inject our user script after the page loads.
if let path = Bundle.main.path(forResource: "FxASignIn", ofType: "js") {
if let source = try? String(contentsOfFile: path, encoding: .utf8) {
let userScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(userScript)
}
}
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(width: 1, height: 1),
configuration: config
)
webView.allowsLinkPreview = false
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(_ type: String, content: [String: Any]) {
let data = [
"type": type,
"content": content,
] as [String: Any]
let json = JSON(data).stringify() ?? ""
let script = "window.postMessage(\(json), '\(self.url.absoluteString)');"
settingsWebView.evaluateJavaScript(script, completionHandler: nil)
}
fileprivate func onCanLinkAccount(_ data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]])
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
fileprivate func onSessionStatus(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
fileprivate func onSignOut(_ data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
fileprivate func onLogin(_ data: JSON) {
injectData("message", content: ["status": "login"])
let app = UIApplication.shared
let helper = FxALoginHelper.sharedInstance
helper.delegate = self
helper.application(app, didReceiveAccountJSON: data)
if profile.hasAccount() {
LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: true])
}
LeanPlumClient.shared.track(event: .signsInFxa)
}
@objc fileprivate func userDidVerify(_ notification: Notification) {
guard let account = profile.getAccount() else {
return
}
// We can't verify against the actionNeeded of the account,
// because of potential race conditions.
// However, we restrict visibility of this method, and make sure
// we only Notify via the FxALoginStateMachine.
let flags = FxALoginFlags(pushEnabled: account.pushRegistration != nil,
verified: true)
LeanPlumClient.shared.set(attributes: [LPAttributeKey.signedInSync: true])
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
// The content server page is ready to be shown.
fileprivate func onLoaded() {
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(_ rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
if !isLoaded && command != .loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
onLoaded()
}
switch command {
case .loaded:
onLoaded()
case .login, .changePassword:
onLogin(data)
case .canLinkAccount:
onCanLinkAccount(data)
case .sessionStatus:
onSessionStatus(data)
case .signOut:
onSignOut(data)
}
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Make sure we're communicating with a trusted page. That is, ensure the origin of the
// message is the same as the origin of the URL we initially loaded in this web view.
// Note that this exploit wouldn't be possible if we were using WebChannels; see
// https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/WebChannel.jsm
let origin = message.frameInfo.securityOrigin
guard origin.`protocol` == url.scheme && origin.host == url.host && origin.port == (url.port ?? 0) else {
print("Ignoring message - \(origin) does not match expected origin: \(url.origin ?? "nil")")
return
}
if message.name == "accountsCommandHandler" {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].stringValue, data: detail["data"])
}
}
// Configure the FxA signin url based on any passed options.
public func createFxAURLWith(_ fxaOptions: FxALaunchParams?, profile: Profile) -> URL {
let profileUrl = profile.accountConfiguration.signInURL
guard let launchParams = fxaOptions else {
return profileUrl
}
// Only append `signin`, `entrypoint` and `utm_*` parameters. Note that you can't
// override the service and context params.
var params = launchParams.query
params.removeValue(forKey: "service")
params.removeValue(forKey: "context")
let queryURL = params.filter { $0.key == "signin" || $0.key == "entrypoint" || $0.key.range(of: "utm_") != nil }.map({
return "\($0.key)=\($0.value)"
}).joined(separator: "&")
return URL(string: "\(profileUrl)&\(queryURL)") ?? profileUrl
}
}
extension FxAContentViewController: FxAPushLoginDelegate {
func accountLoginDidSucceed(withFlags flags: FxALoginFlags) {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidSignIn(self, withFlags: flags)
}
}
func accountLoginDidFail() {
DispatchQueue.main.async {
self.delegate?.contentViewControllerDidCancel(self)
}
}
}
/*
LeakAvoider prevents leaks with WKUserContentController
http://stackoverflow.com/questions/26383031/wkwebview-causes-my-view-controller-to-leak
*/
class LeakAvoider: NSObject, WKScriptMessageHandler {
weak var delegate: WKScriptMessageHandler?
init(delegate: WKScriptMessageHandler) {
self.delegate = delegate
super.init()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
self.delegate?.userContentController(userContentController, didReceive: message)
}
}
| mpl-2.0 | ec929e39856e332b5d334271f20258b4 | 38.023346 | 132 | 0.6552 | 4.930678 | false | false | false | false |
stephentyrone/swift | tools/swift-inspect/Sources/swift-inspect/main.swift | 1 | 6324 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 ArgumentParser
import SwiftRemoteMirror
func argFail(_ message: String) -> Never {
print(message, to: &Std.err)
exit(EX_USAGE)
}
func machErrStr(_ kr: kern_return_t) -> String {
let errStr = String(cString: mach_error_string(kr))
let errHex = String(kr, radix: 16)
return "\(errStr) (0x\(errHex))"
}
func dumpConformanceCache(context: SwiftReflectionContextRef) throws {
try context.iterateConformanceCache { type, proto in
let typeName = context.name(metadata: type) ?? "<unknown>"
let protoName = context.name(proto: proto) ?? "<unknown>"
print("Conformance: \(typeName): \(protoName)")
}
}
func dumpRawMetadata(
context: SwiftReflectionContextRef,
inspector: Inspector,
backtraceStyle: Backtrace.Style?
) throws {
let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:]
for allocation in context.allocations {
let tagNameC = swift_reflection_metadataAllocationTagName(context, allocation.tag)
let tagName = tagNameC.map(String.init) ?? "<unknown>"
print("Metadata allocation at: \(hex: allocation.ptr) " +
"size: \(allocation.size) tag: \(allocation.tag) (\(tagName))")
printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector)
}
}
func dumpGenericMetadata(
context: SwiftReflectionContextRef,
inspector: Inspector,
backtraceStyle: Backtrace.Style?
) throws {
let allocations = context.allocations.sorted()
let metadatas = allocations.findGenericMetadata(in: context)
let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:]
print("Address","Allocation","Size","Offset","Name", separator: "\t")
for metadata in metadatas {
print("\(hex: metadata.ptr)", terminator: "\t")
if let allocation = metadata.allocation, let offset = metadata.offset {
print("\(hex: allocation.ptr)\t\(allocation.size)\t\(offset)",
terminator: "\t")
} else {
print("???\t???\t???", terminator: "\t")
}
print(metadata.name)
if let allocation = metadata.allocation {
printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector)
}
}
}
func printBacktrace(
style: Backtrace.Style?,
for ptr: swift_reflection_ptr_t,
in backtraces: [swift_reflection_ptr_t: Backtrace],
inspector: Inspector
) {
if let style = style {
if let backtrace = backtraces[ptr] {
print(backtrace.symbolicated(style: style, inspector: inspector))
} else {
print("Unknown backtrace.")
}
}
}
func makeReflectionContext(
nameOrPid: String
) -> (Inspector, SwiftReflectionContextRef) {
guard let pid = pidFromHint(nameOrPid) else {
argFail("Cannot find pid/process \(nameOrPid)")
}
guard let inspector = Inspector(pid: pid) else {
argFail("Failed to inspect pid \(pid) (are you running as root?)")
}
guard let reflectionContext = swift_reflection_createReflectionContextWithDataLayout(
inspector.passContext(),
Inspector.Callbacks.QueryDataLayout,
Inspector.Callbacks.Free,
Inspector.Callbacks.ReadBytes,
Inspector.Callbacks.GetStringLength,
Inspector.Callbacks.GetSymbolAddress
) else {
argFail("Failed to create reflection context")
}
return (inspector, reflectionContext)
}
func withReflectionContext(
nameOrPid: String,
_ body: (SwiftReflectionContextRef, Inspector) throws -> Void
) throws {
let (inspector, context) = makeReflectionContext(nameOrPid: nameOrPid)
defer {
swift_reflection_destroyReflectionContext(context)
inspector.destroyContext()
}
try body(context, inspector)
}
struct SwiftInspect: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Swift runtime debug tool",
subcommands: [
DumpConformanceCache.self,
DumpRawMetadata.self,
DumpGenericMetadata.self,
])
}
struct DumpConformanceCache: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the contents of the target's protocol conformance cache.")
@Argument(help: "The pid or partial name of the target process")
var nameOrPid: String
func run() throws {
try withReflectionContext(nameOrPid: nameOrPid) { context, _ in
try dumpConformanceCache(context: context)
}
}
}
struct DumpRawMetadata: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the target's metadata allocations.")
@Argument(help: "The pid or partial name of the target process")
var nameOrPid: String
@Flag(help: "Show the backtrace for each allocation")
var backtrace: Bool
@Flag(help: "Show a long-form backtrace for each allocation")
var backtraceLong: Bool
func run() throws {
let style = backtrace ? Backtrace.Style.oneLine :
backtraceLong ? Backtrace.Style.long :
nil
try withReflectionContext(nameOrPid: nameOrPid) {
try dumpRawMetadata(context: $0, inspector: $1, backtraceStyle: style)
}
}
}
struct DumpGenericMetadata: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the target's generic metadata allocations.")
@Argument(help: "The pid or partial name of the target process")
var nameOrPid: String
@Flag(help: "Show the backtrace for each allocation")
var backtrace: Bool
@Flag(help: "Show a long-form backtrace for each allocation")
var backtraceLong: Bool
func run() throws {
let style = backtrace ? Backtrace.Style.oneLine :
backtraceLong ? Backtrace.Style.long :
nil
try withReflectionContext(nameOrPid: nameOrPid) {
try dumpGenericMetadata(context: $0,
inspector: $1,
backtraceStyle: style)
}
}
}
SwiftInspect.main()
| apache-2.0 | 7436640a076f78a1e6850c2ff02f9efd | 30.462687 | 102 | 0.684219 | 4.174257 | false | false | false | false |
elliottminns/blackfish | Sources/Blackfire/Address.swift | 2 | 1114 |
import Foundation
struct Address {
let raw: UnsafeMutablePointer<sockaddr_in>
init(address: String, port: Int) throws {
let socketAddress = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1)
socketAddress.pointee.sin_family = sa_family_t(AF_INET)
socketAddress.pointee.sin_port = Address.htons(port: in_port_t(port))
#if os(Linux)
socketAddress.pointee.sin_addr = in_addr(s_addr: in_addr_t(0))
#else
socketAddress.pointee.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
socketAddress.pointee.sin_addr = in_addr(s_addr: inet_addr("0.0.0.0"))
#endif
socketAddress.pointee.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
self.raw = socketAddress
}
static func htons(port: in_port_t) -> in_port_t {
#if os(Linux)
return port.bigEndian //use htons(). LLVM Crash currently
#else
let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
return isLittleEndian ? _OSSwapInt16(port) : port
#endif
}
}
| apache-2.0 | a96c0c760605ed7c00ee9799c251d1c9 | 32.757576 | 83 | 0.597846 | 3.828179 | false | false | false | false |
Adlai-Holler/ArrayDiff | ArrayDiff/FoundationExtensions.swift | 1 | 1697 |
import Foundation
// MARK: NSRange <-> Range<Int> conversion
public extension NSRange {
public var range: Range<Int> {
return location..<location+length
}
public init(range: Range<Int>) {
location = range.startIndex
length = range.endIndex - range.startIndex
}
}
// MARK: NSIndexSet -> [NSIndexPath] conversion
public extension NSIndexSet {
/**
Returns an array of NSIndexPaths that correspond to these indexes in the given section.
When reporting changes to table/collection view, you can improve performance by sorting
deletes in descending order and inserts in ascending order.
*/
public func indexPathsInSection(section: Int, ascending: Bool = true) -> [NSIndexPath] {
var result: [NSIndexPath] = []
result.reserveCapacity(count)
enumerateIndexesWithOptions(ascending ? [] : .Reverse) { index, _ in
result.append(NSIndexPath(indexes: [section, index], length: 2))
}
return result
}
}
// MARK: NSIndexSet support
public extension Array {
public subscript (indexes: NSIndexSet) -> [Element] {
var result: [Element] = []
result.reserveCapacity(indexes.count)
indexes.enumerateRangesUsingBlock { nsRange, _ in
result += self[nsRange.range]
}
return result
}
public mutating func removeAtIndexes(indexSet: NSIndexSet) {
indexSet.enumerateRangesWithOptions(.Reverse) { nsRange, _ in
self.removeRange(nsRange.range)
}
}
public mutating func insertElements(newElements: [Element], atIndexes indexes: NSIndexSet) {
assert(indexes.count == newElements.count)
var i = 0
indexes.enumerateRangesUsingBlock { range, _ in
self.insertContentsOf(newElements[i..<i+range.length], at: range.location)
i += range.length
}
}
}
| mit | 208fd089efd268848a2682282035ebe5 | 25.936508 | 93 | 0.727755 | 3.804933 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/YodaConditionRule.swift | 1 | 4134 | import Foundation
import SourceKittenFramework
public struct YodaConditionRule: ASTRule, OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
private static let regularExpression = regex(
"(?<!" + // Starting negative lookbehind
"(" + // First capturing group
"\\+|-|\\*|\\/|%|\\?" + // One of the operators
")" + // Ending negative lookbehind
")" + // End first capturing group
"\\s+" + // Starting with whitespace
"(" + // Second capturing group
"(?:\\\"[\\\"\\w\\ ]+\")" + // Multiple words between quotes
"|" + // OR
"(?:\\d+" + // Number of digits
"(?:\\.\\d*)?)" + // Optionally followed by a dot and any number digits
"|" + // OR
"(nil)" + // `nil` value
")" + // End second capturing group
"\\s+" + // Followed by whitespace
"(" + // Third capturing group
"==|!=|>|<|>=|<=" + // One of comparison operators
")" + // End third capturing group
"\\s+" + // Followed by whitespace
"(" + // Fourth capturing group
"\\w+" + // Number of words
")" // End fourth capturing group
)
private let observedStatements: Set<StatementKind> = [.if, .guard, .repeatWhile, .while]
public static let description = RuleDescription(
identifier: "yoda_condition",
name: "Yoda condition rule",
description: "The variable should be placed on the left, the constant on the right of a comparison operator.",
kind: .lint,
nonTriggeringExamples: [
"if foo == 42 {}\n",
"if foo <= 42.42 {}\n",
"guard foo >= 42 else { return }\n",
"guard foo != \"str str\" else { return }",
"while foo < 10 { }\n",
"while foo > 1 { }\n",
"while foo + 1 == 2",
"if optionalValue?.property ?? 0 == 2",
"if foo == nil"
],
triggeringExamples: [
"↓if 42 == foo {}\n",
"↓if 42.42 >= foo {}\n",
"↓guard 42 <= foo else { return }\n",
"↓guard \"str str\" != foo else { return }",
"↓while 10 > foo { }",
"↓while 1 < foo { }",
"↓if nil == foo"
])
public func validate(file: File,
kind: StatementKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard observedStatements.contains(kind),
let offset = dictionary.offset,
let length = dictionary.length
else {
return []
}
let matches = file.lines.filter({ $0.byteRange.contains(offset) }).reduce([]) { matches, line in
let range = NSRange(location: 0, length: line.content.bridge().length)
let lineMatches = YodaConditionRule.regularExpression.matches(in: line.content, options: [], range: range)
return matches + lineMatches
}
return matches.map { _ -> StyleViolation in
let characterOffset = startOffset(of: offset, with: length, in: file)
let location = Location(file: file, characterOffset: characterOffset)
return StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity,
location: location)
}
}
private func startOffset(of offset: Int, with length: Int, in file: File) -> Int {
let range = file.contents.bridge().byteRangeToNSRange(start: offset, length: length)
return range?.location ?? offset
}
}
| mit | 55f3e8c5e58fbc8d44bd7b9fd0b0f737 | 44.274725 | 118 | 0.477184 | 5.15 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Foundation/Extensions/BrowserProfileExtension.swift | 2 | 930 | //
// ProfileExtension.swift
// Client
//
// Created by Sahakyan on 3/31/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
private let TogglesPrefKey = "clearprivatedata.toggles"
extension Profile {
fileprivate var toggles: [Bool] {
get {
if var savedToggles = self.prefs.arrayForKey(TogglesPrefKey) as? [Bool] {
if savedToggles.count == 4 {
savedToggles.insert(true, at:1)
}
return savedToggles
}
return [true, true, true, true, true]
}
}
func clearPrivateData(_ tabManager: TabManager) {
let clearables: [Clearable] = [
HistoryClearable(profile: self),
BookmarksClearable(profile: self),
CacheClearable(tabManager: tabManager),
CookiesClearable(tabManager: tabManager),
SiteDataClearable(tabManager: tabManager),
]
for (i, c) in clearables.enumerated() {
guard self.toggles[i] else {
continue
}
c.clear()
}
}
}
| mpl-2.0 | 7f7e47e2928c535ee22de28405b99ea1 | 19.644444 | 76 | 0.675996 | 3.40293 | false | false | false | false |
aaroncrespo/Swift-Playgrounds | Algorithms/Algorithms.playground/Contents.swift | 1 | 630 | //: Playground - noun: a place where people can play
import UIKit
//Counting Sort
let arr = [1,2,3,4,5]
let k = arr.maxElement() //cheating
let arrSorted = Array(arr.reverse()).countingSorted(K: k!) { $0 }
print(arrSorted)
let all = Array(zip(["car","boat","ship","mountain"], [1,2,3,4])).shuffle()
var sortedItems = Array<(String, Int)>(all)
sortedItems.countingSort(K: 5) { $0.1 }
print(sortedItems)
// Permutations
[1,2,3].permutations()
let charsView = "fob".characters.permutations()
//colapse view back into string
let chars = charsView.reduce([String]()) { $0 + [String($1)] }
chars
["1", "2"].permutations()
| artistic-2.0 | 2535c4a46a4361b34d35bd65c60e9042 | 18.6875 | 75 | 0.663492 | 2.903226 | false | false | false | false |
nwdl/the-more-you-know-ios | TheMoreYouKnow/Distance.swift | 1 | 860 | //
// Distance.swift
// TheMoreYouKnow
//
// Created by Nate Walczak on 5/21/15.
// Copyright (c) 2015 Detroit Labs, LLC. All rights reserved.
//
import Foundation
class Distance : NSObject {
static let sharedInstance = Distance()
var lengthFormatter = NSLengthFormatter()
lazy var lazyLengthFormatter = NSLengthFormatter()
func printUnitStyle(unitStyle: NSFormattingUnitStyle) {
self.lengthFormatter.unitStyle = unitStyle
self.lazyLengthFormatter.unitStyle = unitStyle
println(self.lengthFormatter.stringFromValue(1000, unit: .Foot))
println(self.lengthFormatter.stringFromValue(1000, unit: .Inch))
println(self.lazyLengthFormatter.stringFromValue(1000, unit: .Yard))
println(self.lazyLengthFormatter.stringFromValue(1000, unit: .Mile))
println()
}
}
| mit | 7d5d9b2d9738fd4de77074698573c0e8 | 27.666667 | 76 | 0.695349 | 4.278607 | false | false | false | false |
ReduxKit/ReduxKitBond | ReduxKitBondTests/ReduxKitBondTests.swift | 1 | 2234 | //
// ReduxKitBondTests.swift
// ReduxKitBondTests
//
// Created by Karl Bowden on 20/12/2015.
// Copyright © 2015 ReduxKit. All rights reserved.
//
import XCTest
import Bond
import ReduxKit
@testable import ReduxKitBond
class ReduxKitBondTests: XCTestCase {
let store: Store<State> = ReduxKitBond.createStore(reducer)
let action = IncrementAction()
let action2 = IncrementAction(payload: 2)
func testStoreCreation() {
// Assert
XCTAssert(store.state.count == 0)
}
func testStoreActions() {
// Act
store.dispatch(action)
// Assert
XCTAssert(store.state.count == 1)
}
func testStoreSubscription() {
// Arrange
var state: State!
store.subscribe { state = $0 }
// Act
store.dispatch(action)
// Assert
XCTAssert(state.count == 1)
}
func testSubscribeInvokesCallbackImmediately() {
// Act
var state: State!
store.subscribe { state = $0 }
// Assert
XCTAssert(state.count == 0)
}
func testMultipleActions() {
// Arrange
var state: State!
store.subscribe { state = $0 }
// Act
store.dispatch(action)
store.dispatch(action2)
// Assert
XCTAssert(state.count == 3)
}
func testDisposability() {
// Arrange
var state: State!
var disposedState: State!
store.subscribe { state = $0 }
let disposable = store.subscribe { disposedState = $0 }
// Act
store.dispatch(action)
disposable.dispose()
store.dispatch(action)
// Assert
XCTAssert(state.count == 2)
XCTAssert(disposedState.count == 1)
}
func testPerformance() {
let count = 100000
self.measureBlock {
// Arrange
let store = ReduxKitBond.createStore(reducer)
let action = IncrementAction()
var state: State!
store.subscribe { state = $0 }
// Act
for _ in 1...count {
store.dispatch(action)
}
// Assert
XCTAssert(state.count == count)
}
}
}
| mit | 124e603d76961331561efaa92e14b791 | 20.892157 | 63 | 0.549933 | 4.439364 | false | true | false | false |
avtr/bluejay | Bluejay/Bluejay/Bluejay.swift | 1 | 42243 | //
// Bluejay.swift
// Bluejay
//
// Created by Jeremy Chiang on 2017-01-03.
// Copyright © 2017 Steamclock Software. All rights reserved.
//
import Foundation
import CoreBluetooth
/**
Bluejay is a simple wrapper around CoreBluetooth that focuses on making a common usage case as straight forward as possible: a single connected peripheral that the user is interacting with regularly (think most personal electronics devices that have an associated iOS app: fitness trackers, guitar amps, etc).
It also supports a few other niceties for simplifying usage, including automatic discovery of services and characteristics as they are used, as well as supporting a background task mode where the interaction with the device can be written as synchronous calls running on a background thread to avoid callback pyramids of death, or heavily chained promises.
*/
public class Bluejay: NSObject {
// MARK: - Private Properties
/// Internal reference to CoreBluetooth's CBCentralManager.
fileprivate var cbCentralManager: CBCentralManager!
/// List of weak references to objects interested in receiving notifications on Bluetooth connection events and state changes.
fileprivate var observers = [WeakConnectionObserver]()
/// Reference to a peripheral that is still connecting. If this is nil, then the peripheral should either be disconnected or connected. This is used to help determine the state of the peripheral's connection.
fileprivate var connectingPeripheral: Peripheral?
/// Reference to a peripheral that is connected. If this is nil, then the peripheral should either be disconnected or still connecting. This is used to help determine the state of the peripheral's connection.
fileprivate var connectedPeripheral: Peripheral?
/// Allowing or disallowing reconnection attempts upon a disconnection. It should only be set to true after a successful connection to a peripheral, and remain true unless there is an explicit and expected disconnection.
fileprivate var shouldAutoReconnect = false
/// Reference to the background task used for supporting state restoration.
fileprivate var startupBackgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
/// Reference to the peripheral identifier used for supporting state restoration.
fileprivate var peripheralIdentifierToRestore: PeripheralIdentifier?
/// Determines whether state restoration is allowed.
fileprivate var shouldRestoreState = false
/// True when background task is running, and helps prevent calling regular read/write/listen.
private var isRunningBackgroundTask = false
// MARK: - Internal Properties
/// Contains the operations to execute in FIFO order.
var queue: Queue!
/// The value for CBCentralManagerOptionRestoreIdentifierKey.
var restoreIdentifier: RestoreIdentifier?
/// Reference to the object capable of restoring listens during state restoration.
var listenRestorer: WeakListenRestorer?
// MARK: - Public Properties
/// Helps distinguish one Bluejay instance from another.
public var uuid = UUID()
/// Allows checking whether Bluetooth is powered on.
public var isBluetoothAvailable: Bool {
return cbCentralManager.state == .poweredOn
}
/// Allows checking whether Bluejay is currently connecting to a peripheral.
public var isConnecting: Bool {
return connectingPeripheral != nil
}
/// Allows checking whether Bluejay is currently connected to a peripheral.
public var isConnected: Bool {
return connectedPeripheral != nil
}
/// Allows checking whether Bluejay is currently disconnecting from a peripheral.
public var isDisconnecting: Bool = false
/// Allows checking whether Bluejay is currently scanning.
public var isScanning: Bool {
// Cannot rely on the manager's state for isScanning as it is not usually updated immediately, and while that delay might be a more accurate representation of the current state, it is almost always more useful to evaluate whether Bluejay is running a scan request at the top of its queue.
return queue.isScanning()
}
// MARK: - Initialization
/**
Initializing a Bluejay instance will not yet initialize the CoreBluetooth stack. An explicit call to start running a Bluejay instance after it is intialized is required because in cases where a state resotration is trying to restore a listen on a characteristic, a listen restorer must be available before the CoreBluetooth stack is re-initialized. This two-step startup allows you to insert and gaurantee the setup of your listen restorer in between the initialization of Bluejay and the initialization of the CoreBluetooth stack.
*/
public override init() {
super.init()
shouldRestoreState = UIApplication.shared.applicationState == .background
if shouldRestoreState {
debugPrint("Begin startup background task for restoring CoreBluetooth.")
startupBackgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
}
log("Bluejay initialized with UUID: \(uuid.uuidString).")
queue = Queue(bluejay: self)
}
deinit {
cancelEverything()
log("Deinit Bluejay with UUID: \(uuid.uuidString).")
}
/**
Starting Bluejay will initialize the CoreBluetooth stack. Initializing a Bluejay instance will not yet initialize the CoreBluetooth stack. An explicit call to start running a Bluejay instance after it is intialized is required because in cases where a state resotration is trying to restore a listen on a characteristic, a listen restorer must be available before the CoreBluetooth stack is re-initialized. This two-step startup allows you to insert and gaurantee the setup of your listen restorer in between the initialization of Bluejay and the initialization of the CoreBluetooth stack.
- Parameters:
- observer: An object interested in observing Bluetooth connection events and state changes. You can register more observers using the `register` function.
- restoreMode: Determines whether Bluejay will opt-in to state restoration, and if so, can optionally provide a listen restorer as well for restoring listens.
*/
public func start(
connectionObserver observer: ConnectionObserver? = nil,
backgroundRestore restoreMode: BackgroundRestoreMode = .disable
)
{
if cbCentralManager != nil {
log("Error: The Bluejay instance with UUID: \(uuid.uuidString) has already started.")
return
}
register(observer: queue)
if let observer = observer {
register(observer: observer)
}
var options: [String : Any] = [CBCentralManagerOptionShowPowerAlertKey : false]
switch restoreMode {
case .disable:
break
case .enable(let restoreID):
checkBackgroundSupportForBluetooth()
restoreIdentifier = restoreID
options[CBCentralManagerOptionRestoreIdentifierKey] = restoreIdentifier
case .enableWithListenRestorer(let restoreID, let restorer):
checkBackgroundSupportForBluetooth()
restoreIdentifier = restoreID
listenRestorer = WeakListenRestorer(weakReference: restorer)
options[CBCentralManagerOptionRestoreIdentifierKey] = restoreIdentifier
}
cbCentralManager = CBCentralManager(
delegate: self,
queue: DispatchQueue.main,
options: options
)
}
/// Check to see whether the "Uses Bluetooth LE accessories" capability is turned on in the residing Xcode project.
private func checkBackgroundSupportForBluetooth() {
var isSupported = false
if let backgroundModes = Bundle.main.object(forInfoDictionaryKey: "UIBackgroundModes") as? [String] {
isSupported = backgroundModes.contains("bluetooth-central")
}
if !isSupported {
log("Warning: It appears your app has not enabled background support for Bluetooth properly. Please make sure the capability, Background Modes, is turned on, and the setting, Uses Bluetooth LE accessories, is checked in your Xcode project.")
}
}
// MARK: - Cancellation
/**
This will cancel the current and all pending operations in the Bluejay queue, as well as stop any ongoing scan, and disconnect any connected peripheral.
- Parameter error: If nil, all tasks in the queue will be cancelled without any errors. If an error is provided, all tasks in the queue will be failed with the supplied error.
*/
public func cancelEverything(_ error: Error? = nil) {
shouldAutoReconnect = false
queue.cancelAll(error)
if isConnected {
cbCentralManager.cancelPeripheralConnection(connectedPeripheral!.cbPeripheral)
}
}
/**
This will remove any cached listens associated with the receiving Bluejay's restore identifier. Call this if you want to stop Bluejay from attempting to restore any listens when state restoration occurs.
- Note: For handling a single specific characteristic, use `endListen`. If that succeeds, it will not only stop the listening on that characteristic, it will also remove that listen from the cache for state restoration if listen restoration is enabled, and if that listen was indeed cached for restoration.
*/
public func clearListenCaches() {
guard
let restoreIdentifier = restoreIdentifier,
let listenCaches = UserDefaults.standard.dictionary(forKey: Constant.listenCaches)
else {
log("Unable to clear listen caches: nothing to clear.")
return
}
var newListenCaches = listenCaches
newListenCaches.removeValue(forKey: restoreIdentifier)
UserDefaults.standard.set(newListenCaches, forKey: Constant.listenCaches)
UserDefaults.standard.synchronize()
}
// MARK: - Events Registration
/**
Register for notifications on Bluetooth connection events and state changes. Unregistering is not required, Bluejay will unregister for you if the observer is no longer in memory.
- Parameter observer:
*/
public func register(observer: ConnectionObserver) {
observers = observers.filter { $0.weakReference != nil && $0.weakReference !== observer }
observers.append(WeakConnectionObserver(weakReference: observer))
if cbCentralManager != nil {
observer.bluetoothAvailable(cbCentralManager.state == .poweredOn)
}
if let connectedPeripheral = connectedPeripheral {
observer.connected(to: connectedPeripheral)
}
}
/**
Unregister for notifications on Bluetooth connection events and state changes. Unregistering is not required, Bluejay will unregister for you if the observer is no longer in memory.
- Parameter observer:
*/
public func unregister(observer: ConnectionObserver) {
observers = observers.filter { $0.weakReference != nil && $0.weakReference !== observer }
}
// MARK: - Scanning
/**
Scan for the peripheral(s) specified.
- Parameters:
- duration: Stops the scan when the duration in seconds is reached. Defaults to zero (indefinite).
- allowDuplicates: Determines whether a previously scanned peripheral is allowed to be discovered again.
- serviceIdentifiers: Specifies what visible services the peripherals must have in order to be discovered.
- discovery: Called whenever a specified peripheral has been discovered.
- expired: Called whenever a previously discovered peripheral has not been seen again for a while, and Bluejay is predicting that it may no longer be in range. (Only for a scan with allowDuplicates enabled)
- stopped: Called when the scan is finished and provides an error if there is any.
*/
public func scan(
duration: TimeInterval = 0,
allowDuplicates: Bool = false,
serviceIdentifiers: [ServiceIdentifier]?,
discovery: @escaping (ScanDiscovery, [ScanDiscovery]) -> ScanAction,
expired: ((ScanDiscovery, [ScanDiscovery]) -> ScanAction)? = nil,
stopped: @escaping ([ScanDiscovery], Error?) -> Void
)
{
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
log("Warning: You cannot start a scan while a background task is still running.")
return
}
let scanOperation = Scan(
duration: duration,
allowDuplicates: allowDuplicates,
serviceIdentifiers: serviceIdentifiers,
discovery: discovery,
expired: expired,
stopped: stopped,
manager: cbCentralManager
)
queue.add(scanOperation)
}
/// Stops an ongoing scan if there is one, otherwise it does nothing.
public func stopScanning() {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
log("Warning: You cannot stop a scan while a background task is still running.")
return
}
queue.stopScanning()
}
// MARK: - Connection
/**
Attempt to connect directly to a known peripheral. The call will fail if Bluetooth is not available, or if Bluejay is already connected. Making a connection request while Bluejay is scanning will also cause Bluejay to stop the current scan for you behind the scene prior to fulfilling your connection request.
- Parameters:
- peripheralIdentifier: The peripheral to connect to.
- completion: Called when the connection request has fully finished and indicates whether it was successful, cancelled, or failed.
*/
public func connect(_ peripheralIdentifier: PeripheralIdentifier, completion: @escaping (ConnectionResult) -> Void) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
completion(.failure(BluejayError.backgroundTaskRunning))
return
}
// Block a connect request when restoring, restore should result in the peripheral being automatically connected.
if (shouldRestoreState) {
// Cache requested connect, in case restore messes up unexpectedly.
peripheralIdentifierToRestore = peripheralIdentifier
return
}
if let cbPeripheral = cbCentralManager.retrievePeripherals(withIdentifiers: [peripheralIdentifier.uuid]).first {
queue.add(Connection(peripheral: cbPeripheral, manager: cbCentralManager, callback: completion))
}
else {
completion(.failure(BluejayError.unexpectedPeripheral(peripheralIdentifier)))
}
}
/**
Disconnect the currently connected peripheral. Providing a completion block is not necessary, but useful in most cases.
- parameter completion: Called when the disconnection request has fully finished and indicates whether it was successful, cancelled, or failed.
*/
public func disconnect(completion: ((DisconnectionResult) -> Void)? = nil) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
log("Warning: You've tried to disconnect while a background task is still running. The disconnect call will either do nothing, or fail if a completion block is provided.")
completion?(.failure(BluejayError.backgroundTaskRunning))
return
}
if isDisconnecting {
completion?(.failure(BluejayError.multipleDisconnectNotSupported))
return
}
if let peripheralToDisconnect = connectedPeripheral {
isDisconnecting = true
shouldAutoReconnect = false
queue.cancelAll()
queue.add(Disconnection(
peripheral: peripheralToDisconnect.cbPeripheral,
manager: cbCentralManager,
callback: { (result) in
switch result {
case .success(let peripheral):
self.isDisconnecting = false
completion?(.success(peripheral))
case .cancelled:
self.isDisconnecting = false
completion?(.cancelled)
case .failure(let error):
self.isDisconnecting = false
completion?(.failure(error))
}
}))
}
else {
log("Cannot disconnect: there is no connected peripheral.")
isDisconnecting = false
completion?(.failure(BluejayError.notConnected))
}
}
// MARK: - Actions
/**
Read from the specified characteristic.
- Parameters:
- characteristicIdentifier: The characteristic to read from.
- completion: Called with the result of the attempt to read from the specified characteristic.
*/
public func read<R: Receivable>(from characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
completion(.failure(BluejayError.backgroundTaskRunning))
return
}
if let peripheral = connectedPeripheral {
peripheral.read(from: characteristicIdentifier, completion: completion)
}
else {
completion(.failure(BluejayError.notConnected))
}
}
/**
Write to the specified characteristic.
- Parameters:
- characteristicIdentifier: The characteristic to write to.
- type: Write type.
- completion: Called with the result of the attempt to write to the specified characteristic.
*/
public func write<S: Sendable>(to characteristicIdentifier: CharacteristicIdentifier, value: S, type: CBCharacteristicWriteType = .withResponse, completion: @escaping (WriteResult) -> Void) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
completion(.failure(BluejayError.backgroundTaskRunning))
return
}
if let peripheral = connectedPeripheral {
peripheral.write(to: characteristicIdentifier, value: value, type: type, completion: completion)
}
else {
completion(.failure(BluejayError.notConnected))
}
}
/**
Listen for notifications on the specified characteristic.
- Parameters:
- characteristicIdentifier: The characteristic to listen to.
- completion: Called with the result of the attempt to listen for notifications on the specified characteristic.
*/
public func listen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
completion(.failure(BluejayError.backgroundTaskRunning))
return
}
if let peripheral = connectedPeripheral {
peripheral.listen(to: characteristicIdentifier, completion: completion)
}
else {
completion(.failure(BluejayError.notConnected))
}
}
/**
End listening on the specified characteristic.
- Parameters:
- characteristicIdentifier: The characteristic to stop listening to.
- completion: Called with the result of the attempt to stop listening to the specified characteristic.
*/
public func endListen(to characteristicIdentifier: CharacteristicIdentifier, completion: ((WriteResult) -> Void)? = nil) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
log("Warning: You've tried to end a listen while a background task is still running. The endListen call will either do nothing, or fail if a completion block is provided.")
completion?(.failure(BluejayError.backgroundTaskRunning))
return
}
if let peripheral = connectedPeripheral {
peripheral.endListen(to: characteristicIdentifier, error: nil, completion: completion)
}
else {
completion?(.failure(BluejayError.notConnected))
}
}
/**
Restore a (believed to be) active listening session, so if we start up in response to a notification, we can receive it.
- Parameters:
- characteristicIdentifier: The characteristic that needs the restoration.
- completion: Called with the result of the attempt to restore the listen on the specified characteristic.
*/
public func restoreListen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void) {
if isRunningBackgroundTask {
// Terminate the app if this is called from the same thread as the running background task.
if #available(iOS 10.0, *) {
Dispatch.dispatchPrecondition(condition: .notOnQueue(DispatchQueue.global()))
} else {
// Fallback on earlier versions
}
completion(.failure(BluejayError.backgroundTaskRunning))
return
}
if let peripheral = connectedPeripheral {
peripheral.restoreListen(to: characteristicIdentifier, completion: completion)
}
else {
completion(.failure(BluejayError.notConnected))
}
}
// MARK: - Background Task
/**
One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This is the simplest one as the background task will not return any typed values back to the completion block on finishing the background task, except for thrown errors, and it also doesn't provide an input for an object that might need thread safe access.
- Warning: Be careful not to access anything that is not thread safe inside background task.
- Parameters:
- backgroundTask: A closure with the jobs to be executed in the background.
- completionOnMainThread: A closure called on the main thread when the background task has either completed or failed.
*/
public func run(
backgroundTask: @escaping (SynchronizedPeripheral) throws -> Void,
completionOnMainThread: @escaping (RunResult<Void>) -> Void)
{
if isRunningBackgroundTask {
completionOnMainThread(.failure(BluejayError.multipleBackgroundTaskNotSupported))
return
}
isRunningBackgroundTask = true
if let peripheral = connectedPeripheral {
DispatchQueue.global().async { [weak self] in
do {
try backgroundTask(SynchronizedPeripheral(parent: peripheral))
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.success(()))
}
}
catch let error as NSError {
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
}
}
}
}
else {
isRunningBackgroundTask = false
completionOnMainThread(.failure(BluejayError.notConnected))
}
}
/**
One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This one allows the background task to potentially return a typed value back to the completion block on finishing the background task successfully.
- Warning: Be careful not to access anything that is not thread safe inside background task.
- Parameters:
- backgroundTask: A closure with the jobs to be executed in the background.
- completionOnMainThread: A closure called on the main thread when the background task has either completed or failed.
*/
public func run<Result>(
backgroundTask: @escaping (SynchronizedPeripheral) throws -> Result,
completionOnMainThread: @escaping (RunResult<Result>) -> Void)
{
if isRunningBackgroundTask {
completionOnMainThread(.failure(BluejayError.multipleBackgroundTaskNotSupported))
return
}
isRunningBackgroundTask = true
if let peripheral = connectedPeripheral {
DispatchQueue.global().async { [weak self] in
do {
let result = try backgroundTask(SynchronizedPeripheral(parent: peripheral))
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.success(result))
}
}
catch let error as NSError {
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
}
}
}
}
else {
isRunningBackgroundTask = false
completionOnMainThread(.failure(BluejayError.notConnected))
}
}
/**
One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This one allows the background task to potentially return a typed value back to the completion block on finishing the background task successfully, as well as supplying an object for thread safe access inside the background task.
- Warning: Be careful not to access anything that is not thread safe inside background task.
- Parameters:
- userData: Any object you wish to have thread safe access inside background task.
- backgroundTask: A closure with the jobs to be executed in the background.
- completionOnMainThread: A closure called on the main thread when the background task has either completed or failed.
*/
public func run<UserData, Result>(
userData: UserData,
backgroundTask: @escaping (SynchronizedPeripheral, UserData) throws -> Result,
completionOnMainThread: @escaping (RunResult<Result>) -> Void)
{
if isRunningBackgroundTask {
completionOnMainThread(.failure(BluejayError.multipleBackgroundTaskNotSupported))
return
}
isRunningBackgroundTask = true
if let peripheral = connectedPeripheral {
DispatchQueue.global().async { [weak self] in
do {
let result = try backgroundTask(SynchronizedPeripheral(parent: peripheral), userData)
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.success(result))
}
}
catch let error as NSError {
DispatchQueue.main.async {
self?.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
}
}
}
}
else {
isRunningBackgroundTask = false
completionOnMainThread(.failure(BluejayError.notConnected))
}
}
// MARK: - Helpers
/**
A helper function to take an array of Sendables and combine their data together.
- Parameter sendables: An array of Sendables whose Data should be appended in the order of the given array.
- Returns: The resulting data of all the Sendables combined in the order of the passed in array.
*/
public static func combine(sendables: [Sendable]) -> Data {
let data = NSMutableData()
for sendable in sendables {
data.append(sendable.toBluetoothData())
}
return data as Data
}
}
// MARK: - CBCentralManagerDelegate
extension Bluejay: CBCentralManagerDelegate {
/**
Bluejay uses this to figure out whether Bluetooth is available or not.
- If Bluetooth is available for the first time, start running the queue.
- If Bluetooth is available for the first time and the app is already connected, then this is a state restoration event. Try listen restoration if possible.
- If Bluetooth is turned off, cancel everything with the `bluetoothUnavailable` error and disconnect.
- Broadcast state changes to observers.
*/
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
let backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
if #available(iOS 10.0, *) {
log("CBCentralManager state updated: \(central.state.string())")
} else {
// Fallback on earlier versions
log("CBCentralManager state updated: \(central.state)")
}
if central.state == .poweredOn {
queue.start()
}
if central.state == .poweredOn && connectedPeripheral != nil {
do {
try requestListenRestoration()
}
catch {
log("Failed to complete listen restoration with error: \(error)")
}
}
if central.state == .poweredOff {
cancelEverything(BluejayError.bluetoothUnavailable)
connectingPeripheral = nil
connectedPeripheral = nil
}
for observer in observers {
observer.weakReference?.bluetoothAvailable(central.state == .poweredOn)
}
UIApplication.shared.endBackgroundTask(backgroundTask)
}
/**
Examine the listen cache in `UserDefaults` to determine whether there are any listens that might need restoration.
*/
private func requestListenRestoration() throws {
log("Starting listen restoration.")
guard
let listenCaches = UserDefaults.standard.dictionary(forKey: Constant.listenCaches),
let cacheData = listenCaches[uuid.uuidString] as? [Data]
else {
log("No listens to restore.")
return
}
let decoder = JSONDecoder()
for data in cacheData {
do {
let listenCache = try decoder.decode(ListenCache.self, from: data)
log("Listen cache to restore: \(listenCache)")
let serviceIdentifier = ServiceIdentifier(uuid: listenCache.serviceUUID)
let characteristicIdentifier = CharacteristicIdentifier(uuid: listenCache.characteristicUUID, service: serviceIdentifier)
if let listenRestorer = listenRestorer?.weakReference {
// If true, assume the listen restorable delegate will restore the listen accordingly, otherwise end the listen.
if !listenRestorer.willRestoreListen(on: characteristicIdentifier) {
endListen(to: characteristicIdentifier)
}
}
else {
// If there is no listen restorable delegate, end the listen as well.
endListen(to: characteristicIdentifier)
}
}
catch {
throw BluejayError.listenCacheDecoding(error)
}
}
log("Listen restoration finished.")
}
/**
If Core Bluetooth will restore state, update Bluejay's internal states to match the states of the Core Bluetooth stack by assigning the peripheral to `connectingPeripheral` or `connectedPeripheral`, or niling them out, depending on what the restored `CBPeripheral` state is.
*/
public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
debugPrint("Will restore state.")
shouldRestoreState = false
guard
let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral],
let cbPeripheral = peripherals.first
else {
// Weird failure case that seems to happen sometime,
// restoring but don't have a device in the restore list
// try to trigger a reconnect if we have a stored
// peripheral
if let id = peripheralIdentifierToRestore {
connect(id, completion: { _ in })
}
return
}
let peripheral = Peripheral(bluejay: self, cbPeripheral: cbPeripheral)
precondition(peripherals.count == 1, "Invalid number of peripheral to restore.")
debugPrint("Peripheral state to restore: \(cbPeripheral.state.string())")
switch cbPeripheral.state {
case .connecting:
precondition(connectedPeripheral == nil,
"Connected peripheral is not nil during willRestoreState for state: connecting.")
connectingPeripheral = peripheral
case .connected:
precondition(connectingPeripheral == nil,
"Connecting peripheral is not nil during willRestoreState for state: connected.")
connectedPeripheral = peripheral
case .disconnecting:
precondition(connectingPeripheral == nil,
"Connecting peripheral is not nil during willRestoreState for state: disconnecting.")
connectedPeripheral = peripheral
case .disconnected:
precondition(connectingPeripheral == nil && connectedPeripheral == nil,
"Connecting and connected peripherals are not nil during willRestoreState for state: disconnected.")
}
debugPrint("State restoration finished.")
if startupBackgroundTask != UIBackgroundTaskInvalid {
debugPrint("Cancelling startup background task.")
UIApplication.shared.endBackgroundTask(startupBackgroundTask)
}
}
/**
When connected, update Bluejay's states by updating the values for `connectingPeripheral`, `connectedPeripheral`, and `shouldAutoReconnect`. Also, make sure to broadcast the event to observers, and notify the queue so that the current operation in-flight can process this event and get a chance to finish.
*/
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
let backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
debugPrint("Did connect to: \(peripheral.name ?? peripheral.identifier.uuidString)")
connectedPeripheral = connectingPeripheral
connectingPeripheral = nil
for observer in observers {
observer.weakReference?.connected(to: connectedPeripheral!)
}
shouldAutoReconnect = true
queue.process(event: .didConnectPeripheral(peripheral), error: nil)
UIApplication.shared.endBackgroundTask(backgroundTask)
}
/**
Handle a disconnection event from Core Bluetooth by figuring out what kind of disconnection it is (planned or unplanned), and updating Bluejay's internal state and sending notifications as appropriate.
*/
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
let backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
let peripheralString = peripheral.name ?? peripheral.identifier.uuidString
let errorString = error?.localizedDescription
if let errorMessage = errorString {
log("Did disconnect from \(peripheralString) with error: \(errorMessage)")
}
else {
log("Did disconnect from \(peripheralString) without errors.")
}
for observer in observers {
let disconnectedPeripheral = connectingPeripheral ?? connectedPeripheral
precondition(disconnectedPeripheral != nil, "Disconnected from an unexpected peripheral.")
observer.weakReference?.disconnected(from: disconnectedPeripheral!)
}
if !queue.isEmpty() {
// If Bluejay is currently connecting or disconnecting, the queue needs to process this disconnection event. Otherwise, this is an unexpected disconnection.
if isConnecting || isDisconnecting {
queue.process(event: .didDisconnectPeripheral(peripheral), error: error as NSError?)
}
else {
queue.cancelAll(BluejayError.notConnected)
}
}
connectingPeripheral = nil
connectedPeripheral = nil
log("Should auto-reconnect: \(shouldAutoReconnect)")
if shouldAutoReconnect {
log("Issuing reconnect to: \(peripheral.name ?? peripheral.identifier.uuidString)")
connect(PeripheralIdentifier(uuid: peripheral.identifier), completion: {_ in })
}
UIApplication.shared.endBackgroundTask(backgroundTask)
}
/**
This mostly happens when either the Bluetooth device or the Core Bluetooth stack somehow only partially completes the negotiation of a connection. For simplicity, Bluejay is currently treating this as a disconnection event, so it can perform all the same clean up logic.
*/
public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Use the same clean up logic provided in the did disconnect callback.
centralManager(central, didDisconnectPeripheral: peripheral, error: error)
}
/**
This should only be called when the current operation in the queue is a `Scan` task.
*/
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// let peripheralString = advertisementData[CBAdvertisementDataLocalNameKey] ?? peripheral.identifier.uuidString
// debugPrint("Did discover: \(peripheralString)")
queue.process(event: .didDiscoverPeripheral(peripheral, advertisementData, RSSI), error: nil)
}
}
/// Allows Bluejay to receive events and delegation from its queue.
extension Bluejay: QueueObserver {
/// Support for the will connect state that CBCentralManagerDelegate does not have.
func willConnect(to peripheral: CBPeripheral) {
connectingPeripheral = Peripheral(bluejay: self, cbPeripheral: peripheral)
}
}
/// Convenience function to log information specific to Bluejay within the framework. We have plans to improve logging significantly in the near future.
func log(_ string: String) {
debugPrint("[Bluejay-Debug] \(string)")
}
| mit | a05dad0ed953cf8d67d4440b62548aed | 44.17861 | 594 | 0.645874 | 5.828895 | false | false | false | false |
QQLS/YouTobe | YouTube/Class/Base/Controller/BQMainViewController.swift | 1 | 7079 | //
// BQMainViewController.swift
// YouTube
//
// Created by xiupai on 2017/3/15.
// Copyright © 2017年 QQLS. All rights reserved.
//
import UIKit
private let mainCellReuseID = UICollectionViewCell.nameOfClass
class BQMainViewController: UIViewController {
fileprivate var itemSize = CGSize.zero
fileprivate var isCanScroll = false
// MARK: - Properties
fileprivate lazy var subControllers: [UIViewController] = {
return [BQHomeViewController.nameOfClass, BQTrendingViewController.nameOfClass, BQSubscriptionsViewController.nameOfClass, BQAccountViewController.nameOfClass].map {
guard let subContr = self.storyboard?.instantiateViewController(withIdentifier: $0) else {
return UIViewController()
}
return subContr
}
} ()
// MARK: - Views
fileprivate lazy var collcetionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.init(x: 0, y: kStatusAndNavigationHeight, width: kScreenWidth, height: kScreenHeight - kStatusAndNavigationHeight), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.bounces = false
collectionView.isPagingEnabled = true
collectionView.isDirectionalLockEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: mainCellReuseID)
return collectionView
} ()
fileprivate lazy var tabBar: BQTabBar = {
let tabBar = BQTabBar(frame: .zero)
tabBar.delegate = self
return tabBar
} ()
private lazy var searchBar: BQSearchView = {
let searchBar = BQSearchView(frame: kScreenBounds)
return searchBar
} ()
private lazy var settingView: BQSettingView = {
let settingView = BQSettingView(frame: kScreenBounds)
return settingView
} ()
private let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 18)
titleLabel.textColor = .white
titleLabel.text = "Home"
return titleLabel
} ()
// MARK: - Initial
override func viewDidLoad() {
super.viewDidLoad()
p_setupView()
NotificationCenter.default.addObserver(self, selector: #selector(BQMainViewController.hiddenNavigationBar(with:)), name: NSNotification.Name(NavigationWillHiddenNotification), object: nil)
}
private func p_setupView() {
// 如果 navigationBar 是透明的,那么下部的 view 会从(0, 0)开始,可以通过设置 isTranslucent 为 false 来解决
// self.navigationController?.navigationBar.isTranslucent = false
// TitleLabel
navigationController?.navigationBar.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(10)
}
// CollectionView
view.addSubview(collcetionView)
// 如果添加约束的话,会导致 collectionView 在导航栏消失和隐藏的时候会闪动的问题
// collcetionView.snp.makeConstraints { (make) in
// make.left.bottom.centerX.equalToSuperview()
// make.top.equalTo(tabBar.snp.bottom)
// }
// TabBar
view.addSubview(tabBar)
tabBar.snp.makeConstraints { (make) in
make.top.left.right.equalToSuperview()
make.height.equalTo(kStatusAndNavigationHeight)
}
}
// MARK: - Action
@IBAction func searchAction(_ sender: UIBarButtonItem) {
if let window = UIApplication.shared.keyWindow {
window.addSubview(searchBar)
searchBar.show()
}
}
@IBAction func moreAction(_ sender: UIBarButtonItem) {
if let window = UIApplication.shared.keyWindow {
window.addSubview(settingView)
settingView.show()
}
}
func hiddenNavigationBar(with notification: Notification) {
DispatchQueue.main.async {
if let hidden = notification.object as? Bool {
self.navigationController?.setNavigationBarHidden(hidden, animated: true)
}
}
}
}
// MARK: - UICollectionViewDataSource
extension BQMainViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subControllers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: mainCellReuseID, for: indexPath)
return cell
}
}
// MARK: - UICollectionViewDataSource
extension BQMainViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard subControllers.count > indexPath.item else {
return
}
let subContr = subControllers[indexPath.item]
if !subContr.isViewLoaded {
addChildViewController(subContr)
cell.addSubview(subContr.view)
subContr.view.snp.makeConstraints({ (make) in
make.edges.equalToSuperview()
})
subContr.didMove(toParentViewController: self)
} else {
cell.addSubview(subContr.view)
subContr.view.snp.makeConstraints({ (make) in
make.edges.equalToSuperview()
})
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension BQMainViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.size
}
}
// MARK: - UIScrollViewDelegate
extension BQMainViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isCanScroll {
let index = Double(scrollView.contentOffset.x / scrollView.width) + 0.5
let indexPath = IndexPath.init(item: Int(index), section: 0)
tabBar.switchSelectItem(to: indexPath)
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isCanScroll = true
}
}
// MARK: - BQTabBarDelegate
extension BQMainViewController: BQTabBarDelegate {
func didSelectItem(at indexPath: IndexPath) {
isCanScroll = false
self.collcetionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
| apache-2.0 | 1e9942b6b516cc7585018a22344bda32 | 34.55102 | 205 | 0.666332 | 5.290812 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/ExpandingCollectionView/ExpandingCollectionViewController.swift | 1 | 2586 | //
// ExpandingCollectionViewController.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/7/22.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
class ExpandingCollectionViewController: UIViewController {
fileprivate lazy var items: [String] = []
private lazy var collectionView: UICollectionView = {
var rect = self.view.frame
let layout = UltravisualLayout()
layout.estimatedItemSize = CGSize(width: 1, height: 1)
// layout.minimumLineSpacing = 16
// layout.minimumInteritemSpacing = 16
let collectionView = UICollectionView(frame: rect, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
for _ in 0 ..< 10 {
items.append("I'm trying to get self sizing UICollectionViewCells working with Auto Layout, but I can't seem to get the cells to size themselves to the content. I'm having trouble understanding how the cell's size is updated from the contents of what's inside the cell's contentView.")
}
collectionView.register(MyCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ExpandingCollectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
(cell as? MyCell)?.text = items[indexPath.row]
return cell
}
}
extension ExpandingCollectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let layout = collectionView.collectionViewLayout as! UltravisualLayout
let offset = layout.dragOffset * CGFloat(indexPath.item)
if collectionView.contentOffset.y != offset {
collectionView.setContentOffset(CGPoint(x: 0, y: offset), animated: true)
}
}
}
| mit | 0681d90c50e3c7c2498ff0fe1c1ba9b1 | 37.373134 | 297 | 0.69895 | 5.458599 | false | false | false | false |
xuephil/Perfect | PerfectLib/DynamicLoader.swift | 2 | 2973 | //
// DynamicLoader.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/13/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
#else
import Darwin
#endif
class DynamicLoader {
// sketchy! PerfectServerModuleInit is not defined as convention(c)
// but it does not seem to matter provided it is Void->Void
// I am unsure on how to convert a void* to a legit Swift ()->() func
typealias InitFunction = @convention(c) ()->()
let initFuncName = "PerfectServerModuleInit"
init() {
}
func loadFramework(atPath: String) -> Bool {
let resolvedPath = atPath.stringByResolvingSymlinksInPath
let moduleName = resolvedPath.lastPathComponent.stringByDeletingPathExtension
let file = File(resolvedPath + "/" + moduleName)
if file.exists() {
let realPath = file.realPath()
return self.loadRealPath(realPath, moduleName: moduleName)
}
return false
}
func loadLibrary(atPath: String) -> Bool {
let resolvedPath = atPath.stringByResolvingSymlinksInPath
let moduleName = resolvedPath.lastPathComponent.stringByDeletingPathExtension
let file = File(resolvedPath)
if file.exists() {
let realPath = file.realPath()
return self.loadRealPath(realPath, moduleName: moduleName)
}
return false
}
private func loadRealPath(realPath: String, moduleName: String) -> Bool {
let openRes = dlopen(realPath, RTLD_NOW|RTLD_LOCAL)
if openRes != nil {
// this is fragile
let newModuleName = moduleName.stringByReplacingString("-", withString: "_").stringByReplacingString(" ", withString: "_")
let symbolName = "_TF\(newModuleName.utf8.count)\(newModuleName)\(initFuncName.utf8.count)\(initFuncName)FT_T_"
let sym = dlsym(openRes, symbolName)
if sym != nil {
let f: InitFunction = unsafeBitCast(sym, InitFunction.self)
f()
return true
} else {
print("Error loading \(realPath). Symbol \(symbolName) not found.")
dlclose(openRes)
}
} else {
print("Errno \(String.fromCString(dlerror())!)")
}
return false
}
}
| agpl-3.0 | e6ae310ebe080b3e0da5b4c8afaab79f | 30.294737 | 125 | 0.725193 | 3.831186 | false | false | false | false |
proxyco/RxBluetoothKit | Source/RxServiceType.swift | 1 | 2527 | // The MIT License (MIT)
//
// Copyright (c) 2016 Polidea
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreBluetooth
/**
Protocol which wraps bluetooth service.
*/
protocol RxServiceType {
/// Service's UUID
var uuid: CBUUID { get }
/// Service's characteristics
var characteristics: [RxCharacteristicType]? { get }
/// Service's included services
var includedServices: [RxServiceType]? { get }
/// True if service is a primary service
var isPrimary: Bool { get }
}
extension Equatable where Self: RxServiceType {}
/**
Services are equal if their UUIDs are equal
- parameter lhs: First service to compare
- parameter rhs: Second service to compare
- returns: True if services UUIDs are the same.
*/
func == (lhs: RxServiceType, rhs: RxServiceType) -> Bool {
return lhs.uuid == rhs.uuid
}
/**
Function compares if two services arrays are the same, which is true if
both of them in sequence are equal and their size is the same.
- parameter lhs: First array of services to compare
- parameter rhs: Second array of services to compare
- returns: True if both arrays contain same services
*/
func == (lhs: [RxServiceType], rhs: [RxServiceType]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
var i1 = lhs.generate()
var i2 = rhs.generate()
var isEqual = true
while let e1 = i1.next(), e2 = i2.next() where isEqual {
isEqual = e1 == e2
}
return isEqual
}
| mit | ae323d91f9a01957287b5dee2e19319e | 32.25 | 81 | 0.714681 | 4.394783 | false | false | false | false |
paidy/paidy-ios | PaidyCheckoutSDK/PaidyCheckoutSDK/InputValidation.swift | 1 | 2844 | //
// InputValidation.swift
// Paidycheckoutsdk
//
// Copyright (c) 2015 Paidy. All rights reserved.
//
import UIKit
class InputValidation {
static func isValidEmail(emailString: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(emailString)
}
static func isValidPhone(phoneString: String) -> Bool {
let phoneRegex = "^(?:070|080|090)\\d{8}$"
var phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluateWithObject(phoneString)
}
static func formatCurrency(amount:AnyObject) -> String {
var numberFormatter: NSNumberFormatter = NSNumberFormatter()
numberFormatter.groupingSeparator = ","
numberFormatter.groupingSize = 3
numberFormatter.usesGroupingSeparator = true
numberFormatter.generatesDecimalNumbers = false
return numberFormatter.stringForObjectValue(amount)!
}
static func isKana(input:String) -> Bool {
let kanaRegex = "^[ぁ-んァ-ロワヲンー。-゚\r\n\t]+$"
var kanaTest = NSPredicate(format: "SELF MATCHES %@", kanaRegex)
return kanaTest.evaluateWithObject(input)
}
static func isDob(input:String) -> Bool {
let dobRegex = "^\\d{4}-\\d{2}-\\d{2}$"
var dobaTest = NSPredicate(format: "SELF MATCHES %@", dobRegex)
if (dobaTest.evaluateWithObject(input)){
return isAgeLimit(input)
} else {
return false
}
}
static func isAgeLimit(dob:String) -> Bool {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateFromString = dateFormatter.dateFromString(dob)
return calculateAge(dateFromString!) >= 18
}
static func calculateAge(birthday: NSDate) -> NSInteger {
var userAge : NSInteger = 0
var calendar : NSCalendar = NSCalendar.currentCalendar()
var unitFlags : NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
var dateComponentNow : NSDateComponents = calendar.components(unitFlags, fromDate: NSDate())
var dateComponentBirth : NSDateComponents = calendar.components(unitFlags, fromDate: birthday)
if ( (dateComponentNow.month < dateComponentBirth.month) ||
((dateComponentNow.month == dateComponentBirth.month) && (dateComponentNow.day < dateComponentBirth.day))
)
{
return dateComponentNow.year - dateComponentBirth.year - 1
}
else {
return dateComponentNow.year - dateComponentBirth.year
}
}
}
| mit | 6ca5390c42995e47782d51aa2d825b5e | 36.653333 | 140 | 0.641643 | 4.778342 | false | true | false | false |
LondonSwift/OnTrack | OnTrack/OnTrack/LocationSpoofer.swift | 1 | 3592 | //
// LocationSpoofer.swift
// OnTrack
//
// Created by Daren David Taylor on 14/12/2015.
// Copyright © 2015 LondonSwift. All rights reserved.
//
import UIKit
import MapKit
import AudioToolbox
import LSRepeater
import AVFoundation
protocol LocationSpooferDelegate {
func locationSpoofer(spoofer:LocationSpoofer, location:CLLocation)
}
class LocationSpoofer {
var delegate: LocationSpooferDelegate?
var position = 0
var locationArray:Array<LocationAndRelativeTime>?
var replayIndex = 0
func load (gpxPath: String) {
let url = NSURL.applicationBundleDirectory().URLByAppendingPathComponent(gpxPath)
self.locationArray = Array<LocationAndRelativeTime>()
var lastTime:NSDate?
var timeDiff:Double?
if let root = GPXParser.parseGPXAtURL(url) {
if let tracks = root.tracks {
for track in tracks as! [GPXTrack] {
for trackSegment in track.tracksegments as! [GPXTrackSegment] {
for trackPoint in trackSegment.trackpoints as! [GPXTrackPoint] {
let location = CLLocation(latitude: CLLocationDegrees(trackPoint.latitude), longitude: CLLocationDegrees(trackPoint.longitude))
if let lastTime = lastTime {
timeDiff = trackPoint.time.timeIntervalSinceDate(lastTime)
}
else {
timeDiff = 0
}
lastTime = trackPoint.time
let locationAndRelativeTime = LocationAndRelativeTime()
locationAndRelativeTime.location = location
locationAndRelativeTime.relativeTime = timeDiff
self.locationArray!.append(locationAndRelativeTime)
}
}
}
}
}
}
func start(delegate: LocationSpooferDelegate) {
self.delegate = delegate
self.triggerNext()
}
func triggerNext() {
if let locationArray = self.locationArray {
if replayIndex < locationArray.count {
let locationAndRelativeTime = locationArray[self.replayIndex]
if let relativeTime = locationAndRelativeTime.relativeTime {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(relativeTime * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
if let location = locationAndRelativeTime.location {
self.delegate?.locationSpoofer(self, location: location)
self.replayIndex++
self.triggerNext()
}
}
}
}
}
}
} | gpl-3.0 | 81cd408a25074ae524d72cba05cf90dd | 29.965517 | 155 | 0.456697 | 6.38968 | false | false | false | false |
1457792186/JWSwift | SwiftWX/LGWeChatKit/LGChatKit/friend/FriendCellModel.swift | 2 | 657 | //
// FriendCellModel.swift
// LGChatViewController
//
// Created by jamy on 10/21/15.
// Copyright © 2015 jamy. All rights reserved.
//
import Foundation
class contactCellModel {
let name: Observable<String>
let phone: Observable<String>
let iconName: Observable<String>
init(_ friend: Friend) {
name = Observable(friend.name)
phone = Observable(friend.phone)
iconName = Observable(friend.iconName)
}
}
class contactSessionModel {
let key: Observable<String>
let friends: Observable<[contactCellModel]>
init() {
key = Observable("")
friends = Observable([])
}
} | apache-2.0 | 3eb62ab50cb13c02234e8c19e277fad7 | 19.53125 | 47 | 0.640244 | 4.178344 | false | false | false | false |
baquiax/ImageProcessor | ImageProcessor.playground/Sources/Filters/Invert.swift | 1 | 759 | //This is an extra Filter, it does not receive parameters.
public class Invert : Filter {
public init () {
}
func newValue(currentValue: Int) -> UInt8 {
return UInt8(255 - currentValue)
}
public func apply(image: RGBAImage) -> RGBAImage {
var pixel : Pixel?
for r in 0...image.height - 1 {
for c in 0...image.width - 1 {
pixel = image.pixels[ image.height * r + c ]
pixel!.red = newValue(Int(pixel!.red))
pixel!.green = newValue(Int(pixel!.green))
pixel!.blue = newValue(Int(pixel!.blue))
image.pixels[image.height * r + c] = pixel!;
}
}
return image
}
} | mit | d8666857acc589d385908fd31f72b56c | 29.4 | 72 | 0.500659 | 4.288136 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTCentralAddressResolution.swift | 1 | 2872 | //
// GATTCentralAddressResolution.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/19/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Central Address Resolution
The information contained on this web page is informative.
Informative means that the text may provide background or context to the authoritative text contained in the adopted Bluetooth specification. Informative text is not considered when determining compliance to the Bluetooth specification. Please refer to the adopted Bluetooth specification for the normative (i.e. authoritative) text used to establish compliance. Compliance issues due to errors on this web page are not the responsibility of the Bluetooth SIG and rest solely with the member.
The Peripheral checks if the peer device supports address resolution by reading the Central Address Resolution characteristic before using directed advertisement where the initiator address is set to a Resolvable Private Address (RPA).
[Central Address Resolution](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.central_address_resolution.xml)
- Note:
A device has only one instance of the Central Address Resolution characteristic. If the Central Address Resolution characteristic is not present, then it is assumed that Central Address Resolution is not supported.
*/
@frozen
public struct GATTCentralAddressResolution: GATTCharacteristic {
public static var uuid: BluetoothUUID { return .centralAddressResolution }
internal static let length = MemoryLayout<UInt8>.size
/// Whether address resolution is supported in this device.
public var isSupported: Bool
public init(isSupported: Bool) {
self.isSupported = isSupported
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let booleanValue = Bool(byteValue: data[0])
else { return nil }
self.init(isSupported: booleanValue)
}
public var data: Data {
return Data([isSupported.byteValue])
}
}
// MARK: - Equatable
extension GATTCentralAddressResolution: Equatable {
public static func == (lhs: GATTCentralAddressResolution, rhs: GATTCentralAddressResolution) -> Bool {
return lhs.isSupported == rhs.isSupported
}
}
// MARK: - CustomStringConvertible
extension GATTCentralAddressResolution: CustomStringConvertible {
public var description: String {
return isSupported.description
}
}
// MARK: - ExpressibleByBooleanLiteral
extension GATTCentralAddressResolution: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self.init(isSupported: value)
}
}
| mit | 7ca369076e0d026843237332feb35ffc | 33.178571 | 493 | 0.726228 | 5.191682 | false | false | false | false |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/Classes/Home/View/PageTitleView.swift | 1 | 6297 | //
// MenuView.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/7.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class {
// 菜单点击
func pageTitleViewClick(_ index:Int)
}
class PageTitleView: UIView {
weak var delegate:PageTitleViewDelegate?
// 上一个选中的菜单
var storedMenuLabel:UILabel?
// 菜单标题
var titles:[String]?
// 存储菜单项
var menuItems:[UILabel]?
// 选中颜色
let selectedColor : (CGFloat,CGFloat,CGFloat) = (255, 128, 0)
// 普通颜色
let normalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
// 存放菜单内容的scrollView
lazy var menuScrollView:UIScrollView = {
let scrollView = UIScrollView()
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
// 底部分隔条
lazy var menuScrollBottomLine:UIView = {
let view = UIView()
view.backgroundColor = UIColor.darkGray
let h:CGFloat = 0.5
let y:CGFloat = menuH - h
view.frame = CGRect(x: 0, y: y, width: screenW, height: h)
return view
}()
// 选中菜单标识view
lazy var selectedMenuLine:UIView = {
let view = UIView()
view.backgroundColor = UIColor.orange
let w:CGFloat = screenW / CGFloat(self.titles!.count)
let h:CGFloat = 2
let y:CGFloat = menuH - h
view.frame = CGRect(x: 0, y: y, width: w, height: h)
return view
}()
init(titles:[String], frame: CGRect) {
self.titles = titles
super.init(frame: frame)
// 初始化UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
// 初始化UI
func setupUI() {
// 1.添加菜单项
addMenuScrollView()
// 2.添加菜单与轮播视图之间的分隔线
addMenuScrollViewBottomLine()
// 3.添加菜单选中时的标识线
addSelectedLine()
}
// 添加菜单项
func addMenuScrollView() {
var labelX:CGFloat = 0
let labelY:CGFloat = 0
let labelW:CGFloat = frame.width / CGFloat(self.titles!.count)
// 存储菜单项,切换菜单时需要用到
menuItems = [UILabel]()
for (index,title) in titles!.enumerated() {
let label = UILabel()
label.text = title
label.tag = index
label.textColor = UIColor.darkGray
label.font = UIFont.systemFont(ofSize: 13)
labelX = labelW * CGFloat(index)
label.textAlignment = .center
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: menuH)
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.menuClick(_:)))
label.addGestureRecognizer(tapGes)
menuItems?.append(label)
menuScrollView.addSubview(label)
}
self.addSubview(menuScrollView)
menuScrollView.frame = bounds
}
// 添加底部分隔条
func addMenuScrollViewBottomLine() {
self.addSubview(menuScrollBottomLine)
}
// 添加选中标识
func addSelectedLine() {
// 设置第一个菜单项选中
self.menuItems!.first!.textColor = UIColor.orange
// 存储选中的菜单项
self.storedMenuLabel = self.menuItems!.first
// 添加选中标识
self.addSubview(selectedMenuLine)
}
// 菜单点击(切换选中的菜单项以及对应菜单的视图)
func menuClick(_ ges:UITapGestureRecognizer) {
// 1.恢复上次选中的菜单项颜色
self.storedMenuLabel!.textColor = UIColor.darkGray
// 2.获取点击的菜单项,设置文字颜色
let targetLabel = ges.view as! UILabel
targetLabel.textColor = UIColor.orange
// 3.存储本次点击的菜单项
self.storedMenuLabel = targetLabel
// 4.选中标识线滑动至本次点击的菜单项位置上
UIView.animate(withDuration: 0.15) {
self.selectedMenuLine.frame.origin.x = targetLabel.frame.origin.x
}
// 5.显示对应的控制器view
delegate?.pageTitleViewClick(targetLabel.tag)
}
}
extension PageTitleView {
// 滑动视图时,菜单项从选中渐变至非选中状态
func setSelectedMenuLineOffset(_ progress:CGFloat, sourceIndex:Int, targetIndex:Int) {
// 已选中的label
let sourceLabel = self.menuItems![sourceIndex]
// 滑动过程中即将选中的label
let targetLabel = self.menuItems![targetIndex]
// 1.选中标识移动
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
// 两个label的间距 乘以 进度 获得滑动过程中的位置偏移量
let moveX = moveTotalX * progress
// 设置选中标识的位置
self.selectedMenuLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 2.文字颜色渐变
let colorRange = (selectedColor.0 - normalColor.0, g: selectedColor.1 - normalColor.1, b: selectedColor.2 - normalColor.2)
// 已经选中的菜单项颜色逐渐变浅
sourceLabel.textColor = UIColor(r: selectedColor.0 - colorRange.0 * progress, g: selectedColor.1 - colorRange.1 * progress, b: selectedColor.2 - colorRange.2 * progress)
// 即将被选中的菜单项颜色逐渐加深
targetLabel.textColor = UIColor(r: normalColor.0 + colorRange.0 * progress, g: normalColor.1 + colorRange.1 * progress, b: normalColor.2 + colorRange.2 * progress)
// 3.保存选中的菜单项
self.storedMenuLabel = targetLabel
}
}
| mit | ac8135f8af4cc94c17f63ecdbe65fefd | 24.852535 | 177 | 0.573797 | 4.4 | false | false | false | false |
taji-taji/vaporReverseLookup | Sources/App/Routes.swift | 1 | 3194 | import Vapor
import Foundation
import SwiftMarkdown
final class Routes: RouteCollection {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
func build(_ builder: RouteBuilder) throws {
/// GET /
builder.get { req in
let markdown = try String(contentsOfFile: "Resources/Views/Markdown/welcome.md")
let html = try markdownToHTML(markdown, options: [])
let contents = try PageContents(node: [
"title": "逆引き Vapor",
"contentsBody": html,
"currentCategoryName": "".makeNode(in: nil),
"currentContentName": "".makeNode(in: nil),
])
.makeNode(in: StaticPageContext(page: .home))
return try self.view.make("base", contents, for: req)
}
/// GET /author
builder.get("author") { req in
let markdown = try String(contentsOfFile: "Resources/Views/Markdown/author.md")
let html = try markdownToHTML(markdown, options: [])
let contents = try PageContents(node: [
"title": "逆引き Vapor | Author",
"contentsBody": html,
"currentCategoryName": "".makeNode(in: nil),
"currentContentName": "".makeNode(in: nil),
])
.makeNode(in: StaticPageContext(page: .author))
return try self.view.make("base", contents, for: req)
}
/// search
builder.resource("search", SearchController(view))
let contents = try PageContents.getSideMenu()
contents.array?.forEach({ (category) in
guard let id = category["id"]?.string, let sub = category["sub"]?.array, let name = category["name"]?.string else {
return
}
// 各カテゴリーのグループを作成
builder.group(id, handler: { (cat_builder) in
sub.forEach({ (content) in
guard
let path = content.object?["name"]?.string,
let markdown = try? String(contentsOfFile: "Resources/Views/Markdown/Categories/\(name)/\(path).md"),
let html = try? markdownToHTML(markdown, options: [.smartQuotes, .hardBreaks, .validateUTF8]),
let c = try? PageContents(node: [
"title": "逆引き Vapor | \(name) | \(path)",
"contentsBody": html,
"currentCategoryName": name,
"currentContentName": path,
])
else {
return
}
// 各カテゴリー配下のmarkdownのコンテンツをルーティングに追加
let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
cat_builder.get(encodedPath) { req in
return try self.view.make("base", c, for: req)
}
})
})
})
}
}
| mit | 835288509941bcdac5cb95e89a70f8f6 | 40.306667 | 127 | 0.499354 | 4.886435 | false | false | false | false |
NobodyNada/chatbot | Sources/Frontend/RowEncoder.swift | 3 | 3531 | //
// RowEncoder.swift
// FireAlarm
//
// Created by NobodyNada on 7/14/17.
//
import Foundation
import SwiftChatSE
internal func nestedObject() -> Never {
fatalError("Arrays and nested dictionaries may not be encoded into database rows")
}
public class RowEncoder {
public init() {}
public func encode(_ value: Codable) throws -> Row {
let encoder = _RowEncoder()
try value.encode(to: encoder)
var columns = [DatabaseNativeType?]()
var columnIndices = [String:Int]()
for (key, value) in encoder.storage {
columnIndices[key] = columns.count
columns.append(value?.asNative)
}
return Row(columns: columns, columnNames: columnIndices)
}
}
private class _RowEncoder: Encoder {
var codingPath: [CodingKey] = []
var userInfo: [CodingUserInfoKey : Any] = [:]
var storage: [String:DatabaseType?] = [:]
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
return KeyedEncodingContainer(_KeyedEncoder<Key>(encoder: self, codingPath: codingPath))
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
nestedObject()
}
func singleValueContainer() -> SingleValueEncodingContainer {
guard !codingPath.isEmpty else {
fatalError("Root object for a database row must be a dictionary")
}
return _SingleValueContainer(encoder: self, key: codingPath.last!, codingPath: codingPath)
}
}
private class _KeyedEncoder<K: CodingKey>: KeyedEncodingContainerProtocol {
typealias Key = K
let encoder: _RowEncoder
let codingPath: [CodingKey]
init(encoder: _RowEncoder, codingPath: [CodingKey]) {
self.encoder = encoder
self.codingPath = codingPath
}
func encodeNil(forKey key: K) throws {
encoder.storage[key.stringValue] = nil as DatabaseType?
}
func encode(_ value: DatabaseType, forKey key: K) throws {
encoder.storage[key.stringValue] = value
}
func encode<T>(_ value: T, forKey key: K) throws where T : Encodable {
if let v = value as? DatabaseType {
try encode(v, forKey: key)
return
}
encoder.codingPath.append(key)
try value.encode(to: encoder)
encoder.codingPath.removeLast()
}
func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> {
nestedObject()
}
func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer {
nestedObject()
}
func superEncoder() -> Encoder {
nestedObject()
}
func superEncoder(forKey key: K) -> Encoder {
nestedObject()
}
}
private class _SingleValueContainer: SingleValueEncodingContainer {
let encoder: _RowEncoder
let key: CodingKey
let codingPath: [CodingKey]
init(encoder: _RowEncoder, key: CodingKey, codingPath: [CodingKey]) {
self.encoder = encoder
self.key = key
self.codingPath = codingPath
}
func encodeNil() throws {
try encode(nil as DatabaseType?)
}
func encode(_ value: DatabaseType?) throws {
encoder.storage[key.stringValue] = value
}
func encode<T>(_ value: T) throws where T : Encodable {
fatalError("Single-value containers may only encode DatabaseTypes")
}
}
| mit | 2870f4d213d0873fd4db8eb806f1e44a | 26.585938 | 133 | 0.626735 | 4.771622 | false | false | false | false |
pdcgomes/RendezVous | Vendor/docopt/Command.swift | 1 | 691 | //
// Command.swift
// docopt
//
// Created by Pavel S. Mazurin on 3/1/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
internal class Command: Argument {
override init(_ name: String?, value: AnyObject? = false) {
super.init(name, value: value)
}
override func singleMatch<T: LeafPattern>(left: [T]) -> SingleMatchResult {
for var i = 0; i < left.count; i++ {
let pattern = left[i]
if pattern is Argument {
if pattern.value as? String == self.name {
return (i, Command(self.name, value: true))
}
}
}
return (0, nil)
}
}
| mit | 455f7d8d6de693e804e3ed57fdfe40b6 | 24.592593 | 79 | 0.53835 | 3.81768 | false | false | false | false |
uchuugaka/OysterKit | Common/Framework/Base/Tokenizer.swift | 1 | 2913 | /*
Copyright (c) 2014, RED When Excited
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.
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.
*/
import Foundation
let __emancipateStates = true
public class Tokenizer : TokenizationState {
var namedStates = [String:Named]()
public override init(){
super.init()
}
public init(states:[TokenizationState]){
super.init()
branches = states
}
public func tokenize(string: String, newToken: (Token)->Bool) {
var emancipatedTokenization = TokenizeOperation(legacyTokenizer: self)
emancipatedTokenization.tokenize(string, tokenReceiver: newToken)
}
public func tokenize(string:String) -> Array<Token>{
var tokens = Array<Token>()
tokenize(string, newToken: {(token:Token)->Bool in
tokens.append(token)
return true
})
return tokens
}
override public class func convertFromStringLiteral(value: String) -> Tokenizer {
if let parsedTokenizer = OKStandard.parseTokenizer(value) {
return parsedTokenizer
}
return Tokenizer()
}
override public class func convertFromExtendedGraphemeClusterLiteral(value: String) -> Tokenizer {
return Tokenizer.convertFromStringLiteral(value)
}
override func serialize(indentation: String) -> String {
var output = ""
for (name,state) in namedStates {
let description = state.serialize("")
output+="\(name) = \(state.rootState.description)\n"
}
output+="begin\n"
return output+"{\n"+serializeStateArray("\t", states: branches)+"}"
}
}
| bsd-2-clause | bba1565ca6a823608f2fbb641e63eb0d | 31.730337 | 102 | 0.694473 | 4.928934 | false | false | false | false |
HotCatLX/SwiftStudy | 05-PikerViewStud/PikerViewStud/ViewController.swift | 1 | 4084 | //
// ViewController.swift
// PikerViewStud
//
// Created by suckerl on 2017/5/12.
// Copyright © 2017年 suckerl. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
var imageArray = [String]()
var dataArray1 = [Int]()
var dataArray2 = [Int]()
var dataArray3 = [Int]()
fileprivate lazy var picker :UIPickerView = {
let picker = UIPickerView()
picker.dataSource = self
picker.delegate = self
return picker
}()
fileprivate lazy var goButton :UIButton = {
let goButton = UIButton()
goButton.layer.cornerRadius = 8
goButton.backgroundColor = UIColor.orange
goButton .setTitle("GO", for: .normal)
goButton.setTitleColor(UIColor.white, for: .normal)
goButton.addTarget(self, action: #selector(ViewController.goButtonClick), for: .touchUpInside)
return goButton
}()
fileprivate lazy var resultLabel :UILabel = {
let resultLabel = UILabel()
resultLabel.textColor = UIColor.white
resultLabel.backgroundColor = UIColor.lightGray
resultLabel.layer.cornerRadius = 8
resultLabel.text = ""
resultLabel.textAlignment = .center
return resultLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(picker)
view.addSubview(goButton)
view.addSubview(resultLabel)
self.constructLayout()
imageArray = ["🐶", "🐼", "🐵", "🐸", "🐮", "🐲", "🐯", "🐰", "🐹", "🐭"]
for _ in 0 ..< 100 {
dataArray1.append((Int)(arc4random() % 10))
dataArray2.append((Int)(arc4random() % 10))
dataArray3.append((Int)(arc4random() % 10))
}
}
}
//MARK:- UIPickerViewDelegate,UIPickerViewDataSource
extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 10
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 50.0
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let emojiLabel = UILabel()
if (component == 0) {
emojiLabel.text = imageArray[(Int)(dataArray1[row])]
} else if (component == 1) {
emojiLabel.text = imageArray[(Int)(dataArray2[row])]
} else {
emojiLabel.text = imageArray[(Int)(dataArray3[row])]
}
emojiLabel.font = UIFont(name: "Apple Color Emoji", size: 40)
emojiLabel.textAlignment = .center
return emojiLabel
}
}
extension ViewController {
func constructLayout() {
picker.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(50)
make.left.equalTo(self.view).offset(50)
make.right.equalTo(self.view).offset(-50)
make.height.equalTo(200)
}
goButton.snp.makeConstraints { (make) in
make.top.equalTo(picker.snp.bottom).offset(180)
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.width.equalTo(100)
}
resultLabel.snp.makeConstraints { (make) in
make.bottom.equalTo(self.view).offset(-100)
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.width.equalTo(200)
}
}
}
extension ViewController {
func goButtonClick() {
//随机
picker.selectRow(Int(arc4random()) % 9 + 3, inComponent: 0, animated: true)
picker.selectRow(Int(arc4random()) % 9 + 3, inComponent: 1, animated: true)
picker.selectRow(Int(arc4random()) % 9 + 3, inComponent: 2, animated: true)
}
}
| mit | 748e38488e35535114d40186e18a0db4 | 29.201493 | 132 | 0.596491 | 4.531915 | false | false | false | false |
avilin/BeatTheDay | BeatTheDay/Modules/Goals/View/GoalsView.swift | 1 | 1009 | //
// GoalsView.swift
// BeatTheDay
//
// Created by Andrés Vicente Linares on 19/6/17.
// Copyright © 2017 Andrés Vicente Linares. All rights reserved.
//
import UIKit
import Anchorage
import Chameleon
class GoalsView: UIView {
var tableView: UITableView!
private var shouldSetupConstraints = true
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
tableView = UITableView()
tableView.rowHeight = 78
tableView.separatorStyle = .none
tableView.backgroundColor = .flatWhite()
addSubview(tableView)
setNeedsUpdateConstraints()
}
override func updateConstraints() {
if shouldSetupConstraints {
tableView.edgeAnchors == edgeAnchors
shouldSetupConstraints = false
}
super.updateConstraints()
}
}
| mit | b64f0a0f69b4de505fa607a90e567548 | 19.12 | 65 | 0.637177 | 4.883495 | false | false | false | false |
toineheuvelmans/Metron | Playground.playground/Pages/1.4. Triangle.xcplaygroundpage/Contents.swift | 1 | 2445 | import CoreGraphics
import Metron
/*: Triangle
# Triangle
A shape formed by three connected line segments and defined by three vertices.
*/
let a = CGPoint.zero
let b = CGPoint(x: 5.0, y: 0.0)
let c = CGPoint(x: 2.5, y: 5.0)
let triangle1 = Triangle(a: a, b: b, c: c)
// A triplet represents three related values (a, b and c) of a single type:
let triplet = Triplet(a: a, b: b, c: c)
let triangle2 = Triangle(triplet)
// Each vertex corresponds to the point (a, b, c) given on init:
triangle1.vertices
triangle1.vertexA
triangle1.vertexB
triangle1.vertexC
// Side {A} is opposite vertex {A}:
triangle1.sides
triangle1.sideA
triangle1.sideB
triangle1.sideC
let lengths = triangle1.sides.asArray.map { $0.length }
lengths
// Angle {A} is the angle at vertex {A}:
triangle1.angles
triangle1.angleA
triangle1.angleB
triangle1.angleC
// An angle bisector is a line from a vertex to the opposite side, that divides the angle in two with equal measures:
triangle1.angleBisectors
triangle1.angleBisectorA
triangle1.angleBisectorB
triangle1.angleBisectorC
// An altitude of a triangle is a straight line through a vertex perpendicular to the opposite side. `altitude{A}` goes
// perpendicular from `side{A}` to `vertex{A}`:
triangle1.altitudes
triangle1.altitudeA
triangle1.altitudeB
triangle1.altitudeC
// Classification
triangle1.isEquilateral // True if all sides are equal.
triangle1.isIsosceles // True iff two sides are equal.
triangle1.isScalene // True if all sides are different.
triangle1.isRight // True if one angle is exactly 90°.
triangle1.isOblique // True of no angle is 90°.
triangle1.isAcute // True if all angles are less than 90°.
triangle1.isObtuse // True if one angle is more than 90°.
// Centers
triangle1.centroid
triangle1.circumcenter
triangle1.incenter
triangle1.orthocenter
// `Triangle` type conforms to `PolygonType` protocol, which has the following properties:
triangle1.edgeCount
triangle1.points
triangle1.lineSegments
// `PolygonType` inherits from `Shape` protocol, which has the following properties:
triangle1.area
triangle1.perimeter
triangle1.center // Is the most common: the centroid.
triangle1.minX
triangle1.minY
triangle1.maxX
triangle1.maxY
triangle1.midX
triangle1.midY
triangle1.width
triangle1.height
triangle1.boundingRect
triangle1.contains(CGPoint(x: 2.5, y: 2.5))
//: ---
//: [BACK: Circle](@previous) | [NEXT: Square](@next)
| mit | 5e0d0c05b53a996711a1eff44a52d9c6 | 22.247619 | 120 | 0.751331 | 3.272118 | false | false | false | false |
lizhihui0215/PCCWFoundationSwift | Source/PFSNetworkService.swift | 1 | 10329 | //
// Created by 李智慧 on 02/05/2017.
//
import Moya
import Result
import RxSwift
import ObjectMapper
import Moya_ObjectMapper
import Alamofire
import KissXML
let transform = TransformOf<String, Int>(fromJSON: { String($0!) }, toJSON: { $0.map { Int($0) ?? 0 } })
public class PFSResponseMappableObject<T: Mappable>: Mappable {
public var message: String = ""
public var code: String = "-1"
public var result: T?
required public init?(map: Map){
}
public func mapping(map: Map) {
message <- map[PFSNetworkServiceStatic.__message]
let codeType = map.JSON[PFSNetworkServiceStatic.__code]
if codeType is Int {
code <- (map[PFSNetworkServiceStatic.__code], transform)
}else {
code <- map[PFSNetworkServiceStatic.__code]
}
result <- map[PFSNetworkServiceStatic.__result]
}
}
public class PFSResponseNil: Mappable {
public var message: String = ""
public var code: String = "-1"
required public init?(map: Map) {
}
public func mapping(map: Map) {
message <- map[PFSNetworkServiceStatic.__message]
let codeType = map.JSON[PFSNetworkServiceStatic.__code]
if codeType is Int {
code <- (map[PFSNetworkServiceStatic.__code], transform)
}else {
code <- map[PFSNetworkServiceStatic.__code]
}
}
}
public class PFSResponseObject<T>: Mappable {
public var message: String = ""
public var code: String = "-1"
public var result: T?
required public init?(map: Map){
}
public func mapping(map: Map) {
message <- map[PFSNetworkServiceStatic.__message]
let codeType = map.JSON[PFSNetworkServiceStatic.__code]
if codeType is Int {
code <- (map[PFSNetworkServiceStatic.__code], transform)
}else {
code <- map[PFSNetworkServiceStatic.__code]
}
result <- map[PFSNetworkServiceStatic.__result]
}
}
public class PFSResponseArray<T>: Mappable {
public var message: String = ""
public var code: String = "-1"
public var result: [T] = []
required public init?(map: Map){
}
public func mapping(map: Map) {
message <- map[PFSNetworkServiceStatic.__message]
let codeType = map.JSON[PFSNetworkServiceStatic.__code]
if codeType is Int {
code <- (map[PFSNetworkServiceStatic.__code], transform)
}else {
code <- map[PFSNetworkServiceStatic.__code]
}
result <- map[PFSNetworkServiceStatic.__result]
}
}
public class PFSResponseMappableArray<T: Mappable>: Mappable {
public var message: String = ""
public var code: String = "-1"
public var result: [T] = []
required public init?(map: Map){
}
public func mapping(map: Map) {
message <- map[PFSNetworkServiceStatic.__message]
let codeType = map.JSON[PFSNetworkServiceStatic.__code]
if codeType is Int {
code <- (map[PFSNetworkServiceStatic.__code], transform)
}else {
code <- map[PFSNetworkServiceStatic.__code]
}
result <- map[PFSNetworkServiceStatic.__result]
}
}
public protocol PFSTargetType: TargetType {
}
public func JSONResponseDataFormatter(_ data: Data) -> Data {
do {
let dataAsJSON = try JSONSerialization.jsonObject(with: data)
let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
return prettyData
} catch {
return data //fallback to original data if it cant be serialized
}
}
public enum PFSNetworkError: Swift.Error {
case serverError(String)
}
public class PFSNetworkServiceStatic{
internal static var _onceTracker = [String: Any]()
fileprivate static var __message: String = "message"
fileprivate static var __code: String = "code"
fileprivate static var __result: String = "result"
}
public class PFSNetworkService<API: PFSTargetType>: PFSNetworkServiceStatic {
let provider: MoyaProvider<API>
public static var shared: PFSNetworkService {
get {
let token = "com.pccw.foundation.swift.network.service.token.\(String(describing: PFSNetworkService.self))"
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if let shared = _onceTracker[token] {
return shared as! PFSNetworkService<API>;
}
_onceTracker[token] = PFSNetworkService<API>()
return _onceTracker[token] as! PFSNetworkService<API>
}
}
open static func config(message: String, code: String, result: String) {
__message = message
__code = code
__result = result
}
public final class func defaultEndpointMapping(for target: API) -> Endpoint<API> {
let endpoint: Endpoint<API> = Endpoint<API>(
url: url(for: target).absoluteString,
sampleResponseClosure: { .networkResponse(200, target.sampleData) },
method: target.method,
task: target.task,
httpHeaderFields: target.headers
)
return endpoint
}
public override init(){
provider = MoyaProvider<API>(endpointClosure: PFSNetworkService.defaultEndpointMapping,
requestClosure: MoyaProvider.defaultRequestMapping,
plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)],
trackInflights: false)
}
// When a TargetType's path is empty, URL.appendingPathComponent may introduce trailing /, which may not be wanted in some cases
// See: https://github.com/Moya/Moya/pull/1053
// And: https://github.com/Moya/Moya/issues/1049
public final class func url(for target: PFSTargetType) -> URL {
if target.path.isEmpty {
return target.baseURL
}
return target.baseURL.appendingPathComponent(target.path)
}
public func request<T>(_ token: API) -> Single<PFSResponseObject<T>> {
return provider.rx.request(token).mapObject(PFSResponseObject<T>.self)
}
public func request<T>(_ token: API) -> Single<PFSResponseMappableArray<T>> {
return provider.rx.request(token).mapObject(PFSResponseMappableArray<T>.self)
}
public func request<T>(_ token: API) -> Single<PFSResponseArray<T>> {
return provider.rx.request(token).mapObject(PFSResponseArray<T>.self)
}
public func request<T>(_ token: API) -> Single<PFSResponseMappableObject<T>> {
return provider.rx.request(token).mapObject(PFSResponseMappableObject<T>.self)
}
public func request(_ token: API) -> Single<PFSResponseNil> {
return provider.rx.request(token).mapObject(PFSResponseNil.self)
}
}
public struct SOAPEncoding: ParameterEncoding {
// public static var `default`: SOAPEncoding { return SOAPEncoding() }
var xml = ""
init(_ fileName: String) {
let filePath = Bundle.main.path(forResource: fileName, ofType: "xml")
xml = try! String(contentsOfFile: filePath!, encoding: .utf8)
}
func method(name: String, param: [String : String]) -> String {
let document = try! XMLDocument(xmlString: xml, options: 0)
let messages = document.rootElement()?.elements(forName: "message")
let types = document.rootElement()?.forName("types")
let schema = types?.forName("schema")
let targetNamespace = schema?.attribute(forName: "targetNamespace")?.stringValue
let namespace = XMLNode.namespace(withName: "ns1", stringValue: targetNamespace!)
let message = messages?.filter{ $0.attribute(forName: "name")?.stringValue == name }.first
let part = message?.forName("part")
let parametersString = part?.attribute(forName: "element")?.stringValue
let parameters = parametersString?.components(separatedBy: ":")
let parameterName = parameters?.last
let messageXX = XMLElement.element(withName: parameterName!) as! XMLElement
messageXX.addNamespace(namespace as! DDXMLNode)
let complexTypes = schema?.elements(forName: "complexType")
let complexType = complexTypes?.filter{ $0.attribute(forName: "name")?.stringValue == name }.first
let sequence = complexType?.forName("sequence")
let xxxx = sequence?.children as? [XMLElement]?
let ffff = xxxx??.map{ $0.attribute(forName: "name")?.stringValue }
for f in ffff! {
let value = param[f!]
messageXX.addChild(XMLElement.element(withName: f!, stringValue: value!) as! DDXMLNode)
}
let root = XMLElement(name: "soap:Envelope")
root.addNamespace(XMLNode.namespace(withName: "soap",
stringValue: "http://schemas.xmlsoap.org/soap/envelope/") as! DDXMLNode)
let header = XMLElement(name: "soap", stringValue: "Header")
let body = XMLElement(name: "soap", stringValue: "Body")
body.addChild(messageXX)
root.addChild(header)
root.addChild(body)
return root.xmlString
}
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard parameters != nil else { return urlRequest }
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = "data".data(using: .utf8)
return urlRequest
}
}
| mit | 964c62b7a6b79d9a2119666367f62953 | 30 | 135 | 0.599051 | 4.647906 | false | false | false | false |
danielsaidi/iExtra | iExtra/Operations/SerialCollectionBatchOperation.swift | 1 | 1852 | //
// SerialCollectionBatchOperation.swift
// iExtra
//
// Created by Daniel Saidi on 2019-01-26.
// Copyright © 2019 Daniel Saidi. All rights reserved.
//
/*
This protocol implements `CollectionOperation` by peforming
the operation serially.
When implementing this protocol, you therefore just have to
implement `BatchOperation`.
*/
import Foundation
public protocol SerialCollectionBatchOperation: CollectionOperation, BatchOperation {
var batchSize: Int { get }
}
public extension SerialCollectionBatchOperation {
func perform(onCollection collection: [OperationItemType], completion: @escaping CollectionCompletion) {
let batches = collection.batched(withBatchSize: batchSize)
perform(at: 0, in: batches, errors: [], completion: completion)
}
}
private extension SerialCollectionBatchOperation {
func perform(at index: Int, in batches: [[OperationItemType]], errors: [Error], completion: @escaping CollectionCompletion) {
guard batches.count > index else { return completion(errors) }
let batch = batches[index]
perform(onBatch: batch) { error in
let errors = errors + [error].compactMap { $0 }
self.perform(at: index + 1, in: batches, errors: errors, completion: completion)
}
}
}
private extension Sequence {
/**
Batch the sequence into groups of a certain max size.
*/
func batched(withBatchSize size: Int) -> [[Element]] {
var result: [[Element]] = []
var batch: [Element] = []
forEach {
batch.append($0)
if batch.count == size {
result.append(batch)
batch = []
}
}
if !batch.isEmpty {
result.append(batch)
}
return result
}
}
| mit | b8c1cf007b121970cd0ef3176ffdd89c | 25.826087 | 129 | 0.625608 | 4.650754 | false | false | false | false |
braintree/braintree_ios | Sources/BraintreeSEPADirectDebit/SEPADirectDebitAPI.swift | 1 | 3850 | import Foundation
#if canImport(BraintreeCore)
import BraintreeCore
#endif
class SEPADirectDebitAPI {
private let apiClient: BTAPIClient
@objc(initWithAPIClient:)
init(apiClient: BTAPIClient) {
self.apiClient = apiClient
}
func createMandate(
sepaDirectDebitRequest: BTSEPADirectDebitRequest,
completion: @escaping (CreateMandateResult?, Error?) -> Void
) {
let billingAddress = sepaDirectDebitRequest.billingAddress
let json: [String: Any] = [
"sepa_debit": [
"merchant_or_partner_customer_id": sepaDirectDebitRequest.customerID ?? "",
"mandate_type": sepaDirectDebitRequest.mandateType?.description ?? "",
"account_holder_name": sepaDirectDebitRequest.accountHolderName ?? "",
"iban": sepaDirectDebitRequest.iban ?? "",
"billing_address": [
"address_line_1": billingAddress?.streetAddress,
"address_line_2": billingAddress?.extendedAddress,
"admin_area_1": billingAddress?.locality,
"admin_area_2": billingAddress?.region,
"postal_code": billingAddress?.postalCode,
"country_code": billingAddress?.countryCodeAlpha2
]
],
"merchant_account_id": sepaDirectDebitRequest.merchantAccountID ?? "",
"cancel_url": sepaDirectDebitRequest.cancelURL,
"return_url": sepaDirectDebitRequest.returnURL
]
apiClient.post("v1/sepa_debit", parameters: json) { body, response, error in
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.create-mandate.started")
if let error = error {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.create-mandate.error")
completion(nil, error)
return
}
guard let body = body else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.create-mandate.no-body.error")
completion(nil, SEPADirectDebitError.noBodyReturned)
return
}
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.create-mandate.success")
let result = CreateMandateResult(json: body)
completion(result, nil)
}
}
func tokenize(createMandateResult: CreateMandateResult, completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void) {
let json: [String: Any] = [
"sepa_debit_account": [
"last_4": createMandateResult.ibanLastFour,
"merchant_or_partner_customer_id": createMandateResult.customerID,
"bank_reference_token": createMandateResult.bankReferenceToken,
"mandate_type": createMandateResult.mandateType
]
]
apiClient.post("v1/payment_methods/sepa_debit_accounts", parameters: json) { body, response, error in
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.tokenize.started")
if let error = error {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.tokenize.error")
completion(nil, error)
return
}
guard let body = body else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.tokenize.no-body.error")
completion(nil, SEPADirectDebitError.noBodyReturned)
return
}
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.api-request.tokenize.success")
let result = BTSEPADirectDebitNonce(json: body)
completion(result, nil)
}
}
}
| mit | 5c75bd236a6ac37ebc944cc4ced4aac7 | 42.258427 | 126 | 0.60961 | 4.836683 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures | Algorithms/GetAllStringPermutations.playground/Contents.swift | 1 | 762 | func stringPermutations(_ stringVal:String) -> [String]{
var returnArray:[String] = []
returnArray.append(stringVal)
var characterArray = stringVal.characters.map{String($0)}
while true{
for x in 0..<characterArray.count - 1{
swap(&characterArray[x], &characterArray[x + 1])
let permutation = toString(characterArray)
if permutation != stringVal{
returnArray.append(permutation)
}else{
return returnArray
}
}
}
}
func toString(_ characterArray:[String]) -> String{
var returnString = ""
for x in 0..<characterArray.count{
returnString += String(characterArray[x])
}
return returnString
}
| mit | 93fdb90ee6797a7e450da4028ea9975c | 25.275862 | 61 | 0.581365 | 4.792453 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.