repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
rhodgkins/UIView-IBInspectable | Tests/UIView+IBInspectable/ViewController.swift | 1 | 714 | //
// ViewController.swift
// UIView+IBInspectable
//
// Created by Richard Hodgkins on 15/11/2014.
// Copyright (c) 2014 Rich H. All rights reserved.
//
import UIKit
public class ViewController: UIViewController {
@IBOutlet weak public var noneView: UIView!
@IBOutlet weak public var cornerRadiusView: UIView!
@IBOutlet weak public var borderWidthView: UIView!
@IBOutlet weak public var borderColorView: UIView!
@IBOutlet weak public var shadowColorView: UIView!
@IBOutlet weak public var shadowOpacityView: UIView!
@IBOutlet weak public var shadowOffsetView: UIView!
@IBOutlet weak public var shadowRadiusView: UIView!
@IBOutlet weak public var allView: UIView!
}
| mit |
stasel/WWDC2015 | StasSeldin/StasSeldin/Model/StasProfile.swift | 1 | 5789 | //
// StasProfile.swift
// StasSeldin
//
// Created by Stas Seldin on 22/04/2015.
// Copyright (c) 2015 Stas Seldin. All rights reserved.
//
import Foundation
class StasProfile {
class func getProfile() -> (Profile) {
let me = Profile(name: FullName(firstName: "Stas", lastName: "Seldin"))
me.dateOfBirth = Date.dateFromComponents(year: 1989, month: 5, day: 26) as Date
me.picture = "Profile"
me.about = "I'm a young student with love and passion to create wonderful things using my programming skills."
me.backgroundPic = "Background"
// ***************** Contact info **********************
me.contact.email = "stasel@stasel.com"
me.contact.faceTime = "stasel@gmail.com"
me.contact.phoneNumber = "+31 6 12 34 56 78"
me.contact.address = Address(street: .Street("Amsterdam"), city: "Amsterdam", country: "The Netherlands")
// ***************** social media **********************
me.socialMedia.faceBook = "https://www.facebook.com/stasel"
me.socialMedia.gitHub = "https://github.com/stasel"
me.socialMedia.linkedIn = "https://linkedin.com/in/stasel"
me.socialMedia.stackOverflow = "http://stackoverflow.com/users/757338/stasel"
// ***************** education **********************
let openu = EducationRecord(degree: .BachelorsDegree("Computer sicence"), fromYear: 2012, toYear: nil, instituteName: "Open University of Israel")
me.education += [openu]
// ***************** work experience **********************
let varonis = WorkRecord(company: "Varonis Systems", role: "iOS and web developer", fromYear: 2013)
varonis.description = "Developing mobile clients for our secure enterprise data collaboration and file syncing software called “DatAnywhere”. Currently specializing in iOS development using Objective C and Swift. Building the iOS client introduced me to varies challenges: uploading and downloading files, battery life optimization, minimizing network bandwidth, supporting older iOS versions."
let matrix = WorkRecord(company: "Matrix IT", role: "Web developer", fromYear: 2010, toYear: 2013)
matrix.description = "Developed on demand enterprise level applications for Israeli health organizations. Using ASP.NET, C#, SQL, HTML, CSS and JavaScript."
let idf = WorkRecord(company: "Israeli Defence Forces", role: "Development team leader", fromYear: 2008, toYear: 2010)
idf.description = "In charge of a small developing team (2-3 developers). The team developed a large variety of software and scripts in many different languages: Warehouse management software (C#), Network monitoring tool (Perl & ASP.NET), automation scrips in Perl and batch."
me.workExperience+=[varonis,matrix,idf]
// ***************** Projects **********************
let yotamDesc = "A unique software which helps to research and prevent the Thalassemia disease. The software was designed to handle a big amount of data such as: blood test results, genetic test results, patient’s origin and more. The software analyzes the data and provides a detailed statistical information about the disease."
let yotam = Project(projectName: "Genetic research software", projectDescription: yotamDesc)
yotam.screenShots+=["Yotam"]
let webetterDesc = "Or the rise and the fall of my first start-up. After winning a hackathon, our team got the opportunity to travel to San Francisco and present our idea to the Silicon Valley. WeBetter is a platform to help organizations to find volunteers through our platform. It makes easier for people to find places to volunteer as well."
let webetter = Project(projectName: "WeBetter.do", projectDescription: webetterDesc)
webetter.screenShots+=["Webetter"]
let snifferDesc = "During my military service, I built a network monitoring software for our base in order to help the Sys Admins managing the network. It was some kind of “probe” that got into a computer, collected the data and reported back to the main database .The software was a great success and managed to monitor more than 1000 computers in our base."
let sniffer = Project(projectName: "The Sniffer", projectDescription: snifferDesc)
sniffer.screenShots+=["Sniffer"]
let chateeDesc = "Currently still in a development. Using the power of Node.js, cloud computing and web sockets protocol I am developing a mind blowing chatting service. (Of course the iOS app is also in development). I wish I could tell you more."
let chatee = Project(projectName: "Revolutionary chatting service", projectDescription: chateeDesc)
chatee.screenShots+=["Chatee"]
me.projects += [yotam, webetter, sniffer, chatee]
// ***************** Skills **********************
me.skills += ["HTML", "CSS", "JavaScript", "Swift", "Objective C", "C#", "node.js","Java", "C", "Rest design", "Design patterns", "SQL", "MongoDB"]
// ***************** Hobbies **********************
let swimming = Hobby(name: "Swimming")
swimming.picture = "Swimming"
let coding = Hobby(name: "Writing some code")
coding.picture = "Coding"
let friends = Hobby(name: "Hanging out with friends")
friends.picture = "Friends"
let family = Hobby(name: "My Girlfriend and our Cat")
family.picture = "Family"
let traveling = Hobby(name: "Traveling")
traveling.picture = "Traveling"
me.hobbies += [traveling, coding, swimming, friends, family]
return me
}
}
| mit |
swiftde/28-SizeClasses | SizeClasses-Tutorial/SizeClasses-TutorialTests/SizeClasses_TutorialTests.swift | 2 | 948 | //
// SizeClasses_TutorialTests.swift
// SizeClasses-TutorialTests
//
// Created by Benjamin Herzog on 26.09.14.
// Copyright (c) 2014 Benjamin Herzog. All rights reserved.
//
import UIKit
import XCTest
class SizeClasses_TutorialTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
asbhat/stanford-ios10-apps | FaceIt/FaceIt/VCLLoggingViewController.swift | 1 | 3704 | //
// VCLLoggingViewController.swift
//
// Created by CS193p Instructor.
// Copyright © 2015-17 Stanford University. All rights reserved.
//
import UIKit
class VCLLoggingViewController : UIViewController {
private struct LogGlobals {
var prefix = ""
var instanceCounts = [String:Int]()
var lastLogTime = Date()
var indentationInterval: TimeInterval = 1
var indentationString = "__"
}
private static var logGlobals = LogGlobals()
private static func logPrefix(for className: String) -> String {
if logGlobals.lastLogTime.timeIntervalSinceNow < -logGlobals.indentationInterval {
logGlobals.prefix += logGlobals.indentationString
print("")
}
logGlobals.lastLogTime = Date()
return logGlobals.prefix + className
}
private static func bumpInstanceCount(for className: String) -> Int {
logGlobals.instanceCounts[className] = (logGlobals.instanceCounts[className] ?? 0) + 1
return logGlobals.instanceCounts[className]!
}
private var instanceCount: Int!
private func logVCL(_ msg: String) {
let className = String(describing: type(of: self))
if instanceCount == nil {
instanceCount = VCLLoggingViewController.bumpInstanceCount(for: className)
}
print("\(VCLLoggingViewController.logPrefix(for: className))(\(instanceCount!)) \(msg)")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
logVCL("init(coder:) - created via InterfaceBuilder ")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
logVCL("init(nibName:bundle:) - create in code")
}
deinit {
logVCL("left the heap")
}
override func awakeFromNib() {
logVCL("awakeFromNib()")
}
override func viewDidLoad() {
super.viewDidLoad()
logVCL("viewDidLoad()")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logVCL("viewWillAppear(animated = \(animated))")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
logVCL("viewDidAppear(animated = \(animated))")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
logVCL("viewWillDisappear(animated = \(animated))")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
logVCL("viewDidDisappear(animated = \(animated))")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
logVCL("didReceiveMemoryWarning()")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
logVCL("viewWillLayoutSubviews() bounds.size = \(view.bounds.size)")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
logVCL("viewDidLayoutSubviews() bounds.size = \(view.bounds.size)")
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
logVCL("viewWillTransition(to: \(size), with: coordinator)")
coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.logVCL("begin animate(alongsideTransition:completion:)")
}, completion: { context -> Void in
self.logVCL("end animate(alongsideTransition:completion:)")
})
}
}
| apache-2.0 |
alex-alex/S2Geometry | Sources/S2LatLng.swift | 1 | 5512 | //
// S2LatLng.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public struct S2LatLng: Equatable {
/// Approximate "effective" radius of the Earth in meters.
public static let earthRadiusMeters: Double = 6367000
public let lat: S1Angle
public let lng: S1Angle
public static func latitude(point p: S2Point) -> S1Angle {
// We use atan2 rather than asin because the input vector is not necessarily
// unit length, and atan2 is much more accurate than asin near the poles.
return S1Angle(radians: atan2(p.z, sqrt(p.x * p.x + p.y * p.y)))
}
public static func longitude(point p: S2Point) -> S1Angle {
// Note that atan2(0, 0) is defined to be zero.
return S1Angle(radians: atan2(p.y, p.x))
}
public init(lat: S1Angle = S1Angle(), lng: S1Angle = S1Angle()) {
self.lat = lat
self.lng = lng
}
public static func fromRadians(lat: Double, lng: Double) -> S2LatLng {
return S2LatLng(lat: S1Angle(radians: lat), lng: S1Angle(radians: lng))
}
public static func fromDegrees(lat: Double, lng: Double) -> S2LatLng {
return S2LatLng(lat: S1Angle(degrees: lat), lng: S1Angle(degrees: lng))
}
public static func fromE5(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e5: lat), lng: S1Angle(e5: lng))
}
public static func fromE6(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e6: lat), lng: S1Angle(e6: lng))
}
public static func fromE7(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e7: lat), lng: S1Angle(e7: lng))
}
/// Convert a point (not necessarily normalized) to an S2LatLng.
public init(point p: S2Point) {
// The latitude and longitude are already normalized. We use atan2 to
// compute the latitude because the input vector is not necessarily unit
// length, and atan2 is much more accurate than asin near the poles.
// Note that atan2(0, 0) is defined to be zero.
self.init(lat: S2LatLng.latitude(point: p), lng: S2LatLng.longitude(point: p))
}
/**
Return true if the latitude is between -90 and 90 degrees inclusive and the
longitude is between -180 and 180 degrees inclusive.
*/
public var isValid: Bool {
return abs(lat.radians) <= M_PI_2 && abs(lng.radians) <= M_PI
}
/**
Returns a new S2LatLng based on this instance for which `isValid` will be `true`.
- Latitude is clipped to the range `[-90, 90]`
- Longitude is normalized to be in the range `[-180, 180]`
If the current point is valid then the returned point will have the same coordinates.
*/
public var normalized: S2LatLng {
// drem(x, 2 * S2.M_PI) reduces its argument to the range
// [-S2.M_PI, S2.M_PI] inclusive, which is what we want here.
return S2LatLng.fromRadians(lat: max(-M_PI_2, min(M_PI_2, lat.radians)), lng: remainder(lng.radians, 2 * M_PI))
}
/// Convert an S2LatLng to the equivalent unit-length vector (S2Point).
public var point: S2Point {
let phi = lat.radians
let theta = lng.radians
let cosphi = cos(phi)
return S2Point(x: cos(theta) * cosphi, y: sin(theta) * cosphi, z: sin(phi))
}
/// Return the distance (measured along the surface of the sphere) to the given point.
public func getDistance(to o: S2LatLng) -> S1Angle {
// This implements the Haversine formula, which is numerically stable for
// small distances but only gets about 8 digits of precision for very large
// distances (e.g. antipodal points). Note that 8 digits is still accurate
// to within about 10cm for a sphere the size of the Earth.
//
// This could be fixed with another sin() and cos() below, but at that point
// you might as well just convert both arguments to S2Points and compute the
// distance that way (which gives about 15 digits of accuracy for all
// distances).
let lat1 = lat.radians
let lat2 = o.lat.radians
let lng1 = lng.radians
let lng2 = o.lng.radians
let dlat = sin(0.5 * (lat2 - lat1))
let dlng = sin(0.5 * (lng2 - lng1))
let x = dlat * dlat + dlng * dlng * cos(lat1) * cos(lat2)
return S1Angle(radians: 2 * atan2(sqrt(x), sqrt(max(0.0, 1.0 - x))))
// Return the distance (measured along the surface of the sphere) to the
// given S2LatLng. This is mathematically equivalent to:
//
// S1Angle::FromRadians(ToPoint().Angle(o.ToPoint())
//
// but this implementation is slightly more efficient.
}
/// Returns the surface distance to the given point assuming a constant radius.
public func getDistance(to o: S2LatLng, radius: Double = S2LatLng.earthRadiusMeters) -> Double {
// TODO(dbeaumont): Maybe check that radius >= 0 ?
return getDistance(to: o).radians * radius
}
/// Returns true if both the latitude and longitude of the given point are within {@code maxError} radians of this point.
public func approxEquals(to other: S2LatLng, maxError: Double = 1e-9) -> Bool {
return (abs(lat.radians - other.lat.radians) < maxError) && (abs(lng.radians - other.lng.radians) < maxError)
}
}
public func ==(lhs: S2LatLng, rhs: S2LatLng) -> Bool {
return lhs.lat == rhs.lat && lhs.lng == rhs.lng
}
public func +(lhs: S2LatLng, rhs: S2LatLng) -> S2LatLng {
return S2LatLng(lat: lhs.lat + rhs.lat, lng: lhs.lng + rhs.lng)
}
public func -(lhs: S2LatLng, rhs: S2LatLng) -> S2LatLng {
return S2LatLng(lat: lhs.lat - rhs.lat, lng: lhs.lng - rhs.lng)
}
public func *(lhs: S2LatLng, m: Double) -> S2LatLng {
return S2LatLng(lat: lhs.lat * m, lng: lhs.lng * m)
}
| mit |
jacobwhite/firefox-ios | SyncTelemetry/SyncTelemetry.swift | 5 | 4132 | /* 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 Alamofire
import Foundation
import XCGLogger
import SwiftyJSON
import Shared
private let log = Logger.browserLogger
private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL!
private let AppName = "Fennec"
public enum TelemetryDocType: String {
case core = "core"
case sync = "sync"
}
public protocol SyncTelemetryEvent {
func record(_ prefs: Prefs)
}
open class SyncTelemetry {
private static var prefs: Prefs?
private static var telemetryVersion: Int = 4
open class func initWithPrefs(_ prefs: Prefs) {
assert(self.prefs == nil, "Prefs already initialized")
self.prefs = prefs
}
open class func recordEvent(_ event: SyncTelemetryEvent) {
guard let prefs = prefs else {
assertionFailure("Prefs not initialized")
return
}
event.record(prefs)
}
open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) {
let docID = UUID().uuidString
let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
let channel = AppConstants.BuildChannel.rawValue
let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)"
let url = ServerURL.appendingPathComponent(path)
var request = URLRequest(url: url)
log.debug("Ping URL: \(url)")
log.debug("Ping payload: \(ping.payload.stringValue() ?? "")")
// Don't add the common ping format for the mobile core ping.
let pingString: String?
if docType != .core {
var json = JSON(commonPingFormat(forType: docType))
json["payload"] = ping.payload
pingString = json.stringValue()
} else {
pingString = ping.payload.stringValue()
}
guard let body = pingString?.data(using: .utf8) else {
log.error("Invalid data!")
assertionFailure()
return
}
guard channel != "default" else {
log.debug("Non-release build; not sending ping")
return
}
request.httpMethod = "POST"
request.httpBody = body
request.addValue(Date().toRFC822String(), forHTTPHeaderField: "Date")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
SessionManager.default.request(request).response { response in
log.debug("Ping response: \(response.response?.statusCode ?? -1).")
}
}
private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = formatter.string(from: NSDate() as Date)
let displayVersion = [
AppInfo.appVersion,
"b",
AppInfo.buildNumber
].joined()
let version = ProcessInfo.processInfo.operatingSystemVersion
let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
return [
"type": type.rawValue,
"id": UUID().uuidString,
"creationDate": date,
"version": SyncTelemetry.telemetryVersion,
"application": [
"architecture": "arm",
"buildId": AppInfo.buildNumber,
"name": AppInfo.displayName,
"version": AppInfo.appVersion,
"displayVersion": displayVersion,
"platformVersion": osVersion,
"channel": AppConstants.BuildChannel.rawValue
]
]
}
}
public protocol SyncTelemetryPing {
var payload: JSON { get }
}
| mpl-2.0 |
shorlander/firefox-ios | Client/Frontend/Accessors/HomePageAccessors.swift | 6 | 1701 | /* 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 XCGLogger
/// Accessors for homepage details from the app state.
/// These are pure functions, so it's quite ok to have them
/// as static.
class HomePageAccessors {
fileprivate static let getPrefs = Accessors.getPrefs
static func getHomePage(_ state: AppState) -> URL? {
return getHomePage(getPrefs(state))
}
static func hasHomePage(_ state: AppState) -> Bool {
return getHomePage(state) != nil
}
static func isButtonInMenu(_ state: AppState) -> Bool {
return isButtonInMenu(getPrefs(state))
}
static func isButtonEnabled(_ state: AppState) -> Bool {
switch state.ui {
case .tab:
return true
case .homePanels, .loading:
return hasHomePage(state)
default:
return false
}
}
}
extension HomePageAccessors {
static func isButtonInMenu(_ prefs: Prefs) -> Bool {
return prefs.boolForKey(HomePageConstants.HomePageButtonIsInMenuPrefKey) ?? true
}
static func getHomePage(_ prefs: Prefs) -> URL? {
let string = prefs.stringForKey(HomePageConstants.HomePageURLPrefKey) ?? getDefaultHomePageString(prefs)
guard let urlString = string else {
return nil
}
return NSURL(string: urlString) as URL?
}
static func getDefaultHomePageString(_ prefs: Prefs) -> String? {
return prefs.stringForKey(HomePageConstants.DefaultHomePageURLPrefKey)
}
}
| mpl-2.0 |
MadAppGang/SmartLog | iOS/Pods/CoreStore/Sources/CSBaseDataTransaction.swift | 2 | 10005 | //
// CSBaseDataTransaction.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 CoreData
// MARK: - CSBaseDataTransaction
/**
The `CSBaseDataTransaction` serves as the Objective-C bridging type for `BaseDataTransaction`.
- SeeAlso: `BaseDataTransaction`
*/
@objc
public class CSBaseDataTransaction: NSObject {
// MARK: Object management
/**
Indicates if the transaction has pending changes
*/
@objc
public var hasChanges: Bool {
return self.swiftTransaction.hasChanges
}
/**
Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `CSInto` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
@objc
public func createInto(_ into: CSInto) -> Any {
return self.swiftTransaction.create(into.bridgeToSwift)
}
/**
Returns an editable proxy of a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@objc
public func editObject(_ object: NSManagedObject?) -> Any? {
return self.swiftTransaction.edit(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: a `CSInto` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@objc
public func editInto(_ into: CSInto, objectID: NSManagedObjectID) -> Any? {
return self.swiftTransaction.edit(into.bridgeToSwift, objectID)
}
/**
Deletes a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` to be deleted
*/
@objc
public func deleteObject(_ object: NSManagedObject?) {
self.swiftTransaction.delete(object)
}
/**
Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted
*/
@objc
public func deleteObjects(_ objects: [NSManagedObject]) {
self.swiftTransaction.delete(objects)
}
/**
Refreshes all registered objects `NSManagedObject`s in the transaction.
*/
@objc
public func refreshAndMergeAllObjects() {
self.swiftTransaction.refreshAndMergeAllObjects()
}
// MARK: Inspecting Pending Objects
/**
Returns all pending `NSManagedObject`s of the specified type that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were inserted to the transaction.
*/
@objc
public func insertedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.insertedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s that were inserted to the transaction.
*/
@objc
public func insertedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.insertedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction.
*/
@objc
public func insertedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.insertedObjectIDs(entity)
}
/**
Returns all pending `NSManagedObject`s of the specified type that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were updated in the transaction.
*/
@objc
public func updatedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.updatedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s that were updated in the transaction.
*/
@objc
public func updatedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.updatedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction.
*/
@objc
public func updatedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.updatedObjectIDs(entity)
}
/**
Returns all pending `NSManagedObject`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.deletedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.deletedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.deletedObjectIDs(entity)
}
// MARK: NSObject
public override var hash: Int {
return ObjectIdentifier(self.swiftTransaction).hashValue
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSBaseDataTransaction else {
return false
}
return self.swiftTransaction === object.swiftTransaction
}
// MARK: Internal
internal let swiftTransaction: BaseDataTransaction
internal init(_ swiftValue: BaseDataTransaction) {
self.swiftTransaction = swiftValue
super.init()
}
// MARK: Deprecated
@available(*, deprecated, message: "Use -[insertedObjectsOfType:] and pass the specific entity class")
@objc
public func insertedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.insertedObjects()
}
@available(*, deprecated, message: "Use -[updatedObjectsOfType:] and pass the specific entity class")
@objc
public func updatedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.updatedObjects()
}
@available(*, deprecated, message: "Use -[deletedObjectsOfType:] and pass the specific entity class")
@objc
public func deletedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.deletedObjects()
}
}
| mit |
jongwonwoo/CodeSamples | StackView/StackViewInScrollView/AppStore/AppStore/AppInfo.swift | 1 | 272 | //
// AppInfo.swift
// AppStore
//
// Created by Jongwon Woo on 25/06/2017.
// Copyright © 2017 WooJongwon. All rights reserved.
//
import Foundation
struct AppInfo {
let name: String
let identifier: String
let iconUrl: URL
let sellerName: String
}
| mit |
hkellaway/Gloss | Sources/Gloss/ExtensionDictionary.swift | 1 | 3846 | //
// ExtensionDictionary.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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
extension Dictionary {
// MARK: - Public Functions
/**
Retrieves value from dictionary given a key path delimited with
provided delimiter to indicate a nested value.
For example, a dictionary with [ "outer" : [ "inner" : "value" ] ]
could retrive 'value' via path "outer.inner", given a
delimiter of ''.
- parameter keyPath: Key path delimited by delimiter.
- parameter delimiter: Delimiter.
- parameter logger: Logger.
- returns: Value retrieved from dic
*/
public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter, logger: Logger = GlossLogger()) -> Any? {
let keys = keyPath.components(separatedBy: delimiter)
guard keys.first as? Key != nil else {
logger.log(message: "Unable to use keyPath '\(keyPath)' as key on type: \(Key.self)")
return nil
}
return self.findValue(keys: keys)
}
// MARK: - Internal functions
/**
Creates a dictionary from a list of elements.
This allows use of map, flatMap and filter.
- parameter elements: Elements to add to the new dictionary.
*/
internal init(elements: [Element]) {
self.init()
for (key, value) in elements {
self[key] = value
}
}
/**
Flat map for dictionary.
- parameter transform: Transform function.
- returns: New dictionary of transformed values.
*/
internal func flatMap<KeyPrime : Hashable, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
return Dictionary<KeyPrime,ValuePrime>(elements: try compactMap({ (key, value) in
return try transform(key, value)
}))
}
// MARK: - Private functions
/**
Retrieves value from dictionary given a key path delimited with
provided delimiter by going down the dictionary stack tree
- parameter keys: Array of keys splited by delimiter
- parameter depthLevel: Indicates current depth level in the dictionary tree
- returns: object retrieved from dic
*/
private func findValue(keys: [String], depthLevel: Int = 0) -> Any? {
if let currentKey = keys[depthLevel] as? Key {
if depthLevel == keys.count-1 {
return self[currentKey]
} else if let newDict = self[currentKey] as? Dictionary {
return newDict.findValue(keys: keys, depthLevel: depthLevel+1)
}
}
return nil
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Filter/FilterSheetViewController.swift | 1 | 1299 | class FilterSheetViewController: UIViewController {
private let viewTitle: String
private let filters: [FilterProvider]
private let changedFilter: (ReaderAbstractTopic) -> Void
init(viewTitle: String,
filters: [FilterProvider],
changedFilter: @escaping (ReaderAbstractTopic) -> Void) {
self.viewTitle = viewTitle
self.filters = filters
self.changedFilter = changedFilter
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = FilterSheetView(viewTitle: viewTitle,
filters: filters,
presentationController: self,
changedFilter: changedFilter)
}
}
extension FilterSheetViewController: DrawerPresentable {
func handleDismiss() {
WPAnalytics.track(.readerFilterSheetDismissed)
}
var scrollableView: UIScrollView? {
return (view as? FilterSheetView)?.tableView
}
var collapsedHeight: DrawerHeight {
if traitCollection.verticalSizeClass == .compact {
return .maxHeight
} else {
return .contentHeight(0)
}
}
}
| gpl-2.0 |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/View Controllers/MyTBA/MyTBAViewController.swift | 1 | 8351 | import CoreData
import FirebaseAuth
import GoogleSignIn
import MyTBAKit
import Photos
import PureLayout
import TBAData
import TBAKit
import UIKit
import UserNotifications
class MyTBAViewController: ContainerViewController {
private let myTBA: MyTBA
private let pasteboard: UIPasteboard?
private let photoLibrary: PHPhotoLibrary?
private let statusService: StatusService
private let urlOpener: URLOpener
private(set) var signInViewController: MyTBASignInViewController = MyTBASignInViewController()
private(set) var favoritesViewController: MyTBATableViewController<Favorite, MyTBAFavorite>
private(set) var subscriptionsViewController: MyTBATableViewController<Subscription, MyTBASubscription>
private var signInView: UIView! {
return signInViewController.view
}
private lazy var signOutBarButtonItem: UIBarButtonItem = {
return UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(logoutTapped))
}()
private var signOutActivityIndicatorBarButtonItem = UIBarButtonItem.activityIndicatorBarButtonItem()
var isLoggingOut: Bool = false {
didSet {
DispatchQueue.main.async {
self.updateInterface()
}
}
}
private var isLoggedIn: Bool {
return myTBA.isAuthenticated
}
init(myTBA: MyTBA, pasteboard: UIPasteboard? = nil, photoLibrary: PHPhotoLibrary? = nil, statusService: StatusService, urlOpener: URLOpener, dependencies: Dependencies) {
self.myTBA = myTBA
self.pasteboard = pasteboard
self.photoLibrary = photoLibrary
self.statusService = statusService
self.urlOpener = urlOpener
favoritesViewController = MyTBATableViewController<Favorite, MyTBAFavorite>(myTBA: myTBA, dependencies: dependencies)
subscriptionsViewController = MyTBATableViewController<Subscription, MyTBASubscription>(myTBA: myTBA, dependencies: dependencies)
super.init(viewControllers: [favoritesViewController, subscriptionsViewController],
segmentedControlTitles: ["Favorites", "Subscriptions"],
dependencies: dependencies)
title = RootType.myTBA.title
tabBarItem.image = RootType.myTBA.icon
favoritesViewController.delegate = self
subscriptionsViewController.delegate = self
GIDSignIn.sharedInstance()?.presentingViewController = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// TODO: Fix the white status bar/white UINavigationController during sign in
// https://github.com/the-blue-alliance/the-blue-alliance-ios/issues/180
// modalPresentationCapturesStatusBarAppearance = true
styleInterface()
myTBA.authenticationProvider.add(observer: self)
}
// MARK: - Private Methods
private func styleInterface() {
addChild(signInViewController)
view.addSubview(signInView)
for edge in [ALEdge.top, ALEdge.bottom] {
signInView.autoPinEdge(toSuperviewSafeArea: edge)
}
for edge in [ALEdge.leading, ALEdge.trailing] {
signInView.autoPinEdge(toSuperviewEdge: edge)
}
updateInterface()
}
private func updateInterface() {
if isLoggingOut {
rightBarButtonItems = [signOutActivityIndicatorBarButtonItem]
} else {
rightBarButtonItems = isLoggedIn ? [signOutBarButtonItem] : []
}
// Disable interaction with our view while logging out
view.isUserInteractionEnabled = !isLoggingOut
signInView.isHidden = isLoggedIn
}
private func logout() {
let signOutOperation = myTBA.unregister { [weak self] (_, error) in
self?.isLoggingOut = false
if let error = error as? MyTBAError, error.code != 404 {
self?.errorRecorder.record(error)
self?.showErrorAlert(with: "Unable to sign out of myTBA - \(error.localizedDescription)")
} else {
// Run on main thread, since we delete our Core Data objects on the main thread.
DispatchQueue.main.async {
self?.logoutSuccessful()
}
}
}
guard let op = signOutOperation else { return }
isLoggingOut = true
OperationQueue.main.addOperation(op)
}
private func logoutSuccessful() {
GIDSignIn.sharedInstance().signOut()
try! Auth.auth().signOut()
// Cancel any ongoing requests
for vc in [favoritesViewController, subscriptionsViewController] as! [Refreshable] {
vc.cancelRefresh()
}
// Remove all locally stored myTBA data
removeMyTBAData()
}
func removeMyTBAData() {
persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Favorite.entity())
persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Subscription.entity())
// Clear notifications
persistentContainer.viewContext.performSaveOrRollback(errorRecorder: errorRecorder)
}
// MARK: - Interface Methods
@objc func logoutTapped() {
let signOutAlertController = UIAlertController(title: "Log Out?", message: "Are you sure you want to sign out of myTBA?", preferredStyle: .alert)
signOutAlertController.addAction(UIAlertAction(title: "Log Out", style: .default, handler: { (_) in
self.logout()
}))
signOutAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(signOutAlertController, animated: true, completion: nil)
}
}
extension MyTBAViewController: MyTBATableViewControllerDelegate {
func eventSelected(_ event: Event) {
let viewController = EventViewController(event: event, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
func teamSelected(_ team: Team) {
let viewController = TeamViewController(team: team, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
func matchSelected(_ match: Match) {
let viewController = MatchViewController(match: match, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
}
extension MyTBAViewController: MyTBAAuthenticationObservable {
@objc func authenticated() {
if let viewController = currentViewController() {
viewController.refresh()
}
updateInterfaceMain()
}
@objc func unauthenticated() {
updateInterfaceMain()
}
func updateInterfaceMain() {
DispatchQueue.main.async { [weak self] in
self?.updateInterface()
}
}
}
| mit |
kickstarter/ios-oss | Library/NSBundleType+Tests.swift | 1 | 513 | @testable import Library
import XCTest
class NSBundleTests: XCTestCase {
func testDebugAppVersionString() {
let bundle = MockBundle(bundleIdentifier: KickstarterBundleIdentifier.debug.rawValue, lang: "en")
XCTAssertEqual(bundle.appVersionString, "1.2.3.4.5.6.7.8.9.0 #1234567890")
}
func testReleaseAppVersionString() {
let bundle = MockBundle(bundleIdentifier: KickstarterBundleIdentifier.release.rawValue, lang: "en")
XCTAssertEqual(bundle.appVersionString, "1.2.3.4.5.6.7.8.9.0")
}
}
| apache-2.0 |
kickstarter/ios-oss | KsApi/models/lenses/ProjectStatsEnvelope.VideoStatsLenses.swift | 1 | 1460 | import Prelude
extension ProjectStatsEnvelope.VideoStats {
public enum lens {
public static let externalCompletions = Lens<ProjectStatsEnvelope.VideoStats, Int>(
view: { $0.externalCompletions },
set: { ProjectStatsEnvelope.VideoStats(
externalCompletions: $0, externalStarts: $1.externalStarts,
internalCompletions: $1.internalCompletions, internalStarts: $1.internalStarts
) }
)
public static let externalStarts = Lens<ProjectStatsEnvelope.VideoStats, Int>(
view: { $0.externalStarts },
set: { ProjectStatsEnvelope.VideoStats(
externalCompletions: $1.externalCompletions, externalStarts: $0,
internalCompletions: $1.internalCompletions, internalStarts: $1.internalStarts
) }
)
public static let internalCompletions = Lens<ProjectStatsEnvelope.VideoStats, Int>(
view: { $0.internalCompletions },
set: { ProjectStatsEnvelope.VideoStats(
externalCompletions: $1.externalCompletions,
externalStarts: $1.externalStarts, internalCompletions: $0, internalStarts: $1.internalStarts
) }
)
public static let internalStarts = Lens<ProjectStatsEnvelope.VideoStats, Int>(
view: { $0.internalStarts },
set: { ProjectStatsEnvelope.VideoStats(
externalCompletions: $1.externalCompletions,
externalStarts: $1.externalStarts, internalCompletions: $1.internalCompletions, internalStarts: $0
) }
)
}
}
| apache-2.0 |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/View Elements/Events/EventTeamStatCellViewModel.swift | 1 | 476 | import Foundation
import TBAData
struct EventTeamStatCellViewModel {
let statName: String
let statValue: String
init(eventTeamStat: EventTeamStat?, statName: String, statKey: String) {
statValue = {
guard let statValue = eventTeamStat?.value(forKey: statKey) as? Double else {
return "----"
}
return String(format: "%.2f", statValue)
}()
self.statName = statName.uppercased()
}
}
| mit |
kickstarter/ios-oss | Library/ViewModels/PledgeExpandableRewardsHeaderViewModelTests.swift | 1 | 3472 | @testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
import XCTest
final class PledgeExpandableRewardsHeaderViewModelTests: TestCase {
internal let vm: PledgeExpandableRewardsHeaderViewModelType = PledgeExpandableRewardsHeaderViewModel()
private let loadRewardsIntoDataSource = TestObserver<[PledgeExpandableRewardsHeaderItem], Never>()
private let expandRewards = TestObserver<Bool, Never>()
override func setUp() {
super.setUp()
self.vm.outputs.loadRewardsIntoDataSource.observe(self.loadRewardsIntoDataSource.observer)
self.vm.outputs.expandRewards.observe(self.expandRewards.observer)
}
func testLoadRewardsIntoDataSource() {
self.loadRewardsIntoDataSource.assertDidNotEmitValue()
let reward1 = Reward.template
|> Reward.lens.id .~ Int(1)
|> Reward.lens.title .~ "Reward 1"
|> Reward.lens.estimatedDeliveryOn .~ 1_475_361_315
|> Reward.lens.minimum .~ 60
let reward2 = Reward.template
|> Reward.lens.id .~ Int(2)
|> Reward.lens.title .~ "Reward 2"
|> Reward.lens.estimatedDeliveryOn .~ 1_475_461_315
|> Reward.lens.minimum .~ 20
let reward3 = Reward.template
|> Reward.lens.id .~ Int(3)
|> Reward.lens.title .~ "Reward 3"
|> Reward.lens.estimatedDeliveryOn .~ 1_475_561_315
|> Reward.lens.minimum .~ 40
let data = PledgeExpandableRewardsHeaderViewData(
rewards: [reward1, reward2, reward3],
selectedQuantities: [reward1.id: 1, reward2.id: 1, reward3.id: 2],
projectCountry: .us,
omitCurrencyCode: false
)
self.vm.inputs.configure(with: data)
self.vm.inputs.viewDidLoad()
self.loadRewardsIntoDataSource.assertValueCount(1)
guard let itemData = self.loadRewardsIntoDataSource.lastValue else {
XCTFail("Should have data")
return
}
XCTAssertEqual(itemData.count, 4)
XCTAssertEqual(itemData[0].data.text, "Estimated delivery October 2016")
XCTAssertEqual(itemData[0].data.amount.string, " US$ 160")
XCTAssertEqual(itemData[0].isHeader, true)
XCTAssertEqual(itemData[0].isReward, false)
XCTAssertEqual(itemData[1].data.text, "Reward 1")
XCTAssertEqual(itemData[1].data.amount.string, "US$ 60")
XCTAssertEqual(itemData[1].isHeader, false)
XCTAssertEqual(itemData[1].isReward, true)
XCTAssertEqual(itemData[2].data.text, "Reward 2")
XCTAssertEqual(itemData[2].data.amount.string, "US$ 20")
XCTAssertEqual(itemData[2].isHeader, false)
XCTAssertEqual(itemData[2].isReward, true)
XCTAssertEqual(itemData[3].data.text, "2 x Reward 3")
XCTAssertEqual(itemData[3].data.amount.string, "US$ 40")
XCTAssertEqual(itemData[3].isHeader, false)
XCTAssertEqual(itemData[3].isReward, true)
}
func testExpandRewards() {
self.expandRewards.assertDidNotEmitValue()
let data = PledgeExpandableRewardsHeaderViewData(
rewards: [.template, .template, .template],
selectedQuantities: [:],
projectCountry: .us,
omitCurrencyCode: false
)
self.vm.inputs.configure(with: data)
self.vm.inputs.viewDidLoad()
self.expandRewards.assertDidNotEmitValue()
self.vm.inputs.expandButtonTapped()
self.expandRewards.assertValues([true])
self.vm.inputs.expandButtonTapped()
self.expandRewards.assertValues([true, false])
self.vm.inputs.expandButtonTapped()
self.expandRewards.assertValues([true, false, true])
}
}
| apache-2.0 |
nghialv/Sapporo | Sapporo/Sources/Core/Sapporo+UIScrollViewDelegate.swift | 1 | 2077 | //
// Sapporo+UIScrollViewDelegate.swift
// Example
//
// Created by Le VanNghia on 4/3/16.
// Copyright © 2016 Le Van Nghia. All rights reserved.
//
import UIKit
extension Sapporo {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.scrollViewDidScroll?(scrollView)
guard loadmoreEnabled else {
return
}
let offset = scrollView.contentOffset
let y = direction == .vertical ? offset.y + scrollView.bounds.height - scrollView.contentInset.bottom : offset.x + scrollView.bounds.width - scrollView.contentInset.right
let h = direction == .vertical ? scrollView.contentSize.height : scrollView.contentSize.width
if y > h - loadmoreDistanceThreshold {
loadmoreEnabled = false
loadmoreHandler?()
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
delegate?.scrollViewWillBeginDragging?(scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
delegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
delegate?.scrollViewWillBeginDecelerating?(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
delegate?.scrollViewDidEndDecelerating?(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
delegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
delegate?.scrollViewDidScrollToTop?(scrollView)
}
}
| mit |
Roche/viper-module-generator | VIPERGenDemo/VIPERGenDemo/Shared/Controllers/TwitterLogin/Interactor/TwitterLoginInteractor.swift | 4 | 1021 | //
// TwitterLoginInteractor.swift
// TwitterLoginGenDemo
//
// Created by AUTHOR on 24/10/14.
// Copyright (c) 2014 AUTHOR. All rights reserved.
//
import Foundation
class TwitterLoginInteractor: TwitterLoginInteractorInputProtocol
{
weak var presenter: TwitterLoginInteractorOutputProtocol?
var APIDataManager: TwitterLoginAPIDataManagerInputProtocol?
var localDatamanager: TwitterLoginLocalDataManagerInputProtocol?
init() {}
// MARK: - TwitterLoginInteractorInputProtocol
func login(completion: (error: NSError?) -> ())
{
self.APIDataManager?.login({ [weak self] (error: NSError?, credentials: TwitterLoginItem?) -> () in
if (credentials != nil) {
self?.localDatamanager?.persistUserCredentials(credentials: credentials!)
self?.localDatamanager?.setupLocalStorage()
completion(error: nil)
}
else {
completion(error: error)
}
})
}
} | mit |
jhwayne/Minimo | SwifferApp/SwifferApp/ComposeViewController.swift | 1 | 2928 | //
// ComposeViewController.swift
// SwifferApp
//
// Created by Training on 29/06/14.
// Copyright (c) 2014 Training. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController, UITextViewDelegate {
@IBOutlet var sweetTextView: UITextView! = UITextView()
@IBOutlet var charRemainingLabel: UILabel! = UILabel()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
sweetTextView.layer.borderColor = UIColor.blackColor().CGColor
sweetTextView.layer.borderWidth = 0.5
sweetTextView.layer.cornerRadius = 5
sweetTextView.delegate = self
sweetTextView.becomeFirstResponder()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendSweet(sender: AnyObject) {
var query = PFQuery(className:"Posts")
query.whereKey("DisplayToday", equalTo:"Yes")
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject!, error: NSError!) -> Void in
if (error != nil || object == nil) {
}
else {
// The find succeeded.
let ID = object["PostID"] as Int
var sweet:PFObject = PFObject(className: "Sweets")
sweet["content"] = self.sweetTextView.text
sweet["sweeter"] = PFUser.currentUser()
sweet["PostID"] = ID
sweet.saveInBackground()
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
func textView(textView: UITextView!,
shouldChangeTextInRange range: NSRange,
replacementText text: String!) -> Bool{
var newLength:Int = (textView.text as NSString).length + (text as NSString).length - range.length
var remainingChar:Int = 140 - newLength
charRemainingLabel.text = "\(remainingChar)"
return (newLength > 140) ? false : true
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit |
LibraryLoupe/PhotosPlus | PhotosPlus/Cameras/Leica/LeicaDIGILUX3.swift | 3 | 498 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Leica {
public struct DIGILUX3: CameraModel {
public init() {}
public let name = "Leica DIGILUX 3"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Leica.self
}
}
public typealias LeicaDIGILUX3 = Cameras.Manufacturers.Leica.DIGILUX3
| mit |
yarec/FeedParser | FeedParser/FeedParser.swift | 1 | 14024 | //
// FeedParser.swift
// FeedParser
//
// Created by Andreas Geitmann on 18.11.14.
// Copyright (c) 2014 simutron IT-Service. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public protocol FeedParserDelegate {
func didStartFeedParsing(parser:FeedParser)
func didFinishFeedParsing(parser:FeedParser, newsFeed:NewsFeed?)
func anErrorOccured(parser:FeedParser, error:NSError)
}
enum ParseMode {
case FEED, ENTRY, IMAGE
}
public class FeedParser: NSObject, NSXMLParserDelegate {
public var newsFeed:NewsFeed = NewsFeed()
public var delegate:FeedParserDelegate?
var parseMode:ParseMode = ParseMode.FEED
var currentContent:String = ""
var tmpEntry:NewsFeedEntry = NewsFeedEntry()
var lastParseMode:ParseMode?
var tmpImage:NewsImage?
// MARK: - Public Functions
public func parseFeedFromUrl(urlString:String) {
self.delegate?.didStartFeedParsing(self)
self.newsFeed.url = urlString
var feedUrl = NSURL(string: urlString)
var parser = NSXMLParser(contentsOfURL: feedUrl!)
parser?.delegate = self
parser?.parse()
}
public func parseFeedFromFile(fileString:String) {
self.delegate?.didStartFeedParsing(self)
self.newsFeed.url = fileString
let feedUrl = NSURL(fileURLWithPath: fileString)
let parser = NSXMLParser(contentsOfURL: feedUrl)
parser?.delegate = self
parser?.parse()
}
// MARK: - NSXMLParserDelegate
public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.currentContent = ""
switch self.newsFeed.feedType {
case FeedType.ATOM:
switch elementName {
case "entry":
self.tmpEntry = NewsFeedEntry()
self.parseMode = ParseMode.ENTRY
case "link":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.link = attributeDict["href"]! //as! String
break
case ParseMode.ENTRY:
self.tmpEntry.link = attributeDict["href"]! //as! String
break
case ParseMode.IMAGE:
break
}
case "enclosure", "media:content":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
self.tmpImage?.url = attributeDict["url"]! //as! String
}
case "title", "updated", "id", "summary", "content", "author", "name":
// Element is not needed for parsing
break
default:
log("ATOM Element's name is \(elementName)")
log("ATOM Element's attributes are \(attributeDict)")
}
case FeedType.RSS:
switch elementName {
case "item":
self.tmpEntry = NewsFeedEntry()
self.parseMode = ParseMode.ENTRY
case "image":
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
case "enclosure", "media:content":
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
self.tmpImage?.url = attributeDict["url"]! //as! String
default:
log("Element's name is \(elementName)")
log("Element's attributes are \(attributeDict)")
}
default:
switch elementName {
case "feed":
self.newsFeed.feedType = FeedType.ATOM
case "channel":
self.newsFeed.feedType = FeedType.RSS
case "title", "updated", "id", "summary", "content":
// Element is not needed for parsing
break
default:
log("RSS Element's name is \(elementName)")
log("RSS Element's attributes are \(attributeDict)")
}
}
}
public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName:String?) {
switch self.newsFeed.feedType {
case FeedType.ATOM:
switch elementName {
case "title":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.title = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.title = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.title = self.currentContent
break
}
case "updated":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.lastUpdated = self.parseRFC3339DateFromString(self.currentContent)
break
case ParseMode.ENTRY:
self.tmpEntry.lastUpdated = self.parseRFC3339DateFromString(self.currentContent)
break
case ParseMode.IMAGE:
break
}
case "id":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.id = self.currentContent
break
case ParseMode.ENTRY:
self.tmpEntry.id = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "summary":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.tmpEntry.summary = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "content":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.tmpEntry.content = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "entry":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.newsFeed.entries[self.tmpEntry.id] = self.tmpEntry
break
case ParseMode.IMAGE:
break
}
case "image", "enclosure", "media:content":
self.parseMode = self.lastParseMode!
if (self.parseMode == ParseMode.FEED) {
self.newsFeed.images.append(self.tmpImage!)
} else if (self.parseMode == ParseMode.ENTRY) {
self.tmpEntry.images.append(self.tmpImage!)
}
case "link", "feed", "author", "name":
// Content not used, value is stored in attribute
break
default:
log("UNKNOWN END ATOM Element \(elementName)")
}
case FeedType.RSS:
switch elementName {
case "guid":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.id = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.id = self.currentContent
case ParseMode.IMAGE:
break
}
case "link":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.link = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.link = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.link? = self.currentContent
}
case "title":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.title = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.title = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.title? = self.currentContent
}
case "url":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
self.tmpImage?.url = self.currentContent
}
case "description":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.summary = self.currentContent
break
case ParseMode.ENTRY:
self.tmpEntry.summary = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "pubDate":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.lastUpdated = self.parseRFC822DateFromString(self.currentContent)
break
case ParseMode.ENTRY:
self.tmpEntry.lastUpdated = self.parseRFC822DateFromString(self.currentContent)
break
case ParseMode.IMAGE:
break
}
case "language":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.language = self.currentContent
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
break
}
case "image", "enclosure", "media:content":
self.parseMode = self.lastParseMode!
if (self.parseMode == ParseMode.FEED) {
self.newsFeed.images.append(self.tmpImage!)
} else if (self.parseMode == ParseMode.ENTRY) {
self.tmpEntry.images.append(self.tmpImage!)
}
case "item":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
if self.tmpEntry.id.isEmpty {
self.newsFeed.entries[self.tmpEntry.link] = self.tmpEntry
} else {
self.newsFeed.entries[self.tmpEntry.id] = self.tmpEntry
}
break
case ParseMode.IMAGE:
break
}
case "channel", "rss":
// Content not used, value is stored in attribute
break
default:
log("UNKNOWN END RSS Element \(elementName)")
}
default:
log("UNKNOWN feedType \(self.newsFeed.feedType)")
}
}
public func parser(parser: NSXMLParser, foundCharacters string: String?) {
self.currentContent += string!
}
public func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
log("Error: \(parseError.description)")
self.delegate?.anErrorOccured(self, error: parseError)
}
public func parserDidEndDocument(parser: NSXMLParser) {
self.delegate?.didFinishFeedParsing(self, newsFeed: self.newsFeed)
}
// MARK: - Private Functions
private func parseRFC3339DateFromString(string:String) -> NSDate {
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
let rfc3339DateFormatter = NSDateFormatter()
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let date:NSDate? = rfc3339DateFormatter.dateFromString(string)
if let isDate = date {
return isDate
}
return NSDate()
}
private func parseRFC822DateFromString(string:String) -> NSDate {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
let date:NSDate? = dateFormat.dateFromString(string)
if let isDate = date {
return isDate
}
return NSDate()
}
private func log(str:String){
// println(str)
}
}
| apache-2.0 |
pankcuf/DataContext | DataContext/Classes/TableDataImpl.swift | 1 | 4842 | //
// TableDataImpl.swift
// DataContext
//
// Created by Vladimir Pirogov on 27/03/17.
// Copyright © 2016 Vladimir Pirogov. All rights reserved.
//
import Foundation
import UIKit
open class TableDataImpl: NSObject, UITableViewDataSource, UITableViewDelegate {
/// Table Delegates
@objc(tableView:heightForRowAtIndexPath:) open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let ctx = tableView.tableView(tableView, contextForRowAt: indexPath)
return ctx?.getDefaultHeight() ?? 0
}
@objc(tableView:estimatedHeightForRowAtIndexPath:) open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let ctx = tableView.tableView(tableView, contextForRowAt: indexPath)
return ctx?.getDefaultHeight() ?? 0
}
@objc(tableView:willDisplayCell:forRowAtIndexPath:) open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard self.tableView(tableView, heightForRowAt: indexPath) != UITableViewAutomaticDimension else { return }
cell.context = tableView.tableView(tableView, contextForRowAt: indexPath)
cell.contextDelegate = tableView
}
open func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerSectionContext = tableView.tableView(tableView, contextFor: section)?.headerContext,
headerSectionContext.getDefaultHeight() != UITableViewAutomaticDimension else { return }
view.context = headerSectionContext
view.contextDelegate = tableView
}
open func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard let footerSectionContext = tableView.tableView(tableView, contextFor: section)?.footerContext,
footerSectionContext.getDefaultHeight() != UITableViewAutomaticDimension else { return }
view.context = footerSectionContext
view.contextDelegate = tableView
}
@objc(numberOfSectionsInTableView:) open func numberOfSections(in tableView: UITableView) -> Int {
return tableView.tableDataContext()?.sectionContext.count ?? 0
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableView.tableView(tableView, contextFor: section)?.rowContext.count ?? 0
}
@objc(tableView:cellForRowAtIndexPath:) open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = indexPath.section
let row = indexPath.row
let ctx = tableView.tableView(tableView, contextFor: section)!
let rows = ctx.rowContext
let cellContext = rows[row]
let reuseId = cellContext.reuseId
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId)!
if self.tableView(tableView, heightForRowAt: indexPath) == UITableViewAutomaticDimension {
cell.context = tableView.tableView(tableView, contextForRowAt: indexPath)
cell.contextDelegate = tableView
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
}
return cell
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let headerSectionContext = tableView.tableView(tableView, contextFor: section)?.headerContext {
if let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerSectionContext.reuseId) {
if self.tableView(tableView, heightForHeaderInSection: section) == UITableViewAutomaticDimension {
header.context = headerSectionContext
header.contextDelegate = tableView
header.contentView.setNeedsLayout()
header.contentView.layoutIfNeeded()
}
return header
}
}
return nil
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let footerSectionContext = tableView.tableView(tableView, contextFor: section)?.footerContext {
if let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: footerSectionContext.reuseId) {
if self.tableView(tableView, heightForFooterInSection: section) == UITableViewAutomaticDimension {
footer.context = footerSectionContext
footer.contextDelegate = tableView
footer.contentView.setNeedsLayout()
footer.contentView.layoutIfNeeded()
}
return footer
}
}
return nil
}
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.tableView(tableView, contextFor: section)?.headerContext?.getDefaultHeight() ?? 0
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return tableView.tableView(tableView, contextFor: section)?.footerContext?.getDefaultHeight() ?? 0
}
}
| mit |
jatoma/ManagedOperation | ManagedOperation/ManagedBlockOperation.swift | 1 | 414 | //
// ManagedBlockOperation.swift
// ManagedOperation
//
// Created by jatoma on 19.02.2016.
//
import UIKit
public class ManagedBlockOperation: ManagedOperation {
public typealias Closure = (ManagedOperation) -> ()
let closure: Closure
public init(closure: Closure) {
self.closure = closure
}
public override func start() {
self.closure(self)
}
}
| mit |
slightair/ff14booklet | iOS/ff14booklet/WeatherForecastLocationCell.swift | 1 | 1251 | //
// WeatherForecastLocationCell.swift
// ff14booklet
//
// Created by tomohiro-moro on 9/14/14.
// Copyright (c) 2014 slightair. All rights reserved.
//
import UIKit
class WeatherForecastLocationCell: UITableViewCell {
@IBOutlet var locationLabel: UILabel!
@IBOutlet var forecastImageView1: UIImageView!
@IBOutlet var forecastImageView2: UIImageView!
@IBOutlet var forecastImageView3: UIImageView!
@IBOutlet var forecastImageView4: UIImageView!
@IBOutlet var forecastLabel1: UILabel!
@IBOutlet var forecastLabel2: UILabel!
@IBOutlet var forecastLabel3: UILabel!
@IBOutlet var forecastLabel4: UILabel!
func updateWithLocation(location: WeatherForecastLocation) {
self.locationLabel.text = location.location.title()
for i in 1...4 {
let imageView = self.valueForKey("forecastImageView\(i)") as? UIImageView
let label = self.valueForKey("forecastLabel\(i)") as? UILabel
let weather = location.forecasts[i - 1]
label?.text = weather.title()
if let imageURL = weather.imageURL() {
imageView?.sd_setImageWithURL(imageURL)
} else {
imageView?.image = nil
}
}
}
}
| mit |
arvedviehweger/swift | test/APINotes/versioned.swift | 1 | 5020 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 4 | %FileCheck -check-prefix=CHECK-SWIFT-4 %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 3 | %FileCheck -check-prefix=CHECK-SWIFT-3 %s
// CHECK-SWIFT-4: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-3: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-4: func accept(_ ptr: UnsafeMutablePointer<Double>)
// CHECK-SWIFT-3: func acceptPointer(_ ptr: UnsafeMutablePointer<Double>?)
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s
// RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 3 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-3 %s
// RUN: %target-swift-frontend -emit-silgen -F %S/Inputs/custom-frameworks -swift-version 4 %s -DSILGEN 2>&1 | %FileCheck -check-prefix=CHECK-SILGEN -check-prefix=CHECK-SILGEN-4 %s
import APINotesFrameworkTest
#if !SILGEN
func testRenamedTopLevelDiags() {
var value = 0.0
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
accept(&value)
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:3: error: 'accept' has been renamed to 'acceptPointer(_:)'
// CHECK-DIAGS-3: note: 'accept' was introduced in Swift 4
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
acceptPointer(&value)
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:3: error: 'acceptPointer' has been renamed to 'accept(_:)'
// CHECK-DIAGS-4: note: 'acceptPointer' was obsoleted in Swift 4
acceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'acceptDoublePointer' has been renamed to
// CHECK-DIAGS-4-SAME: 'accept(_:)'
// CHECK-DIAGS-3-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'acceptDoublePointer' was obsoleted in Swift 3
oldAcceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'oldAcceptDoublePointer' has been renamed to
// CHECK-DIAGS-4-SAME: 'accept(_:)'
// CHECK-DIAGS-3-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'oldAcceptDoublePointer' has been explicitly marked unavailable here
_ = SomeCStruct()
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:7: error: 'SomeCStruct' has been renamed to
// CHECK-DIAGS-4-SAME: 'VeryImportantCStruct'
// CHECK-DIAGS-3-SAME: 'ImportantCStruct'
// CHECK-DIAGS: note: 'SomeCStruct' was obsoleted in Swift 3
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
_ = ImportantCStruct()
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:7: error: 'ImportantCStruct' has been renamed to 'VeryImportantCStruct'
// CHECK-DIAGS-4: note: 'ImportantCStruct' was obsoleted in Swift 4
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
_ = VeryImportantCStruct()
// CHECK-DIAGS-3-NOTE: versioned.swift:[[@LINE-1]]:
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
_ = InnerInSwift4()
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:7: error: 'InnerInSwift4' has been renamed to 'Outer.Inner'
// CHECK-DIAGS-4: note: 'InnerInSwift4' was obsoleted in Swift 4
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
_ = Outer.Inner()
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE-1]]:
}
func testAKA(structValue: ImportantCStruct, aliasValue: ImportantCAlias) {
let _: Int = structValue
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCStruct' to specified type 'Int'
let _: Int = aliasValue
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'ImportantCAlias' (aka 'Int32') to specified type 'Int'
let optStructValue: Optional = structValue
let _: Int = optStructValue
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'Optional<ImportantCStruct>' to specified type 'Int'
let optAliasValue: Optional = aliasValue
let _: Int = optAliasValue
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:16: error: cannot convert value of type 'Optional<ImportantCAlias>' (aka 'Optional<Int32>') to specified type 'Int'
}
#endif
#if !swift(>=4)
func useSwift3Name(_: ImportantCStruct) {}
// CHECK-SILGEN-3: sil hidden @_T09versioned13useSwift3NameySo20VeryImportantCStructVF
func useNewlyNested(_: InnerInSwift4) {}
// CHECK-SILGEN-3: sil hidden @_T09versioned14useNewlyNestedySo5OuterV5InnerVF
#endif
func useSwift4Name(_: VeryImportantCStruct) {}
// CHECK-SILGEN: sil hidden @_T09versioned13useSwift4NameySo20VeryImportantCStructVF
| apache-2.0 |
ngageoint/mage-ios | Mage/ObservationFormReorder.swift | 1 | 6765 | //
// ObservationFormReorder.swift
// MAGE
//
// Created by Daniel Barela on 1/19/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MDCContainerScheme;
@objc protocol ObservationFormReorderDelegate {
func formsReordered(observation: Observation);
func cancelReorder();
}
class ObservationFormReorder: UITableViewController {
let cellReuseIdentifier = "formCell";
let observation: Observation;
let delegate: ObservationFormReorderDelegate;
var observationForms: [[String: Any]] = [];
var observationProperties: [String: Any] = [ : ];
var scheme: MDCContainerScheming?;
private lazy var event: Event? = {
guard let eventId = observation.eventId, let context = observation.managedObjectContext else {
return nil
}
return Event.getEvent(eventId: eventId, context: context)
}()
private lazy var eventForms: [Form]? = {
return event?.forms
}()
private lazy var descriptionHeaderView: UILabel = {
let label = UILabel(forAutoLayout: ());
label.text = "The first form in this list is the primary form, which determines how MAGE displays the observation on the map and in the feed. The forms will be displayed, as ordered, in all other views.";
label.numberOfLines = 0;
label.lineBreakMode = .byWordWrapping;
return label;
}()
private lazy var headerView: UIView = {
let view = UIView();
view.addSubview(descriptionHeaderView);
descriptionHeaderView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
return view;
}()
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(observation: Observation, delegate: ObservationFormReorderDelegate, containerScheme: MDCContainerScheming?) {
self.observation = observation
self.delegate = delegate;
self.scheme = containerScheme;
super.init(style: .grouped)
self.title = "Reorder Forms";
self.view.accessibilityLabel = "Reorder Forms";
tableView.register(cellClass: ObservationFormTableViewCell.self)
if let properties = self.observation.properties as? [String: Any] {
if (properties.keys.contains(ObservationKey.forms.key)) {
observationForms = properties[ObservationKey.forms.key] as! [[String: Any]];
}
self.observationProperties = properties;
} else {
self.observationProperties = [ObservationKey.forms.key:[]];
observationForms = [];
}
}
func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) {
guard let containerScheme = containerScheme else {
return
}
self.scheme = containerScheme;
self.tableView.backgroundColor = containerScheme.colorScheme.backgroundColor;
self.view.backgroundColor = containerScheme.colorScheme.backgroundColor;
self.descriptionHeaderView.font = containerScheme.typographyScheme.overline;
self.descriptionHeaderView.textColor = containerScheme.colorScheme.onBackgroundColor.withAlphaComponent(0.6)
}
override func viewDidLoad() {
super.viewDidLoad();
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Apply", style: .done, target: self, action: #selector(self.saveFormOrder(sender:)));
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(self.cancel(sender:)));
self.tableView.isEditing = true;
self.tableView.rowHeight = UITableView.automaticDimension;
self.tableView.estimatedRowHeight = 64;
self.tableView.tableFooterView = UIView();
self.view.addSubview(headerView);
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
applyTheme(withContainerScheme: scheme);
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let newSize = headerView.systemLayoutSizeFitting(CGSize(width: self.tableView.bounds.width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
headerView.autoSetDimensions(to: newSize);
tableView.contentInset = UIEdgeInsets(top: headerView.frame.size.height, left: 0, bottom: 0, right: 0);
headerView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: -1 * newSize.height, left: 0, bottom: 0, right: 0), excludingEdge: .bottom);
}
@objc func cancel(sender: UIBarButtonItem) {
delegate.cancelReorder();
}
@objc func saveFormOrder(sender: UIBarButtonItem) {
observationProperties[ObservationKey.forms.key] = observationForms;
self.observation.properties = observationProperties;
delegate.formsReordered(observation: self.observation);
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Drag to reorder forms";
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = self.observationForms[sourceIndexPath.row]
observationForms.remove(at: sourceIndexPath.row)
observationForms.insert(movedObject, at: destinationIndexPath.row)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return observationForms.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let formCell : ObservationFormTableViewCell = tableView.dequeue(cellClass: ObservationFormTableViewCell.self, forIndexPath: indexPath);
let observationForm = observationForms[indexPath.row];
if let eventForm: Form = self.eventForms?.first(where: { (form) -> Bool in
return form.formId?.intValue == observationForm[EventKey.formId.key] as? Int
}) {
formCell.configure(observationForm: observationForm, eventForm: eventForm, scheme: self.scheme);
}
return formCell
}
}
| apache-2.0 |
manhpro/website | iOSQuiz-master/iOSQuiz-master/LeoiOSQuiz/Classes/Models/Coordinate.swift | 1 | 520 | //
// Coordinate.swift
// LeoiOSQuiz
//
// Created by framgia on 4/18/17.
// Copyright © 2017 Leo LE. All rights reserved.
//
import UIKit
import ObjectMapper
class Coordinate: Mappable {
var latitude: Double
var longtitude: Double
init() {
self.latitude = 0.0
self.longtitude = 0.0
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
latitude <- map["latitude"]
longtitude <- map["longitude"]
}
}
| cc0-1.0 |
andrewBatutin/SwiftYamp | SwiftYamp/Models/CloseFrame.swift | 1 | 2492 | //
// CloseFrame.swift
// SwiftYamp
//
// Created by Andrey Batutin on 6/13/17.
// Copyright © 2017 Andrey Batutin. All rights reserved.
//
import Foundation
import ByteBackpacker
public enum CloseCodeType: UInt8{
case Unknown = 0x00
case VersionNotSupported = 0x01
case Timeout = 0x02
case Redirect = 0x03
}
public struct CloseFrame: Equatable, YampFrame, YampTypedFrame{
private let typeIndex = 0x00
private let closeCodeIndex = 0x01
private let sizeIndex = 0x02
private let messageIndex = 0x04
public var frameType:FrameType{
return type.type
}
let type:BaseFrame = BaseFrame(type: FrameType.Close)
let closeCode:CloseCodeType
let size:UInt16
var message:String = "" // (optional)
public static func ==(lhs: CloseFrame, rhs: CloseFrame) -> Bool {
return lhs.type == rhs.type && lhs.closeCode == rhs.closeCode && lhs.size == rhs.size && lhs.message == rhs.message
}
public init(closeCode: CloseCodeType) {
self.closeCode = closeCode
self.size = 0
}
public init(closeCode: CloseCodeType, message: String?) {
self.closeCode = closeCode
self.size = UInt16(message?.characters.count ?? 0)
self.message = message ?? ""
}
public init(data: Data) throws{
let dataSize = data.count
if dataSize < messageIndex { throw SerializationError.WrongDataFrameSize(dataSize) }
guard let cCode = CloseCodeType(rawValue: data[closeCodeIndex]) else {
throw SerializationError.CloseCodeTypeNotFound(data[closeCodeIndex])
}
closeCode = cCode
size = UInt16(bigEndian: data.subdata(in: sizeIndex..<messageIndex).withUnsafeBytes{$0.pointee})
let offset:Int = messageIndex + Int(size)
if dataSize != offset { throw SerializationError.WrongDataFrameSize(dataSize) }
let s = data.subdata(in: messageIndex..<offset)
message = String(data: s, encoding: String.Encoding.utf8) ?? ""
}
public func toData() throws -> Data{
var r = ByteBackpacker.pack(self.type.type.rawValue)
r = r + ByteBackpacker.pack(self.closeCode.rawValue)
r = r + ByteBackpacker.pack(self.size, byteOrder: .bigEndian)
guard let encStr = self.message.data(using: .utf8) else{
throw SerializationError.UnexpectedError
}
var res = Data(bytes: r)
res.append(encStr)
return res
}
}
| mit |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Controller/HotTopicViewController.swift | 1 | 4005 | //
// HotTopicViewController.swift
// WeCenterMobile
//
// Created by Bill Hu on 15/12/9.
// Copyright © 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class HotTopicViewController: MSRSegmentedViewController, MSRSegmentedViewControllerDelegate {
override class var positionOfSegmentedControl: MSRSegmentedControlPosition {
return .Top
}
override func loadView() {
super.loadView()
let theme = SettingsManager.defaultManager.currentTheme
segmentedControl.indicator = MSRSegmentedControlUnderlineIndicator()
segmentedControl.tintColor = theme.titleTextColor
segmentedControl.indicator.tintColor = theme.subtitleTextColor
(segmentedControl.backgroundView as! UIToolbar).barStyle = theme.toolbarStyle
view.backgroundColor = theme.backgroundColorA
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Navigation-Root"), style: .Plain, target: self, action: "showSidebar")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Publishment-Article_Question"), style: .Plain, target: self, action: "didPressPublishButton")
msr_navigationBar!.msr_shadowImageView?.hidden = true
scrollView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
scrollView.delaysContentTouches = false
scrollView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.sidebar.screenEdgePanGestureRecognizer)
delegate = self
}
var firstAppear = true
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if firstAppear {
firstAppear = false
let titles: [(TopicObjectListType, String)] = [
(.Focus, "我关注的"),
(.All, "全部"),
(.Month, "最近30天"),
(.Week, "最近7天")]
let vcs: [UIViewController] = titles.map {
(type, title) in
let vc = HotTopicListViewController(type: type)
vc.title = title
return vc
}
setViewControllers(vcs, animated: false)
}
}
func msr_segmentedViewController(segmentedViewController: MSRSegmentedViewController, didSelectViewController viewController: UIViewController?) {
(viewController as? HotTopicListViewController)?.segmentedViewControllerDidSelectSelf(segmentedViewController)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return SettingsManager.defaultManager.currentTheme.statusBarStyle
}
func showSidebar() {
appDelegate.mainViewController.sidebar.expand()
}
func didPressPublishButton() {
let ac = UIAlertController(title: "发布什么?", message: "选择发布的内容种类。", preferredStyle: .ActionSheet)
let presentPublishmentViewController: (String, PublishmentViewControllerPresentable) -> Void = {
[weak self] title, object in
let vc = NSBundle.mainBundle().loadNibNamed("PublishmentViewControllerA", owner: nil, options: nil).first as! PublishmentViewController
vc.dataObject = object
vc.headerLabel.text = title
self?.presentViewController(vc, animated: true, completion: nil)
}
ac.addAction(UIAlertAction(title: "问题", style: .Default) {
action in
presentPublishmentViewController("发布问题", Question.temporaryObject())
})
ac.addAction(UIAlertAction(title: "文章", style: .Default) {
action in
presentPublishmentViewController("发布文章", Article.temporaryObject())
})
ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
| gpl-2.0 |
segmentio/analytics-swift | Examples/apps/SegmentWeatherWidget/WeatherWidget/WeatherWidgetView.swift | 1 | 4069 | //
// WeatherWidgetView.swift
// SegmentWeatherWidgetExample
//
// Created by Alan Charles on 10/26/22.
//
import SwiftUI
import Segment
struct WeatherView: View {
let weather: Weather
let updatedData: Date
var body: some View {
VStack(alignment: .leading) {
Text("San Francisco")
Text("\(weather.temperature)°\(weather.unit)")
.font(.largeTitle)
Text(WeatherUtils.getWeatherIcon(weather.description))
.padding(.top, 10)
Text(weather.description)
.font(.footnote)
HStack {
Spacer()
Text("Update: \(updatedData.timeOnly())")
.font(.system(size: 12))
.foregroundColor(.secondary)
}
}.padding()
}
}
struct DailyWeatherView: View {
let weather: Weather
var body: some View {
VStack(alignment: .leading) {
Text(weather.name.lowercased().contains("night") ? "\(weather.name.prefix(2)) 🌙" : weather.name.prefix(2))
Text("\(weather.temperature)°\(weather.unit)")
Text(WeatherUtils.getWeatherIcon(weather.description))
.padding(.top, 10)
}.padding()
}
}
struct WeatherEntryView: View {
var analytics: Analytics?
let entry: WeatherEntry
@Environment(\.widgetFamily) var family
let baseColor = Color.gray.opacity(0.2)
let darkColor = Color.black.opacity(0.8)
var body: some View {
switch family {
case .systemSmall:
ZStack {
baseColor
WeatherView(weather: entry.weatherInfo[0], updatedData: entry.date)
}.edgesIgnoringSafeArea(.all)
case .systemMedium:
ZStack {
HStack(spacing: 0) {
Rectangle().fill(baseColor)
Rectangle().fill(darkColor)
}
HStack {
WeatherView(weather: entry.weatherInfo[0], updatedData: entry.date)
WeatherView(weather: entry.weatherInfo[1], updatedData: entry.date)
.foregroundColor(.white)
}
}
case .systemLarge:
VStack{
ZStack {
HStack(spacing: 0) {
Rectangle().fill(baseColor)
Rectangle().fill(darkColor)
}
HStack {
WeatherView(weather: entry.weatherInfo[0], updatedData: entry.date)
WeatherView(weather: entry.weatherInfo[1], updatedData: entry.date)
.foregroundColor(.white)
}
}
VStack {
HStack {
VStack(alignment: .leading) {
DailyWeatherView(weather: entry.weatherInfo[2])
DailyWeatherView(weather: entry.weatherInfo[3])
}
VStack(alignment: .leading) {
DailyWeatherView(weather: entry.weatherInfo[4])
DailyWeatherView(weather: entry.weatherInfo[5])
}
VStack(alignment: .leading) {
DailyWeatherView(weather: entry.weatherInfo[6])
DailyWeatherView(weather: entry.weatherInfo[7])
}
VStack(alignment: .leading) {
DailyWeatherView(weather: entry.weatherInfo[8])
DailyWeatherView(weather: entry.weatherInfo[9])
}
}
}
}
default:
ZStack {
baseColor
WeatherView(weather: entry.weatherInfo[0], updatedData: entry.date)
}.edgesIgnoringSafeArea(.all)
}
}
}
| mit |
nathawes/swift | test/Serialization/comments.swift | 23 | 6564 | // Test the case when we have a single file in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t | %FileCheck %s -check-prefix=FIRST
// Test the case when we have a multiple files in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/first.swiftmodule -emit-module-doc -emit-module-doc-path %t/first.swiftdoc -primary-file %s %S/Inputs/def_comments.swift -emit-module-source-info-path %t/first.swiftsourceinfo
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/second.swiftmodule -emit-module-doc -emit-module-doc-path %t/second.swiftdoc %s -primary-file %S/Inputs/def_comments.swift -emit-module-source-info-path %t/second.swiftsourceinfo
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %t/first.swiftmodule %t/second.swiftmodule -emit-module-source-info-path %t/comments.swiftsourceinfo
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=FIRST < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SECOND < %t.printed.txt
// BCANALYZER-NOT: UnknownCode
/// first_decl_generic_class_1 Aaa.
public class first_decl_generic_class_1<T> {
/// deinit of first_decl_generic_class_1 Aaa.
deinit {
}
}
/// first_decl_class_1 Aaa.
public class first_decl_class_1 {
/// decl_func_1 Aaa.
public func decl_func_1() {}
/**
* decl_func_3 Aaa.
*/
public func decl_func_2() {}
/// decl_func_3 Aaa.
/** Bbb. */
public func decl_func_3() {}
}
/// Comment for bar1
extension first_decl_class_1 {
func bar1(){}
}
/// Comment for bar2
extension first_decl_class_1 {
func bar2(){}
}
public protocol P1 { }
/// Comment for no member extension
extension first_decl_class_1 : P1 {}
// FIRST: comments.swift:26:14: Class/first_decl_generic_class_1 RawComment=[/// first_decl_generic_class_1 Aaa.\n]
// FIRST: comments.swift:28:3: Destructor/first_decl_generic_class_1.deinit RawComment=[/// deinit of first_decl_generic_class_1 Aaa.\n]
// FIRST: comments.swift:33:14: Class/first_decl_class_1 RawComment=[/// first_decl_class_1 Aaa.\n]
// FIRST: comments.swift:36:15: Func/first_decl_class_1.decl_func_1 RawComment=[/// decl_func_1 Aaa.\n]
// FIRST: comments.swift:41:15: Func/first_decl_class_1.decl_func_2 RawComment=[/**\n * decl_func_3 Aaa.\n */]
// FIRST: comments.swift:45:15: Func/first_decl_class_1.decl_func_3 RawComment=[/// decl_func_3 Aaa.\n/** Bbb. */]
// SECOND: comments.swift:49:1: Extension/ RawComment=[/// Comment for bar1\n] BriefComment=[Comment for bar1]
// SECOND: comments.swift:54:1: Extension/ RawComment=[/// Comment for bar2\n] BriefComment=[Comment for bar2]
// SECOND: comments.swift:61:1: Extension/ RawComment=[/// Comment for no member extension\n] BriefComment=[Comment for no member extension]
// SECOND: Inputs/def_comments.swift:2:14: Class/second_decl_class_1 RawComment=[/// second_decl_class_1 Aaa.\n]
// SECOND: Inputs/def_comments.swift:5:15: Struct/second_decl_struct_1
// SECOND: Inputs/def_comments.swift:7:9: Accessor/second_decl_struct_1.<getter for second_decl_struct_1.instanceVar>
// SECOND: Inputs/def_comments.swift:8:9: Accessor/second_decl_struct_1.<setter for second_decl_struct_1.instanceVar>
// SECOND: Inputs/def_comments.swift:10:17: Enum/second_decl_struct_1.NestedEnum
// SECOND: Inputs/def_comments.swift:11:22: TypeAlias/second_decl_struct_1.NestedTypealias
// SECOND: Inputs/def_comments.swift:14:13: Enum/second_decl_enum_1
// SECOND: Inputs/def_comments.swift:15:10: EnumElement/second_decl_enum_1.Case1
// SECOND: Inputs/def_comments.swift:16:10: EnumElement/second_decl_enum_1.Case2
// SECOND: Inputs/def_comments.swift:20:12: Constructor/second_decl_class_2.init
// SECOND: Inputs/def_comments.swift:23:17: Protocol/second_decl_protocol_1
// SECOND: Inputs/def_comments.swift:24:20: AssociatedType/second_decl_protocol_1.NestedTypealias
// SECOND: Inputs/def_comments.swift:25:5: Subscript/second_decl_protocol_1.subscript
// SECOND: Inputs/def_comments.swift:25:35: Accessor/second_decl_protocol_1.<getter for second_decl_protocol_1.subscript>
// SECOND: Inputs/def_comments.swift:25:39: Accessor/second_decl_protocol_1.<setter for second_decl_protocol_1.subscript>
// SECOND: Inputs/def_comments.swift:28:13: Var/decl_var_2 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: NonExistingSource.swift:100000:13: Func/functionAfterPoundSourceLoc
// Test the case when we have to import via a .swiftinterface file.
//
// RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/Hidden)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/Hidden/comments.swiftmodule -emit-module-interface-path %t/comments.swiftinterface -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s -enable-library-evolution -swift-version 5
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t -swift-version 5 | %FileCheck %s -check-prefix=FIRST
| apache-2.0 |
GrandCentralBoard/GrandCentralBoard | Pods/GCBCore/GCBCore/Job.swift | 4 | 1758 | //
// Created by Oktawian Chojnacki on 23.04.2016.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import Foundation
/**
Have read only `source` property, having information about `interval` between which the `source` should be updated.
*/
public protocol HavingSource {
var source: UpdatingSource { get }
}
/**
Have read only `target` property conforming to `Updateable` protocol. Target be updated by source.
*/
public protocol HavingTarget {
var target: Updateable { get }
}
/**
Selector specified in `selector` property will be called periodically. The period length is specified by `interval` property.
*/
public protocol Schedulable : class {
/// This property defines the period length between the calls to `selector`.
var interval: NSTimeInterval { get }
/// This selector will be called periodically
var selector: Selector { get }
}
/**
This class have `source` and `target`.
Target is updated from the source when `update()` method is called.
The `update()` method is called periodically. The period length is specified by `interval` property.
*/
public final class Job: Schedulable, HavingSource, HavingTarget {
public let target: Updateable
public let selector: Selector = #selector(update)
public let source: UpdatingSource
public init(target: Updateable, source: UpdatingSource) {
self.target = target
self.source = source
}
/// This property specifies the period between which the `source` should be updated.
public var interval: NSTimeInterval {
return source.interval
}
/// This selector is called by NSTimer initiated in Scheduler `schedule` method.
@objc func update() {
target.update(source)
}
}
| gpl-3.0 |
feiin/DKTextField.Swift | DKTextField.Swift/DKTextField.SwiftTests/DKTextField_SwiftTests.swift | 1 | 920 | //
// DKTextField_SwiftTests.swift
// DKTextField.SwiftTests
//
// Created by yangyin on 14/11/2.
// Copyright (c) 2014年 swiftmi. All rights reserved.
//
import UIKit
import XCTest
class DKTextField_SwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
robpeach/test | SwiftPages/PagedScrollViewController.swift | 1 | 9648 | //
// PagedScrollViewController.swift
// Britannia v2
//
// Created by Rob Mellor on 11/07/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import SDWebImage
class PagedScrollViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
var arrGallery : NSMutableArray!
var imageCache : [String:UIImage]!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet var lblPhotoCount: UILabel!
var pageViews: [UIImageView?] = []
var intPage : NSInteger!
@IBOutlet var viewLower: UIView!
@IBOutlet var viewUpper: UIView!
@IBOutlet weak var newPageView: UIView!
//var newPageView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
scrollView.needsUpdateConstraints()
scrollView.setNeedsLayout()
scrollView.layoutIfNeeded()
//
//
//Manually added constraints at runtime
let constraintTS = NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: viewUpper, attribute: .Bottom, multiplier: 1.0, constant: 0)
let constraintBS = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: viewLower, attribute: .Top, multiplier: 1.0, constant: 0)
let constraintLS = NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0)
let constraintRS = NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1.0, constant: 0)
view.addConstraint(constraintTS)
view.addConstraint(constraintBS)
view.addConstraint(constraintLS)
view.addConstraint(constraintRS)
}
override func viewWillAppear(animated: Bool) {
centerScrollViewContents()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
centerScrollViewContents()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let pageCount = arrGallery.count
for _ in 0..<pageCount {
pageViews.append(nil)
}
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(arrGallery.count), pagesScrollViewSize.height)
scrollView.contentOffset.x = CGFloat(intPage) * self.view.frame.size.width
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
loadVisiblePages()
let recognizer = UITapGestureRecognizer(target: self, action:#selector(PagedScrollViewController.handleTap(_:)))
// 4
recognizer.delegate = self
scrollView.addGestureRecognizer(recognizer)
scrollView.showsVerticalScrollIndicator = false
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func handleTap(recognizer: UITapGestureRecognizer) {
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func loadPage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let page = pageViews[page] {
// Do nothing. The view is already loaded.
} else {
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
let rowData: NSDictionary = arrGallery[page] as! NSDictionary
let urlString: String = rowData["pic"] as! String
let imgURL = NSURL(string: urlString)
// If this image is already cached, don't re-download
if let img = imageCache[urlString] {
let newPageView = UIImageView(image: img)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
pageViews[page] = newPageView
}
else {
SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if error == nil {
// let image = UIImage(data: data!)
//On Main Thread
dispatch_async(dispatch_get_main_queue()){
self?.imageCache[urlString] = image
// Update the cell
let newPageView = UIImageView(image: image)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
self?.scrollView.addSubview(newPageView)
// 4
self?.pageViews[page] = newPageView
}
}
else {
print("Error: \(error!.localizedDescription)")
}
})
}
}
}
func purgePage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
intPage = page
// Update the page control
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
// Work out which pages you want to load
let firstPage = max(0,page - 1)
let lastPage = min(page + 1, arrGallery.count - 1)
// Purge anything before the first page
for index in 0..<firstPage {
purgePage(index)
}
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
// Purge anything after the last page
for index in (lastPage + 1)..<(arrGallery.count) {
purgePage(index)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// Load the pages that are now on screen
if scrollView.contentSize.width > 320{
viewLower.alpha = 1
viewUpper.alpha = 1
loadVisiblePages()
}
}
@IBAction func btnBackTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popToRootViewControllerAnimated(true)
}
}
@IBAction func btnShareTapped(sender: AnyObject) {
var sharingItems = [AnyObject]()
let rowData: NSDictionary = arrGallery[intPage] as! NSDictionary
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
let urlString: String = rowData["pic"] as! String
// let imgURL = NSURL(string: urlString)
let img = imageCache[urlString]
sharingItems.append(img!)
// sharingItems.append(imgURL!)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
@IBAction func btnGalleryTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
}
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size
var contentsFrame = newPageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.height - self.topLayoutGuide.length) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
newPageView.frame = contentsFrame
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
//LightContent
return UIStatusBarStyle.LightContent
//Default
//return UIStatusBarStyle.Default
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
gpancio/iOS-Prototypes | GPUIKit/GPUIKit/Classes/ExpandableTableViewCell.swift | 1 | 2300 | //
// ExpandableTableViewCell.swift
// GPUIKit
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import UIKit
public class ExpandableTableViewCell: UITableViewCell {
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var showDetailIcon: UILabel!
@IBOutlet weak var detailsTextView: UITextView!
@IBOutlet weak var checkbox: CheckBox!
public var title: String? {
didSet {
titleLabel?.text = title
}
}
public var detail: String? {
didSet {
detailsTextView?.text = detail
}
}
override public func awakeFromNib() {
super.awakeFromNib()
stackView.arrangedSubviews.last?.hidden = true
}
public override func prepareForReuse() {
super.prepareForReuse()
stackView.arrangedSubviews.last?.hidden = true
}
override public func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 1,
options: UIViewAnimationOptions.CurveEaseIn,
animations: { () -> Void in
self.stackView.arrangedSubviews.last?.hidden = !selected
},
completion: nil)
let rotate: CGFloat = selected ? CGFloat(M_PI_2) : 0
UIView.animateWithDuration(0.35,
animations: {
self.showDetailIcon.transform = CGAffineTransformMakeRotation(rotate)
if (selected) {
self.stackView.arrangedSubviews.first?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.30)
self.stackView.arrangedSubviews.last?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.30)
} else {
self.stackView.arrangedSubviews.first?.backgroundColor = UIColor.clearColor()
self.stackView.arrangedSubviews.last?.backgroundColor = UIColor.clearColor()
}
}
)
}
}
| mit |
yanif/circator | MetabolicCompassWatchExtension/WaterInterfaceController.swift | 1 | 1468 | //
// WaterInterfaceController.swift
// Circator
//
// Created by Mariano on 3/30/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import WatchKit
import Foundation
import HealthKit
struct waterAmountVariable {
var waterAmount: Double
}
var waterEnterButton = waterAmountVariable(waterAmount:250.0)
class WaterInterfaceController: WKInterfaceController {
@IBOutlet var waterPicker: WKInterfacePicker!
@IBOutlet var EnterButton: WKInterfaceButton!
var water = 0.0
let healthKitStore:HKHealthStore = HKHealthStore()
let healthManager:HealthManager = HealthManager()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
var tempItems: [WKPickerItem] = []
for i in 0...8 {
let item = WKPickerItem()
item.contentImage = WKImage(imageName: "WaterInCups\(i)")
tempItems.append(item)
}
waterPicker.setItems(tempItems)
waterPicker.setSelectedItemIndex(2)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func onWaterEntry(value: Int) {
water = Double(value)*250
}
@IBAction func waterSaveButton() {
waterEnterButton.waterAmount = water
pushControllerWithName("WaterTimesInterfaceController", context: self)
}
}
| apache-2.0 |
eofster/Telephone | UseCases/ServiceAddress.swift | 1 | 2513 | //
// ServiceAddress.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public final class ServiceAddress: NSObject {
@objc public let host: String
@objc public let port: String
@objc public var stringValue: String {
let h = host.isIP6Address ? "[\(host)]" : host
return port.isEmpty ? h : "\(h):\(port)"
}
public override var description: String { return stringValue }
@objc public init(host: String, port: String) {
self.host = trimmingSquareBrackets(host)
self.port = port
}
@objc public convenience init(host: String) {
self.init(host: host, port: "")
}
@objc(initWithString:) public convenience init(_ string: String) {
let address = beforeSemicolon(string)
if trimmingSquareBrackets(address).isIP6Address {
self.init(host: address)
} else if let range = address.range(of: ":", options: .backwards) {
self.init(host: String(address[..<range.lowerBound]), port: String(address[range.upperBound...]))
} else {
self.init(host: address)
}
}
}
extension ServiceAddress {
public override func isEqual(_ object: Any?) -> Bool {
guard let address = object as? ServiceAddress else { return false }
return isEqual(to: address)
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(host)
hasher.combine(port)
return hasher.finalize()
}
private func isEqual(to address: ServiceAddress) -> Bool {
return host == address.host && port == address.port
}
}
private func beforeSemicolon(_ string: String) -> String {
if let index = string.firstIndex(of: ";") {
return String(string[..<index])
} else {
return string
}
}
private func trimmingSquareBrackets(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
}
| gpl-3.0 |
moked/iuob | iUOB 2/Controllers/Schedule Builder/SummaryVC.swift | 1 | 10389 | //
// SummaryVC.swift
// iUOB 2
//
// Created by Miqdad Altaitoon on 12/19/16.
// Copyright © 2016 Miqdad Altaitoon. All rights reserved.
//
import UIKit
import NYAlertViewController
import MBProgressHUD
/// all magic here. find the true number of combinations between the courses
class SummaryVC: UIViewController {
// MARK: - Properties
var filteredCourseSectionDict = [String: [Section]]()
var sectionCombination = [[Section]]() /// all sections
@IBOutlet weak var schedulesFoundLabel: UILabel!
@IBOutlet weak var nextButtonOutlet: UIBarButtonItem!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.nextButtonOutlet.isEnabled = false
builderAlgorithm()
googleAnalytics()
}
func googleAnalytics() {
if let tracker = GAI.sharedInstance().defaultTracker {
tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!)
let builder: NSObject = GAIDictionaryBuilder.createScreenView().build()
tracker.send(builder as! [NSObject : AnyObject])
}
}
/**
this function do everything, but it should be refactored for more efficencey + readablilty
example of what this algorithm do:
let say we have 3 courses which have 3, 2, 5 section respectivly:
course [0]: [0][1][2]
course [1]: [0][1]
course [2]: [0][1][2][3][4]
we will have (3 * 2 * 5 = 30) possible combinations between them.
so insted of going through all sections recuresvly, I refactured the recurseve function into an iteration loop which is much faster.
in order to do it, we need 2 arrays. On to store the current indeces that we have. And the other one to store the actual size for each of the sections array.
It will go like this:
comb 1: [0][0][0]
comb 2: [0][0][1]
comb 3: [0][0][2]
...
comb 30: [2][1][4]
*/
func builderAlgorithm() {
self.schedulesFoundLabel.text = "Calculating..."
MBProgressHUD.showAdded(to: self.view, animated: true)
DispatchQueue.global(qos: .background).async { // do calucaltion in background thread
var allCombinationCount = 1 // all possible combination to iterate through
var indicesArray:[Int] = [] // array to store current indeces for each of the course' sections
var indicesSizeArray:[Int] = [] // array to store the true size for each of the course' sections
let lazyMapCollection = self.filteredCourseSectionDict.keys
let keysArray = Array(lazyMapCollection.map { String($0)! })
/* initilaizing arrays */
for i in 0..<keysArray.count {
allCombinationCount *= self.filteredCourseSectionDict[keysArray[i]]!.count
indicesArray.append(0) // init. zero index for all courses/sections
indicesSizeArray.append(self.filteredCourseSectionDict[keysArray[i]]!.count) // init sizes
}
/* go through all possible combinations */
for _ in 0..<allCombinationCount {
var sectionsToCompare: [Section] = [] // reset each time
for j in 0..<keysArray.count {
sectionsToCompare.append(self.filteredCourseSectionDict[keysArray[j]]![indicesArray[j]])
}
// compare sectionsToCompare, if no clashes, add to new array. to find clshes, double for loop
var isSectionClash = false
for i in 0..<sectionsToCompare.count-1 {
if isSectionClash {break}
for j in i+1..<sectionsToCompare.count {
if isSectionClash {break}
let sectionA = sectionsToCompare[i]
let sectionB = sectionsToCompare[j]
/* compare section A and B. if same day & same cross in time -> CLASH */
for timingA in sectionA.timing {
for timingB in sectionB.timing {
for dayA in timingA.day.characters {
for dayB in timingB.day.characters {
if dayA == dayB {
// if same day -> check timing
let timeStartArrA = timingA.timeFrom.components(separatedBy: ":")
let timeStartArrB = timingB.timeFrom.components(separatedBy: ":")
let timeEndArrA = timingA.timeTo.components(separatedBy: ":")
let timeEndArrB = timingB.timeTo.components(separatedBy: ":")
if timeStartArrA.count > 1 && timeStartArrB.count > 1 && timeEndArrA.count > 1 && timeEndArrB.count > 1 {
let sectionAStartTime = Float(Float(timeStartArrA[0])! + (Float(timeStartArrA[1])! / 60.0))
let sectionBStartTime = Float(Float(timeStartArrB[0])! + (Float(timeStartArrB[1])! / 60.0))
let sectionAEndTime = Float(Float(timeEndArrA[0])! + (Float(timeEndArrA[1])! / 60.0))
let sectionBEndTime = Float(Float(timeEndArrB[0])! + (Float(timeEndArrB[1])! / 60.0))
if (sectionAStartTime >= sectionBStartTime && sectionAStartTime <= sectionBEndTime) ||
(sectionAEndTime >= sectionBStartTime && sectionAEndTime <= sectionBEndTime) ||
(sectionBStartTime >= sectionAStartTime && sectionBStartTime <= sectionAEndTime) ||
(sectionBEndTime >= sectionAStartTime && sectionBEndTime <= sectionAEndTime) {
// if start or end time is between other lectures times -> CLASH
isSectionClash = true
}
}
}
}
}
}
}
}
}
if !isSectionClash {
self.sectionCombination.append(sectionsToCompare)
}
/* state machine to determin each index of arrays */
for index in 0..<self.filteredCourseSectionDict.count {
if indicesArray[index] + 1 == indicesSizeArray[index] {
indicesArray[index] = 0 // reset
} else {
indicesArray[index] += 1 // increment current index
break
}
}
}
DispatchQueue.main.async {
MBProgressHUD.hide(for: self.view, animated: true)
self.schedulesFoundLabel.text = "\(self.sectionCombination.count)"
if self.sectionCombination.count == 0 {
self.nextButtonOutlet.isEnabled = false
self.showAlert(title: "Not found", msg: "No schedule found. Please go back and choose other options or other courses")
} else {
self.nextButtonOutlet.isEnabled = true
}
}
}
}
func showAlert(title: String, msg: String) {
let alertViewController = NYAlertViewController()
alertViewController.title = title
alertViewController.message = msg
alertViewController.buttonCornerRadius = 20.0
alertViewController.view.tintColor = self.view.tintColor
//alertViewController.cancelButtonColor = UIColor.redColor()
alertViewController.destructiveButtonColor = UIColor(netHex:0xFFA739)
alertViewController.swipeDismissalGestureEnabled = true
alertViewController.backgroundTapDismissalGestureEnabled = true
let cancelAction = NYAlertAction(
title: "Close",
style: .cancel,
handler: { (action: NYAlertAction?) -> Void in
self.dismiss(animated: true, completion: nil)
}
)
alertViewController.addAction(cancelAction)
// Present the alert view controller
self.present(alertViewController, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "OptionsListSegue" {
let nextScene = segue.destination as? OptionsListVC
nextScene!.sectionCombination = sectionCombination
}
}
}
| mit |
googlearchive/science-journal-ios | ScienceJournal/ToneGenerator/NotesSoundType.swift | 1 | 2748 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// A tone generator sound type that plays a note only when the value changes or a period of time
/// has gone by without having played a note.
class NotesSoundType: SoundType {
/// The minimum percent change in value that can trigger a sound.
let minimumPercentChange = 10.0
/// The minimum change in time (milliseconds) that can trigger a sound.
let minimumTimeChange: Int64 = 125
/// The maximum time (milliseconds) that can go by without a sound.
let maximumTimeWithoutSound: Int64 = 1000
/// The timestamp of the last value that played a sound.
var previousTimestamp = Date().millisecondsSince1970
/// The last value that played a sound.
var previousValue: Double?
init() {
let name = String.notes
super.init(name: name)
shouldAnimateToNextFrequency = false
}
override func frequency(from value: Double,
valueMin: Double,
valueMax: Double,
timestamp: Int64) -> Double? {
guard let previousValue = previousValue else {
self.previousValue = value
return nil
}
let valueDifference = value - previousValue
let valueRange = valueMax - valueMin
let valuePercentChange = abs(valueDifference / valueRange * 100.0)
let timestampDifference = timestamp - previousTimestamp
// If the `value` hasn't changed more than `minimumPercentChange`, suppress new notes for up to
// `maximumTimeWithoutSound`. If the `value` has changed more than `minimumPercentChange`,
// suppress new notes for `minimumTimeChange`.
let percentChangeAboveMinimum = valuePercentChange >= minimumPercentChange
let timeChangeAboveMinimum = timestampDifference > minimumTimeChange
let timeChangeAboveMaximum = timestampDifference > maximumTimeWithoutSound
if percentChangeAboveMinimum && timeChangeAboveMinimum || timeChangeAboveMaximum {
previousTimestamp = timestamp
self.previousValue = value
return frequencyMin +
(value - valueMin) / (valueMax - valueMin) * (frequencyMax - frequencyMin)
}
return nil
}
}
| apache-2.0 |
kazuhiro4949/PagingKit | Sources/Menu Cells/Overlay/OverlayMenuCell.swift | 1 | 5728 | //
// OverlayMenuCell.swift
// iOS Sample
//
// Copyright (c) 2017 Kazuhiro Hayashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class OverlayMenuCell: PagingMenuViewCell {
public weak var referencedMenuView: PagingMenuView?
public weak var referencedFocusView: PagingMenuFocusView?
public var hightlightTextColor: UIColor? {
set {
highlightLabel.textColor = newValue
}
get {
return highlightLabel.textColor
}
}
public var normalTextColor: UIColor? {
set {
titleLabel.textColor = newValue
}
get {
return titleLabel.textColor
}
}
public var hightlightTextFont: UIFont? {
set {
highlightLabel.font = newValue
}
get {
return highlightLabel.font
}
}
public var normalTextFont: UIFont? {
set {
titleLabel.font = newValue
}
get {
return titleLabel.font
}
}
public static let sizingCell = OverlayMenuCell()
let maskInsets = UIEdgeInsets(top: 6, left: 8, bottom: 6, right: 8)
let textMaskView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let highlightLabel = UILabel()
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addConstraints()
highlightLabel.mask = textMaskView
highlightLabel.textColor = .white
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addConstraints()
highlightLabel.mask = textMaskView
highlightLabel.textColor = .white
}
override public func layoutSubviews() {
super.layoutSubviews()
textMaskView.bounds = bounds.inset(by: maskInsets)
}
public func configure(title: String) {
titleLabel.text = title
highlightLabel.text = title
}
public func updateMask(animated: Bool = true) {
guard let menuView = referencedMenuView, let focusView = referencedFocusView else {
return
}
setFrame(menuView, maskFrame: focusView.frame, animated: animated)
}
func setFrame(_ menuView: PagingMenuView, maskFrame: CGRect, animated: Bool) {
textMaskView.frame = menuView.convert(maskFrame, to: highlightLabel).inset(by: maskInsets)
if let expectedOriginX = menuView.getExpectedAlignmentPositionXIfNeeded() {
textMaskView.frame.origin.x += expectedOriginX
}
}
public func calculateWidth(from height: CGFloat, title: String) -> CGFloat {
configure(title: title)
var referenceSize = UIView.layoutFittingCompressedSize
referenceSize.height = height
let size = systemLayoutSizeFitting(referenceSize, withHorizontalFittingPriority: UILayoutPriority.defaultLow, verticalFittingPriority: UILayoutPriority.defaultHigh)
return size.width
}
}
extension OverlayMenuCell {
private func addConstraints() {
addSubview(titleLabel)
addSubview(highlightLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
highlightLabel.translatesAutoresizingMaskIntoConstraints = false
[titleLabel, highlightLabel].forEach {
let trailingConstraint = NSLayoutConstraint(
item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: $0,
attribute: .trailing,
multiplier: 1,
constant: 16)
let leadingConstraint = NSLayoutConstraint(
item: $0,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 16)
let bottomConstraint = NSLayoutConstraint(
item: self,
attribute: .top,
relatedBy: .equal,
toItem: $0,
attribute: .top,
multiplier: 1,
constant: 8)
let topConstraint = NSLayoutConstraint(
item: $0,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1,
constant: 8)
addConstraints([topConstraint, bottomConstraint, trailingConstraint, leadingConstraint])
}
}
}
| mit |
pneyrinck/corecontrol | controls/swift/CCFader.swift | 1 | 11491 | //
// CCFader.swift
// Example
//
// Created by Bernice Ling on 2/26/16.
// Copyright © 2016 Neyrinck. All rights reserved.
//
import UIKit
struct CCTaperMark
{
var name: String
var position: Float
init(name: String, position: Float) {
self.name = name
self.position = position
}
};
@objcMembers
class CCFader: UIControl{
var capButton: CCFaderCap!
var groove: CCButton!
var displayValue: UILabel!
var logicBar: UIView!
var capTouched: Bool!
var position: Float!
var hasLabelFontSize: Float!
var hashLabelWidth: Float!
var grooveTop: Float!
var grooveBottom: Float!
var grooveLeft: Float!
var grooveRight: Float!
var grooveHCenter: Float!
var gutterBottom: Float!
var gutterTop: Float!
var gutterHeight: Float!
var capVCenterOffset: Float!
var recordMode: Bool!
var faderIsVertical: Bool!
var grooveWidth : Float?
var highlightColor: UIColor
{
didSet {
capButton.highlightColor = self.highlightColor;
capButton.setNeedsDisplay();
}
}
override var isHighlighted: Bool {
didSet {
capButton.isHighlighted = self.isHighlighted;
capButton.setNeedsDisplay();
}
}
var capHeight:NSNumber = 78 {
didSet {
updateSettings()
}
}
var faderCapState:CCButtonState!{
didSet {
if (capButton != nil)
{
capButton.setState(faderCapState, forIndex: 0)
}
}
}
var grooveState:CCButtonState!{
didSet {
if (groove != nil)
{
groove.setState(grooveState, forIndex: 0)
}
}
}
override init(frame: CGRect) {
self.highlightColor = UIColor.clear
super.init(frame: frame)
}
required init?(coder decoder: NSCoder) {
self.highlightColor = UIColor.clear
super.init(coder: decoder)
capTouched = false
position = 0
hashLabelWidth = 22
hasLabelFontSize = 12
self.updateSettings()
}
override func layoutSubviews() {
self.updateSettings()
}
func updateSettings() {
let viewSize: CGSize = self.bounds.size
let faderWasVertical = faderIsVertical
// decide if fader should be displayed vertically or horizontally
if (viewSize.height > viewSize.width) {
faderIsVertical = true
} else {
faderIsVertical = false
}
if faderIsVertical != faderWasVertical {
if capButton != nil {
capButton.removeFromSuperview()
capButton = nil
}
if groove != nil {
groove.removeFromSuperview()
groove = nil
}
}
if faderIsVertical == true {
drawVerticalFader(viewSize)
} else {
drawHorizontalFader(viewSize)
}
}
func drawHorizontalFader(_ viewSize: CGSize){
grooveLeft = Float(self.bounds.origin.x)
grooveRight = Float(self.bounds.origin.x) + Float(viewSize.width)
// draw cap
let capRect: CGRect = CGRect(x: 0.0,y: 0.0,width: 44.0, height: self.frame.height)
if capButton == nil {
capButton = CCFaderCap(frame: capRect)
} else {
capButton.frame.size = capRect.size
}
if faderCapState != nil {
capButton.setState(faderCapState, forIndex: 0)
}
capButton.layer.masksToBounds = false
capButton.layer.shadowColor = UIColor.black.cgColor
capButton.layer.shadowOpacity = 0.7
capButton.layer.shadowRadius = 5
capButton.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
capButton.clipsToBounds = false
capButton.gradientIsLeftToRight = true;
// draw groove
var h:CGFloat!
if (grooveWidth != nil) {
h = CGFloat(grooveWidth!)
} else {
h = CGFloat(6.0)
}
let y = self.frame.height/2 - h/2
let w = viewSize.width - capRect.size.width
let x = capRect.size.width / 2
let grooveRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if groove == nil {
groove = CCButton(frame: grooveRect)
} else {
groove.frame = grooveRect
}
if groove.superview == nil {
self.addSubview(groove)
}
if capButton.superview == nil {
self.insertSubview(capButton, aboveSubview: groove)
}
self.setNeedsDisplay()
self.updateCapPosition()
}
func drawVerticalFader(_ viewSize: CGSize){
// we vertically stretch the groove pict to fit exactly inside the view height
grooveTop = Float(self.bounds.origin.y)
grooveBottom = Float(self.bounds.origin.y) + Float(viewSize.height)
let capRect: CGRect = CGRect(x: 0.0,y: 0.0,width: self.bounds.width, height: CGFloat(capHeight))
if capButton == nil {
capButton = CCFaderCap(frame: capRect)
} else {
capButton.frame.size = capRect.size
}
if faderCapState != nil {
capButton.setState(faderCapState, forIndex: 0)
}
capButton.layer.masksToBounds = false
capButton.layer.shadowColor = UIColor.black.cgColor
capButton.layer.shadowOpacity = 0.7
capButton.layer.shadowRadius = 5
capButton.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
capButton.clipsToBounds = false
var w:CGFloat!
if (grooveWidth != nil) {
w = CGFloat(grooveWidth!)
} else {
w = CGFloat(6.0)
}
let h = viewSize.height - capRect.size.height
let y = capRect.size.height / 2
let x = self.frame.width/2 - w/2
let grooveRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if groove == nil {
groove = CCButton(frame: grooveRect)
} else {
groove.frame = grooveRect
}
if grooveState != nil {
groove.setState(grooveState, forIndex: 0)
}
if groove.superview == nil {
self.addSubview(groove)
}
if capButton.superview == nil {
self.insertSubview(capButton, aboveSubview: groove)
}
self.setNeedsDisplay()
// force redraw of labels and groove
self.updateCapPosition()
}
func handleDoubleTap() {
NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: "FaderViewDoubleTap"), object: self)
}
func updateCapPosition(){
var animate: Bool?
if capTouched == true {
animate = false
} else {
animate = true
}
animate = true
let capSize: CGSize = capButton.frame.size
let w = capSize.width
let h = capSize.height
var x:CGFloat;
var y:CGFloat
if (faderIsVertical == true){
x = 0.0;
y = CGFloat(self.getYPosForFaderValue(position))
} else {
x = CGFloat(self.getXPosForFaderValue(position))
y = 0.0
}
// what is the purpose of logicBarRect and logicBar?
var logicBarRect: CGRect = CGRect(x: 0,y: 0,width: 0.0,height: 0.0)
if logicBar != nil {
logicBarRect = logicBar.frame
x = x + CGFloat(hashLabelWidth)
}
let capRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if (faderIsVertical == true){
logicBarRect.origin.y = CGFloat(grooveTop) + (1 - CGFloat(position)) * (CGFloat(grooveBottom) - CGFloat(grooveTop))
logicBarRect.size.height = CGFloat(position) * (CGFloat(grooveBottom) - CGFloat(grooveTop)) - 4
}
if (faderIsVertical == false){
logicBarRect.origin.x = CGFloat(grooveLeft) + (1 - CGFloat(position)) * (CGFloat(grooveRight) - CGFloat(grooveLeft))
logicBarRect.size.width = CGFloat(position) * (CGFloat(grooveRight) - CGFloat(grooveLeft)) - 4
}
if animate == true {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.09)
UIView.setAnimationCurve(.easeInOut)
UIView.setAnimationDelay(0.0)
}
capButton.frame = capRect
if logicBar != nil {
logicBar.frame = logicBarRect
}
if animate == true {
UIView.commitAnimations()
}
}
func getYPosForFaderValue(_ value: Float) -> Float {
return ((1 - value) * (Float(self.bounds.size.height) - Float(capButton.frame.size.height)))
}
func getXPosForFaderValue(_ value: Float) -> Float {
return (value * (Float(self.bounds.size.width) - Float(capButton.frame.size.width)))
}
func setPosition(_ to: Float) {
if !capTouched {
position = to
self.updateCapPosition()
}
}
func getChannelIndex() -> Int {
return 0
}
func getYPosForScaleValue(_ value: Float) -> Float {
return Float(self.getYPosForFaderValue(value)) + Float(capButton.frame.size.height) / 2
}
func getFaderValueForYPos(_ yPos: Float) -> Float {
let capSize: CGSize = capButton.frame.size
let viewSize: CGSize = self.bounds.size
let value: Float = 1.0 - ((yPos) / (Float(viewSize.height) - Float(capSize.height)))
return value
}
func setValue(_ to: Float) {
if (capTouched == true){
position = to
self.updateCapPosition()
}
}
func setTouchValue(_ to: Float) {
if (capTouched != false) {
position = to
self.updateCapPosition()
self.sendActions(for: .valueChanged)
}
}
func setTouchDelta(_ deltapx: Float) {
if (capTouched != false) {
var delta: Float;
if (faderIsVertical == true){
delta = deltapx / (Float(self.bounds.size.height) - Float(capButton.frame.size.height))
} else {
delta = deltapx / (Float(self.bounds.size.width) - Float(capButton.frame.size.width))
}
let p = position
position = p! - delta;
position = (position < 0) ? 0 : position
position = (position > 1.0) ? 1.0 : position
self.updateCapPosition()
self.sendActions(for: .valueChanged)
}
}
func getPosition() -> Float {
return position
}
func getCapHeight() -> Float {
return Float(capButton.frame.size.height)
}
func getCapWidth() -> Float {
return Float(capButton.frame.size.width)
}
func getFaderWidth() -> Float {
return Float(self.bounds.size.width)
}
func getFaderHeight() -> Float {
return Float(self.bounds.size.height)
}
func setCapTouched(isTouched:Bool)
{
if capTouched==isTouched
{
return;
}
capTouched = isTouched;
if (capTouched == true)
{
self.sendActions(for: .editingDidBegin)
}
else
{
self.sendActions(for: .editingDidEnd)
}
}
}
| gpl-2.0 |
walokra/Haikara | Haikara/Controllers/FilterNewsSourcesViewController.swift | 1 | 15870 | //
// FilterNewsSourcesViewController.swift
// highkara
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Marko Wallin <mtw@iki.fi>
//
// 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
class FilterNewsSourcesViewController: UIViewController {
let viewName = "Settings_FilterNewsSourcesView"
struct MainStoryboard {
struct TableViewCellIdentifiers {
static let listCategoryCell = "tableCell"
}
}
let searchController = UISearchController(searchResultsController: nil)
@IBOutlet weak var tableTitleView: UIView!
@IBOutlet weak var tableView: UITableView!
// @IBOutlet weak var searchFooter: SearchFooter!
let settings = Settings.sharedInstance
var defaults: UserDefaults?
var navigationItemTitle: String = NSLocalizedString("SETTINGS_FILTERED_TITLE", comment: "")
var errorTitle: String = NSLocalizedString("ERROR", comment: "Title for error alert")
var searchPlaceholderText: String = NSLocalizedString("FILTER_SEARCH_PLACEHOLDER", comment: "Search sources to filter")
var newsSources = [NewsSources]()
var filteredTableData = [NewsSources]()
var searchText: String? = ""
let payWallItems = [Paywall.Free, Paywall.Partial, Paywall.Monthly, Paywall.Strict]
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchText = searchController.searchBar.text
searchController.isActive = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController!.title = navigationItemTitle
self.navigationItem.title = navigationItemTitle
if !(searchText?.isEmpty)! {
searchController.searchBar.text = searchText
searchController.isActive = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.defaults = settings.defaults
setObservers()
setTheme()
setContentSize()
sendScreenView(viewName)
if self.newsSources.isEmpty {
getNewsSources()
}
#if DEBUG
print("newsSources filtered=\(String(describing: settings.newsSourcesFiltered[settings.region]))")
#endif
self.tableView!.delegate = self
self.tableView.dataSource = self
// Setup the Search Controller
searchController.searchResultsUpdater = self
if #available(iOS 9.1, *) {
searchController.obscuresBackgroundDuringPresentation = false
} else {
searchController.dimsBackgroundDuringPresentation = false
}
searchController.searchBar.placeholder = searchPlaceholderText
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
// Fallback on earlier versions
}
// self.definesPresentationContext = true
// Setup the Scope Bar
// searchController.searchBar.scopeButtonTitles = [payWallItems[0].description, payWallItems[1].description, payWallItems[2].description, payWallItems[3].description]
// searchController.searchBar.showsScopeBar = true
// searchController.searchBar.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.barStyle = Theme.barStyle
searchController.searchBar.barTintColor = Theme.searchBarTintColor
searchController.searchBar.backgroundColor = Theme.backgroundColor
self.tableTitleView.addSubview(searchController.searchBar)
// Setup the search footer
// tableView.tableFooterView = searchFooter
}
func setObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setRegionNewsSources(_:)), name: .regionChangedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.resetNewsSourcesFiltered(_:)), name: .settingsResetedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setTheme(_:)), name: .themeChangedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setContentSize(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
}
func setTheme() {
Theme.loadTheme()
view.backgroundColor = Theme.backgroundColor
tableView.backgroundColor = Theme.backgroundColor
tableTitleView.backgroundColor = Theme.backgroundColor
}
@objc func setTheme(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, Received themeChangedNotification")
#endif
setTheme()
searchController.searchBar.barStyle = Theme.barStyle
searchController.searchBar.barTintColor = Theme.searchBarTintColor
searchController.searchBar.backgroundColor = Theme.backgroundColor
self.tableView.reloadData()
}
func setContentSize() {
tableView.reloadData()
}
@objc func setContentSize(_ notification: Notification) {
#if DEBUG
print("DetailViewController, Received UIContentSizeCategoryDidChangeNotification")
#endif
setContentSize()
}
@objc func setRegionNewsSources(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, regionChangedNotification")
#endif
getNewsSources()
}
@objc func resetNewsSourcesFiltered(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, Received resetNewsSourcesFiltered")
#endif
if (settings.newsSources.isEmpty) {
getNewsSourcesFromAPI()
} else {
self.newsSources = settings.newsSources
}
self.tableView!.reloadData()
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
// func filterContentForSearchText(_ searchText: String, scope: Paywall = Paywall.All) {
// filteredTableData.removeAll(keepingCapacity: false)
//
// filteredTableData = newsSources.filter({( newsSource : NewsSources) -> Bool in
// let doesPaywallMatch = (scope == Paywall.All) || (newsSource.paywall == scope.type)
//
// if searchBarIsEmpty() {
// return doesPaywallMatch
// } else {
// return doesPaywallMatch && newsSource.sourceName.lowercased().contains(searchText.lowercased())
// }
// })
// tableView.reloadData()
// }
func filterContentForSearchText(_ searchText: String) {
filteredTableData.removeAll(keepingCapacity: false)
filteredTableData = newsSources.filter({( newsSource : NewsSources) -> Bool in
return newsSource.sourceName.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
// func isFiltering() -> Bool {
// let searchBarScopeIsFiltering = searchController.searchBar.selectedScopeButtonIndex != 0
// return searchController.isActive && (!searchBarIsEmpty() || searchBarScopeIsFiltering)
// }
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getNewsSources(){
// Get news sources for selected region from settings' store
if let newsSources: [NewsSources] = self.settings.newsSourcesByLang[self.settings.region] {
#if DEBUG
print("filter view, getNewsSources: getting news sources for '\(self.settings.region)' from settings")
print("newsSources=\(newsSources)")
#endif
if let updated: Date = self.settings.newsSourcesUpdatedByLang[self.settings.region] {
let calendar = Calendar.current
var comps = DateComponents()
comps.day = 1
let updatedPlusWeek = (calendar as NSCalendar).date(byAdding: comps, to: updated, options: NSCalendar.Options())
let today = Date()
#if DEBUG
print("today=\(today), updated=\(updated), updatedPlusWeek=\(String(describing: updatedPlusWeek))")
#endif
if updatedPlusWeek!.isLessThanDate(today) {
getNewsSourcesFromAPI()
return
}
}
self.settings.newsSources = newsSources
self.newsSources = newsSources
self.tableView!.reloadData()
return
}
#if DEBUG
print("filter view, getNewsSources: getting news sources for lang from API")
#endif
// If news sources for selected region is not found, fetch from API
getNewsSourcesFromAPI()
}
func getNewsSourcesFromAPI() {
HighFiApi.listSources(
{ (result) in
self.settings.newsSources = result
self.newsSources = result
self.settings.newsSourcesByLang.updateValue(self.settings.newsSources, forKey: self.settings.region)
do {
let archivedObject = try NSKeyedArchiver.archivedData(withRootObject: self.settings.newsSourcesByLang as Dictionary<String, Array<NewsSources>>, requiringSecureCoding: false)
self.defaults!.set(archivedObject, forKey: "newsSourcesByLang")
}
catch {
#if DEBUG
print("error: \(error)")
#endif
}
self.settings.newsSourcesUpdatedByLang.updateValue(Date(), forKey: self.settings.region)
self.defaults!.set(self.settings.newsSourcesUpdatedByLang, forKey: "newsSourcesUpdatedByLang")
// #if DEBUG
// print("news sources updated, \(String(describing: self.settings.newsSourcesUpdatedByLang[self.settings.region]))")
// #endif
self.defaults!.synchronize()
// #if DEBUG
// print("categoriesByLang=\(self.settings.categoriesByLang[self.settings.region])")
// #endif
self.tableView!.reloadData()
return
}
, failureHandler: {(error)in
self.handleError(error, title: self.errorTitle)
}
)
}
// stop observing
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension FilterNewsSourcesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
// searchFooter.setIsFilteringToShow(filteredItemCount: filteredTableData.count, of: newsSources.count)
return filteredTableData.count
}
// searchFooter.setNotFiltering()
return newsSources.count
}
private func mapPaywallToDesc(newsSource: NewsSources) -> String {
var paywallInfo = ""
payWallItems.forEach { (item) in
if (newsSource.paywall != "free" && item.type == newsSource.paywall) {
paywallInfo = " (" + item.description + ")"
}
}
return paywallInfo
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: MainStoryboard.TableViewCellIdentifiers.listCategoryCell, for: indexPath)
var tableItem: NewsSources
if isFiltering() {
tableItem = filteredTableData[indexPath.row] as NewsSources
} else {
tableItem = newsSources[indexPath.row] as NewsSources
}
cell.textLabel!.text = tableItem.sourceName + mapPaywallToDesc(newsSource: tableItem)
cell.textLabel!.textColor = Theme.cellTitleColor
cell.textLabel!.font = settings.fontSizeXLarge
if (settings.newsSourcesFiltered[settings.region]?.firstIndex(of: tableItem.sourceID) != nil) {
cell.backgroundColor = Theme.selectedColor
cell.accessibilityTraits = UIAccessibilityTraits.selected
} else {
if (indexPath.row % 2 == 0) {
cell.backgroundColor = Theme.evenRowColor
} else {
cell.backgroundColor = Theme.oddRowColor
}
}
Shared.hideWhiteSpaceBeforeCell(tableView, cell: cell)
return cell
}
}
extension FilterNewsSourcesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var selectedNewsSource: NewsSources
if isFiltering() {
selectedNewsSource = self.filteredTableData[indexPath.row]
} else {
selectedNewsSource = self.newsSources[indexPath.row]
}
#if DEBUG
print("didSelectRowAtIndexPath, selectedNewsSource=\(selectedNewsSource.sourceName), \(selectedNewsSource.sourceID)")
#endif
self.trackEvent("removeSource", category: "ui_Event", action: "removeSource", label: "settings", value: selectedNewsSource.sourceID as NSNumber)
let removed = self.settings.removeSource(selectedNewsSource.sourceID)
self.newsSources[indexPath.row].selected = removed
defaults!.set(settings.newsSourcesFiltered, forKey: "newsSourcesFiltered")
defaults!.synchronize()
self.tableView!.reloadData()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let selectionColor = UIView() as UIView
selectionColor.backgroundColor = Theme.tintColor
cell.selectedBackgroundView = selectionColor
}
}
extension FilterNewsSourcesViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
// func updateSearchResults(for searchController: UISearchController) {
// let searchBar = searchController.searchBar
// let scope = payWallItems[searchBar.selectedScopeButtonIndex]
// filterContentForSearchText(searchController.searchBar.text!, scope: scope)
// }
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
//extension FilterNewsSourcesViewController: UISearchBarDelegate {
// // MARK: - UISearchBar Delegate
// func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
// filterContentForSearchText(searchBar.text!, scope: payWallItems[selectedScope])
// }
//}
| mit |
walokra/Haikara | Haikara/Models/Paywall.swift | 1 | 2576 | //
// PaywallType.swift
// highkara
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Marko Wallin <mtw@iki.fi>
//
// 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
var paywallTextAll: String = NSLocalizedString("PAYWALL_TEXT_ALL", comment: "News source paywall type")
var paywallTextFree: String = NSLocalizedString("PAYWALL_TEXT_FREE", comment: "News source paywall type")
var paywallTextPartial: String = NSLocalizedString("PAYWALL_TEXT_PARTIAL", comment: "News source paywall type")
var paywallTextMonthly: String = NSLocalizedString("PAYWALL_TEXT_MONTHLY", comment: "News source paywall type")
var paywallTextStrict: String = NSLocalizedString("PAYWALL_TEXT_STRICT", comment: "News source paywall type")
enum Paywall: String {
case All = "all"
case Free = "free"
case Partial = "partial"
case Monthly = "monthly-limit"
case Strict = "strict-paywall"
// func type() -> String {
// return self.rawValue
// }
var type: String {
switch self {
case .All: return "all"
case .Free: return "free"
case .Partial: return "partial"
case .Monthly: return "monthly-limit"
case .Strict: return "strict-paywall"
}
}
var description: String {
switch self {
case .All: return paywallTextAll
case .Free: return paywallTextFree
case .Partial: return paywallTextPartial
case .Monthly: return paywallTextMonthly
case .Strict: return paywallTextStrict
}
}
}
| mit |
koden-km/dialekt-swift | DialektTests/Parser/TokenTest.swift | 1 | 1856 | import XCTest
import Dialekt
class TokenTest: XCTestCase {
func testConstructor() {
let token = Token(
TokenType.Text,
"foo",
1,
2,
3,
4
)
XCTAssertEqual(TokenType.Text, token.tokenType)
XCTAssertEqual("foo", token.value)
XCTAssertEqual(1, token.startOffset)
XCTAssertEqual(2, token.endOffset)
XCTAssertEqual(3, token.lineNumber)
XCTAssertEqual(4, token.columnNumber)
}
func testTypeDescription() {
for testVector in self.descriptionTestVectors() {
XCTAssertEqual(testVector.description, testVector.tokenType.description)
}
}
func descriptionTestVectors() -> [DescriptionTestVector] {
return [
DescriptionTestVector(
tokenType: .LogicalAnd,
description: "AND operator"
),
DescriptionTestVector(
tokenType: .LogicalOr,
description: "OR operator"
),
DescriptionTestVector(
tokenType: .LogicalNot,
description: "NOT operator"
),
DescriptionTestVector(
tokenType: .Text,
description: "tag"
),
DescriptionTestVector(
tokenType: .OpenBracket,
description: "open bracket"
),
DescriptionTestVector(
tokenType: .CloseBracket,
description: "close bracket"
)
]
}
class DescriptionTestVector {
var tokenType: TokenType
var description: String
init(tokenType: TokenType, description: String) {
self.tokenType = tokenType
self.description = description
}
}
}
| mit |
rduan8/Aerial | Aerial/Source/Models/Debug.swift | 1 | 235 | //
// Debug.swift
// Aerial
//
// Created by John Coates on 10/28/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Foundation
func debugLog(message:String) {
#if DEBUG
NSLog(message);
#endif
} | mit |
Visual-Engineering/HiringApp | HiringApp/HiringAppCore/Models/CandidateModel.swift | 1 | 563 | //
// CandidateModel.swift
// Pods
//
// Created by Alba Luján on 26/6/17.
//
//
import Foundation
struct CandidateModel {
var id: Int
var name: String
var lastname: String
var linkedin: String
var phone: String
var email: String
}
extension CandidateModel {
var dict: [String : Any] {
return [
"id" : self.id,
"name" : self.name,
"lastname" : self.lastname,
"linkedin" : self.linkedin,
"phone" : self.phone,
"email" : self.email
]
}
}
| apache-2.0 |
BBBInc/AlzPrevent-ios | researchline/ColorReadingActivityViewController.swift | 1 | 9293 | //
// ColorReadingViewController.swift
//
// Created by Leo Kang on 11/20/15.
// Copyright © 2015 bbb. All rights reserved.
//
import UIKit
import Alamofire
class ColorReadingActivityViewController: UIViewController {
@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var yellowView: UIView!
@IBOutlet weak var greenView: UIView!
@IBOutlet weak var blueView: UIView!
@IBOutlet weak var purpleView: UIView!
@IBOutlet weak var renderedWord: UITextField!
@IBOutlet weak var resultView: UIImageView!
@IBOutlet weak var successLabel: UILabel!
@IBOutlet weak var failureLabel: UILabel!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var startButton: UIButton!
var resultCorrectMap = [Int: Int]()
var resultTimeMap = [Int: NSTimeInterval]()
var resultTrials = [Bool]()
var resultFailImage: UIImage = UIImage(named: "X")!
var resultSuccessImage: UIImage = UIImage(named: "O")!
var taskName = "Color Reading"
var activityId: String? = ""
@IBAction func clickStartButton(sender: AnyObject) {
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(2, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
descriptionText.hidden = true
startButton.hidden = true
startFlag = true
answerFlag = true
}
@IBAction func clickBlue(sender: AnyObject) {
processClick(0)
}
@IBAction func clickGreen(sender: AnyObject) {
processClick(1)
}
@IBAction func clickOrange(sender: AnyObject) {
processClick(2)
}
@IBAction func clickPurple(sender: AnyObject) {
processClick(3)
}
@IBAction func clickRed(sender: AnyObject) {
processClick(4)
}
@IBAction func clickYellow(sender: AnyObject) {
processClick(5)
}
internal func processClick(number: Int){
timeoutTimer?.invalidate()
if(answerFlag || !startFlag){
return
}
answerFlag = true
resultView.hidden = false
let interval = NSDate().timeIntervalSinceDate(start!)
resultTimeMap[trial] = interval
var result = ""
if(answer == number){
resultView.image = resultSuccessImage
resultCorrectMap[1]? += 1
successLabel.text = "Success: \(resultCorrectMap[1]!)"
result = "correct"
resultTrials.append(true)
}else{
resultView.image = resultFailImage
resultCorrectMap[0]? += 1
failureLabel.text = "Failure: \(resultCorrectMap[0]!)"
result = "fail"
resultTrials.append(false)
}
trial += 1
debugPrint("\(trial)th trial result is \(result) while \(interval)")
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
}
var suffleTimer: NSTimer? = nil
var resultHideTimer: NSTimer? = nil
var timeoutTimer: NSTimer? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.hidesBottomBarWhenPushed = true
let activityKey = "id_\(self.taskName)"
debugPrint(activityKey)
self.activityId = Constants.userDefaults.stringForKey(activityKey)
debugPrint(activityId)
renderedWord.hidden = true
resultView.hidden = true
successLabel.hidden = true
failureLabel.hidden = true
resultCorrectMap[0] = 0
resultCorrectMap[1] = 0
redView.layer.cornerRadius = 5
redView.layer.borderWidth = 1
redView.layer.borderColor = UIColor.blackColor().CGColor
orangeView.layer.cornerRadius = 5
orangeView.layer.borderWidth = 1
orangeView.layer.borderColor = UIColor.blackColor().CGColor
yellowView.layer.cornerRadius = 5
yellowView.layer.borderWidth = 1
yellowView.layer.borderColor = UIColor.blackColor().CGColor
greenView.layer.cornerRadius = 5
greenView.layer.borderWidth = 1
greenView.layer.borderColor = UIColor.blackColor().CGColor
blueView.layer.cornerRadius = 5
blueView.layer.borderWidth = 1
blueView.layer.borderColor = UIColor.blackColor().CGColor
purpleView.layer.cornerRadius = 5
purpleView.layer.borderWidth = 1
purpleView.layer.borderColor = UIColor.blackColor().CGColor
}
var answerFlag = false
var startFlag = false
var value = 0
var answer = 0
var color = 0
var trial = 0
var start: NSDate? = nil
var isTimeout = false
internal func suffle(){
suffleTimer?.invalidate()
if(trial >= 5){
finish()
return
}
renderedWord.hidden = false
resultView.hidden = true
answerFlag = false
value = Int.init(arc4random_uniform(UInt32(36)))
color = value / 6
answer = value % 6
if(color == 0){
renderedWord.text = "Blue"
}else if(color == 1){
renderedWord.text = "Green"
}else if(color == 2){
renderedWord.text = "Orange"
}else if(color == 3){
renderedWord.text = "Purple"
}else if(color == 4){
renderedWord.text = "Red"
}else if(color == 5){
renderedWord.text = "Yellow"
}
if(answer == 0){
renderedWord.textColor = UIColor.blueColor();
}else if(answer == 1){
renderedWord.textColor = UIColor.greenColor();
}else if(answer == 2){
renderedWord.textColor = UIColor.orangeColor();
}else if(answer == 3){
renderedWord.textColor = UIColor.purpleColor();
}else if(answer == 4){
renderedWord.textColor = UIColor.redColor();
}else if(answer == 5){
renderedWord.textColor = UIColor.yellowColor();
}
start = NSDate()
isTimeout = false
timeoutTimer = NSTimer.scheduledTimerWithTimeInterval(3, target:self, selector: #selector(ColorReadingActivityViewController.timeout), userInfo: nil, repeats: false)
}
internal func timeout() {
timeoutTimer?.invalidate()
isTimeout = true
answerFlag = true
resultView.hidden = false
let interval = NSDate().timeIntervalSinceDate(start!)
resultTimeMap[trial] = interval
resultTrials.append(false)
trial += 1
resultCorrectMap[0]? += 1
debugPrint("\(trial)th trial result is fail by timeout")
resultView.image = resultFailImage
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
}
internal func hideResult(){
resultView.hidden = true
}
internal func finish(){
timeoutTimer?.invalidate()
descriptionText.text = "Test is finished. Your success score is \(resultCorrectMap[1]!)."
descriptionText.hidden = false
renderedWord.hidden = true
resultView.hidden = true
startFlag = false
var jsonResult = ""
for i in 0...(resultTimeMap.count-1) {
let timestamp = resultTimeMap[i]
let correct: String = String.init(resultTrials[i])
let trialJson = "{\"name\":\"\(taskName)\",\"timestamp\":\"\(timestamp!)\",\"correct\":\"\(correct)\",\"trial\":\"\(i)\"}";
if(i == 0){
jsonResult = "[\(trialJson)"
}else{
jsonResult = "\(jsonResult),\(trialJson)"
}
}
jsonResult += "]"
debugPrint(jsonResult)
Alamofire.request(.POST, Constants.activity, headers: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType,
"signKey": Constants.signKey()], parameters: [
"value": jsonResult,
"activityId": activityId!
])
.responseJSON { (response: Response) -> Void in
switch response.result{
case.Success(let json):
debugPrint(json)
if(json["success"] as? Int == 0){
break
}
break
default:
break
}
}
}
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.
}
*/
}
| bsd-3-clause |
austinzheng/swift-compiler-crashes | fixed/23089-cleanupillformedexpression.swift | 11 | 233 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d{let f=a{}protocol a:a{typealias e:a
protocol a{protocol a
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/EventsJourney/SchedulePresentation.swift | 1 | 75 | public protocol SchedulePresentation {
func showSchedule()
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Tests/EurofurenceModelTests/Client API/PrivateMessagesAPITests.swift | 1 | 8289 | import EurofurenceModel
import XCTest
import XCTEurofurenceModel
class CapturingV2PrivateMessagesObserver {
private(set) var wasNotifiedResponseSucceeded = false
private(set) var wasNotifiedResponseFailed = false
private(set) var capturedMessages: [MessageCharacteristics]?
func handle(_ messages: [MessageCharacteristics]?) {
if let messages = messages {
wasNotifiedResponseSucceeded = true
capturedMessages = messages
} else {
wasNotifiedResponseFailed = true
}
}
}
class PrivateMessagesAPITests: XCTestCase {
var JSONSession: CapturingJSONSession!
var api: JSONAPI!
var apiUrl: APIURLProviding!
override func setUp() {
super.setUp()
JSONSession = CapturingJSONSession()
apiUrl = StubAPIURLProviding()
api = JSONAPI(jsonSession: JSONSession, apiUrl: apiUrl)
}
private func makeCapturingObserverForResponse(_ response: String?) -> CapturingV2PrivateMessagesObserver {
let observer = CapturingV2PrivateMessagesObserver()
api.loadPrivateMessages(authorizationToken: "", completionHandler: observer.handle)
JSONSession.invokeLastGETCompletionHandler(responseData: response?.data(using: .utf8))
return observer
}
private func makeSuccessfulResponse(id: String = "ID",
authorName: String = "Author",
subject: String = "Subject",
message: String = "Message",
recipientUid: String = "Recipient",
lastChangeDateTime: String = "2017-07-25T18:45:59.050Z",
createdDateTime: String = "2017-07-25T18:45:59.050Z",
receivedDateTime: String = "2017-07-25T18:45:59.050Z",
readDateTime: String = "2017-07-25T18:45:59.050Z") -> String {
return "[" +
"{" +
"\"LastChangeDateTimeUtc\": \"\(lastChangeDateTime)\"," +
"\"Id\": \"\(id)\"," +
"\"RecipientUid\": \"\(recipientUid)\"," +
"\"CreatedDateTimeUtc\": \"\(createdDateTime)\"," +
"\"ReceivedDateTimeUtc\": \"\(receivedDateTime)\"," +
"\"ReadDateTimeUtc\": \"\(readDateTime)\"," +
"\"AuthorName\": \"\(authorName)\"," +
"\"Subject\": \"\(subject)\"," +
"\"Message\": \"\(message)\"" +
"}" +
"]"
}
func testThePrivateMessagesEndpointShouldReceieveRequest() {
let expectedURL = apiUrl.url + "Communication/PrivateMessages"
api.loadPrivateMessages(authorizationToken: "", completionHandler: { _ in })
XCTAssertEqual(expectedURL, JSONSession.getRequestURL)
}
func testTheAuthorizationTokenShouldBeMadeAvailableInTheAuthorizationHeader() {
let token = "Top secret"
api.loadPrivateMessages(authorizationToken: token, completionHandler: { _ in })
XCTAssertEqual("Bearer \(token)", JSONSession.capturedAdditionalGETHeaders?["Authorization"])
}
func testResponseProvidesNilDataShouldProvideFailureResponse() {
let observer = makeCapturingObserverForResponse(nil)
XCTAssertTrue(observer.wasNotifiedResponseFailed)
}
func testResponseProvidesNonJSONDataShouldProvideFailureRespone() {
let observer = makeCapturingObserverForResponse("Not json!")
XCTAssertTrue(observer.wasNotifiedResponseFailed)
}
func testResponseProvidesWrongRootStructureShouldProvideFailureResponse() {
let observer = makeCapturingObserverForResponse("{ \"key\": \"value\" }")
XCTAssertTrue(observer.wasNotifiedResponseFailed)
}
func testResponseProvidesExpectedStructureShouldReturnSuccessfulResponse() {
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse())
XCTAssertTrue(observer.wasNotifiedResponseSucceeded)
}
func testSuccessfulResponseShouldProvideMessageWithIdentifier() {
let identifier = "Some identifier"
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(id: identifier))
XCTAssertEqual(identifier, observer.capturedMessages?.first?.identifier)
}
func testSuccessfulResponseShouldProvideMessageWithAuthorName() {
let authorName = "Some author"
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(authorName: authorName))
XCTAssertEqual(authorName, observer.capturedMessages?.first?.authorName)
}
func testSuccessfulResponseShouldProvideMessageWithSubject() {
let subject = "Some subject"
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(subject: subject))
XCTAssertEqual(subject, observer.capturedMessages?.first?.subject)
}
func testSuccessfulResponseShouldProvideMessageWithItsContent() {
let message = "Some content"
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(message: message))
XCTAssertEqual(message, observer.capturedMessages?.first?.contents)
}
func testSuccessfulResponseWithUnsupportedreceivedDateTimeValueShouldProvideFailureResponse() {
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(receivedDateTime: "Not a date"))
XCTAssertTrue(observer.wasNotifiedResponseFailed)
}
func testSuccessfulResponseWithSupportedreceivedDateTimeValueShouldProvidereceivedDateTime() {
let dateString = "2017-07-25T18:45:59.050Z"
let expectedComponents = DateComponents(year: 2017, month: 7, day: 25, hour: 18, minute: 45, second: 59)
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(receivedDateTime: dateString))
var actualComponents: DateComponents?
if let receievedDate = observer.capturedMessages?.first?.receivedDateTime {
let desiredComponents: [Calendar.Component] = [.year, .month, .day, .hour, .minute, .second]
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "GMT").unsafelyUnwrapped
actualComponents = calendar.dateComponents(Set(desiredComponents), from: receievedDate)
}
XCTAssertEqual(expectedComponents, actualComponents)
}
func testSuccessfulResponseWithUnsupportedReadDateTimeValueShouldNotProvideFailureResponse() {
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(readDateTime: "Not a date"))
XCTAssertFalse(observer.wasNotifiedResponseFailed)
}
func testSuccessfulResponseWithUnsupportedReadDateTimeValueShouldIndicateUnread() {
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(readDateTime: "Not a date"))
XCTAssertEqual(false, observer.capturedMessages?.first?.isRead)
}
func testSuccessfulResponseWithSupportedReadDateTimeValueShouldIndicateIsRead() {
let dateString = "2017-07-25T18:45:59.050Z"
let observer = makeCapturingObserverForResponse(makeSuccessfulResponse(receivedDateTime: dateString))
XCTAssertEqual(true, observer.capturedMessages?.first?.isRead)
}
func testMarkingAPIMessageAsReadSubmitsPOSTRequestToMessageReadURL() {
let identifier = "Test"
api.markMessageWithIdentifierAsRead(identifier, authorizationToken: "")
let expectedURL = apiUrl.url + "Communication/PrivateMessages/\(identifier)/Read"
XCTAssertEqual(expectedURL, JSONSession.postedURL)
}
func testMarkingAPIMessageAsReadSubmitsProvidesTheAuthorizationTokenInTheAuthorizationHeader() {
let token = "Top secret"
api.markMessageWithIdentifierAsRead("", authorizationToken: token)
XCTAssertEqual("Bearer \(token)", JSONSession.capturedAdditionalPOSTHeaders?["Authorization"])
}
// See issue #145
func testMarkingAPIMessageAsReadSubmitsTrueWithinPOSTBodyToSupportSwaggerWorkaround() {
let expected = "true".data(using: .utf8).unsafelyUnwrapped
api.markMessageWithIdentifierAsRead("", authorizationToken: .random)
XCTAssertEqual(expected, JSONSession.POSTData)
}
}
| mit |
ted005/Qiu_Suo | Qiu Suo/Qiu SuoTests/Qiu_SuoTests.swift | 2 | 967 | //
// Qiu_SuoTests.swift
// Qiu SuoTests
//
// Created by robbie on 15/10/4.
// Copyright © 2015年 robbie. All rights reserved.
//
import XCTest
@testable import Qiu_Suo
class Qiu_SuoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Classes/Other/UIButton+NStackLocalizable.swift | 1 | 2324 | //
// UIButton+NStackLocalizable.swift
// NStackSDK
//
// Created by Nicolai Harbo on 30/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
import UIKit
extension UIButton: NStackLocalizable {
private static var _backgroundColor = [String: UIColor?]()
private static var _userInteractionEnabled = [String: Bool]()
private static var _translationIdentifier = [String: TranslationIdentifier]()
@objc public func localize(for stringIdentifier: String) {
guard let identifier = SectionKeyHelper.transform(stringIdentifier) else { return }
NStack.sharedInstance.translationsManager?.localize(component: self, for: identifier)
}
@objc public func setLocalizedValue(_ localizedValue: String) {
setTitle(localizedValue, for: .normal)
}
public var translatableValue: String? {
get {
return titleLabel?.text
}
set {
titleLabel?.text = newValue
}
}
public var translationIdentifier: TranslationIdentifier? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._translationIdentifier[tmpAddress]
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._translationIdentifier[tmpAddress] = newValue
}
}
public var originalBackgroundColor: UIColor? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._backgroundColor[tmpAddress] ?? .clear
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._backgroundColor[tmpAddress] = newValue
}
}
public var originalIsUserInteractionEnabled: Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._userInteractionEnabled[tmpAddress] ?? false
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._userInteractionEnabled[tmpAddress] = newValue
}
}
public var backgroundViewToColor: UIView? {
return titleLabel
}
}
| mit |
FlaneurApp/FlaneurOpen | Example/FlaneurOpen/GooglePlacesDemoViewController.swift | 1 | 3794 | //
// GooglePlacesDemoViewController.swift
// FlaneurOpen
//
// Created by Mickaël Floc'hlay on 24/05/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GooglePlaces
class GooglePlacesDemoViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var filterSegmentedControl: UISegmentedControl!
@IBOutlet weak var consoleTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let plist = Bundle.main.path(forResource: "FlaneurOpenSecretInfo", ofType: "plist") {
if let myProperties = NSDictionary(contentsOfFile: plist) {
if let googlePlacesAPIKey = myProperties.object(forKey: "GooglePlacesFlaneurOpenAPIKey") as? String {
if GMSPlacesClient.provideAPIKey(googlePlacesAPIKey) {
debugPrint("OK")
} else {
debugPrint("NOK -- Unauthorized")
}
} else {
debugPrint("NOK -- Couldn't find the specified key")
}
} else {
debugPrint("NOK -- Couldn't parse file at path", plist)
}
} else {
debugPrint("NOK -- Couldn't find file. Did you run the script from the README?")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func filter(withIndex segmentIndex: Int) -> GMSAutocompleteFilter {
let filter = GMSAutocompleteFilter()
switch segmentIndex {
case 0:
filter.type = .address
case 1:
filter.type = .city
case 2:
filter.type = .establishment
case 3:
filter.type = .geocode
case 4:
filter.type = .noFilter
case 5:
filter.type = .region
default:
debugPrint("Invalid index \(segmentIndex)")
}
return filter
}
func log(_ logMessage: String) {
consoleTextView.text = logMessage
}
func appendLog(_ logMessage: String) {
consoleTextView.text = consoleTextView.text + "\n---\n" + logMessage
}
@IBAction func searchAction(_ sender: Any) {
if let queryString = searchBar.text {
log("Searching for \(queryString)...")
let autocompleteFilter = filter(withIndex: filterSegmentedControl.selectedSegmentIndex)
GMSPlacesClient.shared().autocompleteQuery(queryString,
bounds: nil,
filter: autocompleteFilter) { (results, error) in
if let error = error {
self.log("Autocomplete error:\n\(error)")
return
}
if let results = results {
self.log("Found \(results.count) results")
for result in results {
self.appendLog("Result \(result.attributedFullText) with placeID \(String(describing: result.placeID))")
}
}
}
} else {
log("Can't search empty string")
}
}
}
| mit |
samsymons/Photon | Photon/Core/Scene.swift | 1 | 1928 | // Scene.swift
// Copyright (c) 2017 Sam Symons
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class Scene {
public var geometricObjects: [GeometricObject] {
return renderer.geometricObjects
}
public var width: Int {
return renderer.renderingOptions.width
}
public var height: Int {
return renderer.renderingOptions.height
}
private var renderer: Renderer
// MARK: - Initialization
public init(renderer: Renderer) {
self.renderer = renderer
}
// MARK: - Public Functions
public func add(object: GeometricObject) {
renderer.geometricObjects.append(object)
}
public func add(objects objectArray: [GeometricObject]) {
renderer.geometricObjects.append(contentsOf: objectArray)
}
public func renderScene(_ sceneCompletion: @escaping RendererCompletion) {
renderer.renderScene(sceneCompletion)
}
}
| mit |
idomizrachi/Regen | regen/Dependencies/Stencil/_SwiftSupport.swift | 1 | 1185 | import Foundation
#if !swift(>=4.1)
public extension Sequence {
func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
#if !swift(>=4.1)
public extension Collection {
func index(_ index: Self.Index, offsetBy offset: Int) -> Self.Index {
let indexDistance = Self.IndexDistance(offset)
return self.index(index, offsetBy: indexDistance)
}
}
#endif
#if !swift(>=4.1)
public extension TemplateSyntaxError {
public static func == (lhs: TemplateSyntaxError, rhs: TemplateSyntaxError) -> Bool {
return lhs.reason == rhs.reason &&
lhs.description == rhs.description &&
lhs.token == rhs.token &&
lhs.stackTrace == rhs.stackTrace &&
lhs.templateName == rhs.templateName
}
}
#endif
#if !swift(>=4.1)
public extension Variable {
public static func == (lhs: Variable, rhs: Variable) -> Bool {
return lhs.variable == rhs.variable
}
}
#endif
#if !swift(>=4.2)
extension ArraySlice where Element: Equatable {
func firstIndex(of element: Element) -> Int? {
return index(of: element)
}
}
#endif
| mit |
mircealungu/Zeeguu-API-iOS | ZeeguuAPI/ZeeguuAPI/Article.swift | 2 | 13941 | //
// Article.swift
// Zeeguu Reader
//
// Created by Jorrit Oosterhof on 08-12-15.
// Copyright © 2015 Jorrit Oosterhof.
//
// 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
/// Adds support for comparing `Article` objects using the equals operator (`==`)
///
/// - parameter lhs: The left `Article` operand of the `==` operator (left hand side) <pre><b>lhs</b> == rhs</pre>
/// - parameter rhs: The right `Article` operand of the `==` operator (right hand side) <pre>lhs == <b>rhs</b></pre>
/// - returns: A `Bool` that states whether the two `Article` objects are equal
public func ==(lhs: Article, rhs: Article) -> Bool {
return lhs.feed == rhs.feed && lhs.title == rhs.title && lhs.url == rhs.url && lhs.date == rhs.date && lhs.summary == rhs.summary
}
/// The `Article` class represents an article. It holds the source (`feed`), `title`, `url`, `date`, `summary` and more about the article.
public class Article: CustomStringConvertible, Equatable, ZGSerializable {
// MARK: Properties -
/// The `Feed` from which this article was retrieved
public var feed: Feed
/// The title of this article
public var title: String
/// The url of this article
public var url: String
/// The publication date of this article
public var date: NSDate
/// The summary of this article
public var summary: String
/// Whether this article has been read by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isRead: Bool
/// Whether this article has been starred by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isStarred: Bool
/// Whether this article has been liked by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isLiked: Bool
/// The difficulty that the user has given to this article. This propery is purely for use within an app. This boolean will not be populated from the server.
public var userDifficulty: ArticleDifficulty
/// Whether this article has been read completely by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var hasReadAll: Bool
private var imageURL: String?
private var image: UIImage?
private var contents: String?
private var difficulty: ArticleDifficulty?
/// Whether the contents of this article have been retrieved yet
public var isContentLoaded: Bool {
return contents != nil
}
/// Whether the difficulty of this article has been calculated yet
public var isDifficultyLoaded: Bool {
return difficulty != nil
}
/// The description of this `Article` object. The value of this property will be used whenever the system tries to print this `Article` object or when the system tries to convert this `Article` object to a `String`.
public var description: String {
let str = feed.description.stringByReplacingOccurrencesOfString("\n", withString: "\n\t")
return "Article: {\n\tfeed: \"\(str)\",\n\ttitle: \"\(title)\",\n\turl: \"\(url)\",\n\tdate: \"\(date)\",\n\tsummary: \"\(summary)\",\n\tcontents: \"\(contents)\"\n}"
}
// MARK: Static methods -
/// Get difficulty for all given articles
///
/// Note: This method uses the default difficulty computer.
///
/// - parameter articles: The articles for which to get difficulties. Please note that all `Article` objects are references and once `completion` is called, the given `Article` objects have difficulties.
/// - parameter completion: A block that will indicate success. If `success` is `true`, all `Article` objects have been given their difficulty. Otherwise nothing has happened to the `Article` objects. If `articles` is empty, `success` is `false`.
public static func getDifficultiesForArticles(articles: [Article], completion: (success: Bool) -> Void) {
self.getContentsForArticles(articles, withDifficulty: true, completion: completion)
}
/// Get contents for all given articles
///
/// - parameter articles: The articles for which to get contents. Please note that all `Article` objects are references and once `completion` is called, the given `Article` objects have contents.
/// - parameter withDifficulty: Whether to calculate difficulty for the retrieved contents. Setting this to `true` will send the language code of the first article's feed as the language of all contents.
/// - parameter completion: A block that will indicate success. If `success` is `true`, all `Article` objects have been given their contents. Otherwise nothing has happened to the `Article` objects. If `articles` is empty, `success` is `false`.
public static func getContentsForArticles(articles: [Article], withDifficulty: Bool = false, completion: (success: Bool) -> Void) {
let urls = articles.flatMap({ $0.isContentLoaded && (!withDifficulty || $0.isDifficultyLoaded) ? nil : $0.url })
if urls.count == 0 {
return completion(success: false) // No articles to get content for
}
let langCode: String? = withDifficulty ? articles[0].feed.language : nil
ZeeguuAPI.sharedAPI().getContentFromURLs(urls, langCode: langCode, maxTimeout: urls.count * 10) { (contents) in
if let contents = contents {
for i in 0 ..< contents.count {
articles[i]._updateContents(contents[i], withDifficulty: withDifficulty)
}
return completion(success: true)
}
completion(success: false)
}
}
// MARK: Constructors -
/**
Construct a new `Article` object.
- parameter feed: The `Feed` from which this article was retrieved
- parameter title: The title of the article
- parameter url: The url of the article
- parameter date: The publication date of the article
- parameter summary: The summary of the article
*/
public init(feed: Feed, title: String, url: String, date: String, summary: String) {
self.feed = feed
self.title = title;
self.url = url;
let formatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = enUSPosixLocale
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = formatter.dateFromString(date)
self.date = date!
self.summary = summary
self.isRead = false
self.isStarred = false
self.isLiked = false
self.userDifficulty = .Unknown
self.hasReadAll = false
}
/**
Construct a new `Article` object from the data in the dictionary.
- parameter dictionary: The dictionary that contains the data from which to construct an `Article` object.
*/
@objc public required init?(dictionary dict: [String: AnyObject]) {
var savedDate = dict["date"] as? NSDate
if let date = dict["date"] as? String {
let formatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = enUSPosixLocale
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = formatter.dateFromString(date)
savedDate = date
}
guard let feed = dict["feed"] as? Feed,
title = dict["title"] as? String,
url = dict["url"] as? String,
date = savedDate,
summary = dict["summary"] as? String else {
return nil
}
self.feed = feed
self.title = title
self.url = url
self.date = date
self.summary = summary
self.isRead = dict["isRead"] as? Bool == true
self.isStarred = dict["isStarred"] as? Bool == true
self.imageURL = dict["imageURL"] as? String
self.image = dict["image"] as? UIImage
self.contents = dict["contents"] as? String
if let difficulty = dict["difficulty"] as? String {
self.difficulty = ArticleDifficulty(rawValue: difficulty)
}
self.isLiked = dict["isLiked"] as? Bool == true
if let str = dict["userDifficulty"] as? String, userDifficulty = ArticleDifficulty(rawValue: str) {
self.userDifficulty = userDifficulty
} else {
self.userDifficulty = .Unknown
}
self.hasReadAll = dict["hasReadAll"] as? Bool == true
}
// MARK: Methods -
/**
The dictionary representation of this `Article` object.
- returns: A dictionary that contains all data of this `Article` object.
*/
@objc public func dictionaryRepresentation() -> [String: AnyObject] {
var dict = [String: AnyObject]()
dict["feed"] = self.feed
dict["title"] = self.title
dict["url"] = self.url
dict["date"] = self.date
dict["summary"] = self.summary
dict["isRead"] = self.isRead
dict["isStarred"] = self.isStarred
dict["imageURL"] = self.imageURL
dict["image"] = self.image
dict["contents"] = self.contents
dict["difficulty"] = self.difficulty?.rawValue
dict["isLiked"] = self.isLiked
dict["userDifficulty"] = self.userDifficulty.rawValue
dict["hasReadAll"] = self.hasReadAll
return dict
}
/**
Get the contents of this article. This method will make sure that the contents are cached within this `Article` object, so calling this method again will not retrieve the contents again, but will return the cached version instead.
- parameter completion: A closure that will be called once the contents have been retrieved. If there were no contents to retrieve, `contents` is the empty string. Otherwise, it contains the article contents.
*/
public func getContents(completion: (contents: String) -> Void) {
if let c = contents {
return completion(contents: c)
}
_getContents { (contents) in
if let c = contents {
return completion(contents: c.0)
}
completion(contents: "")
}
}
/**
Get the image of this article. This method will make sure that the image url is cached within this `Article` object, so calling this method again will not retrieve the image again, but will return the cached version instead.
- parameter completion: A closure that will be called once the image has been retrieved. If there was no image to retrieve, `image` is `nil`. Otherwise, it contains the article image.
*/
public func getImage(completion: (image: UIImage?) -> Void) {
_getContents { (contents) in
if let c = contents, imURL = NSURL(string: c.1) {
let request = NSMutableURLRequest(URL: imURL)
ZeeguuAPI.sharedAPI().sendAsynchronousRequestWithDataResponse(request) { (data, error) -> Void in
if let res = data {
return completion(image: UIImage(data: res))
}
if ZeeguuAPI.sharedAPI().enableDebugOutput {
print("Could not get image with url '\(self.imageURL)', error: \(error)")
}
completion(image: nil)
}
} else {
completion(image: nil)
}
}
}
/**
Get the difficulty of this article. This method will make sure that the difficulty is cached within this `Article` object, so calling this method again will not calculate the difficulty again, but will return the cached version instead.
- parameter completion: A closure that will be called once the difficulty has been calculated. If there was no difficulty to calculate, `difficulty` is `ArticleDifficulty.Unknown`. Otherwise, it contains the article difficulty.
*/
public func getDifficulty(difficultyComputer: String = "default", completion: (difficulty: ArticleDifficulty) -> Void) {
if let diff = difficulty {
return completion(difficulty: diff)
}
if difficultyComputer == "default" {
_getContents(true) { (contents) in
if let c = contents {
return completion(difficulty: c.2)
}
completion(difficulty: .Unknown)
}
} else {
getContents({ (contents) in
if contents == "" {
return completion(difficulty: .Unknown)
}
ZeeguuAPI.sharedAPI().getDifficultyForTexts([contents], langCode: self.feed.language, difficultyComputer: difficultyComputer, completion: { (difficulties) in
if let diffs = difficulties {
self.difficulty = diffs[0]
return completion(difficulty: diffs[0])
}
completion(difficulty: .Unknown)
})
})
}
}
// MARK: -
private func _updateContents(contents: (String, String, ArticleDifficulty), withDifficulty: Bool) {
if contents.0 != "" {
self.contents = contents.0
}
if contents.1 != "" {
self.imageURL = contents.1
}
if withDifficulty {
self.difficulty = contents.2
}
}
private func _getContents(withDifficulty: Bool = false, completion: (contents: (String, String, ArticleDifficulty)?) -> Void) {
if let con = contents, imURL = imageURL, diff = difficulty where withDifficulty == true {
completion(contents: (con, imURL, diff))
} else if let con = contents, imURL = imageURL where withDifficulty == false {
completion(contents: (con, imURL, difficulty == nil ? .Unknown : difficulty!))
} else {
ZeeguuAPI.sharedAPI().getContentFromURLs([url]) { (contents) in
if let content = contents?[0] {
self._updateContents(content, withDifficulty: withDifficulty)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(contents: content)
})
} else {
if ZeeguuAPI.sharedAPI().enableDebugOutput {
print("Failure, no content")
}
}
}
}
}
}
| mit |
reTXT/thrift | lib/cocoa/src/TMap.swift | 1 | 4418 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
public struct TMap<Key : TSerializable, Value : TSerializable> : CollectionType, DictionaryLiteralConvertible, TSerializable {
public static var thriftType : TType { return .MAP }
public typealias Storage = Dictionary<Key, Value>
public typealias Index = Storage.Index
public typealias Element = Storage.Element
public var storage : Storage
public var startIndex : Index {
return storage.startIndex
}
public var endIndex: Index {
return storage.endIndex
}
public var keys: LazyMapCollection<[Key : Value], Key> {
return storage.keys
}
public var values: LazyMapCollection<[Key : Value], Value> {
return storage.values
}
public init() {
storage = Storage()
}
public init(dictionaryLiteral elements: (Key, Value)...) {
storage = Storage()
for (key, value) in elements {
storage[key] = value
}
}
public init(_ dictionary: [Key: Value]) {
storage = dictionary
}
public init(minimumCapacity: Int) {
storage = Storage(minimumCapacity: minimumCapacity)
}
public subscript (position: Index) -> Element {
get {
return storage[position]
}
}
public func indexForKey(key: Key) -> Index? {
return storage.indexForKey(key)
}
public subscript (key: Key) -> Value? {
get {
return storage[key]
}
set {
storage[key] = newValue
}
}
public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
return updateValue(value, forKey: key)
}
public mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) -> (Key, Value) {
return removeAtIndex(index)
}
public mutating func removeValueForKey(key: Key) -> Value? {
return storage.removeValueForKey(key)
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
storage.removeAll(keepCapacity: keepCapacity)
}
public var hashValue : Int {
let prime = 31
var result = 1
for (key, value) in storage {
result = prime * result + key.hashValue
result = prime * result + value.hashValue
}
return result
}
public static func readValueFromProtocol(proto: TProtocol) throws -> TMap {
let (keyType, valueType, size) = try proto.readMapBegin()
if keyType != Key.thriftType || valueType != Value.thriftType {
throw NSError(
domain: TProtocolErrorDomain,
code: Int(TProtocolError.InvalidData.rawValue),
userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)])
}
var map = TMap()
for _ in 0..<size {
let key = try Key.readValueFromProtocol(proto)
let value = try Value.readValueFromProtocol(proto)
map.storage[key] = value
}
try proto.readMapEnd()
return map
}
public static func writeValue(value: TMap, toProtocol proto: TProtocol) throws {
try proto.writeMapBeginWithKeyType(Key.thriftType, valueType: Value.thriftType, size: value.count)
for (key, value) in value.storage {
try Key.writeValue(key, toProtocol: proto)
try Value.writeValue(value, toProtocol: proto)
}
try proto.writeMapEnd()
}
}
extension TMap : CustomStringConvertible, CustomDebugStringConvertible {
public var description : String {
return storage.description
}
public var debugDescription : String {
return storage.debugDescription
}
}
public func ==<Key, Value>(lhs: TMap<Key,Value>, rhs: TMap<Key, Value>) -> Bool {
if lhs.count != rhs.count {
return false
}
return lhs.storage == rhs.storage
}
| apache-2.0 |
google/swift-benchmark | Sources/BenchmarkSuiteExample/Suites.swift | 1 | 637 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public let suites = [
addStringBenchmarks
]
| apache-2.0 |
apple/swift | validation-test/compiler_crashers_fixed/26529-swift-typechecker-validatetype.swift | 65 | 461 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct c<h{class A:b{struct S<T where g:A{class B<T>:A{var f=a
| apache-2.0 |
codestergit/swift | test/ClangImporter/objc_parse.swift | 1 | 22765 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify -verify-ignore-unknown
// REQUIRES: objc_interop
import AppKit
import AVFoundation
import Newtype
import objc_ext
import TestProtocols
import ObjCParseExtras
import ObjCParseExtrasToo
import ObjCParseExtrasSystem
func markUsed<T>(_ t: T) {}
func testAnyObject(_ obj: AnyObject) {
_ = obj.nsstringProperty
}
// Construction
func construction() {
_ = B()
}
// Subtyping
func treatBAsA(_ b: B) -> A {
return b
}
// Instance method invocation
func instanceMethods(_ b: B) {
var i = b.method(1, with: 2.5 as Float)
i = i + b.method(1, with: 2.5 as Double)
// BOOL
b.setEnabled(true)
// SEL
b.perform(#selector(NSObject.isEqual(_:)), with: b)
if let result = b.perform(#selector(B.getAsProto), with: nil) {
_ = result.takeUnretainedValue()
}
// Renaming of redundant parameters.
b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}}
b.performAdd(1, withValue:2, withValue:4, withValue2: 3)
b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }}
// Both class and instance methods exist.
_ = b.description
b.instanceTakesObjectClassTakesFloat(b)
b.instanceTakesObjectClassTakesFloat(2.0)
// Instance methods with keyword components
var obj = NSObject()
var prot = NSObjectProtocol.self
b.`protocol`(prot, hasThing:obj)
b.doThing(obj, protocol: prot)
}
// Class method invocation
func classMethods(_ b: B, other: NSObject) {
var i = B.classMethod()
i += B.classMethod(1)
i += B.classMethod(1, with: 2)
i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}}
// Both class and instance methods exist.
B.description()
B.instanceTakesObjectClassTakesFloat(2.0)
B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}}
// Call an instance method of NSObject.
var c: AnyClass = B.myClass() // no-warning
c = b.myClass() // no-warning
}
// Instance method invocation on extensions
func instanceMethodsInExtensions(_ b: B) {
b.method(1, onCat1:2.5)
b.method(1, onExtA:2.5)
b.method(1, onExtB:2.5)
b.method(1, separateExtMethod:3.5)
let m1 = b.method(_:onCat1:)
_ = m1(1, 2.5)
let m2 = b.method(_:onExtA:)
_ = m2(1, 2.5)
let m3 = b.method(_:onExtB:)
_ = m3(1, 2.5)
let m4 = b.method(_:separateExtMethod:)
_ = m4(1, 2.5)
}
func dynamicLookupMethod(_ b: AnyObject) {
if let m5 = b.method(_:separateExtMethod:) {
_ = m5(1, 2.5)
}
}
// Properties
func properties(_ b: B) {
var i = b.counter
b.counter = i + 1
i = i + b.readCounter
b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}}
b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}}
// Informal properties in Objective-C map to methods, not variables.
b.informalProp()
// An informal property cannot be made formal in a subclass. The
// formal property is simply ignored.
b.informalMadeFormal()
b.informalMadeFormal = i // expected-error{{cannot assign to property: 'informalMadeFormal' is a method}}
b.setInformalMadeFormal(5)
b.overriddenProp = 17
// Dynamic properties.
var obj : AnyObject = b
var optStr = obj.nsstringProperty
if optStr != nil {
var s : String = optStr!
}
// Properties that are Swift keywords
var prot = b.`protocol`
// Properties whose accessors run afoul of selector splitting.
_ = SelectorSplittingAccessors()
}
// Construction.
func newConstruction(_ a: A, aproxy: AProxy) {
var b : B = B()
b = B(int: 17)
b = B(int:17)
b = B(double:17.5, 3.14159)
b = B(bbb:b)
b = B(forWorldDomination:())
b = B(int: 17, andDouble : 3.14159)
b = B.new(with: a)
B.alloc()._initFoo()
b.notAnInit()
// init methods are not imported by themselves.
b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}}
// init methods on non-NSObject-rooted classes
AProxy(int: 5) // expected-warning{{unused}}
}
// Indexed subscripting
func indexedSubscripting(_ b: B, idx: Int, a: A) {
b[idx] = a
_ = b[idx] as! A
}
// Keyed subscripting
func keyedSubscripting(_ b: B, idx: A, a: A) {
b[a] = a
var a2 = b[a] as! A
let dict = NSMutableDictionary()
dict[NSString()] = a
let value = dict[NSString()]
dict[nil] = a // expected-error {{ambiguous reference}}
let q = dict[nil] // expected-error {{ambiguous subscript}}
_ = q
}
// Typed indexed subscripting
func checkHive(_ hive: Hive, b: Bee) {
let b2 = hive.bees[5] as Bee
b2.buzz()
}
// Protocols
func testProtocols(_ b: B, bp: BProto) {
var bp2 : BProto = b
var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}}
bp.method(1, with: 2.5 as Float)
bp.method(1, withFoo: 2.5) // expected-error{{incorrect argument label in call (have '_:withFoo:', expected '_:with:')}}
bp2 = b.getAsProto()
var c1 : Cat1Proto = b
var bcat1 = b.getAsProtoWithCat()!
c1 = bcat1
bcat1 = c1 // expected-error{{value of type 'Cat1Proto' does not conform to 'BProto & Cat1Proto' in assignment}}
}
// Methods only defined in a protocol
func testProtocolMethods(_ b: B, p2m: P2.Type) {
b.otherMethod(1, with: 3.14159)
b.p2Method()
b.initViaP2(3.14159, second: 3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}}
// Imported constructor.
var b2 = B(viaP2: 3.14159, second: 3.14159)
_ = p2m.init(viaP2:3.14159, second: 3.14159)
}
func testId(_ x: AnyObject) {
x.perform!("foo:", with: x) // expected-warning{{no method declared with Objective-C selector 'foo:'}}
// expected-warning @-1 {{result of call is unused, but produces 'Unmanaged<AnyObject>!'}}
_ = x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4)
_ = x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4)
_ = x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4)
}
class MySubclass : B {
// Override a regular method.
override func anotherMethodOnB() {}
// Override a category method
override func anotherCategoryMethod() {}
}
func getDescription(_ array: NSArray) {
_ = array.description
}
// Method overriding with unfortunate ordering.
func overridingTest(_ srs: SuperRefsSub) {
let rs : RefedSub
rs.overridden()
}
func almostSubscriptableValueMismatch(_ as1: AlmostSubscriptable, a: A) {
as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}}
}
func almostSubscriptableKeyMismatch(_ bc: BadCollection, key: NSString) {
// FIXME: We end up importing this as read-only due to the mismatch between
// getter/setter element types.
var _ : Any = bc[key]
}
func almostSubscriptableKeyMismatchInherited(_ bc: BadCollectionChild,
key: String) {
var value : Any = bc[key] // no-warning, inherited from parent
bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
func almostSubscriptableKeyMismatchInherited(_ roc: ReadOnlyCollectionChild,
key: String) {
var value : Any = roc[key] // no-warning, inherited from parent
roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
// Use of 'Class' via dynamic lookup.
func classAnyObject(_ obj: NSObject) {
_ = obj.myClass().description!()
}
// Protocol conformances
class Wobbler : NSWobbling { // expected-note{{candidate has non-matching type '()'}}
@objc func wobble() { }
func returnMyself() -> Self { return self } // expected-error{{non-'@objc' method 'returnMyself()' does not satisfy requirement of '@objc' protocol 'NSWobbling'}}{{none}}
// expected-error@-1{{method cannot be an implementation of an @objc requirement because its result type cannot be represented in Objective-C}}
}
extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}}
}
@objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{candidate has non-matching type '()'}}
func wobble() { }
func returnMyself() -> Self { return self }
}
extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}}
}
func optionalMemberAccess(_ w: NSWobbling) {
w.wobble()
w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}}
let x = w[5]!!
_ = x
}
func protocolInheritance(_ s: NSString) {
var _: NSCoding = s
}
func ivars(_ hive: Hive) {
var d = hive.bees.description
hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}}
}
class NSObjectable : NSObjectProtocol {
@objc var description : String { return "" }
@objc(conformsToProtocol:) func conforms(to _: Protocol) -> Bool { return false }
@objc(isKindOfClass:) func isKind(of aClass: AnyClass) -> Bool { return false }
}
// Properties with custom accessors
func customAccessors(_ hive: Hive, bee: Bee) {
markUsed(hive.isMakingHoney)
markUsed(hive.makingHoney()) // expected-error{{cannot call value of non-function type 'Bool'}}{{28-30=}}
hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}}
_ = (hive.`guard` as AnyObject).description // okay
_ = (hive.`guard` as AnyObject).description! // no-warning
hive.`guard` = bee // no-warning
}
// instancetype/Dynamic Self invocation.
func testDynamicSelf(_ queen: Bee, wobbler: NSWobbling) {
var hive = Hive()
// Factory method with instancetype result.
var hive1 = Hive(queen: queen)
hive1 = hive
hive = hive1
// Instance method with instancetype result.
var hive2 = hive!.visit()
hive2 = hive
hive = hive2
// Instance method on a protocol with instancetype result.
var wobbler2 = wobbler.returnMyself()!
var wobbler: NSWobbling = wobbler2
wobbler2 = wobbler
// Instance method on a base class with instancetype result, called on the
// class itself.
// FIXME: This should be accepted.
// FIXME: The error is lousy, too.
let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error{{missing argument for parameter #1 in call}}
}
func testRepeatedProtocolAdoption(_ w: NSWindow) {
_ = w.description
}
class ProtocolAdopter1 : FooProto {
@objc var bar: CInt // no-warning
init() { bar = 5 }
}
class ProtocolAdopter2 : FooProto {
@objc var bar: CInt {
get { return 42 }
set { /* do nothing! */ }
}
}
class ProtocolAdopterBad1 : FooProto { // expected-error {{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}}
@objc var bar: Int = 0 // expected-note {{candidate has non-matching type 'Int'}}
}
class ProtocolAdopterBad2 : FooProto { // expected-error {{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}}
let bar: CInt = 0 // expected-note {{candidate is not settable, but protocol requires it}}
}
class ProtocolAdopterBad3 : FooProto { // expected-error {{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}}
var bar: CInt { // expected-note {{candidate is not settable, but protocol requires it}}
return 42
}
}
@objc protocol RefinedFooProtocol : FooProto {}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: NSObject) {
// FIXME: We shouldn't need the ": Bool" type annotation here.
// <rdar://problem/18006008>
let _: Bool = NSObject.isEqual(obj)
_ = NSObject.isEqual(obj) as (NSObject!) -> Bool // no-warning
}
func testPropertyAndMethodCollision(_ obj: PropertyAndMethodCollision,
rev: PropertyAndMethodReverseCollision) {
obj.object = nil
obj.object(obj, doSomething:#selector(getter: NSMenuItem.action))
type(of: obj).classRef = nil
type(of: obj).classRef(obj, doSomething:#selector(getter: NSMenuItem.action))
rev.object = nil
rev.object(rev, doSomething:#selector(getter: NSMenuItem.action))
type(of: rev).classRef = nil
type(of: rev).classRef(rev, doSomething:#selector(getter: NSMenuItem.action))
var value: Any
value = obj.protoProp()
value = obj.protoPropRO()
value = type(of: obj).protoClassProp()
value = type(of: obj).protoClassPropRO()
_ = value
}
func testPropertyAndMethodCollisionInOneClass(
obj: PropertyAndMethodCollisionInOneClass,
rev: PropertyAndMethodReverseCollisionInOneClass
) {
obj.object = nil
obj.object()
type(of: obj).classRef = nil
type(of: obj).classRef()
rev.object = nil
rev.object()
type(of: rev).classRef = nil
type(of: rev).classRef()
}
func testSubscriptAndPropertyRedeclaration(_ obj: SubscriptAndProperty) {
_ = obj.x
obj.x = 5
_ = obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}}
obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testSubscriptAndPropertyWithProtocols(_ obj: SubscriptAndPropertyWithProto) {
_ = obj.x
obj.x = 5
obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testProtocolMappingSameModule(_ obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) {
markUsed(p.enablePostProcessing)
markUsed(obj.enablePostProcessing)
_ = obj.backgroundColor
}
func testProtocolMappingDifferentModules(_ obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) {
markUsed(p.thisIsTheProto)
markUsed(obj.thisClassHasAnAwfulName)
let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}}
_ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}}
_ = ObjCParseExtrasToo.ProtoInHelper()
_ = ObjCParseExtrasTooHelper.ClassInHelper()
_ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}}
}
func testProtocolClassShadowing(_ obj: ClassInHelper, p: ProtoInHelper) {
let _: ObjCParseExtrasToo.ClassInHelper = obj
let _: ObjCParseExtrasToo.ProtoInHelper = p
}
func testDealloc(_ obj: NSObject) {
// dealloc is subsumed by deinit.
// FIXME: Special-case diagnostic in the type checker?
obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}}
}
func testConstantGlobals() {
markUsed(MAX)
markUsed(SomeImageName)
markUsed(SomeNumber.description)
MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}}
SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}}
SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}}
}
func testWeakVariable() {
let _: AnyObject = globalWeakVar
}
class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}}
// expected-error@-1{{type 'IncompleteProtocolAdopter' does not conform to protocol 'Incomplete'}}
@objc func getObject() -> AnyObject { return self } // expected-note{{candidate has non-matching type '() -> AnyObject'}}
}
func testNullarySelectorPieces(_ obj: AnyObject) {
obj.foo(1, bar: 2, 3) // no-warning
obj.foo(1, 2, bar: 3) // expected-error{{cannot call value of non-function type 'Any?!'}}
}
func testFactoryMethodAvailability() {
_ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}}
}
func testRepeatedMembers(_ obj: RepeatedMembers) {
obj.repeatedMethod()
}
// rdar://problem/19726164
class FooDelegateImpl : NSObject, FooDelegate {
var _started = false
var isStarted: Bool {
get { return _started }
@objc(setStarted:) set { _started = newValue }
}
}
class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto {
var foo: Any? // no errors about conformance
var bar: Any? // no errors about conformance
}
func testUnusedResults(_ ur: UnusedResults) {
_ = ur.producesResult()
ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}}
}
func testStrangeSelectors(obj: StrangeSelectors) {
StrangeSelectors.cStyle(0, 1, 2) // expected-error{{type 'StrangeSelectors' has no member 'cStyle'}}
_ = StrangeSelectors(a: 0, b: 0) // okay
obj.empty(1, 2) // okay
}
func testProtocolQualified(_ obj: CopyableNSObject, cell: CopyableSomeCell,
plainObj: NSObject, plainCell: SomeCell) {
_ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = obj as NSObjectProtocol
_ = obj as NSCopying
_ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = cell as NSObject
_ = cell as NSObjectProtocol
_ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = cell as SomeCell
_ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'NSCopying & NSObjectProtocol'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}}
_ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe.
}
extension Printing {
func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
static func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
}
// <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated.
func testSetInitializers() {
let a: [AnyObject] = [NSObject()]
let _ = NSCountedSet(array: a)
let _ = NSMutableSet(array: a)
}
func testNSUInteger(_ obj: NSUIntegerTests, uint: UInt, int: Int) {
obj.consumeUnsigned(uint) // okay
obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay
obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(uint, andAnother: int) // okay
do {
let x = obj.unsignedProducer()
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.unsignedProducer(uint, fromCount: int) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.normalProducer(int, fromUnsigned: uint)
let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
}
let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
do {
testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = testUnsigned(uint, uint) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
// NSNumber
let num = NSNumber(value: uint)
let _: String = num.uintValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
class NewtypeUser {
@objc func stringNewtype(a: SNTErrorDomain) {}
@objc func stringNewtypeOptional(a: SNTErrorDomain?) {}
@objc func intNewtype(a: MyInt) {}
@objc func intNewtypeOptional(a: MyInt?) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: did you mean 'makingHoney'?
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27493-swift-parser-consumetoken.swift | 1 | 457 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{{{{protocol A{l}}}}}class B<T where g:a{class a{class B:a
| apache-2.0 |
reproto/reproto | it/structures/swift/basic-codable/Test.swift | 1 | 590 | public struct Test_Entry: Codable {
// The foo field.
let foo: Test_Foo?
enum CodingKeys: String, CodingKey {
case foo = "foo"
}
}
public struct Test_Foo: Codable {
// The field.
let field: String
enum CodingKeys: String, CodingKey {
case field = "field"
}
}
public struct Test_Bar: Codable {
// The inner field.
let field: Test_Bar_Inner
enum CodingKeys: String, CodingKey {
case field = "field"
}
}
public struct Test_Bar_Inner: Codable {
// The field.
let field: String
enum CodingKeys: String, CodingKey {
case field = "field"
}
}
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/15698-swift-sourcemanager-getmessage.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
[ {
{
class B
{
func b {
{
for {
class
case ,
| mit |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift | 15 | 22905 | //
// BarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BarChartRenderer: BarLineScatterCandleBubbleRenderer
{
fileprivate class Buffer
{
var rects = [CGRect]()
}
open weak var dataProvider: BarChartDataProvider?
public init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
// [CGRect] per dataset
fileprivate var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if top > 0
{
top *= CGFloat(phaseY)
}
else
{
bottom *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var bottom = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
top *= CGFloat(phaseY)
bottom *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
for i in 0 ..< barData.dataSetCount
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
}
fileprivate var _barShadowRectBuffer: CGRect = CGRect()
open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard
let animator = animator,
let barData = dataProvider.barData
else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.width = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width)
{
continue
}
if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x)
{
break
}
_barShadowRectBuffer.origin.y = viewPortHandler.contentTop
_barShadowRectBuffer.size.height = viewPortHandler.contentHeight
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(barRect)
}
}
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
}
context.restoreGState()
}
open func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let left = x - barWidthHalf
let right = x + barWidthHalf
let top = y1
let bottom = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0)
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler,
let barData = dataProvider.barData,
let animator = animator
else { return }
var dataSets = barData.dataSets
let valueOffsetPlus: CGFloat = 4.5
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if isInverted
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let buffer = _buffers[dataSetIndex]
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let x = rect.origin.x + rect.size.width / 2.0
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
let val = e.y
drawValue(
context: context,
value: formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if we have stacks
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let vals = e.yValues
let rect = buffer.rects[bufferIndex]
let x = rect.origin.x + rect.size.width / 2.0
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: rect.origin.y +
(e.y >= 0 ? posOffset : negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
else
{
// draw stack values
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY)))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
vals[k],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: y,
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
/// Draws a value at the specified x and y position.
open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
context.saveGState()
var barRect = CGRect()
for high in indices
{
guard
let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
set.isHighlightEnabled
else { continue }
if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
{
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setFillColor(set.highlightColor.cgColor)
context.setAlpha(set.highlightAlpha)
let isStack = high.stackIndex >= 0 && e.isStacked
let y1: Double
let y2: Double
if isStack
{
if dataProvider.isHighlightFullBarEnabled
{
y1 = e.positiveSum
y2 = -e.negativeSum
}
else
{
let range = e.ranges?[high.stackIndex]
y1 = range?.from ?? 0.0
y2 = range?.to ?? 0.0
}
}
else
{
y1 = e.y
y2 = 0.0
}
prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
setHighlightDrawPos(highlight: high, barRect: barRect)
context.fill(barRect)
}
}
context.restoreGState()
}
/// Sets the drawing position of the highlight object based on the riven bar-rect.
internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midX, y: barRect.origin.y)
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/03011-swift-sourcemanager-getmessage.swift | 11 | 312 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var b {
class a {
enum b : a {
protocol c : b = compose() {
return "[1]]
}
class func b: B<1 {
if true {
init<h: P {
class
case c,
func c,
cla
| mit |
ukitaka/UILifeCycleClosure | Example/UILifeCycleClosure/AppDelegate.swift | 1 | 2163 | //
// AppDelegate.swift
// UILifeCycleClosure
//
// Created by yuki.takahashi on 08/25/2015.
// Copyright (c) 2015 yuki.takahashi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/17749-swift-sourcemanager-getmessage.swift | 11 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( {
enum A {
var d = [ {
{
{
case
{
{
func g {
class A {
class
case ,
| mit |
wenluma/swift | test/SILGen/default_arguments_generic.swift | 1 | 3026 | // RUN: %target-swift-frontend -emit-silgen -swift-version 3 %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -swift-version 4 %s | %FileCheck %s
func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
struct Zim<T: ExpressibleByIntegerLiteral> {
init(x: T = 0) { }
init<U: ExpressibleByFloatLiteral>(_ x: T = 0, y: U = 0.5) { }
static func zim(x: T = 0) { }
static func zang<U: ExpressibleByFloatLiteral>(_: U.Type, _ x: T = 0, y: U = 0.5) { }
}
// CHECK-LABEL: sil hidden @_T025default_arguments_generic3baryyF : $@convention(thin) () -> () {
func bar() {
// CHECK: [[FOO_DFLT:%.*]] = function_ref @_T025default_arguments_generic3foo
// CHECK: apply [[FOO_DFLT]]<Int>
foo(Int.self)
// CHECK: [[ZIM_DFLT:%.*]] = function_ref @_T025default_arguments_generic3ZimV3zim
// CHECK: apply [[ZIM_DFLT]]<Int>
Zim<Int>.zim()
// CHECK: [[ZANG_DFLT_0:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A0_
// CHECK: apply [[ZANG_DFLT_0]]<Int, Double>
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self)
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self, 22)
}
protocol Initializable {
init()
}
struct Generic<T: Initializable> {
init(_ value: T = T()) {}
}
struct InitializableImpl: Initializable {
init() {}
}
// CHECK-LABEL: sil hidden @_T025default_arguments_generic17testInitializableyyF
func testInitializable() {
// The ".init" is required to trigger the crash that used to happen.
_ = Generic<InitializableImpl>.init()
// CHECK: [[INIT:%.+]] = function_ref @_T025default_arguments_generic7GenericVACyxGxcfC
// CHECK: function_ref @_T025default_arguments_generic7GenericVACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
// CHECK: apply [[INIT]]<InitializableImpl>({{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : Initializable> (@in τ_0_0, @thin Generic<τ_0_0>.Type) -> Generic<τ_0_0>
} // CHECK: end sil function '_T025default_arguments_generic17testInitializableyyF'
// Local generic functions with default arguments
// CHECK-LABEL: sil hidden @_T025default_arguments_generic5outeryx1t_tlF : $@convention(thin) <T> (@in T) -> ()
func outer<T>(t: T) {
func inner1(x: Int = 0) {}
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner1L_ySi1x_tlFfA_ : $@convention(thin) () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]() : $@convention(thin) () -> Int
_ = inner1()
func inner2(x: Int = 0) { _ = T.self }
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner2L_ySi1x_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]<T>() : $@convention(thin) <τ_0_0> () -> Int
_ = inner2()
}
| mit |
iCrany/iOSExample | iOSExample/Module/SwiftExample/VO/TextSwiftMixProtocolVO.swift | 1 | 308 | //
// TextSwiftMixProtocolVO.swift
// iOSExample
//
// Created by iCrany on 2018/9/29.
// Copyright © 2018 iCrany. All rights reserved.
//
import Foundation
class TextSwiftMixProtocolVO: SwiftMixOC2Protocol {
func testMethod3() {
print("TextSwiftMixProtocolVO imp testMethod3()")
}
}
| mit |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/Services/AccessTokenProvider.swift | 1 | 7150 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Combine
import Foundation
import GoogleRidesharingDriver
import UIKit
/// A service that can fetch tokens from the backend and test their validity.
///
/// Note that this class needs to inherit from NSObject in order to be able to adopt an Objective-C
/// protocol.
class AccessTokenProvider: NSObject, GMTDAuthorization, ObservableObject {
/// The data for a token as received from the Backend.
struct Token: Hashable, Codable {
let token: String
let creationTimestampMs: Date
let expirationTimestampMs: Date
static func loadFrom(from data: Data) throws -> Token {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode(self, from: data)
}
}
/// Special-purpose error to indicate an uninitialized enum.
enum Errors: Error {
case uninitialized
}
/// Type for the most recent result.
typealias TokenOrError = Result<Token, Error>
/// Type for the callback from fetch().
typealias TokenCompletion = (TokenOrError) -> Void
/// The vehicleId for which we fetch tokens.
var vehicleId: String? {
didSet {
synchronize {
result = TokenOrError.failure(Errors.uninitialized)
fetch(nil)
}
}
}
/// This Error indicates that the vehicleId property was not set before fetch() was called.
enum TokenServiceError: Error {
case vehicleIdUninitialized
}
/// The most recent result.
///
/// Any token in this result may not be valid, so this shouldn't be
/// used for transactions; those should always call fetchToken().
/// This property is intended for debugging UIs that display the last result.
@Published public private(set) var result = TokenOrError.failure(Errors.uninitialized)
/// The cancelable for any token request in-flight.
private var inFlightFetch: AnyCancellable?
/// The set of completions to notify when a fetch completes.
private var completions: [TokenCompletion] = [TokenCompletion]()
/// Fetches an up-to-date token or reports an error.
///
/// This fetches a token, taking advantage of an internally cached token if it is still valid.
/// An error will be passed to the callback if a token cannot be fetched or if the vehicleId
/// property has not been initialized.
///
/// Since this is called by the GMTDAuthorization entry point below, this method
/// may be invoked on an arbitrary queue.
func fetch(_ callback: TokenCompletion?) {
synchronize {
switch result {
case .success(let token):
if token.expirationTimestampMs >= Date() {
callback?(result)
return
}
fallthrough
case .failure:
if let vehicleId = vehicleId {
if let callback = callback {
completions.append(callback)
}
if inFlightFetch != nil {
return
}
let backendBaseURL = URL(string: ApplicationDefaults.backendBaseURLString.value)!
var components = URLComponents(url: backendBaseURL, resolvingAgainstBaseURL: false)!
components.path = "/token/delivery_driver/\(vehicleId)"
let request = URLRequest(url: components.url!)
inFlightFetch =
URLSession
.DataTaskPublisher(request: request, session: .shared)
.receive(on: RunLoop.main)
.sink(
receiveCompletion: { [weak self] completion in
self?.handleReceiveCompletion(completion: completion)
},
receiveValue: { [weak self] output in
self?.handleReceiveData(data: output.data)
}
)
result = TokenOrError.failure(Errors.uninitialized)
} else {
/// vehicleId == nil
if let callback = callback {
callback(TokenOrError.failure(TokenServiceError.vehicleIdUninitialized))
}
return
}
}
}
}
/// Handler for the completion of the URLSession DataTask.
private func handleReceiveCompletion(
completion: Subscribers.Completion<URLSession.DataTaskPublisher.Failure>
) {
self.synchronize {
switch completion {
case .finished:
break
case .failure(let error):
self.result = TokenOrError.failure(error)
self.invokeCallbacks()
}
/// switch(completion)
self.inFlightFetch = nil
}
}
/// Handler for the data callback of the URLSession DataTask.
private func handleReceiveData(data: Data) {
var newResult = TokenOrError.failure(Errors.uninitialized)
do {
try newResult = TokenOrError.success(Token.loadFrom(from: data))
} catch {
newResult = TokenOrError.failure(error)
}
self.synchronize {
self.result = newResult
self.invokeCallbacks()
}
}
/// Entry point for GMTDAuthorization protocol called by DriverSDK.
///
/// The GMTDAuthorization header file notes that this method may be invoked on an arbitrary
/// queue.
func fetchToken(
with authorizationContext: GMTDAuthorizationContext?,
completion: @escaping GMTDAuthTokenFetchCompletionHandler
) {
/// Enforce the function signature.
assert(authorizationContext?.vehicleID != nil)
/// We expect DriverSDK to only be invoked on the single manifest supported by this app.
assert(authorizationContext?.vehicleID == vehicleId)
/// Fetch the token from the token service, which already handles caching.
fetch { tokenOrError in
switch tokenOrError {
case .failure(let error):
completion(nil, error)
case .success(let token):
completion(token.token, nil)
}
}
}
/// Re-entrant, lock-based synchronization primitive.
///
/// Equivalent to Objective-C @synchronized. See
/// https://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html for more commentary
/// on synchronization in Swift. That also explains why this is in the individual class and not
/// placed in a helper function.
private func synchronize<T>(execute: () throws -> T) rethrows -> T {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
return try execute()
}
/// Invoke all pending callbacks with the current result and clear the completions array.
///
/// This must be called from inside a synchronize block.
private func invokeCallbacks() {
for completion in completions {
completion(self.result)
}
completions.removeAll()
}
}
| apache-2.0 |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/1.cook/2.Cook/Cook/PopAnimator.swift | 1 | 2913 | //
// PopAnimator.swift
// Cook
//
// Created by Dariel on 16/7/25.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
// 转场动画的原理:
/**
当两个控制器发生push或dismiss的时候,系统会把原始的view放到负责转场的控制器容器中,也会把目的的view也放进去,但是是不可见的,因此我们要做的就是把新的view显现出来,把老的view移除掉
*/
// 遵守协议
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
// 动画持续时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
//
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 获得容器
let containerView = transitionContext.containerView()!
// 获得目标view
// viewForKey 获取新的和老的控制器的view
// viewControllerForKey 获取新的和老的控制器
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
// 拿到需要做动画的view
let herbView = presenting ? toView : fromView
// 获取初始和最终的frame
let initialFrame = presenting ? originFrame : herbView.frame
let finalFrame = presenting ? herbView.frame : originFrame
// 设置收缩比率
let xScaleFactor = presenting ? initialFrame.width / finalFrame.width : finalFrame.width / initialFrame.width
let yScaleFactor = presenting ? initialFrame.height / finalFrame.height : finalFrame.height / initialFrame.height
let scaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor)
// 当presenting的时候,设置herbView的初始位置
if presenting {
herbView.transform = scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(initialFrame), y: CGRectGetMidY(initialFrame))
herbView.clipsToBounds = true
}
containerView.addSubview(toView)
// 保证在最前,不然添加的东西看不到哦
containerView.bringSubviewToFront(herbView)
// 加了个弹性效果
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
herbView.transform = self.presenting ? CGAffineTransformIdentity : scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(finalFrame), y: CGRectGetMidY(finalFrame))
}) { (_) -> Void in
transitionContext.completeTransition(true)
}
}
}
| mit |
davejlin/treehouse | swift/swift3/RestaurantReviews/RestaurantReviews/YelpReviewsDataSource.swift | 1 | 1518 | //
// YelpReviewsDataSource.swift
// RestaurantReviews
//
// Created by Pasan Premaratne on 5/9/17.
// Copyright © 2017 Treehouse. All rights reserved.
//
import Foundation
import UIKit
class YelpReviewsDataSource: NSObject, UITableViewDataSource {
private var data: [YelpReview]
init(data: [YelpReview]) {
self.data = data
super.init()
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ReviewCell.reuseIdentifier, for: indexPath) as! ReviewCell
let review = object(at: indexPath)
let viewModel = ReviewCellViewModel(review: review)
cell.configure(with: viewModel)
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Reviews"
}
// MARK: Helpers
func update(_ object: YelpReview, at indexPath: IndexPath) {
data[indexPath.row] = object
}
func updateData(_ data: [YelpReview]) {
self.data = data
}
func object(at indexPath: IndexPath) -> YelpReview {
return data[indexPath.row]
}
}
| unlicense |
railsware/Sleipnir | Sleipnir/Spec/Matchers/Container/ContainSpec.swift | 1 | 5837 | //
// ContainSpec.swift
// Sleipnir
//
// Created by Artur Termenji on 7/22/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
class ContainSpec : SleipnirSpec {
var containSpec : () = describe("Contain matcher") {
describe("when the container is an Array") {
var container: [Int]?
context("and it is is nil") {
beforeEach {
container = nil
}
it("should fail") {
let failureMessage = "Expected <nil> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it is empty") {
beforeEach {
container = [Int]()
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <[]> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = [1, 2, 3, 4, 5]
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
describe("negative match") {
let element = 1
it("should fail with a sensible failure message") {
let failureMessage = "Expected <[1, 2, 3, 4, 5]> to not contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).toNot(contain(element))
}
}
}
}
}
describe("when the container is a String") {
let container = "Test String"
var nested: String?
context("and it contains nested String") {
beforeEach {
nested = "Test"
}
describe("positive match") {
it("should pass") {
// expect(container).to(contain(nested!))
}
}
}
context("and it does not contain nested String") {
beforeEach {
nested = "Testt"
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <Test String> to contain <Testt>"
expectFailureWithMessage(failureMessage) {
// expect(container).to(contain(nested!))
}
}
}
}
describe("when the container is an NSArray") {
var container: NSArray?
context("and it is empty") {
beforeEach {
container = NSArray(array: [])
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <()> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = NSArray(array: [1, 2, 3, 4, 5])
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
context("when elements are Strings") {
beforeEach {
container = NSArray(array: ["test", "string"])
}
describe("positive match") {
let element = "test"
it("should pass") {
expect(container).to(contain(element))
}
}
}
}
}
describe("when the container is an NSSet") {
var container: NSSet?
context("and it is empty") {
beforeEach {
container = NSSet(array: [])
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <{()}> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = NSSet(array: [1, 2, 3, 4, 5])
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
}
}
}
} | mit |
0xcodezero/Vatrena | Vatrena/Vatrena/view/NLSegmentControl/UIView+Layout.swift | 3 | 6027 | //
// UIView+Layout.swift
// NLSegmentControl
//
// Created by songhailiang on 27/05/2017.
// Copyright © 2017 hailiang.song. All rights reserved.
//
import UIKit
// MARK: - Autolayout
public extension UIView {
@discardableResult
func nl_equalTop(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalLeft(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalBottom(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toView, attribute: .bottom, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalRight(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: toView, attribute: .trailing, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalWidth(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: toView, attribute: .width, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalHeight(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: toView, attribute: .height, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalCenterX(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: toView, attribute: .centerX, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalCenterY(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: toView, attribute: .centerY, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginTop(toView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .bottom, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginLeft(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .trailing, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginBottom(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginRight(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_widthIs(_ width: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width)
layout.isActive = true
return layout
}
@discardableResult
func nl_heightIs(_ height: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height)
layout.isActive = true
return layout
}
@discardableResult
func nl_ratioIs(_ ratio: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: ratio, constant: 0)
layout.isActive = true
return layout
}
}
| mit |
treejames/firefox-ios | UITests/NavigationTests.swift | 3 | 3475 | /* 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 WebKit
class NavigationTests: KIFTestCase, UITextFieldDelegate {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
/**
* Tests basic page navigation with the URL bar.
*/
func testNavigation() {
tester().tapViewWithAccessibilityIdentifier("url")
var textView = tester().waitForViewWithAccessibilityLabel("Address and Search") as? UITextField
XCTAssertTrue(textView!.text.isEmpty, "Text is empty")
XCTAssertNotNil(textView!.placeholder, "Text view has a placeholder to show when its empty")
let url1 = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
tester().tapViewWithAccessibilityIdentifier("url")
textView = tester().waitForViewWithAccessibilityLabel("Address and Search") as? UITextField
XCTAssertEqual(textView!.text, url1, "Text is url")
let url2 = "\(webRoot)/numberedPage.html?page=2"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url2)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 2")
tester().tapViewWithAccessibilityLabel("Back")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
tester().tapViewWithAccessibilityLabel("Forward")
tester().waitForWebViewElementWithAccessibilityLabel("Page 2")
}
func testScrollsToTopWithMultipleTabs() {
// test scrollsToTop works with 1 tab
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/scrollablePage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Top")
// var webView = tester().waitForViewWithAccessibilityLabel("Web content") as? WKWebView
tester().scrollViewWithAccessibilityIdentifier("contentView", byFractionOfSizeHorizontal: -0.9, vertical: -0.9)
tester().waitForWebViewElementWithAccessibilityLabel("Bottom")
tester().tapStatusBar()
tester().waitForWebViewElementWithAccessibilityLabel("Top")
// now open another tab and test it works too
tester().tapViewWithAccessibilityLabel("Show Tabs")
var addTabButton = tester().waitForViewWithAccessibilityLabel("Add Tab") as? UIButton
addTabButton?.tap()
tester().waitForViewWithAccessibilityLabel("Web content")
let url2 = "\(webRoot)/scrollablePage.html?page=2"
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url2)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Top")
tester().scrollViewWithAccessibilityIdentifier("contentView", byFractionOfSizeHorizontal: -0.9, vertical: -0.9)
tester().waitForWebViewElementWithAccessibilityLabel("Bottom")
tester().tapStatusBar()
tester().waitForWebViewElementWithAccessibilityLabel("Top")
}
override func tearDown() {
BrowserUtils.clearHistoryItems(tester(), numberOfTests: 5)
}
}
| mpl-2.0 |
finngaida/healthpad | Shared/ChartViews/WeightView.swift | 1 | 733 | //
// WeightView.swift
// HealthPad
//
// Created by Finn Gaida on 17.03.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
public class WeightView: LineView {
override init(frame: CGRect) {
super.init(frame: frame)
self.color = .Yellow
self.titleText = "Weight"
self.averageText = "79 kg"
self.todayText = "78.5 kg"
self.dateText = "Today, 3:14 PM"
}
public override func majorValueFromHealthObject(obj:HealthObject) -> String {
if let o = obj as? Weight {
return "\(o.value)"
} else {return ""}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| apache-2.0 |
stormpath/stormpath-sdk-swift | Stormpath/Networking/ResetPasswordAPIRequestManager.swift | 1 | 1029 | //
// ResetPasswordAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 2/8/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
typealias ResetPasswordAPIRequestCallback = ((NSError?) -> Void)
class ResetPasswordAPIRequestManager: APIRequestManager {
var email: String
var callback: ResetPasswordAPIRequestCallback
init(withURL url: URL, email: String, callback: @escaping ResetPasswordAPIRequestCallback) {
self.email = email
self.callback = callback
super.init(withURL: url)
}
override func prepareForRequest() {
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: ["email": email], options: [])
}
override func requestDidFinish(_ data: Data, response: HTTPURLResponse) {
performCallback(nil)
}
override func performCallback(_ error: NSError?) {
DispatchQueue.main.async {
self.callback(error)
}
}
}
| apache-2.0 |
HaloWang/FangYuan | FangYuanTests/FangYuanTests.swift | 1 | 549 | //
// FangYuanTests.swift
// FangYuanTests
//
// Created by 王策 on 16/4/11.
// Copyright © 2016年 王策. All rights reserved.
//
import XCTest
import FangYuan
class FangYuanTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| mit |
yikaraman/iOS8-day-by-day | 12-healthkit/BodyTemple/BodyTemple/TabBarViewController.swift | 1 | 2356 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import HealthKit
class TabBarViewController: UITabBarController {
var healthStore: HKHealthStore?
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
createAndPropagateHealthStore()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
createAndPropagateHealthStore()
}
override func viewDidLoad() {
super.viewDidLoad()
requestAuthorisationForHealthStore()
}
private func createAndPropagateHealthStore() {
if self.healthStore == nil {
self.healthStore = HKHealthStore()
}
for vc in viewControllers {
if let healthStoreUser = vc as? HealthStoreUser {
healthStoreUser.healthStore = self.healthStore
}
}
}
private func requestAuthorisationForHealthStore() {
let dataTypesToWrite = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
]
let dataTypesToRead = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)
]
self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),
readTypes: NSSet(array: dataTypesToRead), completion: {
(success, error) in
if success {
println("User completed authorisation request.")
} else {
println("The user cancelled the authorisation request. \(error)")
}
})
}
}
| apache-2.0 |
taipingeric/RubyInSwift | RubyInSwiftExtension.swift | 1 | 6324 | import Foundation
extension Int {
/// Execute closure N times
func times(f: () -> ()) {
if self > 0 {
for _ in 0..<self { f() }
}
}
func times(@autoclosure f: () -> ()) {
if self > 0 {
for _ in 0..<self { f() }
}
}
}
extension CollectionType where Index.Distance == Int {
/// Return random element from collection, or nil if collection is empty or count out of range
public var sample: Generator.Element? {
if isEmpty { return nil }
let randomIndex = startIndex.advancedBy(Int(arc4random_uniform(UInt32(self.count))))
return self[randomIndex]
}
/// Return random elements from collection, or nil if collection is empty or count out of range
public func sample(count: Int = 1) -> [Generator.Element]? {
if isEmpty || count > self.count { return nil }
var count = count
var storedIndex: [Index] = []
while count > 0 {
let randomIndex = startIndex.advancedBy(Int(arc4random_uniform(UInt32(self.count))))
if storedIndex.contains(randomIndex) == false {
storedIndex.append(randomIndex)
count -= 1
}
}
var resultCollection: [Generator.Element] = []
storedIndex.forEach { resultCollection.append(self[$0]) }
return resultCollection
}
}
extension Array {
public func isIndexValid(index: Int) -> Bool { return self.indices.contains(index) }
public func isCountValid(count: Int) -> Bool { return count < self.count }
/// Unsigned Int index
private func uIndex(index: Int) -> Int {
return (index % count) + count
}
/// Return element at index, or nil if self is empty or out of range.
public func fetch(index: Int, defaultValue: Element? = nil) -> Generator.Element?{
guard self.count != 0 else {
return nil
}
if index < 0 {
return self[uIndex(index)]
}
if isIndexValid(index) {
return self[index]
} else {
return defaultValue ?? nil
}
}
/// Return element at index, or nil with exception closure executed if self is empty or out of range.
public func fetch(index: Int, exception: (Int -> ())?) -> Element? {
guard let element = fetch(index) else{
exception?(index)
return nil
}
return element
}
/// Returns the first N elements of self, or nil if self is empty or out of range.
public func first(count: Int) -> [Element]? {
return take(count)
}
/// Returns the last N elements of self, or nil if self is empty or out of range.
public func last(count: Int) -> [Element]? {
return drop(count)
}
/// Return first N elements in array, or nil if self is empty or out of range.
public func take(count: Int) -> [Element]? {
return isCountValid(count) ? Array(prefix(count)) : nil
}
/// Return last N elements in array, or nil if self is empty or out of range.
public func drop(count: Int) -> [Element]? {
return isCountValid(count) ? Array(suffix(count)) : nil
}
/// The number of elements the Array stores.
public var length: Int {
return count
}
public var size: Int {
return count
}
/// Returns `true` iff `self` is empty.
public var empty: Bool {
return isEmpty
}
/// Append the elements of `newElements` to `self`.
public mutating func push(newElements: Element...) {
self.appendContentsOf(newElements)
}
/// Insert the elements of `newElements` to the beginning of `self` .
public mutating func unshift(newElements: Element...) {
self.insertContentsOf(newElements, at: 0)
}
/// Insert the elements of `newElements` at the index of `self` .
public mutating func insert(index: Int, newElements: Element...) {
uIndex(index)
index < 0 ? self.insertContentsOf(newElements, at: uIndex(index) + 1) : self.insertContentsOf(newElements, at: index)
}
}
infix operator << { associativity left precedence 160 }
/// << operator: push elements to array
public func << <T>(inout left: [T], right: [T]) {
left.appendContentsOf(right)
}
extension SequenceType where Generator.Element : Equatable {
/// Returns `true` iff `element` is in `self`.
public func include(element: Generator.Element) -> Bool {
return contains(element)
}
}
extension Array {
/// If `!self.isEmpty`, remove the last element and return it, otherwise nil
public mutating func pop() -> Element? {
return popLast()
}
/// pop last N elements and return them, return nil count is no valid
public mutating func pop(count: Int) -> [Element]? {
guard isCountValid(count) else {
return nil
}
var arr: [Element] = []
count.times {
arr.append( self.popLast()! )
}
return arr.reverse()
}
/// Pop first element, otherwise return nil
public mutating func shift() -> Element? {
let first = self.first
removeAtIndex(0)
return first
}
/// Pop first N elements, nil if count is not available or array is empty
public mutating func shift(count: Int) -> [Element]? {
guard isCountValid(count) else {
return nil
}
var array: [Element] = []
count.times {
array.append( self.shift()! )
}
return array
}
/// Remove and return the element at index `i`, nil if index is not valid
public mutating func delete_at(index: Int) -> Element? {
guard isIndexValid(index) else {
return nil
}
return removeAtIndex(index)
}
}
extension Array where Element: Equatable {
/// Remove all elements equal to input item, nil if no matching element
public mutating func delete(item: Element, exception: (() -> Element)? = nil) -> Element? {
let isExist = contains(item)
self = self.filter { element -> Bool in
return element != item
}
if isExist {
return item
}
return exception?()
}
} | mit |
fumiyasac/handMadeCalendarAdvance | handMadeCalendarAdvance/MainViewController.swift | 1 | 297 | //
// MainViewController.swift
// handMadeCalendarAdvance
//
// Created by 酒井文也 on 2020/12/06.
// Copyright © 2020 just1factory. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit |
wireapp/wire-ios-data-model | Source/Model/Message/AssetCache.swift | 1 | 2152 | //
// 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
import WireSystem
import WireImages
protocol Cache {
/// Returns the asset data for a given key.
///
/// This will probably cause I/O
func assetData(_ key: String) -> Data?
/// Returns the file URL (if any) for a given key.
func assetURL(_ key: String) -> URL?
/// Stores the asset data for a given key.
///
/// - parameter data: Asset data which should be stored
/// - parameter key: unique key used to store & retrieve the asset data
/// - parameter createdAt: date when the asset data was created
///
/// This will probably cause I/O
func storeAssetData(_ data: Data, key: String, createdAt: Date)
/// Stores the asset data for a source url that must be a local file.
///
/// - parameter url: URL pointing to the data which should be stored
/// - parameter key: unique key used to store & retrieve the asset data
/// - parameter createdAt: date when the asset data was created
///
/// This will probably cause I/O
func storeAssetFromURL(_ url: URL, key: String, createdAt: Date)
/// Deletes the data for a key.
func deleteAssetData(_ key: String)
/// Deletes assets created earlier than the given date.
///
/// This will cause I/O
func deleteAssetsOlderThan(_ date: Date) throws
/// Checks if the data exists in the cache. Faster than checking the data itself
func hasDataForKey(_ key: String) -> Bool
}
| gpl-3.0 |
lorentey/swift | test/attr/attr_availability_objc.swift | 36 | 9336 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
@objc
protocol OlfactoryProtocol {
@available(*, unavailable)
func bad() // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() // expected-note {{here}}
@available(*, unavailable)
var badProp: Int { get } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "init")
func nowAnInitializer() // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() // expected-note {{here}}
}
final class SchnozType : OlfactoryProtocol {
@objc func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}}
@objc func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}}
@objc func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{14-17=new}}
@objc func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{14-26=new}}
@objc var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}}
@objc var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}}
@objc var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{13-20=new}}
@objc var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{13-29=new}}
@objc func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}}
@objc func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}}
@objc init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}}
@objc init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}}
@objc func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-33=shinyLabeledArguments}} {{34-34=example }}
@objc func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-35=shinyLabeledArguments}} {{36-37=example}}
@objc func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{14-31=shinyLabeledArguments}}
@objc func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{14-29=shinyLabeledArguments}}
@objc func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-32=shinyLabeledArguments}} {{33-34=example}}
@objc func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{14-36=shinyLabeledArguments}}
@objc func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{14-37=shinyLabeledArguments}} {{38-38=_ }}
@objc func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{14-34=shinyLabeledArguments}}
@objc func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{14-37=shinyLabeledArguments}} {{38-39=example}} {{48-49=another}}
@objc func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{14-41=shinyLabeledArguments}}
@objc func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{14-42=shinyLabeledArguments}} {{43-43=_ }} {{51-51=_ }}
@objc init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{14-14=shinyNewName }}
@objc init(_ unavailableUnnamed: Int) {} // expected-error {{'init(_:)' has been renamed to 'init(a:)'}} {{14-15=a}}
@objc init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{14-14=_ }}
@objc init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init(_:_:)' has been renamed to 'init(a:b:)'}} {{14-15=a}} {{46-48=}}
@objc init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{14-42=_}} {{51-51=_ }}
@objc func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
@objc func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}}
@objc func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
@objc func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}}
}
// Make sure we can still conform to a protocol with unavailable requirements,
// and check for some bogus diagnostics not being emitted.
@objc
protocol Snout {
@available(*, unavailable)
func sniff()
}
class Tapir : Snout {}
class Elephant : Snout {
@nonobjc func sniff() {}
}
class Puppy : Snout {}
extension Puppy {
func sniff() {}
}
class Kitten : Snout {}
extension Kitten {
@nonobjc func sniff() {}
}
| apache-2.0 |
joninsky/JVUtilities | JVUtilities/TUCell.swift | 1 | 2086 | //
// TUCell.swift
// JVUtilities
//
// Created by Jon Vogel on 4/7/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
public class TUCell: UICollectionViewCell {
var cellImage: UIImageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
cellImage.translatesAutoresizingMaskIntoConstraints = false
self.cellImage.contentMode = UIViewContentMode.ScaleAspectFit
self.addSubview(self.cellImage)
self.constrainImageView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func constrainImageView() {
var constraints = [NSLayoutConstraint]()
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=0)-[image]-(>=0)-|", options: [], metrics: nil, views: ["image":self.cellImage])
for c in verticalConstraints {
constraints.append(c)
}
let centerHorizontal = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.cellImage, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
constraints.append(centerHorizontal)
let centerVertical = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.cellImage, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
constraints.append(centerVertical)
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=0)-[image]-(>=0)-|", options: [], metrics: nil, views: ["image":self.cellImage])
for c in horizontalConstraints {
constraints.append(c)
}
self.addConstraints(constraints)
}
}
| mit |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/nested_arrays/main.swift | 2 | 914 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
class C {
private struct Nested { public static var g_counter = 1 }
let m_counter: Int
private init(_ val: Int) { m_counter = val }
class func Create() -> C {
Nested.g_counter += 1
return C(Nested.g_counter)
}
}
func main() {
var aInt = [[1,2,3,4,5],[1,2,3,4],[1,2,3],[1,2],[1],[]]
var aC = [[C.Create(),C.Create(),C.Create(),C.Create()],[C.Create(),C.Create()],[],[C.Create()],[C.Create(),C.Create()]]
print(0) // break here
}
main()
| apache-2.0 |
cacawai/Tap2Read | tap2read/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift | 103 | 1573 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
@available(iOS 9.0, *)
public struct ConstraintLayoutGuideDSL: ConstraintAttributesDSL {
public var target: AnyObject? {
return self.guide
}
internal let guide: ConstraintLayoutGuide
internal init(guide: ConstraintLayoutGuide) {
self.guide = guide
}
}
| mit |
mshhmzh/firefox-ios | Utils/Extensions/HexExtensions.swift | 4 | 2389 | /* 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
extension String {
public var hexDecodedData: NSData {
// Convert to a CString and make sure it has an even number of characters (terminating 0 is included, so we
// check for uneven!)
guard let cString = self.cStringUsingEncoding(NSASCIIStringEncoding) where (cString.count % 2) == 1 else {
return NSData()
}
guard let result = NSMutableData(capacity: (cString.count - 1) / 2) else {
return NSData()
}
for i in 0.stride(to: (cString.count - 1), by: 2) {
guard let l = hexCharToByte(cString[i]), r = hexCharToByte(cString[i+1]) else {
return NSData()
}
var value: UInt8 = (l << 4) | r
result.appendBytes(&value, length: sizeofValue(value))
}
return result
}
private func hexCharToByte(c: CChar) -> UInt8? {
if c >= 48 && c <= 57 { // 0 - 9
return UInt8(c - 48)
}
if c >= 97 && c <= 102 { // a - f
return 10 + UInt8(c - 97)
}
if c >= 65 && c <= 70 { // A - F
return 10 + UInt8(c - 65)
}
return nil
}
}
private let HexDigits: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
extension NSData {
public var hexEncodedString: String {
let result = NSMutableString(capacity: length * 2)
let p = UnsafePointer<UInt8>(bytes)
for i in 0..<length {
result.appendString(HexDigits[Int((p[i] & 0xf0) >> 4)])
result.appendString(HexDigits[Int(p[i] & 0x0f)])
}
return String(result)
}
public class func randomOfLength(length: UInt) -> NSData? {
let length = Int(length)
if let data = NSMutableData(length: length) {
_ = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes))
return NSData(data: data)
} else {
return nil
}
}
}
extension NSData {
public var base64EncodedString: String {
return base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
}
}
| mpl-2.0 |
kasketis/netfox | netfox_ios_demo/TextViewController.swift | 1 | 2603 | //
// TextViewController.swift
// netfox_ios_demo
//
// Created by Nathan Jangula on 10/12/17.
// Copyright © 2017 kasketis. All rights reserved.
//
import UIKit
class TextViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var session: URLSession!
var dataTask: URLSessionDataTask?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func tappedLoad(_ sender: Any) {
dataTask?.cancel()
if session == nil {
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }
let request = URLRequest(url: url)
dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
self.handleCompletion(error: error.localizedDescription, data: data)
} else {
guard let data = data else { self.handleCompletion(error: "Invalid data", data: nil); return }
guard let response = response as? HTTPURLResponse else { self.handleCompletion(error: "Invalid response", data: data); return }
guard response.statusCode >= 200 && response.statusCode < 300 else { self.handleCompletion(error: "Invalid response code", data: data); return }
self.handleCompletion(error: error?.localizedDescription, data: data)
}
}
dataTask?.resume()
}
private func handleCompletion(error: String?, data: Data?) {
DispatchQueue.main.async {
if let error = error {
NSLog(error)
return
}
if let data = data {
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let message = dict?["value"] as? String {
self.textView.text = message
}
} catch {
}
}
}
}
}
extension TextViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}
| mit |
noppoMan/Suv | Tests/SuvTests/QueueWorkerTests.swift | 1 | 845 | //
// QueueWorkerTests.swift
// Suv
//
// Created by Yuki Takei on 3/4/16.
// Copyright © 2016 MikeTOKYO. All rights reserved.
//
import XCTest
import CLibUv
@testable import Suv
func fibonacci(_ number: Int) -> (Int) {
if number <= 1 {
return number
} else {
return fibonacci(number - 1) + fibonacci(number - 2)
}
}
class QueueWorkerTests: XCTestCase {
static var allTests: [(String, (QueueWorkerTests) -> () throws -> Void)] {
return [
("testQWork", testQWork)
]
}
func testQWork() {
Process.qwork(onThread: { ctx in
ctx.storage["result"] = fibonacci(10)
}, onFinish: { ctx in
XCTAssertEqual(55, ctx.storage["result"] as! Int)
Loop.defaultLoop.stop()
})
Loop.defaultLoop.run()
}
}
| mit |
MAARK/Charts | Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift | 5 | 12730 | //
// XAxisRendererHorizontalBarChart.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class XAxisRendererHorizontalBarChart: XAxisRenderer
{
internal weak var chart: BarChartView?
@objc public init(viewPortHandler: ViewPortHandler, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer)
self.chart = chart
}
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
if let transformer = self.transformer
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutY
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
if inverted
{
min = Double(p2.y)
max = Double(p1.y)
}
else
{
min = Double(p1.y)
max = Double(p2.y)
}
}
}
computeAxisValues(min: min, max: max)
}
open override func computeSize()
{
guard let
xAxis = self.axis as? XAxis
else { return }
let longest = xAxis.getLongestLabel() as NSString
let labelSize = longest.size(withAttributes: [NSAttributedString.Key.font: xAxis.labelFont])
let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5)
let labelHeight = labelSize.height
let labelRotatedSize = CGSize(width: labelSize.width, height: labelHeight).rotatedBy(degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5)
xAxis.labelRotatedHeight = round(labelRotatedSize.height)
}
open override func renderAxisLabels(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis
else { return }
if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil
{
return
}
let xoffset = xAxis.xOffset
if xAxis.labelPosition == .top
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else if xAxis.labelPosition == .topInside
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottom
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottomInside
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
}
/// draws the x-labels on the specified y-position
open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle.DEG2RAD
let centeringEnabled = xAxis.isCenterAxisLabelsEnabled
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
for i in stride(from: 0, to: xAxis.entryCount, by: 1)
{
// only fill x values
position.x = 0.0
if centeringEnabled
{
position.y = CGFloat(xAxis.centeredEntries[i])
}
else
{
position.y = CGFloat(xAxis.entries[i])
}
transformer.pointValueToPixel(&position)
if viewPortHandler.isInBoundsY(position.y)
{
if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis)
{
drawLabel(
context: context,
formattedLabel: label,
x: pos,
y: position.y,
attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor],
anchor: anchor,
angleRadians: labelRotationAngleRadians)
}
}
}
}
@objc open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [NSAttributedString.Key : Any],
anchor: CGPoint,
angleRadians: CGFloat)
{
ChartUtils.drawText(
context: context,
text: formattedLabel,
point: CGPoint(x: x, y: y),
attributes: attributes,
anchor: anchor,
angleRadians: angleRadians)
}
open override var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
private var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat)
{
if viewPortHandler.isInBoundsY(y)
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y))
context.strokePath()
}
}
open override func renderAxisLine(context: CGContext)
{
guard let xAxis = self.axis as? XAxis else { return }
if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(xAxis.axisLineColor.cgColor)
context.setLineWidth(xAxis.axisLineWidth)
if xAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if xAxis.labelPosition == .top ||
xAxis.labelPosition == .topInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
if xAxis.labelPosition == .bottom ||
xAxis.labelPosition == .bottomInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
open override func renderLimitLines(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
var limitLines = xAxis.limitLines
if limitLines.count == 0
{
return
}
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .topRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .bottomRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .topLeft
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
}
}
}
}
| apache-2.0 |
couchbase/couchbase-lite-ios | Swift/Tests/PredictiveQueryTest.swift | 1 | 44772 | //
// PredictiveQueryTest.swift
// CouchbaseLite
//
// Copyright (c) 2018 Couchbase, Inc. All rights reserved.
//
// Licensed under the Couchbase License Agreement (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import CouchbaseLiteSwift
class PredictiveQueryTest: CBLTestCase {
override func setUp() {
super.setUp()
Database.prediction.unregisterModel(withName: AggregateModel.name)
Database.prediction.unregisterModel(withName: TextModel.name)
Database.prediction.unregisterModel(withName: EchoModel.name)
}
@discardableResult
func createDocument(withNumbers numbers: [Int]) -> MutableDocument {
let doc = MutableDocument()
doc.setValue(numbers, forKey: "numbers")
try! db.saveDocument(doc)
return doc
}
func testRegisterAndUnregisterModel() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
// Query before registering the model:
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.int(forKey: "sum"), 15)
}
XCTAssertEqual(rows, 1);
aggregateModel.unregisterModel()
// Query after unregistering the model:
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
}
func testRegisterMultipleModelsWithSameName() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let model = "TheModel"
let aggregateModel = AggregateModel()
Database.prediction.registerModel(aggregateModel, withName: model)
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
var rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.int(forKey: "sum"), 15)
}
XCTAssertEqual(rows, 1);
// Register a new model with the same name:
let echoModel = EchoModel()
Database.prediction.registerModel(echoModel, withName: model)
// Query again should use the new model:
rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertNil(pred.value(forKey: "sum"))
XCTAssert(pred.array(forKey: "numbers")!.toArray() == [1, 2, 3, 4, 5])
}
XCTAssertEqual(rows, 1);
Database.prediction.unregisterModel(withName: model)
}
func testPredictionInputOutput() throws {
// Register echo model:
let echoModel = EchoModel()
echoModel.registerModel()
// Create a doc:
let doc = self.createDocument()
doc.setString("Daniel", forKey: "name")
doc.setInt(2, forKey: "number")
try self.saveDocument(doc)
// Create prediction function input:
let date = Date()
let dateStr = jsonFromDate(date)
let power = Function.power(base: Expression.property("number"), exponent: Expression.value(2))
let dict: [String: Any] = [
// Literal:
"number1": 10,
"number2": 10.1,
"int_min": Int.min,
"int_max": Int.max,
"int64_min": Int64.min,
"int64_max": Int64.max,
"float_min": Float.leastNormalMagnitude,
"float_max": Float.greatestFiniteMagnitude,
"double_min": Double.leastNormalMagnitude,
// rounding error: https://issues.couchbase.com/browse/CBL-1363
// "double_max": Double.greatestFiniteMagnitude,
"boolean_true": true,
"boolean_false": false,
"string": "hello",
"date": date,
"null": NSNull(),
"dict": ["foo": "bar"],
"array": ["1", "2", "3"],
// Expression:
"expr_property": Expression.property("name"),
"expr_value_number1": Expression.value(20),
"expr_value_number2": Expression.value(20.1),
"expr_value_boolean": Expression.value(true),
"expr_value_string": Expression.value("hi"),
"expr_value_date": Expression.value(date),
"expr_value_null": Expression.value(nil),
"expr_value_dict": Expression.value(["ping": "pong"]),
"expr_value_array": Expression.value(["4", "5", "6"]),
"expr_power": power
]
// Execute query and validate output:
let input = Expression.value(dict)
let model = EchoModel.name
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.count, dict.count)
// Literal:
XCTAssertEqual(pred.int(forKey: "number1"), 10)
XCTAssertEqual(pred.double(forKey: "number2"), 10.1)
XCTAssertEqual(pred.int(forKey: "int_min"), Int.min)
XCTAssertEqual(pred.int(forKey: "int_max"), Int.max)
XCTAssertEqual(pred.int64(forKey: "int64_min"), Int64.min)
XCTAssertEqual(pred.int64(forKey: "int64_max"), Int64.max)
XCTAssertEqual(pred.float(forKey: "float_min"), Float.leastNormalMagnitude)
XCTAssertEqual(pred.float(forKey: "float_max"), Float.greatestFiniteMagnitude)
XCTAssertEqual(pred.double(forKey: "double_min"), Double.leastNormalMagnitude)
XCTAssertEqual(pred.boolean(forKey: "boolean_true"), true)
XCTAssertEqual(pred.boolean(forKey: "boolean_false"), false)
XCTAssertEqual(pred.string(forKey: "string"), "hello")
XCTAssertEqual(jsonFromDate(pred.date(forKey: "date")!), dateStr)
XCTAssertEqual(pred.value(forKey: "null") as! NSNull, NSNull())
XCTAssert(pred.dictionary(forKey: "dict")!.toDictionary() == ["foo": "bar"] as [String: Any])
XCTAssert(pred.array(forKey: "array")!.toArray() == ["1", "2", "3"])
// Expression:
XCTAssertEqual(pred.string(forKey: "expr_property"), "Daniel")
XCTAssertEqual(pred.int(forKey: "expr_value_number1"), 20)
XCTAssertEqual(pred.double(forKey: "expr_value_number2"), 20.1)
XCTAssertEqual(pred.boolean(forKey: "expr_value_boolean"), true)
XCTAssertEqual(pred.string(forKey: "expr_value_string"), "hi")
XCTAssertEqual(jsonFromDate(pred.date(forKey: "expr_value_date")!), dateStr)
XCTAssertEqual(pred.value(forKey: "expr_value_null") as! NSNull, NSNull())
XCTAssert(pred.dictionary(forKey: "expr_value_dict")!.toDictionary() == ["ping": "pong"] as [String: Any])
XCTAssert(pred.array(forKey: "expr_value_array")!.toArray() == ["4", "5", "6"])
XCTAssertEqual(pred.int(forKey: "expr_power"), 4)
}
XCTAssertEqual(rows, 1);
echoModel.unregisterModel()
}
func testPredictionWithBlobPropertyInput() throws {
let texts = [
"Knox on fox in socks in box. Socks on Knox and Knox in box.",
"Clocks on fox tick. Clocks on Knox tock. Six sick bricks tick. Six sick chicks tock."
]
for text in texts {
let doc = MutableDocument()
doc.setBlob(blobForString(text), forKey: "text")
try db.saveDocument(doc)
}
let textModel = TextModel()
textModel.registerModel()
let model = TextModel.name
let input = Expression.dictionary(["text" : Expression.property("text")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("text"),
SelectResult.expression(prediction.property("wc")).as("wc"))
.from(DataSource.database(db))
.where(prediction.property("wc").greaterThan(Expression.value(15)))
let rows = try verifyQuery(q) { (n, r) in
let blob = r.blob(forKey: "text")!
let text = String(bytes: blob.content!, encoding: .utf8)!
XCTAssertEqual(text, texts[1])
XCTAssertEqual(r.int(forKey: "wc"), 16)
}
XCTAssertEqual(rows, 1);
textModel.unregisterModel()
}
func testPredictionWithBlobParameterInput() throws {
try db.saveDocument(MutableDocument())
let textModel = TextModel()
textModel.registerModel()
let model = TextModel.name
let input = Expression.dictionary(["text" : Expression.parameter("text")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("wc")).as("wc"))
.from(DataSource.database(db))
let params = Parameters()
params.setBlob(blobForString("Knox on fox in socks in box. Socks on Knox and Knox in box."),
forName: "text")
q.parameters = params
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 14)
}
XCTAssertEqual(rows, 1);
textModel.unregisterModel()
}
func testPredictionWithNonSupportedInputTypes() throws {
try db.saveDocument(MutableDocument())
let echoModel = EchoModel()
echoModel.registerModel()
// Query with non dictionary input:
let model = EchoModel.name
let input = Expression.value("string")
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
// Query with non-supported value type in dictionary input.
// Note: The code below will crash the test as Swift cannot handle exception thrown by
// Objective-C
//
// let input2 = Expression.value(["key": self])
// let prediction2 = Function.prediction(model: model, input: input2)
// let q2 = QueryBuilder
// .select(SelectResult.expression(prediction2))
// .from(DataSource.database(db))
// try q2.execute()
echoModel.unregisterModel()
}
func testQueryPredictionResultDictionary() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"), SelectResult.expression(prediction))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let pred = r.dictionary(at: 1)!
XCTAssertEqual(pred.int(forKey: "sum"), numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(pred.int(forKey: "min"), numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(pred.int(forKey: "max"), numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(pred.int(forKey: "avg"), numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 2);
aggregateModel.unregisterModel()
}
func testQueryPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("min")).as("min"),
SelectResult.expression(prediction.property("max")).as("max"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
let min = r.int(at: 2)
let max = r.int(at: 3)
let avg = r.int(at: 4)
XCTAssertEqual(sum, r.int(forKey: "sum"))
XCTAssertEqual(min, r.int(forKey: "min"))
XCTAssertEqual(max, r.int(forKey: "max"))
XCTAssertEqual(avg, r.int(forKey: "avg"))
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(min, numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(max, numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(avg, numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 2);
aggregateModel.unregisterModel()
}
func testWhereUsingPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("min")).as("min"),
SelectResult.expression(prediction.property("max")).as("max"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, 15)
let min = r.int(at: 2)
let max = r.int(at: 3)
let avg = r.int(at: 4)
XCTAssertEqual(sum, r.int(forKey: "sum"))
XCTAssertEqual(min, r.int(forKey: "min"))
XCTAssertEqual(max, r.int(forKey: "max"))
XCTAssertEqual(avg, r.int(forKey: "avg"))
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(min, numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(max, numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(avg, numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 1);
aggregateModel.unregisterModel()
}
func testOrderByUsingPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").greaterThan(Expression.value(1)))
.orderBy(Ordering.expression(prediction.property("sum")).descending())
var sums: [Int] = []
let rows = try verifyQuery(q) { (n, r) in
sums.append(r.int(at: 0))
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(sums, [40, 15])
aggregateModel.unregisterModel()
}
func testPredictiveModelReturningNull() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let doc = createDocument()
doc.setString("Knox on fox in socks in box. Socks on Knox and Knox in box.", forKey: "text")
try saveDocument(doc)
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
var q: Query = QueryBuilder
.select(SelectResult.expression(prediction),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
var rows = try verifyQuery(q) { (n, r) in
if n == 1 {
XCTAssertNotNil(r.dictionary(at: 0))
XCTAssertEqual(r.int(at: 1), 15)
} else {
XCTAssertNil(r.value(at: 0))
XCTAssertNil(r.value(at: 1))
}
}
XCTAssertEqual(rows, 2);
// Evaluate with nullOrMissing:
q = QueryBuilder
.select(SelectResult.expression(prediction),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.notNullOrMissing())
rows = try verifyQuery(q) { (n, r) in
XCTAssertNotNil(r.dictionary(at: 0))
XCTAssertEqual(r.int(at: 1), 15)
}
XCTAssertEqual(rows, 1);
}
func testIndexPredictionValueUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")))
try db.createIndex(index, withName: "SumIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"), SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
}
func testIndexMultiplePredictionValuesUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let sumIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")))
try db.createIndex(sumIndex, withName: "SumIndex")
let avgIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("avg")))
try db.createIndex(avgIndex, withName: "AvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssert(r.int(at: 0) == 15 || r.int(at: 1) == 8)
}
XCTAssertEqual(rows, 2);
}
func testIndexCompoundPredictiveValuesUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")),
ValueIndexItem.expression(prediction.property("avg")))
try db.createIndex(index, withName: "SumAvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)).and(
prediction.property("avg").equalTo(Expression.value(3))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumAvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 15)
XCTAssertEqual(r.int(at: 1), 3)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 4);
}
func testIndexPredictionResultUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input)
try db.createIndex(index, withName: "AggIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX AggIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexPredictionValueUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(index, withName: "SumIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexMultiplePredictionValuesUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let sumIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(sumIndex, withName: "SumIndex")
let avgIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["avg"])
try db.createIndex(avgIndex, withName: "AvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssert(r.int(at: 0) == 15 || r.int(at: 1) == 8)
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexCompoundPredictiveValuesUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum", "avg"])
try db.createIndex(index, withName: "SumAvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)).and(
prediction.property("avg").equalTo(Expression.value(3))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumAvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 15)
XCTAssertEqual(r.int(at: 1), 3)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testDeletePredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
// Index:
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(index, withName: "SumIndex")
// Query with index:
var q: Query = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
var explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
var rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
// Delete SumIndex:
try db.deleteIndex(forName: "SumIndex")
// Query again:
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testDeletePredictiveIndexesSharingSameCacheTable() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
// Create agg index:
let aggIndex = IndexBuilder.predictiveIndex(model: model, input: input)
try db.createIndex(aggIndex, withName: "AggIndex")
// Create sum index:
let sumIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(sumIndex, withName: "SumIndex")
// Create avg index:
let avgIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["avg"])
try db.createIndex(avgIndex, withName: "AvgIndex")
// Query:
var q: Query = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
var explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
var rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
// Delete SumIndex:
try db.deleteIndex(forName: "SumIndex")
// Note: when having only one index, SQLite optimizer doesn't utilize the index
// when using OR expr. Hence explicity test each index with two queries:
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("avg").equalTo(Expression.value(8)))
explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
// Delete AvgIndex
try db.deleteIndex(forName: "AvgIndex")
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("avg").equalTo(Expression.value(8)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
// Delete AggIndex
try db.deleteIndex(forName: "AggIndex")
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 2);
XCTAssert(aggregateModel.numberOfCalls > 0);
aggregateModel.unregisterModel()
}
func testEuclideanDistance() throws {
let tests: [[Any]] = [
[[10, 10], [13, 14], 5],
[[1, 2, 3], [1, 2, 3], 0],
[[], [], 0],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.euclideanDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.int(at: 0), r.int(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
func testSquaredEuclideanDistance() throws {
let tests: [[Any]] = [
[[10, 10], [13, 14], 25],
[[1, 2, 3], [1, 2, 3], 0],
[[], [], 0],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.squaredEuclideanDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.int(at: 0), r.int(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
func testCosineDistance() throws {
let tests: [[Any]] = [
[[10, 0], [0, 99], 1.0],
[[1, 2, 3], [1, 2, 3], 0.0],
[[1, 0, -1], [-1, -1, 0], 1.5],
[[], [], NSNull()],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.cosineDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.double(at: 0), r.double(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
}
// MARK: Models
class TestPredictiveModel: PredictiveModel {
class var name: String {
return "Untitled"
}
var numberOfCalls = 0
func predict(input: DictionaryObject) -> DictionaryObject? {
numberOfCalls = numberOfCalls + 1
return self.doPredict(input: input)
}
func doPredict(input: DictionaryObject) -> DictionaryObject? {
return nil
}
func registerModel() {
Database.prediction.registerModel(self, withName: type(of: self).name)
}
func unregisterModel() {
Database.prediction.unregisterModel(withName: type(of: self).name)
}
func reset() {
numberOfCalls = 0
}
}
class EchoModel: TestPredictiveModel {
override class var name: String {
return "EchoModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
return input;
}
}
class AggregateModel: TestPredictiveModel {
override class var name: String {
return "AggregateModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
guard let numbers = input.array(forKey: "numbers")?.toArray() as NSArray? else {
return nil
}
let output = MutableDictionaryObject()
output.setValue(numbers.value(forKeyPath: "@sum.self"), forKey: "sum")
output.setValue(numbers.value(forKeyPath: "@min.self"), forKey: "min")
output.setValue(numbers.value(forKeyPath: "@max.self"), forKey: "max")
output.setValue(numbers.value(forKeyPath: "@avg.self"), forKey: "avg")
return output
}
}
class TextModel: TestPredictiveModel {
override class var name: String {
return "TextModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
guard let blob = input.blob(forKey: "text") else {
return nil
}
guard let contentType = blob.contentType, contentType == "text/plain" else {
NSLog("WARN: Invalid blob content type; not text/plain.")
return nil
}
let text = String(bytes: blob.content!, encoding: .utf8)! as NSString
var wc = 0
var sc = 0
var curSentLoc = NSNotFound
text.enumerateLinguisticTags(in: NSRange(location: 0, length: text.length),
scheme: NSLinguisticTagScheme(rawValue: NSLinguisticTagScheme.tokenType.rawValue),
options: [], orthography: nil)
{ (tag, token, sent, stop) in
if tag!.rawValue == NSLinguisticTag.word.rawValue {
wc = wc + 1
}
if sent.location != NSNotFound && curSentLoc != sent.location {
curSentLoc = sent.location
sc = sc + 1
}
}
let output = MutableDictionaryObject()
output.setInt(wc, forKey: "wc")
output.setInt(sc, forKey: "sc")
return output
}
}
| apache-2.0 |
adrfer/swift | test/DebugInfo/archetype.swift | 12 | 1116 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | FileCheck %s
protocol IntegerArithmeticType {
static func uncheckedSubtract(lhs: Self, rhs: Self) -> (Self, Bool)
}
protocol RandomAccessIndexType : IntegerArithmeticType {
typealias Distance : IntegerArithmeticType
static func uncheckedSubtract(lhs: Self, rhs: Self) -> (Distance, Bool)
}
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtTQQq_F9archetype16ExistentialTuple
// CHECK-SAME: identifier: [[TT:".+"]])
// archetype.ExistentialTuple <A : RandomAccessIndexType, B>(x : A, y : A) -> B
// CHECK: !DISubprogram(name: "ExistentialTuple", linkageName: "_TF9archetype16ExistentialTuple
// CHECK-SAME: line: [[@LINE+2]]
// CHECK-SAME: isDefinition: true
func ExistentialTuple<T: RandomAccessIndexType>(x: T, y: T) -> T.Distance {
// (B, Swift.Bool)
// CHECK: !DILocalVariable(name: "tmp"
// CHECK-SAME: line: [[@LINE+2]]
// CHECK-SAME: type: ![[TT]]
var tmp : (T.Distance, Bool) = T.uncheckedSubtract(x, rhs: y)
return _overflowChecked((tmp.0, tmp.1))
}
| apache-2.0 |
akiramur/PeerClient | PeerClient/PeerConnection.swift | 1 | 5617 | //
// PeerConnection.swift
// PeerClient
//
// Created by Akira Murao on 10/16/15.
// Copyright © 2017 Akira Murao. All rights reserved.
//
import Foundation
import libjingle_peerconnection
public protocol PeerConnectionDelegate {
func connection(connection: PeerConnection, shouldSendMessage message: [String: Any]) // TODO: replace this with block?
func connection(connection: PeerConnection, didReceiveRemoteStream stream: RTCMediaStream?)
func connection(connection: PeerConnection, didClose error: Error?)
func connection(connection: PeerConnection, didReceiveData data: Data)
}
enum PeerConnectionError: Error {
case invalidState
case creatingDataChannel
}
public class PeerConnection: NSObject {
public enum ConnectionType {
case media
case data
public var string: String {
switch self {
case .media:
return "media"
case .data:
return "data"
}
}
var prefix: String {
switch self {
case .media:
return "mc_"
case .data:
return "dc_"
}
}
}
var delegate: PeerConnectionDelegate?
var closeCompletionBlock: ((Error?) -> Void)?
public private(set) var peerId: String
public var connectionId: String {
get {
return self.options.connectionId
}
}
public var connectionType: PeerConnection.ConnectionType {
get {
return self.options.connectionType
}
}
var pc: RTCPeerConnection? {
didSet {
print("PeerConnection pc: \(String(describing: self.pc))")
}
}
var isOpen: Bool
var options: PeerConnectionOptions
var lostMessages: [[String: Any]]
var negotiator: Negotiator
/*
options = @{
@"connectionId": connectionId,
@"payload": payload,
@"metadata": metadata}
*/
init(peerId: String?, delegate: PeerConnectionDelegate?, options: PeerConnectionOptions) {
//EventEmitter.call(this); // lets move this to public method call
self.delegate = delegate
self.peerId = peerId ?? ""
self.pc = nil
self.isOpen = false
self.options = options
self.lostMessages = [[String: Any]]()
self.negotiator = Negotiator()
super.init()
// lets call this in subclasses
//self.startConnection(options)
}
func close(_ completion: @escaping (Error?) -> Void) {
print("PeerConnection close() \(self.options.connectionId)")
guard self.closeCompletionBlock == nil else {
print("ERROR: closeCompletionBlock already exists. something went wrong.")
return
}
if !self.isOpen {
completion(PeerConnectionError.invalidState)
return
}
self.closeCompletionBlock = completion
self.isOpen = false
if let pc = self.pc {
self.negotiator.stopConnection(pc: pc)
}
self.pc = nil
//this.emit('close')
// MEMO: let's call this in iceConnectionChanged: RTCICEConnectionClosed
//DispatchQueue.main.async {
// self.delegate?.connectionDidClose(connection: self)
//}
}
// from Negotiator
func handleLostMessages() {
// Find messages.
let messages = self.getMessages()
for message in messages {
self.handleMessage(message: message)
}
}
func storeMessage(message: [String: Any]) {
self.lostMessages.append(message)
}
func getMessages() -> [[String: Any]] {
let messages = self.lostMessages
self.lostMessages.removeAll()
return messages
}
func handleMessage(message: [String: Any]) {
print("handleMessage")
guard let pc = self.pc else {
print("ERROR: pc does't exist")
return
}
guard let payload = message["payload"] as? [String: Any] else {
print("ERROR: payload doesn't exist")
return
}
guard let type = message["type"] as? String else {
print("ERROR: type doesn't exist")
return
}
print("TYPE: \(type)")
switch type {
case "ANSWER":
if let browser = payload["browser"] as? String {
self.options.browser = browser
}
if let sdp = payload["sdp"] as? [String: Any] {
self.negotiator.handleSDP(pc, peerId: self.peerId, type: "answer", message: sdp, options: self.options, completion: { [weak self] (result) in
switch result {
case let .success(message):
if let sself = self {
sself.delegate?.connection(connection: sself, shouldSendMessage: message)
}
case let .failure(error):
print("Error: something went wrong in handleSDP \(error)")
return
}
})
self.isOpen = true
}
case "CANDIDATE":
if let candidate = payload["candidate"] as? [String: Any] {
self.negotiator.handleCandidate(pc, message: candidate)
}
default:
print("WARNING: Unrecognized message type: \(type) from peerId: \(self.peerId)")
break
}
}
}
| mit |
LeeroyDing/Bond | Bond/iOS/Bond+UISegmentedControl.swift | 8 | 3351 | //
// Bond+UISegmentedControl.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Austin Cooley (@adcooley)
//
// 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
@objc class SegmentedControlDynamicHelper
{
weak var control: UISegmentedControl?
var listener: (UIControlEvents -> Void)?
init(control: UISegmentedControl) {
self.control = control
control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func valueChanged(control: UISegmentedControl) {
self.listener?(.ValueChanged)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
}
class SegmentedControlDynamic<T>: InternalDynamic<UIControlEvents>
{
let helper: SegmentedControlDynamicHelper
init(control: UISegmentedControl) {
self.helper = SegmentedControlDynamicHelper(control: control)
super.init()
self.helper.listener = { [unowned self] in
self.value = $0
}
}
}
private var eventDynamicHandleUISegmentedControl: UInt8 = 0;
extension UISegmentedControl /*: Dynamical, Bondable */ {
public var dynEvent: Dynamic<UIControlEvents> {
if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUISegmentedControl) {
return (d as? Dynamic<UIControlEvents>)!
} else {
let d = SegmentedControlDynamic<UIControlEvents>(control: self)
objc_setAssociatedObject(self, &eventDynamicHandleUISegmentedControl, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<UIControlEvents> {
return self.dynEvent
}
public var designatedBond: Bond<UIControlEvents> {
return self.dynEvent.valueBond
}
}
public func ->> (left: UISegmentedControl, right: Bond<UIControlEvents>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UISegmentedControl, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == UIControlEvents>(left: T, right: UISegmentedControl) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<UIControlEvents>, right: UISegmentedControl) {
left ->> right.designatedBond
}
| mit |
blue42u/swift-t | stc/tests/920-wait-1.swift | 4 | 190 |
import assert;
main {
int x = f(0);
int y = f(1);
wait(x, y, f(3)) {
trace(x + y);
assertEqual(x + y, 3, "x+y");
}
}
(int r) f (int x) {
r = x + 1;
}
| apache-2.0 |
Mindera/Alicerce | Tests/AlicerceTests/View/CollectionReusableViewSizerTestCase.swift | 1 | 9427 | import XCTest
@testable import Alicerce
final class CollectionReusableViewSizerTestCase: XCTestCase {
private var reusableViewSizer: CollectionReusableViewSizer<MockSizerReusableView>!
private var cellSizer: CollectionReusableViewSizer<MockSizerCell>!
// MARK: - Setup
override func setUp() {
super.setUp()
reusableViewSizer = CollectionReusableViewSizer()
cellSizer = CollectionReusableViewSizer()
}
override func tearDown() {
reusableViewSizer = nil
cellSizer = nil
super.tearDown()
}
// MARK: - Tests
// MARK: ReusableView
func testSizer_WithReusableViewAndNoConstraints_ShouldReturnZeroSize() {
let viewModel = MockSizerViewModel()
let size = reusableViewSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 0, height: 0))
}
func testSizer_WithReusableViewAndWidthConstraint_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
return [widthConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = reusableViewSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 100, height: 0))
}
func testSizer_WithReusableViewAndBothConstraints_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = reusableViewSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 100, height: 200))
}
func testSizer_WithReusableViewAndFixedDimension_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 50)
widthConstraint.priority = .defaultHigh
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = reusableViewSizer.sizeFor(viewModel: viewModel, width: .fixed(100))
XCTAssertEqual(size, CGSize(width: 100, height: 200))
}
// MARK: Cell
func testSizer_WithCellAndNoConstraints_ShouldReturnZeroSize() {
let viewModel = MockSizerViewModel()
let size = cellSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 0, height: 0))
}
func testSizer_WithCellAndWidthConstraint_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
return [widthConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = cellSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 100, height: 0))
}
func testSizer_WithCellAndBothConstraints_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = cellSizer.sizeFor(viewModel: viewModel)
XCTAssertEqual(size, CGSize(width: 100, height: 200))
}
func testSizer_WithCellAndFixedDimension_ShouldReturnCorrectSize() {
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 50)
widthConstraint.priority = .defaultHigh
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel = MockSizerViewModel(constraints: constraints)
let size = cellSizer.sizeFor(viewModel: viewModel, width: .fixed(100))
XCTAssertEqual(size, CGSize(width: 100, height: 200))
}
// MARK: Cache
func testSizerCache_WithSameKey_ShouldReturnCachedSize() {
let sizerCache = CollectionReusableViewSizerCache<MockSizerReusableView>()
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel1 = MockSizerViewModel(constraints: constraints, cacheKey: "🔑")
let size1 = sizerCache.sizeFor(viewModel: viewModel1)
XCTAssertEqual(size1, CGSize(width: 100, height: 200))
let viewModel2 = MockSizerViewModel(cacheKey: "🗝")
let size2 = sizerCache.sizeFor(viewModel: viewModel2)
XCTAssertEqual(size2, CGSize(width: 0, height: 0))
let viewModel3 = MockSizerViewModel(cacheKey: "🔑")
let size3 = sizerCache.sizeFor(viewModel: viewModel3)
XCTAssertEqual(size3, CGSize(width: 100, height: 200))
}
// MARK: Cache Group
func testSizerCacheGroup_WithSameView_ShouldReturnCachedSizes() {
let sizerCacheGroup = CollectionReusableViewSizerCacheGroup()
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel1 = MockSizerViewModel(constraints: constraints, cacheKey: "🔑")
let size1 = sizerCacheGroup.sizeFor(MockSizerReusableView.self, viewModel: viewModel1)
XCTAssertEqual(size1, CGSize(width: 100, height: 200))
let viewModel2 = MockSizerViewModel(cacheKey: "🔑")
let size2 = sizerCacheGroup.sizeFor(MockSizerReusableView.self, viewModel: viewModel2)
XCTAssertEqual(size2, CGSize(width: 100, height: 200))
}
func testSizerCacheGroup_WithDifferentViews_ShouldReturnCalculatedSizes() {
let sizerCacheGroup = CollectionReusableViewSizerCacheGroup()
let constraints: MockSizerViewModel.ConstraintClosure = { view in
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 200)
return [widthConstraint, heightConstraint]
}
let viewModel1 = MockSizerViewModel(constraints: constraints, cacheKey: "🔑")
let size1 = sizerCacheGroup.sizeFor(MockSizerReusableView.self, viewModel: viewModel1)
XCTAssertEqual(size1, CGSize(width: 100, height: 200))
let viewModel2 = MockSizerViewModel(cacheKey: "🔑")
let size2 = sizerCacheGroup.sizeFor(MockSizerCell.self, viewModel: viewModel2)
XCTAssertEqual(size2, CGSize(width: 0, height: 0))
}
}
// MARK: - Mock Sizer ViewModel & Views
private final class MockSizerViewModel {
typealias ConstraintClosure = (UIView) -> [NSLayoutConstraint]
let constraints: ConstraintClosure?
let cacheKey: String?
init(constraints: ConstraintClosure? = nil, cacheKey: String? = nil) {
self.constraints = constraints
self.cacheKey = cacheKey
}
}
private protocol MockSizerViewModelView: SizerViewModelView where ViewModel == MockSizerViewModel {}
private extension MockSizerViewModelView {
static func sizerCacheKeyFor(viewModel: ViewModel) -> String? { return viewModel.cacheKey }
}
private final class MockSizerReusableView: UICollectionReusableView, ReusableViewModelView, MockSizerViewModelView {
var viewModel: MockSizerViewModel? {
didSet { setUpBindings() }
}
private var _constraints: [NSLayoutConstraint] = []
func setUpSubviews() {}
func setUpConstraints() {}
func setUpBindings() {
guard let viewModel = viewModel else { return }
NSLayoutConstraint.deactivate(_constraints)
_constraints = viewModel.constraints?(self) ?? []
NSLayoutConstraint.activate(_constraints)
}
override func prepareForReuse() { viewModel = nil }
}
private final class MockSizerCell: UICollectionViewCell, ReusableViewModelView, MockSizerViewModelView {
var viewModel: MockSizerViewModel? {
didSet { setUpBindings() }
}
private var _constraints: [NSLayoutConstraint] = []
func setUpSubviews() {}
func setUpConstraints() {}
func setUpBindings() {
guard let viewModel = viewModel else { return }
NSLayoutConstraint.deactivate(_constraints)
_constraints = viewModel.constraints?(contentView) ?? []
NSLayoutConstraint.activate(_constraints)
}
override func prepareForReuse() { viewModel = nil }
}
| mit |
massaentertainment/MECarouselView | CarouselScrollView/MECarouselView+ScrollViewDelegate.swift | 1 | 1814 |
//
// CarouselScrollView+ScrollViewDelegate.swift
// CarouselScrollView
//
// Created by Gabriel Bezerra Valério on 12/06/17.
// Copyright © 2017 bepiducb. All rights reserved.
//
import UIKit
extension MECarouselView : UIScrollViewDelegate {
private func visibleViews() -> [UIView] {
var visibleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.bounds.size)
let scale = 1.0 / scrollView.zoomScale
visibleRect.origin.x *= scale
visibleRect.origin.y *= scale
visibleRect.size.width *= scale
visibleRect.size.height *= scale
var visibleViews:[UIView] = []
for view in stackView.subviews where view.frame.intersects(visibleRect) {
visibleViews.append(view)
}
return visibleViews
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollCenter = scrollView.frame.size.width / 2
let offset = scrollView.contentOffset.x
let visibleViews = self.visibleViews()
for view in visibleViews {
let normalizedCenter = view.center.x - offset
let maxDistance = view.frame.size.width + stackView.spacing
let distance = min(abs(scrollCenter - normalizedCenter), maxDistance)
let ratio = (maxDistance - distance) / maxDistance
let scale = ratio * (1 - self.standardItemScale) + self.standardItemScale
view.layer.transform = CATransform3DScale(CATransform3DIdentity, scale, scale, 1.0)
view.layer.zPosition = 10 * scale
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.delegate?.carouselView?(self, DidSnapTo: actualIndex)
}
}
| mit |
TwoRingSoft/shared-utils | Sources/PippinLibrary/Foundation/String/String+CSV.swift | 1 | 835 | //
// String+CSV.swift
// Pippin
//
// Created by Andrew McKnight on 1/8/19.
//
import Foundation
public typealias CSVRow = [String]
public typealias CSV = [CSVRow]
public extension String {
/// Split a String containing a CSV file's contents and split it into a 2-dimensional array of Strings, representing each row and its column fields.
var csv: CSV {
let rowComponents = split(separator: "\r\n").map({ (substring) -> String in
return String(substring)
})
let valueRows = Array(rowComponents[1..<rowComponents.count]) // return all but header row
let valueRowComponents: [CSVRow] = valueRows.map({ (row) -> [String] in
let result = Array(row.split(separator: ",")).map({String($0)})
return result
})
return valueRowComponents
}
}
| mit |
Appletone/RubySwift | RubySwift/RubySwiftString.swift | 1 | 565 | //
// RubySwiftString.swift
// RubySwift
//
// Created by Appletone on 2014/7/16.
// Copyright (c) 2014年 Appletone. All rights reserved.
//
import Foundation
extension String {
// computed properties
var capitalized: String {
return capitalizedString
}
var downcase: String {
return lowercaseString
}
var upcase: String {
return uppercaseString
}
// functions
mutating func downcase$() -> String {
self = self.lowercaseString
return self
}
}
| mit |
natecook1000/swift | test/SILGen/witnesses_class.swift | 1 | 5353 |
// RUN: %target-swift-emit-silgen -module-name witnesses_class -enable-sil-ownership %s | %FileCheck %s
protocol Fooable: class {
func foo()
static func bar()
init()
}
class Foo: Fooable {
func foo() { }
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW
// CHECK-NOT: function_ref
// CHECK: class_method
class func bar() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FZTW
// CHECK-NOT: function_ref
// CHECK: class_method
required init() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP{{[_0-9a-zA-Z]*}}fCTW
// CHECK-NOT: function_ref
// CHECK: class_method
}
// CHECK-LABEL: sil hidden @$S15witnesses_class3genyyxAA7FooableRzlF
// CHECK: bb0([[SELF:%.*]] : @guaranteed $T)
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $T
// CHECK: apply [[METHOD]]<T>([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func gen<T: Fooable>(_ foo: T) {
foo.foo()
}
// CHECK-LABEL: sil hidden @$S15witnesses_class2exyyAA7Fooable_pF
// CHECK: bb0([[SELF:%[0-0]+]] : @guaranteed $Fooable):
// CHECK: [[SELF_PROJ:%.*]] = open_existential_ref [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Fooable]],
// CHECK-NOT: copy_value [[SELF_PROJ]] : $
// CHECK: apply [[METHOD]]<[[OPENED]]>([[SELF_PROJ]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func ex(_ foo: Fooable) {
foo.foo()
}
// Default implementations in a protocol extension
protocol HasDefaults {
associatedtype T = Self
func hasDefault()
func hasDefaultTakesT(_: T)
func hasDefaultGeneric<U : Fooable>(_: U)
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U)
}
extension HasDefaults {
func hasDefault() {}
func hasDefaultTakesT(_: T) {}
func hasDefaultGeneric<U : Fooable>(_: U) {}
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U) {}
}
protocol Barable {}
class UsesDefaults<X : Barable> : HasDefaults {}
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP10hasDefaultyyFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable> (@in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE10hasDefaultyyF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP16hasDefaultTakesTyy1TQzFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable> (@in_guaranteed UsesDefaults<τ_0_0>, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE16hasDefaultTakesTyy1TQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0.T, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>>(
// CHECK: return
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP17hasDefaultGenericyyqd__AA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable><τ_2_0 where τ_2_0 : Fooable> (@guaranteed τ_2_0, @in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE17hasDefaultGenericyyqd__AA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_2_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed UsesDefaults<τ_0_0>, @guaranteed τ_1_0, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed τ_0_0.T, @guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>, τ_1_0>(
// CHECK: return
protocol ReturnsCovariantSelf {
func returnsCovariantSelf() -> Self
}
extension ReturnsCovariantSelf {
func returnsCovariantSelf() -> Self { return self }
}
class NonMatchingMember: ReturnsCovariantSelf {
func returnsCovariantSelf() {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class17NonMatchingMemberCAA20ReturnsCovariantSelfA2aDP07returnsgH0xyFTW : $@convention(witness_method: ReturnsCovariantSelf) <τ_0_0 where τ_0_0 : NonMatchingMember> (@in_guaranteed τ_0_0) -> @out τ_0_0 {
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.