repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
csontosgabor/Twitter_Post | Twitter_Post/VideoFetcher.swift | 1 | 3784 | //
// VideoFetcher.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/18/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import Foundation
import AVFoundation
import Photos
public typealias VideoFetcherSuccess = (URL) -> Void
public typealias VideoFetcherFailure = (NSError) -> Void
public class VideoFetcher {
private let errorDomain = "com.zero.singleImageSaver"
private var success: VideoFetcherSuccess?
private var failure: VideoFetcherFailure?
public init() { }
public func onSuccess(_ success: @escaping VideoFetcherSuccess) -> Self {
self.success = success
return self
}
public func onFailure(_ failure: @escaping VideoFetcherFailure) -> Self {
self.failure = failure
return self
}
public func fetch(_ localId: String) -> Self {
_ = PhotoLibraryAuthorizer { error in
if error == nil {
self._fetch(localId)
} else {
self.failure?(error!)
}
}
return self
}
private func _fetch(_ localId: String) {
let manager = PHImageManager()
let requestOptions = PHVideoRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [localId], options: nil)
guard let asset = assets.firstObject
else {
let error = errorWithKey("error.cant-fetch-video", domain: errorDomain)
failure?(error)
return
}
manager.requestAVAsset(forVideo: asset, options: nil) { (videoAsset, audioMix, info) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if let asset = videoAsset {
if asset.isKind(of: AVComposition.self) {
print("slow motion video to convert")
//compress video to be able to play
var converter = ConvertSlowMotionVideo()
.onSuccess { url in
self.success?(url)
}
.onFailure { error in
self.failure?(error)
}
converter = converter.convertSlowMotionVideo(asset)
return
} else if asset.isKind(of: AVURLAsset.self){
if let url = asset as? AVURLAsset {
self.success?(url.url)
} else {
let error = errorWithKey("error.cant-fetch-video", domain: self.errorDomain)
self.failure?(error)
}
} else {
print("unkown")
}
} else {
let error = errorWithKey("error.cant-fetch-video", domain: self.errorDomain)
self.failure?(error)
}
})
}
}
}
| mit | 64deb3fe708e0b5b256eada5f59135a1 | 30.525 | 108 | 0.41898 | 6.47774 | false | false | false | false |
rudkx/swift | test/Interop/Cxx/templates/template-type-parameter-not-in-signature.swift | 1 | 1922 | // RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop -Xfrontend -validate-tbd-against-ir=none)
//
// REQUIRES: executable_test
import TemplateTypeParameterNotInSignature
import StdlibUnittest
var TemplateNotInSignatureTestSuite = TestSuite("Template Type Parameters Not in Function Signature")
TemplateNotInSignatureTestSuite.test("Function with defaulted template type parameters") {
templateTypeParamNotUsedInSignature(T: Int.self)
multiTemplateTypeParamNotUsedInSignature(T: Float.self, U: Int.self)
let x: Int = multiTemplateTypeParamOneUsedInSignature(1, T: Int.self)
expectEqual(x, 1)
multiTemplateTypeParamNotUsedInSignatureWithUnrelatedParams(1, 1, T: Int32.self, U: Int.self)
let y: Int = templateTypeParamUsedInReturnType(10)
expectEqual(y, 10)
}
TemplateNotInSignatureTestSuite.test("Instanciate the same function template twice.") {
// Intentionally test the same thing twice.
templateTypeParamNotUsedInSignature(T: Int.self)
templateTypeParamNotUsedInSignature(T: Int.self)
}
TemplateNotInSignatureTestSuite.test("Pointer types") {
var x = 1
x = templateTypeParamUsedInReferenceParam(&x)
expectEqual(x, 1)
}
TemplateNotInSignatureTestSuite.test("Member function templates") {
let s = Struct()
s.templateTypeParamNotUsedInSignature(T: Int.self)
let x: Int = templateTypeParamUsedInReturnType(42)
expectEqual(x, 42)
}
TemplateNotInSignatureTestSuite.test("Member function templates (mutable)") {
var s = Struct()
s.templateTypeParamNotUsedInSignatureMutable(T: Int.self)
}
TemplateNotInSignatureTestSuite.test("Member function templates (static)") {
Struct.templateTypeParamNotUsedInSignatureStatic(T: Int.self)
}
TemplateNotInSignatureTestSuite.test("Type not used in signature and takes an inout parameter.") {
var x = 42
let out = templateTypeParamNotUsedInSignatureWithRef(&x, U: Int.self)
expectEqual(out, 42)
}
runAllTests()
| apache-2.0 | 5651e1658048084c2e85408f276db007 | 34.592593 | 118 | 0.792924 | 3.93047 | false | true | false | false |
rambler-digital-solutions/rambler-it-ios | Carthage/Checkouts/rides-ios-sdk/source/UberRides/DeeplinkRequestingBehavior.swift | 1 | 2472 | //
// DeeplinkRequestingBehavior.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// 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.
@objc(UBSDKDeeplinkRequestingBehavior) public class DeeplinkRequestingBehavior : NSObject, RideRequesting {
/**
Requests a ride using a RequestDeeplink that is constructed using the provided
rideParameters
- parameter rideParameters: The RideParameters to use for building and executing
the deeplink
*/
@objc public func requestRide(parameters rideParameters: RideParameters?) {
guard let rideParameters = rideParameters else {
return
}
let deeplink = createDeeplink(rideParameters: rideParameters)
let deeplinkCompletion: (NSError?) -> () = { error in
if let error = error, error.code != DeeplinkErrorType.deeplinkNotFollowed.rawValue {
self.createAppStoreDeeplink(rideParameters: rideParameters).execute(completion: nil)
}
}
deeplink.execute(completion: deeplinkCompletion)
}
func createDeeplink(rideParameters: RideParameters) -> RequestDeeplink {
return RequestDeeplink(rideParameters: rideParameters)
}
func createAppStoreDeeplink(rideParameters: RideParameters) -> Deeplinking {
return AppStoreDeeplink(userAgent: rideParameters.userAgent)
}
}
| mit | c25b9b0307c0fb02c41b31be9c6cd9e8 | 43.927273 | 107 | 0.720356 | 5.126556 | false | false | false | false |
ontouchstart/swift3-playground | Drawing Sounds.playgroundbook/Contents/Sources/Speech.swift | 1 | 2420 | //
// Speech.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import AVFoundation
/// A speech class that can speak various words and have filters and effects applied to the speech.
public class Speech: SoundProducer {
// MARK: Properties
private var _defaultVolume = ClampedInteger(clampedUserValueWithDefaultOf: 5)
public var defaultVolume: Int {
get { return _defaultVolume.clamped }
set { _defaultVolume.clamped = newValue }
}
var normalizedVolume: CGFloat {
return CGFloat(defaultVolume) / CGFloat(Constants.maxUserValue)
}
private var _defaultSpeed = ClampedInteger(clampedUserValueWithDefaultOf: 30)
public var defaultSpeed: Int {
get { return _defaultSpeed.clamped }
set { _defaultSpeed.clamped = newValue }
}
var normalizedSpeed: CGFloat {
return CGFloat(defaultSpeed) / CGFloat(Constants.maxUserValue)
}
private var _defaultPitch = ClampedInteger(clampedUserValueWithDefaultOf: 33)
public var defaultPitch: Int {
get { return _defaultPitch.clamped }
set { _defaultPitch.clamped = newValue }
}
var normalizedPitch: CGFloat {
return CGFloat(defaultPitch) / CGFloat(Constants.maxUserValue)
}
// If any effect is applied on touches across the X axis.
public var xEffect: SpeechTweak?
// MARK: Private Properties
private var speechWords: [String] = []
private var speechSynthesizer = AVSpeechSynthesizer()
// MARK: SoundProducer
public var noteCount: Int {
return speechWords.count
}
// MARK: Initializers
public init(words: String) {
self.speechWords = words.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
}
func word(forIndex index: Int) -> String? {
if index >= 0 && index < speechWords.count {
return speechWords[index]
}
return nil
}
func speak(_ text: String, rate: Float = 0.6, pitchMultiplier: Float = 1.0, volume: Float = 1.0) {
let utterance = AVSpeechUtterance(string: text)
utterance.rate = rate
utterance.volume = volume
utterance.pitchMultiplier = pitchMultiplier
speechSynthesizer.speak(utterance)
}
func stopSpeaking() {
speechSynthesizer.stopSpeaking(at: .word)
}
}
| mit | c24e2c177a18b745e3415818aad9662b | 28.156627 | 102 | 0.647521 | 4.583333 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/Gateway.swift | 1 | 2067 | /**
* (C) Copyright IBM Corp. 2019, 2020.
*
* 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
/**
Object describing a specific gateway.
*/
public struct Gateway: Codable, Equatable {
/**
The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway.
`idle` means this gateway is not currently in use.
*/
public enum Status: String {
case connected = "connected"
case idle = "idle"
}
/**
The gateway ID of the gateway.
*/
public var gatewayID: String?
/**
The user defined name of the gateway.
*/
public var name: String?
/**
The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway.
`idle` means this gateway is not currently in use.
*/
public var status: String?
/**
The generated **token** for this gateway. The value of this field is used when configuring the remotly installed
gateway.
*/
public var token: String?
/**
The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed
gateway.
*/
public var tokenID: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case gatewayID = "gateway_id"
case name = "name"
case status = "status"
case token = "token"
case tokenID = "token_id"
}
}
| apache-2.0 | f79824b24bf3a3d7fe8a2bf2ea78207d | 28.528571 | 120 | 0.665215 | 4.342437 | false | false | false | false |
alexcurylo/iso3166-flags-maps-worldheritage | masterlister/Masterlister/TWHS.swift | 1 | 6370 | // @copyright Trollwerks Inc.
import Foundation
import SWXMLHash
struct TWHS: Codable {
private let id_number: String?
private let iso_code: String?
private let site: String?
//private let submitted: String
//private let category: String
var name: String {
guard let site = site,
!site.isEmpty else {
assertionFailure("invalid name field")
return "<missing>"
}
return site
}
var siteId: Int {
guard let idString = id_number,
let id = Int(idString) else {
assertionFailure("invalid ID field")
return 0
}
return id
}
var countries: String {
guard let codes = iso_code,
!codes.isEmpty else {
assertionFailure(("no countries for \(siteId): \(name)"))
return ""
}
return codes
}
static var sitelist: [TWHS] = {
sitesFromHTML(file: "twhs")
}()
private static func sitesFromHTML(file: String) -> [TWHS] {
guard let path = Bundle.main.path(forResource: file, ofType: "html"),
let page = try? String(contentsOfFile: path) else {
assertionFailure("missing TWHS file: \(file).html")
return []
}
do {
let nsrange = NSRange(page.startIndex..<page.endIndex, in: page)
// <span > <a href="/en/tentativelists/6339/" >Qajartalik (13/04/2018)</a> Canada </span>
let linkPattern = #"lists\/(?<id>[0-9]+)\/"\s*>"#
let linkRegex = try NSRegularExpression(pattern: linkPattern, options: [])
let ids = linkRegex.matches(in: page, options: [], range: nsrange)
.map { page.substring(with: $0.range(withName: "id")) }
var sites: [TWHS] = []
// swiftlint:disable:next line_length
let pattern = #"lists\/(?<id>[0-9]+)\/"\s*>(?<site>.+)\s\([0-9\/]{10}\)<\/a>\s*(?<state>\S+.*\S)\s*<\/span>"#
let regex = try NSRegularExpression(pattern: pattern, options: [])
regex.enumerateMatches(in: page,
options: [],
range: nsrange) { match, _, _ in
guard let match = match else { return }
let site = TWHS(
id_number: page.substring(with: match.range(withName: "id")),
iso_code: Country.iso(for: page.substring(with: match.range(withName: "state"))),
site: page.substring(with: match.range(withName: "site"))
)
sites.append(site)
}
if ids.count != sites.count {
let diff = ids.difference(from: sites.map { $0.id_number })
assertionFailure("ids (\(ids.count)) != sites (\(sites.count)): \(diff)")
}
return sorted(sites: sites)
} catch {
assertionFailure("scraping TWHS failed")
}
return []
}
private static func sitesFromJSON(file: String) -> [TWHS] {
guard let path = Bundle.main.path(forResource: file, ofType: "json"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
assertionFailure("missing TWHS file: \(file).json")
return []
}
do {
let sites = try JSONDecoder().decode([TWHS].self, from: data)
return sorted(sites: sites)
} catch DecodingError.dataCorrupted(let context) {
print(context.debugDescription)
} catch DecodingError.keyNotFound(let key, let context) {
print("Key '\(key)' not Found")
print("Debug Description:", context.debugDescription)
} catch DecodingError.valueNotFound(let value, let context) {
print("Value '\(value)' not Found")
print("Debug Description:", context.debugDescription)
} catch DecodingError.typeMismatch(let type, let context) {
print("Type '\(type)' mismatch")
print("Debug Description:", context.debugDescription)
} catch {
print("error: ", error)
}
return []
}
private static func sitesFromXML(file: String) -> [TWHS] {
guard let path = Bundle.main.path(forResource: file, ofType: "xml"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
assertionFailure("missing TWHS file: \(file).xml")
return []
}
let xml = SWXMLHash.parse(data)
let document = xml["pkg:package"]["pkg:part"].all[2]
let documentName = document.element?.attribute(by: "pkg:name")?.text
assert(documentName == "/word/document.xml")
let body = document["pkg:xmlData"]["w:document"]["w:body"]
let rows = body["query"]["row"].all
assert(rows.count == 1_700, "1700 TWHS on 2019.08.01")
let sites: [TWHS] = rows.compactMap { TWHS(from: $0) }
return sorted(sites: sites)
}
private static func sorted(sites: [TWHS]) -> [TWHS] {
let sites = sites.sorted { lhs, rhs in
lhs.name < rhs.name
}
// Should match http://whc.unesco.org/en/tentativelists/
assert(sites.count == 1_700, "1700 TWHS on 2019.08.01")
return sites
}
init?(from xml: XMLIndexer) {
defer {
assert(!id_number.isNilOrEmpty, "Missing id")
assert(!site.isNilOrEmpty, "Missing name")
assert(!iso_code.isNilOrEmpty, "Missing iso")
}
id_number = xml["id"].element?.text
iso_code = xml["iso"].element?.text
site = xml["site"].element?.text
}
init(id_number: String?,
iso_code: String?,
site: String?) {
self.id_number = id_number
self.iso_code = iso_code
self.site = site
}
}
extension String {
func substring(with nsrange: NSRange) -> String? {
guard let range = Range(nsrange, in: self) else { return nil }
return String(self[range])
}
}
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.symmetricDifference(otherSet))
}
}
| mit | e5ec2c3a56826df337e5dced04012e20 | 33.432432 | 121 | 0.543171 | 4.243837 | false | false | false | false |
OrielBelzer/StepCoin | HDAugmentedRealityDemo/MapViewController.swift | 1 | 10414 | //
// MapViewController.swift
// StepCoin
//
// Created by Oriel Belzer on 11/07/16.
// Copyright (c) 2016 StepCoin. All rights reserved.
//
import UIKit
import CoreLocation
import Mapbox
import Haneke
import SwiftyJSON
class MapViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate
{
var updateTimer: Timer?
@IBOutlet var mapView: MGLMapView!
var coinsController = CoinsController()
let defaults = UserDefaults.standard
let cache = Shared.dataCache
var counter = 0
let locManager = CLLocationManager()
var lastTimeLocationWasSentToServer = Date()
var desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyThreeKilometers
override func viewDidLoad()
{
super.viewDidLoad()
locManager.delegate = self
// if (defaults.bool(forKey:"shouldReloadMapDelegateAgain"))
let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap))
mapView.addGestureRecognizer(singleTap)
sendLocationToServer()
defaults.set(false, forKey: "shouldReloadMapDelegateAgain")
// }
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//WORK AROUND - NEED TO FIX IT AT SOME POINT
mapView.delegate = nil
//mapView.removeFromSuperview()
// self.dismiss(animated: false, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadCoinsToMap(swLongitude: String(mapView.visibleCoordinateBounds.sw.longitude), swLatitude: String(mapView.visibleCoordinateBounds.sw.latitude), neLongitude: String(mapView.visibleCoordinateBounds.ne.longitude), neLatitude: String(mapView.visibleCoordinateBounds.ne.latitude))
//WORK AROUND - NEED TO FIX IT AT SOME POINT
mapView.delegate = self
mapView.userTrackingMode = .follow
/* Get configuration from server */
ConnectionController.sharedInstance.getConfiguration(userId: (defaults.value(forKey: "userId") as! String)) { (responseObject:SwiftyJSON.JSON, error:String) in
if (error == "") {
self.defaults.set(responseObject["collect_coins_visability_distance"].stringValue, forKey: "visabilityDistance")
self.defaults.set(responseObject["desiredAccuracy"].stringValue, forKey: "desiredAccuracy")
switch (self.defaults.value(forKey: "desiredAccuracy") as! String)
{
case "best":
self.desiredAccuracy = kCLLocationAccuracyBest
case "ten":
self.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
case "hundreds":
self.desiredAccuracy = kCLLocationAccuracyHundredMeters
case "kilometer":
self.desiredAccuracy = kCLLocationAccuracyKilometer
case "threeKilomoters":
self.desiredAccuracy = kCLLocationAccuracyThreeKilometers
default:
self.desiredAccuracy = kCLLocationAccuracyHundredMeters
}
self.sendLocationToServer()
} else {
print(error)
// self.desiredAccuracy = kCLLocationAccuracyHundredMeters
}
}
}
func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
loadCoinsToMap(swLongitude: String(mapView.visibleCoordinateBounds.sw.longitude), swLatitude: String(mapView.visibleCoordinateBounds.sw.latitude), neLongitude: String(mapView.visibleCoordinateBounds.ne.longitude), neLatitude: String(mapView.visibleCoordinateBounds.ne.latitude))
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
if (self.defaults.value(forKey: "gotFirstFreeCoin") == nil) {
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation: CLLocation
currentLocation = locManager.location!
let lat = currentLocation.coordinate.latitude // 37.241681
let lon = currentLocation.coordinate.longitude // -121.884804
ConnectionController.sharedInstance.addCoin(longitude: String(lon), latitude: String(lat)) { (responseObject:SwiftyJSON.JSON, error:String) in
if (error == "") {
} else {
print(error)
}
}
defaults.set(true, forKey: "gotFirstFreeCoin")
} else {
//Nothing - user should not get another coin
}
}
} else {
print("Location services are not enabled")
}
}
func loadCoinsToMap(swLongitude: String, swLatitude: String, neLongitude: String, neLatitude: String) {
print("---------------------------------")
print(mapView.visibleCoordinateBounds.ne.latitude)
print(mapView.visibleCoordinateBounds.ne.longitude)
print(mapView.visibleCoordinateBounds.sw.latitude)
print(mapView.visibleCoordinateBounds.sw.longitude)
print("---------------------------------")
coinsController.reloadCoinsFromServerBasedOnZoom(userId: self.defaults.value(forKey: "userId") as! String, swLongitude: swLongitude, swLatitude: swLatitude, neLongitude: neLongitude, neLatitude: neLatitude) { (responseObject:[AnyObject], error:String) in
if (error == "") {
StoreController().getStoresForCoins(coinsToGetStoresFor: (responseObject as? [Coin2])!)
self.addCoinsToMap(coinsToAddToMap: (responseObject as? [Coin2])!)
}
}
}
func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) {
}
func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: "CoinImage")
/* TODO -
1. To see if I can put the logo of the business as a coin instaed of the generic photo
2. See if I can group annotations in case there is more than 1 at the exact same location
*/
if annotationImage == nil {
var image = UIImage(named: "CoinImage")!
image = image.withAlignmentRectInsets(UIEdgeInsetsMake(0, 0, image.size.height/2, 0))
annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: "CoinImage")
}
return annotationImage
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
private func addCoinsToMap(coinsToAddToMap: [Coin2]) {
if (self.mapView.annotations != nil) {
self.mapView.removeAnnotations(self.mapView.annotations!)
}
for coin in coinsToAddToMap {
let point = MGLPointAnnotation()
point.coordinate = CLLocationCoordinate2D(latitude: Double((coin.location?.latitude)!)!, longitude: Double((coin.location?.longitude)!)!)
Shared.dataCache.fetch(key: "stores").onSuccess { data in
if let stores = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Store] {
for store in stores {
if store.id == coin.storeId {
point.title = "$"+coin.value! + " at " + store.name!
self.mapView.addAnnotation(point)
break
}
}
}
}
}
}
func handleSingleTap(tap: UITapGestureRecognizer) {
if (self.defaults.value(forKey: "debugMode") != nil) {
if (self.defaults.bool(forKey: "debugMode")) {
let location: CLLocationCoordinate2D = mapView.convert(tap.location(in: mapView), toCoordinateFrom: mapView)
print("You tapped at: \(location.latitude), \(location.longitude)")
ConnectionController.sharedInstance.addCoin(longitude: String(location.longitude), latitude: String(location.latitude)) { (responseObject:SwiftyJSON.JSON, error:String) in
if (error == "") {
} else {
print(error)
}
}
}
}
}
func sendLocationToServer() {
locManager.requestAlwaysAuthorization()
//var currentLocation: CLLocation
let currentLocation = locManager.location
if (currentLocation != nil) {
// currentLocation = try locManager.location!
locManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locManager.distanceFilter = 100
locManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
counter = counter + 1
print("in updated location " + String(counter))
let currentDateTime = Date()
if (minutesBetweenDates(startDate: lastTimeLocationWasSentToServer, endDate: currentDateTime) >= 1) {
let location:CLLocation = locations[locations.count-1] as CLLocation
UserController().sendLocationToServer(userId: defaults.value(forKey: "userId") as! String, latitude: String(location.coordinate.latitude), longitude: String(location.coordinate.longitude))
lastTimeLocationWasSentToServer = currentDateTime
}
}
func minutesBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.minute], from: startDate, to: endDate)
return components.minute!
}
}
| mit | 7ceaf50e512fc629b6f21776c51a375a | 43.314894 | 286 | 0.610332 | 5.533475 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/User/EditProfileRequestSpec.swift | 1 | 2007 | //
// EditProfileRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class EditProfileRequestSpec: QuickSpec {
override func spec() {
describe("EditProfileRequest") {
it("Should have proper method") {
let request = EditProfileRequest(identifier: "", data: EditProfileData())
expect(request.method) == RequestMethod.put
}
it("Should have `users/IDENTIFIER/account` endpoint") {
let identifier = "TestUserIdentifier"
let request = EditProfileRequest(identifier: identifier, data: EditProfileData())
expect(request.endpoint) == "users/\(identifier)/account"
}
it("Should parse parameters properly") {
//TODO
}
}
}
}
| mit | a05c6c790da314cbced1053d4ccc715a | 39.959184 | 97 | 0.684106 | 4.722353 | false | false | false | false |
darrinhenein/firefox-ios | Client/Frontend/Home/HistoryPanel.swift | 1 | 5725 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
private func getDate(#dayOffset: Int) -> NSDate {
let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let nowComponents = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: NSDate())
let today = calendar.dateFromComponents(nowComponents)!
return calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: dayOffset, toDate: today, options: nil)!
}
class HistoryPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
private let NumSections = 4
private let Today = getDate(dayOffset: 0)
private let Yesterday = getDate(dayOffset: -1)
private let ThisWeek = getDate(dayOffset: -7)
private var sectionOffsets = [Int: Int]()
override func reloadData() {
let opts = QueryOptions()
opts.sort = .LastVisit
profile.history.get(opts, complete: { (data: Cursor) -> Void in
self.sectionOffsets = [Int: Int]()
self.data = data
self.tableView.reloadData()
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
let offset = sectionOffsets[indexPath.section]!
if let site = data[indexPath.row + offset] as? Site {
cell.textLabel?.text = site.title
cell.detailTextLabel?.text = site.url
if let img = site.icon? {
let imgURL = NSURL(string: img.url)
cell.imageView?.sd_setImageWithURL(imgURL, placeholderImage: self.profile.favicons.defaultIcon)
} else {
cell.imageView?.image = self.profile.favicons.defaultIcon
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let offset = sectionOffsets[indexPath.section]!
if let site = data[indexPath.row + offset] as? Site {
if let url = NSURL(string: site.url) {
homePanelDelegate?.homePanel(self, didSelectURL: url)
return
}
}
println("Could not click on history row")
}
// Functions that deal with showing header rows
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumSections
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return NSLocalizedString("Today", comment: "")
case 1: return NSLocalizedString("Yesterday", comment: "")
case 2: return NSLocalizedString("Last week", comment: "")
case 3: return NSLocalizedString("Last month", comment: "")
default:
assertionFailure("Invalid history section \(section)")
}
}
private func isInSection(date: NSDate, section: Int) -> Bool {
let now = NSDate()
switch section {
case 0:
return date.timeIntervalSince1970 > Today.timeIntervalSince1970
case 1:
return date.timeIntervalSince1970 > Yesterday.timeIntervalSince1970
case 2:
return date.timeIntervalSince1970 > ThisWeek.timeIntervalSince1970
default:
return true
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let current = sectionOffsets[section] {
if let next = sectionOffsets[section+1] {
if current == next {
// If this points to the same element as the next one, it's empty. Don't show it.
return 0
}
}
} else {
// This may not be filled in yet (for instance, if the number of rows in data is zero). If it is,
// just return zero.
return 0
}
// Return the default height for header rows
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let size = sectionOffsets[section] {
if let nextSize = sectionOffsets[section+1] {
return nextSize - size
}
}
var searchingSection = 0
sectionOffsets[searchingSection] = 0
// Loop over all the data. Record the start of each "section" of our list.
for i in 0..<data.count {
if let site = data[i] as? Site {
if !isInSection(site.latestVisit!.date, section: searchingSection) {
searchingSection++
sectionOffsets[searchingSection] = i
}
if searchingSection == NumSections {
break
}
}
}
// Now fill in any sections that weren't found with data.count.
// Note, we actually fill in one past the end of the list to make finding the length
// of a section easier.
searchingSection++
for i in searchingSection...NumSections {
sectionOffsets[i] = data.count
}
// This function wants the size of a section, so return the distance between two adjacent ones
return sectionOffsets[section+1]! - sectionOffsets[section]!
}
}
| mpl-2.0 | f0f3ac32ae4057d563570a1c49337eb7 | 37.682432 | 164 | 0.621485 | 5.05742 | false | false | false | false |
tehprofessor/SwiftyFORM | Source/Cells/SimpleToolbar.swift | 1 | 2698 | // MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
public class SimpleToolbar: UIToolbar {
public var jumpToPrevious: Void -> Void = {}
public var jumpToNext: Void -> Void = {}
public var dismissKeyboard: Void -> Void = {}
public init() {
super.init(frame: CGRectZero)
self.backgroundColor = UIColor.whiteColor()
self.items = self.toolbarItems()
self.autoresizingMask = [.FlexibleWidth, .FlexibleHeight, .FlexibleBottomMargin, .FlexibleTopMargin]
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public lazy var previousButton: UIBarButtonItem = {
let image = UIImage(named: "SwiftFORMArrowLeft", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)
if let image = image {
let image2 = image.imageWithRenderingMode(.AlwaysTemplate)
return UIBarButtonItem(image: image2, style: .Plain, target: self, action: "previousButtonAction:")
}
return UIBarButtonItem(title: "<<", style: .Plain, target: self, action: "previousButtonAction:")
}()
public lazy var nextButton: UIBarButtonItem = {
let image = UIImage(named: "SwiftFORMArrowRight", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)
if let image = image {
let image2 = image.imageWithRenderingMode(.AlwaysTemplate)
return UIBarButtonItem(image: image2, style: .Plain, target: self, action: "nextButtonAction:")
}
return UIBarButtonItem(title: ">>", style: .Plain, target: self, action: "nextButtonAction:")
}()
public lazy var closeButton: UIBarButtonItem = {
let item = UIBarButtonItem(title: "OK", style: .Plain, target: self, action: "closeButtonAction:")
return item
}()
public func toolbarItems() -> [UIBarButtonItem] {
let spacer0 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
spacer0.width = 15.0
let spacer1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var items = [UIBarButtonItem]()
items.append(previousButton)
items.append(spacer0)
items.append(nextButton)
items.append(spacer1)
items.append(closeButton)
return items
}
public func previousButtonAction(sender: UIBarButtonItem!) {
jumpToPrevious()
}
public func nextButtonAction(sender: UIBarButtonItem!) {
jumpToNext()
}
public func closeButtonAction(sender: UIBarButtonItem!) {
dismissKeyboard()
}
public func updateButtonConfiguration(cell: UITableViewCell) {
previousButton.enabled = cell.form_canMakePreviousCellFirstResponder()
nextButton.enabled = cell.form_canMakeNextCellFirstResponder()
}
}
| mit | 8d89548fd4f578545e44e1f9f9ce5160 | 35.459459 | 135 | 0.747961 | 4.157165 | false | false | false | false |
AlexLittlejohn/ALCameraViewController | Example/ViewController.swift | 1 | 2231 | //
// ViewController.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/17.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var minimumSize: CGSize = CGSize(width: 60, height: 60)
var croppingParameters: CroppingParameters {
return CroppingParameters(isEnabled: croppingSwitch.isOn, allowResizing: resizableSwitch.isOn, allowMoving: movableSwitch.isOn, minimumSize: minimumSize)
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var croppingParametersView: UIView!
@IBOutlet weak var minimumSizeLabel: UILabel!
@IBOutlet weak var librarySwitch: UISwitch!
@IBOutlet weak var croppingSwitch: UISwitch!
@IBOutlet weak var resizableSwitch: UISwitch!
@IBOutlet weak var movableSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.contentMode = .scaleAspectFit
croppingParametersView.isHidden = !croppingSwitch.isOn
}
@IBAction func openCamera(_ sender: Any) {
let cameraViewController = CameraViewController(croppingParameters: croppingParameters, allowsLibraryAccess: librarySwitch.isOn) { [weak self] image, asset in
self?.imageView.image = image
self?.dismiss(animated: true, completion: nil)
}
present(cameraViewController, animated: true, completion: nil)
}
@IBAction func openLibrary(_ sender: Any) {
let libraryViewController = CameraViewController.imagePickerViewController(croppingParameters: croppingParameters) { [weak self] image, asset in
self?.imageView.image = image
self?.dismiss(animated: true, completion: nil)
}
present(libraryViewController, animated: true, completion: nil)
}
@IBAction func croppingChanged(_ sender: UISwitch) {
croppingParametersView.isHidden = !sender.isOn
}
@IBAction func minimumSizeChanged(_ sender: UISlider) {
let newValue = sender.value
minimumSize = CGSize(width: CGFloat(newValue), height: CGFloat(newValue))
minimumSizeLabel.text = "Minimum size: \(newValue.rounded())"
}
}
| mit | 76d8cda5612b6fa6aaefaddaf73bef80 | 34.983871 | 166 | 0.6961 | 4.860566 | false | false | false | false |
easykoo/Sidebar | SideBar/RootViewController.swift | 1 | 3292 | //
// RootController.swift
// SideBar
//
// Created by Steven on 10/11/14.
// Copyright (c) 2014 Steven. All rights reserved.
//
import UIKit
public enum MenuState: Int {
case Opened
case Closed
}
protocol MenuDelegate {
func openMenu()
func closeMenu()
}
var menuState:MenuState = MenuState.Closed
class RootViewController: UIViewController, MenuDelegate {
var mainController:UINavigationController!
var leftController:UIViewController!
var tapRecognizer:UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
var storyboard = UIStoryboard(name: "Main", bundle: nil)
mainController = storyboard.instantiateViewControllerWithIdentifier("MainController") as UINavigationController
(mainController.viewControllers[0] as MainController).delegate = self
leftController = storyboard.instantiateViewControllerWithIdentifier("LeftController") as UIViewController
self.view.addSubview(mainController.view)
mainController.view.frame = self.view.bounds
mainController.view.layer.shadowRadius = 10.0
mainController.view.layer.shadowOpacity = 0.8
self.view.addSubview(leftController.view)
leftController.view.frame = self.view.bounds
self.view.bringSubviewToFront(mainController.view)
var panGesture = UIPanGestureRecognizer(target: self, action: Selector("pan:"))
self.mainController.view.addGestureRecognizer(panGesture)
self.tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("closeMenu"))
}
func pan(panGesture:UIPanGestureRecognizer) {
switch panGesture.state {
case .Changed:
var point = panGesture.translationInView(self.view)
if point.x > 0 || panGesture.view!.center.x > self.view.center.x {
panGesture.view?.center = CGPointMake(panGesture.view!.center.x + point.x, panGesture.view!.center.y)
panGesture.setTranslation(CGPointMake(0, 0), inView: self.view)
}
case .Ended, .Failed:
if mainController.view.frame.origin.x > self.view.frame.origin.x + 100{
openMenu()
} else {
closeMenu()
}
default:
break
}
}
func openMenu() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
mainController.view.frame = CGRectMake(200, mainController.view.frame.origin.y, mainController.view.frame.size.width, mainController.view.frame.size.height)
UIView.commitAnimations()
menuState = MenuState.Opened
mainController.view.addGestureRecognizer(self.tapRecognizer!)
}
func closeMenu() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
mainController.view.frame = CGRectMake(0, mainController.view.frame.origin.y, mainController.view.frame.size.width, mainController.view.frame.size.height)
UIView.commitAnimations()
menuState = MenuState.Closed
mainController.view.removeGestureRecognizer(self.tapRecognizer!)
}
}
| apache-2.0 | a338ddf4c3447b55e23bd91f81336ba9 | 35.175824 | 164 | 0.673451 | 4.965309 | false | false | false | false |
adrfer/swift | stdlib/public/core/CompilerProtocols.swift | 2 | 8463 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that represents a Boolean value.
///
/// Types that conform to the `BooleanType` protocol can be used as
/// the condition in control statements (`if`, `while`, C-style `for`)
/// and other logical value contexts (e.g., `case` statement guards).
///
/// Only three types provided by Swift, `Bool`, `DarwinBoolean`, and `ObjCBool`,
/// conform to `BooleanType`. Expanding this set to include types that
/// represent more than simple boolean values is discouraged.
public protocol BooleanType {
/// The value of `self`, expressed as a `Bool`.
var boolValue: Bool { get }
}
/// A type that can be converted to an associated "raw" type, then
/// converted back to produce an instance equivalent to the original.
public protocol RawRepresentable {
/// The "raw" type that can be used to represent all values of `Self`.
///
/// Every distinct value of `self` has a corresponding unique
/// value of `RawValue`, but `RawValue` may have representations
/// that do not correspond to a value of `Self`.
associatedtype RawValue
/// Convert from a value of `RawValue`, yielding `nil` iff
/// `rawValue` does not correspond to a value of `Self`.
init?(rawValue: RawValue)
/// The corresponding value of the "raw" type.
///
/// `Self(rawValue: self.rawValue)!` is equivalent to `self`.
var rawValue: RawValue { get }
}
/// Returns `true` iff `lhs.rawValue == rhs.rawValue`.
@warn_unused_result
public func == <
T : RawRepresentable where T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// Returns `true` iff `lhs.rawValue != rhs.rawValue`.
@warn_unused_result
public func != <
T : RawRepresentable where T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T : Equatable
/// Returns `true` iff `lhs.rawValue != rhs.rawValue`.
@warn_unused_result
public func != <
T : Equatable where T : RawRepresentable, T.RawValue : Equatable
>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue != rhs.rawValue
}
/// Conforming types can be initialized with `nil`.
public protocol NilLiteralConvertible {
/// Create an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _BuiltinIntegerLiteralConvertible {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
/// Conforming types can be initialized with integer literals.
public protocol IntegerLiteralConvertible {
associatedtype IntegerLiteralType : _BuiltinIntegerLiteralConvertible
/// Create an instance initialized to `value`.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _BuiltinFloatLiteralConvertible {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// Conforming types can be initialized with floating point literals.
public protocol FloatLiteralConvertible {
associatedtype FloatLiteralType : _BuiltinFloatLiteralConvertible
/// Create an instance initialized to `value`.
init(floatLiteral value: FloatLiteralType)
}
public protocol _BuiltinBooleanLiteralConvertible {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// Conforming types can be initialized with the Boolean literals
/// `true` and `false`.
public protocol BooleanLiteralConvertible {
associatedtype BooleanLiteralType : _BuiltinBooleanLiteralConvertible
/// Create an instance initialized to `value`.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _BuiltinUnicodeScalarLiteralConvertible {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// Conforming types can be initialized with string literals
/// containing a single [Unicode scalar value](http://www.unicode.org/glossary/#unicode_scalar_value).
public protocol UnicodeScalarLiteralConvertible {
associatedtype UnicodeScalarLiteralType : _BuiltinUnicodeScalarLiteralConvertible
/// Create an instance initialized to `value`.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _BuiltinExtendedGraphemeClusterLiteralConvertible
: _BuiltinUnicodeScalarLiteralConvertible {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
byteSize: Builtin.Word,
isASCII: Builtin.Int1)
}
/// Conforming types can be initialized with string literals
/// containing a single [Unicode extended grapheme cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster).
public protocol ExtendedGraphemeClusterLiteralConvertible
: UnicodeScalarLiteralConvertible {
associatedtype ExtendedGraphemeClusterLiteralType
: _BuiltinExtendedGraphemeClusterLiteralConvertible
/// Create an instance initialized to `value`.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
public protocol _BuiltinStringLiteralConvertible
: _BuiltinExtendedGraphemeClusterLiteralConvertible {
init(
_builtinStringLiteral start: Builtin.RawPointer,
byteSize: Builtin.Word,
isASCII: Builtin.Int1)
}
public protocol _BuiltinUTF16StringLiteralConvertible
: _BuiltinStringLiteralConvertible {
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
numberOfCodeUnits: Builtin.Word)
}
/// Conforming types can be initialized with arbitrary string literals.
public protocol StringLiteralConvertible
: ExtendedGraphemeClusterLiteralConvertible {
// FIXME: when we have default function implementations in protocols, provide
// an implementation of init(extendedGraphemeClusterLiteral:).
associatedtype StringLiteralType : _BuiltinStringLiteralConvertible
/// Create an instance initialized to `value`.
init(stringLiteral value: StringLiteralType)
}
/// Conforming types can be initialized with array literals.
public protocol ArrayLiteralConvertible {
associatedtype Element
/// Create an instance initialized with `elements`.
init(arrayLiteral elements: Element...)
}
/// Conforming types can be initialized with dictionary literals.
public protocol DictionaryLiteralConvertible {
associatedtype Key
associatedtype Value
/// Create an instance initialized with `elements`.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// Conforming types can be initialized with string interpolations
/// containing `\(`...`)` clauses.
public protocol StringInterpolationConvertible {
/// Create an instance by concatenating the elements of `strings`.
init(stringInterpolation strings: Self...)
/// Create an instance containing `expr`'s `print` representation.
init<T>(stringInterpolationSegment expr: T)
}
/// Conforming types can be initialized with color literals (e.g.
/// `[#Color(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)#]`).
public protocol _ColorLiteralConvertible {
init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)
}
/// Conforming types can be initialized with image literals (e.g.
/// `[#Image(imageLiteral: "hi.png")#]`).
public protocol _ImageLiteralConvertible {
init(imageLiteral: String)
}
/// Conforming types can be initialized with strings (e.g.
/// `[#FileReference(fileReferenceLiteral: "resource.txt")#]`).
public protocol _FileReferenceLiteralConvertible {
init(fileReferenceLiteral: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
public protocol _DestructorSafeContainer {
}
| apache-2.0 | a2414ef277e174874f4a6fdcca939fa6 | 36.281938 | 120 | 0.738981 | 5.0405 | false | false | false | false |
nextcloud/ios | iOSClient/Transfers/NCTransferCell.swift | 1 | 5588 | //
// NCTransferCell.swift
// Nextcloud
//
// Created by Marino Faggiana on 08/10/2020.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
class NCTransferCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProtocol {
@IBOutlet weak var imageItem: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelPath: UILabel!
@IBOutlet weak var labelStatus: UILabel!
@IBOutlet weak var labelInfo: UILabel!
@IBOutlet weak var imageMore: UIImageView!
@IBOutlet weak var buttonMore: UIButton!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
private var objectId = ""
private var user = ""
weak var delegate: NCTransferCellDelegate?
var indexPath = IndexPath()
var namedButtonMore = ""
var fileObjectId: String? {
get { return objectId }
set { objectId = newValue ?? "" }
}
var filePreviewImageView: UIImageView? {
get { return imageItem }
set { imageItem = newValue }
}
var fileUser: String? {
get { return user }
set { user = newValue ?? "" }
}
var fileTitleLabel: UILabel? {
get { return labelTitle }
set { labelTitle = newValue }
}
var fileInfoLabel: UILabel? {
get { return labelInfo }
set { labelInfo = newValue }
}
var fileProgressView: UIProgressView? {
get { return progressView }
set { progressView = newValue }
}
var fileMoreImage: UIImageView? {
get { return imageMore }
set { imageMore = newValue }
}
override func awakeFromNib() {
super.awakeFromNib()
isAccessibilityElement = true
imageItem.layer.cornerRadius = 6
imageItem.layer.masksToBounds = true
progressView.tintColor = NCBrandColor.shared.brandElement
progressView.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
progressView.trackTintColor = .clear
let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gestureRecognizer:)))
longPressedGesture.minimumPressDuration = 0.5
longPressedGesture.delegate = self
longPressedGesture.delaysTouchesBegan = true
self.addGestureRecognizer(longPressedGesture)
let longPressedGestureMore = UILongPressGestureRecognizer(target: self, action: #selector(longPressInsideMore(gestureRecognizer:)))
longPressedGestureMore.minimumPressDuration = 0.5
longPressedGestureMore.delegate = self
longPressedGestureMore.delaysTouchesBegan = true
buttonMore.addGestureRecognizer(longPressedGestureMore)
separator.backgroundColor = .separator
separatorHeightConstraint.constant = 0.5
labelTitle.text = ""
labelInfo.text = ""
}
override func prepareForReuse() {
super.prepareForReuse()
imageItem.backgroundColor = nil
}
@IBAction func touchUpInsideShare(_ sender: Any) {
delegate?.tapShareListItem(with: objectId, sender: sender)
}
@IBAction func touchUpInsideMore(_ sender: Any) {
delegate?.tapMoreListItem(with: objectId, namedButtonMore: namedButtonMore, image: imageItem.image, sender: sender)
}
@objc func longPressInsideMore(gestureRecognizer: UILongPressGestureRecognizer) {
delegate?.longPressMoreListItem(with: objectId, namedButtonMore: namedButtonMore, gestureRecognizer: gestureRecognizer)
}
@objc func longPress(gestureRecognizer: UILongPressGestureRecognizer) {
delegate?.longPressListItem(with: objectId, gestureRecognizer: gestureRecognizer)
}
func hideButtonMore(_ status: Bool) {
imageMore.isHidden = status
buttonMore.isHidden = status
}
func setButtonMore(named: String, image: UIImage) {
namedButtonMore = named
imageMore.image = image
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(
name: NSLocalizedString("_cancel_", comment: ""),
target: self,
selector: #selector(touchUpInsideMore))
]
}
func writeInfoDateSize(date: NSDate, size: Int64) {
labelInfo.text = CCUtility.dateDiff(date as Date) + " · " + CCUtility.transformedSize(size)
}
}
protocol NCTransferCellDelegate: AnyObject {
func tapShareListItem(with objectId: String, sender: Any)
func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any)
func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer)
func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer)
}
| gpl-3.0 | a5e86aefafb077839af913bb016d334a | 35.509804 | 139 | 0.69531 | 4.925926 | false | false | false | false |
gobetti/Swift | CoreDataSample2/CoreDataSample2/ViewController.swift | 1 | 2826 | //
// ViewController.swift
// CoreDataSample2
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var results: NSArray?
@IBOutlet weak var name: UITextField!
@IBOutlet weak var surname: UITextField!
@IBOutlet weak var table: UITableView!
@IBAction func save(sender: UIButton) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let cell = NSEntityDescription.insertNewObjectForEntityForName("Form", inManagedObjectContext: context)
cell.setValue(name.text, forKey: "name")
cell.setValue(surname.text, forKey: "surname")
// Save the context.
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
}
self.loadTable()
self.table.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadTable() //start load
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier: nil)
let aux = results![indexPath.row] as! NSManagedObject
cell.textLabel!.text = aux.valueForKey("name") as? String
cell.detailTextLabel!.text = aux.valueForKey("surname") as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results!.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Contacts"
}
func loadTable(){
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Form")
request.returnsObjectsAsFaults = false
results = try? context.executeFetchRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | c43168486d134a80abe046bd940d020c | 31.113636 | 190 | 0.651097 | 5.562992 | false | false | false | false |
cplaverty/KeitaiWaniKani | AlliCrab/UserScripts/UserScriptSupport.swift | 1 | 3609 | //
// SupportsUserScripts.swift
// AlliCrab
//
// Copyright © 2016 Chris Laverty. All rights reserved.
//
import os
import WebKit
import WaniKaniKit
protocol UserScriptSupport {
func injectScript(name: String)
func injectStyleSheet(name: String)
func injectBundledFontReferences()
func injectUserScripts(for: URL) -> Bool
}
extension UserScriptSupport {
func injectUserScripts(for url: URL) -> Bool {
os_log("Loading user scripts for %@", type: .info, url as NSURL)
var scriptsInjected = false
var bundledFontReferencesInjected = false
for script in UserScriptDefinitions.all where script.canBeInjected(toPageAt: url) {
if script.requiresFonts && !bundledFontReferencesInjected {
injectBundledFontReferences()
bundledFontReferencesInjected = true
}
script.inject(into: self)
scriptsInjected = true
}
return scriptsInjected
}
}
private let fonts = [
"ChihayaGothic": "chigfont.ttf",
"cinecaption": "cinecaption2.28.ttf",
"darts font": "dartsfont.ttf",
"FC-Flower": "fc_fl.ttf",
"HakusyuKaisyoExtraBold_kk": "hkgokukaikk.ttf",
"Hosofuwafont": "Hosohuwafont.ttf",
"Nchifont+": "n_chifont+.ttf",
"santyoume-font": "santyoume.otf"
]
// MARK: - WKWebView
protocol WebViewUserScriptSupport: UserScriptSupport, BundleResourceLoader {
var webView: WKWebView! { get }
}
extension WebViewUserScriptSupport {
func injectStyleSheet(name: String) {
os_log("Loading stylesheet %@", type: .debug, name + ".css")
let contents = loadBundleResource(name: name, withExtension: "css", javascriptEncode: true)
injectStyleSheet(title: "\(name).css", contents: contents)
}
func injectScript(name: String) {
os_log("Loading script %@", type: .debug, name + ".js")
let source = loadBundleResource(name: name, withExtension: "js", javascriptEncode: false)
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(script)
}
func injectBundledFontReferences() {
for (fontFamily, font) in fonts {
guard let path = Bundle.main.path(forResource: font, ofType: nil), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
continue
}
let isOpenType = font.hasSuffix("otf")
let mimeType = isOpenType ? "font/otf" : "font/ttf"
let fontFormat = isOpenType ? "opentype" : "truetype"
os_log("Adding %@", type: .debug, fontFamily)
let source = "@font-face { font-family: \"\(fontFamily)\"; src: url(data:\(mimeType);base64,\(data.base64EncodedString())) format(\"\(fontFormat)\"); }"
injectStyleSheet(title: "font: \(fontFamily)", contents: source)
}
}
private func injectStyleSheet(title: String, contents: String) {
let source = """
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.appendChild(document.createTextNode('\(contents)'));
document.head.appendChild(document.createComment('\(title)'));
document.head.appendChild(style);
"""
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(script)
}
}
| mit | 5c03de9314013359a494f5b76556fb90 | 34.722772 | 164 | 0.634978 | 4.315789 | false | false | false | false |
ochococo/Design-Patterns-In-Swift | Design-Patterns-CN.playground/Pages/Structural.xcplaygroundpage/Contents.swift | 2 | 9028 | /*:
结构型模式(Structural)
====================
> 在软件工程中结构型模式是设计模式,借由一以贯之的方式来了解元件间的关系,以简化设计。
>
>**来源:** [维基百科](https://zh.wikipedia.org/wiki/%E7%B5%90%E6%A7%8B%E5%9E%8B%E6%A8%A1%E5%BC%8F)
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
/*:
🔌 适配器(Adapter)
--------------
适配器模式有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
### 示例:
*/
protocol NewDeathStarSuperLaserAiming {
var angleV: Double { get }
var angleH: Double { get }
}
/*:
**被适配者**
*/
struct OldDeathStarSuperlaserTarget {
let angleHorizontal: Float
let angleVertical: Float
init(angleHorizontal: Float, angleVertical: Float) {
self.angleHorizontal = angleHorizontal
self.angleVertical = angleVertical
}
}
/*:
**适配器**
*/
struct NewDeathStarSuperlaserTarget: NewDeathStarSuperLaserAiming {
private let target: OldDeathStarSuperlaserTarget
var angleV: Double {
return Double(target.angleVertical)
}
var angleH: Double {
return Double(target.angleHorizontal)
}
init(_ target: OldDeathStarSuperlaserTarget) {
self.target = target
}
}
/*:
### 用法
*/
let target = OldDeathStarSuperlaserTarget(angleHorizontal: 14.0, angleVertical: 12.0)
let newFormat = NewDeathStarSuperlaserTarget(target)
newFormat.angleH
newFormat.angleV
/*:
🌉 桥接(Bridge)
-----------
桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
### 示例:
*/
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
/*:
### 用法
*/
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()
/*:
🌿 组合(Composite)
--------------
将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
### 示例:
组件(Component)
*/
protocol Shape {
func draw(fillColor: String)
}
/*:
叶子节点(Leafs)
*/
final class Square: Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle: Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
/*:
组合
*/
final class Whiteboard: Shape {
private lazy var shapes = [Shape]()
init(_ shapes: Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
/*:
### 用法
*/
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")
/*:
🍧 修饰(Decorator)
--------------
修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。
就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。
### 示例:
*/
protocol CostHaving {
var cost: Double { get }
}
protocol IngredientsHaving {
var ingredients: [String] { get }
}
typealias BeverageDataHaving = CostHaving & IngredientsHaving
struct SimpleCoffee: BeverageDataHaving {
let cost: Double = 1.0
let ingredients = ["Water", "Coffee"]
}
protocol BeverageHaving: BeverageDataHaving {
var beverage: BeverageDataHaving { get }
}
struct Milk: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Milk"]
}
}
struct WhipCoffee: BeverageHaving {
let beverage: BeverageDataHaving
var cost: Double {
return beverage.cost + 0.5
}
var ingredients: [String] {
return beverage.ingredients + ["Whip"]
}
}
/*:
### 用法
*/
var someCoffee: BeverageDataHaving = SimpleCoffee()
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = Milk(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
someCoffee = WhipCoffee(beverage: someCoffee)
print("Cost: \(someCoffee.cost); Ingredients: \(someCoffee.ingredients)")
/*:
🎁 外观(Facade)
-----------
外观模式为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
### 示例:
*/
final class Defaults {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
subscript(key: String) -> String? {
get {
return defaults.string(forKey: key)
}
set {
defaults.set(newValue, forKey: key)
}
}
}
/*:
### 用法
*/
let storage = Defaults()
// Store
storage["Bishop"] = "Disconnect me. I’d rather be nothing"
// Read
storage["Bishop"]
/*:
🍃 享元(Flyweight)
--------------
使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。
### 示例:
*/
// 特指咖啡生成的对象会是享元
struct SpecialityCoffee {
let origin: String
}
protocol CoffeeSearching {
func search(origin: String) -> SpecialityCoffee?
}
// 菜单充当特制咖啡享元对象的工厂和缓存
final class Menu: CoffeeSearching {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func search(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private let menu: CoffeeSearching
init(menu: CoffeeSearching) {
self.menu = menu
}
func takeOrder(origin: String, table: Int) {
orders[table] = menu.search(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
/*:
### 用法
*/
let coffeeShop = CoffeeShop(menu: Menu())
coffeeShop.takeOrder(origin: "Yirgacheffe, Ethiopia", table: 1)
coffeeShop.takeOrder(origin: "Buziraguhindwa, Burundi", table: 3)
coffeeShop.serve()
/*:
☔ 保护代理模式(Protection Proxy)
------------------
在代理模式中,创建一个类代表另一个底层类的功能。
保护代理用于限制访问。
### 示例:
*/
protocol DoorOpening {
func open(doors: String) -> String
}
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "pass" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
/*:
### 用法
*/
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
computer.open(doors: podBay)
computer.authenticate(password: "pass")
computer.open(doors: podBay)
/*:
🍬 虚拟代理(Virtual Proxy)
----------------
在代理模式中,创建一个类代表另一个底层类的功能。
虚拟代理用于对象的需时加载。
### 示例:
*/
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
/*:
### 用法
*/
let humanInterface = HEVSuitHumanInterface()
humanInterface.administerMorphine()
| gpl-3.0 | f82c615e4c21a3391780f6424a36b6b8 | 18.128395 | 95 | 0.649025 | 3.221206 | false | false | false | false |
ObserveSocial/Focus | Sources/BeFalse.swift | 1 | 1087 | //
// BeFalse.swift
// FocusPackageDescription
//
// Created by Sam Meech-Ward on 2018-01-14.
//
import Foundation
public extension Beable where ItemType: ExpressibleByBooleanLiteral {
/**
Compare any boolean to the value `false`
`item == false`
- parameter message: The message to be output if the comparison fails.
- parameter file: The file that this method was called from.
- parameter line: The line number that this method was called from.
*/
public func `false`(_ message: String = "Expected false", file: StaticString = #file, line: UInt = #line, method: String = #function) {
guard let item = item as? Bool else {
self.fail(message, file: file, line: line, method: method, evaluation: "Item \(self.item) is not a boolean value")
return
}
guard item == false else {
self.fail(message, file: file, line: line, method: method, evaluation: "Item \(self.item) is not false")
return
}
self.pass(message, file: file, line: line, method: method, evaluation: "Item \(self.item) is false")
}
}
| mit | 88b2672b958682443fcdcd1857f15dfa | 30.057143 | 137 | 0.661454 | 3.896057 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/01236-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 1 | 1938 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<g>() -> (g, g -> g) -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
}
class d: f{ class func i {}
func a(b: Int = 0) {
}
let c = a
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
}
}
}
protocol a : a {
}
protocol a {
}
class b: a {
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
protocol A {
}
struct B<T : A> {
}
protocol C {
}
struct D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
func ^(a: Boolean, Bool) -> Bool {
}
protocol A {
}
struct B : A {
}
struct C<D, E: A where D.C == E> {
}
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
}
class a {
}
class c {
func b((Any, c))(a: (Any, AnyObject)) {
}
}
func f() {
}
class A: A {
}
class B : C {
}
protocol A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
protocol A {
}
class B {
func d() -> String {
}
}
class C: B, A {
override func d() -> String {
}
func c() -> String {
}
}
func e<T where T: A, T: B>(t: T) {
}
protocol A {
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
var f1: Int -> Int = {
}
let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in
}(x1, f1)
let crashes: Int = { x, f in
}(x1, f1)
func c<d {
enum c {
}
}
protocol b {
}
struct c {
func e() {
}
struct c<d : Sequence> {
}
func a<d>() -> [c<d>] {
}
func a(b: Int = 0) {
}
func c<d {
enum c {
}
}
func ^(a: Boolean, Bool) -> Bool {
}
protocol a {
for (mx : T?) in xs {
rth): \(g())" }
}
func a<T>() {
enum b {
}
}
}
}
struct e : d {
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
protocol b {
}
struct c {
func e() {
}
}
enum S<T> {
}
struct c<d : Sequence> {
}
func a<d>() -> [c<d>] {
| apache-2.0 | 71605afb8529a01c246d2bc1437d4b63 | 11.584416 | 87 | 0.508772 | 2.189831 | false | false | false | false |
yuezaixz/UPillow | UPillow/Classes/ViewCotrollers/DFUViewController.swift | 1 | 12378 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import CoreBluetooth
import iOSDFULibrary
class DFUViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, DFUServiceDelegate, DFUProgressDelegate, LoggerDelegate {
/// The UUID of the experimental Buttonless DFU Service from SDK 12.
/// This service is not advertised so the app needs to connect to check if it's on the device's attribute list.
static var dfuServiceUUID = CBUUID(string: "00001530-1212-EFDE-1523-785FEABCD123")
//MARK: - Class Properties
var centralManager : CBCentralManager?
var dfuPeripheral : CBPeripheral?
var scanningStarted : Bool = false
var isOverOrTimeout : Bool = false
fileprivate var dfuController : DFUServiceController?
fileprivate var selectedFirmware : DFUFirmware?
fileprivate var selectedFileURL : URL?
//MARK: - View Outlets
@IBOutlet weak var dfuActivityIndicator : UIActivityIndicatorView!
@IBOutlet weak var dfuStatusLabel : UILabel!
@IBOutlet weak var peripheralNameLabel : UILabel!
@IBOutlet weak var dfuUploadProgressView : UIProgressView!
@IBOutlet weak var dfuUploadStatus : UILabel!
@IBOutlet weak var stopProcessButton : UIButton!
//MARK: - View Actions
@IBAction func actionBack(_ sender: Any) { self.navigationController?.popViewController(animated: true)
if isOverOrTimeout {
self.dismiss(animated: true, completion: {
})
} else {
self.noticeError("升级中", autoClear: true, autoClearTime: 2)
}
}
@IBAction func stopProcessButtonTapped(_ sender: AnyObject) {
guard dfuController != nil else {
print("No DFU peripheral was set")
return
}
guard !dfuController!.aborted else {
stopProcessButton.setTitle("Stop process", for: .normal)
dfuController!.restart()
return
}
print("Action: DFU paused")
dfuController!.pause()
let alertView = UIAlertController(title: "Warning", message: "Are you sure you want to stop the process?", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "Abort", style: .destructive) {
(action) in
print("Action: DFU aborted")
_ = self.dfuController!.abort()
})
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel) {
(action) in
print("Action: DFU resumed")
self.dfuController!.resume()
})
present(alertView, animated: true)
}
//MARK: - Class Implementation
func startDiscovery() {
if !scanningStarted {
scanningStarted = true
print("Start discovery")
// the legacy and secure DFU UUIDs are advertised by devices in DFU mode,
// the device info service is in the adv packet of DFU_HRM sample and the Experimental Buttonless DFU from SDK 12
centralManager!.delegate = self
centralManager!.scanForPeripherals(withServices: [
DFUViewController.dfuServiceUUID])
dfuStatusLabel.text = "搜索中..."
performAfterDelay(sec: 15, handler: {
if self.scanningStarted {
self.stopDiscovery()
self.noticeError("升级失败", autoClear: true, autoClearTime: 2)
self.dismiss(animated: true, completion: nil)
}
})
}
}
func stopDiscovery() {
if scanningStarted {
print("stop discovery")
scanningStarted = false
centralManager!.stopScan()
}
}
func getBundledFirmwareURLHelper() -> URL? {
return Bundle.main.url(forResource: "ZT_S130_H801", withExtension: "zip")!
}
func startDFUProcess() {
guard dfuPeripheral != nil else {
print("No DFU peripheral was set")
return
}
let dfuInitiator = DFUServiceInitiator(centralManager: centralManager!, target: dfuPeripheral!)
dfuInitiator.delegate = self
dfuInitiator.progressDelegate = self
dfuInitiator.logger = self
//不设置默认是12,没升级完成就会断开。
// dfuInitiator.packetReceiptNotificationParameter = 1
// This enables the experimental Buttonless DFU feature from SDK 12.
// Please, read the field documentation before use.
dfuInitiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = true
dfuController = dfuInitiator.with(firmware: selectedFirmware!).start()
}
//MARK: - UIViewController implementation
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
centralManager = CBCentralManager(delegate: self, queue: nil) // The delegate must be set in init in order to work on iOS 8
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if centralManager!.state == .poweredOn {
startDiscovery()
}
}
func connectDfuPeripheral() {
peripheralNameLabel.text = "升级中 \((dfuPeripheral?.name)!)..."
dfuActivityIndicator.startAnimating()
dfuUploadProgressView.progress = 0.0
dfuUploadStatus.text = ""
dfuStatusLabel.text = ""
stopProcessButton.isEnabled = false
selectedFileURL = getBundledFirmwareURLHelper()
if selectedFileURL != nil {
selectedFirmware = DFUFirmware(urlToZipFile: selectedFileURL!)
startDFUProcess()
} else {
centralManager!.delegate = self
centralManager!.connect(dfuPeripheral!)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
_ = dfuController?.abort()
dfuController = nil
}
//MARK: - CBCentralManagerDelegate API
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("CentralManager is now powered on")
startDiscovery()
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// Ignore dupliactes.
// They will not be reported in a single scan, as we scan without CBCentralManagerScanOptionAllowDuplicatesKey flag,
// but after returning from DFU view another scan will be started.
if advertisementData[CBAdvertisementDataServiceUUIDsKey] != nil {
let name = peripheral.name ?? "Unknown"
let legacyUUIDString = DFUViewController.dfuServiceUUID.uuidString
let advertisedUUIDstring = ((advertisementData[CBAdvertisementDataServiceUUIDsKey]!) as AnyObject).firstObject as! CBUUID
if advertisedUUIDstring.uuidString == legacyUUIDString {
print("Found dfu Peripheral: \(name)")
dfuPeripheral = peripheral
connectDfuPeripheral()
stopDiscovery()
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
let name = peripheral.name ?? "Unknown"
print("Connected to peripheral: \(name)")
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
let name = peripheral.name ?? "Unknown"
print("Disconnected from peripheral: \(name)")
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
selectedFileURL = getBundledFirmwareURLHelper()
selectedFirmware = DFUFirmware(urlToZipFile: selectedFileURL!)
startDFUProcess()
}
//MARK: - DFUServiceDelegate
func dfuStateDidChange(to state: DFUState) {
switch state {
case .completed, .disconnecting:
self.dfuActivityIndicator.stopAnimating()
self.dfuUploadProgressView.setProgress(0, animated: true)
self.stopProcessButton.isEnabled = false
isOverOrTimeout = true
case .aborted:
self.dfuActivityIndicator.stopAnimating()
self.dfuUploadProgressView.setProgress(0, animated: true)
self.stopProcessButton.setTitle("Restart", for: .normal)
self.stopProcessButton.isEnabled = true
default:
self.stopProcessButton.isEnabled = true
}
dfuStatusLabel.text = state.zhDescription()
print("Changed state to: \(state.description())")
// Forget the controller when DFU is done
if state == .completed {
dfuController = nil
}
}
func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
dfuStatusLabel.text = "错误 \(error.rawValue): \(message)"
dfuActivityIndicator.stopAnimating()
dfuUploadProgressView.setProgress(0, animated: true)
print("Error \(error.rawValue): \(message)")
// Forget the controller when DFU finished with an error
dfuController = nil
}
//MARK: - DFUProgressDelegate
func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
dfuUploadProgressView.setProgress(Float(progress)/100.0, animated: true)
dfuUploadStatus.text = String(format: "进度: %d/%d\n速度: %.1f KB/s\n平均速度: %.1f KB/s",
part, totalParts, currentSpeedBytesPerSecond/1024, avgSpeedBytesPerSecond/1024)
}
//MARK: - LoggerDelegate
func logWith(_ level: LogLevel, message: String) {
print("\(level.name()): \(message)")
}
}
extension DFUState {
public func zhDescription() -> String {
switch self {
case .connecting: return "连接中"
case .starting: return "开始"
case .enablingDfuMode: return "激活升级模式"
case .uploading: return "传输中"
case .validating: return "验证中" // this state occurs only in Legacy DFU
case .disconnecting: return "断开中"
case .completed: return "已完成"
case .aborted: return "中止"
}
}
}
| gpl-3.0 | ec634783d97c310503b5b37bf112af29 | 39.556291 | 155 | 0.643615 | 5.176669 | false | false | false | false |
jordane-quincy/M2_DevMobileIos | JSONProject/Demo/ResultatPersonTableView.swift | 1 | 3428 | //
// ResultatPersonTableView.swift
// Demo
//
// Created by MAC ISTV on 10/05/2017.
// Copyright © 2017 UVHC. All rights reserved.
//
import UIKit
class ResultatPersonTableView: UITableViewController {
var realmServices = RealmServices()
var customNavigationController: UINavigationController? = nil
var affiliates: Array<Person> = Array<Person>()
public func setupNavigationController(navigationController: UINavigationController){
self.customNavigationController = navigationController
}
public func setupAffiliates(affiliates: Array<Person>) {
self.affiliates = affiliates
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Liste affiliés"
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
}
override func willMove(toParentViewController: UIViewController?)
{
if (toParentViewController == nil) {
// Back to parent
self.customNavigationController?.setNavigationBarHidden(true, animated: true)
}
}
override func viewDidAppear(_ animated: Bool) {
//self.refreshServicesArray()
//self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.affiliates.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell
let row = indexPath.row
cell.textLabel?.text = self.affiliates[row].getDefaultFirstAndLastName(index: row)
return cell
}
override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .normal, title: "Supprimer") { action, index in
print("delete button tapped")
print(self.affiliates[editActionsForRowAt.row])
// Delete BusinessService from DataBase
self.realmServices.deleteSubcriber(id: self.affiliates[editActionsForRowAt.row].id)
// Refresh 'services' variable
//self.refreshServicesArray()
// Delete Row in TableView
self.affiliates.remove(at: editActionsForRowAt.row)
tableView.deleteRows(at: [editActionsForRowAt], with: .automatic)
}
delete.backgroundColor = .red
return [delete]
}
// method when we tap on a cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("tap on cell \(indexPath.row)")
// go to the detail of the person
let resultatPersonDetails = ResultatPersonDetails(nibName: "ResultatPersonDetails", bundle: nil)
resultatPersonDetails.setupAffiliate(affiliate: self.affiliates[indexPath.row])
resultatPersonDetails.setupNavigationController(navigationController: self.customNavigationController!)
self.customNavigationController?.pushViewController(resultatPersonDetails, animated: true)
}
}
| mit | 821984f0515bccfa8b6e1eebb63dc1c7 | 35.063158 | 114 | 0.66871 | 5.113433 | false | false | false | false |
jingkecn/WatchWorker | src/ios/JSCore/Workers/SharedWatchWorker.swift | 1 | 776 | //
// SharedWatchWorker.swift
// WTVJavaScriptCore
//
// Created by Jing KE on 30/07/16.
// Copyright © 2016 WizTiVi. All rights reserved.
//
import Foundation
class SharedWatchWorker: SharedWorker{
override func run() {
print("==================== [\(self.className)] Start running shared watch worker ====================")
SharedWatchWorkerGlobalScope.runWorker(self)
print("==================== [\(self.className)] End running shared watch worker ====================")
}
}
extension SharedWatchWorker {
override class func create(context: ScriptContext, scriptURL: String, name: String = "") -> SharedWatchWorker {
return SharedWatchWorker(context: context, scriptURL: scriptURL, name: name)
}
} | mit | a83f781686ae2cf89c8d61d1edb9f026 | 27.740741 | 115 | 0.607742 | 4.454023 | false | false | false | false |
yonasstephen/swift-of-airbnb | frameworks/airbnb-datepicker/airbnb-datepicker/AirbnbDatePickerFooter.swift | 2 | 1909 | //
// AirbnbDatePickerFooter.swift
// airbnb-datepicker
//
// Created by Yonas Stephen on 24/2/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
protocol AirbnbDatePickerFooterDelegate {
func didSave()
}
class AirbnbDatePickerFooter: UIView {
var delegate: AirbnbDatePickerFooterDelegate?
var isSaveEnabled: Bool? {
didSet {
if let enabled = isSaveEnabled, enabled {
saveButton.isEnabled = true
saveButton.alpha = 1
} else {
saveButton.isEnabled = false
saveButton.alpha = 0.5
}
}
}
lazy var saveButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.backgroundColor = Theme.SECONDARY_COLOR
btn.setTitleColor(UIColor.white, for: .normal)
btn.setTitle("Save", for: .normal)
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
btn.addTarget(self, action: #selector(AirbnbDatePickerFooter.handleSave), for: .touchUpInside)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = Theme.PRIMARY_COLOR
addSubview(saveButton)
saveButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
saveButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
saveButton.heightAnchor.constraint(equalTo: heightAnchor, constant: -20).isActive = true
saveButton.widthAnchor.constraint(equalTo: widthAnchor, constant: -30).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func handleSave() {
if let del = delegate {
del.didSave()
}
}
}
| mit | a008187f2ead889660d8e4b67a08e83c | 29.285714 | 102 | 0.62631 | 4.867347 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.CharacteristicValueTransitionControl.swift | 1 | 2183 | import Foundation
public extension AnyCharacteristic {
static func characteristicValueTransitionControl(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read, .write],
description: String? = "Characteristic Value Transition Control",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.characteristicValueTransitionControl(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func characteristicValueTransitionControl(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read, .write],
description: String? = "Characteristic Value Transition Control",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .characteristicValueTransitionControl,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | f9b6759fe2464d2a25167c241c78193f | 34.786885 | 74 | 0.601008 | 5.597436 | false | false | false | false |
michaelsabo/VisualFormatLanguageExample | VisualFormatLanguage/ViewController.swift | 1 | 3385 | //
// ViewController.swift
// VisualFormatLanguage
//
// Created by Mike Sabo on 11/19/15.
// Copyright © 2015 Mike Sabo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge.None
let label1 = UILabel()
label1.translatesAutoresizingMaskIntoConstraints = false
label1.backgroundColor = UIColor.lightGrayColor()
label1.text = "Tommy Boy"
let label2 = UILabel()
label2.translatesAutoresizingMaskIntoConstraints = false
label2.backgroundColor = UIColor.greenColor()
label2.text = "Anchorman"
let label3 = UILabel()
label3.translatesAutoresizingMaskIntoConstraints = false
label3.backgroundColor = UIColor.cyanColor()
label3.text = "Kindergarten Cop"
let label4 = UILabel()
label4.translatesAutoresizingMaskIntoConstraints = false
label4.backgroundColor = UIColor.orangeColor()
label4.text = "Goonies"
let label5 = UILabel()
label5.translatesAutoresizingMaskIntoConstraints = false
label5.backgroundColor = UIColor.cyanColor()
label5.text = "Ninja Turtles....Turtle Power"
view.addSubview(label1)
view.addSubview(label2)
view.addSubview(label3)
view.addSubview(label4)
view.addSubview(label5)
//Add the label to a dictionary with a unique key
// in this example i didnt have to explicility define the type of dictionary, aka String : UILabel
// but if i had a UIButton, XCode would change this type to String : UIView
let viewsDictionary = ["label1": label1, "label2": label2, "label3": label3, "label4": label4, "label5": label5]
// this will add a horizontal constraint for all the labels, except for 2 and 3
for label in viewsDictionary.keys {
if (label == "label2" || label == "label3") {
continue
}
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[\(label)]|", options: [], metrics: nil, views: viewsDictionary))
}
let halfScreenWidth = UIScreen.mainScreen().bounds.width/2
// here we define a horizontal constraint for labels 2 and 3 so that they appear next to each other
// the 999 is the constraint priority. It's set to 1000 by default. If autolayout had conflicting constraints it would throw an error
// in the debugger without changing the priority to 999
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[label2(width@999)]-[label3(label2)]|", options: [], metrics: ["width": halfScreenWidth], views: viewsDictionary))
// adding vertical constrains to the labels, except for label3
// we also define a padding at the bottom of greater than or equal to 20
// we define a height of 100 and apply it to label1
// we then tell VSL to use the same height constraints with the other labels by referencing label 1 in the
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label1(height@999)]-[label2(label1)]-[label4(label1)]-[label5(label1)]->=20-|", options: [], metrics: ["height": 100], views: viewsDictionary))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label1]-[label3(height@999)]-[label4]", options: [], metrics: ["height": 100], views: viewsDictionary))
}
}
| mit | 03517cea6c4732a2f3ab3be87ddb232b | 38.811765 | 219 | 0.706265 | 4.554509 | false | false | false | false |
Asura19/My30DaysOfSwift | ClearTableViewCell/ClearTableViewCell/GradientCell.swift | 2 | 1351 | //
// GradientCell.swift
// ClearTableViewCell
//
// Created by Phoenix on 2017/3/21.
// Copyright © 2017年 Wolkamo. All rights reserved.
//
import UIKit
class GradientCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
let gradientLayer = CAGradientLayer()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let color1 = UIColor(white: 1.0, alpha: 0.2).cgColor
let color2 = UIColor(white: 1.0, alpha: 0.1).cgColor
let color3 = UIColor.clear.cgColor
let color4 = UIColor(white: 0, alpha: 0.05).cgColor
gradientLayer.colors = [color1, color2, color3, color4]
gradientLayer.locations = [0.0, 0.04, 0.95, 1.0]
layer.insertSublayer(gradientLayer, at: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.gradientLayer.frame = self.bounds
}
}
| mit | aae90c368d880a3dd3dade61c015dad9 | 26.510204 | 74 | 0.636499 | 4.292994 | false | false | false | false |
MadAppGang/SmartLog | iOS/Watch Extension/Managers/SessionsManager.swift | 1 | 2356 | //
// SessionsManager.swift
// SmartLog
//
// Created by Dmytro Lisitsyn on 10/10/16.
// Copyright © 2016 MadAppGang. All rights reserved.
//
import Foundation
import CoreMotion
final class SessionsManager {
fileprivate let motionManager: CMMotionManager
fileprivate let connectivityService: ConnectivityService
fileprivate var currentSessionID = 0
fileprivate var accelerometerDataSamplesCount = 0
fileprivate var markersCount = 0
init(connectivityService: ConnectivityService) {
self.connectivityService = connectivityService
motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.1
}
}
extension SessionsManager: SessionsService {
func beginSession(activityType: ActivityType) throws {
guard motionManager.isAccelerometerAvailable else {
throw SessionsServiceError.accelerometerIsUnavailable
}
currentSessionID = Int(Date().timeIntervalSince1970)
connectivityService.sendActivityType(sessionID: currentSessionID, activityType: activityType.rawValue)
let operationQueue = OperationQueue()
operationQueue.qualityOfService = .utility
motionManager.startAccelerometerUpdates(to: operationQueue) { accelerometerData, error in
guard let accelerometerData = accelerometerData else { return }
self.accelerometerDataSamplesCount += 1
self.connectivityService.sendAccelerometerData(sessionID: self.currentSessionID, x: accelerometerData.acceleration.x, y: accelerometerData.acceleration.y, z: accelerometerData.acceleration.z, dateTaken: Date(timeIntervalSince1970: accelerometerData.timestamp))
}
}
func endSession() {
guard motionManager.isAccelerometerActive else { return }
motionManager.stopAccelerometerUpdates()
connectivityService.sendSessionFinished(sessionID: currentSessionID, accelerometerDataSamplesCount: accelerometerDataSamplesCount, markersCount: markersCount)
currentSessionID = 0
accelerometerDataSamplesCount = 0
markersCount = 0
}
func addMarker() {
markersCount += 1
connectivityService.sendMarker(sessionID: currentSessionID, dateAdded: Date())
}
}
| mit | 581483839bac0e02428630d728e1e508 | 34.681818 | 272 | 0.713376 | 5.688406 | false | false | false | false |
phimage/Arithmosophi | Samples/Parity.swift | 1 | 1972 | //
// Parity.swift
// Arithmosophi
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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 Arithmosophi
public enum Parity: IntegerLiteralType, Equatable, Addable, Substractable, Multiplicable {
case even, odd
public init(integerLiteral value: IntegerLiteralType) {
self = value % 2 == 0 ? .even : .odd
}
}
// MARK: Equatable
public func == (left: Parity, right: Parity) -> Bool {
switch (left, right) {
case (.even, .even), (.odd, .odd): return true
case (.even, .odd), (.odd, .even): return false
}
}
// MARK: Addable
public func + (left: Parity, right: Parity) -> Parity {
return left == right ? .even : .odd
}
// MARK: Substractable
public func - (left: Parity, right: Parity) -> Parity {
return left + right
}
// MARK: Multiplicable
public func * (left: Parity, right: Parity) -> Parity {
return left == .odd && right == .odd ? .odd : .even
}
| mit | b14c3bf0536bb310fdbc5416c227e93c | 31.327869 | 90 | 0.722617 | 4.00813 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/UITestsFoundation/Screens/Login/LoginPasswordScreen.swift | 1 | 1435 | import ScreenObject
import XCTest
// TODO: remove when unifiedAuth is permanent.
class LoginPasswordScreen: ScreenObject {
let passwordTextFieldGetter: (XCUIApplication) -> XCUIElement = {
$0.secureTextFields["Password"]
}
init(app: XCUIApplication = XCUIApplication()) throws {
try super.init(
expectedElementGetters: [passwordTextFieldGetter],
app: app,
waitTimeout: 7
)
}
func proceedWith(password: String) throws -> LoginEpilogueScreen {
_ = tryProceed(password: password)
return try LoginEpilogueScreen()
}
func tryProceed(password: String) -> LoginPasswordScreen {
let passwordTextField = passwordTextFieldGetter(app)
passwordTextField.tap()
passwordTextField.typeText(password)
let loginButton = app.buttons["Password next Button"]
loginButton.tap()
if loginButton.exists && !loginButton.isHittable {
XCTAssertEqual(loginButton.waitFor(predicateString: "isEnabled == true"), .completed)
}
return self
}
func verifyLoginError() -> LoginPasswordScreen {
let errorLabel = app.staticTexts["pswdErrorLabel"]
_ = errorLabel.waitForExistence(timeout: 2)
XCTAssertTrue(errorLabel.exists)
return self
}
static func isLoaded() -> Bool {
(try? LoginPasswordScreen().isLoaded) ?? false
}
}
| gpl-2.0 | afba9c7811c3e7859e616069a3f46309 | 28.285714 | 97 | 0.652265 | 5.070671 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBACheckmarkView.swift | 1 | 4875 | //
// SBACheckmarkView.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
class SBACheckmarkView: UIView {
func drawCheckmarkAnimated(_ animated:Bool) {
guard animated else {
_shapeLayer.strokeEnd = 1
return
}
let timing = CAMediaTimingFunction(controlPoints: 0.180739998817444, 0, 0.577960014343262, 0.918200016021729)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.timingFunction = timing
animation.fillMode = kCAFillModeBoth
animation.fromValue = 0
animation.toValue = 1
animation.duration = 0.3
_shapeLayer.strokeEnd = 0
_shapeLayer.add(animation, forKey: "strokeEnd")
}
fileprivate var _shapeLayer: CAShapeLayer!
fileprivate var _tickViewSize: CGFloat!
static let defaultSize: CGFloat = 122
init() {
let tickViewSize = SBACheckmarkView.defaultSize
let frame = CGRect(x: 0, y: 0, width: tickViewSize, height: tickViewSize)
super.init(frame: frame)
_tickViewSize = tickViewSize
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
_tickViewSize = min(frame.size.width, frame.size.height)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
_tickViewSize = min(self.bounds.size.width, self.bounds.size.height)
commonInit()
}
fileprivate func commonInit() {
self.layer.cornerRadius = _tickViewSize / 2;
self.backgroundColor = UIColor.greenTintColor
let ratio = _tickViewSize / SBACheckmarkView.defaultSize
let path = UIBezierPath()
path.move(to: CGPoint(x: ratio * 37, y: ratio * 65))
path.addLine(to: CGPoint(x: ratio * 50, y: ratio * 78))
path.addLine(to: CGPoint(x: ratio * 87, y: ratio * 42))
path.lineCapStyle = CGLineCap.round
path.lineWidth = min(max(1, ratio * 5), 5)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.lineWidth = path.lineWidth
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.frame = self.layer.bounds
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.backgroundColor = UIColor.clear.cgColor
shapeLayer.fillColor = nil
shapeLayer.strokeEnd = 0
self.layer.addSublayer(shapeLayer);
_shapeLayer = shapeLayer;
self.translatesAutoresizingMaskIntoConstraints = false
self.accessibilityTraits |= UIAccessibilityTraitImage
self.isAccessibilityElement = true
}
override func layoutSubviews() {
super.layoutSubviews()
_shapeLayer.frame = self.layer.bounds;
}
override var intrinsicContentSize : CGSize {
return CGSize(width: _tickViewSize, height: _tickViewSize)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return intrinsicContentSize
}
}
| bsd-3-clause | a317c709b33b029864f268cc7cf05117 | 35.103704 | 117 | 0.679729 | 4.825743 | false | false | false | false |
exyte/Macaw | Example-macOS/Example-macOS/Examples/Easing/EasingView.swift | 1 | 1192 | import Macaw
class EasingView: MacawView {
var mAnimations = [Animation]()
var circlesNodes = [Group]()
var animation: Animation!
required init?(coder aDecoder: NSCoder) {
let centerX = 250.0
let fromStroke = Stroke(fill: Color.black, width: 3)
let all = [Easing.ease, Easing.easeIn, Easing.easeOut, Easing.easeInOut, Easing.elasticInOut]
let titles = ["Easing", "Easy In", "Easy Out", "Easy In Out", "Elastic In Out"]
for (index, easing) in all.enumerated() {
let y = Double(80 + index * 80)
let titleText = Text(text: titles[index], align: .mid, place: .move(dx: centerX, dy: y - 45))
let fromCircle = Circle(cx: centerX - 100, cy: y, r: 20).stroke(with: fromStroke)
let toPlace = fromCircle.place.move(dx: 200, dy: 0)
let toAnimation = fromCircle.placeVar.animation(to: toPlace).easing(easing)
mAnimations.append([toAnimation.autoreversed()].sequence())
circlesNodes.append(Group(contents: [titleText]))
circlesNodes.append(Group(contents: [fromCircle]))
}
animation = mAnimations.combine().cycle()
super.init(node: circlesNodes.group(), coder: aDecoder)
}
}
| mit | a2dd661b6e47502501672efe33aca802 | 36.25 | 99 | 0.651846 | 3.748428 | false | false | false | false |
AgentFeeble/pgoapi | pgoapi/Classes/Data/ApiResponseDataConverter.swift | 1 | 1880 | //
// ApiResponseDataConverter.swift
// pgoapi
//
// Created by Rayman Rosevear on 2016/07/29.
// Copyright © 2016 MC. All rights reserved.
//
import Foundation
import ProtocolBuffers
struct ApiResponseDataConverter: DataConverter
{
typealias OutputType = ApiResponse
typealias SubResponseConverter = ProtoBufDataConverter<GeneratedMessage>
struct Builder
{
private var subResponseConverters: [(ApiResponse.RequestType, SubResponseConverter)] = []
mutating func addSubResponseConverter(_ type: ApiResponse.RequestType, converter: SubResponseConverter)
{
subResponseConverters.append((type, converter))
}
func build() -> ApiResponseDataConverter
{
return ApiResponseDataConverter(subResponseConverters: subResponseConverters)
}
}
private let subResponseConverters: [(ApiResponse.RequestType, SubResponseConverter)]
func convert(_ data: Data) throws -> ApiResponse
{
let response = try Pogoprotos.Networking.Envelopes.ResponseEnvelope.parseFrom(data: data)
let subresponses = try parseSubResponses(response)
return ApiResponse(response: response, subresponses: subresponses)
}
private func parseSubResponses(_ response: Pogoprotos.Networking.Envelopes.ResponseEnvelope) throws -> [ApiResponse.RequestType : GeneratedMessage]
{
let subresponseCount = min(subResponseConverters.count, response.returns.count)
var subresponses: [ApiResponse.RequestType : GeneratedMessage] = [:]
for (idx, subresponseData) in response.returns[ 0..<subresponseCount ].enumerated()
{
let (requestType, converter) = subResponseConverters[idx]
subresponses[requestType] = try converter.convert(subresponseData)
}
return subresponses
}
}
| apache-2.0 | af5fc30c601cf18483e2670b1149d80d | 35.134615 | 151 | 0.69984 | 4.99734 | false | false | false | false |
nessBautista/iOSBackup | iOSNotebook/iOSNotebook/Rx/UI Examples/MultiCellViewModel.swift | 1 | 4266 | //
// MultiCellViewModel.swift
// iOSNotebook
//
// Created by Néstor Hernández Bautista on 7/24/18.
// Copyright © 2018 Néstor Hernández Bautista. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
//FIRST: you will need to create a special data struct to hand on Rx so it can do its magic:
//Also, the incidentDashboard struct is kind of messy, there is a lot of different data types being
//displayed at one Screen (and different service convergin, like the confluence of rivers)
//This makes a perfect candidate for Rx
struct TableSection
{
var header: String
var sectionData: Any
var items: [Any]
var isCollapsed:Bool
var sectionType:GlobaldDashboardSectionType
init(header: String, items:[Any], sectionData: Any, sectionType: GlobaldDashboardSectionType = .generalInfo){
self.header = header
self.items = items
self.isCollapsed = true
self.sectionData = sectionData
self.sectionType = sectionType
}
}
extension TableSection: SectionModelType
{
init(original: TableSection, items: [Any])
{
self = original
self.items = items
}
}
//You'll need for types of items, one for each section:
/*
1) Header section
2) The objectives
3) The Casualties
4) The progress
*/
enum GlobaldDashboardSectionType:Int {
case none = 0
case generalInfo
case objectives
case casualties
case progress
}
struct GlobalDashboardGeneralInfoSection {
var title = String()
var location = "Complicated things here: Donec condimentum pulvinar felis."
var casualties = 0
init(title: String = String()) {
self.title = title
}
}
struct GlobalDashboardObjectiveSection {
var title = String()
var location = "@Somewhere"
var casualties = 0
init(title: String = String()) {
self.title = title
}
}
struct GlobalDashboardCasualtiesSection {
var title = String()
var location = "@Somewhere"
var casualties = 0
init(title: String = String()) {
self.title = title
}
}
struct GlobalDashboardProgressSection {
var title = String()
var location = "@Somewhere"
var casualties = 0
init(title: String = String()) {
self.title = title
}
}
class MultiCellViewModel: NSObject
{
let disposeBag = DisposeBag()
//A Variable will be able to trigger table refresh
var data = BehaviorRelay<[TableSection]>(value: [TableSection]())
let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)
/*We only will have 4 section*/
func initData()
{
var sections:[TableSection] = []
for section in 0..<4
{
switch section
{
case 0:
let section = TableSection(header: "TIMELINE HEADER", items: ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum", String()], sectionData: GlobalDashboardGeneralInfoSection(title: "Incident short description"))
sections.append(section)
case 1:
let section = TableSection(header: "OBJECTIVES", items: ["Test1", "Test2"], sectionData: GlobalDashboardObjectiveSection())
sections.append(section)
case 2:
let section = TableSection(header: "CASUALTIES", items: ["Test1", "Test2"], sectionData: GlobalDashboardCasualtiesSection())
sections.append(section)
case 3:
let section = TableSection(header: "PROGRESS", items: ["Test1", "Test2"], sectionData: GlobalDashboardProgressSection())
sections.append(section)
default:
break
}
}
self.data.accept(sections)
}
}
| cc0-1.0 | 259130d899969a73bb617ffbd5383884 | 29.007042 | 623 | 0.646092 | 4.656831 | false | false | false | false |
codegeeker180/AVFonts | AVFonts/Classes/AVFonts.swift | 1 | 5051 | // * AVFonts.swift
// * AVFonts
// * Created by Arnav Gupta on 7/31/17.
// *Copyright © 2017 Arnav. All rights reserved.
import Foundation
import UIKit
public enum AVFontsView: Int {
case label = 1
case button = 2
case textfield = 3
case textview = 4
}
public class AVFonts: NSObject {
static var attributeFontLbl = [String: String]()
static var attributeFontbtn = [String: String]()
static var attributeFonttf = [String: String]()
static var attributeFonttv = [String: String]()
static var attributeFontSizeLabel = [String: CGFloat]()
static var attributeFontSizeBtn = [String: CGFloat]()
static var attributeFontSizetf = [String: CGFloat]()
static var attributeFontSizetv = [String: CGFloat]()
static var changeFontThroughOut: String = ""
static var changeFontThroughOutIncremnt: CGFloat = 0.0
static var changeFontThroughOutTypes: [AVFontsView] = []
static var checkFont: Bool = false
}
// MARK: -
// MARK: - Change Fonts
extension AVFonts {
public class func changeFont(toFont: String) {
changeFontThroughOut = toFont
changeFontThroughOutTypes = [.button,
.label,
.textfield,
.textview]
}
public class func changeFont(toFont: String, _ types: [AVFontsView]) {
changeFontThroughOut = toFont
changeFontThroughOutTypes = types
}
public class func changeFont(toFont: String, increment: CGFloat) {
changeFontThroughOut = toFont
changeFontThroughOutTypes = [.button,
.label,
.textfield,
.textview]
changeFontThroughOutIncremnt = increment
}
public class func changeFont(toFont: String, _ types: [AVFontsView], increment: CGFloat) {
changeFontThroughOut = toFont
changeFontThroughOutIncremnt = increment
changeFontThroughOutTypes = types
}
}
// MARK: -
// MARK: - Swap Fonts
extension AVFonts {
public class func swapFont(currentFont: String, toFont: String) {
if currentFont == toFont {
return
}
AVFonts.swapFont(currentFont: currentFont,
toFont: toFont,
[.button, .label, .textfield, .textview])
}
public class func swapFont(currentFont: String, toFont: String, _ types: [AVFontsView]) {
if currentFont == toFont {
return
}
for type in types {
switch type {
case .label:
self.attributeFontLbl[currentFont] = toFont
break
case .button:
self.attributeFontbtn[currentFont] = toFont
break
case .textfield:
self.attributeFonttf[currentFont] = toFont
break
case .textview:
self.attributeFonttv[currentFont] = toFont
break
}
}
}
public class func swapFont(currentFont: String, toFont: String, increment: CGFloat) {
if currentFont == toFont {
return
}
attributeFontSizeLabel[currentFont] = increment
attributeFontSizetf[currentFont] = increment
attributeFontSizeBtn[currentFont] = increment
attributeFontSizetv[currentFont] = increment
AVFonts.swapFont(currentFont: currentFont,
toFont: toFont,
[.button, .label, .textfield, .textview])
}
public class func swapFont(currentFont: String, toFont: String, _ types: [AVFontsView], increment: CGFloat) {
if currentFont == toFont {
return
}
for type in types {
switch type {
case .label: attributeFontSizeLabel[currentFont] = increment
case .button:attributeFontSizeBtn[currentFont] = increment
case .textfield:attributeFontSizetf[currentFont] = increment
case .textview:attributeFontSizetv[currentFont] = increment
}
}
AVFonts.swapFont(currentFont: currentFont, toFont: toFont, types)
}
}
// MARK: -
// MARK: - Apply Fonts
extension AVFonts {
public class func applyAVFonts() {
MethodSwizzleGivenClassName(cls: UILabel.self, originalSelector: #selector(UILabel.layoutSubviews), overrideSelector: #selector(UILabel.customFontLayoutSubviews))
MethodSwizzleGivenClassName(cls: UITextView.self, originalSelector: #selector(UITextView.layoutSubviews), overrideSelector: #selector(UITextView.customFontLayoutSubviews))
MethodSwizzleGivenClassName(cls: UITextField.self, originalSelector: #selector(UITextField.layoutSubviews), overrideSelector: #selector(UITextField.customFontLayoutSubviews))
MethodSwizzleGivenClassName(cls: UIButton.self, originalSelector: #selector(UIButton.layoutSubviews), overrideSelector: #selector(UIButton.customFontLayoutSubviews))
}
}
| mit | 659e854e7bd07cac88e36864d10f1456 | 36.132353 | 182 | 0.623168 | 4.809524 | false | false | false | false |
allbto/ios-swiftility | Swiftility/Sources/Core/Dynamic.swift | 2 | 2479 | //
// Dynamic.swift
// Swiftility
//
// Created by Allan Barbato on 9/9/15.
// Copyright © 2015 Allan Barbato. All rights reserved.
//
import Foundation
public struct Dynamic<T>
{
public typealias Listener = (T) -> Void
// MARK: - Private
fileprivate var _listener: Listener?
// MARK: - Properties
/// Contained value. Changes fire listener if `self.shouldFire == true`
public var value: T {
didSet {
guard shouldFire == true else { return }
self.fire()
}
}
/// Whether value didSet should fire or not
public var shouldFire: Bool = true
/// Whether fire() should call listener on main thread or not
public var fireOnMainThread: Bool = true
// Has a listener
public var isBinded: Bool {
return _listener != nil
}
// MARK: - Life cycle
/// Init with a value
public init(_ v: T)
{
value = v
}
// MARK: - Binding
/**
Bind a listener to value changes
- parameter listener: Closure called when value changes
*/
public mutating func bind(_ listener: Listener?)
{
_listener = listener
}
/**
Same as `bind` but also fires immediately
- parameter listener: Closure called immediately and when value changes
*/
public mutating func bindAndFire(_ listener: Listener?)
{
self.bind(listener)
self.fire()
}
// MARK: - Actions
// Fires listener if not nil. Regardless of `self.shouldFire`
public func fire()
{
if fireOnMainThread && !Thread.isMainThread {
async_main {
self._listener?(self.value)
}
} else {
self._listener?(self.value)
}
}
/**
Set value with optional firing. Regardless of `self.shouldFire`
- parameter value: Value to update to
- parameter =true;fire: Should fire changes of value
*/
public mutating func setValue(_ value: T, fire: Bool = true)
{
let originalShouldFire = shouldFire
shouldFire = fire
self.value = value
shouldFire = originalShouldFire
}
}
// MARK: - Convenience
precedencegroup Assignement {
associativity: left
assignment: true
higherThan: CastingPrecedence
}
infix operator .= : Assignement
public func .= <T>(lhs: inout Dynamic<T>, rhs: T)
{
lhs.value = rhs
}
| mit | 4bb6e490b55db892063148b81d30778a | 20.547826 | 76 | 0.5795 | 4.481013 | false | false | false | false |
evamalloc/Calculator-Test | CalculatorTest/AppDelegate.swift | 1 | 6105 | //
// AppDelegate.swift
// CalculatorTest
//
// Created by Yang Tian on 11/14/15.
// Copyright © 2015 Jiao Chu. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lw.2015.CalculatorTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CalculatorTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bsd-3-clause | e6b1ef6f006235155d282e554659aaa7 | 53.990991 | 291 | 0.719856 | 5.88621 | false | false | false | false |
naoyashiga/LegendTV | LegendTV/TopViewController.swift | 1 | 8910 | //
// TopViewController.swift
// Gaki
//
// Created by naoyashiga on 2015/07/20.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import UIKit
import RealmSwift
import Accounts
class TopViewController: UIViewController {
@IBOutlet var playerView: UIView!
@IBOutlet var containerView: UIView!
var videoID = ""
var videoTitle = ""
var videoThunmNailImageView = UIImageView()
var playingCell = VideoListCollectionViewCell()
var playingStory: Story? {
didSet {
applyFavoriteButtonState()
}
}
var playingKikaku: Kikaku?
var collectionViewHeight: CGFloat = 600
var activityIndicatorView: NVActivityIndicatorView?
let activityIndicatorViewTagNumber: Int = 1
@IBOutlet var playerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet var controlBarHeightConstraint: NSLayoutConstraint!
@IBOutlet var playOrPauseButtonVerticalConstraint: NSLayoutConstraint!
@IBOutlet var favoriteButton: UIButton!
@IBOutlet var playOrPauseButton: UIButton! {
didSet {
playOrPauseButton.selected = true
}
}
@IBOutlet var controlBarSeriesName: UILabel!
@IBOutlet var controlBarKikakuName: UILabel!
@IBOutlet var controlBarThumbNaiImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
playerViewHeightConstraint.constant = 0
controlBarHeightConstraint.constant = 0
playOrPauseButtonVerticalConstraint.constant = 74
view.layoutIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
applyChildVCDelegate()
}
//MARK: action method
@IBAction func playOrPauseButtonTapped(sender: UIButton) {
didPlayOrPauseButtonTapped(sender)
}
@IBAction func fullScreenButtonTapped(sender: UIButton) {
didFullScreenButtonTapped(sender)
}
@IBAction func favoriteButtonTapped(sender: UIButton) {
didFavoriteButtonTapped(sender)
}
//MARK: private method
func videoDisplayAnimation() {
playOrPauseButtonVerticalConstraint.constant = 74
checkVideoPlayerState()
if playerViewHeightConstraint.constant == 0 {
controlBarHeightConstraint.constant = 60
playerViewHeightConstraint.constant = 170
}
UIView.animateWithDuration(
0.6,
delay: 0.1,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.0,
options: [],
animations: {
self.view.layoutIfNeeded()
self.resizedVC()
}, completion: nil)
startActivityIndicatorView()
}
func applyForControlBarData(story story: Story) {
controlBarKikakuName.text = story.title
controlBarSeriesName.text = story.seriesName
controlBarThumbNaiImageView.sd_setImageWithURL(NSURL(string: story.thumbNailImageURL))
}
func applyForControlBarKikakuData<T: Kikaku>(kikaku kikaku: T) {
controlBarKikakuName.text = kikaku.kikakuName
controlBarSeriesName.text = kikaku.seriesName
controlBarThumbNaiImageView.sd_setImageWithURL(NSURL(string: kikaku.thumbNailImageURL))
//お気に入りボタンの状態を更新
if kikaku is Favorite {
favoriteButton.selected = true
} else if kikaku is History {
do {
let realm = try Realm()
let predicate = NSPredicate(format: "videoID == %@", kikaku.videoID)
if realm.objects(Favorite).filter(predicate).count == 0 {
//お気に入り未登録
favoriteButton.selected = false
} else {
//お気に入り登録済み
favoriteButton.selected = true
}
} catch {
print("error in applyForControlBarKikakuData")
}
}
}
private func applyFavoriteButtonState() {
guard let playingStory = playingStory else {
print("playingStory is nil")
return
}
do {
let realm = try Realm()
let predicate = NSPredicate(format: "videoID == %@", playingStory.videoID)
if realm.objects(Favorite).filter(predicate).count == 0 {
//お気に入り未登録
favoriteButton.selected = false
} else {
//お気に入り登録済み
favoriteButton.selected = true
}
} catch {
print("error in applyFavoriteButtonState")
}
}
func applyFavoriteButtonStateByPlayingKikaku() {
if let playingKikaku = playingKikaku {
if playingKikaku is Favorite {
do {
let realm = try Realm()
try realm.write {
//お気に入り解除
realm.delete(playingKikaku)
}
favoriteButton.selected = false
} catch {
print("error in checkFavorite")
}
}
if playingKikaku is History {
checkFavorite(kikaku: playingKikaku, story: nil)
}
}
}
func checkFavorite(kikaku kikaku: Kikaku?,story: Story?) {
if favoriteButton.selected {
var predicate: NSPredicate?
if let kikaku = kikaku {
predicate = NSPredicate(format: "videoID == %@", kikaku.videoID)
}
if let story = story {
predicate = NSPredicate(format: "videoID == %@", story.videoID)
}
if let predicate = predicate {
do {
let realm = try Realm()
let deletedFav = realm.objects(Favorite).filter(predicate)[0]
try realm.write {
//お気に入り解除
realm.delete(deletedFav)
}
favoriteButton.selected = false
} catch {
print("error in checkFavorite")
}
}
} else {
favoriteButton.selected = true
//お気に入り登録
let newFavorite = Favorite()
if let kikaku = kikaku {
saveKikakuFromFavoriteOrHistory(tmpKikaku: newFavorite, savedKikaku: kikaku)
}
if let story = story {
saveKikaku(kikaku: newFavorite, cell: playingCell, story: story)
}
}
}
func saveKikaku<T: Kikaku>(kikaku kikaku: T, cell: VideoListCollectionViewCell, story: Story) {
kikaku.videoID = story.videoID
kikaku.kikakuName = story.title
kikaku.seriesName = story.seriesName
kikaku.thumbNailImageURL = story.thumbNailImageURL
kikaku.duration = cell.durationLabel.text!
kikaku.viewCount = cell.viewCountLabel.text!
kikaku.likeCount = cell.likeCountLabel.text!
kikaku.createdAt = NSDate().timeIntervalSince1970
do {
let realm = try Realm()
try realm.write {
realm.add(kikaku, update: true)
}
} catch {
print("error in saveKikaku")
}
}
func saveKikakuFromFavoriteOrHistory<T: Kikaku>(tmpKikaku tmpKikaku: T,savedKikaku: T) {
tmpKikaku.videoID = savedKikaku.videoID
tmpKikaku.kikakuName = savedKikaku.kikakuName
tmpKikaku.seriesName = savedKikaku.seriesName
tmpKikaku.thumbNailImageURL = savedKikaku.thumbNailImageURL
tmpKikaku.duration = savedKikaku.duration
tmpKikaku.viewCount = savedKikaku.viewCount
tmpKikaku.likeCount = savedKikaku.likeCount
tmpKikaku.createdAt = NSDate().timeIntervalSince1970
do {
let realm = try Realm()
try realm.write {
realm.add(tmpKikaku, update: true)
}
} catch {
print("error in saveKikakuFromFavoriteOrHistory")
}
}
}
| mit | c679d36f13c9e82f758e6ca30e4dfb7f | 29.034247 | 99 | 0.539681 | 5.158824 | false | false | false | false |
BalestraPatrick/TweetsCounter | Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Demos/Timelines Demo/SearchFilteredTimelineViewController.swift | 2 | 1223 | //
// SearchFilteredTimelineViewController.swift
// FabricSampleApp
//
// Created by Alejandro Crosa on 11/15/16.
// Copyright © 2016 Twitter. All rights reserved.
//
import UIKit
@objc (SearchFilteredTimelineViewController)
class SearchFilteredTimelineViewController: TWTRTimelineViewController, DZNEmptyDataSetSource {
convenience init() {
let client = TWTRAPIClient.withCurrentUser()
let dataSource = TWTRSearchTimelineDataSource(searchQuery: "twitter", apiClient: client)
// filter the search timeline
let filter = TWTRTimelineFilter()
filter.keywords = [ "book", "phone" ]
filter.hashtags = [ "#twitter", "#followme" ]
filter.urls = [ "twitter.com", "fabric.io" ]
filter.handles = [ "ericfrohnhoefer", "benward", "vam_si", "katejaiheelee", "esacrosa" ]
dataSource.timelineFilter = filter
self.init(dataSource: dataSource)
self.title = dataSource.searchQuery
self.hidesBottomBarWhenPushed = true
self.showTweetActions = true
// To remove our default message
self.tableView.backgroundView = nil
// For DZNEmptyDataSet
self.tableView.emptyDataSetSource = self;
}
}
| mit | 1b6f91610465d94c00403dac97d4851c | 32.027027 | 96 | 0.680851 | 4.427536 | false | false | false | false |
mpdifran/MyoSports | MyoSports/MyoDataCollector/MyoDataCollector.swift | 1 | 6350 | //
// MyoDataCollector.swift
// MyoSports
//
// Created by Mark DiFranco on 2015-05-28.
// Copyright (c) 2015 MDF Projects. All rights reserved.
//
import Foundation
class MyoDataCollector: NSObject {
private var shouldRecord = false
var isRecording: Bool {
return shouldRecord
}
private var myo: TLMMyo? {
return TLMHub.sharedHub().myoDevices().first as? TLMMyo
}
private let highPassFilterAlpha: Float = 0.8
private var gravityVector = TLMVector3Make(0, 0, 0)
private var recordingStartDate: NSDate?
private var documentDirectory: String?
private var accelFileName: String?
private var gyroFileName: String?
private var orientationFileName: String?
private var emgFileName: String?
private let accelQueue = dispatch_queue_create("AccelerationFileQueue", DISPATCH_QUEUE_SERIAL)
private let gyroQueue = dispatch_queue_create("GyroscopeFileQueue", DISPATCH_QUEUE_SERIAL)
private let orientationQueue = dispatch_queue_create("OrientationFileQueue", DISPATCH_QUEUE_SERIAL)
private let emgQueue = dispatch_queue_create("EMGFileQueue", DISPATCH_QUEUE_SERIAL)
// MARK: - Constructors
override init() {
super.init()
setupNotifications()
documentDirectory = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first as? String
}
// MARK: - Instance Methods
func beginRecording() {
if documentDirectory == nil {
println("No document directory to write to")
return
}
recordingStartDate = NSDate()
accelFileName = documentDirectory!.stringByAppendingPathComponent(recordingStartDate!.description + "-Acceleration.csv")
gyroFileName = documentDirectory!.stringByAppendingPathComponent(recordingStartDate!.description + "-Gyroscope.csv")
orientationFileName = documentDirectory!.stringByAppendingPathComponent(recordingStartDate!.description + "-Orientation.csv")
emgFileName = documentDirectory!.stringByAppendingPathComponent(recordingStartDate!.description + "-EMG.csv")
shouldRecord = true
}
func toggleRecording() {
if shouldRecord {
endRecording()
} else {
beginRecording()
}
}
func endRecording() {
shouldRecord = false
recordingStartDate = nil
accelFileName = nil
gyroFileName = nil
orientationFileName = nil
emgFileName = nil
}
func recordEventWithName(name: String) {
for (filename, queue) in [(accelFileName, accelQueue), (gyroFileName, gyroQueue), (orientationFileName, orientationQueue), (emgFileName, emgQueue)] {
if filename == nil {
continue
}
writeToFile(filename!, value: "Event,\(name)\n", queue: queue)
}
}
// MARK: - Private Instance Methods
private func setupNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserverForName(TLMHubDidConnectDeviceNotification, object: nil, queue: nil) {
(notification: NSNotification!) -> Void in
myo?.setStreamEmg(TLMStreamEmgType.Enabled)
}
notificationCenter.addObserver(self, selector: Selector("onOrientation:"), name: TLMMyoDidReceiveOrientationEventNotification, object: nil)
notificationCenter.addObserver(self, selector: Selector("onAccelerometer:"), name: TLMMyoDidReceiveAccelerometerEventNotification, object: nil)
notificationCenter.addObserver(self, selector: Selector("onGyroscope:"), name: TLMMyoDidReceiveGyroscopeEventNotification, object: nil)
notificationCenter.addObserver(self, selector: Selector("onEmg:"), name: TLMMyoDidReceiveEmgEventNotification, object: nil)
}
private func writeToFile(filename: String, value: String, queue: dispatch_queue_t) {
dispatch_async(queue) {
let data: NSData! = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if NSFileManager.defaultManager().fileExistsAtPath(filename) {
let handle: NSFileHandle! = NSFileHandle(forWritingAtPath: filename)
handle.truncateFileAtOffset(handle!.seekToEndOfFile())
handle.writeData(data)
} else {
data.writeToFile(filename, atomically: false)
}
}
}
// MARK: - Notification Handlers
func onOrientation(notification: NSNotification!) {
if let orientationEvent = notification.userInfo?[kTLMKeyOrientationEvent] as? TLMOrientationEvent {
if shouldRecord {
if let fileName = orientationFileName {
writeToFile(fileName, value: orientationEvent.toCSV(), queue: orientationQueue)
}
}
}
}
func onAccelerometer(notification: NSNotification!) {
if let accelerometerEvent = notification.userInfo?[kTLMKeyAccelerometerEvent] as? TLMAccelerometerEvent {
// Apply a high pass filter to get rid of gravity
let accelVector = accelerometerEvent.vector
gravityVector = accelVector * highPassFilterAlpha + gravityVector * (1.0 - highPassFilterAlpha)
if shouldRecord {
if let fileName = accelFileName {
let linearVector = accelVector - gravityVector
writeToFile(fileName, value: accelerometerEvent.toCSV(linearVector), queue: accelQueue)
}
}
}
}
func onGyroscope(notification: NSNotification!) {
if let gyroscopeEvent = notification.userInfo?[kTLMKeyGyroscopeEvent] as? TLMGyroscopeEvent {
if shouldRecord {
if let fileName = gyroFileName {
writeToFile(fileName, value: gyroscopeEvent.toCSV(), queue: gyroQueue)
}
}
}
}
func onEmg(notification: NSNotification!) {
if let emgEvent = notification.userInfo?[kTLMKeyEMGEvent] as? TLMEmgEvent {
if shouldRecord {
if let fileName = emgFileName {
writeToFile(fileName, value: emgEvent.toCSV(), queue: emgQueue)
}
}
}
}
}
| mit | cbaab4d34dccd0204e415a506f601413 | 37.719512 | 166 | 0.660787 | 5.019763 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift | 268 | 3376 | //
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
private let _hasHigherPriority: (Element, Element) -> Bool
private let _isEqual: (Element, Element) -> Bool
fileprivate var _elements = [Element]()
init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _elements.count == 0
}
mutating func dequeue() -> Element? {
guard let front = peek() else {
return nil
}
removeAt(0)
return front
}
mutating func remove(_ element: Element) {
for i in 0 ..< _elements.count {
if _isEqual(_elements[i], element) {
removeAt(i)
return
}
}
}
private mutating func removeAt(_ index: Int) {
let removingLast = index == _elements.count - 1
if !removingLast {
swap(&_elements[index], &_elements[_elements.count - 1])
}
_ = _elements.popLast()
if !removingLast {
bubbleToHigherPriority(index)
bubbleToLowerPriority(index)
}
}
private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while unbalancedIndex > 0 {
let parentIndex = (unbalancedIndex - 1) / 2
guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break }
swap(&_elements[unbalancedIndex], &_elements[parentIndex])
unbalancedIndex = parentIndex
}
}
private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while true {
let leftChildIndex = unbalancedIndex * 2 + 1
let rightChildIndex = unbalancedIndex * 2 + 2
var highestPriorityIndex = unbalancedIndex
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex])
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue : CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
| mit | b389e3b6c02c3da0106729289279cda9 | 29.133929 | 133 | 0.618963 | 4.87013 | false | false | false | false |
lulee007/GankMeizi | GankMeizi/Utils/DateUtil.swift | 1 | 1262 | //
// DateUtil.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/23.
// Copyright © 2016年 lulee007. All rights reserved.
//
import Foundation
public class DateUtil {
static let DATE_FORMATTER = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
public static func stringToNSDate(dateString: String,formatter: String = DATE_FORMATTER) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = formatter
return dateFormatter.dateFromString( dateString )!
}
public static func nsDateToString(date: NSDate,formatter: String = "yyyy-MM-dd HH:mm:ss" ) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = formatter
return dateFormatter.stringFromDate(date)
}
public static func areDatesSameDay(dateOne:NSDate,dateTwo:NSDate) -> Bool {
let calender = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [.Day, .Month, .Year]
let compOne: NSDateComponents = calender.components(flags, fromDate: dateOne)
let compTwo: NSDateComponents = calender.components(flags, fromDate: dateTwo);
return (compOne.day == compTwo.day && compOne.month == compTwo.month && compOne.year == compTwo.year);
}
} | mit | 894536a15cb9123be4ffca06de203db2 | 34.828571 | 110 | 0.676776 | 4.149007 | false | true | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Analysis.playground/Pages/Tracking Frequency.xcplaygroundpage/Contents.swift | 1 | 2475 | //: ## Tracking Frequency
//: Tracking frequency is just as easy as tracking amplitude, and even
//: includes amplitude, but it is more CPU intensive, so if you just need amplitude,
//: use the amplitude tracker.
import XCPlayground
import AudioKit
//: First lets set up sound source to track
let oscillatorNode = AKOperationGenerator() { _ in
// Let's set up the volume to be changing in the shape of a sine wave
let volume = AKOperation.sineWave(frequency: 0.2).scale(minimum: 0, maximum: 0.5)
// And let's make the frequency also be a sineWave
let frequency = AKOperation.sineWave(frequency: 0.1).scale(minimum: 100, maximum: 2200)
return AKOperation.sineWave(frequency: frequency, amplitude: volume)
}
let tracker = AKFrequencyTracker(oscillatorNode)
let booster = AKBooster(tracker, gain: 0.5)
let secondaryOscillator = AKOscillator()
//: The frequency tracker passes its input to the output,
//: so we can insert into the signal chain at the bottom
AudioKit.output = AKMixer(booster, secondaryOscillator)
AudioKit.start()
oscillatorNode.start()
secondaryOscillator.start()
//: User Interface
class PlaygroundView: AKPlaygroundView {
var trackedAmplitudeSlider: AKPropertySlider?
var trackedFrequencySlider: AKPropertySlider?
override func setup() {
AKPlaygroundLoop(every: 0.1) {
self.trackedAmplitudeSlider?.value = tracker.amplitude
self.trackedFrequencySlider?.value = tracker.frequency
secondaryOscillator.frequency = tracker.frequency
secondaryOscillator.amplitude = tracker.amplitude
}
addTitle("Tracking Frequency")
trackedAmplitudeSlider = AKPropertySlider(
property: "Tracked Amplitude",
format: "%0.3f",
value: 0, maximum: 0.8,
color: AKColor.greenColor()
) { sliderValue in
// Do nothing, just for display
}
addSubview(trackedAmplitudeSlider!)
trackedFrequencySlider = AKPropertySlider(
property: "Tracked Frequency",
format: "%0.3f",
value: 0, maximum: 2400,
color: AKColor.redColor()
) { sliderValue in
// Do nothing, just for display
}
addSubview(trackedFrequencySlider!)
addSubview(AKRollingOutputPlot.createView())
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | 961b80062dd2fec375cf59fdb0d6baf2 | 32.445946 | 91 | 0.689293 | 4.787234 | false | false | false | false |
svdo/ReRxSwift | Pods/Nimble/Sources/Nimble/Matchers/Contain.swift | 7 | 5802 | #if canImport(Foundation)
import Foundation
#endif
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
public func contain<S: Sequence>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
return contain(items)
}
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
public func contain<S: Sequence>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.allSatisfy {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
return contain(items)
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.allSatisfy {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: Sequence & SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable {
return contain(items)
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: Sequence & SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.allSatisfy {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: String...) -> Predicate<String> {
return contain(substrings)
}
public func contain(_ substrings: [String]) -> Predicate<String> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = substrings.allSatisfy {
let range = actual.range(of: $0)
return range != nil && !range!.isEmpty
}
return PredicateStatus(bool: matches)
}
}
#if canImport(Foundation)
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: NSString...) -> Predicate<NSString> {
return contain(substrings)
}
public func contain(_ substrings: [NSString]) -> Predicate<NSString> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = substrings.allSatisfy { actual.range(of: $0.description).length != 0 }
return PredicateStatus(bool: matches)
}
}
#endif
/// A Nimble matcher that succeeds when the actual collection contains the expected object.
public func contain(_ items: Any?...) -> Predicate<NMBContainer> {
return contain(items)
}
public func contain(_ items: [Any?]) -> Predicate<NMBContainer> {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.allSatisfy { item in
return item.map { actual.contains($0) } ?? false
}
return PredicateStatus(bool: matches)
}
}
#if canImport(Darwin)
extension NMBPredicate {
@objc public class func containMatcher(_ expected: [NSObject]) -> NMBPredicate {
return NMBPredicate { actualExpression in
let location = actualExpression.location
let actualValue = try actualExpression.evaluate()
if let value = actualValue as? NMBContainer {
let expr = Expression(expression: ({ value as NMBContainer }), location: location)
// A straightforward cast on the array causes this to crash, so we have to cast the individual items
let expectedOptionals: [Any?] = expected.map({ $0 as Any? })
return try contain(expectedOptionals).satisfies(expr).toObjectiveC()
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
// swiftlint:disable:next force_cast
return try contain(expected as! [String]).satisfies(expr).toObjectiveC()
}
let message: ExpectationMessage
if actualValue != nil {
message = ExpectationMessage.expectedActualValueTo(
// swiftlint:disable:next line_length
"contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)"
)
} else {
message = ExpectationMessage
.expectedActualValueTo("contain <\(arrayAsString(expected))>")
.appendedBeNilHint()
}
return NMBPredicateResult(status: .fail, message: message.toObjectiveC())
}
}
}
#endif
| mit | 79597cc273418b557951a67e0e725ff6 | 41.043478 | 121 | 0.661496 | 4.896203 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Messages/OWSMessageSend.swift | 1 | 2360 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalMetadataKit
// Corresponds to a single effort to send a message to a given recipient,
// which may span multiple attempts. Note that group messages may be sent
// to multiple recipients and therefore require multiple instances of
// OWSMessageSend.
@objc
public class OWSMessageSend: NSObject {
@objc
public let message: TSOutgoingMessage
@objc
public let thread: TSThread
@objc
public let recipient: SignalRecipient
private static let kMaxRetriesPerRecipient: Int = 3
@objc
public var remainingAttempts = OWSMessageSend.kMaxRetriesPerRecipient
// We "fail over" to REST sends after _any_ error sending
// via the web socket.
@objc
public var hasWebsocketSendFailed = false
@objc
public var udAccess: OWSUDAccess?
@objc
public var senderCertificate: SMKSenderCertificate?
@objc
public let localAddress: SignalServiceAddress
@objc
public let isLocalAddress: Bool
@objc
public let success: () -> Void
@objc
public let failure: (Error) -> Void
@objc
public init(message: TSOutgoingMessage,
thread: TSThread,
recipient: SignalRecipient,
senderCertificate: SMKSenderCertificate?,
udAccess: OWSUDAccess?,
localAddress: SignalServiceAddress,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
self.message = message
self.thread = thread
self.recipient = recipient
self.localAddress = localAddress
self.senderCertificate = senderCertificate
self.udAccess = udAccess
self.isLocalAddress = recipient.address.isLocalAddress
self.success = success
self.failure = failure
}
@objc
public var isUDSend: Bool {
return udAccess != nil && senderCertificate != nil
}
@objc
public func disableUD() {
Logger.verbose("\(String(describing: recipient.address))")
udAccess = nil
}
@objc
public func setHasUDAuthFailed() {
Logger.verbose("\(String(describing: recipient.address))")
// We "fail over" to non-UD sends after auth errors sending via UD.
disableUD()
}
}
| gpl-3.0 | 548e8527f424d38db11a98874e4000e5 | 25.516854 | 75 | 0.652119 | 4.865979 | false | false | false | false |
oNaiPs/dmenu-mac | src/ResultsView.swift | 1 | 3272 | /*
* Copyright (c) 2016 Jose Pereira <[email protected]>.
*
* 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, version 3.
*
* 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 Cocoa
class ResultsView: NSView {
@IBOutlet fileprivate var scrollView: NSScrollView!
let rectFillPadding: CGFloat = 5
var resultsList: [ListItem] = []
var dirtyWidth: Bool = false
var selectedRect = NSRect()
var selectedIndexValue: Int = 0
var selectedIndex: Int {
get {
return selectedIndexValue
}
set {
if newValue < 0 || newValue >= resultsList.count {
return
}
selectedIndexValue = newValue
needsDisplay = true
}
}
var list: [ListItem] {
get {
return resultsList
}
set {
selectedIndexValue = 0
resultsList = newValue
needsDisplay = true
}
}
func selectedItem() -> ListItem? {
if selectedIndexValue < 0 || selectedIndexValue >= resultsList.count {
return nil
} else {
return resultsList[selectedIndexValue]
}
}
func clear() {
resultsList.removeAll()
needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
var textX = CGFloat(rectFillPadding)
let drawList = list.count > 0 ? list : [ListItem(name: "No results", data: nil)]
for i in 0 ..< drawList.count {
let item = (drawList[i].name) as NSString
let size = item.size(withAttributes: [NSAttributedString.Key: Any]())
let textY = (frame.height - size.height) / 2
if selectedIndexValue == i {
selectedRect = NSRect(
x: textX - rectFillPadding,
y: textY - rectFillPadding,
width: size.width + rectFillPadding * 2,
height: size.height + rectFillPadding * 2)
NSColor.selectedTextBackgroundColor.setFill()
__NSRectFill(selectedRect)
}
item.draw(in: NSRect(
x: textX,
y: textY,
width: size.width,
height: size.height), withAttributes: [
NSAttributedString.Key.foregroundColor: NSColor.textColor
])
textX += 10 + size.width
}
if dirtyWidth {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: textX, height: frame.height)
dirtyWidth = false
scrollView.contentView.scrollToVisible(selectedRect)
}
}
func updateWidth() {
dirtyWidth = true
}
}
| gpl-3.0 | eee00a6d71cbcc52af69c99e3d9f586a | 29.867925 | 100 | 0.55868 | 4.935143 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/AlertToast.swift | 1 | 6185 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
/// AlertToast from the Figma Component Library.
///
/// # Figma
///
/// [AlertToast](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=212%3A5937)
public struct AlertToast: View {
private let text: String
private let variant: Variant
private var icon: Icon?
/// Create an AlertToast view
/// - Parameters:
/// - text: Text displayed in the toast
/// - variant: Color variant. See `extension AlertToast.Variant` below for options.
/// - icon: Optional Icon to be displayed on the leading of the toast
public init(
text: String,
variant: Variant = .default,
icon: Icon? = nil
) {
self.text = text
self.variant = variant
self.icon = icon
}
public var body: some View {
HStack(spacing: 8) {
if let icon = self.icon {
icon
.accentColor(variant.iconColor)
.frame(width: 16, height: 16)
}
Text(text)
.typography(.body2)
.foregroundColor(variant.textColor)
}
.padding(.horizontal, 24)
.padding(.vertical, 14)
.background(
GeometryReader { proxy in
RoundedRectangle(cornerRadius: Spacing.roundedBorderRadius(for: proxy.size.height))
.fill(variant.backgroundColor)
.shadow(
color: Color(
light: .palette.black.opacity(0.04),
dark: .palette.black.opacity(0.04)
),
radius: 1,
x: 0,
y: 3
)
.shadow(
color: Color(
light: .palette.black.opacity(0.12),
dark: .palette.black.opacity(0.12)
),
radius: 8,
x: 0,
y: 3
)
}
)
}
/// Style variant for AlertToast
public struct Variant {
fileprivate let backgroundColor: Color
fileprivate let textColor: Color
fileprivate let iconColor: Color
}
}
extension AlertToast.Variant {
public static let `default` = AlertToast.Variant(
backgroundColor: .init(light: .palette.dark800, dark: .palette.grey300),
textColor: .init(light: .palette.white, dark: .palette.grey900),
iconColor: .init(light: .palette.white, dark: .palette.grey900)
)
// success
public static let success = AlertToast.Variant(
backgroundColor: .init(light: .palette.dark800, dark: .palette.green600),
textColor: .init(light: .palette.green400, dark: .palette.white),
iconColor: .init(light: .palette.green400, dark: .palette.white)
)
// warning
public static let warning = AlertToast.Variant(
backgroundColor: .init(light: .palette.dark800, dark: .palette.orange400),
textColor: .init(light: .palette.orange400, dark: .palette.dark800),
iconColor: .init(light: .palette.orange400, dark: .palette.dark800)
)
// error
public static let error = AlertToast.Variant(
backgroundColor: .init(light: .palette.dark800, dark: .palette.red600),
textColor: .init(light: .palette.red400, dark: .palette.white),
iconColor: .init(light: .palette.red400, dark: .palette.white)
)
}
struct AlertToast_Previews: PreviewProvider {
static var previews: some View {
Group {
VStack {
AlertToast(text: "Default", variant: .default)
AlertToast(text: "Default", variant: .default)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Default")
VStack {
AlertToast(text: "Default", variant: .default, icon: .refresh)
AlertToast(text: "Default", variant: .default, icon: .refresh)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Default + Icon")
VStack {
AlertToast(text: "Success", variant: .success)
AlertToast(text: "Success", variant: .success)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Success")
VStack {
AlertToast(text: "Success", variant: .success, icon: .checkCircle)
AlertToast(text: "Success", variant: .success, icon: .checkCircle)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Success + Icon")
VStack {
AlertToast(text: "Warning", variant: .warning)
AlertToast(text: "Warning", variant: .warning)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Warning")
VStack {
AlertToast(text: "Warning", variant: .warning, icon: .alert)
AlertToast(text: "Warning", variant: .warning, icon: .alert)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Warning + Icon")
VStack {
AlertToast(text: "Error", variant: .error)
AlertToast(text: "Error", variant: .error)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Error")
VStack {
AlertToast(text: "Error", variant: .error, icon: .error)
AlertToast(text: "Error", variant: .error, icon: .error)
.colorScheme(.dark)
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Error + Icon")
}
.padding()
}
}
| lgpl-3.0 | e7aed0be33b40bea19d7580628c88772 | 34.136364 | 106 | 0.527167 | 4.699088 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeImage/AwesomeImage/Classes/Extensions/UIImageViewExtensions.swift | 1 | 3053 | //
// UIImageViewExtensions.swift
// AwesomeImage
//
// Created by Evandro Harrison Hoffmann on 4/13/18.
//
import UIKit
import AwesomeLoading
import Kingfisher
//private var loadedUrlAssociationKey: String = ""
//private var alreadyLoadedOriginalImageAssociationKey: Bool = false
extension UIImageView {
/*final internal var loadedUrl: String! {
get {
return objc_getAssociatedObject(self, &loadedUrlAssociationKey) as? String
}
set {
objc_setAssociatedObject(self, &loadedUrlAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
final internal var alreadyLoadedOriginalImage: Bool! {
get {
return objc_getAssociatedObject(self, &alreadyLoadedOriginalImageAssociationKey) as? Bool
}
set {
objc_setAssociatedObject(self, &alreadyLoadedOriginalImageAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}*/
public func setImage(_ urlString: String?, placeholder: UIImage? = nil, completion:((UIImage?) -> Void)? = nil) {
self.layer.masksToBounds = true
guard let urlString = urlString, let url = URL(string: urlString) else {
return
}
self.startShimmerAnimation()
kf.setImage(with: url, placeholder: placeholder) { (image, _, _, _) in
self.stopShimmerAnimation()
completion?(image)
}
}
/*
self.image = nil
if let placeholder = placeholder {
self.image = placeholder
}
self.loadedUrl = ""
self.alreadyLoadedOriginalImage = false
guard let url = url else {
return
}
self.startShimmerAnimation()
self.loadedUrl = url
let initialLoadedUrl = self.loadedUrl as String
if let thumbnailUrl = thumbnailUrl {
_ = UIImage.loadImage(thumbnailUrl) { (image) in
if(initialLoadedUrl == self.loadedUrl && !self.alreadyLoadedOriginalImage) {
self.image = image
if(animated) {
self.alpha = 0.2
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1.0
})
}
} else {
return
}
}
}
UIImage.loadImage(url) { (image) in
if(initialLoadedUrl == self.loadedUrl) {
self.alreadyLoadedOriginalImage = true
self.image = image
if(animated) {
self.alpha = 0.2
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 1.0
})
}
completion?(image)
}
self.stopShimmerAnimation()
}
}*/
}
| mit | d2eb617904b78258f2657a2802b57566 | 29.53 | 153 | 0.532591 | 5.254733 | false | false | false | false |
gergelyorosz/SwiftAlgorithmsAndDataStructures | AlgorithmsAndDataStructures/AlgorithmsAndDataStructures/QuickSort.swift | 1 | 2109 | //
// InsertionSort.swift
// AlgorithmsAndDataStructures
//
// Created by Carolyn Johnson on 30/07/2014.
// Copyright (c) 2014 com.gergelyorosz. All rights reserved.
//
import Foundation
class QuickSort
{
class func sort(inout array: [Int]) {
quicksort(&array, left:0, right:array.count-1)
}
class func quicksort(inout array: [Int], left: Int, right: Int) {
if left < right {
var partitionIndex = partition(&array, left: left, right: right)
quicksort(&array, left:left, right: partitionIndex-1)
quicksort(&array, left:partitionIndex+1, right: right)
}
}
class func partition(inout array: [Int], left: Int, right: Int) -> Int {
var pivotIndex = choosePivotIndex(array, left: left, right: right);
var pivotValue = array[pivotIndex]
var storeIndex = left
swap(&array, index1: pivotIndex, index2: right)
for (var i=left; i<right; i++) {
if array[i] <= pivotValue {
swap(&array, index1: i, index2: storeIndex)
storeIndex += 1
}
}
swap(&array, index1: storeIndex, index2: right)
return storeIndex
}
class func swap(inout array: [Int], index1: Int, index2: Int) {
var tmp = array[index1];
array[index1] = array[index2]
array[index2] = tmp
}
class func choosePivotIndex(array: [Int], left: Int, right: Int) -> Int {
var middle = (left + right) / 2
if array[left] <= array[middle] {
if array[middle] <= array[right] {
return middle
}
else if array[left] >= array[right] {
return left
}
else {
return right
}
} else { // array[left] >= array[middle]
if array[left] <= array[right] {
return left
}
else if array[middle] >= array[right] {
return middle
}
else {
return right
}
}
}
}
| mit | f4712ef6ab9bedbcaedd2f3e07dd27cf | 29.128571 | 77 | 0.522523 | 3.994318 | false | false | false | false |
gaurav1981/Swiftz | Swiftz/NonEmptyList.swift | 1 | 3443 | //
// NonEmptyList.swift
// swiftz
//
// Created by Maxwell Swadling on 10/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
/// A list that may not ever be empty.
///
/// Traditionally partial operations on regular lists are total with non-empty lists.
public struct NonEmptyList<A> {
public let head : Box<A>
public let tail : List<A>
public init(_ a : A, _ t : List<A>) {
head = Box(a)
tail = t
}
public init?(_ list : List<A>) {
switch list.match() {
case .Nil:
return nil
case let .Cons(h, t):
self.init(h, t)
}
}
public func toList() -> List<A> {
return List(head.value, tail)
}
}
public func head<A>() -> Lens<NonEmptyList<A>, NonEmptyList<A>, A, A> {
return Lens { nel in IxStore(nel.head.value) { NonEmptyList($0, nel.tail) } }
}
public func tail<A>() -> Lens<NonEmptyList<A>, NonEmptyList<A>, List<A>, List<A>> {
return Lens { nel in IxStore(nel.tail) { NonEmptyList(nel.head.value, $0) } }
}
public func ==<A : Equatable>(lhs : NonEmptyList<A>, rhs : NonEmptyList<A>) -> Bool {
return (lhs.head.value == rhs.head.value && lhs.tail == rhs.tail)
}
extension NonEmptyList : ArrayLiteralConvertible {
typealias Element = A
public init(arrayLiteral s: Element...) {
var xs : [A] = []
var g = s.generate()
let h: A? = g.next()
while let x : A = g.next() {
xs.append(x)
}
var l = List<A>()
for x in xs.reverse() {
l = List(x, l)
}
self = NonEmptyList(h!, l)
}
}
public final class NonEmptyListGenerator<A> : K1<A>, GeneratorType {
var head: A?
var l: List<A>?
public func next() -> A? {
if let h = head {
head = nil
return h
} else {
var r = l?.head()
l = self.l?.tail()
return r
}
}
public init(_ l : NonEmptyList<A>) {
head = l.head.value
self.l = l.tail
}
}
extension NonEmptyList : SequenceType {
public func generate() -> NonEmptyListGenerator<A> {
return NonEmptyListGenerator(self)
}
}
extension NonEmptyList : Printable {
public var description : String {
var x = ", ".join(self.fmap({ "\($0)" }))
return "[\(x)]"
}
}
extension NonEmptyList : Functor {
typealias B = Any
typealias FB = NonEmptyList<B>
public func fmap<B>(f : (A -> B)) -> NonEmptyList<B> {
return NonEmptyList<B>(f(self.head.value), self.tail.fmap(f))
}
}
extension NonEmptyList : Pointed {
public static func pure(x : A) -> NonEmptyList<A> {
return NonEmptyList(x, List())
}
}
extension NonEmptyList : Applicative {
typealias FA = NonEmptyList<A>
typealias FAB = NonEmptyList<A -> B>
public func ap<B>(f : NonEmptyList<A -> B>) -> NonEmptyList<B> {
return f.bind({ f in self.bind({ x in NonEmptyList<B>.pure(f(x)) }) })
}
}
extension NonEmptyList : Monad {
public func bind<B>(f : A -> NonEmptyList<B>) -> NonEmptyList<B> {
let nh = f(self.head.value)
return NonEmptyList<B>(nh.head.value, nh.tail + self.tail.bind { t in f(t).toList() })
}
}
extension NonEmptyList : Copointed {
public func extract() -> A {
return self.head.value
}
}
extension NonEmptyList : Comonad {
typealias FFA = NonEmptyList<NonEmptyList<A>>
public func duplicate() -> NonEmptyList<NonEmptyList<A>> {
switch NonEmptyList(self.tail) {
case .None:
return NonEmptyList<NonEmptyList<A>>(self, [])
case let .Some(x):
return NonEmptyList<NonEmptyList<A>>(self, x.duplicate().toList())
}
}
public func extend<B>(fab : NonEmptyList<A> -> B) -> NonEmptyList<B> {
return self.duplicate().fmap(fab)
}
}
| bsd-3-clause | 73186d79b12a8c6d6d4a0677ef81a0da | 22.107383 | 88 | 0.640139 | 2.988715 | false | false | false | false |
tgu/HAP | Sources/HAP/Endpoints/accessories().swift | 1 | 745 | import func Evergreen.getLogger
import Foundation
import HKDF
fileprivate let logger = getLogger("hap.endpoints.accessories")
func accessories(device: Device) -> Application {
return { connection, request in
guard request.method == "GET" else {
return .badRequest
}
let serialized: [String: Any] = [
"accessories": device.accessories.map { $0.serialized() }
]
do {
let json = try JSONSerialization.data(withJSONObject: serialized, options: [])
return Response(data: json, mimeType: "application/hap+json")
} catch {
logger.error("Could not serialize object", error: error)
return .internalServerError
}
}
}
| mit | 54b5bebad3188da2c44cc600f7dd2e54 | 31.391304 | 90 | 0.61745 | 4.745223 | false | false | false | false |
Jnosh/swift | validation-test/compiler_crashers_fixed/25876-llvm-errs.swift | 65 | 2714 | // 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
class d<T where g: <T where : String {let a{
let : T.e
struct B<T where h: C {
var e(d func f:String{
func a{
private let f: NSObject {
let g c{() {
extension NSData{
class A {()enum S<B<A}c{ "
typealias A<T.e(String
protocol c
struct d:T>:A
struct d=c{ "\(){
{
{}
private let : NSObject {let a {
}
struct d<T where g: A<T where g: d a(d func a<T where : C {
struct B<T where g:A:A< B {
{
import Foundation
struct S<T {
func a
}struct B<T where g:A
func a{
struct c{let v: A {
struct c
struct S<T where g: {{
let f=e(d func a
var d<T where g:A:a< : NSObject {
let : C {"\(d func d=c
struct d: NSObject {
}
class d<T>){struct B<T where f: NSObject
struct c{ "
}
() > {
struct c : C {
enum e
{let f: A {
struct c
class A {{
class d=c{(String
extension NSData{"\() > {
}
struct c
func f: C {
class a
let c n
extension NSData{init{
}
}
case,
let a{class{let a {
func f{
extension NSData{}
("
let f:String
protocol a< : {
struct B<T where h: A
v: a{
var e, : C {protocol c
class A {
let : NSObject
let a
}
func b
deinit{
struct c
protocol c{ "
var d=c
extension NSData{
func f=e(String
}
class a
protocol a<T where g: C {
let a{
func d=e, : <T where : <T where
struct B<A<T where g: NSObject
deinit{
func b
func b
protocol a
func f: A {
extension D{(String
func d=c
let a {
typealias A<T where g: T>){let f{
v: NSObject
private let : <T where f: d func a
class d:String
func a{
}
let a {
func b
}c<T where I:T>:String{struct B{(String{(String{
let v: d a
class B< : T>){protocol A< B {
extension NSData{
let : <T where g:String{
{
func b
func a
func f=c
protocol c
private let a{() {
func b
}
let a{
deinit{
let a{
func f: A {(d a(d a<T where I:A:T>){
deinit{
extension D{
}c
func d:a
extension D{func a
let a {init{
struct B{let g c
}
println -
case,
}
let c {
func a(d a{
func a{() > {
}
}
struct A<T where I:String
struct B{
class B{(d func f: C {struct c
}c
() {
func f: C {
protocol c : d func f{let a<A< : NSObject
case,
struct c n
{struct c
let g c{
class a{
protocol c
enum e, : T>:String{func a
(d a{("
let f: <T where
let a {let a {
struct c n
func a<T where : NSObject
struct c
case,
struct S<T>){
}struct d<B{let a {class
func d<A:N{
func d:C{struct c{init{
struct c
import Foundation
case,
func d=e
struct S<T {
func d<T where : NSObject
case,
struct B<T where I:a
class B<T where
func f: <T>:C{class{
class
| apache-2.0 | 7fe71dfc6567bda80b2d86fb42af6e4b | 14.77907 | 79 | 0.661017 | 2.562795 | false | false | false | false |
swiftde/Udemy-Swift-Kurs | Kapitel 1/Kapitel 1/HauptmenüTVC.swift | 1 | 2372 | //
// HauptmenüTVC.swift
// Kapitel 1
//
// Created by Udemy on 27.12.14.
// Copyright (c) 2014 Udemy. All rights reserved.
//
import UIKit
class Hauptmenu_TVC: UITableViewController {
let daten = ["Synchroner Download", "Asynchroner Download", "JSON parsen", "XML parsen", "CoreLocation/MapKit", "Core Image", "Eigenes Delegate-Protokoll", "Facebook / Twitter", "Movieplayer", "Kontaktiere mich!"]
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return daten.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = daten[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var identifier = ""
switch indexPath.row {
case 0,1:
identifier = "datenLaden"
case 2:
identifier = "jsonSegue"
case 3:
identifier = "xmlSegue"
case 4:
identifier = "clmkSegue"
case 5:
identifier = "ciSegue"
case 6:
identifier = "delegateSegue"
case 7:
identifier = "socialSegue"
case 8:
identifier = "movieSegue"
case 9:
identifier = "contactMeSegue"
default:
break
}
let senderCell = tableView.cellForRowAtIndexPath(indexPath)
performSegueWithIdentifier(identifier, sender: senderCell)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let zielViewController = segue.destinationViewController as? a_synchronDatenLadenVC where segue.identifier == "datenLaden" {
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)!
let titel = daten[indexPath.row]
zielViewController.titel = titel
if indexPath.row == 1 {
zielViewController.asynchron = true
}
}
}
}
| apache-2.0 | 5df68affd2e58fea5a8e48ae11bde35b | 30.197368 | 217 | 0.621257 | 4.742 | false | false | false | false |
devxin/Stanford-iOS8 | Autolayout/Autolayout/User.swift | 1 | 1135 | //
// User.swift
// Autolayout
//
// Created by XIN on 16/7/17.
// Copyright © 2016年 XIN. All rights reserved.
//
import Foundation
struct User {
let name: String
let company: String
let login: String
let password: String
static let database: Dictionary<String, User> = {
var theDatabase = Dictionary<String, User>()
for user in [
User(name: "John Appleseed", company: "Apple", login: "japple", password: "foo"),
User(name: "Madison Bumgarner", company: "World Champion San Francisco Giants", login: "madbum", password: "foo"),
User(name: "John Hennessy", company: "Stanford", login: "hennessy", password: "foo"),
User(name: "Bad Guy", company: "Criminals, Inc", login: "baddie", password: "foo"),
]{
theDatabase[user.login] = user
}
return theDatabase
}()
static func login(login: String, password: String) -> User? {
if let user = database[login] {
if user.password == password {
return user
}
}
return nil
}
} | mit | 8530a3012d08f5dba20f66933d58ace1 | 28.815789 | 126 | 0.564488 | 3.916955 | false | false | false | false |
ChatSecure/ChatSecure-Push-iOS | ChatSecurePush-SDK/Device.swift | 1 | 2932 | //
// Device.swift
// Pods
//
// Created by David Chiles on 7/7/15.
//
//
import Foundation
@objc public enum DeviceKind:Int {
case unknown = 0
case iOS = 1
case android = 2
}
public extension Data {
//https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift/40089462#40089462
func hexString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
@objc open class Device: NSObject, NSCoding, NSCopying {
@objc open var name: String?
@objc open var id: String?
@objc open var deviceID: String?
@objc open var registrationID: String
@objc open var active = true
@objc open var deviceKind = DeviceKind.unknown
@objc public let dateCreated: Date
@objc public init (registrationID: String,dateCreated: Date, name: String?, deviceID: String?, id: String?) {
self.name = name
self.dateCreated = dateCreated
self.registrationID = registrationID
self.deviceID = deviceID
self.id = id
}
public required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as? String
self.id = aDecoder.decodeObject(forKey: "id") as? String
self.deviceID = aDecoder.decodeObject(forKey: "deviceID") as? String
if let registrationID = aDecoder.decodeObject(forKey: "registrationID") as? String {
self.registrationID = registrationID
} else {
self.registrationID = ""
}
self.active = aDecoder.decodeBool(forKey: "active")
if let date = aDecoder.decodeObject(forKey: "dateCreated") as? Date {
self.dateCreated = date
} else {
self.dateCreated = Date()
}
if let deviceKindRawValue = aDecoder.decodeObject(forKey: "deviceKind") as? Int {
if let deviceKind = DeviceKind(rawValue: deviceKindRawValue) {
self.deviceKind = deviceKind
} else {
self.deviceKind = .unknown
}
} else {
self.deviceKind = .unknown
}
}
open func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.deviceID, forKey: "deviceID")
aCoder.encode(self.registrationID, forKey: "registrationID")
aCoder.encode(self.active, forKey: "active")
aCoder.encode(self.dateCreated, forKey: "dateCreated")
aCoder.encode(self.deviceKind.rawValue, forKey: "deviceKind")
}
open func copy(with zone: NSZone?) -> Any {
let newDevice = Device(registrationID: self.registrationID, dateCreated: self.dateCreated, name: self.name, deviceID: self.deviceID, id: self.deviceID)
newDevice.active = self.active
newDevice.deviceKind = self.deviceKind
return newDevice
}
}
| gpl-3.0 | 0ae8dc3c04ed5aebe5f6b82b6d9887ba | 33.093023 | 159 | 0.624829 | 4.1471 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Onboarding/OnboardingScreen.swift | 1 | 4322 | ////
/// OnboardingScreen.swift
//
class OnboardingScreen: EmptyScreen {
struct Size {
static let buttonHeight: CGFloat = 50
static let buttonInset: CGFloat = 10
static let abortButtonWidth: CGFloat = 70
}
var controllerContainer: UIView = Container()
private var buttonContainer = Container()
private var promptButton = StyledButton(style: .roundedGrayOutline)
private var nextButton = StyledButton(style: .green)
private var abortButton = StyledButton(style: .grayText)
weak var delegate: OnboardingScreenDelegate?
var hasAbortButton: Bool = false {
didSet {
updateButtonVisibility()
}
}
var canGoNext: Bool = false {
didSet {
updateButtonVisibility()
}
}
var prompt: String? {
get { return promptButton.currentTitle }
set { promptButton.title = newValue ?? InterfaceString.Onboard.CreateProfile }
}
override func setup() {
abortButton.isHidden = true
nextButton.isHidden = true
}
override func style() {
buttonContainer.backgroundColor = .greyE5
}
override func bindActions() {
promptButton.isEnabled = false
promptButton.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
nextButton.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
abortButton.addTarget(self, action: #selector(abortAction), for: .touchUpInside)
}
override func setText() {
promptButton.title = ""
nextButton.title = ""
abortButton.title = InterfaceString.Onboard.ImDone
}
override func arrange() {
super.arrange()
addSubview(controllerContainer)
addSubview(buttonContainer)
buttonContainer.addSubview(promptButton)
buttonContainer.addSubview(nextButton)
buttonContainer.addSubview(abortButton)
buttonContainer.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(self)
make.top.equalTo(keyboardAnchor.snp.top).offset(
-(2 * Size.buttonInset + Size.buttonHeight)
)
}
promptButton.snp.makeConstraints { make in
make.top.leading.trailing.equalTo(buttonContainer).inset(Size.buttonInset)
make.height.equalTo(Size.buttonHeight)
}
nextButton.snp.makeConstraints { make in
make.top.bottom.leading.equalTo(promptButton)
}
abortButton.snp.makeConstraints { make in
make.top.bottom.trailing.equalTo(promptButton)
make.leading.equalTo(nextButton.snp.trailing).offset(Size.buttonInset)
make.width.equalTo(Size.abortButtonWidth)
}
controllerContainer.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(statusBar.snp.bottom)
make.bottom.equalTo(buttonContainer.snp.top)
}
}
private func updateButtonVisibility() {
if hasAbortButton && canGoNext {
promptButton.isHidden = true
nextButton.isVisible = true
abortButton.isVisible = true
}
else {
promptButton.isEnabled = canGoNext
promptButton.style = canGoNext ? .green : .roundedGrayOutline
promptButton.isVisible = true
nextButton.isHidden = true
abortButton.isHidden = true
}
}
func styleFor(step: OnboardingStep) {
let nextString: String
switch step {
case .creatorType: nextString = InterfaceString.Onboard.CreateAccount
case .categories: nextString = InterfaceString.Onboard.CreateProfile
case .createProfile: nextString = InterfaceString.Onboard.InvitePeople
case .inviteFriends: nextString = InterfaceString.Join.Discover
}
promptButton.isVisible = true
nextButton.isHidden = true
abortButton.isHidden = true
promptButton.title = nextString
nextButton.title = nextString
}
}
extension OnboardingScreen {
@objc
func nextAction() {
delegate?.nextAction()
}
@objc
func abortAction() {
delegate?.abortAction()
}
}
extension OnboardingScreen: OnboardingScreenProtocol {}
| mit | 0904129a396c54b5b03cd9578c91fe39 | 30.318841 | 88 | 0.643683 | 4.973533 | false | false | false | false |
diogot/MyWeight | MyWeight/Screens/List/ListViewController.swift | 1 | 2943 | //
// ListViewController.swift
// MyWeight
//
// Created by Diogo on 09/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import Combine
import HealthService
import UIKit
public protocol ListViewControllerDelegate {
func didTapAddMeasure(last mass: DataPoint<UnitMass>?)
func failedToDeleteMass()
}
public class ListViewController: UIViewController {
private let healthService: HealthRepository
private var masses = [DataPoint<UnitMass>]() {
didSet {
updateView()
}
}
public var delegate: ListViewControllerDelegate?
private lazy var customView = ListView()
private var massObserverCancellable: AnyCancellable?
private var cancellables = Set<AnyCancellable>()
private var loadMassCancellable: AnyCancellable?
public required init(with healthService: HealthRepository)
{
self.healthService = healthService
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView()
{
self.view = customView
}
public override func viewDidLoad()
{
healthService.authorizationStatusPublisher(for: .mass).sink(weak: self, receiveValue: { me, _ in
me.observeMassesUpdate()
}).store(in: &cancellables)
}
func updateView()
{
let viewModel =
ListViewModel(with: masses,
didTap: { [weak self] in self?.tapAddMass() },
deleteMass: { [weak self] in self?.delete($0) })
customView.viewModel = viewModel
}
func observeMassesUpdate()
{
massObserverCancellable?.cancel()
massObserverCancellable = healthService.observeChanges(in: .mass)
.prepend(())
.flatMap { [healthService] _ in
healthService.fetchMass().catchFailureLogAndReplace(with: [])
}
.sink(
weak: self,
receiveCompletion: { _, completion in
if let error = completion.error {
Log.error(error)
}
},
receiveValue: { me, masses in
me.masses = masses
}
)
}
func tapAddMass()
{
let mass = masses.first
delegate?.didTapAddMeasure(last: mass)
}
func delete(_ mass: DataPoint<UnitMass>)
{
healthService.delete(mass)
.sink(weak: self, receiveCompletion: { me, completion in
if let error = completion.error {
me.failToDelete(error)
}
}).store(in: &cancellables)
}
func failToDelete(_ error: Error)
{
Log.debug(error)
delegate?.failedToDeleteMass()
}
}
| mit | 85a10563a87dd89187ecc6f1b700f20b | 25.504505 | 104 | 0.581577 | 4.838816 | false | false | false | false |
siuying/Alt | Pod/Classes/EventEmitter.swift | 1 | 5010 | //
// EventEmitter.swift
// Pods
//
// Created by Chan Fai Chong on 8/11/2015.
//
//
import Foundation
public class EventEmitter {
public typealias Listener = (object: AnyObject?) -> ()
let subscriber : EventSubscriptionVendor
var currentSubscription : EventSubscription?
public init() {
self.subscriber = EventSubscriptionVendor()
}
/// Adds a listener to be invoked when events of the specified type are
/// emitted. An optional calling context may be provided. The data arguments
/// emitted will be passed to the listener function.
public func addListener(eventType: String, listener: Listener) -> EventSubscription {
return self.subscriber.addSubscription(eventType, subscription: EventSubscription(subscriber: self.subscriber, listener: listener))
}
/// Similar to addListener, except that the listener is removed after it is invoked once.
public func once(eventType: String, listener: Listener) -> EventSubscription {
let internalListener : Listener = { [weak self] object in
self?.removeCurrentListener()
listener(object: object)
}
return self.subscriber.addSubscription(eventType, subscription: EventSubscription(subscriber: self.subscriber, listener: internalListener))
}
/// Remove listener with the corresponding subscription
public func removeListenerWithSubscription(subscription: EventSubscription) {
self.subscriber.removeSubscription(subscription)
}
/// Removes all of the registered listeners, including those registered as
/// listener maps.
public func removeAllListeners(eventType: String?) {
self.subscriber.removeAllSubscriptions(eventType)
}
/// Provides an API that can be called during an eventing cycle to remove the
/// last listener that was invoked. This allows a developer to provide an event
/// object that can remove the listener (or listener map) during the
/// invocation.
public func removeCurrentListener() {
guard let currentSubscription = self.currentSubscription else {
fatalError("Not in an emitting cycle; there is no current subscription")
}
self.subscriber.removeSubscription(currentSubscription)
}
/// Returns an array of listeners that are currently registered for the given event
/// @param eventType Name of the event to query
public func listeners(eventType: String) -> [Listener] {
let subscriptions = self.subscriber.getSubscriptionForType(eventType)
return subscriptions.map({ $0.listener })
}
/// Emits an event of the given type with the given data. All handlers of that
/// particular type will be notified.
public func emit(eventType: String, object: AnyObject? = nil) {
let subscriptions = self.subscriber.getSubscriptionForType(eventType)
for subscription in subscriptions {
self.currentSubscription = subscription
self.emitToSubscription(subscription, object: object)
}
self.currentSubscription = nil
}
private func emitToSubscription(subscription: EventSubscription, object: AnyObject? = nil) {
subscription.listener(object: object)
}
}
public class EventSubscription {
weak var subscriber : EventSubscriptionVendor?
public let listener : EventEmitter.Listener
public var eventType : String?
public var key : Int?
init(subscriber: EventSubscriptionVendor, listener: EventEmitter.Listener) {
self.subscriber = subscriber
self.listener = listener
}
public func remove() {
self.subscriber?.removeSubscription(self)
}
}
internal class EventSubscriptionVendor {
var subscriptionsForType : [String: [EventSubscription]] = [:]
init() {
}
func addSubscription(type: String, subscription: EventSubscription) -> EventSubscription {
if self.subscriptionsForType[type] == nil {
self.subscriptionsForType[type] = []
}
let key = self.subscriptionsForType[type]!.count
self.subscriptionsForType[type]!.append(subscription)
subscription.eventType = type
subscription.key = key
return subscription
}
func removeSubscription(subscription: EventSubscription) {
guard let eventType = subscription.eventType, let key = subscription.key else {
fatalError("missing event type / key")
}
if self.subscriptionsForType[eventType] != nil {
self.subscriptionsForType[eventType]?.removeAtIndex(key)
}
}
func removeAllSubscriptions(type: String?) {
if let type = type {
self.subscriptionsForType.removeValueForKey(type)
} else {
self.subscriptionsForType = [:]
}
}
func getSubscriptionForType(eventType: String) -> [EventSubscription] {
return self.subscriptionsForType[eventType] ?? []
}
} | mit | 446dcb0b01022bd76b8983aa3edeb5d4 | 35.576642 | 147 | 0.683234 | 5.246073 | false | false | false | false |
ohadh123/MuscleUp- | Pods/JSSAlertView/JSSAlertView/Classes/JSSAlertView+UIColor.swift | 4 | 1988 | //
// JSSAlertView+UIColor.swift
// Pods
//
// Created by Tomas Sykora, jr. on 05/11/2016.
//
//
import UIKit
// Extend UIImage with a method to create
// a UIImage from a solid color
//
// See: http://stackoverflow.com/questions/20300766/how-to-change-the-highlighted-color-of-a-uibutton
// MARK: - UIImage Extension
public extension UIImage {
class func with(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(rect)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
// For any hex code 0xXXXXXX and alpha value,
// return a matching UIColor
/// Returns Color from HEX
///
/// - Parameters:
/// - rgbValue: rgb value
/// - alpha: alpha
/// - Returns: UIColor
public func UIColorFromHex(_ rgbValue:UInt32, alpha:Double=1.0) -> UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
// For any UIColor and brightness value where darker <1
// and lighter (>1) return an altered UIColor.
//
// See: http://a2apps.com.au/lighten-or-darken-a-uicolor/
/// Adjusts brightnes
///
/// - Parameters:
/// - color: color for brightness
/// - amount: amount to adjust
/// - Returns: returns new adjusted UIColor
public func adjustBrightness(_ color:UIColor, amount:CGFloat) -> UIColor {
var hue:CGFloat = 0
var saturation:CGFloat = 0
var brightness:CGFloat = 0
var alpha:CGFloat = 0
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
brightness += (amount-1.0)
brightness = max(min(brightness, 1.0), 0.0)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
return color
}
| apache-2.0 | 70ac602fdd4f5e759320cc987ec5514a | 26.611111 | 101 | 0.701207 | 3.380952 | false | false | false | false |
jhliberty/GitLabKit | GitLabKit/ProjectOwnedQueryParamBuilders.swift | 1 | 8591 | //
// ProjectOwnedQueryParamBuilders.swift
// GitLabKit
//
// Copyright (c) 2015 orih. All rights reserved.
//
// 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 class ProjectOwnedQueryParamBuilder: GeneralQueryParamBuilder, GitLabParamBuildable {
init(projectId: UInt) {
super.init()
params["projectId"] = projectId
}
init(projectName: String, namespace: String) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
}
}
// MARK: ProjectIssues
public class ProjectIssueQueryParamBuilder : IssueQueryParamBuilder {
init(projectId: UInt) {
super.init()
params["projectId"] = projectId
}
init(projectName: String, namespace: String) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
}
public func issueId(issueId: UInt) -> Self {
if params["issueId"]? != nil {
return self
}
params["issueId"] = issueId
return self
}
public func milestone(milestone: String) -> Self {
if !milestone.isEmpty {
params["milestone"] = milestone.trim()
}
return self
}
}
// MARK: ProjectMembers
public class ProjectMemberQueryParamBuilder : ProjectOwnedQueryParamBuilder {
public func userId(userId: UInt) -> Self {
if params["userId"]? != nil {
return self
}
params["userId"] = userId
return self
}
}
// MARK: ProjectEvents
public class ProjectEventQueryParamBuilder: ProjectOwnedQueryParamBuilder {}
// MARK: ProjectMergeRequests
public class ProjectMergeRequestQueryParamBuilder: ProjectOwnedQueryParamBuilder {
public func state(state: MergeRequestState) -> Self {
params["state"] = state.rawValue
return self
}
public func orderBy(order: MergeRequestOrderBy?) -> Self {
params["order_by"] = order? == nil ? nil : order!.rawValue
return self
}
public func sort(sort: MergeRequestSort?) -> Self {
params["sort"] = sort? == nil ? nil : sort!.rawValue
return self
}
}
// MARK: ProjectBranches
public class ProjectBranchQueryParamBuilder : ProjectOwnedQueryParamBuilder {
public func branchName(name: String) -> Self {
if params["name"]? != nil {
return self
}
params["name"] = name
return self
}
}
// MARK: ProjectHooks
public class ProjectHookQueryParamBuilder: ProjectOwnedQueryParamBuilder {
public func hookId(hookId: UInt) -> Self {
if params["hookId"]? != nil {
return self
}
params["hookId"] = hookId
return self
}
}
// MARK: ProjectSnippets
public class ProjectSnippetQueryParamBuilder: ProjectOwnedQueryParamBuilder {
public func snippetId(snippetId: UInt) -> Self {
if params["snippetId"]? != nil {
return self
}
params["snippetId"] = snippetId
return self
}
}
// MARK: ProjectFiles
public class ProjectFileQueryParamBuilder: GeneralQueryParamBuilder, GitLabParamBuildable {
/**
initializer
:param: projectId
:param: filePath Full path to new file. Ex. lib/class.rb
:param: ref The name of branch, tag or commit
:returns: ProjectFileQueryParamBuilder
*/
init(projectId: UInt, filePath: String, ref: String) {
super.init()
params["projectId"] = projectId
params["file_path"] = filePath
params["ref"] = ref
}
init(projectName: String, namespace: String, filePath: String, ref: String) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
params["file_path"] = filePath
params["ref"] = ref
}
}
// MARK: ProjectTags
public class ProjectTagQueryParamBuilder: ProjectOwnedQueryParamBuilder {}
// MARK: ProjectTrees
public class ProjectTreeQueryParamBuilder: ProjectOwnedQueryParamBuilder {
/**
Specify the path inside repository
:param: path The path inside repository. Used to get contend of subdirectories
*/
public func path(path: String) -> Self {
params["path"] = path
return self
}
/**
Specify the name of a repository branch or tag
:param: refName The name of a repository branch or tag or if not given the default branch
*/
public func refName(refName: String) -> Self {
params["refName"] = refName
return self
}
}
// MARK: ProjectCommits
public class ProjectCommitQueryParamBuilder: ProjectOwnedQueryParamBuilder {
/**
Specify the name of a repository branch or tag
:param: refName The name of a repository branch or tag or if not given the default branch
*/
public func refName(refName: String) -> Self {
params["refName"] = refName
return self
}
public func sha(sha: String) -> Self {
params["sha"] = sha
return self
}
}
// MARK: Comment For ProjectCommits
public class ProjectCommentForCommitQueryParamBuilder: GeneralQueryParamBuilder, GitLabParamBuildable {
init(projectId: UInt, commitSha: String) {
super.init()
params["projectId"] = projectId
params["sha"] = commitSha
}
init(projectName: String, namespace: String, commitSha: String) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
params["sha"] = commitSha
}
}
// MARK: Comment For ProjectIssues
public class ProjectCommentForIssueQueryParamBuilder : IssueQueryParamBuilder {
init(projectId: UInt, issueId: UInt) {
super.init()
params["projectId"] = projectId
params["issueId"] = issueId
}
init(projectName: String, namespace: String, issueId: UInt) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
params["issueId"] = issueId
}
public func noteId(noteId: String) -> Self {
if params["noteId"]? != nil {
return self
}
params["noteId"] = noteId
return self
}
}
// MARK: Comment For ProjectSnippets
public class ProjectCommentForSnippetQueryParamBuilder : IssueQueryParamBuilder {
init(projectId: UInt, snippetId: UInt) {
super.init()
params["projectId"] = projectId
params["snippetId"] = snippetId
}
init(projectName: String, namespace: String, snippetId: UInt) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
params["snippetId"] = snippetId
}
public func noteId(noteId: String) -> Self {
if params["noteId"]? != nil {
return self
}
params["noteId"] = noteId
return self
}
}
// MARK: ProjectDiff
public class ProjectDiffQueryParamBuilder: ProjectCommentForCommitQueryParamBuilder {}
// MARK: ProjectRawfile
// TODO: Handle Project Rawfile
// Raw file content
// Raw blob content
// Get file archive
/*public class ProjectRawfileQueryParamBuilder : GeneralQueryParamBuilder, GitLabParamBuildable {
init(projectId: UInt, sha: String, filePath: String) {
super.init()
params["projectId"] = projectId
}
init(projectName: String, namespace: String, sha: String, filePath: String) {
super.init()
params["namespaceAndName"] = "\(namespace)/\(projectName)"
}
public func build() -> [String : AnyObject]? {
return params
}
}*/ | mit | 42dc5091d87a493436b172b9aabbd74e | 27.832215 | 103 | 0.647189 | 4.584312 | false | false | false | false |
imzyf/99-projects-of-swift | 024-3d-touch-quick-action/024-3d-touch-quick-action/AppDelegate.swift | 1 | 1261 | //
// AppDelegate.swift
// 024-3d-touch-quick-action
//
// Created by moma on 2018/2/9.
// Copyright © 2018年 yifans. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if window?.traitCollection.forceTouchCapability == .available {
setup3DTouch(application)
}
return true
}
fileprivate func setup3DTouch(_ application: UIApplication) {
let loveActionIcon = UIApplicationShortcutIcon(type: .love)
let loveItem = UIApplicationShortcutItem(type: "LoveItem", localizedTitle: "Love Action", localizedSubtitle: nil, icon: loveActionIcon, userInfo: nil)
application.shortcutItems = [loveItem]
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ShortcutAction"), object: nil, userInfo: ["shortcutItem": shortcutItem])
}
}
| mit | 665456ad869535f729173d22dd79be24 | 33 | 158 | 0.701908 | 5.032 | false | false | false | false |
Erez-Panda/LiveBankSDK | Pod/Classes/LinearInterpView.swift | 1 | 2643 | //
// LinearInterpView.swift
// Panda4rep
//
// Created by Erez Haim on 5/8/15.
// Copyright (c) 2015 Erez. All rights reserved.
//
import UIKit
class LinearInterpView: UIView {
var path : UIBezierPath?
var enabled = true
var points: Array<Array<CGPoint>> = []
var blockTouches = false
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
SignColors.sharedInstance.uicolorFromHex(0x000F7D).setStroke()
path?.stroke()
// Drawing code
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.multipleTouchEnabled = false
self.backgroundColor = UIColor.clearColor()
path = UIBezierPath()
path?.lineWidth = 2.0
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !blockTouches{
super.touchesBegan(touches, withEvent: event)
}
if (enabled){
if let touch: UITouch = touches.first{
let touchLocation = touch.locationInView(self) as CGPoint
path?.moveToPoint(touchLocation)
path?.addLineToPoint(CGPointMake(touchLocation.x+1, touchLocation.y+1))
points.append([touchLocation])
self.setNeedsDisplay()
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !blockTouches{
super.touchesEnded(touches, withEvent: event)
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if !blockTouches{
super.touchesCancelled(touches, withEvent: event)
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if !blockTouches{
super.touchesMoved(touches, withEvent: event)
}
if (enabled){
if let touch: UITouch = touches.first{
if #available(iOS 9.0, *) {
//print(touch.force)
} else {
// Fallback on earlier versions
}
let touchLocation = touch.locationInView(self) as CGPoint
path?.addLineToPoint(touchLocation)
points[points.count-1].append(touchLocation)
self.setNeedsDisplay()
}
}
}
func cleanView(){
self.path?.removeAllPoints()
points = []
self.setNeedsDisplay()
}
}
| mit | fcd565444a87ba597e992efc1c6c54a3 | 29.732558 | 87 | 0.584185 | 4.876384 | false | false | false | false |
melling/ios_topics | CenteredAutoLayoutButton/CenteredAutoLayoutButton/ViewController.swift | 1 | 1894 | //
// ViewController.swift
// CenteredAutoLayoutButton
//
// Created by Michael Mellinger on 8/14/14.
//
import UIKit
class ViewController: UIViewController {
private let button = UIButton()
private func addButton() {
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.borderWidth = 1
button.layer.cornerRadius = 10
button.setTitle("Am I centered?", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(pressed(_:)), for: .touchUpInside)
view.addSubview(button)
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
button.widthAnchor.constraint(equalToConstant: 130),
])
}
@objc private func pressed(_ sender: UIButton!) {
let title = "Awesome"
let message = "You did it"
let alert = UIAlertController(title: title,
message:message,
preferredStyle: .alert)
let action = UIAlertAction(title: "Take Action 1?", style: .default, handler:nil)
alert.addAction(action)
let action2 = UIAlertAction(title: "Take Action 2?", style: .default, handler:nil)
alert.addAction(action2)
self.present(alert, animated: true, completion: nil)
}
// MARK: - View Management
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(named: "AppleBlue")
addButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cc0-1.0 | 57454d055f7c4536251776a117bf2184 | 27.268657 | 90 | 0.598205 | 5.160763 | false | false | false | false |
Bersaelor/SwiftyHYGDB | Sources/SwiftyHYGDB/RadialStar+Codable.swift | 1 | 1309 | //
// Star+Codable.swift
//
// Created by Konrad Feiler on 28.08.17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
extension RadialStar: Codable {
private enum CodingKeys: String, CodingKey {
case normalizedAscension = "nA"
case normalizedDeclination = "nD"
case starData = "s"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
normalizedAscension = try container.decode(Float.self, forKey: .normalizedAscension)
normalizedDeclination = try container.decode(Float.self, forKey: .normalizedDeclination)
let starValue: StarData = try container.decode(StarData.self, forKey: .starData)
starData = Box(starValue)
}
public func encode(to encoder: Encoder) throws {
guard let value = starData?.value else {
print("Failed to decode starData's value for star")
return
}
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(normalizedAscension, forKey: .normalizedAscension)
try container.encode(normalizedDeclination, forKey: .normalizedDeclination)
try container.encode(value, forKey: .starData)
}
}
| mit | 5ef2ef76823d1d3c91d16e4735685f84 | 36.371429 | 98 | 0.665902 | 4.331126 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Model/Keyframes/KeyframeData.swift | 3 | 3330 | //
// Keyframe.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
import CoreGraphics
import Foundation
// MARK: - KeyframeData
/// A generic class used to parse and remap keyframe json.
///
/// Keyframe json has a couple of different variations and formats depending on the
/// type of keyframea and also the version of the JSON. By parsing the raw data
/// we can reconfigure it into a constant format.
final class KeyframeData<T> {
// MARK: Lifecycle
init(
startValue: T?,
endValue: T?,
time: AnimationFrameTime?,
hold: Int?,
inTangent: LottieVector2D?,
outTangent: LottieVector2D?,
spatialInTangent: LottieVector3D?,
spatialOutTangent: LottieVector3D?)
{
self.startValue = startValue
self.endValue = endValue
self.time = time
self.hold = hold
self.inTangent = inTangent
self.outTangent = outTangent
self.spatialInTangent = spatialInTangent
self.spatialOutTangent = spatialOutTangent
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case startValue = "s"
case endValue = "e"
case time = "t"
case hold = "h"
case inTangent = "i"
case outTangent = "o"
case spatialInTangent = "ti"
case spatialOutTangent = "to"
}
/// The start value of the keyframe
let startValue: T?
/// The End value of the keyframe. Note: Newer versions animation json do not have this field.
let endValue: T?
/// The time in frames of the keyframe.
let time: AnimationFrameTime?
/// A hold keyframe freezes interpolation until the next keyframe that is not a hold.
let hold: Int?
/// The in tangent for the time interpolation curve.
let inTangent: LottieVector2D?
/// The out tangent for the time interpolation curve.
let outTangent: LottieVector2D?
/// The spacial in tangent of the vector.
let spatialInTangent: LottieVector3D?
/// The spacial out tangent of the vector.
let spatialOutTangent: LottieVector3D?
var isHold: Bool {
if let hold = hold {
return hold > 0
}
return false
}
}
// MARK: Encodable
extension KeyframeData: Encodable where T: Encodable { }
// MARK: Decodable
extension KeyframeData: Decodable where T: Decodable { }
// MARK: DictionaryInitializable
extension KeyframeData: DictionaryInitializable where T: AnyInitializable {
convenience init(dictionary: [String: Any]) throws {
let startValue = try? dictionary[CodingKeys.startValue.rawValue].flatMap(T.init)
let endValue = try? dictionary[CodingKeys.endValue.rawValue].flatMap(T.init)
let time: AnimationFrameTime? = try? dictionary.value(for: CodingKeys.time)
let hold: Int? = try? dictionary.value(for: CodingKeys.hold)
let inTangent: LottieVector2D? = try? dictionary.value(for: CodingKeys.inTangent)
let outTangent: LottieVector2D? = try? dictionary.value(for: CodingKeys.outTangent)
let spatialInTangent: LottieVector3D? = try? dictionary.value(for: CodingKeys.spatialInTangent)
let spatialOutTangent: LottieVector3D? = try? dictionary.value(for: CodingKeys.spatialOutTangent)
self.init(
startValue: startValue,
endValue: endValue,
time: time,
hold: hold,
inTangent: inTangent,
outTangent: outTangent,
spatialInTangent: spatialInTangent,
spatialOutTangent: spatialOutTangent)
}
}
| apache-2.0 | b5ed3b1f7622b9d20071a06d4077b960 | 28.469027 | 101 | 0.70961 | 3.978495 | false | false | false | false |
DroidsOnRoids/TwitterLogIn | twittersdksample/Application View Controllers/LoginViewController/Views/LoginButton/LoginButton.swift | 1 | 736 | //
// LoginButton.swift
// twittersdksample
//
// Created by Paweł Sternik on 07.12.2015.
// Copyright © 2015 Paweł Sternik. All rights reserved.
//
import UIKit
class LoginButton: UIButton {
// MARK: Initial methods
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
func setup() {
setTitleColor(.whiteColor(), forState: .Normal)
layer.borderWidth = 2.0
layer.cornerRadius = 5.0
layer.masksToBounds = true
layer.borderColor = UIColor.whiteColor().CGColor
backgroundColor = .twitterColor()
}
}
| mit | 943e815cdce53e8c7c64a96605cbf3da | 19.361111 | 56 | 0.607094 | 4.094972 | false | false | false | false |
DrabWeb/Komikan | Komikan/Komikan/KMSearchListItemData.swift | 1 | 962 | //
// KMGroupListItemData.swift
// Komikan
//
// Created by Seth on 2016-02-14.
//
import Cocoa
class KMSearchListItemData: NSObject {
/// The name of this item
var name : String = "";
/// Is this item checked off?
var checked : Bool = true;
/// How many manga have this items property?
var count : Int = 0;
/// The type this item is
var type : KMPropertyType?;
// A simple init with no parameters
override init() {
self.name = "";
self.checked = false;
}
// An init with just a name
init(name : String) {
self.name = name;
}
// An init with a name and type
init(name : String, type : KMPropertyType) {
self.name = name;
self.type = type;
}
// An init with a group name and defining if its checked off
init(name : String, checked : Bool) {
self.name = name;
self.checked = checked;
}
}
| gpl-3.0 | 057326920f1697da8dc9cf96be3f7466 | 20.377778 | 64 | 0.557173 | 3.926531 | false | false | false | false |
gpbl/SwiftChart | Source/Chart.swift | 1 | 26890 | //
// Chart.swift
//
// Created by Giampaolo Bellavite on 07/11/14.
// Copyright (c) 2014 Giampaolo Bellavite. All rights reserved.
//
import UIKit
public protocol ChartDelegate: class {
/**
Tells the delegate that the specified chart has been touched.
- parameter chart: The chart that has been touched.
- parameter indexes: Each element of this array contains the index of the data that has been touched, one for each
series. If the series hasn't been touched, its index will be nil.
- parameter x: The value on the x-axis that has been touched.
- parameter left: The distance from the left side of the chart.
*/
func didTouchChart(_ chart: Chart, indexes: [Int?], x: Double, left: CGFloat)
/**
Tells the delegate that the user finished touching the chart. The user will
"finish" touching the chart only swiping left/right outside the chart.
- parameter chart: The chart that has been touched.
*/
func didFinishTouchingChart(_ chart: Chart)
/**
Tells the delegate that the user ended touching the chart. The user
will "end" touching the chart whenever the touchesDidEnd method is
being called.
- parameter chart: The chart that has been touched.
*/
func didEndTouchingChart(_ chart: Chart)
}
/**
Represent the x- and the y-axis values for each point in a chart series.
*/
typealias ChartPoint = (x: Double, y: Double)
/**
Set the a x-label orientation.
*/
public enum ChartLabelOrientation {
case horizontal
case vertical
}
@IBDesignable
open class Chart: UIControl {
// MARK: Options
@IBInspectable
open var identifier: String?
/**
Series to display in the chart.
*/
open var series: [ChartSeries] = [] {
didSet {
DispatchQueue.main.async {
self.setNeedsDisplay()
}
}
}
/**
The values to display as labels on the x-axis. You can format these values with the `xLabelFormatter` attribute.
As default, it will display the values of the series which has the most data.
*/
open var xLabels: [Double]?
/**
Formatter for the labels on the x-axis. `index` represents the `xLabels` index, `value` its value.
*/
open var xLabelsFormatter = { (labelIndex: Int, labelValue: Double) -> String in
String(Int(labelValue))
}
/**
Text alignment for the x-labels.
*/
open var xLabelsTextAlignment: NSTextAlignment = .left
/**
Orientation for the x-labels.
*/
open var xLabelsOrientation: ChartLabelOrientation = .horizontal
/**
Skip the last x-label. Setting this to false may make the label overflow the frame width.
*/
open var xLabelsSkipLast: Bool = true
/**
Values to display as labels of the y-axis. If not specified, will display the lowest, the middle and the highest
values.
*/
open var yLabels: [Double]?
/**
Formatter for the labels on the y-axis.
*/
open var yLabelsFormatter = { (labelIndex: Int, labelValue: Double) -> String in
String(Int(labelValue))
}
/**
Displays the y-axis labels on the right side of the chart.
*/
open var yLabelsOnRightSide: Bool = false
/**
Font used for the labels.
*/
open var labelFont: UIFont? = UIFont.systemFont(ofSize: 12)
/**
The color used for the labels.
*/
@IBInspectable
open var labelColor: UIColor = UIColor.black
/**
Color for the axes.
*/
@IBInspectable
open var axesColor: UIColor = UIColor.gray.withAlphaComponent(0.3)
/**
Color for the grid.
*/
@IBInspectable
open var gridColor: UIColor = UIColor.gray.withAlphaComponent(0.3)
/**
Enable the lines for the labels on the x-axis
*/
open var showXLabelsAndGrid: Bool = true
/**
Enable the lines for the labels on the y-axis
*/
open var showYLabelsAndGrid: Bool = true
/**
Height of the area at the bottom of the chart, containing the labels for the x-axis.
*/
open var bottomInset: CGFloat = 20
/**
Height of the area at the top of the chart, acting a padding to make place for the top y-axis label.
*/
open var topInset: CGFloat = 20
/**
Width of the chart's lines.
*/
@IBInspectable
open var lineWidth: CGFloat = 2
/**
Delegate for listening to Chart touch events.
*/
weak open var delegate: ChartDelegate?
/**
Custom minimum value for the x-axis.
*/
open var minX: Double?
/**
Custom minimum value for the y-axis.
*/
open var minY: Double?
/**
Custom maximum value for the x-axis.
*/
open var maxX: Double?
/**
Custom maximum value for the y-axis.
*/
open var maxY: Double?
/**
Color for the highlight line.
*/
open var highlightLineColor = UIColor.gray
/**
Width for the highlight line.
*/
open var highlightLineWidth: CGFloat = 0.5
/**
Hide the highlight line when touch event ends, e.g. when stop swiping over the chart
*/
open var hideHighlightLineOnTouchEnd = false
/**
Alpha component for the area color.
*/
open var areaAlphaComponent: CGFloat = 0.1
// MARK: Private variables
fileprivate var highlightShapeLayer: CAShapeLayer!
fileprivate var layerStore: [CAShapeLayer] = []
fileprivate var drawingHeight: CGFloat!
fileprivate var drawingWidth: CGFloat!
// Minimum and maximum values represented in the chart
fileprivate var min: ChartPoint!
fileprivate var max: ChartPoint!
// Represent a set of points corresponding to a segment line on the chart.
typealias ChartLineSegment = [ChartPoint]
// MARK: initializations
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
convenience public init() {
self.init(frame: .zero)
commonInit()
}
private func commonInit() {
backgroundColor = UIColor.clear
contentMode = .redraw // redraw rects on bounds change
}
override open func draw(_ rect: CGRect) {
#if TARGET_INTERFACE_BUILDER
drawIBPlaceholder()
#else
drawChart()
#endif
}
/**
Adds a chart series.
*/
open func add(_ series: ChartSeries) {
self.series.append(series)
}
/**
Adds multiple chart series.
*/
open func add(_ series: [ChartSeries]) {
for s in series {
add(s)
}
}
/**
Remove the series at the specified index.
*/
open func removeSeriesAt(_ index: Int) {
series.remove(at: index)
}
/**
Remove all the series.
*/
open func removeAllSeries() {
series = []
}
/**
Return the value for the specified series at the given index.
*/
open func valueForSeries(_ seriesIndex: Int, atIndex dataIndex: Int?) -> Double? {
if dataIndex == nil { return nil }
let series = self.series[seriesIndex] as ChartSeries
return series.data[dataIndex!].y
}
fileprivate func drawIBPlaceholder() {
let placeholder = UIView(frame: self.frame)
placeholder.backgroundColor = UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1)
let label = UILabel()
label.text = "Chart"
label.font = UIFont.systemFont(ofSize: 28)
label.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2)
label.sizeToFit()
label.frame.origin.x += frame.width/2 - (label.frame.width / 2)
label.frame.origin.y += frame.height/2 - (label.frame.height / 2)
placeholder.addSubview(label)
addSubview(placeholder)
}
fileprivate func drawChart() {
drawingHeight = bounds.height - bottomInset - topInset
drawingWidth = bounds.width
let minMax = getMinMax()
min = minMax.min
max = minMax.max
highlightShapeLayer = nil
// Remove things before drawing, e.g. when changing orientation
for view in self.subviews {
view.removeFromSuperview()
}
for layer in layerStore {
layer.removeFromSuperlayer()
}
layerStore.removeAll()
// Draw content
for (index, series) in self.series.enumerated() {
// Separate each line in multiple segments over and below the x axis
let segments = Chart.segmentLine(series.data as ChartLineSegment, zeroLevel: series.colors.zeroLevel)
segments.forEach({ segment in
let scaledXValues = scaleValuesOnXAxis( segment.map { $0.x } )
let scaledYValues = scaleValuesOnYAxis( segment.map { $0.y } )
if series.line {
drawLine(scaledXValues, yValues: scaledYValues, seriesIndex: index)
}
if series.area {
drawArea(scaledXValues, yValues: scaledYValues, seriesIndex: index)
}
})
}
drawAxes()
if showXLabelsAndGrid && (xLabels != nil || series.count > 0) {
drawLabelsAndGridOnXAxis()
}
if showYLabelsAndGrid && (yLabels != nil || series.count > 0) {
drawLabelsAndGridOnYAxis()
}
}
// MARK: - Scaling
fileprivate func getMinMax() -> (min: ChartPoint, max: ChartPoint) {
// Start with user-provided values
var min = (x: minX, y: minY)
var max = (x: maxX, y: maxY)
// Check in datasets
for series in self.series {
let xValues = series.data.map { $0.x }
let yValues = series.data.map { $0.y }
let newMinX = xValues.minOrZero()
let newMinY = yValues.minOrZero()
let newMaxX = xValues.maxOrZero()
let newMaxY = yValues.maxOrZero()
if min.x == nil || newMinX < min.x! { min.x = newMinX }
if min.y == nil || newMinY < min.y! { min.y = newMinY }
if max.x == nil || newMaxX > max.x! { max.x = newMaxX }
if max.y == nil || newMaxY > max.y! { max.y = newMaxY }
}
// Check in labels
if let xLabels = self.xLabels {
let newMinX = xLabels.minOrZero()
let newMaxX = xLabels.maxOrZero()
if min.x == nil || newMinX < min.x! { min.x = newMinX }
if max.x == nil || newMaxX > max.x! { max.x = newMaxX }
}
if let yLabels = self.yLabels {
let newMinY = yLabels.minOrZero()
let newMaxY = yLabels.maxOrZero()
if min.y == nil || newMinY < min.y! { min.y = newMinY }
if max.y == nil || newMaxY > max.y! { max.y = newMaxY }
}
if min.x == nil { min.x = 0 }
if min.y == nil { min.y = 0 }
if max.x == nil { max.x = 0 }
if max.y == nil { max.y = 0 }
return (min: (x: min.x!, y: min.y!), max: (x: max.x!, max.y!))
}
fileprivate func scaleValuesOnXAxis(_ values: [Double]) -> [Double] {
let width = Double(drawingWidth)
var factor: Double
if max.x - min.x == 0 {
factor = 0
} else {
factor = width / (max.x - min.x)
}
let scaled = values.map { factor * ($0 - self.min.x) }
return scaled
}
fileprivate func scaleValuesOnYAxis(_ values: [Double]) -> [Double] {
let height = Double(drawingHeight)
var factor: Double
if max.y - min.y == 0 {
factor = 0
} else {
factor = height / (max.y - min.y)
}
let scaled = values.map { Double(self.topInset) + height - factor * ($0 - self.min.y) }
return scaled
}
fileprivate func scaleValueOnYAxis(_ value: Double) -> Double {
let height = Double(drawingHeight)
var factor: Double
if max.y - min.y == 0 {
factor = 0
} else {
factor = height / (max.y - min.y)
}
let scaled = Double(self.topInset) + height - factor * (value - min.y)
return scaled
}
fileprivate func getZeroValueOnYAxis(zeroLevel: Double) -> Double {
if min.y > zeroLevel {
return scaleValueOnYAxis(min.y)
} else {
return scaleValueOnYAxis(zeroLevel)
}
}
// MARK: - Drawings
fileprivate func drawLine(_ xValues: [Double], yValues: [Double], seriesIndex: Int) {
// YValues are "reverted" from top to bottom, so 'above' means <= level
let isAboveZeroLine = yValues.max()! <= self.scaleValueOnYAxis(series[seriesIndex].colors.zeroLevel)
let path = CGMutablePath()
path.move(to: CGPoint(x: CGFloat(xValues.first!), y: CGFloat(yValues.first!)))
for i in 1..<yValues.count {
let y = yValues[i]
path.addLine(to: CGPoint(x: CGFloat(xValues[i]), y: CGFloat(y)))
}
let lineLayer = CAShapeLayer()
lineLayer.frame = self.bounds
lineLayer.path = path
if isAboveZeroLine {
lineLayer.strokeColor = series[seriesIndex].colors.above.cgColor
} else {
lineLayer.strokeColor = series[seriesIndex].colors.below.cgColor
}
lineLayer.fillColor = nil
lineLayer.lineWidth = lineWidth
lineLayer.lineJoin = CAShapeLayerLineJoin.bevel
self.layer.addSublayer(lineLayer)
layerStore.append(lineLayer)
}
fileprivate func drawArea(_ xValues: [Double], yValues: [Double], seriesIndex: Int) {
// YValues are "reverted" from top to bottom, so 'above' means <= level
let isAboveZeroLine = yValues.max()! <= self.scaleValueOnYAxis(series[seriesIndex].colors.zeroLevel)
let area = CGMutablePath()
let zero = CGFloat(getZeroValueOnYAxis(zeroLevel: series[seriesIndex].colors.zeroLevel))
area.move(to: CGPoint(x: CGFloat(xValues[0]), y: zero))
for i in 0..<xValues.count {
area.addLine(to: CGPoint(x: CGFloat(xValues[i]), y: CGFloat(yValues[i])))
}
area.addLine(to: CGPoint(x: CGFloat(xValues.last!), y: zero))
let areaLayer = CAShapeLayer()
areaLayer.frame = self.bounds
areaLayer.path = area
areaLayer.strokeColor = nil
if isAboveZeroLine {
areaLayer.fillColor = series[seriesIndex].colors.above.withAlphaComponent(areaAlphaComponent).cgColor
} else {
areaLayer.fillColor = series[seriesIndex].colors.below.withAlphaComponent(areaAlphaComponent).cgColor
}
areaLayer.lineWidth = 0
self.layer.addSublayer(areaLayer)
layerStore.append(areaLayer)
}
fileprivate func drawAxes() {
let context = UIGraphicsGetCurrentContext()!
context.setStrokeColor(axesColor.cgColor)
context.setLineWidth(0.5)
// horizontal axis at the bottom
context.move(to: CGPoint(x: CGFloat(0), y: drawingHeight + topInset))
context.addLine(to: CGPoint(x: CGFloat(drawingWidth), y: drawingHeight + topInset))
context.strokePath()
// horizontal axis at the top
context.move(to: CGPoint(x: CGFloat(0), y: CGFloat(0)))
context.addLine(to: CGPoint(x: CGFloat(drawingWidth), y: CGFloat(0)))
context.strokePath()
// horizontal axis when y = 0
if min.y < 0 && max.y > 0 {
let y = CGFloat(getZeroValueOnYAxis(zeroLevel: 0))
context.move(to: CGPoint(x: CGFloat(0), y: y))
context.addLine(to: CGPoint(x: CGFloat(drawingWidth), y: y))
context.strokePath()
}
// vertical axis on the left
context.move(to: CGPoint(x: CGFloat(0), y: CGFloat(0)))
context.addLine(to: CGPoint(x: CGFloat(0), y: drawingHeight + topInset))
context.strokePath()
// vertical axis on the right
context.move(to: CGPoint(x: CGFloat(drawingWidth), y: CGFloat(0)))
context.addLine(to: CGPoint(x: CGFloat(drawingWidth), y: drawingHeight + topInset))
context.strokePath()
}
fileprivate func drawLabelsAndGridOnXAxis() {
let context = UIGraphicsGetCurrentContext()!
context.setStrokeColor(gridColor.cgColor)
context.setLineWidth(0.5)
var labels: [Double]
if xLabels == nil {
// Use labels from the first series
labels = series[0].data.map({ (point: ChartPoint) -> Double in
return point.x })
} else {
labels = xLabels!
}
let scaled = scaleValuesOnXAxis(labels)
let padding: CGFloat = 5
scaled.enumerated().forEach { (i, value) in
let x = CGFloat(value)
let isLastLabel = x == drawingWidth
// Add vertical grid for each label, except axes on the left and right
if x != 0 && x != drawingWidth {
context.move(to: CGPoint(x: x, y: CGFloat(0)))
context.addLine(to: CGPoint(x: x, y: bounds.height))
context.strokePath()
}
if xLabelsSkipLast && isLastLabel {
// Do not add label at the most right position
return
}
// Add label
let label = UILabel(frame: CGRect(x: x, y: drawingHeight, width: 0, height: 0))
label.font = labelFont
label.text = xLabelsFormatter(i, labels[i])
label.textColor = labelColor
// Set label size
label.sizeToFit()
// Center label vertically
label.frame.origin.y += topInset
if xLabelsOrientation == .horizontal {
// Add left padding
label.frame.origin.y -= (label.frame.height - bottomInset) / 2
label.frame.origin.x += padding
// Set label's text alignment
label.frame.size.width = (drawingWidth / CGFloat(labels.count)) - padding * 2
label.textAlignment = xLabelsTextAlignment
} else {
label.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
// Adjust vertical position according to the label's height
label.frame.origin.y += label.frame.size.height / 2
// Adjust horizontal position as the series line
label.frame.origin.x = x
if xLabelsTextAlignment == .center {
// Align horizontally in series
label.frame.origin.x += ((drawingWidth / CGFloat(labels.count)) / 2) - (label.frame.size.width / 2)
} else {
// Give some space from the vertical line
label.frame.origin.x += padding
}
}
self.addSubview(label)
}
}
fileprivate func drawLabelsAndGridOnYAxis() {
let context = UIGraphicsGetCurrentContext()!
context.setStrokeColor(gridColor.cgColor)
context.setLineWidth(0.5)
var labels: [Double]
if yLabels == nil {
labels = [(min.y + max.y) / 2, max.y]
if yLabelsOnRightSide || min.y != 0 {
labels.insert(min.y, at: 0)
}
} else {
labels = yLabels!
}
let scaled = scaleValuesOnYAxis(labels)
let padding: CGFloat = 5
let zero = CGFloat(getZeroValueOnYAxis(zeroLevel: 0))
scaled.enumerated().forEach { (i, value) in
let y = CGFloat(value)
// Add horizontal grid for each label, but not over axes
if y != drawingHeight + topInset && y != zero {
context.move(to: CGPoint(x: CGFloat(0), y: y))
context.addLine(to: CGPoint(x: self.bounds.width, y: y))
if labels[i] != 0 {
// Horizontal grid for 0 is not dashed
context.setLineDash(phase: CGFloat(0), lengths: [CGFloat(5)])
} else {
context.setLineDash(phase: CGFloat(0), lengths: [])
}
context.strokePath()
}
let label = UILabel(frame: CGRect(x: padding, y: y, width: 0, height: 0))
label.font = labelFont
label.text = yLabelsFormatter(i, labels[i])
label.textColor = labelColor
label.sizeToFit()
if yLabelsOnRightSide {
label.frame.origin.x = drawingWidth
label.frame.origin.x -= label.frame.width + padding
}
// Labels should be placed above the horizontal grid
label.frame.origin.y -= label.frame.height
self.addSubview(label)
}
UIGraphicsEndImageContext()
}
// MARK: - Touch events
fileprivate func drawHighlightLineFromLeftPosition(_ left: CGFloat) {
if let shapeLayer = highlightShapeLayer {
// Use line already created
let path = CGMutablePath()
path.move(to: CGPoint(x: left, y: 0))
path.addLine(to: CGPoint(x: left, y: drawingHeight + topInset))
shapeLayer.path = path
} else {
// Create the line
let path = CGMutablePath()
path.move(to: CGPoint(x: left, y: CGFloat(0)))
path.addLine(to: CGPoint(x: left, y: drawingHeight + topInset))
let shapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = path
shapeLayer.strokeColor = highlightLineColor.cgColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = highlightLineWidth
highlightShapeLayer = shapeLayer
layer.addSublayer(shapeLayer)
layerStore.append(shapeLayer)
}
}
func handleTouchEvents(_ touches: Set<UITouch>, event: UIEvent!) {
let point = touches.first!
let left = point.location(in: self).x
let x = valueFromPointAtX(left)
if left < 0 || left > (drawingWidth as CGFloat) {
// Remove highlight line at the end of the touch event
if let shapeLayer = highlightShapeLayer {
shapeLayer.path = nil
}
delegate?.didFinishTouchingChart(self)
return
}
drawHighlightLineFromLeftPosition(left)
if delegate == nil {
return
}
var indexes: [Int?] = []
for series in self.series {
var index: Int? = nil
let xValues = series.data.map({ (point: ChartPoint) -> Double in
return point.x })
let closest = Chart.findClosestInValues(xValues, forValue: x)
if closest.lowestIndex != nil && closest.highestIndex != nil {
// Consider valid only values on the right
index = closest.lowestIndex
}
indexes.append(index)
}
delegate!.didTouchChart(self, indexes: indexes, x: x, left: left)
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouchEvents(touches, event: event)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouchEvents(touches, event: event)
if self.hideHighlightLineOnTouchEnd {
if let shapeLayer = highlightShapeLayer {
shapeLayer.path = nil
}
}
delegate?.didEndTouchingChart(self)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
handleTouchEvents(touches, event: event)
}
// MARK: - Utilities
fileprivate func valueFromPointAtX(_ x: CGFloat) -> Double {
let value = ((max.x-min.x) / Double(drawingWidth)) * Double(x) + min.x
return value
}
fileprivate func valueFromPointAtY(_ y: CGFloat) -> Double {
let value = ((max.y - min.y) / Double(drawingHeight)) * Double(y) + min.y
return -value
}
fileprivate class func findClosestInValues(
_ values: [Double],
forValue value: Double
) -> (
lowestValue: Double?,
highestValue: Double?,
lowestIndex: Int?,
highestIndex: Int?
) {
var lowestValue: Double?, highestValue: Double?, lowestIndex: Int?, highestIndex: Int?
values.enumerated().forEach { (i, currentValue) in
if currentValue <= value && (lowestValue == nil || lowestValue! < currentValue) {
lowestValue = currentValue
lowestIndex = i
}
if currentValue >= value && (highestValue == nil || highestValue! > currentValue) {
highestValue = currentValue
highestIndex = i
}
}
return (
lowestValue: lowestValue,
highestValue: highestValue,
lowestIndex: lowestIndex,
highestIndex: highestIndex
)
}
/**
Segment a line in multiple lines when the line touches the x-axis, i.e. separating
positive from negative values.
*/
fileprivate class func segmentLine(_ line: ChartLineSegment, zeroLevel: Double) -> [ChartLineSegment] {
var segments: [ChartLineSegment] = []
var segment: ChartLineSegment = []
line.enumerated().forEach { (i, point) in
segment.append(point)
if i < line.count - 1 {
let nextPoint = line[i+1]
if point.y >= zeroLevel && nextPoint.y < zeroLevel || point.y < zeroLevel && nextPoint.y >= zeroLevel {
// The segment intersects zeroLevel, close the segment with the intersection point
let closingPoint = Chart.intersectionWithLevel(point, and: nextPoint, level: zeroLevel)
segment.append(closingPoint)
segments.append(segment)
// Start a new segment
segment = [closingPoint]
}
} else {
// End of the line
segments.append(segment)
}
}
return segments
}
/**
Return the intersection of a line between two points and 'y = level' line
*/
fileprivate class func intersectionWithLevel(_ p1: ChartPoint, and p2: ChartPoint, level: Double) -> ChartPoint {
let dy1 = level - p1.y
let dy2 = level - p2.y
return (x: (p2.x * dy1 - p1.x * dy2) / (dy1 - dy2), y: level)
}
}
extension Sequence where Element == Double {
func minOrZero() -> Double {
return self.min() ?? 0.0
}
func maxOrZero() -> Double {
return self.max() ?? 0.0
}
}
| mit | 2dbc48505e2640ecf3bbdc473cfe6e4f | 30.59812 | 119 | 0.578617 | 4.408919 | false | false | false | false |
SwiftAndroid/swift-jni | JNI.swift | 1 | 2253 | @_exported import CJNI // Clang module
public class JNI {
/// Our reference to the Java Virtual Machine, to be set on init
let _jvm: UnsafeMutablePointer<JavaVM>
/// Ensure the _env pointer we have is always attached to the JVM
var _env: UnsafeMutablePointer<JNIEnv> {
let jvm = _jvm.memory.memory
// The type `JNIEnv` is defined as a non-mutable pointer,
// so use this mutable _tmpPointer as an intermediate:
var _tmpPointer = UnsafeMutablePointer<Void>()
let threadStatus = jvm.GetEnv(_jvm, &_tmpPointer, jint(JNI_VERSION_1_6))
var _env = UnsafeMutablePointer<JNIEnv>(_tmpPointer)
switch threadStatus {
case JNI_OK: break // if we're already attached, do nothing
case JNI_EDETACHED:
// We weren't attached to the Java UI thread
jvm.AttachCurrentThread(_jvm, &_env, nil)
case JNI_EVERSION:
fatalError("This version of JNI is not supported")
default: break
}
return _env
}
// Normally we init the jni global ourselves in JNI_OnLoad
public init?(jvm: UnsafeMutablePointer<JavaVM>) {
if jvm == nil { return nil }
self._jvm = jvm
}
}
public extension JNI {
public func GetVersion() -> jint {
let env = self._env
return env.memory.memory.GetVersion(env)
}
public func GetJavaVM(vm: UnsafeMutablePointer<UnsafeMutablePointer<JavaVM>>) -> jint {
let env = self._env
return env.memory.memory.GetJavaVM(env, vm)
}
public func RegisterNatives(targetClass: jclass, _ methods: UnsafePointer<JNINativeMethod>, _ nMethods: jint) -> jint {
let env = self._env
return env.memory.memory.RegisterNatives(env, targetClass, methods, nMethods)
}
public func UnregisterNatives(targetClass: jclass) -> jint {
let env = self._env
return env.memory.memory.UnregisterNatives(env, targetClass)
}
public func MonitorEnter(obj: jobject) -> jint {
let env = self._env
return env.memory.memory.MonitorEnter(env, obj)
}
public func MonitorExit(obj: jobject) -> jint {
let env = self._env
return env.memory.memory.MonitorExit(env, obj)
}
}
| apache-2.0 | 111fe2c7a2c328ddc4aff8efe3e0c108 | 32.626866 | 123 | 0.637816 | 3.994681 | false | false | false | false |
multinerd/Mia | Mia/Testing/Material/MaterialColorGroupWithAccents.swift | 1 | 1901 | //
// MaterialColorGroupWithAccents.swift
// Mia
//
// Created by Michael Hedaitulla on 8/2/18.
//
import Foundation
open class MaterialColorGroupWithAccents: MaterialColorGroup {
open let A100: MaterialColor
open let A200: MaterialColor
open let A400: MaterialColor
open let A700: MaterialColor
open var accents: [MaterialColor] {
return [A100, A200, A400, A700]
}
open override var hashValue: Int {
return super.hashValue + accents.reduce(0) { $0 + $1.hashValue }
}
open override var endIndex: Int {
return colors.count + accents.count
}
open override subscript(i: Int) -> MaterialColor {
return (colors + accents)[i]
}
internal init(name: String,
_ P50: MaterialColor,
_ P100: MaterialColor,
_ P200: MaterialColor,
_ P300: MaterialColor,
_ P400: MaterialColor,
_ P500: MaterialColor,
_ P600: MaterialColor,
_ P700: MaterialColor,
_ P800: MaterialColor,
_ P900: MaterialColor,
_ A100: MaterialColor,
_ A200: MaterialColor,
_ A400: MaterialColor,
_ A700: MaterialColor
) {
self.A100 = A100
self.A200 = A200
self.A400 = A400
self.A700 = A700
super.init(name: name, P50, P100, P200, P300, P400, P500, P600, P700, P800, P900)
}
open override func colorForName(_ name: String) -> MaterialColor? {
return (colors + accents).filter { $0.name == name}.first
}
}
func ==(lhs: MaterialColorGroupWithAccents, rhs: MaterialColorGroupWithAccents) -> Bool {
return (lhs as MaterialColorGroup) == (rhs as MaterialColorGroup) &&
lhs.accents == rhs.accents
}
| mit | 66f93fa354de1c22ce4e0020d0efbec3 | 29.174603 | 89 | 0.56181 | 4.205752 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/ConversationViewController+NavigationBar.swift | 1 | 10584 | //
// 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 UIKit
import WireSyncEngine
import WireCommonComponents
// MARK: - Update left navigator bar item when size class changes
extension ConversationViewController {
typealias IconColors = SemanticColors.Icon
typealias ButtonColors = SemanticColors.Button
typealias CallActions = L10n.Localizable.Call.Actions
func addCallStateObserver() -> Any? {
return conversation.voiceChannel?.addCallStateObserver(self)
}
var audioCallButton: UIButton {
let button = IconButton()
button.setIcon(.phone, size: .tiny, for: .normal)
button.setIconColor(IconColors.foregroundDefault, for: .normal)
button.accessibilityIdentifier = "audioCallBarButton"
button.accessibilityTraits.insert(.startsMediaSession)
button.accessibilityLabel = CallActions.Label.makeAudioCall
button.addTarget(self, action: #selector(ConversationViewController.voiceCallItemTapped(_:)), for: .touchUpInside)
button.backgroundColor = ButtonColors.backgroundBarItem
button.layer.borderWidth = 1
button.setBorderColor(ButtonColors.borderBarItem, for: .normal)
button.layer.cornerRadius = 12
button.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)
button.bounds.size = button.systemLayoutSizeFitting(CGSize(width: .max, height: 32))
return button
}
var videoCallButton: UIButton {
let button = IconButton()
button.setIcon(.camera, size: .tiny, for: .normal)
button.setIconColor(IconColors.foregroundDefault, for: .normal)
button.accessibilityIdentifier = "videoCallBarButton"
button.accessibilityTraits.insert(.startsMediaSession)
button.accessibilityLabel = CallActions.Label.makeVideoCall
button.addTarget(self, action: #selector(ConversationViewController.videoCallItemTapped(_:)), for: .touchUpInside)
button.backgroundColor = ButtonColors.backgroundBarItem
button.layer.borderWidth = 1
button.setBorderColor(ButtonColors.borderBarItem, for: .normal)
button.layer.cornerRadius = 12
button.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner]
button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)
button.bounds.size = button.systemLayoutSizeFitting(CGSize(width: .max, height: 32))
return button
}
private var audioAndVideoCallButtons: UIView {
let buttonStack = UIStackView(frame: CGRect(x: 0, y: 0, width: 80, height: 32))
buttonStack.distribution = .fillEqually
buttonStack.spacing = 0
buttonStack.axis = .horizontal
buttonStack.addArrangedSubview(videoCallButton)
buttonStack.addArrangedSubview(audioCallButton)
let buttonsView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 32))
buttonsView.addSubview(buttonStack)
return buttonsView
}
var joinCallButton: UIBarButtonItem {
let button = IconButton(fontSpec: .smallSemiboldFont)
button.adjustsTitleWhenHighlighted = true
button.adjustBackgroundImageWhenHighlighted = true
button.setTitle("conversation_list.right_accessory.join_button.title".localized(uppercased: true), for: .normal)
button.accessibilityLabel = "conversation.join_call.voiceover".localized
button.accessibilityTraits.insert(.startsMediaSession)
button.backgroundColor = SemanticColors.LegacyColors.strongLimeGreen
button.addTarget(self, action: #selector(joinCallButtonTapped), for: .touchUpInside)
button.contentEdgeInsets = UIEdgeInsets(top: 2, left: 8, bottom: 2, right: 8)
button.bounds.size = button.systemLayoutSizeFitting(CGSize(width: .max, height: 24))
button.layer.cornerRadius = button.bounds.height / 2
return UIBarButtonItem(customView: button)
}
var backButton: UIBarButtonItem {
let hasUnreadInOtherConversations = self.conversation.hasUnreadMessagesInOtherConversations
let arrowIcon: StyleKitIcon = view.isRightToLeft
? (hasUnreadInOtherConversations ? .forwardArrowWithDot : .forwardArrow)
: (hasUnreadInOtherConversations ? .backArrowWithDot : .backArrow)
let icon: StyleKitIcon = (self.parent?.wr_splitViewController?.layoutSize == .compact) ? arrowIcon : .hamburger
let action = #selector(ConversationViewController.onBackButtonPressed(_:))
let button = UIBarButtonItem(icon: icon, target: self, action: action)
button.accessibilityIdentifier = "ConversationBackButton"
button.accessibilityLabel = "general.back".localized
if hasUnreadInOtherConversations {
button.tintColor = UIColor.accent()
button.accessibilityValue = "conversation_list.voiceover.unread_messages.hint".localized
}
return button
}
var shouldShowCollectionsButton: Bool {
guard
SecurityFlags.forceEncryptionAtRest.isEnabled == false,
session.encryptMessagesAtRest == false
else {
return false
}
switch self.conversation.conversationType {
case .group: return true
case .oneOnOne:
if let connection = conversation.connection,
connection.status != .pending && connection.status != .sent {
return true
} else {
return nil != conversation.teamRemoteIdentifier
}
default: return false
}
}
func rightNavigationItems(forConversation conversation: ZMConversation) -> [UIBarButtonItem] {
guard !conversation.isReadOnly, conversation.localParticipants.count != 0 else { return [] }
if conversation.canJoinCall {
return [joinCallButton]
} else if conversation.isCallOngoing {
return []
} else if conversation.canStartVideoCall {
let barButtonItems = UIBarButtonItem(customView: audioAndVideoCallButtons)
return [barButtonItems]
} else {
let barButtonItem = UIBarButtonItem(customView: audioCallButton)
return [barButtonItem]
}
}
func leftNavigationItems(forConversation conversation: ZMConversation) -> [UIBarButtonItem] {
var items: [UIBarButtonItem] = []
if self.parent?.wr_splitViewController?.layoutSize != .regularLandscape {
items.append(backButton)
}
if shouldShowCollectionsButton {
items.append(searchBarButtonItem)
}
return items
}
func updateRightNavigationItemsButtons() {
navigationItem.rightBarButtonItems = rightNavigationItems(forConversation: conversation)
}
/// Update left navigation bar items
func updateLeftNavigationBarItems() {
navigationItem.leftBarButtonItems = leftNavigationItems(forConversation: conversation)
}
@objc
func voiceCallItemTapped(_ sender: UIBarButtonItem) {
endEditing()
startCallController.startAudioCall(started: ConversationInputBarViewController.endEditingMessage)
}
@objc func videoCallItemTapped(_ sender: UIBarButtonItem) {
endEditing()
startCallController.startVideoCall(started: ConversationInputBarViewController.endEditingMessage)
}
@objc private dynamic func joinCallButtonTapped(_sender: AnyObject!) {
startCallController.joinCall()
}
@objc func dismissCollectionIfNecessary() {
if let collectionController = self.collectionController {
collectionController.dismiss(animated: false)
}
}
}
extension ConversationViewController: CollectionsViewControllerDelegate {
func collectionsViewController(_ viewController: CollectionsViewController, performAction action: MessageAction, onMessage message: ZMConversationMessage) {
switch action {
case .forward:
viewController.dismissIfNeeded(animated: true) {
self.contentViewController.scroll(to: message) { cell in
self.contentViewController.showForwardFor(message: message, from: cell)
}
}
case .showInConversation:
viewController.dismissIfNeeded(animated: true) {
self.contentViewController.scroll(to: message) { _ in
self.contentViewController.highlight(message)
}
}
case .reply:
viewController.dismissIfNeeded(animated: true) {
self.contentViewController.scroll(to: message) { cell in
self.contentViewController.perform(action: .reply, for: message, view: cell)
}
}
default:
contentViewController.perform(action: action, for: message, view: view)
}
}
}
extension ConversationViewController: WireCallCenterCallStateObserver {
public func callCenterDidChange(callState: CallState, conversation: ZMConversation, caller: UserType, timestamp: Date?, previousCallState: CallState?) {
updateRightNavigationItemsButtons()
}
}
extension ZMConversation {
/// Whether there is an incoming or inactive incoming call that can be joined.
var canJoinCall: Bool {
return voiceChannel?.state.canJoinCall ?? false
}
var canStartVideoCall: Bool {
return !isCallOngoing
}
var isCallOngoing: Bool {
return voiceChannel?.state.isCallOngoing ?? true
}
}
extension CallState {
var canJoinCall: Bool {
switch self {
case .incoming: return true
default: return false
}
}
var isCallOngoing: Bool {
switch self {
case .none, .incoming: return false
default: return true
}
}
}
| gpl-3.0 | d965fbc6688403fbde137d167ecde546 | 36.66548 | 160 | 0.686602 | 5.125424 | false | false | false | false |
ortizraf/macsoftwarecenter | Mac Application Store/AppDelegate.swift | 1 | 10896 | //
// AppDelegate.swift
// Mac Software Center
//
// Created by Rafael Ortiz.
// Copyright © 2017 Nextneo. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSViewController, NSApplicationDelegate, NSUserNotificationCenterDelegate {
var applications = [App]()
var categories = [Category]()
var organizations = [Organization]()
var softwareInfos = [SoftwareInfo]()
let baseURL = "https://raw.githubusercontent.com/ortizraf/macsoftwarecenter/master/files/macsoftwarecenter.json"
func applicationWillFinishLaunching(_ notification: Notification) {
createTable()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
func createTable(){
print("creating table")
let dbCategory = CategoryDB()
dbCategory.dropTable()
let dbOrganization = OrganizationDB()
dbOrganization.dropTable()
let dbApp = AppDB()
dbApp.dropTable()
let dbSoftwareInfo = SoftwareInfoDB()
dbSoftwareInfo.dropTable()
dbCategory.createTable()
dbOrganization.createTable()
dbApp.createTable()
dbSoftwareInfo.createTable()
getRequestData()
print("table created successfull")
}
func getRequestData(){
let url = NSURL(string: baseURL)
let request = NSURLRequest(url: url! as URL)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request as URLRequest) { (data,response,error) -> Void in
if error == nil {
do {
if data?.count != 0 {
if let dataCategory = data,
let jsonCategories = try JSONSerialization.jsonObject(with: dataCategory) as? [String: Any],
let categories = jsonCategories["category"] as? [[String: Any]] {
for cat in categories {
let category = Category()
if let catId = cat["id"] as? Int {
category.id = catId
}
if let catName = cat["name"] as? String {
category.name = catName
}
if let catActive = cat["isActive"] as? Bool {
category.active = catActive
}
self.categories.append(category)
}
}
if let dataOrganization = data,
let jsonOrganizations = try JSONSerialization.jsonObject(with: dataOrganization) as? [String: Any],
let organizations = jsonOrganizations["organization"] as? [[String: Any]] {
for org in organizations {
let organization = Organization()
if let orgId = org["id"] as? Int {
organization.id = orgId
}
if let orgName = org["name"] as? String {
organization.name = orgName
}
self.organizations.append(organization)
}
}
if let dataApp = data,
let jsonApp = try JSONSerialization.jsonObject(with: dataApp) as? [String: Any],
let apps = jsonApp["app"] as? [[String: Any]] {
for app in apps {
let application = App()
if let name = app["name"] as? String {
application.name = name
}
if let image = app["url_image"] as? String {
application.url_image = image
}
if let link = app["download_link"] as? String {
application.download_link = link
}
if let categoryId = app["category_id"] as? Int {
let category = Category()
category.id = categoryId
application.category = category
}
if let is_active = app["is_active"] as? Bool {
application.is_active = is_active
}
if let description = app["description"] as? String {
application.description = description
}
if let version = app["version"] as? String {
application.version = version
}
if let last_update = app["last_update"] as? String {
application.last_update_text = last_update
}
if let organizationId = app["organization_id"] as? Int {
let organization = Organization()
organization.id = organizationId
application.organization = organization
}
if let website = app["website"] as? String {
application.website = website
}
if let order_by = app["order_by"] as? Int {
application.order_by = order_by
}
if let file_format = app["file_format"] as? String {
application.file_format = file_format
}
self.applications.append(application)
}
}
if let dataSoftwareInfo = data,
let jsonSoftwareInfos = try JSONSerialization.jsonObject(with: dataSoftwareInfo) as? [String: Any],
let softwareInfos = jsonSoftwareInfos["software_info"] as? [[String: Any]] {
for softinfo in softwareInfos {
let softwareInfo = SoftwareInfo()
if let softinfoId = softinfo["id"] as? Int {
softwareInfo.id = softinfoId
}
if let softinfoVersion = softinfo["version"] as? String {
softwareInfo.version = softinfoVersion
}
if let softinfoVersionBuild = softinfo["versionBuild"] as? Int {
softwareInfo.versionBuild = softinfoVersionBuild
}
if let softinfoDescription = softinfo["description"] as? String {
softwareInfo.description = softinfoDescription
}
if let softinfoDownloadLink = softinfo["downloadLink"] as? String {
softwareInfo.download_link = softinfoDownloadLink
}
if let softinfoInformationLink = softinfo["informationLink"] as? String {
softwareInfo.information_link = softinfoInformationLink
}
if let softinfoLicenseLink = softinfo["licenseLink"] as? String {
softwareInfo.license_link = softinfoLicenseLink
}
if let softindoDateUpdate = softinfo["dateUpdate"] as? String {
softwareInfo.date_update_text = softindoDateUpdate
}
self.softwareInfos.append(softwareInfo)
}
}
} else {
print("no data")
}
} catch {
print("Error deserializing JSON: \(error)")
}
for category in self.categories {
self.insertDataCategory(category: category)
}
for organization in self.organizations {
self.insertDataOrganization(organization: organization)
}
for app in self.applications {
self.insertDataApp(app: app)
}
for softwareInfo in self.softwareInfos {
self.insertDataSoftwareInfo(softwareInfo: softwareInfo)
}
} else{
print("Error")
}
}
task.resume()
}
func insertDataCategory(category: Category){
let dbCategory = CategoryDB()
dbCategory.save(category: category)
}
func insertDataOrganization(organization: Organization){
let dbOrganization = OrganizationDB()
dbOrganization.save(organization: organization)
}
func insertDataApp(app: App){
let dbApp = AppDB()
dbApp.save(app: app)
}
func insertDataSoftwareInfo(softwareInfo: SoftwareInfo){
let dbSoftwareInfo = SoftwareInfoDB()
dbSoftwareInfo.save(softwareInfo: softwareInfo)
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSUserNotificationCenter.default.delegate = self
}
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
}
| gpl-3.0 | bfbee2f547c769197b5a17a01f30b5dd | 43.835391 | 127 | 0.430564 | 6.667687 | false | false | false | false |
benlangmuir/swift | validation-test/Sema/type_checker_perf/fast/rdar22282851.swift | 25 | 312 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan
struct S {
let s: String
}
func rdar22282851(_ a: [S]) -> [S] {
let result = a.filter { $0.s == "hello" }.sorted { $0.s < $1.s || ($0.s == $1.s && $0.s < $1.s) && $0.s >= $1.s }
return result
}
| apache-2.0 | b90b6cbdcf08b8f0cc178a68b72d81aa | 27.363636 | 115 | 0.570513 | 2.4375 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Style/WPStyleGuide+AlertView.swift | 2 | 1225 | import Foundation
import WordPressShared
extension WPStyleGuide {
public struct AlertView {
// MARK: - Title Styles
public static let titleRegularFont = WPStyleGuide.fontForTextStyle(.callout, fontWeight: .light)
public static let titleColor = UIColor.neutral(.shade30)
// MARK: - Detail Styles
public static let detailsRegularFont = WPStyleGuide.fontForTextStyle(.footnote)
public static let detailsBoldFont = WPStyleGuide.fontForTextStyle(.footnote, fontWeight: .semibold)
public static let detailsColor = UIColor.neutral(.shade70)
public static let detailsRegularAttributes: [NSAttributedString.Key: Any] = [.font: detailsRegularFont,
.foregroundColor: detailsColor]
public static let detailsBoldAttributes: [NSAttributedString.Key: Any] = [.font: detailsBoldFont,
.foregroundColor: detailsColor]
// MARK: - Button Styles
public static let buttonFont = WPFontManager.systemRegularFont(ofSize: 16)
}
}
| gpl-2.0 | c2759fdda1de5d79bfedba601a9b3cab | 48 | 117 | 0.6 | 6.282051 | false | false | false | false |
CJGitH/QQMusic | QQMusic/Classes/QQList/View/QQMusicListCell.swift | 1 | 2308 | //
// QQMusicListCell.swift
// QQMusic
//
// Created by chen on 16/5/16.
// Copyright © 2016年 chen. All rights reserved.
//
import UIKit
enum AnimatonType {
case Rotation
case Translation
}
class QQMusicListCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var songNameLabel: UILabel!
@IBOutlet weak var singerNameLabel: UILabel!
var musicM: QQMusicModel? {
didSet {
if musicM?.icon != nil {
iconImageView.image = UIImage(named: (musicM?.icon)!)
}
songNameLabel.text = musicM?.name
singerNameLabel.text = musicM?.singer
}
}
class func cellWithTableView(tableView: UITableView) -> QQMusicListCell {
let cellID = "musicList"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? QQMusicListCell
if cell == nil {
print("创建了cell")
cell = NSBundle.mainBundle().loadNibNamed("QQMusicListCell", owner: nil , options: nil).first as? QQMusicListCell
}
return cell!
}
//做动画
func beginAnimation(type: AnimatonType) -> () {
switch type {
case .Rotation:
self.layer.removeAnimationForKey("rotation")
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.values = [M_PI * 0.25, 0]
animation.duration = 0.2
self.layer.addAnimation(animation, forKey: "rotation")
case .Translation:
self.layer.removeAnimationForKey("translation")
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.values = [60, 0]
animation.duration = 0.2
self.layer.addAnimation(animation, forKey: "translation")
}
}
override func awakeFromNib() {
super.awakeFromNib()
iconImageView.layer.cornerRadius = iconImageView.width * 0.5
iconImageView.layer.masksToBounds = true
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
}
}
| mit | 2a048b357fb213dff8b90ce45b742c45 | 24.764045 | 125 | 0.570868 | 5.017505 | false | false | false | false |
magnetsystems/message-samples-ios | Soapbox/Pods/MagnetMaxCore/MagnetMax/Core/MMUser.swift | 2 | 9272 | /*
* Copyright (c) 2015 Magnet Systems, Inc.
* 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 extension MMUser {
/// The currently logged-in user or nil.
static private var currentlyLoggedInUser: MMUser?
/**
Registers a new user.
- Parameters:
- success: A block object to be executed when the registration finishes successfully. This block has no return value and takes one argument: the newly created user.
- failure: A block object to be executed when the registration finishes with an error. This block has no return value and takes one argument: the error object.
*/
public func register(success: ((user: MMUser) -> Void)?, failure: ((error: NSError) -> Void)?) {
assert(!userName.isEmpty && !password.isEmpty, "userName or password cannot be empty")
MMCoreConfiguration.serviceAdapter.registerUser(self, success: { user in
success?(user: user)
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
/**
Logs in as an user.
- Parameters:
- credential: A credential object containing the user's userName and password.
- success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments.
- failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func login(credential: NSURLCredential, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) {
login(credential, rememberMe: false, success: success, failure: failure)
}
/**
Logs in as an user.
- Parameters:
- credential: A credential object containing the user's userName and password.
- rememberMe: A boolean indicating if the user should stay logged in across app restarts.
- success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments.
- failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func login(credential: NSURLCredential, rememberMe: Bool, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) {
MMCoreConfiguration.serviceAdapter.loginWithUsername(credential.user, password: credential.password, rememberMe: rememberMe, success: { _ in
// Get current user now
MMCoreConfiguration.serviceAdapter.getCurrentUserWithSuccess({ user -> Void in
// Reset the state
userTokenExpired(nil)
currentlyLoggedInUser = user
let userInfo = ["userID": user.userID, "deviceID": MMServiceAdapter.deviceUUID(), "token": MMCoreConfiguration.serviceAdapter.HATToken]
NSNotificationCenter.defaultCenter().postNotificationName(MMServiceAdapterDidReceiveHATTokenNotification, object: self, userInfo: userInfo)
// Register for token expired notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userTokenExpired:", name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil)
success?()
}, failure: { error in
failure?(error: error)
}).executeInBackground(nil)
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
/**
Acts as the userToken expired event receiver.
- Parameters:
- notification: The notification that was received.
*/
@objc static private func userTokenExpired(notification: NSNotification?) {
currentlyLoggedInUser = nil
// Unregister for token expired notification
NSNotificationCenter.defaultCenter().removeObserver(self, name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil)
}
/**
Logs out a currently logged-in user.
*/
static public func logout() {
logout(nil, failure: nil)
}
/**
Logs out a currently logged-in user.
- Parameters:
- success: A block object to be executed when the logout finishes successfully. This block has no return value and takes no arguments.
- failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func logout(success: (() -> Void)?, failure: ((error: NSError) -> Void)?) {
if currentUser() == nil {
success?()
return
}
userTokenExpired(nil)
MMCoreConfiguration.serviceAdapter.logoutWithSuccess({ _ in
success?()
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
/**
Get the currently logged-in user.
- Returns: The currently logged-in user or nil.
*/
static public func currentUser() -> MMUser? {
return currentlyLoggedInUser
}
/**
Search for users based on some criteria.
- Parameters:
- query: The DSL can be found here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax
- limit: The number of records to retrieve.
- offset: The offset to start from.
- sort: The sort criteria.
- success: A block object to be executed when the call finishes successfully. This block has no return value and takes one argument: the list of users that match the specified criteria.
- failure: A block object to be executed when the call finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func searchUsers(query: String, limit take: Int, offset skip: Int, sort: String, success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) {
let userService = MMUserService()
userService.searchUsers(query, take: Int32(take), skip: Int32(skip), sort: sort, success: { users in
success?(users)
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
/**
Get users with userNames.
- Parameters:
- userNames: A list of userNames to fetch users for.
- success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userNames.
- failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func usersWithUserNames(userNames:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) {
let userService = MMUserService()
userService.getUsersByUserNames(userNames, success: { users in
success?(users)
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
/**
Get users with userIDs.
- Parameters:
- userNames: A list of userIDs to fetch users for.
- success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userIDs.
- failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object.
*/
static public func usersWithUserIDs(userIDs:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) {
let userService = MMUserService()
userService.getUsersByUserIds(userIDs, success: { users in
success?(users)
}) { error in
failure?(error: error)
}.executeInBackground(nil)
}
override public func isEqual(object: AnyObject?) -> Bool {
if let rhs = object as? MMUser {
return userID != nil && userID == rhs.userID
}
return false
}
override var hash: Int {
return userID != nil ? userID.hashValue : ObjectIdentifier(self).hashValue
}
}
| apache-2.0 | ff2b60e22d9256fa095614446aa30ea3 | 44.45098 | 197 | 0.638374 | 5.061135 | false | false | false | false |
wanliming11/MurlocAlgorithms | Last/Algorithms/BST/BST/BST/BST.swift | 1 | 4070 | //
// Created by FlyingPuPu on 06/12/2016.
// Copyright (c) 2016 FlyingPuPu. All rights reserved.
//
import Foundation
//因为接下来的实现中,需要使用> < = 之类的比较,所以类型需要实现comparable协议。
public enum BSTree<T:Comparable> {
/*
三种形态: 空, 叶子, 节点(包含左子节点或者右节点)
两种计算值: 数目,高度
操作: 插入, 搜索,是否包含,
扩展:debug
*/
case Empty
case Leaf(T)
indirect case Node(BSTree, T, BSTree)
//计算BST的数目
public var count: Int {
switch self {
case .Empty:
return 0
case .Leaf:
return 1
case let .Node(left, _, right):
return 1 + left.count + right.count
}
}
public var height: Int {
switch self {
case .Empty:
return 0
case .Leaf:
return 1
case .Node(let left, _, let right):
return 1 + max(left.height, right.height)
}
}
public func insert(_ element: T) -> BSTree {
switch self {
case .Empty:
return .Leaf(element)
case .Leaf(let value):
//大于当前值,插入到右节点,反之都插入到左节点
if element > value {
return .Node(.Empty, value, BSTree.Leaf(element))
} else {
return .Node(BSTree.Leaf(element), value, .Empty)
}
case .Node(let left, let value, let right):
//新插入的值
if element < value {
return .Node(left.insert(element), value, right)
} else {
return .Node(left, value, right.insert(element))
}
}
}
public func search(_ element: T) -> BSTree? {
switch self {
case .Empty: return nil
case .Leaf(let value):
if value == element {
return self
} else {
return nil
}
case .Node(let left, let value, let right):
if value == element {
return self
} else if element > value {
return right.search(element)
} else {
return left.search(element)
}
}
}
public func isContains(_ element: T) -> Bool {
return search(element) != nil
}
//依赖深度O(h)
public func minimum() -> BSTree {
//记录一个当前和一个以前的,因为如果以前的左子树是一个叶子,则直接返回prev
var current = self
var prev = self
while case let .Node(left, _, _) = current {
prev = current //先把以前的记录下来
current = left //然后把当前的内容作为下一次的循环条件
}
//找到是叶子节点的时候则跳出来了
if case .Leaf = current {
return current
}
return prev
}
public func maximum() -> BSTree {
//记录一个当前和一个以前的,因为如果以前的左子树是一个叶子,则直接返回prev
var current = self
var prev = self
while case let .Node(_, _, right) = current {
prev = current //先把以前的记录下来
current = right //然后把当前的内容作为下一次的循环条件
}
//找到是叶子节点的时候则跳出来了
if case .Leaf = current {
return current
}
return prev
}
}
extension BSTree: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .Empty:
return "."
case .Leaf(let value):
return "\(value)"
case .Node(let left, let value, let right):
return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))"
}
}
}
| mit | 745526901d5ac3551e89910e80314ad4 | 24.824818 | 88 | 0.488129 | 4.029613 | false | false | false | false |
karavakis/simply_counted | simply_counted/ClassTableViewController.swift | 1 | 2693 | //
// ClassTableViewController.swift
// simply_counted
//
// Created by Jennifer Karavakis on 8/21/16.
// Copyright © 2017 Jennifer Karavakis. All rights reserved.
//
import UIKit
class ClassTableViewController: UITableViewController {
@IBOutlet weak var classTableView: UITableView!
var classes = ClassCollection()
var fullClientList = ClientCollection()
var isLoading = false
func classesDidLoad() -> Void {
isLoading = false
classTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
isLoading = true
classes.load(classesDidLoad)
}
//TODO: Don't load events here, find a way to just load new ones.
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.view.backgroundColor = UIColor.white
self.tabBarController?.navigationItem.title = "Classes"
if( !isLoading ) {
isLoading = true
classes.load(classesDidLoad)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
if isLoading {
return 0
}
else {
return 1
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return classes.count()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : SimpleLabelTableViewCell
cell = tableView.dequeueReusableCell(withIdentifier: "ClassCell") as! SimpleLabelTableViewCell
//TODO add errors
if let classDate = classes[indexPath.row] {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.full
dateFormatter.timeStyle = DateFormatter.Style.none
cell.label.text = dateFormatter.string(from: classDate.date)
cell.label2.text = String(classDate.checkIns.count)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
if (segue.identifier == "classClicked") {
let controller = (segue.destination as! ClientTableViewController)
let row = self.classTableView.indexPathForSelectedRow!.row
let classDate = classes[row]
if let classDate = classDate {
controller.classDate = classDate
controller.fullClientList = fullClientList
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 1a1d622fcb9227c3895349a43ce3a63f | 27.638298 | 109 | 0.634101 | 5.206963 | false | false | false | false |
xwu/swift | test/Index/local.swift | 4 | 5348 | // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck -check-prefix=CHECK %s
// RUN: %target-swift-ide-test -print-indexed-symbols -include-locals -source-filename %s | %FileCheck -check-prefix=LOCAL %s
func foo(a: Int, b: Int, c: Int) {
// CHECK-NOT: [[@LINE-1]]:10 | function/acc-get/Swift | getter:a
// CHECK-NOT: [[@LINE-1]]:10 | function/acc-set/Swift | setter:a
let x = a + b
// LOCAL: [[@LINE-1]]:9 | variable(local)/Swift | x | [[x_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:9 | variable(local)/Swift | x | {{.*}} | Def,RelChild | rel: 1
// LOCAL-NOT: [[@LINE-3]]:13 | function/acc-get/Swift | getter:a
let y = x + c
// LOCAL: [[@LINE-1]]:9 | variable(local)/Swift | y | [[y_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:9 | variable(local)/Swift | y | {{.*}} | Def,RelChild | rel: 1
// LOCAL: [[@LINE-3]]:13 | variable(local)/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-4]]:13 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
struct LocalStruct {
// LOCAL: [[@LINE-1]]:12 | struct(local)/Swift | LocalStruct | [[LocalStruct_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:12 | struct(local)/Swift | LocalStruct | {{.*}} | Def,RelChild | rel: 1
let member = 2
// LOCAL: [[@LINE-1]]:13 | instance-property(local)/Swift | member | {{.*}} | Def,RelChild | rel: 1
// LOCAL-NEXT: RelChild | struct(local)/Swift | LocalStruct | [[LocalStruct_USR]]
// CHECK-NOT: [[@LINE-3]]:13 | instance-property(local)/Swift | member | {{.*}} | Def,RelChild | rel: 1
}
enum LocalEnum {
// LOCAL: [[@LINE-1]]:10 | enum(local)/Swift | LocalEnum | [[LocalEnum_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:10 | enum(local)/Swift | LocalEnum | {{.*}} | Def,RelChild | rel: 1
case foo(x: LocalStruct)
// LOCAL: [[@LINE-1]]:14 | enumerator(local)/Swift | foo(x:) | [[LocalEnum_foo_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:14 | enumerator(local)/Swift | foo(x:) | {{.*}} | Def,RelChild | rel: 1
// LOCAL: [[@LINE-3]]:21 | struct(local)/Swift | LocalStruct | [[LocalStruct_USR]] | Ref,RelCont | rel: 1
}
let _ = LocalEnum.foo(x: LocalStruct())
// LOCAL: [[@LINE-1]]:13 | enum(local)/Swift | LocalEnum | [[LocalEnum_USR]] | Ref,RelCont | rel: 1
// CHECK-NOT: [[@LINE-2]]:13 | enum(local)/Swift | LocalEnum | {{.*}} | Ref,RelCont | rel: 1
// LOCAL: [[@LINE-3]]:23 | enumerator(local)/Swift | foo(x:) | [[LocalEnum_foo_USR]] | Ref,RelCont | rel: 1
// CHECK-NOT: [[@LINE-4]]:23 | enumerator(local)/Swift | foo(x:) | {{.*}} | Ref,RelCont | rel: 1
// LOCAL: [[@LINE-5]]:30 | struct(local)/Swift | LocalStruct | [[LocalStruct_USR]] | Ref,RelCont | rel: 1
// CHECK-NOT: [[@LINE-6]]:30 | struct(local)/Swift | LocalStruct | {{.*}} | Ref,RelCont | rel: 1
}
func bar(arg: Int?) {
switch arg {
case let .some(x) where x == 0:
// LOCAL: [[@LINE-1]]:18 | variable(local)/Swift | x | [[x_USR:.*]] | Def,RelChild | rel: 1
// LOCAL: [[@LINE-2]]:27 | variable(local)/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-3]]:18 | variable(local)/Swift | x | {{.*}} | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-4]]:27 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
print(x)
// LOCAL: [[@LINE-1]]:11 | variable(local)/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-2]]:11 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
case let .some(x) where x == 1,
// LOCAL: [[@LINE-1]]:18 | variable(local)/Swift | x | [[x2_USR:.*]] | Def,RelChild | rel: 1
// LOCAL: [[@LINE-2]]:27 | variable(local)/Swift | x | [[x2_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-3]]:18 | variable(local)/Swift | x | {{.*}} | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-4]]:27 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
let .some(x) where x == 2:
// LOCAL: [[@LINE-1]]:18 | variable(local)/Swift | x | [[x2_USR]] | Def,RelChild | rel: 1
// LOCAL: [[@LINE-2]]:27 | variable(local)/Swift | x | [[x2_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-3]]:18 | variable(local)/Swift | x | {{.*}} | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-4]]:27 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
print(x)
// LOCAL: [[@LINE-1]]:11 | variable(local)/Swift | x | [[x2_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-2]]:11 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
fallthrough
case let .some(x) where x == 3:
// LOCAL: [[@LINE-1]]:18 | variable(local)/Swift | x | [[x2_USR]] | Def,RelChild | rel: 1
// LOCAL: [[@LINE-2]]:27 | variable(local)/Swift | x | [[x2_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-1]]:18 | variable(local)/Swift | x | {{.*}} | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-2]]:27 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
print(x)
// LOCAL: [[@LINE-1]]:11 | variable(local)/Swift | x | [[x2_USR]] | Ref,Read,RelCont | rel: 1
// CHECK-NOT: [[@LINE-1]]:11 | variable(local)/Swift | x | {{.*}} | Ref,Read,RelCont | rel: 1
default:
break
}
}
| apache-2.0 | c8faba2c4d15d993af9f6602b58a459c | 61.917647 | 126 | 0.551234 | 3.001122 | false | false | false | false |
algolia/algolia-swift-demo | Source/MoviesIpadViewController.swift | 1 | 12034 | //
// Copyright (c) 2016 Algolia
// http://www.algolia.com/
//
// 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 AlgoliaSearch
import InstantSearchCore
import TTRangeSlider
import UIKit
class MoviesIpadViewController: UIViewController, UICollectionViewDataSource, TTRangeSliderDelegate, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, SearchProgressDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var genreTableView: UITableView!
@IBOutlet weak var yearRangeSlider: TTRangeSlider!
@IBOutlet weak var ratingSelectorView: RatingSelectorView!
@IBOutlet weak var moviesCollectionView: UICollectionView!
@IBOutlet weak var actorsTableView: UITableView!
@IBOutlet weak var movieCountLabel: UILabel!
@IBOutlet weak var searchTimeLabel: UILabel!
@IBOutlet weak var genreTableViewFooter: UILabel!
@IBOutlet weak var genreFilteringModeSwitch: UISwitch!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var actorSearcher: Searcher!
var movieSearcher: Searcher!
var actorHits: [JSONObject] = []
var movieHits: [JSONObject] = []
var genreFacets: [FacetValue] = []
var yearFilterDebouncer = Debouncer(delay: 0.3)
var searchProgressController: SearchProgressController!
override func viewDidLoad() {
super.viewDidLoad()
self.movieCountLabel.text = NSLocalizedString("movie_count_placeholder", comment: "")
self.searchTimeLabel.text = nil
// Customize search bar.
searchBar.placeholder = NSLocalizedString("search_bar_placeholder", comment: "")
// Customize year range slider.
yearRangeSlider.numberFormatterOverride = NumberFormatter()
let tintColor = self.view.tintColor
yearRangeSlider.tintColorBetweenHandles = tintColor
yearRangeSlider.handleColor = tintColor
yearRangeSlider.lineHeight = 3
yearRangeSlider.minLabelFont = UIFont.systemFont(ofSize: 12)
yearRangeSlider.maxLabelFont = yearRangeSlider.minLabelFont
ratingSelectorView.addObserver(self, forKeyPath: "rating", options: .new, context: nil)
// Customize genre table view.
genreTableView.tableFooterView = genreTableViewFooter
genreTableViewFooter.isHidden = true
// Configure actor search.
actorSearcher = Searcher(index: AlgoliaManager.sharedInstance.actorsIndex, resultHandler: self.handleActorSearchResults)
actorSearcher.params.hitsPerPage = 10
actorSearcher.params.attributesToHighlight = ["name"]
// Configure movie search.
movieSearcher = Searcher(index: AlgoliaManager.sharedInstance.moviesIndex, resultHandler: self.handleMovieSearchResults)
movieSearcher.params.facets = ["genre"]
movieSearcher.params.attributesToHighlight = ["title"]
movieSearcher.params.hitsPerPage = 30
// Configure search progress monitoring.
searchProgressController = SearchProgressController(searcher: movieSearcher)
searchProgressController.graceDelay = 0.5
searchProgressController.delegate = self
search()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Actions
private func search() {
actorSearcher.search()
movieSearcher.params.setFacet(withName: "genre", disjunctive: genreFilteringModeSwitch.isOn)
movieSearcher.params.clearNumericRefinements()
movieSearcher.params.addNumericRefinement("year", .greaterThanOrEqual, Int(yearRangeSlider.selectedMinimum))
movieSearcher.params.addNumericRefinement("year", .lessThanOrEqual, Int(yearRangeSlider.selectedMaximum))
movieSearcher.params.addNumericRefinement("rating", .greaterThanOrEqual, ratingSelectorView.rating)
movieSearcher.search()
}
@IBAction func genreFilteringModeDidChange(_ sender: AnyObject) {
movieSearcher.params.setFacet(withName: "genre", disjunctive: genreFilteringModeSwitch.isOn)
search()
}
@IBAction func configTapped(_ sender: AnyObject) {
let vc = ConfigViewController(nibName: "ConfigViewController", bundle: nil)
self.present(vc, animated: true, completion: nil)
}
// MARK: - UISearchBarDelegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
actorSearcher.params.query = searchText
movieSearcher.params.query = searchText
search()
}
// MARK: - Search completion handlers
private func handleActorSearchResults(results: SearchResults?, error: Error?) {
guard let results = results else { return }
if results.page == 0 {
actorHits = results.hits
} else {
actorHits.append(contentsOf: results.hits)
}
self.actorsTableView.reloadData()
// Scroll to top.
if results.page == 0 {
self.moviesCollectionView.contentOffset = CGPoint.zero
}
}
private func handleMovieSearchResults(results: SearchResults?, error: Error?) {
guard let results = results else {
self.searchTimeLabel.textColor = UIColor.red
self.searchTimeLabel.text = NSLocalizedString("error_search", comment: "")
return
}
if results.page == 0 {
movieHits = results.hits
} else {
movieHits.append(contentsOf: results.hits)
}
// Sort facets: first selected facets, then by decreasing count, then by name.
genreFacets = FacetValue.listFrom(facetCounts: results.facets(name: "genre"), refinements: movieSearcher.params.buildFacetRefinements()["genre"]).sorted() { (lhs, rhs) in
// When using cunjunctive faceting ("AND"), all refined facet values are displayed first.
// But when using disjunctive faceting ("OR"), refined facet values are left where they are.
let disjunctiveFaceting = results.disjunctiveFacets.contains("genre")
let lhsChecked = self.movieSearcher.params.hasFacetRefinement(name: "genre", value: lhs.value)
let rhsChecked = self.movieSearcher.params.hasFacetRefinement(name: "genre", value: rhs.value)
if !disjunctiveFaceting && lhsChecked != rhsChecked {
return lhsChecked
} else if lhs.count != rhs.count {
return lhs.count > rhs.count
} else {
return lhs.value < rhs.value
}
}
let exhaustiveFacetsCount = results.exhaustiveFacetsCount == true
genreTableViewFooter.isHidden = exhaustiveFacetsCount
let formatter = NumberFormatter()
formatter.locale = NSLocale.current
formatter.numberStyle = .decimal
formatter.usesGroupingSeparator = true
formatter.groupingSize = 3
self.movieCountLabel.text = "\(formatter.string(for: results.nbHits)!) MOVIES"
searchTimeLabel.textColor = UIColor.lightGray
self.searchTimeLabel.text = "Found in \(results.processingTimeMS) ms"
// Indicate origin of content.
if results.content["origin"] as? String == "local" {
searchTimeLabel.textColor = searchTimeLabel.highlightedTextColor
searchTimeLabel.text! += " (offline results)"
}
self.genreTableView.reloadData()
self.moviesCollectionView.reloadData()
// Scroll to top.
if results.page == 0 {
self.moviesCollectionView.contentOffset = CGPoint.zero
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movieHits.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as! MovieCell
cell.movie = MovieRecord(json: movieHits[indexPath.item])
if indexPath.item + 5 >= movieHits.count {
movieSearcher.loadMore()
}
return cell
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch tableView {
case actorsTableView: return actorHits.count
case genreTableView: return genreFacets.count
default: assert(false); return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch tableView {
case actorsTableView:
let cell = tableView.dequeueReusableCell(withIdentifier: "actorCell", for: indexPath) as! ActorCell
cell.actor = Actor(json: actorHits[indexPath.item])
if indexPath.item + 5 >= actorHits.count {
actorSearcher.loadMore()
}
return cell
case genreTableView:
let cell = tableView.dequeueReusableCell(withIdentifier: "genreCell", for: indexPath) as! GenreCell
cell.value = genreFacets[indexPath.item]
cell.checked = movieSearcher.params.hasFacetRefinement(name: "genre", value: genreFacets[indexPath.item].value)
return cell
default: assert(false); return UITableViewCell()
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch tableView {
case genreTableView:
movieSearcher.params.toggleFacetRefinement(name: "genre", value: genreFacets[indexPath.item].value)
movieSearcher.search()
break
default: return
}
}
// MARK: - TTRangeSliderDelegate
func rangeSlider(_ sender: TTRangeSlider!, didChangeSelectedMinimumValue selectedMinimum: Float, andMaximumValue selectedMaximum: Float) {
yearFilterDebouncer.call {
self.search()
}
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let object = object as? NSObject else { return }
if object === ratingSelectorView {
if keyPath == "rating" {
search()
}
}
}
// MARK: - SearchProgressDelegate
func searchDidStart(_ searchProgressController: SearchProgressController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
activityIndicator.startAnimating()
}
func searchDidStop(_ searchProgressController: SearchProgressController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activityIndicator.stopAnimating()
}
}
| mit | 58bfbf3e4b6d7801e0d1c2092b8a5c08 | 40.930314 | 190 | 0.682151 | 5.094835 | false | false | false | false |
salimbraksa/Machinery | Machinery/StateMachine.swift | 1 | 5604 | //
// StateMachine.swift
// StateMachine
//
// Created by Salim Braksa on 2/18/17.
// Copyright © 2017 Salim Braksa. All rights reserved.
//
import Foundation
precedencegroup TransitionPrecedence {
associativity: left
}
infix operator <-: TransitionPrecedence
infix operator <-!: TransitionPrecedence
public protocol StateHandler {
associatedtype T: State
func didEnter(state: T)
func willExit(state: T)
}
open class StateMachine<T: State>: NSObject {
// MARK: - Public Properties
open var currentState: T { return currentNode.state }
open override var debugDescription: String {
var result = ""
for (_, node) in nodes {
let currentNodeSymbol = node.state.description == currentNode.state.description ? "+ " : ""
let initialNodeSymbol = node.state.description == initialNode.state.description ? "- " : ""
result += "\(initialNodeSymbol)\(currentNodeSymbol)\(node.state.description) => "
result += String(describing: node.destinationNodes().map({ $0.state })) + "\n"
}
return result
}
// MARK: - Private Properties
private var stateHandlers = [String: AnyStateHandler<T>]()
// MARK: - Private Properties
fileprivate var initialNode: Node<T>!
fileprivate let notificationCenter = NotificationCenter.default
fileprivate var nodes = [String: Node<T>]()
fileprivate var currentNode: Node<T>! {
willSet {
if let currentNode = self.currentNode {
willSet(currentNode: currentNode)
}
} didSet {
didSet(currentNode: currentNode)
}
}
// MARK: - Initializer
public override init() {
super.init()
}
public init(initial: T) {
super.init()
self.initial(initial)
}
// MARK: - Performing Transitions
@discardableResult
open func move(to state: T) -> StateMachine<T> {
let node = self.nodes[state.description]
node?.state = state
self.currentNode = node
return self
}
@discardableResult
open func `try`(_ state: T) -> StateMachine<T> {
guard let destinationNode = currentNode.state(withIdentifier: "to \(state.description)") else { return self }
currentNode = destinationNode
return self
}
// MARK: - Machine construction
@discardableResult
public func initial(_ state: T) -> StateMachine<T> {
let node = self.node(from: state)
initialNode = node
currentNode = node
return self
}
@discardableResult
public func add(_ transition: Transition<T>) -> StateMachine<T> {
let source = transition.source
let destination = transition.destination
let identifier = "to \(destination.description)"
let isWeak = destination.has(node: source)
source.destinationStates[identifier] = Container(value: destination, isWeak: isWeak)
return self
}
@discardableResult
open func add(_ state: T) -> StateMachine<T> {
if nodes[state.description] == nil {
nodes[state.description] = Node(state)
}
return self
}
@discardableResult
open func add(_ states: T...) -> StateMachine<T> {
states.forEach { self.add($0) }
return self
}
@discardableResult
open func add(source: T, destination: T) -> StateMachine<T> {
let source = self.node(from: source)
let destination = self.node(from: destination)
return self.add(Transition(source: source, destination: destination))
}
func node(from state: T) -> Node<T> {
if nodes[state.description] == nil {
nodes[state.description] = Node(state)
}
return nodes[state.description]!
}
// MARK: - State Handling
open func handle<H: StateHandler>(_ state: T, with handler: H) where H.T == T {
self.stateHandlers[state.description] = AnyStateHandler<T>(handler)
}
// MARK: - Property Observers
private func willSet(currentNode: Node<T>) {
let handler = self.stateHandlers[currentNode.state.description]
handler?.willExit(state: currentNode.state)
}
private func didSet(currentNode: Node<T>) {
let handler = self.stateHandlers[currentNode.state.description]
handler?.didEnter(state: currentNode.state)
}
// MARK: - Operator
@discardableResult
open static func + (left: StateMachine, right: (source: T, destination: T)) -> StateMachine {
return left.add(source: right.source, destination: right.destination)
}
@discardableResult
open static func <- (left: StateMachine, right: T) -> StateMachine {
return left.try(right)
}
@discardableResult
open static func <-! (left: StateMachine, right: T) -> StateMachine {
return left.move(to: right)
}
}
class AnyStateHandler<T: State>: StateHandler {
private let _willExit: (T) -> Void
private let _didEnter: (T) -> Void
init<H: StateHandler>(_ handler: H) where H.T == T {
self._willExit = handler.willExit(state:)
self._didEnter = handler.didEnter(state:)
}
func willExit(state: T) {
self._willExit(state)
}
func didEnter(state: T) {
self._didEnter(state)
}
}
| mit | f6a3820070d5e44f0db17dcd506d02ff | 25.9375 | 117 | 0.593789 | 4.60773 | false | false | false | false |
elslooo/hoverboard | OnboardKit/OnboardKit/Views/NavigationBar.swift | 1 | 5224 | /*
* Copyright (c) 2017 Tim van Elsloo
*
* 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
/**
* This class is inspired by UINavigationBar.
*/
internal class NavigationBar : NSView {
/**
* This is the title that is shown in the navigation bar. This overrides
* attributedTitle if it is set later.
*/
public var title: String? {
didSet {
self.titleLabel.stringValue = self.title ?? ""
self.layout()
}
}
/**
* This is the attributed title that is shown in the navigation bar. This
* overrides title if it is set later.
*/
public var attributedTitle: NSAttributedString? {
didSet {
guard let attributedTitle = self.attributedTitle else {
self.titleLabel.stringValue = ""
return
}
self.titleLabel.attributedStringValue = attributedTitle
self.layout()
}
}
/**
* The navigation bar always shows an image view that displays the app icon.
*/
private let imageView = NSImageView(frame: NSRect(
x: 15,
y: 15,
width: 64,
height: 64
))
/**
* The navigation bar always shows a title that depends on the view
* controller that is currently visible.
*/
private let titleLabel = NSTextField(frame: NSRect(
x: 94,
y: 25,
width: 0,
height: 34
))
/**
* This function initializes the navigation bar with the given frame.
*/
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.setupImageView()
self.setupTitleLabel()
self.setupSeparator()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
* This function configures the image view.
*/
func setupImageView() {
// Here we retrieve the app icon from its NSBundle.
let bundle = Bundle.main
// Make sure there is an icon set.
let key = "CFBundleIconFile"
guard let value = bundle.object(forInfoDictionaryKey: key),
let name = value as? String else {
return
}
// Make sure that we can retrieve a path to that icon.
guard let path = bundle.pathForImageResource(name) else {
return
}
// Open image and assign it to the image view.
self.imageView.image = NSImage(contentsOfFile: path)
// Finally, add the image view to the navigation bar.
self.addSubview(self.imageView)
}
/**
* This function configures the title label.
*/
func setupTitleLabel() {
// Make sure it isn't editable, bordered, etc.
self.titleLabel.isEditable = false
self.titleLabel.isSelectable = false
self.titleLabel.isBordered = false
self.titleLabel.drawsBackground = false
// Set font and color. Secondary label color makes sure it gets some
// vibrancy in an effect view.
self.titleLabel.font = .systemFont(ofSize: 24)
self.titleLabel.textColor = .secondaryLabelColor
self.addSubview(self.titleLabel)
}
/**
* This function configures the separator.
*/
func setupSeparator() {
let separator = Separator(frame: NSRect(
x: 0,
y: self.bounds.height - 1,
width: self.bounds.width,
height: 1
))
self.addSubview(separator)
}
override var isFlipped: Bool {
return true
}
override var allowsVibrancy: Bool {
return true
}
/**
* We override this function to reposition the title label.
*/
override func layout() {
super.layout()
// Make sure that the title label can fit the title.
self.titleLabel.sizeToFit()
// Next, center the title label.
var frame = self.titleLabel.frame
frame.origin.y = round((self.bounds.height - frame.height) / 2)
self.titleLabel.frame = frame
}
}
| mit | 875916d8bfe687282664333309ece705 | 28.851429 | 80 | 0.613515 | 4.814747 | false | false | false | false |
object-kazu/JabberwockProtoType | JabberWock/JabberWock/global/TagAttribute.swift | 1 | 1009 | //
// TagAttribute.swift
// JabberWock
//
// Created by kazuyuki shimizu on 2017/01/23.
// Copyright © 2017年 momiji-mac. All rights reserved.
//
import Foundation
class TagAttribute {
var aString = ""
func add (lang: LANG){
if lang == LANG.NO_LANG {return}
aString += SPC + lang.str()
}
// templete method
func templeteAdd (index:String, val:String) {
if !val.isEmpty {
aString += SPC + index + "=".inDoubleQuo(inn: val)
}
}
// use templete
func add(title : String){
templeteAdd(index: "title", val: title)
}
func add(href: String) {
templeteAdd(index: "href", val: href)
}
func add(target: String){
templeteAdd(index: "target", val: target)
}
func add(name:String) {
templeteAdd(index: "name", val: name)
}
func add(download:String){
templeteAdd(index: "download", val: download)
}
}
| mit | 66e6f47a6f6943f49040e97e5d925ba4 | 18.72549 | 62 | 0.539761 | 3.605735 | false | false | false | false |
cshireman/VPAppManager | VPAppManager/Classes/VPNagScreen.swift | 1 | 2417 | //
// VPNagScreen.swift
// Pods
//
// Created by Christopher Shireman on 2/14/17.
//
//
import UIKit
import SwiftyJSON
public enum NagType: String {
case purchase = "purchase"
case application = "application"
}
public protocol VPNagScreenDelegate {
func nagScreenAcceptPressed(_ nagScreen: VPNagScreen)
func nagScreenDeclinePressed(_ nagScreen: VPNagScreen)
}
open class VPNagScreen: NSObject {
open var title: String = ""
open var message: String = ""
open var acceptButtonTitle: String = ""
open var declineButtonTitle: String = ""
open var frequency: Int = 0
open var type: NagType = .purchase
open var isActive: Bool = true
open var value: String = ""
open var delegate: VPNagScreenDelegate?
public init(json: JSON) {
super.init()
title = json["title"].stringValue
message = json["message"].stringValue
acceptButtonTitle = json["accept_button_title"].stringValue
declineButtonTitle = json["decline_button_title"].stringValue
frequency = json["frequency"].intValue
type = NagType(rawValue: json["type"].stringValue) ?? .purchase
isActive = json["is_active"].boolValue
value = json["value"].stringValue
}
public func canShow() -> Bool {
let defaults = UserDefaults.standard
var count = defaults.integer(forKey: "VPNagScreenCount")
return count >= frequency
}
public func show() {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: acceptButtonTitle, style: .default, handler: { (action) in
self.delegate?.nagScreenAcceptPressed(self)
}))
alert.addAction(UIAlertAction(title: declineButtonTitle, style: .cancel, handler: { (action) in
self.delegate?.nagScreenDeclinePressed(self)
}))
if let rootController = UIApplication.shared.delegate?.window??.rootViewController {
rootController.present(alert, animated: true, completion: nil)
}
}
public func incrementCount() {
let defaults = UserDefaults.standard
var count = defaults.integer(forKey: "VPNagScreenCount")
count += 1
if count > frequency {
count = 0
}
defaults.set(count, forKey: "VPNagScreenCount")
defaults.synchronize()
}
}
| mit | d1aac2cf7f776e4259ff2c1feacded7d | 27.435294 | 103 | 0.649566 | 4.451197 | false | false | false | false |
kidaa/codecombat-ios | CodeCombat/LevelSettingsManager.swift | 3 | 2241 | //
// LevelSettingsManager.swift
// CodeCombat
//
// Created by Michael Schmatz on 10/31/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
private let levelSettingsManagerSharedInstance = LevelSettingsManager()
import UIKit
enum CodeLanguage:String {
case Python = "python"
case Javascript = "javascript"
}
enum LevelName:String {
case DungeonsOfKithgard = "dungeons-of-kithgard"
case GemsInTheDeep = "gems-in-the-deep"
case ShadowGuard = "shadow-guard"
case KounterKithwise = "kounter-kithwise"
case CrawlwaysOfKithgard = "crawlways-of-kithgard"
case ForgetfulGemsmith = "forgetful-gemsmith"
case TrueNames = "true-names"
case FavorableOdds = "favorable-odds"
case TheRaisedSword = "the-raised-sword"
case TheFirstKithmaze = "the-first-kithmaze"
case HauntedKithmaze = "haunted-kithmaze"
case DescendingFurther = "descending-further"
case TheSecondKithmaze = "the-second-kithmaze"
case DreadDoor = "dread-door"
case KnownEnemy = "known-enemy"
case MasterOfNames = "master-of-names"
case LowlyKithmen = "lowly-kithmen"
case ClosingTheDistance = "closing-the-distance"
case TacticalStrike = "tactical-strike"
case TheFinalKithmaze = "the-final-kithmaze"
case TheGauntlet = "the-gauntlet"
case KithgardGates = "kithgard-gates"
case CavernSurvival = "cavern-survival"
case DefenseOfPlainswood = "defense-of-plainswood"
case WindingTrail = "winding-trail"
case ThornbushFarm = "thornbush-farm"
case BackToBack = "back-to-back"
case OgreEncampment = "ogre-encampment"
case WoodlandCleaver = "woodland-cleaver"
case ShieldRush = "shield-rush"
case PeasantProtection = "peasant-protection"
case MunchkinSwarm = "munchkin-swarm"
case Coinucopia = "coinucopia"
case CopperMeadows = "copper-meadows"
case DropTheFlag = "drop-the-flag"
case DeadlyPursuit = "deadly-pursuit"
case RichForager = "rich-forager"
case MultiplayerTreasureGrove = "multiplayer-treasure-grove"
case DuelingGrounds = "dueling-grounds"
case Unknown = "unknown"
}
class LevelSettingsManager {
var level:LevelName = .TheRaisedSword
var language:CodeLanguage = .Python
class var sharedInstance: LevelSettingsManager {
return levelSettingsManagerSharedInstance
}
}
| mit | de604633c304dd5f528440cbe2e3beef | 32.954545 | 71 | 0.754128 | 3.174221 | false | false | false | false |
Nyx0uf/SwiftyImages | src/extensions/UIImage+Filtering.swift | 1 | 3965 | // UIImage+Filtering.swift
// Copyright (c) 2016 Nyx0uf
//
// 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 extension UIImage
{
public func alphaed(value: CGFloat) -> UIImage?
{
guard let transparentImageRef = self.cgImage?.alphaed(value: value) else
{
return nil
}
return UIImage(cgImage: transparentImageRef, scale: self.scale, orientation: self.imageOrientation)
}
// Value should be in the range (-255, 255)
public func brightened(value: Float) -> UIImage?
{
guard let brightenedImageRef = self.cgImage?.brightened(value: value) else
{
return nil
}
return UIImage(cgImage: brightenedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
/// (-255, 255)
public func contrasted(value: Float) -> UIImage?
{
guard let contrastedImageRef = self.cgImage?.contrasted(value: value) else
{
return nil
}
return UIImage(cgImage: contrastedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func edgeDetected(_ bias: Int32 = 0) -> UIImage?
{
guard let edgedImageRef = self.cgImage?.edgeDetected(bias) else
{
return nil
}
return UIImage(cgImage: edgedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func embossed(_ bias: Int32 = 0) -> UIImage?
{
guard let embossedImageRef = self.cgImage?.embossed(bias) else
{
return nil
}
return UIImage(cgImage: embossedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
/// (0.01, 8)
public func gammaCorrected(value: Float) -> UIImage?
{
guard let gammaImageRef = self.cgImage?.gammaCorrected(value: value) else
{
return nil
}
return UIImage(cgImage: gammaImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func grayscaled() -> UIImage?
{
guard let grayscaledImageRef = self.cgImage?.grayscaled() else
{
return nil
}
return UIImage(cgImage: grayscaledImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func inverted() -> UIImage?
{
guard let invertedImageRef = self.cgImage?.inverted() else
{
return nil
}
return UIImage(cgImage: invertedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func sepiaed() -> UIImage?
{
guard let sepiaImageRef = self.cgImage?.sepiaed() else
{
return nil
}
return UIImage(cgImage: sepiaImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func sharpened(_ bias: Int32 = 0) -> UIImage?
{
guard let sharpenedImageRef = self.cgImage?.sharpened(bias) else
{
return nil
}
return UIImage(cgImage: sharpenedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
public func unsharpened(_ bias: Int32 = 0) -> UIImage?
{
guard let unsharpenedImageRef = self.cgImage?.unsharpened(bias) else
{
return nil
}
return UIImage(cgImage: unsharpenedImageRef, scale: self.scale, orientation: self.imageOrientation)
}
}
| mit | c0b8d4e4e98edf128281cf6b26769bea | 27.321429 | 101 | 0.732156 | 3.640955 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Widgets/TabsButton.swift | 2 | 11078 | /* 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 SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
struct TabsButtonUX {
static let TitleColor: UIColor = UIColor.blackColor()
static let TitleBackgroundColor: UIColor = UIColor.whiteColor()
static let CornerRadius: CGFloat = 2
static let TitleFont: UIFont = UIConstants.DefaultChromeSmallFontBold
static let BorderStrokeWidth: CGFloat = 1
static let BorderColor: UIColor = UIColor.clearColor()
static let TitleInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.borderColor = UIConstants.PrivateModePurple
theme.borderWidth = BorderStrokeWidth
theme.font = UIConstants.DefaultChromeBoldFont
theme.backgroundColor = UIConstants.AppBackgroundColor
theme.textColor = UIConstants.PrivateModePurple
theme.insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
theme.highlightButtonColor = UIConstants.PrivateModePurple
theme.highlightTextColor = TabsButtonUX.TitleColor
theme.highlightBorderColor = UIConstants.PrivateModePurple
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.borderColor = BorderColor
theme.borderWidth = BorderStrokeWidth
theme.font = TitleFont
theme.backgroundColor = TitleBackgroundColor
theme.textColor = TitleColor
theme.insets = TitleInsets
theme.highlightButtonColor = TabsButtonUX.TitleColor
theme.highlightTextColor = TabsButtonUX.TitleBackgroundColor
theme.highlightBorderColor = TabsButtonUX.TitleBackgroundColor
themes[Theme.NormalMode] = theme
return themes
}()
}
class TabsButton: UIControl {
private var theme: Theme = TabsButtonUX.Themes[Theme.NormalMode]!
override var highlighted: Bool {
didSet {
if highlighted {
borderColor = theme.highlightBorderColor!
titleBackgroundColor = theme.highlightButtonColor
textColor = theme.highlightTextColor
} else {
borderColor = theme.borderColor!
titleBackgroundColor = theme.backgroundColor
textColor = theme.textColor
}
}
}
override var transform: CGAffineTransform {
didSet {
clonedTabsButton?.transform = transform
}
}
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = TabsButtonUX.TitleFont
label.layer.cornerRadius = TabsButtonUX.CornerRadius
label.textAlignment = NSTextAlignment.Center
label.userInteractionEnabled = false
return label
}()
lazy var insideButton: UIView = {
let view = UIView()
view.clipsToBounds = false
view.userInteractionEnabled = false
return view
}()
private lazy var labelBackground: UIView = {
let background = UIView()
background.layer.cornerRadius = TabsButtonUX.CornerRadius
background.userInteractionEnabled = false
return background
}()
private lazy var borderView: InnerStrokedView = {
let border = InnerStrokedView()
border.strokeWidth = TabsButtonUX.BorderStrokeWidth
border.cornerRadius = TabsButtonUX.CornerRadius
border.userInteractionEnabled = false
return border
}()
private var buttonInsets: UIEdgeInsets = TabsButtonUX.TitleInsets
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: TabsButton?
override init(frame: CGRect) {
super.init(frame: frame)
insideButton.addSubview(labelBackground)
insideButton.addSubview(borderView)
insideButton.addSubview(titleLabel)
addSubview(insideButton)
isAccessibilityElement = true
accessibilityTraits |= UIAccessibilityTraitButton
}
override func updateConstraints() {
super.updateConstraints()
labelBackground.snp_remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
borderView.snp_remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
titleLabel.snp_remakeConstraints { (make) -> Void in
make.edges.equalTo(insideButton)
}
insideButton.snp_remakeConstraints { (make) -> Void in
make.edges.equalTo(self).inset(insets)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func clone() -> UIView {
let button = TabsButton()
button.accessibilityLabel = accessibilityLabel
button.titleLabel.text = titleLabel.text
// Copy all of the styable properties over to the new TabsButton
button.titleLabel.font = titleLabel.font
button.titleLabel.textColor = titleLabel.textColor
button.titleLabel.layer.cornerRadius = titleLabel.layer.cornerRadius
button.labelBackground.backgroundColor = labelBackground.backgroundColor
button.labelBackground.layer.cornerRadius = labelBackground.layer.cornerRadius
button.borderView.strokeWidth = borderView.strokeWidth
button.borderView.color = borderView.color
button.borderView.cornerRadius = borderView.cornerRadius
return button
}
func updateTabCount(count: Int, animated: Bool = true) {
let currentCount = self.titleLabel.text
let infinity = "\u{221E}"
let countToBe = (count < 100) ? count.description : infinity
// only animate a tab count change if the tab count has actually changed
if currentCount != count.description || (clonedTabsButton?.titleLabel.text ?? count.description) != count.description {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
insideButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = clone() as! TabsButton
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: #selector(TabsButton.cloneDidClickTabs), forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.titleLabel.text = countToBe
newTabsButton.accessibilityValue = countToBe
superview?.addSubview(newTabsButton)
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = self.frame
newTabsButton.insets = insets
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
let frame = self.insideButton.frame
let halfTitleHeight = CGRectGetHeight(frame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.insideButton.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.insideButton.layer.transform = CATransform3DIdentity
self.insideButton.layer.transform = oldFlipTransform
self.insideButton.layer.opacity = 0
}
let completion: (Bool) -> Void = { finished in
if finished {
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.insideButton.layer.opacity = 1
self.insideButton.layer.transform = CATransform3DIdentity
self.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) tab toolbar")
}
self.titleLabel.text = countToBe
self.accessibilityValue = countToBe
}
if animated {
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func cloneDidClickTabs() {
sendActionsForControlEvents(UIControlEvents.TouchUpInside)
}
}
extension TabsButton: Themeable {
func applyTheme(themeName: String) {
guard let theme = TabsButtonUX.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
borderColor = theme.borderColor!
borderWidth = theme.borderWidth!
titleFont = theme.font
titleBackgroundColor = theme.backgroundColor
textColor = theme.textColor
insets = theme.insets!
self.theme = theme
}
}
// MARK: UIAppearance
extension TabsButton {
dynamic var borderColor: UIColor {
get { return borderView.color }
set { borderView.color = newValue }
}
dynamic var borderWidth: CGFloat {
get { return borderView.strokeWidth }
set { borderView.strokeWidth = newValue }
}
dynamic var textColor: UIColor? {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
dynamic var titleFont: UIFont? {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
dynamic var titleBackgroundColor: UIColor? {
get { return labelBackground.backgroundColor }
set { labelBackground.backgroundColor = newValue }
}
dynamic var insets : UIEdgeInsets {
get { return buttonInsets }
set {
buttonInsets = newValue
setNeedsUpdateConstraints()
}
}
} | mpl-2.0 | d0b77ef6ee8b2722d74b523a34693f65 | 37.33564 | 207 | 0.645153 | 5.678114 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCIReadRemoteVersionInformation.swift | 1 | 1827 | //
// HCIReadRemoteVersionInformation.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/7/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// Read Remote Version Information Command
///
/// This command will obtain the values for the version information for the remote device identified by the Connection_Handle parameter. The Connection_Handle must be a Connection_Handle for an ACL or LE connection.
func readRemoteVersionInformation(handle: UInt16,
timeout: HCICommandTimeout = .default) async throws -> HCIReadRemoteVersionInformationComplete {
let readRemoteVersionInformation = HCIReadRemoteVersionInformation(handle: handle)
return try await deviceRequest(readRemoteVersionInformation,
HCIReadRemoteVersionInformationComplete.self,
timeout: timeout)
}
}
// MARK: - Command
/// Read Remote Version Information Command
///
/// This command will obtain the values for the version information for the remote device identified by the Connection_Handle parameter. The Connection_Handle must be a Connection_Handle for an ACL or LE connection.
@frozen
public struct HCIReadRemoteVersionInformation: HCICommandParameter {
public static let command = LinkControlCommand.readRemoteVersion
/// Specifies which Connection_Handle’s version information to get.
public var handle: UInt16
public init(handle: UInt16) {
self.handle = handle
}
public var data: Data {
let handleBytes = handle.littleEndian.bytes
return Data([handleBytes.0, handleBytes.1])
}
}
| mit | 4442886afd11bb4a5cb1f5b54e4824db | 33.415094 | 219 | 0.6875 | 5.109244 | false | false | false | false |
brentdax/swift | test/PlaygroundTransform/nested_function.swift | 7 | 1836 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -playground -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift && %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift && %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
func returnSum() -> Int {
var y = 10
func add() {
y += 5
}
add()
let addAgain = {
y += 5
}
addAgain()
let addMulti = {
y += 5
_ = 0 // force a multi-statement closure
}
addMulti()
return y
}
returnSum()
// CHECK-NOT: __builtin
// CHECK: [9:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [10:{{.*}}] __builtin_log[y='10']
// CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [12:{{.*}}] __builtin_log[y='15']
// CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [15:{{.*}}] __builtin_log[addAgain='{{.*}}']
// CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_entry
// FIXME: We drop the log for the addition here.
// CHECK-NEXT: [16:{{.*}}] __builtin_log[='()']
// CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_exit
// FIXME: There's an extra, unbalanced scope exit here.
// CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [19:{{.*}}] __builtin_log[addMulti='{{.*}}']
// CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [20:{{.*}}] __builtin_log[y='25']
// CHECK-NEXT: [21:{{.*}}] __builtin_log[='0']
// CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [24:{{.*}}] __builtin_log[='25']
// CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [27:{{.*}}] __builtin_log[='25']
// CHECK-NOT: __builtin
| apache-2.0 | 34989d47269829a09accaac013ffa982 | 33 | 198 | 0.587691 | 2.951768 | false | false | false | false |
jtauber/minilight-swift | Minilight/vector.swift | 1 | 2258 | //
// Vector.swift
// Minilight
//
// Created by James Tauber on 6/14/14.
// Copyright (c) 2014 James Tauber. See LICENSE.
//
import Foundation
struct Vector: Equatable, Printable {
let x, y, z: Double
var description: String {
return "(\(x), \(y), \(z))"
}
init() {
self.init(n: 0.0)
}
init(n: Double) {
self.init(x: n, y: n, z: n)
}
init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
init(other: Vector) {
self.init(x: other.x, y: other.y, z: other.z)
}
subscript(index: Int) -> Double {
return [x, y, z][index]
}
func unitize() -> Vector {
let length = sqrt(x * x + y * y + z * z)
if length > 0 {
return self * (1.0 / length)
} else {
return Vector()
}
}
func cross(other:Vector) -> Vector {
return Vector(
x: (y * other.z) - (z * other.y),
y: (z * other.x) - (x * other.z),
z: (x * other.y) - (y * other.x)
)
}
func dot(other:Vector) -> Double {
return (x * other.x) + (y * other.y) + (z * other.z)
}
func clamped(#lo: Vector, hi: Vector) -> Vector {
return Vector(
x: min(max(x, lo.x), hi.x),
y: min(max(y, lo.y), hi.y),
z: min(max(z, lo.z), hi.z)
)
}
}
func +(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z)
}
func -(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z)
}
prefix func -(v: Vector) -> Vector {
return Vector(x: -v.x, y: -v.y, z: -v.z)
}
// component-wise multiplication
func *(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x * rhs.x, y: lhs.y * rhs.y, z: lhs.z * rhs.z)
}
// scalar multiplication
func *(lhs: Vector, rhs: Double) -> Vector {
return Vector(x: lhs.x * rhs, y: lhs.y * rhs, z: lhs.z * rhs)
}
func ==(lhs: Vector, rhs: Vector) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
let ZERO = Vector()
let ONE = Vector(n: 1.0)
let MAX = Vector(n: Double.infinity)
| bsd-3-clause | 6c011de67f0d80a4a6bee4fe8d128e99 | 21.58 | 71 | 0.487157 | 2.872774 | false | false | false | false |
Stitch7/Instapod | Instapod/Feed/FeedOperation/FeedOperation.swift | 1 | 2187 | //
// FeedOperation.swift
// Instapod
//
// Created by Christopher Reitz on 02.04.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
class FeedOperation: AsynchronousOperation {
// MARK: - Properties
let uuid: String
var url: URL
var parser: FeedParser
var task: URLSessionTask!
var delegate: FeedOperationDelegate?
var session = URLSession.shared
// MARK: - Initializer
init(uuid: String, url: URL, parser: FeedParser) {
self.uuid = uuid
self.parser = parser
self.url = url
super.init()
configureTask()
}
fileprivate func configureTask() {
task = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self else { return }
defer {
strongSelf.completeOperation()
}
if let requestError = error {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: requestError)
return
}
guard let xmlData = data else {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: error)
return
}
do {
let parser = strongSelf.parser
var podcast = try parser.parseFeed(uuid: strongSelf.uuid,
url: strongSelf.url,
xmlData: xmlData)
podcast.nextPage = try parser.nextPage(xmlData)
podcast.image = try parser.parseImage(xmlData)
podcast.episodes = try parser.parseEpisodes(xmlData)
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithPodcast: podcast)
} catch {
strongSelf.delegate?.feedOperation(strongSelf, didFinishWithError: error)
}
})
}
// MARK: - NSOperation
override func main() {
print("📦⬇️: \(url.absoluteString)")
task.resume()
}
override func cancel() {
task.cancel()
super.cancel()
}
}
| mit | 34425a727235d34cfb8d300d46fb5acb | 28.053333 | 102 | 0.558513 | 5.091121 | false | false | false | false |
jopamer/swift | test/expr/unary/keypath/keypath.swift | 1 | 22724 | // RUN: %target-swift-frontend -typecheck -parse-as-library %s -verify
struct Sub: Hashable {
static func ==(_: Sub, _: Sub) -> Bool { return true }
var hashValue: Int { return 0 }
}
struct OptSub: Hashable {
static func ==(_: OptSub, _: OptSub) -> Bool { return true }
var hashValue: Int { return 0 }
}
struct NonHashableSub {}
struct Prop {
subscript(sub: Sub) -> A { get { return A() } set { } }
subscript(optSub: OptSub) -> A? { get { return A() } set { } }
subscript(nonHashableSub: NonHashableSub) -> A { get { return A() } set { } }
subscript(a: Sub, b: Sub) -> A { get { return A() } set { } }
subscript(a: Sub, b: NonHashableSub) -> A { get { return A() } set { } }
var nonMutatingProperty: B {
get { fatalError() }
nonmutating set { fatalError() }
}
}
struct A: Hashable {
init() { fatalError() }
var property: Prop
var optProperty: Prop?
let optLetProperty: Prop?
subscript(sub: Sub) -> A { get { return self } set { } }
static func ==(_: A, _: A) -> Bool { fatalError() }
var hashValue: Int { fatalError() }
}
struct B {}
struct C<T> {
var value: T
subscript() -> T { get { return value } }
subscript(sub: Sub) -> T { get { return value } set { } }
subscript<U: Hashable>(sub: U) -> U { get { return sub } set { } }
subscript<X>(noHashableConstraint sub: X) -> X { get { return sub } set { } }
}
struct Unavailable {
@available(*, unavailable)
var unavailableProperty: Int
// expected-note@-1 {{'unavailableProperty' has been explicitly marked unavailable here}}
@available(*, unavailable)
subscript(x: Sub) -> Int { get { } set { } }
// expected-note@-1 {{'subscript' has been explicitly marked unavailable here}}
}
struct Deprecated {
@available(*, deprecated)
var deprecatedProperty: Int
@available(*, deprecated)
subscript(x: Sub) -> Int { get { } set { } }
}
@available(*, deprecated)
func getDeprecatedSub() -> Sub {
return Sub()
}
extension Array where Element == A {
var property: Prop { fatalError() }
}
protocol P { var member: String { get } }
extension B : P { var member : String { return "Member Value" } }
struct Exactly<T> {}
func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {}
func testKeyPath(sub: Sub, optSub: OptSub,
nonHashableSub: NonHashableSub, x: Int) {
var a = \A.property
expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var b = \A.[sub]
expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self)
var c = \A.[sub].property
expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var d = \A.optProperty?
expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self)
var e = \A.optProperty?[sub]
expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self)
var f = \A.optProperty!
expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var g = \A.property[optSub]?.optProperty![sub]
expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self)
var h = \[A].property
expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self)
var i = \[A].property.nonMutatingProperty
expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self)
var j = \[A].[x]
expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self)
var k = \[A: B].[A()]
expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self)
var l = \C<A>.value
expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self)
// expected-error@+1{{generic parameter 'T' could not be inferred}}
_ = \C.value
// expected-error@+1{{}}
_ = \(() -> ()).noMember
let _: PartialKeyPath<A> = \.property
let _: KeyPath<A, Prop> = \.property
let _: WritableKeyPath<A, Prop> = \.property
// expected-error@+1{{ambiguous}} (need to improve diagnostic)
let _: ReferenceWritableKeyPath<A, Prop> = \.property
// FIXME: shouldn't be ambiguous
// expected-error@+1{{ambiguous}}
let _: PartialKeyPath<A> = \.[sub]
let _: KeyPath<A, A> = \.[sub]
let _: WritableKeyPath<A, A> = \.[sub]
// expected-error@+1{{ambiguous}} (need to improve diagnostic)
let _: ReferenceWritableKeyPath<A, A> = \.[sub]
let _: PartialKeyPath<A> = \.optProperty?
let _: KeyPath<A, Prop?> = \.optProperty?
// expected-error@+1{{cannot convert}}
let _: WritableKeyPath<A, Prop?> = \.optProperty?
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<A, Prop?> = \.optProperty?
let _: PartialKeyPath<A> = \.optProperty?[sub]
let _: KeyPath<A, A?> = \.optProperty?[sub]
// expected-error@+1{{cannot convert}}
let _: WritableKeyPath<A, A?> = \.optProperty?[sub]
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<A, A?> = \.optProperty?[sub]
let _: KeyPath<A, Prop> = \.optProperty!
let _: KeyPath<A, Prop> = \.optLetProperty!
let _: KeyPath<A, Prop?> = \.property[optSub]?.optProperty!
let _: KeyPath<A, A?> = \.property[optSub]?.optProperty![sub]
let _: PartialKeyPath<C<A>> = \.value
let _: KeyPath<C<A>, A> = \.value
let _: WritableKeyPath<C<A>, A> = \.value
// expected-error@+1{{ambiguous}} (need to improve diagnostic)
let _: ReferenceWritableKeyPath<C<A>, A> = \.value
let _: PartialKeyPath<C<A>> = \C.value
let _: KeyPath<C<A>, A> = \C.value
let _: WritableKeyPath<C<A>, A> = \C.value
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<C<A>, A> = \C.value
let _: PartialKeyPath<Prop> = \.nonMutatingProperty
let _: KeyPath<Prop, B> = \.nonMutatingProperty
let _: WritableKeyPath<Prop, B> = \.nonMutatingProperty
let _: ReferenceWritableKeyPath<Prop, B> = \.nonMutatingProperty
var m = [\A.property, \A.[sub], \A.optProperty!]
expect(&m, toHaveType: Exactly<[PartialKeyPath<A>]>.self)
// FIXME: shouldn't be ambiguous
// expected-error@+1{{ambiguous}}
var n = [\A.property, \.optProperty, \.[sub], \.optProperty!]
expect(&n, toHaveType: Exactly<[PartialKeyPath<A>]>.self)
// FIXME: shouldn't be ambiguous
// expected-error@+1{{ambiguous}}
let _: [PartialKeyPath<A>] = [\.property, \.optProperty, \.[sub], \.optProperty!]
var o = [\A.property, \C<A>.value]
expect(&o, toHaveType: Exactly<[AnyKeyPath]>.self)
let _: AnyKeyPath = \A.property
let _: AnyKeyPath = \C<A>.value
let _: AnyKeyPath = \.property // expected-error{{ambiguous}}
let _: AnyKeyPath = \C.value // expected-error{{cannot convert}} (need to improve diagnostic)
let _: AnyKeyPath = \.value // expected-error{{ambiguous}}
let _ = \Prop.[nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \Prop.[sub, sub]
let _ = \Prop.[sub, nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \C<Int>.[]
let _ = \C<Int>.[sub]
let _ = \C<Int>.[noHashableConstraint: sub]
let _ = \C<Int>.[noHashableConstraint: nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \Unavailable.unavailableProperty // expected-error {{'unavailableProperty' is unavailable}}
let _ = \Unavailable.[sub] // expected-error {{'subscript' is unavailable}}
let _ = \Deprecated.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated}}
let _ = \Deprecated.[sub] // expected-warning {{'subscript' is deprecated}}
let _ = \A.[getDeprecatedSub()] // expected-warning {{'getDeprecatedSub()' is deprecated}}
}
func testKeyPathInGenericContext<H: Hashable, X>(hashable: H, anything: X) {
let _ = \C<Int>.[hashable]
let _ = \C<Int>.[noHashableConstraint: hashable]
let _ = \C<Int>.[noHashableConstraint: anything] // expected-error{{subscript index of type 'X' in a key path must be Hashable}}
}
func testDisembodiedStringInterpolation(x: Int) {
\(x) // expected-error{{string interpolation}} expected-error{{}}
\(x, radix: 16) // expected-error{{string interpolation}} expected-error{{}}
_ = \(Int, Int).0 // expected-error{{cannot reference tuple elements}}
}
func testNoComponents() {
let _: KeyPath<A, A> = \A // expected-error{{must have at least one component}}
let _: KeyPath<C, A> = \C // expected-error{{must have at least one component}} expected-error{{}}
}
struct TupleStruct {
var unlabeled: (Int, String)
var labeled: (foo: Int, bar: String)
}
func tupleComponent() {
// TODO: Customized diagnostic
let _ = \(Int, String).0 // expected-error{{}}
let _ = \(Int, String).1 // expected-error{{}}
let _ = \TupleStruct.unlabeled.0 // expected-error{{}}
let _ = \TupleStruct.unlabeled.1 // expected-error{{}}
let _ = \(foo: Int, bar: String).0 // expected-error{{}}
let _ = \(foo: Int, bar: String).1 // expected-error{{}}
let _ = \(foo: Int, bar: String).foo // expected-error{{}}
let _ = \(foo: Int, bar: String).bar // expected-error{{}}
let _ = \TupleStruct.labeled.0 // expected-error{{}}
let _ = \TupleStruct.labeled.1 // expected-error{{}}
let _ = \TupleStruct.labeled.foo // expected-error{{}}
let _ = \TupleStruct.labeled.bar // expected-error{{}}
}
struct Z { }
func testKeyPathSubscript(readonly: Z, writable: inout Z,
kp: KeyPath<Z, Int>,
wkp: WritableKeyPath<Z, Int>,
rkp: ReferenceWritableKeyPath<Z, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
let pkp: PartialKeyPath = rkp
var anySink1 = readonly[keyPath: pkp]
expect(&anySink1, toHaveType: Exactly<Any>.self)
var anySink2 = writable[keyPath: pkp]
expect(&anySink2, toHaveType: Exactly<Any>.self)
readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign to immutable}}
writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign to immutable}}
let akp: AnyKeyPath = pkp
var anyqSink1 = readonly[keyPath: akp]
expect(&anyqSink1, toHaveType: Exactly<Any?>.self)
var anyqSink2 = writable[keyPath: akp]
expect(&anyqSink2, toHaveType: Exactly<Any?>.self)
readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign to immutable}}
writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign to immutable}}
}
struct ZwithSubscript {
subscript(keyPath kp: KeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: WritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: ReferenceWritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: PartialKeyPath<ZwithSubscript>) -> Any { return 0 }
}
struct NotZ {}
func testKeyPathSubscript(readonly: ZwithSubscript, writable: inout ZwithSubscript,
wrongType: inout NotZ,
kp: KeyPath<ZwithSubscript, Int>,
wkp: WritableKeyPath<ZwithSubscript, Int>,
rkp: ReferenceWritableKeyPath<ZwithSubscript, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}}
writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: subscript is get-only}}
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: wkp] = sink
// FIXME: silently falls back to keypath application, which seems inconsistent
readonly[keyPath: rkp] = sink
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: rkp] = sink
let pkp: PartialKeyPath = rkp
var anySink1 = readonly[keyPath: pkp]
expect(&anySink1, toHaveType: Exactly<Any>.self)
var anySink2 = writable[keyPath: pkp]
expect(&anySink2, toHaveType: Exactly<Any>.self)
readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: subscript is get-only}}
writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: subscript is get-only}}
let akp: AnyKeyPath = pkp
var anyqSink1 = readonly[keyPath: akp]
expect(&anyqSink1, toHaveType: Exactly<Any?>.self)
var anyqSink2 = writable[keyPath: akp]
expect(&anyqSink2, toHaveType: Exactly<Any?>.self)
// FIXME: silently falls back to keypath application, which seems inconsistent
readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign to immutable}}
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign to immutable}}
_ = wrongType[keyPath: kp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: wkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: rkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: pkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: akp]
}
func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type,
kp: KeyPath<Z.Type, Int>,
wkp: WritableKeyPath<Z.Type, Int>,
rkp: ReferenceWritableKeyPath<Z.Type, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
}
func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z),
kp: KeyPath<(Z,Z), Int>,
wkp: WritableKeyPath<(Z,Z), Int>,
rkp: ReferenceWritableKeyPath<(Z,Z), Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: kp] = sink // expected-error{{cannot assign to immutable}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign to immutable}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
}
func testKeyPathSubscriptLValue(base: Z, kp: inout KeyPath<Z, Z>) {
_ = base[keyPath: kp]
}
func testKeyPathSubscriptExistentialBase(concreteBase: inout B,
existentialBase: inout P,
kp: KeyPath<P, String>,
wkp: WritableKeyPath<P, String>,
rkp: ReferenceWritableKeyPath<P, String>,
pkp: PartialKeyPath<P>,
s: String) {
_ = concreteBase[keyPath: kp]
_ = concreteBase[keyPath: wkp]
_ = concreteBase[keyPath: rkp]
_ = concreteBase[keyPath: pkp]
concreteBase[keyPath: kp] = s // expected-error{{}}
concreteBase[keyPath: wkp] = s // expected-error{{}}
concreteBase[keyPath: rkp] = s
concreteBase[keyPath: pkp] = s // expected-error{{}}
_ = existentialBase[keyPath: kp]
_ = existentialBase[keyPath: wkp]
_ = existentialBase[keyPath: rkp]
_ = existentialBase[keyPath: pkp]
existentialBase[keyPath: kp] = s // expected-error{{}}
existentialBase[keyPath: wkp] = s
existentialBase[keyPath: rkp] = s
existentialBase[keyPath: pkp] = s // expected-error{{}}
}
struct AA {
subscript(x: Int) -> Int { return x }
subscript(labeled x: Int) -> Int { return x }
var c: CC? = CC()
}
class CC {
var i = 0
}
func testKeyPathOptional() {
_ = \AA.c?.i
_ = \AA.c!.i
// SR-6198
let path: KeyPath<CC,Int>! = \CC.i
let cc = CC()
_ = cc[keyPath: path]
}
func testLiteralInAnyContext() {
let _: AnyKeyPath = \A.property
let _: AnyObject = \A.property
let _: Any = \A.property
let _: Any? = \A.property
}
func testMoreGeneralContext<T, U>(_: KeyPath<T, U>, with: T.Type) {}
func testLiteralInMoreGeneralContext() {
testMoreGeneralContext(\.property, with: A.self)
}
func testLabeledSubscript() {
let _: KeyPath<AA, Int> = \AA.[labeled: 0]
let _: KeyPath<AA, Int> = \.[labeled: 0]
let k = \AA.[labeled: 0]
// TODO: These ought to work without errors.
let _ = \AA.[keyPath: k] // expected-error{{}}
let _ = \AA.[keyPath: \AA.[labeled: 0]] // expected-error{{}}
}
func testInvalidKeyPathComponents() {
let _ = \.{return 0} // expected-error* {{}}
}
class X {
class var a: Int { return 1 }
static var b = 2
}
func testStaticKeyPathComponent() {
_ = \X.a // expected-error{{}}
_ = \X.Type.a // expected-error{{cannot refer to static member}}
_ = \X.b // expected-error{{}}
_ = \X.Type.b // expected-error{{cannot refer to static member}}
}
class Bass: Hashable {
static func ==(_: Bass, _: Bass) -> Bool { return false }
var hashValue: Int { return 0 }
}
class Treble: Bass { }
struct BassSubscript {
subscript(_: Bass) -> Int { fatalError() }
subscript(_: @autoclosure () -> String) -> Int { fatalError() }
}
func testImplicitConversionInSubscriptIndex() {
_ = \BassSubscript.[Treble()]
_ = \BassSubscript.["hello"] // expected-error{{must be Hashable}}
}
// Crash in diagnostics
struct AmbiguousSubscript {
subscript(sub: Sub) -> Int { get { } set { } }
// expected-note@-1 {{'subscript' declared here}}
subscript(y y: Sub) -> Int { get { } set { } }
// expected-note@-1 {{'subscript(y:)' declared here}}
}
func useAmbiguousSubscript(_ sub: Sub) {
let _: PartialKeyPath<AmbiguousSubscript> = \.[sub]
// expected-error@-1 {{ambiguous reference to member 'subscript'}}
}
struct BothUnavailableSubscript {
@available(*, unavailable)
subscript(sub: Sub) -> Int { get { } set { } }
@available(*, unavailable)
subscript(y y: Sub) -> Int { get { } set { } }
}
func useBothUnavailableSubscript(_ sub: Sub) {
let _: PartialKeyPath<BothUnavailableSubscript> = \.[sub]
// expected-error@-1 {{type of expression is ambiguous without more context}}
}
// SR-6106
func sr6106() {
class B {}
class A {
var b: B? = nil
}
class C {
var a: A?
func myFunc() {
let _ = \C.a?.b
}
}
}
// SR-6744
func sr6744() {
struct ABC {
let value: Int
func value(adding i: Int) -> Int { return value + i }
}
let abc = ABC(value: 0)
func get<T>(for kp: KeyPath<ABC, T>) -> T {
return abc[keyPath: kp]
}
_ = get(for: \.value)
}
func sr7380() {
_ = ""[keyPath: \.count]
_ = ""[keyPath: \String.count]
let arr1 = [1]
_ = arr1[keyPath: \.[0]]
_ = arr1[keyPath: \[Int].[0]]
let dic1 = [1:"s"]
_ = dic1[keyPath: \.[1]]
_ = dic1[keyPath: \[Int: String].[1]]
var arr2 = [1]
arr2[keyPath: \.[0]] = 2
arr2[keyPath: \[Int].[0]] = 2
var dic2 = [1:"s"]
dic2[keyPath: \.[1]] = ""
dic2[keyPath: \[Int: String].[1]] = ""
_ = [""][keyPath: \.[0]]
_ = [""][keyPath: \[String].[0]]
_ = ["": ""][keyPath: \.["foo"]]
_ = ["": ""][keyPath: \[String: String].["foo"]]
class A {
var a: String = ""
}
_ = A()[keyPath: \.a]
_ = A()[keyPath: \A.a]
A()[keyPath: \.a] = ""
A()[keyPath: \A.a] = ""
}
struct VisibilityTesting {
private(set) var x: Int
fileprivate(set) var y: Int
let z: Int
// Key path exprs should not get special dispensation to write to lets
// in init contexts
init() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
// Allow WritableKeyPath for Swift 3/4 only.
expect(&zRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
}
func inPrivateContext() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&zRef,
toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self)
}
}
struct VisibilityTesting2 {
func inFilePrivateContext() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
// Allow WritableKeyPath for Swift 3/4 only.
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&zRef,
toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self)
}
}
protocol PP {}
class Base : PP { var i: Int = 0 }
class Derived : Base {}
func testSubtypeKeypathClass(_ keyPath: ReferenceWritableKeyPath<Base, Int>) {
testSubtypeKeypathClass(\Derived.i)
}
func testSubtypeKeypathProtocol(_ keyPath: ReferenceWritableKeyPath<PP, Int>) {
testSubtypeKeypathProtocol(\Base.i) // expected-error {{type 'PP' has no member 'i'}}
}
// rdar://problem/32057712
struct Container {
let base: Base? = Base()
}
var rdar32057712 = \Container.base?.i
func testSyntaxErrors() { // expected-note{{}}
_ = \. ; // expected-error{{expected member name following '.'}}
_ = \.a ;
_ = \[a ;
_ = \[a];
_ = \? ;
_ = \! ;
_ = \. ; // expected-error{{expected member name following '.'}}
_ = \.a ;
_ = \[a ;
_ = \[a,;
_ = \[a:;
_ = \[a];
_ = \.a?;
_ = \.a!;
_ = \A ;
_ = \A, ;
_ = \A< ;
_ = \A. ; // expected-error{{expected member name following '.'}}
_ = \A.a ;
_ = \A[a ;
_ = \A[a];
_ = \A? ;
_ = \A! ;
_ = \A. ; // expected-error{{expected member name following '.'}}
_ = \A.a ;
_ = \A[a ;
_ = \A[a,;
_ = \A[a:;
_ = \A[a];
_ = \A.a?;
_ = \A.a!;
} // expected-error@+1{{}}
| apache-2.0 | 31df4b3210728449c4a8858634c60a5d | 31.743516 | 149 | 0.634395 | 3.731976 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationMock/WalletAuthentication/MockDeviceVerificationService.swift | 1 | 3714 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
@testable import FeatureAuthenticationDomain
import Foundation
final class MockDeviceVerificationService: DeviceVerificationServiceAPI {
// swiftlint:disable line_length
static let validDeeplink = URL(string: "https://login.blockchain.com/#/login/eyJndWlkIjoiNzRjNzZlOTMtZWUwZi00ZjllLWJmYTYtNzE2ZTg0N2EwMmQ5IiwiZW1haWwiOiJncmF5c29uQGJsb2NrY2hhaW4uY29tIiwiaXNfbW9iaWxlX3NldHVwIjpmYWxzZSwiaGFzX2Nsb3VkX2JhY2t1cCI6ZmFsc2UsImVtYWlsX2NvZGUiOiJCcmgxa252NFh6eEg3bmZITnRzZE5uWVpWbFZvQ1BTWlBJVUNBUWIvTDB6eG1xVFg0OVNDR0QxRURhQ3FWMFJ1R3VxQ2xacHYyUjBVTldHdGdnd08rV29aZTd3SzlPUTRNWE5uZEFxdTVDQkJsQUpXaFIrWUttbTRmbVlBN25KRklpMi9MQjlsMkFpSmZuWUpMMndmUnN4czNNc0RzbGFud1lmc1c4Yyt2NVJHb3dvVk91V1BoYUZnSXZyakg4MzUifQ")!
static let invalidDeeplink = URL(string: "https://")!
static let deeplinkWithValidGuid = URL(string: "https://login.blockchain.com/#/login/cd76e920-7a39-4458-829a-1bb752ef628d")!
static let mockWalletInfo = WalletInfo(
wallet: WalletInfo.Wallet(
guid: "cd76e920-7a39-4458-829a-1bb752ef628d",
email: "[email protected]",
emailCode: "example email code",
isMobileSetup: false,
hasCloudBackup: false,
nabu: nil
)
)
static let mockWalletInfoWithTwoFA = WalletInfo(
wallet: WalletInfo.Wallet(
guid: "cd76e920-7a39-4458-829a-1bb752ef628d",
email: "[email protected]",
twoFaType: .sms,
emailCode: "example email code",
isMobileSetup: false,
hasCloudBackup: false,
sessionId: nil
)
)
static let mockWalletInfoWithGuidOnly = WalletInfo(
wallet: WalletInfo.Wallet(
guid: "cd76e920-7a39-4458-829a-1bb752ef628d"
)
)
var expectedSessionMismatch: Bool = false
func sendDeviceVerificationEmail(
to emailAddress: String
) -> AnyPublisher<Void, DeviceVerificationServiceError> {
// always succeed
.just(())
}
func authorizeLogin(emailCode: String) -> AnyPublisher<Void, DeviceVerificationServiceError> {
// always succeed
.just(())
}
func handleLoginRequestDeeplink(url deeplink: URL) -> AnyPublisher<WalletInfo, WalletInfoError> {
if expectedSessionMismatch {
return .failure(
.sessionTokenMismatch(originSession: "", base64Str: "")
)
}
if deeplink == MockDeviceVerificationService.validDeeplink {
return .just(MockDeviceVerificationService.mockWalletInfo)
} else if deeplink == MockDeviceVerificationService.deeplinkWithValidGuid {
return .just(MockDeviceVerificationService.mockWalletInfoWithGuidOnly)
} else {
return .failure(.failToDecodeBase64Component)
}
}
func pollForWalletInfo() -> AnyPublisher<Result<WalletInfo, WalletInfoPollingError>, DeviceVerificationServiceError> {
.just(.success(MockDeviceVerificationService.mockWalletInfo))
}
func authorizeVerifyDevice(from sessionToken: String, payload: String, confirmDevice: Bool?) -> AnyPublisher<Void, AuthorizeVerifyDeviceError> {
guard let confirmDevice = confirmDevice else {
return .failure(
.confirmationRequired(
requestTime: Date(timeIntervalSince1970: 1000),
details: DeviceVerificationDetails(originLocation: "", originIP: "", originBrowser: "")
)
)
}
if confirmDevice {
return .just(())
} else {
return .failure(.requestDenied)
}
}
}
| lgpl-3.0 | c51ca1a1212eae57c6ad7e9fec9a7f88 | 39.358696 | 534 | 0.682736 | 3.742944 | false | false | false | false |
wayfindrltd/wayfindr-demo-ios | Wayfindr DemoTests/Classes/Controller/User/DirectionsPreviewViewController_Tests.swift | 1 | 3196 | ////
//// DirectionsPreviewViewController_Tests.swift
//// Wayfindr Demo
////
//// Created by Wayfindr on 20/11/2015.
//// Copyright (c) 2016 Wayfindr (http://www.wayfindr.net)
////
//// 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 XCTest
//import CoreLocation
//
//@testable import Wayfindr_Demo
//
//
//class DirectionsPreviewViewController_Tests : XCTestCase {
//
// // MARK: - Properties
//
// var viewController: DirectionsPreviewViewController!
//
// var mockInterface = MockBeaconInterface()
// let speechEngine = AudioEngine()
//
// let fakeBeacon = CLBeacon()
//
//
// // MARK: - Setup/Teardown
//
// override func setUp() {
// super.setUp()
//
// guard let venue = testVenue() else {
// XCTFail("Unable to load test data.")
// return
// }
//
// let singlePathItem = venue.destinationGraph.edges[0]
// let firstNode = venue.destinationGraph.getNode(identifier: singlePathItem.sourceID)!
// //loadFakeBeacon(firstNode.minor)
//
// viewController = DirectionsPreviewViewController(interface: mockInterface, venue: venue, route: [singlePathItem], startingBeacon: WAYBeacon(beacon: fakeBeacon), speechEngine: speechEngine)
//
// UIApplication.shared.keyWindow!.rootViewController = viewController
//
// // Test and Load the View at the Same Time!
// XCTAssertNotNil(viewController.view)
// }
//
// fileprivate func loadFakeBeacon(_ minor: Int) {
// fakeBeacon.setValue(1, forKey: "major")
// fakeBeacon.setValue(minor, forKey: "minor")
// fakeBeacon.setValue(0.12345, forKey: "accuracy")
// fakeBeacon.setValue(-68, forKey: "rssi")
// fakeBeacon.setValue(CLProximity.near.rawValue, forKey: "proximity")
// }
//
//
// // MARK: - Tests
//
//// func testLoad() {
//// XCTAssertTrue(true)
//// }
//
// func testViewDidAppear() {
// viewController.viewDidAppear(false)
//
// XCTAssertTrue(true)
// }
//
//}
//
| mit | 2362fea828fefeb586b374445fe63bfa | 35.318182 | 198 | 0.644556 | 4.081737 | false | true | false | false |
powerytg/PearlCam | PearlCam/PearlFX/Components/FilterSelectorView.swift | 2 | 4619 | //
// FilterSelectorView.swift
// Accented
//
// PearlFX filter selector view
//
// Created by You, Tiangong on 6/9/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import GPUImage
protocol FilterSelectorViewDelegate : NSObjectProtocol {
func didSelectColorPreset(_ colorPreset : String?)
}
class FilterSelectorView : UIView {
var filterManager : FilterManager!
var previewImage : UIImage! {
didSet {
didSetPreviewImage()
}
}
private let scrollView = UIScrollView()
private let contentView = UIView()
static let thumbnailSize : CGFloat = 60
private let gap : CGFloat = 10
private let padding : CGFloat = 10
private var thumbnails = [ColorPresetThumbnailView]()
private var previewInput : PictureInput!
private var previewOutputs = [PictureOutput]()
private var selectedThumbnail : ColorPresetThumbnailView?
var selectedColorPreset : String?
weak var delegate : FilterSelectorViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(scrollView)
scrollView.addSubview(contentView)
}
func didSetPreviewImage() {
previewInput = PictureInput(image: previewImage)
// Create a "reset" thumbnail
createColorPresetThumbnail(nil)
// Create LUT thumbnails
for lookupImage in filterManager.colorPresets {
createColorPresetThumbnail(lookupImage)
}
// By default, select the first preset (which should be the null preset that outputs the original photo)
let firstThumbnail = thumbnails[0]
firstThumbnail.isSelected = true
selectedColorPreset = firstThumbnail.colorPresetImageName
selectedThumbnail = firstThumbnail
previewInput.processImage()
setNeedsLayout()
}
private func createColorPresetThumbnail(_ presetImageName : String?) {
let thumbnailBounds = CGRect(x: 0, y: 0, width: FilterSelectorView.thumbnailSize, height: FilterSelectorView.thumbnailSize)
let thumbnail = ColorPresetThumbnailView(colorPresetImageName: presetImageName, frame : thumbnailBounds)
contentView.addSubview(thumbnail)
thumbnails.append(thumbnail)
if let lookupImageName = presetImageName {
let filter = LookupFilter()
let previewOutput = PictureOutput()
previewOutputs.append(previewOutput)
previewOutput.imageAvailableCallback = { (image) in
DispatchQueue.main.async {
thumbnail.previewImage = image
}
}
filter.lookupImage = PictureInput(imageName: lookupImageName)
previewInput --> filter --> previewOutput
} else {
thumbnail.previewImage = previewImage
}
// Tap event
let tap = UITapGestureRecognizer(target: self, action: #selector(didTapOnThumbnail(_:)))
thumbnail.addGestureRecognizer(tap)
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame = self.bounds
var nextX : CGFloat = padding
let originY : CGFloat = bounds.height / 2 - FilterSelectorView.thumbnailSize / 2
for thumbnail in thumbnails {
thumbnail.frame.origin.x = nextX
thumbnail.frame.origin.y = originY
thumbnail.frame.size = CGSize(width: FilterSelectorView.thumbnailSize, height: FilterSelectorView.thumbnailSize)
nextX += FilterSelectorView.thumbnailSize + gap
}
let contentWidth : CGFloat = nextX + padding
contentView.frame = CGRect(x: 0, y: 0, width: contentWidth, height: self.bounds.height)
scrollView.contentSize = CGSize(width: contentWidth, height: self.bounds.height)
}
@objc private func didTapOnThumbnail(_ tap : UITapGestureRecognizer) {
let thumbnail = tap.view as! ColorPresetThumbnailView
if let previousSelectedThumbnail = selectedThumbnail {
previousSelectedThumbnail.isSelected = false
}
thumbnail.isSelected = true
selectedThumbnail = thumbnail
selectedColorPreset = thumbnail.colorPresetImageName
delegate?.didSelectColorPreset(selectedColorPreset)
}
}
| bsd-3-clause | 936f3c8dcac7b799df5c72e0dbeecf80 | 32.708029 | 131 | 0.645951 | 5.344907 | false | false | false | false |
nighttime/EchoiOS | Echo/EchoNetwork.swift | 1 | 2203 | //
// EchoNetwork.swift
// Echo
//
// Created by Nick McKenna on 11/3/14.
// Copyright (c) 2014 nighttime software. All rights reserved.
//
import UIKit
import CoreLocation
import Alamofire
/*
* Behavior of Network Operations
*
* - User must get immediate feedback and regain control of the app
* • If the server is unreachable or returns an error, silently cache message and try to send later
*
*/
class EchoNetwork {
class func echo(textContent: String, callback: (NSError?) -> ()) {
var location = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
if let loc = locationManager.location {
location = loc.coordinate
}
let lat: Double = location.latitude
let lon: Double = location.longitude
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let time = formatter.stringFromDate(NSDate())
var params: [String:AnyObject] =
[
"lat" : lat,
"lon" : lon,
"datetime" : time,
"echo_count" : 1,
"echoContent" : textContent,
"contentType" : 0
]
Alamofire.request(.POST, "http://www.echo2.me/echoPost/return_echo", parameters: params, encoding: .JSON).response {(request, response, data, error) in
callback(error)
}
}
class func echoBack(delete: Bool, var parameters: [String:AnyObject], callback: (NSError?) -> ()) {
parameters["deleted"] = NSNumber(bool: delete)
Alamofire.request(.POST, "http://www.echo2.me/echoPost/return_echo", parameters: parameters, encoding: .JSON).response {(request, response, data, error) in
callback(error)
}
}
class func listen(callback: ([String:AnyObject]?, NSError?) -> ()) {
Alamofire.request(.GET, "http://www.echo2.me/echoGet/get_echo")
.responseJSON {(request, response, JSON, error) in
println(response)
println(JSON)
println(error)
println("------------")
callback(JSON as? [String:AnyObject], error)
}
}
}
| mit | f1f9e9fd1a98851608c384d7a60eeba9 | 30.442857 | 163 | 0.5811 | 4.265504 | false | false | false | false |
tjw/swift | test/SILGen/enum_resilience_testable.swift | 1 | 2834 | // REQUIRES: plus_zero_runtime
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift -enable-testing
// RUN: %target-swift-frontend -module-name enum_resilience_testable -I %t -enable-sil-ownership -emit-silgen -enable-nonfrozen-enum-exhaustivity-diagnostics -swift-version 5 %s | %FileCheck %s
// This is mostly testing the same things as enum_resilienc.swift, just in a
// context where the user will never be forced to write a default case. It's the
// same effect as -swift-version 4 and ignoring the exhaustivity warning,
// though.
@testable import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden @$S24enum_resilience_testable15resilientSwitchyy0d1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]
// CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: destroy_value [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick Medium.Type, [[BOX]] : $*Medium
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<Medium>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NOT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(_ m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
| apache-2.0 | a112c7a28accd117df16028990108f57 | 47.827586 | 209 | 0.659958 | 3.281576 | false | true | false | false |
scoremedia/Fisticuffs | Tests/FisticuffsTests/MemoryManagementSpec.swift | 1 | 3909 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Quick
import Nimble
@testable import Fisticuffs
class MemoryManagementSpec: QuickSpec {
override func spec() {
describe("Observable") {
it("should not be referenced strongly by its subscriptions") {
weak var weakObservable: Observable<String>?
autoreleasepool {
let observable: Observable<String>? = Observable("test")
weakObservable = observable
_ = observable?.subscribe { }
// observable should dealloc here
}
expect(weakObservable).to(beNil())
}
}
describe("Computed") {
it("should not be referenced strongly by its subscriptions") {
weak var weakComputed: Computed<String>?
autoreleasepool {
let computed: Computed<String>? = Computed { "Hello" }
weakComputed = computed
_ = computed?.subscribe { }
// computed should dealloc here
}
expect(weakComputed).to(beNil())
}
}
describe("UIKit") {
it("should dispose of any subscriptions on dealloc") {
weak var weakObservable: Observable<String>?
autoreleasepool {
let observable = Observable("testing memory management")
weakObservable = observable
let textField = UITextField()
textField.b_text.bind(observable)
}
// if textField properly disposed of it's subscriptions, the object weakObservable
// is pointing at will have been dealloc'd
expect(weakObservable).to(beNil())
}
it("should release any actions on dealloc") {
class NoopViewModel {
func noop() { }
}
weak var weakViewModel: NoopViewModel?
autoreleasepool {
let viewModel = NoopViewModel()
weakViewModel = viewModel
let button = UIButton()
_ = button.b_onTap.subscribe(viewModel.noop)
}
// if button correctly disposes of the tap listener, view model should be dealloc'd
expect(weakViewModel).to(beNil())
}
}
}
}
| mit | 0e73aa8ebad2673a5016042ccafda5e5 | 37.70297 | 99 | 0.543617 | 5.834328 | false | false | false | false |
mcarter6061/FetchedResultsCoordinator | Pod/Classes/TableSelection.swift | 1 | 2375 | // Copyright © 2016 Mark Carter. All rights reserved.
import Foundation
public protocol TableSelection {
associatedtype ObjectType
func selectObjects(tableView:UITableView, objects: [ObjectType] )
func selectedObjects(tableView: UITableView) -> [ObjectType]
func selectedObject(tableView: UITableView) -> ObjectType?
func indexPathForObject( object:ObjectType) -> NSIndexPath?
func objectAtIndexPath( indexPath:NSIndexPath ) -> ObjectType
}
extension TableSelection {
/// Selects the table view rows for the `objects` passed in
public func selectObjects( tableView:UITableView, objects: [ObjectType] ) {
let indexPathsForObjects = objects.flatMap(indexPathForObject)
indexPathsForObjects.forEach{tableView.selectRowAtIndexPath($0, animated: false, scrollPosition: .None)}
}
/// Returns underlying `ObjectType` objects for the selected rows of a table view that allows multiple selection
public func selectedObjects(tableView: UITableView) -> [ObjectType] {
return tableView.indexPathsForSelectedRows?.map{objectAtIndexPath($0)} ?? []
}
/// Returns underlying `ObjectType` objects for the selected row
public func selectedObject(tableView: UITableView) -> ObjectType? {
return tableView.indexPathForSelectedRow.map{objectAtIndexPath($0)}
}
}
extension FetchedTableDataSource: TableSelection {
public func objectAtIndexPath( indexPath: NSIndexPath ) -> ManagedObjectType {
guard let object = fetchedResultsController.objectAtIndexPath(indexPath) as? ManagedObjectType else {
fatalError("Wrong object type")
}
return object
}
public func indexPathForObject(object: ManagedObjectType) -> NSIndexPath? {
return fetchedResultsController.indexPathForObject(object)
}
}
extension ListTableDataSource: TableSelection {
public func objectAtIndexPath( indexPath: NSIndexPath ) -> ObjectType {
guard indexPath.section == 0 else { fatalError("Only single section supported by ListTableDataSource currently") }
return data[indexPath.row]
}
public func indexPathForObject(object: ObjectType) -> NSIndexPath? {
guard let row = data.indexOf(object) else { return nil }
return NSIndexPath(forRow: row, inSection: 0)
}
}
| mit | c06f982c45cd1db5114b02ae70e33089 | 35.523077 | 122 | 0.713564 | 5.470046 | false | false | false | false |
r-peck/Focus | Tests/UserExample.swift | 2 | 793 | //
// UserExample.swift
// swiftz
//
// Created by Maxwell Swadling on 9/06/2014.
// Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved.
//
import Focus
// A user example
// an example of why we need SYB, Generics or macros
open class User {
let name : String
let age : Int
let tweets : [String]
let attr : String
public init(_ n : String, _ a : Int, _ t : [String], _ r : String) {
name = n
age = a
tweets = t
attr = r
}
// lens example
open class func luserName() -> Lens<User, User, String, String> {
return Lens { user in IxStore(user.name) { User($0, user.age, user.tweets, user.attr) } }
}
}
public func ==(lhs : User, rhs : User) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age && lhs.tweets == rhs.tweets && lhs.attr == rhs.attr
}
| mit | 59a516ff2e1956c564b0a339d4daa109 | 22.323529 | 102 | 0.625473 | 2.970037 | false | false | false | false |
powerytg/Accented | Accented/UI/PearlCam/CameraUIViewController.swift | 1 | 16697 | //
// CameraUIViewController.swift
// Accented
//
// PearlCam camera UI overlay controller
//
// Created by Tiangong You on 6/3/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import AVFoundation
import CRRulerControl
protocol CameraOverlayDelegate : NSObjectProtocol {
func switchCameraButtonDidTap()
func shutterButtonDidTap()
func didTapOnViewFinder(_ point : CGPoint)
func didLongPressOnViewFinder(_ point : CGPoint)
func userDidChangeExpComp(_ ec : Float)
func userDidChangeShutterSpeed(_ shutterSpeed : CMTime)
func userDidChangeISO(_ iso : Float)
func userDidChangeFlashMode()
func userDidUnlockAEL()
func autoManualModeButtonDidTap()
func backButtonDidTap()
}
class CameraUIViewController: UIViewController, MeterViewDelegate {
@IBOutlet weak var expControlLabel: UILabel!
@IBOutlet weak var switchCameraButton: UIButton!
@IBOutlet weak var shutterButton: UIButton!
@IBOutlet weak var exposureView: UIView!
@IBOutlet weak var exposureIndicator: UIImageView!
@IBOutlet weak var shutterSpeedLabel: UILabel!
@IBOutlet weak var expControlView: UIStackView!
@IBOutlet weak var isoLabel: UILabel!
@IBOutlet weak var exposureIndicatorCenterConstraint: NSLayoutConstraint!
@IBOutlet weak var lightMeterWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var exposureModeButton: UIButton!
@IBOutlet weak var isoControlView: UIView!
@IBOutlet weak var osdLabel: UILabel!
@IBOutlet weak var aelButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var backButton: UIButton!
private var exposureIndicatorOffset : CGFloat = 2
private var viewFinder : ViewFinder?
var iso : Float?
var minISO : Float?
var maxISO : Float?
var maxZoomFactor : CGFloat?
var minShutterSpeed : CMTime?
var maxShutterSpeed : CMTime?
var minExpComp : Float?
var maxExpComp : Float?
var isManualExpModeSupported : Bool?
var isAutoExpModeSupported : Bool?
var isContinuousAutoExpModeSupported : Bool?
var expComp : Float = 0
private var exposureMode : AVCaptureExposureMode?
private let defaultISO : Float = 100
private var currentShutterSpeed : CMTime?
weak var delegate : CameraOverlayDelegate?
// Current slider view
var currentMeter : MeterType?
private var currentMeterView : MeterView?
private let meterViewHeight : CGFloat = 70
private let exposureMeterScale : Float = 1000
private var isLockingExposure = false
// OSD text
private var osdAttributes = [String : Any]()
override func viewDidLoad() {
super.viewDidLoad()
exposureView.layer.cornerRadius = 8
osdAttributes = [NSStrokeColorAttributeName : UIColor.black,
NSStrokeWidthAttributeName : -1]
osdLabel.layer.shadowOffset = CGSize(width: 0, height: 1.0)
osdLabel.layer.shadowRadius = 13.0
osdLabel.layer.shadowOpacity = 0.85
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func previewDidBecomeAvailable(previewLayer : AVCaptureVideoPreviewLayer) {
if viewFinder != nil && viewFinder?.previewLayer == previewLayer {
return
}
if let viewFinder = self.viewFinder {
viewFinder.removeFromSuperview()
}
viewFinder = ViewFinder(previewLayer: previewLayer, frame: view.bounds)
view.insertSubview(viewFinder!, at: 0)
// Events
let tap = UITapGestureRecognizer(target: self, action: #selector(didTapOnViewFinder(_:)))
viewFinder!.addGestureRecognizer(tap)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressOnViewFinder(_:)))
viewFinder!.addGestureRecognizer(longPress)
let expTap = UITapGestureRecognizer(target: self, action: #selector(didTapOnExpControl(_:)))
expControlView.addGestureRecognizer(expTap)
let isoTap = UITapGestureRecognizer(target: self, action: #selector(didTapOnISOControl(_:)))
isoControlView.addGestureRecognizer(isoTap)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// We always take the default, fixed 4/3 photo, so position the preview layer accordingly
if let viewFinder = self.viewFinder {
let aspectRatio = CGFloat(4.0 / 3.0)
viewFinder.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height / aspectRatio)
}
}
func showMessage(_ message : String) {
let text = NSAttributedString(string: message.uppercased(), attributes: osdAttributes)
osdLabel.attributedText = text
UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseInOut, animations: { [weak self] in
self?.osdLabel.transform = CGAffineTransform(translationX: 0, y: -8)
self?.osdLabel.alpha = 1.0
}) { (finished) in
UIView.animate(withDuration: 0.3, delay: 2.0, options: .curveEaseInOut, animations: { [weak self] in
self?.osdLabel.alpha = 0
self?.osdLabel.transform = CGAffineTransform.identity
}, completion: nil)
}
}
func focusPointDidChange(_ point: CGPoint) {
if let viewFinder = viewFinder {
viewFinder.focusPointDidChange(point)
}
}
func focusDidStart(){
if let viewFinder = viewFinder {
viewFinder.focusDidStart()
}
}
func focusDidStop() {
if let viewFinder = viewFinder {
viewFinder.focusDidStop()
}
}
func exposurePointDidChange(_ point : CGPoint) {
if let viewFinder = viewFinder {
viewFinder.aelPointDidChange(point)
}
}
func lightMeterReadingDidChange(_ offset: Float) {
let value = CGFloat(offset + expComp)
let lightMeterWidth = lightMeterWidthConstraint.constant
let step = lightMeterWidth / 18.0
var position : CGFloat = value * step
position = max(min(position, lightMeterWidth / 2), -lightMeterWidth / 2)
exposureIndicatorCenterConstraint.constant = position + exposureIndicatorOffset
}
func shutterSpeedReadingDidChange(_ duration: CMTime) {
currentShutterSpeed = duration
shutterSpeedLabel.text = formatExposureLabel(duration)
}
func isoReadingDidChange(_ iso : Float) {
self.iso = iso
let displayValue = Int(iso)
isoLabel.text = "\(displayValue)"
}
func exposureModeDidChange(_ mode : AVCaptureExposureMode) {
self.exposureMode = mode
if mode == .autoExpose || mode == .continuousAutoExposure {
exposureModeButton.setImage(UIImage(named: "AutoExpButton"), for: .normal)
if !isLockingExposure {
showMessage("AUTO MODE")
}
expControlLabel.text = formatExposureCompensationLabel(expComp)
} else {
exposureModeButton.setImage(UIImage(named: "ManualExpButton"), for: .normal)
if !isLockingExposure {
showMessage("MANUAL MODE")
}
expControlLabel.text = formatExposureLabel(currentShutterSpeed)
}
}
func flashModeDidChange(_ mode: AVCaptureFlashMode) {
switch mode {
case .auto:
flashButton.setImage(UIImage(named: "FlashAuto"), for: .normal)
case .on:
flashButton.setImage(UIImage(named: "FlashOn"), for: .normal)
case .off:
flashButton.setImage(UIImage(named: "FlashOff"), for: .normal)
}
}
private func formatExposureLabel(_ exposure : CMTime?) -> String? {
guard exposure != nil else { return nil }
let shutterSpeed = Double(exposure!.value) / Double(exposure!.timescale)
if shutterSpeed < 1.0 {
let displayValue = Int(1.0 / shutterSpeed)
return "1/\(displayValue)"
} else {
let displayValue = Int(shutterSpeed)
return "\(displayValue)"
}
}
private func formatExposureCompensationLabel(_ ec : Float?) -> String? {
guard ec != nil else { return nil }
if ec! >= 0 {
return String(format: "+%.1f", ec!)
} else {
return String(format: "%.1f", ec!)
}
}
private func fadeInMeterView(_ type : MeterType) {
guard viewFinder != nil else { return }
guard minExpComp != nil, maxExpComp != nil else { return }
let meterOriginY : CGFloat = viewFinder!.bounds.maxY - meterViewHeight
let f = CGRect(x: 0, y: meterOriginY, width: view.bounds.width, height: meterViewHeight)
currentMeter = type
switch type {
case .exposureCompensation:
currentMeterView = MeterView(meterType : .exposureCompensation, minValue: minExpComp!, maxValue: maxExpComp!, currentValue: expComp, frame: f)
case .shutterSpeed:
let minDisplayValue = Float(CMTimeGetSeconds(minShutterSpeed!)) * exposureMeterScale
let maxDisplayValue = Float(CMTimeGetSeconds(maxShutterSpeed!)) * exposureMeterScale
let currentDisplayValue = Float(CMTimeGetSeconds(currentShutterSpeed!)) * exposureMeterScale
currentMeterView = MeterView(meterType : .shutterSpeed, minValue: minDisplayValue, maxValue: maxDisplayValue, currentValue: currentDisplayValue, frame: f)
case .iso:
let currentISO = (iso != nil ? iso! : defaultISO)
currentMeterView = MeterView(meterType : .iso, minValue: minISO!, maxValue: maxISO!, currentValue: currentISO, frame: f)
}
currentMeterView!.delegate = self
view.addSubview(currentMeterView!)
currentMeterView!.isHidden = false
currentMeterView!.alpha = 0
currentMeterView!.transform = CGAffineTransform(translationX: 0, y: 20)
UIView.animate(withDuration: 0.2) { [weak self] in
self?.currentMeterView?.alpha = 1
self?.currentMeterView?.transform = CGAffineTransform.identity
}
}
private func fadeOutMeterView() {
guard minExpComp != nil, maxExpComp != nil else { return }
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.currentMeterView?.alpha = 0
self?.currentMeterView?.transform = CGAffineTransform(translationX: 0, y: 20)
}) { [weak self] (finished) in
self?.currentMeterView?.isHidden = true
}
}
private func showAELButton() {
aelButton.alpha = 0
aelButton.isHidden = false
UIView.animate(withDuration: 0.2) { [weak self] in
self?.aelButton.alpha = 1
}
}
private func hideAELButton() {
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.aelButton.alpha = 0
}) { [weak self] (finished) in
self?.aelButton.isHidden = true
}
}
@IBAction func switchCameraButtonDidTap(_ sender: Any) {
delegate?.switchCameraButtonDidTap()
}
@IBAction func shutterButtonDidTap(_ sender: Any) {
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
}
delegate?.shutterButtonDidTap()
}
@IBAction func autoManualButtonDidTap(_ sender: Any) {
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
}
// Do not switch mode if either auto or manual mode being not supported
guard isAutoExpModeSupported != nil && isManualExpModeSupported != nil else { return }
guard isAutoExpModeSupported! && isManualExpModeSupported! else { return }
delegate?.autoManualModeButtonDidTap()
}
@IBAction func backButtonDidTap(_ sender: Any) {
delegate?.backButtonDidTap()
}
// MARK: - MeterViewDelegate
func meterValueDidChange(_ value: Float) {
guard currentMeter != nil else { return }
if let meterType = currentMeter {
switch meterType {
case .exposureCompensation:
guard minExpComp != nil && maxExpComp != nil else { return }
guard value >= minExpComp! && value <= maxExpComp! else { return }
expComp = value
expControlLabel.text = formatExposureCompensationLabel(expComp)
delegate?.userDidChangeExpComp(value)
case .iso:
guard minISO != nil && maxISO != nil else { return }
guard value >= minISO! && value <= maxISO! else { return }
iso = value
let displayValue = Int(iso!)
isoLabel.text = "\(displayValue)"
delegate?.userDidChangeISO(iso!)
case .shutterSpeed:
let exp = CMTime(seconds: Double(value / exposureMeterScale), preferredTimescale: currentShutterSpeed!.timescale)
guard minShutterSpeed != nil && maxShutterSpeed != nil else { return }
guard exp >= minShutterSpeed! && exp <= maxShutterSpeed! else { return }
currentShutterSpeed = exp
expControlLabel.text = formatExposureLabel(currentShutterSpeed)
delegate?.userDidChangeShutterSpeed(exp)
}
}
}
// MARK: - Gestures
@objc private func didTapOnViewFinder(_ tap : UITapGestureRecognizer) {
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
return
}
let positionInView = tap.location(in: viewFinder)
let positionInCamera = viewFinder?.previewLayer.captureDevicePointOfInterest(for: positionInView)
if let pt = positionInCamera {
debugPrint("Focus point changed to \(pt)")
delegate?.didTapOnViewFinder(pt)
}
}
@objc private func didLongPressOnViewFinder(_ tap : UILongPressGestureRecognizer) {
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
return
}
switch tap.state {
case .began:
isLockingExposure = true
let positionInView = tap.location(in: viewFinder)
let positionInCamera = viewFinder?.previewLayer.captureDevicePointOfInterest(for: positionInView)
if let pt = positionInCamera {
debugPrint("AEL set to \(pt)")
delegate?.didLongPressOnViewFinder(pt)
}
viewFinder?.aelDidLock()
showAELButton()
case .ended:
isLockingExposure = false
showMessage("AUTO EXP LOCKED")
case .cancelled:
isLockingExposure = false
default:
break
}
}
@objc private func didTapOnExpControl(_ tap : UITapGestureRecognizer) {
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
return
} else {
if exposureMode == nil || exposureMode! == .autoExpose || exposureMode! == .continuousAutoExposure {
fadeInMeterView(.exposureCompensation)
} else {
guard minShutterSpeed != nil, maxShutterSpeed != nil, currentShutterSpeed != nil else { return }
fadeInMeterView(.shutterSpeed)
}
}
}
@objc private func didTapOnISOControl(_ tap : UITapGestureRecognizer) {
if isManualExpModeSupported == nil || !isManualExpModeSupported! {
return
}
if currentMeterView != nil && !currentMeterView!.isHidden {
fadeOutMeterView()
return
} else {
// We need to set the camera exposure mode to manual so that we can set fixed iso
if exposureMode == nil || exposureMode! == .autoExpose || exposureMode! == .continuousAutoExposure {
delegate?.autoManualModeButtonDidTap()
}
fadeInMeterView(.iso)
}
}
@IBAction func didTapOnAELButton(_ sender: Any) {
delegate?.userDidUnlockAEL()
hideAELButton()
viewFinder?.aelDidUnlock()
}
@IBAction func didTapOnFlashButton(_ sender: Any) {
delegate?.userDidChangeFlashMode()
}
}
| mit | 371a1daa1a101a23a6012055f67d105f | 36.434978 | 166 | 0.621227 | 4.877593 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.