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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tectijuana/iOS | ColorianoAngelino/calculadora/ViewController.swift | 2 | 2250 | //
// ViewController.swift
// calculadora
//
// Created by isc on 11/21/16.
// Copyright © 2016 isc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
//Tienes que asociar todos los botones de digitos al método appenDigit
@IBAction func appenDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber{
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
//Tienes que asociar todos los botones de operaciones al metodo operate
@IBAction func operate(_ sender: UIButton) {
let operacion = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operacion {
case "x": performOperation { $0 * $1 }
case "/": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "-": performOperation { $1 - $0 }
case "*": performSqrt { sqrt($0) }
default: break
}
}
func performOperation(_ operacion: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operacion(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
func performSqrt(_ operacion: (Double) -> Double) {
if operandStack.count >= 1 {
displayValue = operacion(operandStack.removeLast())
enter()
}
}
var operandStack = Array<Double>()
//Tienes que asociar el boton de la flechita a este metodo ENTER
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NumberFormatter().number(from: display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
| mit | 5fb83af2c9688cd3415fd6b0684a8e7b | 25.139535 | 90 | 0.577847 | 4.897603 | false | false | false | false |
hikelee/cinema | Sources/App/Controllers/SettingController.swift | 1 | 1241 | import Vapor
import HTTP
import Foundation
class SettingAdminController : ChannelBasedController<Setting> {
typealias Model = Setting
override var path:String {return "/admin/cinema/setting"}
override func additonalFormData(_ request: Request) throws ->[String:Node]{
return try [
"parents":Channel.allNode()
]
}
}
class SettingApiController: Controller {
let path = "/api/cinema/setting"
override func makeRouter(){
routerGroup.group(path){group in
group.get("/"){request in
guard let identification = request.data["id"]?.string?.uppercased() else {
return try JSON(node:["status":1,"message":"no id"])
}
guard let projector = try Projector.load("identification",identification) else{
return try JSON(node:["status":1,"message":"no projector found"])
}
guard let setting = try Setting.load("channel_id",projector.channelId) else {
return try JSON(node:["status":1,"message":"no setting found"])
}
return try JSON(node:["status":0, "wallpaper":setting.wallpaper,])
}
}
}
}
| mit | 676e2d313e8ccd69fcdcf5eb9de92be4 | 36.606061 | 95 | 0.586624 | 4.791506 | false | false | false | false |
XWJACK/PageKit | Sources/GuidePage.swift | 1 | 2884 | //
// GuidePage.swift
//
// Copyright (c) 2017 Jack
//
// 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
/// Delegate for guide page.
public protocol GuidePageDatasource: class {
/// Asks for number of pages.
///
/// - Returns: Total number of page.
func numberOfPages() -> Int
/// Asks for Page.
///
/// - Parameters:
/// - guidePage: GuidePage.
/// - index: Page index.
/// - Returns: Page.
func guidePage(_ guidePage: GuidePage, pageForIndexAt index: Int) -> Page
}
/// Guide page with system page control.
open class GuidePage: ReuseContainer {
/// Data source
open weak var dataSource: GuidePageDatasource? = nil
/// System page control.
open let pageControl = UIPageControl()
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(pageControl)
}
open override func reloadNumberOfPages() -> Int {
let number = dataSource?.numberOfPages() ?? 0
pageControl.numberOfPages = number
return number
}
open override func page(forIndexAt index: Int) -> Page? {
return dataSource?.guidePage(self, pageForIndexAt: index)
}
open override func layoutSubviews() {
super.layoutSubviews()
pageControl.sizeToFit()
pageControl.frame.origin = CGPoint(x: (frame.size.width - pageControl.frame.size.width) / 2,
y: frame.size.height - pageControl.frame.size.height)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageControl.currentPage = index(withOffset: scrollView.contentOffset.x)
}
}
| mit | df2681add9ee212d0d4c2e0cc759633b | 34.170732 | 100 | 0.67025 | 4.577778 | false | false | false | false |
eviathan/Salt | Salt/Models/Song.swift | 1 | 828 | //
// Song.swift
// Salt
//
// Created by Brian on 02/04/2017.
// Copyright © 2017 Iko. All rights reserved.
//
import Foundation
class Song {
// Tracks
var tracks: [Track] = [Track]()
var returnTracks: [ReturnTrack] = [ReturnTrack]()
var masterTrack: MasterTrack = MasterTrack()
// Global
var tempo: Double = 120.0
var timeSignature = TimeSignature()
// Playhead
var currentSongTime: Double = 0.0
var isPlaying: Bool = false
// Loop
var loop: Bool = false
var loopStart: Double = 0.0
var loopLength: Double = 0.0
init () {
addDefaultTracks()
}
private func addDefaultTracks() {
tracks.append(AudioTrack())
tracks.append(MIDITrack())
returnTracks.append(ReturnTrack())
}
}
| apache-2.0 | c16719363eac1fc9a334847471cf9a46 | 18.690476 | 53 | 0.58162 | 3.975962 | false | false | false | false |
jeffreybergier/SwiftLint | Source/SwiftLintFramework/Rules/IdentifierNameRule.swift | 1 | 5556 | //
// IdentifierNameRule.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct IdentifierNameRule: ASTRule, ConfigurationProviderRule {
public var configuration = NameConfiguration(minLengthWarning: 3,
minLengthError: 2,
maxLengthWarning: 40,
maxLengthError: 60)
public init() {}
public static let description = RuleDescription(
identifier: "identifier_name",
name: "Identifier Name",
description: "Identifier names should only contain alphanumeric characters and " +
"start with a lowercase character or should only contain capital letters. " +
"In an exception to the above, variable names may start with a capital letter " +
"when they are declared static and immutable. Variable names should not be too " +
"long or too short.",
nonTriggeringExamples: IdentifierNameRuleExamples.swift3NonTriggeringExamples,
triggeringExamples: IdentifierNameRuleExamples.swift3TriggeringExamples,
deprecatedAliases: ["variable_name"]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard !dictionary.enclosedSwiftAttributes.contains("source.decl.attribute.override") else {
return []
}
return validateName(dictionary: dictionary, kind: kind).map { name, offset in
guard !configuration.excluded.contains(name) else {
return []
}
let isFunction = SwiftDeclarationKind.functionKinds().contains(kind)
let description = type(of: self).description
let type = self.type(for: kind)
if !isFunction {
if !CharacterSet.alphanumerics.isSuperset(ofCharactersIn: name) {
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: "\(type) name should only contain alphanumeric " +
"characters: '\(name)'")
]
}
if let severity = severity(forLength: name.characters.count) {
let reason = "\(type) name should be between " +
"\(configuration.minLengthThreshold) and " +
"\(configuration.maxLengthThreshold) characters long: '\(name)'"
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
}
if kind != .varStatic && name.isViolatingCase && !name.isOperator {
let reason = "\(type) name should start with a lowercase character: '\(name)'"
return [
StyleViolation(ruleDescription: description,
severity: .error,
location: Location(file: file, byteOffset: offset),
reason: reason)
]
}
return []
} ?? []
}
private func validateName(dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> (name: String, offset: Int)? {
guard let name = dictionary.name,
let offset = dictionary.offset,
kinds(for: .current).contains(kind),
!name.hasPrefix("$") else {
return nil
}
return (name.nameStrippingLeadingUnderscoreIfPrivate(dictionary), offset)
}
private func kinds(for version: SwiftVersion) -> [SwiftDeclarationKind] {
let common = SwiftDeclarationKind.variableKinds() + SwiftDeclarationKind.functionKinds()
switch version {
case .two, .twoPointThree:
return common
case .three:
return common + [.enumelement]
}
}
private func type(for kind: SwiftDeclarationKind) -> String {
if SwiftDeclarationKind.functionKinds().contains(kind) {
return "Function"
} else if kind == .enumelement {
return "Enum element"
} else {
return "Variable"
}
}
}
fileprivate extension String {
var isViolatingCase: Bool {
let secondIndex = characters.index(after: startIndex)
let firstCharacter = substring(to: secondIndex)
guard firstCharacter.isUppercase() else {
return false
}
guard characters.count > 1 else {
return true
}
let range = secondIndex..<characters.index(after: secondIndex)
let secondCharacter = substring(with: range)
return secondCharacter.isLowercase()
}
var isOperator: Bool {
let operators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", ".", "%", "<", ">", "&"]
return !operators.filter(hasPrefix).isEmpty
}
}
| mit | 87b225467d41032fd6d60f838af45026 | 38.964029 | 99 | 0.543114 | 5.726804 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/View/Settings/VSettings.swift | 1 | 7447 | import UIKit
class VSettings:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CSettings!
private weak var collectionView:VCollection!
private(set) weak var viewBar:VSettingsBar!
private(set) weak var viewBackground:VSettingsBackground!
private weak var layoutBarHeight:NSLayoutConstraint!
private let kMaxBarHeight:CGFloat = 200
private let kCollectionBottom:CGFloat = 20
private let kButtonBackWidth:CGFloat = 60
private let kButtonBackHeight:CGFloat = 47
private let kButtonBackBottom:CGFloat = -133
private let kDeselectTime:TimeInterval = 0.3
override init(controller:CController)
{
super.init(controller:controller)
backgroundColor = UIColor.clear
self.controller = controller as? CSettings
let viewGradient:VSettingsGradient = VSettingsGradient()
let viewBar:VSettingsBar = VSettingsBar(
controller:self.controller)
self.viewBar = viewBar
let viewBackground:VSettingsBackground = VSettingsBackground()
self.viewBackground = viewBackground
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VSettingsCellLanguage.self)
collectionView.registerCell(cell:VSettingsCellResults.self)
collectionView.registerCell(cell:VSettingsCellRetina.self)
collectionView.registerCell(cell:VSettingsCellShare.self)
collectionView.registerCell(cell:VSettingsCellReview.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.sectionInset = UIEdgeInsets(
top:kMaxBarHeight,
left:0,
bottom:kCollectionBottom,
right:0)
}
let buttonBack:UIButton = UIButton()
buttonBack.translatesAutoresizingMaskIntoConstraints = false
buttonBack.setImage(
#imageLiteral(resourceName: "assetGenericBackWhite").withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.normal)
buttonBack.setImage(
#imageLiteral(resourceName: "assetGenericBackWhite").withRenderingMode(UIImageRenderingMode.alwaysTemplate),
for:UIControlState.highlighted)
buttonBack.imageView!.clipsToBounds = true
buttonBack.imageView!.contentMode = UIViewContentMode.center
buttonBack.imageView!.tintColor = UIColor(white:1, alpha:0.2)
buttonBack.addTarget(
self,
action:#selector(actionBack(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(viewGradient)
addSubview(viewBackground)
addSubview(collectionView)
addSubview(viewBar)
addSubview(buttonBack)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
NSLayoutConstraint.topToTop(
view:viewBar,
toView:self)
layoutBarHeight = NSLayoutConstraint.height(
view:viewBar,
constant:kMaxBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:self)
NSLayoutConstraint.equals(
view:viewBackground,
toView:self)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:buttonBack,
toView:viewBar,
constant:kButtonBackBottom)
NSLayoutConstraint.height(
view:buttonBack,
constant:kButtonBackHeight)
NSLayoutConstraint.leftToLeft(
view:buttonBack,
toView:self)
NSLayoutConstraint.width(
view:buttonBack,
constant:kButtonBackWidth)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: actions
func actionBack(sender button:UIButton)
{
controller.back()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MSettingsItem
{
let item:MSettingsItem = controller.model.items[index.item]
return item
}
//MARK: public
func clean()
{
viewBackground.timer?.invalidate()
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let item:MSettingsItem = modelAtIndex(index:indexPath)
let width:CGFloat = collectionView.bounds.size.width
let size:CGSize = CGSize(width:width, height:item.cellHeight)
return size
}
func scrollViewDidScroll(_ scrollView:UIScrollView)
{
let offsetY:CGFloat = scrollView.contentOffset.y
var newBarHeight:CGFloat = kMaxBarHeight - offsetY
if newBarHeight < 0
{
newBarHeight = 0
}
layoutBarHeight.constant = newBarHeight
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.items.count
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let item:MSettingsItem = modelAtIndex(index:indexPath)
let cell:VSettingsCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
item.reusableIdentifier,
for:indexPath) as! VSettingsCell
cell.config(model:item, controller:controller)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
let item:MSettingsItem = modelAtIndex(index:indexPath)
return item.selectable
}
func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
let item:MSettingsItem = modelAtIndex(index:indexPath)
return item.selectable
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
collectionView.isUserInteractionEnabled = false
let item:MSettingsItem = modelAtIndex(index:indexPath)
item.selected(controller:controller)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kDeselectTime)
{ [weak collectionView] in
collectionView?.isUserInteractionEnabled = true
collectionView?.selectItem(
at:nil,
animated:true,
scrollPosition:UICollectionViewScrollPosition())
}
}
}
| mit | 684352bd354f75f5368e983d5a92d654 | 31.951327 | 155 | 0.646569 | 5.849961 | false | false | false | false |
SSU-CS-Department/ssumobile-ios | SSUMobile/Modules/Email/Views/SSUEmailViewController.swift | 1 | 6211 | //
// SSUEmailViewController.swift
// SSUMobile
//
// Created by Eric Amorde on 2/7/15.
// Copyright (c) 2015 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
import WebKit
import MBProgressHUD
class SSUEmailViewController: UIViewController, SSUEmailLoginDelegate, WKNavigationDelegate {
enum Mode {
case googleDocs
case email
}
private struct Segue {
static let login = "login"
}
let webView: WKWebView = WKWebView()
@IBOutlet var inboxButton: UIBarButtonItem!
var progressHUD: MBProgressHUD = MBProgressHUD()
var mode: Mode = .email
var emailURL: URL!
var isLoggedIn: Bool = false
var isLoggingIn: Bool = false
var canceledLogin: Bool = false
var api: SSUEmailAPI = SSUEmailAPI()
private var loadingView: MBProgressHUD?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
webView.snp.makeConstraints { (make) in
make.top.equalTo(topLayoutGuide.snp.bottom)
make.bottom.equalTo(bottomLayoutGuide.snp.top)
make.left.equalToSuperview()
make.right.equalToSuperview()
}
webView.navigationDelegate = self
switch mode {
case .googleDocs:
emailURL = URL(string: SSUConfiguration.instance.string(forKey: SSUEmailGoogleDocsURLKey)!)!
inboxButton.title = "Inbox"
case .email:
emailURL = URL(string: SSUConfiguration.instance.string(forKey: SSUEmailMailURLKey)!)
inboxButton.title = "Home"
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isLoggedIn && !canceledLogin && !isLoggingIn {
showLoginViewController()
} else if isLoggedIn {
load(url: emailURL)
}
}
private func showLoadingIndicator(text: String? = nil) {
if let indicator = loadingView {
indicator.show(animated: true)
indicator.label.text = text
} else {
let indicator = MBProgressHUD.showAdded(to: webView, animated: true)
indicator.label.text = text
loadingView = indicator
}
}
private func hideLoadingIndicator() {
loadingView?.hide(animated: true)
}
private func load(url: URL) {
let request = URLRequest(url: url)
webView.load(request)
}
private func logout() {
SSULDAPCredentials.instance.clearCredentials()
api.clearCookies(for: self.emailURL)
showLoginViewController()
}
private func showLoginViewController() {
performSegue(withIdentifier: Segue.login, sender: self)
}
private func alertUnknownError() {
let alert = UIAlertController(title: "Error", message: "An unknown error occurred. Please try again or come back later", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
// MARK: SSUEmailLoginDelegate
func loginControllerDidLogin(_ viewController: SSUEmailLoginViewController) {
canceledLogin = false
isLoggedIn = true
if viewController.rememberLogin {
let credentials = SSULDAPCredentials.instance
credentials.username = viewController.username
credentials.password = viewController.password
credentials.hasCredentials = true
}
showLoadingIndicator()
isLoggingIn = true
api.authenticateLDAP(username: viewController.username, password: viewController.password, completion: { (error) in
if let error = error {
SSULogging.logError("Failed to authenticate to LDAP: \(error)")
self.showLoginViewController()
} else {
self.load(url: self.emailURL)
}
})
navigationController?.popViewController(animated: true)
}
func loginControllerDidCancel(_ viewController: SSUEmailLoginViewController) {
canceledLogin = true
hideLoadingIndicator()
if !isLoggedIn {
// Pop both the login and self
navigationController?.popViewController(animated: false)
navigationController?.popViewController(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showLoadingIndicator()
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard isLoggedIn else {
decisionHandler(.allow)
return
}
if let url = navigationAction.request.url {
// If the user logs out using gmail's interface, perform a logout on the client
if url.absoluteString.contains("logout") || url.absoluteString.contains("logoff") {
logout()
}
}
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
hideLoadingIndicator()
}
// MARK: IBActions
@IBAction func inboxButtonPressed(_ button: UIBarButtonItem) {
load(url: emailURL)
}
@IBAction func logoutButtonPressed(_ button: UIBarButtonItem) {
let alert = UIAlertController(title: "Logout", message: "Are you sure you want to log out?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Logout", style: .destructive, handler: { (action) in
self.logout()
}))
present(alert, animated: true, completion: nil)
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let loginVc = segue.destination as? SSUEmailLoginViewController {
loginVc.delegate = self
}
}
}
| apache-2.0 | 532f6e45abeb6cb7d28a83d851be8d25 | 32.213904 | 157 | 0.641604 | 5.021019 | false | false | false | false |
mrommel/TreasureDungeons | TreasureDungeons/Source/Models/Skybox.swift | 1 | 2989 | //
// Skybox.swift
// AnimateCube
//
// Created by burt on 2016. 2. 28..
// Copyright © 2016년 BurtK. All rights reserved.
//
import GLKit
class Skybox : Model {
static let kY0: GLfloat = 0.0
static let kY1: GLfloat = 0.333333333333
static let kY2: GLfloat = 0.666666666666
static let kY3: GLfloat = 1.0
let vertexList : [Vertex] = [
// Front
Vertex( 1, -1, 1, 1, 0, 0, 1, 0.25, kY1, 0, 0, 1), // 0
Vertex( 1, 1, 1, 0, 1, 0, 1, 0.25, kY2, 0, 0, 1), // 1
Vertex(-1, 1, 1, 0, 0, 1, 1, 0.0, kY2, 0, 0, 1), // 2
Vertex(-1, -1, 1, 0, 0, 0, 1, 0.0, kY1, 0, 0, 1), // 3
// Back
Vertex(-1, -1, -1, 0, 0, 1, 1, 0.75, kY1, 0, 0,-1), // 4
Vertex(-1, 1, -1, 0, 1, 0, 1, 0.75, kY2, 0, 0,-1), // 5
Vertex( 1, 1, -1, 1, 0, 0, 1, 0.5, kY2, 0, 0,-1), // 6
Vertex( 1, -1, -1, 0, 0, 0, 1, 0.5, kY1, 0, 0,-1), // 7
// Left
Vertex(-1, -1, 1, 1, 0, 0, 1, 1.0, kY1, -1, 0, 0), // 8
Vertex(-1, 1, 1, 0, 1, 0, 1, 1.0, kY2, -1, 0, 0), // 9
Vertex(-1, 1, -1, 0, 0, 1, 1, 0.75, kY2, -1, 0, 0), // 10
Vertex(-1, -1, -1, 0, 0, 0, 1, 0.75, kY1, -1, 0, 0), // 11
// Right
Vertex( 1, -1, -1, 1, 0, 0, 1, 0.5, kY1, 1, 0, 0), // 12
Vertex( 1, 1, -1, 0, 1, 0, 1, 0.5, kY2, 1, 0, 0), // 13
Vertex( 1, 1, 1, 0, 0, 1, 1, 0.25, kY2, 1, 0, 0), // 14
Vertex( 1, -1, 1, 0, 0, 0, 1, 0.25, kY1, 1, 0, 0), // 15
// Top
Vertex( 1, 1, 1, 1, 0, 0, 1, 0.25, kY2, 0, 1, 0), // 16
Vertex( 1, 1, -1, 0, 1, 0, 1, 0.5, kY2, 0, 1, 0), // 17
Vertex(-1, 1, -1, 0, 0, 1, 1, 0.5, kY3, 0, 1, 0), // 18
Vertex(-1, 1, 1, 0, 0, 0, 1, 0.25, kY3, 0, 1, 0), // 19
// Bottom - messed
Vertex( 1, -1, -1, 1, 0, 0, 1, 0.25, kY1, 0,-1, 0), // 20
Vertex( 1, -1, 1, 0, 1, 0, 1, 0.25, kY0, 0,-1, 0), // 21
Vertex(-1, -1, 1, 0, 0, 1, 1, 0.5, kY0, 0,-1, 0), // 22
Vertex(-1, -1, -1, 0, 0, 0, 1, 0.5, kY1, 0,-1, 0), // 23
]
let indexList : [GLuint] = [
// Front
0, 2, 1,
2, 0, 3,
// Back
4, 6, 5,
6, 4, 7,
// Left
8, 10, 9,
10, 8, 11,
// Right
12, 14, 13,
14, 12, 15,
// Top
16, 18, 17,
18, 16, 19,
// Bottom
20, 22, 21,
22, 20, 23
]
init(shader: BaseEffect) {
super.init(name: "skybox", shader: shader, vertices: vertexList, indices: indexList)
self.loadTexture("skybox.png")
self.scale = 30.0
}
override func updateWithDelta(_ dt: TimeInterval) {
//self.rotationZ = self.rotationZ + Float(M_PI*dt)
//self.rotationY = self.rotationY + Float(Double.pi * dt / 8)
}
}
| apache-2.0 | 3d9083b8105f6d3990532cfd3f3bfe73 | 29.469388 | 92 | 0.388814 | 2.384984 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/UI/Controller/ActionableFormCreator.swift | 1 | 7707 | //
// ActionableFormCreator.swift
// YourGoals
//
// Created by André Claaßen on 21.12.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
import Eureka
/// the form tags for the FormViewModel
///
/// **Hint**: A tag is a unique field identifier
///
/// - titleTag: the tag for the title in the navigation bar of the form
/// - taskTag: the tag id of the task
/// - goalTag: the tag id of the selectable goal
/// - commitDateTag: the task id of the commit date
enum EditTaskFormTag:String {
case taskTag
case goalTag
case commitDateTag
}
// MARK: - ActionableInfo
extension ActionableInfo {
/// create an actionable info based on the values of the eureka actionable form
///
/// - Parameters:
/// - type: type of the acgtinoable
/// - values: the values
init(type: ActionableType, values: [String: Any?]) {
guard let name = values[EditTaskFormTag.taskTag.rawValue] as? String? else {
fatalError("There should be a name value")
}
let goal = values[EditTaskFormTag.goalTag.rawValue] as? Goal
let commitDateTuple = values[EditTaskFormTag.commitDateTag.rawValue] as? CommitDateTuple
self.init(type: type, name: name, commitDate: commitDateTuple?.date, parentGoal: goal)
}
}
/// create an Eureka form for editing or creation actionables (tasks or habits)
class ActionableFormCreator:StorageManagerWorker {
/// the Eureka form
let form:Form
/// a .task or .habit
let type:ActionableType
/// new entry or editing an existing enty
let newEntry:Bool
var deleteHandler: (() -> Void)? = nil
/// initialize the form creator with the (empty) eureka form and a storage managerand
///
/// - Parameters:
/// - form: the eureka formand
/// - type: .habit or .task
/// - newEntry: create a task/habit or edit one
/// - manager: the storage manager
init(form: Form, forType type: ActionableType, newEntry:Bool, manager: GoalsStorageManager) {
self.form = form
self.type = type
self.newEntry = newEntry
super.init(manager: manager)
}
/// create a form based on the actionable info for the specific date
///
/// ** Hint **: The date is needed to create a range of selectable commit date
/// textes like today, tomorrow and so on.
///
func createForm() {
self.form
+++ Section()
<<< taskNameRow()
<<< parentGoalRow()
+++ Section() { $0.hidden = Condition.function([], { _ in self.type == .habit }) }
<<< commitDateRow()
+++ Section()
<<< remarksRow(remarks: nil)
+++ Section()
<<< ButtonRow() {
$0.title = "Delete \(type.asString())"
$0.hidden = Condition.function([], { _ in self.newEntry })
}.cellSetup({ (cell, row) in
cell.backgroundColor = UIColor.red
cell.tintColor = UIColor.white
}).onCellSelection{ _, _ in
self.deleteHandler?()
}
}
/// call back is called, when user is clicking on the delete handler
///
/// - Parameter callback: the callback function called after touching delte
@discardableResult
func onDelete(_ callback: @escaping (() -> Void)) -> Self {
self.deleteHandler = callback
return self
}
/// set the values of the form based on the actionableInfo for the specific date
///
/// - Parameters:
/// - actionableInfo: the actionable info
/// - date: the date for the row options for the commit date
func setValues(for actionableInfo: ActionableInfo, forDate date: Date) {
let commitDateCreator = SelectableCommitDatesCreator()
var values = [String: Any?]()
values[EditTaskFormTag.taskTag.rawValue] = actionableInfo.name
values[EditTaskFormTag.goalTag.rawValue] = actionableInfo.parentGoal
values[EditTaskFormTag.commitDateTag.rawValue] = commitDateCreator.dateAsTuple(date: actionableInfo.commitDate)
let pushRow:PushRow<CommitDateTuple> = self.form.rowBy(tag: EditTaskFormTag.commitDateTag.rawValue)!
let tuples = commitDateCreator.selectableCommitDates(startingWith: date, numberOfDays: 7, includingDate: actionableInfo.commitDate)
pushRow.options = tuples
self.form.setValues(values)
}
/// read the input values out of the form and create an ActionableInfo
///
/// - Returns: the actionableinfo
func getActionableInfoFromValues() -> ActionableInfo {
let values = self.form.values()
return ActionableInfo(type: self.type, values: values)
}
// MARK: - Row creating helper functions
/// create a row for editing the task name
///
/// - Returns: a base row
func taskNameRow() -> BaseRow {
let row = TextRow(tag: EditTaskFormTag.taskTag.rawValue).cellSetup { cell, row in
cell.textField.placeholder = "Please enter your task"
row.add(rule: RuleRequired())
row.validationOptions = .validatesAlways
}
return row
}
/// create a row for selecting a goal
///
/// - Returns: the row
func parentGoalRow() -> BaseRow {
return PushRow<Goal>(EditTaskFormTag.goalTag.rawValue) { row in
row.title = "Select a Goal"
row.options = selectableGoals()
}.onPresent{ (_, to) in
to.selectableRowCellUpdate = { cell, row in
cell.textLabel?.text = row.selectableValue?.name
}
}.cellUpdate{ (cell, row) in
cell.textLabel?.text = "Goal"
cell.detailTextLabel?.text = row.value?.name
}
}
/// create a row for selecting a commit date
///
/// - Parameters:
/// - date: starting date for create meaningful texts
///
/// - Returns: the commit date
func commitDateRow() -> BaseRow {
return PushRow<CommitDateTuple>() { row in
row.tag = EditTaskFormTag.commitDateTag.rawValue
row.title = "Select a commit date"
row.options = []
}.onPresent { (_, to) in
to.selectableRowCellUpdate = { cell, row in
cell.textLabel?.text = row.selectableValue?.text
}
}.cellUpdate { (cell,row) in
cell.textLabel?.text = "Commit Date"
cell.detailTextLabel?.text = row.value?.text
}
}
/// create a row with remarks for the tasks
///
/// - Parameter remarks: the remakrs
/// - Returns: a row with remarks for a date
func remarksRow(remarks:String?) -> BaseRow {
return TextAreaRow() {
$0.placeholder = "Remarks on your task"
$0.textAreaHeight = .dynamic(initialTextViewHeight: 110)
}
}
// MARK: Helper methods to create needed data lists for the Eureka rows
/// an array of selectable goals for this actionable
///
/// - Returns: the array
/// - Throws: a core data exception
func selectableGoals() -> [Goal] {
do {
let strategyOrderManager = StrategyOrderManager(manager: self.manager)
let goals = try strategyOrderManager.goalsByPrio(withTypes: [GoalType.userGoal] )
return goals
}
catch let error {
NSLog("couldn't fetch the selectable goals: \(error)")
return []
}
}
}
| lgpl-3.0 | 73ec753042503beaed63cce04dabf21b | 33.850679 | 139 | 0.593742 | 4.496205 | false | false | false | false |
swiftingio/alti-sampler | Sampler/Exporter.swift | 1 | 2662 | import CoreData
enum Field: String {
case timestamp, json
}
class Exporter {
let context: NSManagedObjectContext
let filemgr = FileManager.default
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let encoder = JSONEncoder()
init(context: NSManagedObjectContext) {
self.context = context
self.encoder.dateEncodingStrategy = .iso8601
}
func allRecordings() throws -> [String] {
let request: NSFetchRequest<Recording> = NSFetchRequest(entityName: String(describing: Recording.self))
request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
let recordings: [Recording] = try context.fetch(request)
let strings: [String] = recordings.map { $0.json ?? "" }.filter { $0 != "" }
return strings
}
func saveAsPlistToDocuments() throws -> String? {
let recordings = try allRecordings()
let filePath = documentsPath.appendingPathComponent("\(Date()).plist")
_ = filemgr.createFile(atPath: filePath, contents: nil, attributes: nil)
let saved = (recordings as NSArray).write(toFile: filePath, atomically: true)
return saved ? filePath : nil
}
func allJSONRecordings() throws -> String {
let recordings = try allRecordings()
let json = "[\(recordings.joined(separator: ","))]"
return json
}
func save(_ samples: [Sample], outputFormatting: JSONEncoder.OutputFormatting = JSONEncoder.OutputFormatting(rawValue: 0)) {
guard !samples.isEmpty else { return }
do {
encoder.outputFormatting = outputFormatting
let data = try encoder.encode(samples)
let json = String(bytes: data, encoding: .utf8)
let entity = NSEntityDescription.insertNewObject(forEntityName: "Recording", into: context)
entity.setValue(json, forKey: Field.json.rawValue)
entity.setValue(Date(), forKey: Field.timestamp.rawValue)
try context.save()
} catch {
print(error.localizedDescription)
}
}
func json(from sample: Sample, outputFormatting: JSONEncoder.OutputFormatting = .prettyPrinted) -> String? {
do {
encoder.outputFormatting = outputFormatting
let data = try encoder.encode(sample)
let json = String(bytes: data, encoding: .utf8)
return json
} catch {
print(error.localizedDescription)
return nil
}
}
func clearAll() {
try? context.deleteEntities(ofType: Recording.self)
}
}
| mit | bff3c32c74a4e776f7957566b3ba3d1c | 37.57971 | 128 | 0.644252 | 4.957169 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/managers/TKStyleManager.swift | 1 | 10738 | //
// TKStyleManager.swift
// TripKit
//
// Created by Adrian Schoenig on 4/7/17.
// Copyright © 2017 SkedGo. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#endif
extension TKColor {
@objc public static var routeDashColorNonTravelled: TKColor {
#if os(iOS) || os(tvOS)
if #available(iOS 13.0, *) {
return .secondarySystemFill
} else {
return TKColor.lightGray.withAlphaComponent(0.25)
}
#elseif os(OSX)
return TKColor.lightGray.withAlphaComponent(0.25)
#endif
}
}
// MARK: - Colors
public class TKStyleManager {
private init() {}
private static func color(for dict: [String: Int]?) -> TKColor? {
guard
let red = dict?["Red"],
let green = dict?["Green"],
let blue = dict?["Blue"]
else { return nil }
return TKColor(red: Double(red) / 255, green: Double(green) / 255, blue: Double(blue) / 255, alpha: 1)
}
public static var globalTintColor: TKColor = {
color(for: TKConfig.shared.globalTintColor) ?? #colorLiteral(red: 0, green: 0.8, blue: 0.4, alpha: 1)
}()
@available(*, deprecated, message: "Use dynamic colors that are compatible with Dark Mode, e.g., from TripKitUI")
public static var globalBarTintColor: TKColor = {
color(for: TKConfig.shared.globalBarTintColor) ?? #colorLiteral(red: 0.1647058824, green: 0.2274509804, blue: 0.3019607843, alpha: 1)
}()
@available(*, deprecated, message: "Use dynamic colors that are compatible with Dark Mode, e.g., from TripKitUI")
public static var globalSecondaryBarTintColor: TKColor = {
color(for: TKConfig.shared.globalSecondaryBarTintColor) ?? #colorLiteral(red: 0.1176470588, green: 0.1647058824, blue: 0.2117647059, alpha: 1)
}()
public static var globalAccentColor: TKColor = {
color(for: TKConfig.shared.globalAccentColor) ?? globalTintColor
}()
}
// MARK: - Images
extension TKStyleManager {
private static let dummyImage = TKImage()
private static let imageCache = NSCache<NSString, TKImage>()
public static func activityImage(_ partial: String) -> TKImage {
let name: String
#if os(iOS) || os(tvOS)
switch UIDevice.current.userInterfaceIdiom {
case .phone: name = "icon-actionBar-\(partial)-30"
default: name = "icon-actionBar-\(partial)-38"
}
#elseif os(OSX)
name = "icon-actionBar-\(partial)-38"
#endif
return image(named: name)
}
public static func image(named: String) -> TKImage {
let image = optionalImage(named: named)
assert(image != nil, "Image named '\(named)' not found in \(TripKit.bundle).")
return image!
}
public static func optionalImage(named: String) -> TKImage? {
#if os(iOS) || os(tvOS)
return TKImage(named: named, in: .tripKit, compatibleWith: nil)
#elseif os(OSX)
return TripKit.bundle.image(forResource: named)
#endif
}
public static func image(forModeImageName imageName: String?, isRealTime: Bool = false, of iconType: TKStyleModeIconType = .listMainMode) -> TKImage? {
guard let partName = imageName?.lowercased() else {
return nil
}
let key = "\(partName)-\(isRealTime)-\(iconType.rawValue)" as NSString
if let cached = imageCache.object(forKey: key) {
return cached == dummyImage ? nil : cached
}
let fullName: String
switch iconType {
case .resolutionIndependent, .vehicle, .mapIcon:
assertionFailure("Not supported locally")
return nil
case .listMainMode:
fullName = isRealTime ? "icon-mode-\(partName)-realtime" : "icon-mode-\(partName)"
case .alert:
fullName = "icon-alert-yellow-map"
@unknown default:
return nil
}
if let image = optionalImage(named: fullName) {
imageCache.setObject(image, forKey: key)
return image
} else if isRealTime {
return self.image(forModeImageName:imageName, isRealTime:false, of:iconType)
} else {
imageCache.setObject(dummyImage, forKey: key)
return nil
}
}
}
// MARK: - Fonts
extension TKStyleManager {
public enum FontWeight {
case regular
case medium
case bold
case semibold
var weight: TKFont.Weight {
switch self {
case .regular: return .regular
case .medium: return .medium
case .bold: return .bold
case .semibold: return .semibold
}
}
var preferredFontName: String? {
switch self {
case .regular:
return TKConfig.shared.preferredFonts?["Regular"]
case .medium:
return TKConfig.shared.preferredFonts?["Medium"]
case .bold:
return TKConfig.shared.preferredFonts?["Bold"]
case .semibold:
return TKConfig.shared.preferredFonts?["Semibold"]
}
}
}
/// This method returns a font with custom font face for a given font size and weight.
/// If there's no custom font face specified in the plist, system font face is used.
/// This method is recommended to use with system controls such as `UIButton`
///
/// - Parameter size: Font size desired
/// - Parameter weight: Font weight desired
/// - Returns: A font with custom font face of the requested weight.
public static func font(size: Double, weight: FontWeight = .regular) -> TKFont {
if let preferredFontName = weight.preferredFontName, let font = TKFont(name: preferredFontName, size: size) {
return font
} else {
return TKFont.systemFont(ofSize: size, weight: weight.weight)
}
}
#if os(iOS) || os(tvOS)
//// This method returns a font with custom font face for a given text style and weight.
/// If there's no custom font face specified in the plist, system font face is used.
/// This method is typically used on `UILabel`, `UITextField`, and `UITextView` but
/// not recommended for system controls, such as `UIButton`.
///
/// - Parameter textStyle: TextStyle desired
/// - Parameter weight: Font weight desired
/// - Returns: A font with custom font face and weight.
public static func font(textStyle: TKFont.TextStyle, weight: FontWeight = .regular) -> UIFont {
let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
if let preferredFontName = weight.preferredFontName, let font = UIFont(name: preferredFontName, size: descriptor.pointSize) {
return UIFontMetrics.default.scaledFont(for: font)
} else {
return UIFont.systemFont(ofSize: descriptor.pointSize, weight: weight.weight)
}
}
#endif
// @available(*, deprecated, renamed: "font(size:weight:)")
public static func systemFont(size: Double) -> TKFont {
return font(size: size, weight: .regular)
}
// @available(*, deprecated, renamed: "font(size:weight:)")
public static func boldSystemFont(size: Double) -> TKFont {
return font(size: size, weight: .bold)
}
// @available(*, deprecated, renamed: "font(size:weight:)")
public static func semiboldSystemFont(size: Double) -> TKFont {
return font(size: size, weight: .semibold)
}
// @available(*, deprecated, renamed: "font(size:weight:)")
public static func mediumSystemFont(size: Double) -> TKFont {
return font(size: size, weight: .medium)
}
#if os(iOS) || os(tvOS)
// @available(*, deprecated, renamed: "font(textStyle:weight:)")
public static func customFont(forTextStyle textStyle: UIFont.TextStyle) -> UIFont {
return font(textStyle: textStyle, weight: .regular)
}
// @available(*, deprecated, renamed: "font(textStyle:weight:)")
public static func boldCustomFont(forTextStyle textStyle: UIFont.TextStyle) -> UIFont {
return font(textStyle: textStyle, weight: .bold)
}
// @available(*, deprecated, renamed: "font(textStyle:weight:)")
public static func semiboldCustomFont(forTextStyle textStyle: UIFont.TextStyle) -> UIFont {
return font(textStyle: textStyle, weight: .semibold)
}
// @available(*, deprecated, renamed: "font(textStyle:weight:)")
public static func mediumCustomFont(forTextStyle textStyle: UIFont.TextStyle) -> UIFont {
return font(textStyle: textStyle, weight: .medium)
}
#endif
}
// MARK: - Formatting
extension TKStyleManager {
private static var exerciseFormatter: EnergyFormatter = {
let formatter = EnergyFormatter()
formatter.isForFoodEnergyUse = false // For exercise
formatter.numberFormatter.maximumSignificantDigits = 2
formatter.numberFormatter.usesSignificantDigits = true
return formatter
}()
@objc(exerciseStringForCalories:)
public static func exerciseString(calories: Double) -> String {
return exerciseFormatter.string(fromValue: calories, unit: .kilocalorie)
}
public static func timeString(_ date: Date, for timeZone: TimeZone? = nil, relativeTo other: TimeZone? = nil) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
formatter.locale = .current
formatter.timeZone = timeZone ?? .current
let string = formatter.string(from: date)
let compact = string.replacingOccurrences(of: " ", with: "").localizedLowercase
if let other, let abbreviation = timeZone?.abbreviation(for: date), other.abbreviation(for: date) != abbreviation {
return "\(compact) (\(abbreviation))"
} else {
return compact
}
}
public static func dateString(_ date: Date, for timeZone: TimeZone? = nil) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .none
formatter.doesRelativeDateFormatting = true
formatter.locale = .current
formatter.timeZone = timeZone ?? .current
return formatter.string(from: date).localizedCapitalized
}
public static func format(_ date: Date, for timeZone: TimeZone? = nil, showDate: Bool, showTime: Bool) -> String {
let formatter = DateFormatter()
formatter.dateStyle = showDate ? .medium : .none
formatter.timeStyle = showTime ? .short : .none
formatter.locale = .current
formatter.timeZone = timeZone ?? .current
return formatter.string(from: date)
}
public static func format(_ date: Date, for timeZone: TimeZone? = nil, forceFormat: String? = nil, forceStyle: DateFormatter.Style = .none) -> String {
let formatter = DateFormatter()
if let forceFormat {
formatter.dateFormat = forceFormat
} else {
formatter.dateStyle = forceStyle
}
formatter.locale = .current
formatter.timeZone = timeZone ?? .current
return formatter.string(from: date)
}
@available(*, deprecated, renamed: "format(_:for:showDate:showTime:)")
public static func string(for date: Date, for timeZone: TimeZone? = nil, showDate: Bool, showTime: Bool) -> String {
format(date, for: timeZone, showDate: showDate, showTime: showTime)
}
}
| apache-2.0 | 922abe9f94b84a9a03a0c983cdad0207 | 32.977848 | 153 | 0.682034 | 4.189231 | false | false | false | false |
mohamede1945/quran-ios | Quran/ShareController/ShareController.swift | 1 | 1826 | //
// ShareController.swift
// Quran
//
// Created by Hossam Ghareeb on 6/20/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import UIKit
class ShareController: NSObject {
class func share(text: String,
image: UIImage? = nil,
url: URL? = nil,
sourceView: UIView,
sourceRect: CGRect,
sourceViewController: UIViewController,
handler: UIActivityViewControllerCompletionWithItemsHandler?) {
var itemsToShare = [AnyObject]()
itemsToShare.append(text as AnyObject)
if let shareImage = image {
itemsToShare.append(shareImage)
}
if let shareURL = url {
itemsToShare.append(shareURL as AnyObject)
}
let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
activityViewController.completionWithItemsHandler = handler
activityViewController.popoverPresentationController?.sourceView = sourceView
activityViewController.popoverPresentationController?.sourceRect = sourceRect
sourceViewController.present(activityViewController, animated: true, completion: nil)
}
}
| gpl-3.0 | 862e4d98048a61e9cc4eb7e79af80efd | 37.851064 | 118 | 0.679628 | 5.232092 | false | false | false | false |
superman-coder/pakr | pakr/pakr/Widget/Material/ModifiedTextField.swift | 1 | 23775 | //
// ModifiedTextField.swift
// pakr
//
// Created by Huynh Quang Thao on 4/12/16.
// Copyright © 2016 Pakr. All rights reserved.
//
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
public protocol TextFieldDelegate : UITextFieldDelegate {}
@IBDesignable
public class ModifiedTextField : UITextField {
/// A reference to the placeholder value.
private var placeholderText: String?
/**
This property is the same as clipsToBounds. It crops any of the view's
contents from bleeding past the view's frame.
*/
@IBInspectable public var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set(value) {
layer.masksToBounds = value
}
}
/// A property that accesses the backing layer's backgroundColor.
@IBInspectable public override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.CGColor
}
}
/// A property that accesses the layer.frame.origin.x property.
@IBInspectable public var x: CGFloat {
get {
return layer.frame.origin.x
}
set(value) {
layer.frame.origin.x = value
}
}
/// A property that accesses the layer.frame.origin.y property.
@IBInspectable public var y: CGFloat {
get {
return layer.frame.origin.y
}
set(value) {
layer.frame.origin.y = value
}
}
/// A property that accesses the layer.frame.size.width property.
@IBInspectable public var width: CGFloat {
get {
return layer.frame.size.width
}
set(value) {
layer.frame.size.width = value
}
}
/// A property that accesses the layer.frame.size.height property.
@IBInspectable public var height: CGFloat {
get {
return layer.frame.size.height
}
set(value) {
layer.frame.size.height = value
}
}
/// A property that accesses the backing layer's shadowColor.
@IBInspectable public var shadowColor: UIColor? {
didSet {
layer.shadowColor = shadowColor?.CGColor
}
}
/// A property that accesses the backing layer's shadowOffset.
@IBInspectable public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set(value) {
layer.shadowOffset = value
}
}
/// A property that accesses the backing layer's shadowOpacity.
@IBInspectable public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set(value) {
layer.shadowOpacity = value
}
}
/// A property that accesses the backing layer's shadowRadius.
@IBInspectable public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set(value) {
layer.shadowRadius = value
}
}
/// A property that accesses the backing layer's shadowPath.
@IBInspectable public var shadowPath: CGPath? {
get {
return layer.shadowPath
}
set(value) {
layer.shadowPath = value
}
}
/// Enables automatic shadowPath sizing.
@IBInspectable public var shadowPathAutoSizeEnabled: Bool = true {
didSet {
if shadowPathAutoSizeEnabled {
layoutShadowPath()
} else {
shadowPath = nil
}
}
}
/**
A property that sets the shadowOffset, shadowOpacity, and shadowRadius
for the backing layer. This is the preferred method of setting depth
in order to maintain consitency across UI objects.
*/
public var depth: MaterialDepth = .None {
didSet {
let value: MaterialDepthType = MaterialDepthToValue(depth)
shadowOffset = value.offset
shadowOpacity = value.opacity
shadowRadius = value.radius
layoutShadowPath()
}
}
/// A property that sets the cornerRadius of the backing layer.
public var cornerRadiusPreset: MaterialRadius = .None {
didSet {
if let v: MaterialRadius = cornerRadiusPreset {
cornerRadius = MaterialRadiusToValue(v)
}
}
}
/// A property that accesses the layer.cornerRadius.
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set(value) {
layer.cornerRadius = value
layoutShadowPath()
}
}
/// A preset property to set the borderWidth.
public var borderWidthPreset: MaterialBorder = .None {
didSet {
borderWidth = MaterialBorderToValue(borderWidthPreset)
}
}
/// A property that accesses the layer.borderWith.
@IBInspectable public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(value) {
layer.borderWidth = value
}
}
/// A property that accesses the layer.borderColor property.
@IBInspectable public var borderColor: UIColor? {
get {
return nil == layer.borderColor ? nil : UIColor(CGColor: layer.borderColor!)
}
set(value) {
layer.borderColor = value?.CGColor
}
}
/// A property that accesses the layer.position property.
@IBInspectable public var position: CGPoint {
get {
return layer.position
}
set(value) {
layer.position = value
}
}
/// A property that accesses the layer.zPosition property.
@IBInspectable public var zPosition: CGFloat {
get {
return layer.zPosition
}
set(value) {
layer.zPosition = value
}
}
/// Handle the clearButton manually.
@IBInspectable public var clearButtonAutoHandleEnabled: Bool = true {
didSet {
clearButton.removeTarget(self, action: #selector(handleClearButton), forControlEvents: .TouchUpInside)
if clearButtonAutoHandleEnabled {
clearButton.addTarget(self, action: #selector(handleClearButton), forControlEvents: .TouchUpInside)
}
}
}
/// Reference to the clearButton.
public var clearButton: FlatButton!
/// The bottom border layer.
public private(set) lazy var lineLayer: CAShapeLayer = CAShapeLayer()
/**
A property that sets the distance between the textField and
lineLayer.
*/
@IBInspectable public var lineLayerDistance: CGFloat = 4
/// The lineLayer color when inactive.
@IBInspectable public var lineLayerColor: UIColor? {
didSet {
lineLayer.backgroundColor = lineLayerColor?.CGColor
}
}
/// The lineLayer active color.
@IBInspectable public var lineLayerActiveColor: UIColor?
/// The lineLayer detail color when inactive.
@IBInspectable public var lineLayerDetailColor: UIColor?
/// The lineLayer detail active color.
@IBInspectable public var lineLayerDetailActiveColor: UIColor?
/**
The title UILabel that is displayed when there is text. The
titleLabel text value is updated with the placeholder text
value before being displayed.
*/
@IBInspectable public private(set) var titleLabel: UILabel!
/// The color of the titleLabel text when the textField is not active.
@IBInspectable public var titleLabelColor: UIColor? {
didSet {
titleLabel.textColor = titleLabelColor
if nil == lineLayerColor {
lineLayerColor = titleLabelColor
}
}
}
/// The color of the titleLabel text when the textField is active.
@IBInspectable public var titleLabelActiveColor: UIColor? {
didSet {
if nil == lineLayerActiveColor {
lineLayerActiveColor = titleLabelActiveColor
}
}
}
/**
A property that sets the distance between the textField and
titleLabel.
*/
@IBInspectable public var titleLabelAnimationDistance: CGFloat = 4
/// An override to the text property.
@IBInspectable public override var text: String? {
didSet {
textFieldDidChange()
}
}
/**
The detail UILabel that is displayed when the detailLabelHidden property
is set to false.
*/
public var detailLabel: UILabel? {
didSet {
prepareDetailLabel()
}
}
/**
The color of the detailLabel text when the detailLabelHidden property
is set to false.
*/
@IBInspectable public var detailLabelActiveColor: UIColor? {
didSet {
if !detailLabelHidden {
detailLabel?.textColor = detailLabelActiveColor
if nil == lineLayerDetailActiveColor {
lineLayerDetailActiveColor = detailLabelActiveColor
}
}
}
}
/**
A property that sets the distance between the textField and
detailLabel.
*/
@IBInspectable public var detailLabelAnimationDistance: CGFloat = 8
/**
A Boolean that indicates the detailLabel should hide
automatically when text changes.
*/
@IBInspectable public var detailLabelAutoHideEnabled: Bool = true
/**
:name: detailLabelHidden
*/
@IBInspectable public var detailLabelHidden: Bool = true {
didSet {
if detailLabelHidden {
detailLabel?.textColor = titleLabelColor
lineLayer.backgroundColor = (editing ? lineLayerActiveColor : lineLayerColor)?.CGColor
hideDetailLabel()
} else {
detailLabel?.textColor = detailLabelActiveColor
lineLayer.backgroundColor = (nil == lineLayerDetailActiveColor ? detailLabelActiveColor : lineLayerDetailActiveColor)?.CGColor
showDetailLabel()
}
}
}
/// A wrapper for searchBar.placeholder.
@IBInspectable public override var placeholder: String? {
didSet {
if let v: String = placeholder {
attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderTextColor])
}
}
}
/// Placeholder textColor.
@IBInspectable public var placeholderTextColor: UIColor = MaterialColor.black {
didSet {
if let v: String = placeholder {
attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderTextColor])
}
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: CGRectNull)
}
/// Overriding the layout callback for sublayers.
public override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
if self.layer == layer {
layoutLineLayer()
layoutShadowPath()
}
}
/**
A method that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
public func animate(animation: CAAnimation) {
animation.delegate = self
if let a: CABasicAnimation = animation as? CABasicAnimation {
a.fromValue = (nil == layer.presentationLayer() ? layer : layer.presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!)
}
if let a: CAPropertyAnimation = animation as? CAPropertyAnimation {
layer.addAnimation(a, forKey: a.keyPath!)
} else if let a: CAAnimationGroup = animation as? CAAnimationGroup {
layer.addAnimation(a, forKey: nil)
} else if let a: CATransition = animation as? CATransition {
layer.addAnimation(a, forKey: kCATransition)
}
}
/**
A delegation method that is executed when the backing layer starts
running an animation.
- Parameter anim: The currently running CAAnimation instance.
*/
public override func animationDidStart(anim: CAAnimation) {
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim)
}
/**
A delegation method that is executed when the backing layer stops
running an animation.
- Parameter anim: The CAAnimation instance that stopped running.
- Parameter flag: A boolean that indicates if the animation stopped
because it was completed or interrupted. True if completed, false
if interrupted.
*/
public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let a: CAPropertyAnimation = anim as? CAPropertyAnimation {
if let b: CABasicAnimation = a as? CABasicAnimation {
if let v: AnyObject = b.toValue {
if let k: String = b.keyPath {
layer.setValue(v, forKeyPath: k)
layer.removeAnimationForKey(k)
}
}
}
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag)
} else if let a: CAAnimationGroup = anim as? CAAnimationGroup {
for x in a.animations! {
animationDidStop(x, finished: true)
}
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public func prepareView() {
backgroundColor = MaterialColor.white
masksToBounds = false
placeholderTextColor = MaterialColor.grey.base
font = RobotoFont.regularWithSize(16)
textColor = MaterialColor.grey.darken4
borderStyle = .None
prepareClearButton()
prepareTitleLabel()
prepareLineLayer()
reloadView()
}
/// Reloads the view.
public func reloadView() {
/// Align the clearButton.
clearButton.frame = CGRectMake(width - height, 0, height, height)
}
/// Clears the textField text.
internal func handleClearButton() {
text = ""
}
/// Ahdnler when text value changed.
internal func textFieldValueChanged() {
if detailLabelAutoHideEnabled && !detailLabelHidden {
detailLabelHidden = true
lineLayer.backgroundColor = (nil == lineLayerActiveColor ? titleLabelActiveColor : lineLayerActiveColor)?.CGColor
}
}
/// Handler for text editing began.
internal func textFieldDidBegin() {
showTitleLabel()
titleLabel.textColor = titleLabelActiveColor
lineLayer.frame = CGRectMake(0, bounds.height + lineLayerDistance, bounds.width, 2)
lineLayer.backgroundColor = (detailLabelHidden ? nil == lineLayerActiveColor ? titleLabelActiveColor : lineLayerActiveColor : nil == lineLayerDetailActiveColor ? detailLabelActiveColor : lineLayerDetailActiveColor)?.CGColor
}
/// Handler for text changed.
internal func textFieldDidChange() {
sendActionsForControlEvents(.ValueChanged)
}
/// Handler for text editing ended.
internal func textFieldDidEnd() {
if 0 < text?.utf16.count {
showTitleLabel()
} else if 0 == text?.utf16.count {
hideTitleLabel()
}
titleLabel.textColor = titleLabelColor
lineLayer.frame = CGRectMake(0, bounds.height + lineLayerDistance, bounds.width, 1)
lineLayer.backgroundColor = (detailLabelHidden ? nil == lineLayerColor ? titleLabelColor : lineLayerColor : nil == lineLayerDetailColor ? detailLabelActiveColor : lineLayerDetailColor)?.CGColor
}
/// Sets the shadow path.
internal func layoutShadowPath() {
if shadowPathAutoSizeEnabled {
if .None == depth {
shadowPath = nil
} else if nil == shadowPath {
shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
} else {
animate(MaterialAnimation.shadowPath(UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath, duration: 0))
}
}
}
/// Prepares the titleLabel.
private func prepareTitleLabel() {
titleLabel = UILabel()
titleLabel.hidden = true
titleLabel.font = RobotoFont.mediumWithSize(12)
addSubview(titleLabel)
titleLabelColor = MaterialColor.grey.base
titleLabelActiveColor = MaterialColor.blue.accent3
if 0 < text?.utf16.count {
showTitleLabel()
} else {
titleLabel.alpha = 0
}
addTarget(self, action: #selector(textFieldDidBegin), forControlEvents: .EditingDidBegin)
addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged)
addTarget(self, action: #selector(textFieldDidEnd), forControlEvents: .EditingDidEnd)
}
/// Prepares the detailLabel.
private func prepareDetailLabel() {
if let v: UILabel = detailLabel {
v.hidden = true
addSubview(v)
if detailLabelHidden {
v.alpha = 0
} else {
showDetailLabel()
}
if nil == titleLabel {
addTarget(self, action: #selector(textFieldDidBegin), forControlEvents: .EditingDidBegin)
addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged)
addTarget(self, action: #selector(textFieldDidEnd), forControlEvents: .EditingDidEnd)
}
addTarget(self, action: #selector(textFieldValueChanged), forControlEvents: .ValueChanged)
}
}
/// Prepares the lineLayer.
private func prepareLineLayer() {
layoutLineLayer()
layer.addSublayer(lineLayer)
}
/// Layout the lineLayer.
private func layoutLineLayer() {
let h: CGFloat = 1 < lineLayer.frame.height ? lineLayer.frame.height : 1
lineLayer.frame = CGRectMake(0, bounds.height + lineLayerDistance, bounds.width, h)
}
/// Prepares the clearButton.
private func prepareClearButton() {
let image: UIImage? = MaterialIcon.cm.close
clearButton = FlatButton()
clearButton.contentEdgeInsets = UIEdgeInsetsZero
clearButton.pulseColor = MaterialColor.grey.base
clearButton.pulseScale = false
clearButton.tintColor = MaterialColor.grey.base
clearButton.setImage(image, forState: .Normal)
clearButton.setImage(image, forState: .Highlighted)
clearButtonAutoHandleEnabled = true
clearButtonMode = .Never
rightViewMode = .WhileEditing
rightView = clearButton
}
/// Shows and animates the titleLabel property.
private func showTitleLabel() {
if titleLabel.hidden {
if let s: String = placeholder {
titleLabel.text = s
placeholderText = s
placeholder = nil
}
let h: CGFloat = ceil(titleLabel.font.lineHeight)
titleLabel.frame = bounds
titleLabel.font = font
titleLabel.hidden = false
UIView.animateWithDuration(0.15, animations: { [unowned self] in
self.titleLabel.alpha = 1
self.titleLabel.transform = CGAffineTransformScale(self.titleLabel.transform, 0.75, 0.75)
self.titleLabel.frame = CGRectMake(0, -(self.titleLabelAnimationDistance + h), self.bounds.width, h)
})
}
}
/// Hides and animates the titleLabel property.
private func hideTitleLabel() {
UIView.animateWithDuration(0.15, animations: { [unowned self] in
self.titleLabel.transform = CGAffineTransformIdentity
self.titleLabel.frame = self.bounds
}) { [unowned self] _ in
self.placeholder = self.placeholderText
self.titleLabel.hidden = true
}
}
/// Shows and animates the detailLabel property.
private func showDetailLabel() {
if let v: UILabel = detailLabel {
if v.hidden {
let h: CGFloat = ceil(v.font.lineHeight)
v.frame = CGRectMake(0, bounds.height + lineLayerDistance, bounds.width, h)
v.hidden = false
UIView.animateWithDuration(0.15, animations: { [unowned self] in
v.frame.origin.y = self.frame.height + self.lineLayerDistance + self.detailLabelAnimationDistance
v.alpha = 1
})
}
}
}
/// Hides and animates the detailLabel property.
private func hideDetailLabel() {
if let v: UILabel = detailLabel {
UIView.animateWithDuration(0.15, animations: { [unowned self] in
v.alpha = 0
v.frame.origin.y -= self.detailLabelAnimationDistance
}) { _ in
v.hidden = true
}
}
}
}
| apache-2.0 | 5e2bb66ec3b4cc76dbb5aeab8525af94 | 33.555233 | 231 | 0.618491 | 5.426615 | false | false | false | false |
bradhowes/SynthInC | SynthInC/SwiftyTimer.swift | 1 | 5688 | //
// SwiftyTimer
//
// Copyright (c) 2015-2016 Radosław Pietruszewski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
extension Timer {
// MARK: Schedule timers
/// Create and schedule a timer that will call `block` once after the specified time.
@discardableResult
public class func after(_ interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
let timer = Timer.new(after: interval, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
@discardableResult
public class func every(_ interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
let timer = Timer.new(every: interval, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
/// (This variant also passes the timer instance to the block)
@nonobjc @discardableResult
public class func every(_ interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
let timer = Timer.new(every: interval, block)
timer.start()
return timer
}
// MARK: Create timers without scheduling
/// Create a timer that will call `block` once after the specified time.
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.after` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
public class func new(after interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, 0, 0, 0) { _ in
block()
}
}
/// Create a timer that will call `block` repeatedly in specified time intervals.
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.every` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
public class func new(every interval: TimeInterval, _ block: @escaping () -> Void) -> Timer {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
block()
}
}
/// Create a timer that will call `block` repeatedly in specified time intervals.
/// (This variant also passes the timer instance to the block)
///
/// - Note: The timer won't fire until it's scheduled on the run loop.
/// Use `NSTimer.every` to create and schedule a timer in one step.
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
@nonobjc public class func new(every interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
block(timer)
}
return timer
}
// MARK: Manual scheduling
/// Schedule this timer on the run loop
///
/// By default, the timer is scheduled on the current run loop for the default mode.
/// Specify `runLoop` or `modes` to override these defaults.
public func start(runLoop: RunLoop = .current, modes: RunLoop.Mode...) {
let modes = modes.isEmpty ? [RunLoop.Mode.default] : modes
for mode in modes {
runLoop.add(self, forMode: mode)
}
}
}
// MARK: - Time extensions
extension Double {
public var millisecond: TimeInterval { return self / 1000 }
public var milliseconds: TimeInterval { return self / 1000 }
public var ms: TimeInterval { return self / 1000 }
public var second: TimeInterval { return self }
public var seconds: TimeInterval { return self }
public var minute: TimeInterval { return self * 60 }
public var minutes: TimeInterval { return self * 60 }
public var hour: TimeInterval { return self * 3600 }
public var hours: TimeInterval { return self * 3600 }
public var day: TimeInterval { return self * 3600 * 24 }
public var days: TimeInterval { return self * 3600 * 24 }
}
| mit | 0a1c85cc9ec9ae484b9ec5a0a9138dfa | 41.440299 | 130 | 0.659047 | 4.731281 | false | false | false | false |
tutsplus/iOSFromScratch-TabBarControllers | Tabbed Library/BooksViewController.swift | 1 | 3449 | //
// BooksViewController.swift
// Library
//
// Created by Bart Jacobs on 07/12/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
class BooksViewController: UITableViewController {
let CellIdentifier = "Cell Identifier"
let SegueBookCoverViewController = "BookCoverViewController"
var author: [String: AnyObject]?
lazy var books: [AnyObject] = {
// Initialize Books
var buffer = [AnyObject]()
if let author = self.author, let books = author["Books"] as? [AnyObject] {
buffer += books
} else {
let filePath = NSBundle.mainBundle().pathForResource("Books", ofType: "plist")
if let path = filePath {
let authors = NSArray(contentsOfFile: path) as! [AnyObject]
for author in authors {
if let books = author["Books"] as? [AnyObject] {
buffer += books
}
}
}
}
return buffer
}()
// MARK: -
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Initialize Tab Bar Item
tabBarItem = UITabBarItem(title: "Books", image: UIImage(named: "icon-books"), tag: 1)
// Configure Tab Bar Item
tabBarItem.badgeValue = "8"
}
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
if let author = author, let name = author["Author"] as? String {
title = name
} else {
title = "Books"
}
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueBookCoverViewController {
if let indexPath = tableView.indexPathForSelectedRow, let book = books[indexPath.row] as? [String: String] {
let destinationViewController = segue.destinationViewController as! BookCoverViewController
destinationViewController.book = book
}
}
}
// MARK: -
// MARK: Table View Data Source Methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue Resuable Cell
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)
if let book = books[indexPath.row] as? [String: String], let title = book["Title"] {
// Configure Cell
cell.textLabel?.text = title
}
return cell;
}
// MARK: -
// MARK: Table View Delegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Perform Segue
performSegueWithIdentifier(SegueBookCoverViewController, sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| bsd-2-clause | 8b03d4d20b4987b638ffa2f76483f9da | 30.925926 | 121 | 0.591357 | 5.395931 | false | false | false | false |
imitationgame/pokemonpassport | pokepass/View/Main/Generic/VMainShadow.swift | 1 | 1210 | import UIKit
class VMainShadow:UIView
{
init()
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
alpha = 0
let visualEffect:UIVisualEffect = UIBlurEffect(style:UIBlurEffectStyle.dark)
let blur:UIVisualEffectView = UIVisualEffectView(effect:visualEffect)
blur.translatesAutoresizingMaskIntoConstraints = false
blur.isUserInteractionEnabled = false
blur.clipsToBounds = true
addSubview(blur)
let views:[String:UIView] = [
"blur":blur]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[blur]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[blur]-0-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
}
| mit | 9573f715b6796c441d77dd39606bb007 | 27.139535 | 84 | 0.587603 | 5.789474 | false | false | false | false |
jaischeema/Twist | Source/MediaItem.swift | 1 | 5195 | //
// MediaItem.swift
// Twist
//
// Created by Jais Cheema on 3/06/2016.
// Copyright © 2016 Needle Apps. All rights reserved.
//
import Foundation
import AVFoundation
var myContext = 0
let kPlaybackLikelyToKeepUp = "playbackLikelyToKeepUp"
class MediaItem: NSObject {
let player: Twist
let itemURL: URL
let itemIndex: Int
var avPlayerItem: AVPlayerItem?
var mediaResourceLoader: MediaItemResourceLoader?
init(player: Twist, itemURL: URL, itemIndex: Int) {
self.player = player
self.itemURL = itemURL
self.itemIndex = itemIndex
super.init()
self.setupResourceLoader()
self.setupObservers()
}
func cleanup() {
self.avPlayerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status))
self.avPlayerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges))
self.avPlayerItem?.removeObserver(self, forKeyPath: kPlaybackLikelyToKeepUp)
self.avPlayerItem = nil
self.mediaResourceLoader?.session.invalidateAndCancel()
}
func setupResourceLoader() {
self.mediaResourceLoader
= MediaItemResourceLoader(mediaURL: itemURL,
cachePath: player.dataSource?.twist(player, cacheFilePathForItemAtIndex: itemIndex),
cachingEnabled: player.dataSource?.twist(player, shouldCacheItemAtIndex: itemIndex))
self.mediaResourceLoader?.successfulDownloadCallback = { mediaItemURL in
self.player.delegate?.twist(self.player,
downloadedMedia: self.itemURL,
forItemAtIndex: self.itemIndex)
}
self.avPlayerItem = AVPlayerItem(asset: self.mediaResourceLoader!.asset)
}
func setupObservers() {
self.avPlayerItem!.addObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
options: [.new, .initial],
context: &myContext)
self.avPlayerItem!.addObserver(self,
forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges),
options: [.new, .initial],
context: &myContext)
self.avPlayerItem!.addObserver(self,
forKeyPath: kPlaybackLikelyToKeepUp,
options: [.new],
context: &myContext)
}
// MARK: Observer methods
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
guard context == &myContext else {
super.observeValue(forKeyPath: keyPath,
of: object,
change: change,
context: context)
return
}
guard let playerItem = object as? AVPlayerItem,
let keyPath = keyPath else { return }
switch keyPath {
case #keyPath(AVPlayerItem.status):
switch playerItem.status {
case .readyToPlay:
Twist.log.twistInfo("Item is ready to play")
case .failed:
Twist.log.twistError("Failed to play current media item")
self.player.changeState(TwistState.failed)
self.player.cleanupCurrentItem()
self.player.delegate?.twist(self.player,
failedToPlayURL: self.itemURL,
forItemAtIndex: self.itemIndex)
case .unknown:
Twist.log.twistDebug("Status updated but not ready to play")
}
case #keyPath(AVPlayerItem.loadedTimeRanges):
if let availableDuration = self.availableDurationForCurrentItem() {
let duration = playerItem.duration
let totalDuration = CMTimeGetSeconds(duration)
self.player.delegate?.twist(self.player,
loaded: availableDuration,
outOf: totalDuration)
}
case kPlaybackLikelyToKeepUp:
if playerItem.isPlaybackLikelyToKeepUp {
self.player.playRespectingForcePause()
}
default:
Twist.log.twistDebug("Unhandled key :\(keyPath)")
}
}
func availableDurationForCurrentItem() -> TimeInterval? {
guard let avPlayerItem = self.avPlayerItem else { return nil }
let loadedTimeRanges = avPlayerItem.loadedTimeRanges
if let timeRange = loadedTimeRanges.first?.timeRangeValue {
let startSeconds = CMTimeGetSeconds(timeRange.start)
let durationSeconds = CMTimeGetSeconds(timeRange.duration)
return startSeconds + durationSeconds
}
return nil
}
}
| mit | c39203684b6c093a8374d87aa33749c3 | 39.263566 | 122 | 0.557759 | 5.751938 | false | false | false | false |
gowansg/firefox-ios | Client/Frontend/Home/ReaderPanel.swift | 1 | 14008 | /* 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
import ReadingList
private struct ReadingListPanelUX {
static let RowHeight: CGFloat = 86
}
private struct ReadingListTableViewCellUX {
static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44)
static let ReadIndicatorWidth: CGFloat = 16 + 16 + 16 // padding + image width + padding
static let ReadIndicatorHeight: CGFloat = 14 + 16 + 14 // padding + image height + padding
static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest
static let TitleLabelFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Bold" : "HelveticaNeue-Medium", size: 15)
static let TitleLabelTopOffset: CGFloat = 14 - 4
static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16
static let TitleLabelRightOffset: CGFloat = -40
static let HostnameLabelFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue" : "HelveticaNeue-Light", size: 14)
static let HostnameLabelBottomOffset: CGFloat = 11
static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035)
static let DeleteButtonTitleFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue" : "HelveticaNeue-Light", size: 15)
static let DeleteButtonTitleColor = UIColor.whiteColor()
static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1)
static let MarkAsReadButtonTitleFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue" : "HelveticaNeue-Light", size: 15)
static let MarkAsReadButtonTitleColor = UIColor.whiteColor()
static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
// Localizable strings
static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item")
static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read")
static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread")
}
class ReadingListTableViewCell: SWTableViewCell {
var title: String = "Example" {
didSet {
titleLabel.text = title
updateAccessibilityLabel()
}
}
var url: NSURL = NSURL(string: "http://www.example.com")! {
didSet {
hostnameLabel.text = simplifiedHostnameFromURL(url)
updateAccessibilityLabel()
}
}
var unread: Bool = true {
didSet {
readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")
titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal)
markAsReadAction.name = markAsReadButton.titleLabel!.text
updateAccessibilityLabel()
}
}
private let deleteAction: UIAccessibilityCustomAction
private let markAsReadAction: UIAccessibilityCustomAction
let readStatusImageView: UIImageView!
let titleLabel: UILabel!
let hostnameLabel: UILabel!
let deleteButton: UIButton!
let markAsReadButton: UIButton!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
readStatusImageView = UIImageView()
titleLabel = UILabel()
hostnameLabel = UILabel()
deleteButton = UIButton()
markAsReadButton = UIButton()
deleteAction = UIAccessibilityCustomAction()
markAsReadAction = UIAccessibilityCustomAction()
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clearColor()
separatorInset = UIEdgeInsetsZero
layoutMargins = UIEdgeInsetsZero
preservesSuperviewLayoutMargins = false
contentView.addSubview(readStatusImageView)
readStatusImageView.contentMode = UIViewContentMode.Center
readStatusImageView.snp_makeConstraints { (make) -> () in
make.top.left.equalTo(self.contentView)
make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth)
make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight)
}
contentView.addSubview(titleLabel)
titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
titleLabel.numberOfLines = 2
titleLabel.font = ReadingListTableViewCellUX.TitleLabelFont
titleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset)
make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec
}
contentView.addSubview(hostnameLabel)
hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
hostnameLabel.numberOfLines = 1
hostnameLabel.font = ReadingListTableViewCellUX.HostnameLabelFont
hostnameLabel.snp_makeConstraints { (make) -> () in
make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)
make.left.right.equalTo(self.titleLabel)
}
deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor
deleteButton.titleLabel?.font = ReadingListTableViewCellUX.DeleteButtonTitleFont
deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor
deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center
deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal)
deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets
deleteAction.name = deleteButton.titleLabel!.text
deleteAction.target = self
deleteAction.selector = "deleteActionActivated"
rightUtilityButtons = [deleteButton]
markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor
markAsReadButton.titleLabel?.font = ReadingListTableViewCellUX.MarkAsReadButtonTitleFont
markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor
markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center
markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal)
markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets
markAsReadAction.name = markAsReadButton.titleLabel!.text
markAsReadAction.target = self
markAsReadAction.selector = "markAsReadActionActivated"
leftUtilityButtons = [markAsReadButton]
accessibilityCustomActions = [deleteAction, markAsReadAction]
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
private func simplifiedHostnameFromURL(url: NSURL) -> String {
let hostname = url.host ?? ""
for prefix in prefixesToSimplify {
if hostname.hasPrefix(prefix) {
return hostname.substringFromIndex(advance(hostname.startIndex, count(prefix)))
}
}
return hostname
}
@objc private func markAsReadActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0)
return true
}
@objc private func deleteActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0)
return true
}
private func updateAccessibilityLabel() {
if let hostname = hostnameLabel.text,
title = titleLabel.text {
let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.")
let string = "\(title), \(unreadStatus), \(hostname)"
var label: AnyObject
if !unread {
// mimic light gray visual dimming by "dimming" the speech by reducing pitch
let lowerPitchString = NSMutableAttributedString(string: string as String)
lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length))
label = NSAttributedString(attributedString: lowerPitchString)
} else {
label = string
}
// need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this
// see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple
// also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly...
setValue(label, forKey: "accessibilityLabel")
}
}
}
class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
private var records: [ReadingListClientRecord]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = ReadingListPanelUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell")
view.backgroundColor = AppConstants.PanelBackgroundColor
}
override func viewWillAppear(animated: Bool) {
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell
cell.delegate = self
if let record = records?[indexPath.row] {
cell.title = record.title
cell.url = NSURL(string: record.url)!
cell.unread = record.unread
}
return cell
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell {
cell.hideUtilityButtonsAnimated(true)
if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess {
// TODO This is a bit odd because the success value of the update is an optional optional Record
if let successValue = result.successValue, updatedRecord = successValue {
records?[indexPath.row] = updatedRecord
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
}
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.deleteRecord(record) where result.isSuccess {
records?.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) {
homePanelDelegate?.homePanel(self, didSelectURL: encodedURL)
}
}
}
| mpl-2.0 | c08f5fc7c352754782219f7b12676dcd | 50.5 | 333 | 0.716805 | 5.774114 | false | false | false | false |
FTChinese/iPhoneApp | FT Academy/HappyUser.swift | 1 | 3121 | //
// HappyReader.swift
// FT中文网
//
// Created by Oliver Zhang on 2017/5/11.
// Copyright © 2017年 Financial Times Ltd. All rights reserved.
//
import Foundation
import StoreKit
// MARK: When user is happy, request review
public class HappyUser {
private let versionKey = "current version"
private let launchCountKey = "launch count"
private let requestReviewFrequency = 10
private let ratePromptKey = "rate prompted"
private var shouldTrackRequestReview = false
public var didRequestReview = false
public var canTryRequestReview = true
func launchCount() {
let versionFromBundle: String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let versionFromUserDefault: String = UserDefaults.standard.string(forKey: versionKey) ?? ""
var currentLaunchCount: Int = UserDefaults.standard.integer(forKey: launchCountKey)
if versionFromBundle == versionFromUserDefault {
currentLaunchCount += 1
} else {
UserDefaults.standard.set(versionFromBundle, forKey: versionKey)
UserDefaults.standard.set(false, forKey: ratePromptKey)
currentLaunchCount = 1
}
UserDefaults.standard.set(currentLaunchCount, forKey: launchCountKey)
//print ("current version is \(versionFromBundle) and launch count is \(currentLaunchCount)")
// if let bundle = Bundle.main.bundleIdentifier {
// UserDefaults.standard.removePersistentDomain(forName: bundle)
// }
}
func requestReview() {
// MARK: Request user to review
let currentLaunchCount: Int = UserDefaults.standard.integer(forKey: launchCountKey)
let ratePrompted: Bool = UserDefaults.standard.bool(forKey: ratePromptKey)
if ratePrompted != true && currentLaunchCount >= requestReviewFrequency && canTryRequestReview == true {
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
UserDefaults.standard.set(true, forKey: ratePromptKey)
didRequestReview = true
shouldTrackRequestReview = true
}
}
}
func checkDeviceType() -> String {
let deviceType: String
if UIDevice.current.userInterfaceIdiom == .pad {
deviceType = "iPad"
} else {
deviceType = "iPhone"
}
return deviceType
}
func requestReviewTracking() -> String? {
let deviceType = checkDeviceType()
let versionFromBundle = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let currentLaunchCount = UserDefaults.standard.integer(forKey: launchCountKey)
let jsCode = "try{ga('send','event', '\(deviceType) Request Review', '\(versionFromBundle)', '\(currentLaunchCount)', {'nonInteraction':1});}catch(ignore){}"
if shouldTrackRequestReview == true {
shouldTrackRequestReview = false
didRequestReview = true
return jsCode
}
return nil
}
}
| mit | 2569fee723bc477cca3f1e0a4dde3fa9 | 38.897436 | 165 | 0.648458 | 5.003215 | false | false | false | false |
easyui/SwiftMan | SwiftMan/Extension/Swift/Array+Man.swift | 1 | 1247 | //
// Array+Man.swift
// SwiftMan
//
// Created by yangjun on 16/5/4.
// Copyright © 2016年 yangjun. All rights reserved.
//
extension Array {
/// 转JSON
///
/// - Returns: 可选的格式化的JSON字符串
public func m_prettyJSONString() -> String?{
return m_JSONString(option: [.prettyPrinted])
}
/// 转JSON
///
/// - Returns: 可选的一行JSON字符串
public func m_JSONStringRepresentation() -> String?{
return m_JSONString(option: [])
}
/// 转JSON
///
/// - Returns: 可选的JSON字符串
public func m_JSONString(option: JSONSerialization.WritingOptions,encoding:String.Encoding = String.Encoding.utf8) -> String?{
do{
let data = try JSONSerialization.data(withJSONObject: self, options: option)
return String(data: data, encoding: encoding)
} catch {
return nil
}
}
public mutating func m_safeSwap(from index: Index, to otherIndex: Index) {
guard index != otherIndex else { return }
guard startIndex..<endIndex ~= index else { return }
guard startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
}
| mit | 3b6610c8ad8422f0272e746c6d484154 | 25.444444 | 130 | 0.594958 | 4.265233 | false | false | false | false |
chrisjmendez/swift-exercises | Maps/MyMapbox/MyMapbox/ViewController.swift | 1 | 1598 | //
// ViewController.swift
// MyMapbox
//
// Created by Tommy Trojan on 10/5/15.
// Copyright © 2015 Chris Mendez. All rights reserved.
//
import UIKit
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
var mapView: MGLMapView!
@IBOutlet weak var mapCanvas: UIView!
func initMap(){
// initialize the map view
mapView = MGLMapView(frame: mapCanvas.bounds)
mapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
// set the map's center coordinate
mapView.setCenterCoordinate(CLLocationCoordinate2D(
latitude: 38.894368,
longitude: -77.036487),
zoomLevel: 15,
animated: false)
view.addSubview(mapView)
mapView.delegate = self
}
func initPoint(){
// Declare the annotation `point` and set its coordinates, title, and subtitle
let point = MGLPointAnnotation()
point.coordinate = CLLocationCoordinate2D(latitude: 38.894368, longitude: -77.036487)
point.title = "Hello world!"
point.subtitle = "Welcome to The Ellipse."
// Add annotation `point` to the map
mapView.addAnnotation(point)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initMap()
initPoint()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 579d4f1692695c87413836b8b9254ab5 | 26.067797 | 93 | 0.623669 | 4.854103 | false | false | false | false |
EugeneVegner/sit-autolifestory-vapor-server | Sources/App/Helpers/Response.swift | 1 | 2951 | import Foundation
//import Core
import Vapor
import HTTP
@_exported import Node
//extension Request {
//
// private func callback(data: Node? = nil, errors: [Error]? = nil, code: Int = 0) -> ResponseRepresentable {
//
// var success: Bool = true
// var nodeErr: [Node]? = nil
//
// if let errs = errors {
// success = false
//
// for err in errs {
// nodeErr?.append(err.makeNode())
// }
// }
// var resp: [String: Node] = [:]
// resp["success"] = Node(success)
// resp["code"] = Node(code)
// resp["data"] = data == nil ? Node.null : data!
// resp["errors"] = nodeErr == nil ? Node.null : Node(nodeErr!)
//
// return JSON(Node(resp))
//
// }
//
// func callbackSuccess(data: Node) -> ResponseRepresentable {
// return callback(data: data, errors: nil, code: 0)
// }
//
// func callbackFailure(errors:[Error]) -> ResponseRepresentable {
//
// if errors.count == 0 {
// return callback(data: nil, errors: [Errors.unknownError], code: -1)
// }
//
// let err = errors.first
// return callback(data: nil, errors: errors, code: err?.code ?? -2)
// }
//
//
//}
//public struct SuccessJSON: JSON {
// public var node: Node
//
// public init(_ node: Node) {
// self.node = node
// }
//}
//import Vapor
//import HTTP
//import Fluent
//import Foundation
//import Core
//
////import Foundation
////import Core
//@_exported import Node
//
////public struct SuccessJSON: NodeBacked {
//// public var node: Node
//// public init(_ node: Node) {
//// self.node = [
//// "success": true,
//// "code": 0,
//// "errors": nil,
//// "data": node
//// ]
////
////// self.node["success"] = true
////// self.node["code"] = 0
////// self.node["errors"] = nil
////// self.node["data"] = node
//// }
////}
//
//
//
//
//
//final class SuccessJSON {
// public var data: Node
// var code: Int = 0
//
// public init(_ data: Node) {
// self.data = data
// }
//
// init(data: JSON, code: Int = 0) {
// self.data = data.node
// self.code = code
// }
//
// func send() -> Node {
// return Node([
// "success": true,
// "code": Node(self.code),
// "data": data
// ])
// }
//
//
//
// func index(request: Request) throws -> ResponseRepresentable {
// return try Post.all().makeNode().converted(to: JSON.self)
// }
//
// func test(request: Request) throws -> ResponseRepresentable {
// // var post = try request.post()
// // try post.save()
// // return post
//
//
// return JSON(["source":"val"])
// }
//
//}
| mit | dcb48bd2f3b2bd4005ce1cde39dcdbcf | 22.054688 | 112 | 0.471027 | 3.467685 | false | false | false | false |
nnsnodnb/nowplaying-ios | NowPlaying/Sources/ViewControllers/Setting/SettingViewController.swift | 1 | 5821 | //
// SettingViewController.swift
// NowPlaying
//
// Created by Yuya Oka on 2021/12/31.
//
import RxDataSources
import RxSwift
import UIKit
import UniformTypeIdentifiers
final class SettingViewController: UIViewController {
// MARK: - Dependency
typealias Dependency = SettingViewModelType
// MARK: - Life Cycle
private let viewModel: SettingViewModelType
private let disposeBag = DisposeBag()
@IBOutlet private var tableView: UITableView! {
didSet {
tableView.register(SettingTableViewCell.self)
tableView.tableFooterView = .init()
}
}
private lazy var rightBarButtonItem: UIBarButtonItem = {
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: nil, action: nil)
navigationItem.rightBarButtonItem = barButtonItem
return barButtonItem
}()
private lazy var dataSource: DataSource = {
return .init(
animationConfiguration: .init(insertAnimation: .top, reloadAnimation: .automatic, deleteAnimation: .bottom),
decideViewTransition: { _, _, changesets in
return changesets.contains(where: { !$0.insertedSections.isEmpty }) ? .reload : .animated
},
configureCell: { _, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(with: SettingTableViewCell.self, for: indexPath)
cell.configure(item: item)
return cell
},
titleForHeaderInSection: { dataSource, section in
return dataSource[section].model.sectionTitle
}
)
}()
// MARK: - Initialize
init(dependency: Dependency) {
self.viewModel = dependency
super.init(nibName: Self.className, bundle: .main)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "設定"
bind(to: viewModel)
}
}
// MARK: - Private method
private extension SettingViewController {
func bind(to viewModel: SettingViewModelType) {
// 閉じるボタン
rightBarButtonItem.rx.tap.asSignal()
.emit(to: viewModel.inputs.dismiss)
.disposed(by: disposeBag)
// UITableView
tableView.rx.modelSelected(Item.self).asSignal()
.emit(to: viewModel.inputs.item)
.disposed(by: disposeBag)
tableView.rx.itemSelected.asSignal()
.emit(with: self, onNext: { strongSelf, indexPath in
strongSelf.tableView.deselectRow(at: indexPath, animated: true)
})
.disposed(by: disposeBag)
viewModel.outputs.dataSource
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
}
// MARK: - DataSource
private extension SettingViewController {
typealias DataSource = RxTableViewSectionedAnimatedDataSource<SectionModel>
}
// MARK: - SectionModel
extension SettingViewController {
typealias SectionModel = AnimatableSectionModel<Section, Item>
}
// MARK: - Section
extension SettingViewController {
enum Section: String, Equatable, IdentifiableType {
case sns
case app
// MARK: - Properties
var identity: String {
return rawValue
}
var sectionTitle: String {
switch self {
case .sns:
return "SNS設定"
case .app:
return "アプリについて"
}
}
}
}
// MARK: - Item
extension SettingViewController {
enum Item: Equatable, IdentifiableType {
case socialType(SocialType)
case link(Link)
case removeAdMob
case review
// MARK: - Properties
var identity: String {
switch self {
case let .socialType(socialType):
return socialType.rawValue
case let .link(link):
return link.rawValue
case .removeAdMob:
return "removeAdMob"
case .review:
return "review"
}
}
var title: String {
switch self {
case let .socialType(socialType):
switch socialType {
case .twitter:
return "Twitter設定"
case .mastodon:
return "Mastodon設定"
}
case let .link(link):
return link.title
case .removeAdMob:
return "アプリ内広告削除(有料)"
case .review:
return "レビューする"
}
}
}
}
// MARK: - Link
extension SettingViewController {
enum Link: String, Equatable {
case developer
case github
case contact
// MARK: - Properties
var url: URL {
switch self {
case .developer:
return URL(string: "https://twitter.com/nnsnodnb")!
case .github:
return URL(string: "https://github.com/nnsnodnb/nowplaying-ios")!
case .contact:
return URL(string: "https://forms.gle/gE5ms3bEM5A85kdVA")!
}
}
var title: String {
switch self {
case .developer:
return "開発者(Twitter)"
case .github:
return "ソースコード(GitHub)"
case .contact:
return "機能要望・バグ報告"
}
}
}
}
// MARK: - ViewControllerInjectable
extension SettingViewController: ViewControllerInjectable {}
| mit | 180f528571899504e257e9838b73b072 | 28.287179 | 120 | 0.573105 | 4.987773 | false | false | false | false |
mendesbarreto/IOS | Slice/Slice/AppDelegate.swift | 1 | 2457 | //
// AppDelegate.swift
// Slice
//
// Created by Douglas Barreto on 2/15/16.
// Copyright © 2016 Concrete Solutions. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var strO:String? = nil
strO = "0"
var text: String = "Hello budy . Hello!"
let index:String.Index = text.characters.indexOf( "." )!
let i:Int = index.toInt()
print(i)
//print( Int(index) )
// var highscore:String = "Douglas "
// highscore.appendContentsOf(index!)
// print(highscore)
//
// if let str:String = index {
// print("NAME: \(str)")
// }
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | aa0410873296be7ca240d00b21f238a2 | 33.591549 | 279 | 0.751629 | 4.489945 | false | false | false | false |
Asura19/SwiftAlgorithm | SwiftAlgorithm/SwiftAlgorithm/LC224.swift | 1 | 1627 | //
// LC224.swift
// SwiftAlgorithm
//
// Created by Phoenix on 2019/7/20.
// Copyright © 2019 Phoenix. All rights reserved.
//
import Foundation
extension String {
var int: Int? {
return Int(self)
}
var compute: (Int, Int) -> Int {
func plus(lhs: Int, rhs: Int) -> Int {
return lhs + rhs
}
func difference(lhs: Int, rhs: Int) -> Int {
return lhs - rhs
}
if self == "+" {
return plus
}
else {
return difference
}
}
}
extension Character {
var string: String {
return String(self)
}
}
extension LeetCode {
// "(1+(4+5+2)-3)+(6+8)"
static func calculate(_ s: String) -> Int {
var stack = Stack<String>()
var result: Int = 0
for c in s.reversed() {
if c == "(" {
var temp = 0
var lhs = stack.pop()!.int!
while stack.top()! != ")" {
let cal = stack.pop()!.compute
let rhs = stack.pop()!.int!
temp = cal(lhs, rhs)
lhs = temp
}
stack.pop()
stack.push(String(temp))
}
else {
stack.push(c.string)
}
}
var lhs = stack.pop()!.int!
while stack.count > 0 {
let cal = stack.pop()!.compute
let rhs = stack.pop()!.int!
result = cal(lhs, rhs)
lhs = result
}
return result
}
}
| mit | 02018a4528d0eba02f6ace0821d2baec | 20.972973 | 52 | 0.413284 | 4.278947 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILEUpdateConnection.swift | 1 | 6190 | //
// HCILEUpdateConnection.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Connection Update Command
///
/// The LE_Connection_Update command is used to change the Link Layer connection parameters of a connection.
/// This command may be issued on both the master and slave.
func updateLowEnergyConnection(handle: UInt16,
connectionInterval: LowEnergyConnectionIntervalRange = .full,
connectionLatency: LowEnergyConnectionLatency = .zero,
supervisionTimeout: LowEnergySupervisionTimeout = .max,
connectionLength: LowEnergyConnectionLength = .full,
timeout: HCICommandTimeout = .default) async throws {
let parameters = HCILEUpdateConnection(connectionHandle: handle,
connectionInterval: connectionInterval,
connectionLatency: connectionLatency,
supervisionTimeout: supervisionTimeout,
connectionLength: connectionLength)
try await deviceRequest(parameters, timeout: timeout)
}
}
// MARK: - Command
/// LE Connection Update Command
///
/// The LE_Connection_Update command is used to change the Link Layer connection parameters of a connection. This command may be issued on both the master and slave.
///
/// The Conn_Interval_Min and Conn_Interval_Max parameters are used to define the minimum and maximum allowed connection interval.
/// The Conn_Interval_Min parameter shall not be greater than the Conn_Interval_Max parameter.
///
/// The Conn_Latency parameter shall define the maximum allowed connection latency.
///
/// The Supervision_Timeout parameter shall define the link supervision timeout for the LE link.
/// The Supervision_Timeout in milliseconds shall be larger than (1 + Conn_Latency) * Conn_Interval_Max * 2, where Conn_Interval_Max is given in milliseconds.
///
/// The Minimum_CE_Length and Maximum_CE_Length are information parameters providing the Controller with a hint about the expected minimum and maximum length
/// of the connection events. The Minimum_CE_Length shall be less than or equal to the Maximum_CE_Length.
///
/// The actual parameter values selected by the Link Layer may be different from the parameter values provided by the Host through this command.
@frozen
public struct HCILEUpdateConnection: HCICommandParameter { // HCI_LE_Connection_Update
public typealias SupervisionTimeout = LowEnergySupervisionTimeout
public static let command = HCILowEnergyCommand.connectionUpdate //0x0013
public let connectionHandle: UInt16 //Connection_Handle
/// Value for the connection event interval.
///
/// Defines the minimum and maximum allowed connection interval.
public let connectionInterval: LowEnergyConnectionIntervalRange // Conn_Interval_Min, Conn_Interval_Max
/// Slave latency for the connection in number of connection events.
///
/// Defines the maximum allowed connection latency.
public let connectionLatency: LowEnergyConnectionLatency
/// Supervision timeout for the LE Link.
///
/// Defines the link supervision timeout for the connection.
///
/// - Note: The `supervisionTimeout` in milliseconds shall be
/// larger than the `connectionInterval.miliseconds.upperBound` in milliseconds.
public let supervisionTimeout: SupervisionTimeout
/// Connection Length
///
/// Informative parameters providing the Controller with the expected minimum
/// and maximum length of the connection needed for this LE connection.
public let connectionLength: LowEnergyConnectionLength
public init(connectionHandle: UInt16,
connectionInterval: LowEnergyConnectionIntervalRange = .full,
connectionLatency: LowEnergyConnectionLatency = .zero,
supervisionTimeout: SupervisionTimeout = .max,
connectionLength: LowEnergyConnectionLength = .full) {
precondition(supervisionTimeout.miliseconds > connectionInterval.miliseconds.upperBound, "The Supervision_Timeout in milliseconds shall be larger than the Conn_Interval_Max in milliseconds.")
self.connectionHandle = connectionHandle
self.connectionInterval = connectionInterval
self.connectionLatency = connectionLatency
self.supervisionTimeout = supervisionTimeout
self.connectionLength = connectionLength
}
public var data: Data {
let connectionIntervalMinBytes = connectionInterval.rawValue.lowerBound.littleEndian.bytes
let connectionIntervalMaxBytes = connectionInterval.rawValue.upperBound.littleEndian.bytes
let connectionLatencyBytes = connectionLatency.rawValue.littleEndian.bytes
let supervisionTimeoutBytes = supervisionTimeout.rawValue.littleEndian.bytes
let connectionLengthMinBytes = connectionLength.rawValue.lowerBound.littleEndian.bytes
let connectionLengthMaxBytes = connectionLength.rawValue.upperBound.littleEndian.bytes
return Data([connectionHandle.littleEndian.bytes.0,
connectionHandle.littleEndian.bytes.1,
connectionIntervalMinBytes.0,
connectionIntervalMinBytes.1,
connectionIntervalMaxBytes.0,
connectionIntervalMaxBytes.1,
connectionLatencyBytes.0,
connectionLatencyBytes.1,
supervisionTimeoutBytes.0,
supervisionTimeoutBytes.1,
connectionLengthMinBytes.0,
connectionLengthMinBytes.1,
connectionLengthMaxBytes.0,
connectionLengthMaxBytes.1])
}
}
| mit | 4bcfab668e98538ec11481dff21fb504 | 48.119048 | 199 | 0.681047 | 5.626364 | false | false | false | false |
sora0077/iTunesMusic | Sources/Player/PlayerImpl.swift | 1 | 12128 | //
// CrossFadePlayer.swift
// iTunesMusic
//
// Created by 林達也 on 2016/06/12.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import AVKit
import AVFoundation
import APIKit
import RxSwift
import ErrorEventHandler
import RealmSwift
import AbstractPlayerKit
private extension AVPlayerItem {
private struct AVPlayerItemKey {
static var trackId: UInt8 = 0
}
var trackId: Int? {
get {
return objc_getAssociatedObject(self, &AVPlayerItemKey.trackId) as? Int
}
set {
objc_setAssociatedObject(self, &AVPlayerItemKey.trackId, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private extension Notification.Name {
static let PlayerTrackItemPrepareForPlay = Notification.Name("PlayerTrackItemPrepareForPlay")
}
public final class PlayerTrackItem: PlayerItem {
fileprivate let track: Model.Track
override public var name: String? { return track.entity?.name }
init(track: Model.Track) {
self.track = track
super.init()
}
override public func fetcher() -> Observable<AVPlayerItem?> {
guard let track = track.entity, track.canPreview else {
return .just(nil)
}
func getPreviewURL() -> Observable<URL?>? {
guard let url = track.metadata?.fileURL ?? track.metadata?.previewURL else { return nil }
print(url)
return .just(url)
}
let id = track.id
return (getPreviewURL() ?? fetchPreviewURL(from: track)).flatMap { url -> Observable<AVPlayerItem?> in
guard let url = url else { return .just(nil) }
return Observable.create { subscriber in
let asset = AVURLAsset(url: url)
asset.loadValuesAsynchronously(forKeys: ["duration"]) {
var error: NSError?
let status = asset.statusOfValue(forKey: "duration", error: &error)
switch status {
case .loaded:
let item = AVPlayerItem(asset: asset)
item.trackId = id
configureFading(item: item)
NotificationCenter.default.post(
name: .PlayerTrackItemPrepareForPlay,
object: item)
subscriber.onNext(item)
subscriber.onCompleted()
default:
subscriber.onNext(nil)
}
}
return Disposables.create()
}
}
}
private func fetchPreviewURL(from track: Track) -> Observable<URL?> {
let (id, viewURL) = (track.id, track.viewURL)
return Observable<URL?>.create { [weak self] subscriber in
let task = Session.shared.send(GetPreviewUrl(id: id, url: viewURL), callbackQueue: callbackQueue) { result in
switch result {
case .success(let (url, duration)):
var fileURL: URL?
let realm = iTunesRealm()
try? realm.write {
guard let track = self?.track.entity?.impl else { return }
fileURL = track.metadata?.fileURL
let metadata = _TrackMetadata(track: track)
metadata.updatePreviewURL(url)
metadata.duration = Double(duration) / 1000
realm.add(metadata, update: true)
}
subscriber.onNext(fileURL ?? url)
case .failure:
subscriber.onNext(nil)
}
}
task?.resume()
return Disposables.create {
task?.cancel()
}
}
}
override public func didFinishRequest() -> PlayerItem.RequestState {
return .done
}
}
public final class PlayerListItem: PlayerItem {
override public var name: String? { return playlist.name }
private let playlist: Playlist
public var tracks: [PlayerTrackItem] = []
private var requesting: Bool = false
init(playlist: Playlist) {
self.playlist = playlist
super.init()
}
override public func fetcher() -> Observable<AVPlayerItem?> {
if self.requesting {
return .just(nil)
}
return Observable<Observable<AVPlayerItem?>>.create { [weak self] subscriber in
DispatchQueue.main.async {
guard let `self` = self else { return }
self.requesting = true
let index = self.tracks.count
let playlist = self.playlist
if playlist.isTrackEmpty || playlist.trackCount <= index {
self.requesting = false
subscriber.onNext(.just(nil))
return
}
if let paginator = playlist as? _Fetchable,
!paginator._hasNoPaginatedContents && playlist.trackCount - index < 3 {
if !paginator._requesting.value {
paginator.fetch(ifError: DefaultError.self, level: DefaultErrorLevel.none) { [weak self] _ in
self?.requesting = false
subscriber.onNext(.just(nil))
}
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.requesting = false
subscriber.onNext(.just(nil))
}
}
return
}
let track = Model.Track(track: playlist.track(at: index))
let item = PlayerTrackItem(track: track)
self.tracks.append(item)
self.requesting = false
subscriber.onNext(item.fetcher())
}
return Disposables.create()
}.flatMap { $0 }
}
override public func didFinishRequest() -> PlayerItem.RequestState {
return DispatchQueue.main.sync {
if self.playlist.isTrackEmpty {
return .done
}
if self.playlist.allTrackCount == self.items.count {
return .done
}
return .prepareForRequest
}
}
}
private enum DefaultError: ErrorLog.Error {
case none
init(error: Swift.Error?) {
self = .none
}
}
private enum DefaultErrorLevel: ErrorLog.Level {
case none
}
final class Player2: NSObject {
fileprivate let core: AbstractPlayerKit.Player
var errorType: ErrorLog.Error.Type = DefaultError.self
var errorLevel: ErrorLog.Level = DefaultErrorLevel.none
private(set) lazy var nowPlaying: Observable<Track?> = asObservable(self._nowPlayingTrack)
private let _nowPlayingTrack = Variable<Track?>(nil)
let currentTime = Variable<Float64>(0)
var playingQueue: Observable<[PlayerItem]> {
//swiftlint:disable:next force_cast
return core.items.map { $0.map { $0 as! PlayerItem } }.subscribeOn(MainScheduler.instance)
}
var playing: Bool { return core.playing }
fileprivate var middlewares: [PlayerMiddleware] = []
private let queuePlayer = AVQueuePlayer()
private let disposeBag = DisposeBag()
override init() {
core = AbstractPlayerKit.Player(queuePlayer: queuePlayer)
super.init()
#if (arch(i386) || arch(x86_64)) && os(iOS)
queuePlayer.volume = 0.02
print("simulator")
#else
print("iphone")
#endif
queuePlayer.addObserver(self, forKeyPath: #keyPath(AVQueuePlayer.currentItem), options: .new, context: nil)
queuePlayer.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.1, 600), queue: nil) { [weak self] (time) in
self?.currentTime.value = CMTimeGetSeconds(time)
}
NotificationCenter.default.addObserver(
self,
selector: #selector(self.trackItemGenerateAVPlayerItem(notification:)),
name: .PlayerTrackItemPrepareForPlay,
object: nil)
nowPlaying.map { $0?.id }.distinctUntilChanged { $0 == $1 }
.subscribe(onNext: { [weak self] trackId in
if let trackId = trackId {
self?.middlewares.forEach { $0.willStartPlayTrack(trackId) }
} else {
self?.middlewares.forEach { $0.didEndPlay() }
}
})
.addDisposableTo(disposeBag)
}
deinit {
queuePlayer.removeObserver(self, forKeyPath: #keyPath(AVQueuePlayer.currentItem))
NotificationCenter.default.removeObserver(self)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { return }
switch keyPath {
case #keyPath(AVQueuePlayer.currentItem):
DispatchQueue.main.async {
var track: Model.Track?
if let trackId = self.queuePlayer.currentItem?.trackId {
track = Model.Track(trackId: trackId)
}
self._nowPlayingTrack.value = track?.entity
}
default:()
}
}
@objc
private func trackItemGenerateAVPlayerItem(notification: Notification) {
guard doOnMainThread(execute: self.trackItemGenerateAVPlayerItem(notification: notification)) else { return }
guard let avPlayerItem = notification.object as? AVPlayerItem else { return }
NotificationCenter.default.addObserver(
self,
selector: #selector(self.didEndPlay(notification:)),
name: .AVPlayerItemDidPlayToEndTime,
object: avPlayerItem)
}
func install(middleware: PlayerMiddleware) {
middlewares.append(middleware)
middleware.middlewareInstalled(self)
}
func play() { core.play() }
func pause() { core.pause() }
func advanceToNextItem() { core.advanceToNextItem() }
func add(track: Model.Track) {
let item = PlayerTrackItem(track: track)
core.insert(inPriorityHigh: item)
}
func add(playlist: Playlist) {
let item = PlayerListItem(playlist: playlist)
core.insert(item, after: nil)
}
func removeAll() {
core.removeAllItems()
}
}
extension Player2: Player {
@objc
fileprivate func didEndPlay(notification: Notification) {
guard doOnMainThread(execute: self.didEndPlay(notification: notification)) else { return }
if let item = notification.object as? AVPlayerItem, let trackId = item.trackId {
middlewares.forEach { $0.didEndPlayTrack(trackId) }
}
}
}
private func configureFading(item: AVPlayerItem) {
guard let track = item.asset.tracks(withMediaType: AVMediaType.audio).first else { return }
let inputParams = AVMutableAudioMixInputParameters(track: track)
let fadeDuration = CMTimeMakeWithSeconds(5, 600)
let fadeOutStartTime = item.asset.duration - fadeDuration
let fadeInStartTime = kCMTimeZero
inputParams.setVolumeRamp(fromStartVolume: 1, toEndVolume: 0, timeRange: CMTimeRangeMake(fadeOutStartTime, fadeDuration))
inputParams.setVolumeRamp(fromStartVolume: 0, toEndVolume: 1, timeRange: CMTimeRangeMake(fadeInStartTime, fadeDuration))
// var callbacks = AudioProcessingTapCallbacks()
// var tap: Unmanaged<MTAudioProcessingTap>?
// MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PostEffects, &tap)
// inputParams.audioTapProcessor = tap?.takeUnretainedValue()
// tap?.release()
let audioMix = AVMutableAudioMix()
audioMix.inputParameters = [inputParams]
item.audioMix = audioMix
}
| mit | 06c15bd08e7df11f25d42c44e9ab6d14 | 33.331445 | 150 | 0.582474 | 4.979047 | false | false | false | false |
cfdrake/lobsters-reader | Source/UI/View Controllers/StoriesViewController/StoryTableViewCell.swift | 1 | 1457 | //
// StoryTableViewCell.swift
// LobstersReader
//
// Created by Colin Drake on 5/28/17.
// Copyright © 2017 Colin Drake. All rights reserved.
//
import UIKit
protocol StoryTableViewCellDelegate {
func tappedCommentsButton(inStoryTableViewCell cell: StoryTableViewCell)
}
/// Table view cell for stories.
final class StoryTableViewCell: UITableViewCell {
static let cellIdentifier = "StoryTableViewCell"
static let nib = UINib(nibName: StoryTableViewCell.cellIdentifier, bundle: .main)
@IBOutlet var storyTitleLabel: UILabel?
@IBOutlet var storyScoreLabel: UILabel?
@IBOutlet var storyDomainLabel: UILabel?
@IBOutlet var storySubmitDateLabel: UILabel?
@IBOutlet var storyCommentsButton: UIButton?
var delegate: StoryTableViewCellDelegate?
// MARK: Helpers
func configure(viewModel: StoryViewModel, unread: Bool) {
storyTitleLabel?.text = viewModel.title
storyTitleLabel?.textColor = (unread ? .black : .lightGray)
storyScoreLabel?.text = "↑\(viewModel.score)"
storySubmitDateLabel?.text = viewModel.fuzzyPostedAt
storyCommentsButton?.setTitle("\(viewModel.comments)", for: .normal)
storyCommentsButton?.alpha = (unread ? 1.0 : 0.5)
storyDomainLabel?.text = "(\(viewModel.urlDomain ?? "text"))"
}
// MARK: Actions
@IBAction func tappedCommentsButton() {
delegate?.tappedCommentsButton(inStoryTableViewCell: self)
}
}
| mit | 7d54df882e816e318319c064f604b652 | 31.311111 | 85 | 0.713205 | 4.630573 | false | false | false | false |
nikHowlett/WatchHealthMedicalDoctor | mobile/PreHealthViewController.swift | 1 | 5607 | //
// PreHealthViewController.swift
// mobile
//
// Created by MAC-ATL019922 on 6/25/15.
// Copyright (c) 2015 UCB+nikhowlett. All rights reserved.
//
import UIKit
import HealthKit
class PreHealthViewController: UIViewController {
let healthStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
authorizeHealthKit { (authorized, error) -> Void in
if authorized {
print("HealthKit authorization received.")
self.performSegueWithIdentifier("heartRateDisplay", sender: self)
}
else {
print("HealthKit authorization denied!")
if error != nil {
print("\(error)")
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "heartRateDisplay" {
if let happinessViewController = segue.destinationViewController as? SleepAndHeartsViewController {
happinessViewController.healthStore = healthStore
}
}
}
func autorizationComplete(success: Bool, error: NSError?) -> Void {
if success {
print("HealthKit authorization received.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier("heartRateDisplay", sender: self)
})
} else {
print("HealthKit authorization denied!")
if error != nil {
print("\(error)")
}
}
}
let HK_Store = HKHealthStore()
let healthDataToWrite : Set<HKQuantityType> = Set()
let healthDatatoRead: Set<HKQuantityType> = Set(arrayLiteral: HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!)
var authorizationReceived : Bool = false
//MARK: Authorization
func authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!)
{
if !HKHealthStore.isHealthDataAvailable() {
authorizationReceived = false
let error = NSError(domain: "com.greci.MatthewGreci", code: 1, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available on this Device"])
if (completion != nil) {
completion(success:false, error:error)
}
return;
}
HK_Store.requestAuthorizationToShareTypes(healthDataToWrite, readTypes: healthDatatoRead) { (success, error) -> Void in
if (completion != nil) {
completion(success:success,error:error)
self.authorizationReceived = true
}
}
}
/*func authorizeHealthKit(completion: ((success: Bool, error:NSError!) -> Void)!) {
//let healthKitTypesToRead: [HKObjectType] = [HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)]
let healthkitTypesToRead = NSSet(array: [
// Each type we need access to is going to be an HKObjectType.
// Here is are getting the Sex, BloodType and StepCount information.
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex),
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType),
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount),
])
// 2. Set the types you want to write to HK Store
let healthKitTypesToWrite: [HKObjectType] = [
/*HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)*/
]
// 3. If the store is not available (for instance, iPad) return an error and don't go on.
if !HKHealthStore.isHealthDataAvailable() {
let error = NSError(domain: "han.ica.mad.HealthKitWorkshop", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
autorizationComplete(false, error:error)
return;
}
// 4. Request HealthKit authorization
/*SWIFT 2.0
func requestAuthorizationToShareTypes(_ typesToShare: Set<HKSampleType>?,
readTypes typesToRead: Set<HKObjectType>?,
completion completion: (Bool,
NSError?) -> Void)
healthStore.requestAuthorizationToShareTypes(nil,
readTypes: types,
completion: {succeeded, error in
if succeeded && error == nil{
dispatch_async(dispatch_get_main_queue(),
self.startObservingWeightChanges)
} else {
if let theError = error{
print("Error occurred = \(theError)")
}
}
})
*/
//healthStore.requestAuthorizationToShareTypes(Set(healthKitTypesToWrite), readTypes: Set(healthKitTypesToRead), completion: autorizationComplete)
healthStore.requestAuthorizationToShareTypes(nil, readTypes: Set(healthkitTypesToRead, completion: { (result: Bool, error: NSError?) -> Void in })
}
}*/
} | mit | 3d5cec9dc9860d2439a1136d0eb2ecc0 | 40.540741 | 168 | 0.583378 | 5.865063 | false | false | false | false |
yzhou65/DSWeibo | DSWeibo/Classes/Compose/EmoticonView/UITextView+Category.swift | 1 | 3513 | //
// UITextView+Category.swift
// 表情键盘界面布局
//
// Created by Yue on 9/16/16.
// Copyright © 2016 小码哥. All rights reserved.
//
import UIKit
extension UITextView {
func insertEmoticon(emoticon: Emoticon) {
//处理删除按钮
if emoticon.isRemoveButton {
deleteBackward()
}
//判断当前点击的是否是emoji表情
if emoticon.emojiStr != nil {
//以下代码有可能因为循环引用导致无法调用deinit。解决办法就是在闭包arg前加上[unowned self]修饰
self.replaceRange(self.selectedTextRange!, withText: emoticon.emojiStr!)
}
//判断当前点击的是否是表情图片
if emoticon.png != nil {
//创建表情字符串
let imageText = EmoticonTextAttachment.imageText(emoticon, font: font ?? UIFont.systemFontOfSize(17)) //直接使用TextView的font
//拿到当前所有的内容
let strM = NSMutableAttributedString(attributedString: self.attributedText)
//插入表情到当前光标所在的位置
let range = self.selectedRange //用户选中的Range
strM.replaceCharactersInRange(range, withAttributedString: imageText)
//属性字符串有自己默认的尺寸
strM.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(range.location, 1))
//将替换后的字符串赋值给UITextView
self.attributedText = strM
//回复光标所在的位置
//两个参数:第一个是指定光标所在的位置,第二个参数是选中文本的个数
self.selectedRange = NSMakeRange(range.location + 1, 0)
//注意:如果先输入的是默认表情(非emoji),不会触发textViewDidChange的监听方法,所以需要自己主动调用
//自己主动出发textViewDidChange方法
delegate?.textViewDidChange!(self)
}
}
/**
获取需要发送给服务器的字符串
*/
func emoticonAttributedText() -> String {
//需要发送给服务器的数据
var strM = String()
attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (objc, range, _) in
/*
//遍历的时候传递给我们的objc是一个字典。如果字典中的NSAttachment这个key有值,那么就证明当前是一个图片
print(objc["NSAttachment"])
// range就是纯字符串的范围
// 如果纯字符串中间有图片表情,那么range就会传递多次
print(range)
let res = (self.customTextView.text as NSString).substringWithRange(range)
print(res)
print("+++++++++++++++++++")
*/
// range就是纯字符串的范围
// 如果纯字符串中间有图片表情,那么range就会传递多次
if objc["NSAttachment"] != nil {
let attachment = objc["NSAttachment"] as! EmoticonTextAttachment
strM += attachment.chs!
}
else {
//文字
strM += (self.text as NSString).substringWithRange(range)
}
}
return strM
}
}
| apache-2.0 | 3ba27a51d9a463b33635f7e4006c3cb0 | 31.917647 | 170 | 0.566833 | 4.624793 | false | false | false | false |
mozilla-mobile/focus-ios | Blockzilla/UIComponents/BrowserToolset.swift | 1 | 5299 | /* 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 CoreGraphics
protocol BrowserToolsetDelegate: AnyObject {
func browserToolsetDidPressBack(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressForward(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressReload(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressStop(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressDelete(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressContextMenu(_ browserToolbar: BrowserToolset, menuButton: InsetButton)
}
class BrowserToolset {
weak var delegate: BrowserToolsetDelegate?
let backButton = InsetButton()
let forwardButton = InsetButton()
let stopReloadButton = InsetButton()
let deleteButton = InsetButton()
let contextMenuButton = InsetButton()
init() {
backButton.setImage(#imageLiteral(resourceName: "icon_back_active"), for: .normal)
backButton.addTarget(self, action: #selector(didPressBack), for: .touchUpInside)
backButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
backButton.accessibilityLabel = UIConstants.strings.browserBack
backButton.isEnabled = false
forwardButton.setImage(#imageLiteral(resourceName: "icon_forward_active"), for: .normal)
forwardButton.addTarget(self, action: #selector(didPressForward), for: .touchUpInside)
forwardButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
forwardButton.accessibilityLabel = UIConstants.strings.browserForward
forwardButton.isEnabled = false
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_refresh_menu"), for: .normal)
stopReloadButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
stopReloadButton.addTarget(self, action: #selector(didPressStopReload), for: .touchUpInside)
stopReloadButton.accessibilityIdentifier = "BrowserToolset.stopReloadButton"
deleteButton.setImage(#imageLiteral(resourceName: "icon_delete"), for: .normal)
deleteButton.addTarget(self, action: #selector(didPressDelete), for: .touchUpInside)
deleteButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
deleteButton.accessibilityIdentifier = "URLBar.deleteButton"
deleteButton.isEnabled = false
contextMenuButton.setImage(UIImage(named: "icon_hamburger_menu"), for: .normal)
contextMenuButton.tintColor = .primaryText
if #available(iOS 14.0, *) {
contextMenuButton.showsMenuAsPrimaryAction = true
contextMenuButton.menu = UIMenu(children: [])
contextMenuButton.addTarget(self, action: #selector(didPressContextMenu), for: .menuActionTriggered)
} else {
contextMenuButton.addTarget(self, action: #selector(didPressContextMenu), for: .touchUpInside)
}
contextMenuButton.accessibilityLabel = UIConstants.strings.browserSettings
contextMenuButton.accessibilityIdentifier = "HomeView.settingsButton"
contextMenuButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
contextMenuButton.imageView?.snp.makeConstraints { $0.size.equalTo(UIConstants.layout.contextMenuIconSize) }
}
var canGoBack: Bool = false {
didSet {
backButton.isEnabled = canGoBack
backButton.alpha = canGoBack ? 1 : UIConstants.layout.browserToolbarDisabledOpacity
}
}
var canGoForward: Bool = false {
didSet {
forwardButton.isEnabled = canGoForward
forwardButton.alpha = canGoForward ? 1 : UIConstants.layout.browserToolbarDisabledOpacity
}
}
var isLoading: Bool = false {
didSet {
if isLoading {
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_stop_menu"), for: .normal)
stopReloadButton.accessibilityLabel = UIConstants.strings.browserStop
} else {
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_refresh_menu"), for: .normal)
stopReloadButton.accessibilityLabel = UIConstants.strings.browserReload
}
}
}
var canDelete: Bool = false {
didSet {
deleteButton.isEnabled = canDelete
deleteButton.alpha = canDelete ? 1 : UIConstants.layout.browserToolbarDisabledOpacity
}
}
@objc private func didPressBack() {
delegate?.browserToolsetDidPressBack(self)
}
@objc private func didPressForward() {
delegate?.browserToolsetDidPressForward(self)
}
@objc private func didPressStopReload() {
if isLoading {
delegate?.browserToolsetDidPressStop(self)
} else {
delegate?.browserToolsetDidPressReload(self)
}
}
@objc func didPressDelete() {
if canDelete {
delegate?.browserToolsetDidPressDelete(self)
}
}
@objc private func didPressContextMenu(_ sender: InsetButton) {
delegate?.browserToolsetDidPressContextMenu(self, menuButton: sender)
}
}
| mpl-2.0 | 6f666592a8bdc22a4813d1b5eed88506 | 41.733871 | 116 | 0.705982 | 5.215551 | false | false | false | false |
CartoDB/mobile-ios-samples | HelloMap.Swift/HelloMap.Swift/ViewController.swift | 1 | 3920 | //
// ViewController.swift
// HelloMap.Swift
//
// Created by Aare Undo on 22/09/16.
// Copyright © 2016 Aare Undo. All rights reserved.
//
import UIKit
import CartoMobileSDK
class ViewController: UIViewController {
var mapView: NTMapView?
override func viewDidLoad() {
super.viewDidLoad()
// Miminal sample code follows
title = "Hello Map"
// Create NTMapView
mapView = NTMapView()
view = mapView
// Set common options. Use EPSG4326 projection so that longitude/latitude can be directly used for coordinates.
let proj = NTEPSG4326()
mapView?.getOptions()?.setBaseProjection(proj)
mapView?.getOptions()?.setRenderProjectionMode(NTRenderProjectionMode.RENDER_PROJECTION_MODE_SPHERICAL)
mapView?.getOptions()?.setZoomGestures(true)
// Create base map layer
let baseLayer = NTCartoOnlineVectorTileLayer(style: NTCartoBaseMapStyle.CARTO_BASEMAP_STYLE_VOYAGER)
mapView?.getLayers().add(baseLayer)
// Create map position located at Tallinn, Estonia
let tallinn = NTMapPos(x: 24.646469, y: 59.426939)
// Animate map to Tallinn, Estonia
mapView?.setFocus(tallinn, durationSeconds: 0)
mapView?.setRotation(0, durationSeconds: 0)
mapView?.setZoom(3, durationSeconds: 0)
mapView?.setZoom(4, durationSeconds: 2)
// Initialize a local vector data source
let vectorDataSource = NTLocalVectorDataSource(projection: proj)
// Initialize a vector layer with the created data source
let vectorLayer = NTVectorLayer(dataSource: vectorDataSource)
// Add the created layer to the map
mapView?.getLayers().add(vectorLayer)
// Create a marker marker style
let markerStyleBuilder = NTMarkerStyleBuilder()
markerStyleBuilder?.setSize(15)
markerStyleBuilder?.setColor(NTColor(r: 0, g: 255, b: 0, a: 255))
let markerStyle = markerStyleBuilder?.buildStyle()
// Create a marker with the previously defined style and add it to the data source
let marker = NTMarker(pos: tallinn, style: markerStyle)
vectorDataSource?.add(marker)
// Create a map listener so that we will receive click events on a map
let listener = HelloMapListener(vectorDataSource: vectorDataSource!)
mapView?.setMapEventListener(listener)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Disconnect listener from the mapView to avoid leaks
let mapView = view as! NTMapView
mapView.setMapEventListener(nil)
}
}
public class HelloMapListener : NTMapEventListener {
var vectorDataSource: NTLocalVectorDataSource!
convenience init(vectorDataSource: NTLocalVectorDataSource!) {
self.init()
self.vectorDataSource = vectorDataSource
}
override public func onMapClicked(_ mapClickInfo: NTMapClickInfo!) {
// Create a new marker with random style at the clicked location
let markerStyleBuilder = NTMarkerStyleBuilder()
let size = Float(arc4random_uniform(20) + 10)
markerStyleBuilder?.setSize(size)
var colors = [
NTColor(r: 255, g: 255, b: 255, a: 255),
NTColor(r: 0, g: 0, b: 255, a: 255),
NTColor(r: 255, g: 0, b: 0, a: 255),
NTColor(r: 0, g: 255, b: 0, a: 255),
NTColor(r: 0, g: 200, b: 0, a: 255),
]
let color = colors[Int(arc4random_uniform(4))]
markerStyleBuilder?.setColor(color)
let markerStyle = markerStyleBuilder?.buildStyle()
let marker = NTMarker(pos: mapClickInfo.getClickPos(), style: markerStyle)
self.vectorDataSource.add(marker)
}
}
| bsd-2-clause | 88e4817ca48f94a91281c17b3a5a3ed8 | 35.287037 | 119 | 0.640725 | 4.325607 | false | false | false | false |
AngryLi/note-iOS | iOS/Demos/SpotlightDemo/SpotlightDemo/SupportSpotlightDelagete.swift | 3 | 2286 | //
// SupportSpotlightDelagete.swift
// SpotlightDemo
//
// Created by 李亚洲 on 16/3/31.
// Copyright © 2016年 angryli. All rights reserved.
//
import UIKit
import CoreSpotlight
@objc protocol SupportSpotlightDelagete {
optional func p_supportSpotlight( uniqueIdentifier : String, titles : [String], descriptions : [String], thumbnails : [UIImage]?) throws
}
enum Error : ErrorType {
case Titles_Descriptions(description : String)
case Thumbnails(description : String)
}
extension SupportSpotlightDelagete {
func p_supportSpotlight( uniqueIdentifier : String, titles : [String], descriptions : [String], thumbnails : [UIImage]?) throws {
guard titles.count == descriptions.count else {
throw Error.Titles_Descriptions(description: "标题数和描述数目不同")
}
guard thumbnails == nil && thumbnails!.count < titles.count else {
throw Error.Thumbnails(description: "缩略图不得少于标题数")
}
//创建SearchableItems的数组
var searchableItems = [CSSearchableItem]()
for i in 0..<titles.count {
//1.创建条目的属性集合
let attributeSet = CSSearchableItemAttributeSet(itemContentType: "image")
//2.给属性集合添加属性
attributeSet.title = titles[i];
attributeSet.contentDescription = descriptions[i] + titles[i]
attributeSet.thumbnailData = (thumbnails == nil) ? nil : UIImagePNGRepresentation(thumbnails![i])
//3.属性集合与条目进行关联
let searchableItem = CSSearchableItem(uniqueIdentifier: String(i + 1), domainIdentifier: uniqueIdentifier, attributeSet: attributeSet)
//把该条目进行暂存
searchableItems.append(searchableItem)
}
//4.吧条目数组与索引进行关联
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems, completionHandler: { (error1 : NSError?) in
if let error = error1 {
print(#function + error.localizedDescription)
}
defer {
print("完成")
}
})
}
}
| mit | e546399b322ba5fb4fc8123ead8c784c | 33.274194 | 146 | 0.620706 | 4.589633 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/WMTS layer/WMTSLayerViewController.swift | 1 | 2245 | // Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class WMTSLayerViewController: UIViewController {
@IBOutlet private weak var mapView: AGSMapView!
private var map: AGSMap!
private var wmtsService: AGSWMTSService!
private let wmtsServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS")!
override func viewDidLoad() {
super.viewDidLoad()
// initialize the map
self.map = AGSMap()
// assign the map to the map view
self.mapView.map = self.map
// create a WMTS service with the service URL
self.wmtsService = AGSWMTSService(url: wmtsServiceURL)
// load the WMTS service to access the service information
self.wmtsService.load { [weak self] (error) in
guard let self = self else { return }
if let error = error {
self.presentAlert(message: "Failed to load WMTS layer: \(error.localizedDescription)")
} else if let layerInfo = self.wmtsService.serviceInfo?.layerInfos.first {
// Create a WMTS layer using the first element in the collection
// of WMTS layer info objects.
let wmtsLayer = AGSWMTSLayer(layerInfo: layerInfo)
// Set the basemap of the map with WMTS layer.
self.map.basemap = AGSBasemap(baseLayer: wmtsLayer)
}
}
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["WMTSLayerViewController"]
}
}
| apache-2.0 | b14dc5155b19796d78e5b8a5ea1a086f | 39.818182 | 138 | 0.660579 | 4.436759 | false | false | false | false |
yaslab/CSV.swift | Tests/CSVTests/LineBreakTests.swift | 1 | 3922 | //
// LineBreakTests.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/11.
// Copyright © 2016 yaslab. All rights reserved.
//
import XCTest
@testable import CSV
class LineBreakTests: XCTestCase {
func testLF() {
let csv = "abab,cdcd,efef\nzxcv,asdf,qwer"
let records = parse(csv: csv)
XCTAssertEqual(records[0], ["abab", "cdcd", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qwer"])
}
func testCRLF() {
let csv = "abab,cdcd,efef\r\nzxcv,asdf,qwer"
let records = parse(csv: csv)
XCTAssertEqual(records[0], ["abab", "cdcd", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qwer"])
}
func testLastCR() {
let csv = "abab,,cdcd,efef\r\nzxcv,asdf,\"qw\"\"er\",\r"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["abab", "", "cdcd", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qw\"er", ""])
}
func testLastCRLF() {
let csv = "abab,,cdcd,efef\r\nzxcv,asdf,\"qw\"\"er\",\r\n"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["abab", "", "cdcd", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qw\"er", ""])
}
func testLastLF() {
let csv = "abab,,cdcd,efef\r\nzxcv,asdf,\"qw\"\"er\",\n"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["abab", "", "cdcd", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qw\"er", ""])
}
func testLFInQuotationMarks() {
let csv = "abab,,\"\rcdcd\n\",efef\r\nzxcv,asdf,\"qw\"\"er\",\n"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["abab", "", "\rcdcd\n", "efef"])
XCTAssertEqual(records[1], ["zxcv", "asdf", "qw\"er", ""])
}
func testLineBreakLF() {
let csv = "qwe,asd\nzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], ["zxc", "rty"])
}
func testLineBreakCR() {
let csv = "qwe,asd\rzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], ["zxc", "rty"])
}
func testLineBreakCRLF() {
let csv = "qwe,asd\r\nzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 2)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], ["zxc", "rty"])
}
func testLineBreakLFLF() {
let csv = "qwe,asd\n\nzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 3)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], [""])
XCTAssertEqual(records[2], ["zxc", "rty"])
}
func testLineBreakCRCR() {
let csv = "qwe,asd\r\rzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 3)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], [""])
XCTAssertEqual(records[2], ["zxc", "rty"])
}
func testLineBreakCRLFCRLF() {
let csv = "qwe,asd\r\n\r\nzxc,rty"
let records = parse(csv: csv)
XCTAssertEqual(records.count, 3)
XCTAssertEqual(records[0], ["qwe", "asd"])
XCTAssertEqual(records[1], [""])
XCTAssertEqual(records[2], ["zxc", "rty"])
}
private func parse(csv: String) -> [[String]] {
let reader = try! CSVReader(string: csv)
return reader.map { $0 }
// var records = [[String]]()
// try! reader.enumerateRows { (row, _, _) in
// records.append(row)
// }
// return records
}
}
| mit | 41df5994758467a1abc2185173ef90ad | 31.404959 | 72 | 0.552665 | 3.43345 | false | true | false | false |
GirAppe/BTracker | Sources/Classes/Value.swift | 1 | 1063 | //
// Copyright © 2017 GirAppe Studio. All rights reserved.
//
import Foundation
public enum Value<T:Equatable>: Equatable {
case any
case some(T)
}
public protocol AnyValueEquatable: Equatable {
associatedtype ValueType: Equatable
func value() -> ValueType?
}
extension Value: AnyValueEquatable {
public typealias ValueType = T
public func value() -> ValueType? {
switch self {
case let .some(value): return value
default: return nil
}
}
}
extension AnyValueEquatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
guard let lhs = lhs.value() else { return true }
guard let rhs = rhs.value() else { return true }
return lhs == rhs
}
public static func == (lhs: Self, rhs: ValueType) -> Bool {
guard let lhs = lhs.value() else { return true }
return lhs == rhs
}
public static func == (lhs: ValueType, rhs: Self) -> Bool {
guard let rhs = rhs.value() else { return true }
return lhs == rhs
}
}
| mit | 531043e5a8795785a3330364ab7076a2 | 22.6 | 63 | 0.600753 | 4.164706 | false | false | false | false |
fuku2014/quizpencil | CreatedQuizListViewController.swift | 1 | 4799 | /**
CreatedQuizListViewController
作成済みクイズ一覧を表示させる画面
- Author: fuku
- Copyright: Copyright (c) 2016 fuku. All rights reserved.
- Date: 2016/6/18
- Version: 2.0
*/
import UIKit
import RealmSwift
class CreatedQuizListViewController: BaseTableViewController {
var collection: Results<Quiz>!
var selectedQuiz: Quiz?
/**
viewWillAppear
*/
override func viewWillAppear(animated: Bool) {
fetchQuizList()
}
/**
fetchQuizList
*/
func fetchQuizList() {
let realm = try! Realm()
collection = realm.objects(Quiz).filter("isDownload = false")
self.tableView.reloadData()
}
/**
numberOfSectionsInTableView
*/
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
/**
numberOfRowsInSection
*/
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return collection.count
}
/**
cellForRowAtIndexPath
*/
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("quizList", forIndexPath: indexPath)
cell.textLabel?.textAlignment = NSTextAlignment.Left
cell.textLabel?.font = UIFont.systemFontOfSize(17)
cell.detailTextLabel?.textColor = UIColor.darkGrayColor()
cell.detailTextLabel?.textAlignment = NSTextAlignment.Left
cell.detailTextLabel?.font = UIFont.systemFontOfSize(11)
cell.backgroundColor = UIColor.whiteColor()
let model = collection[indexPath.row]
cell.textLabel?.text = model.name
cell.detailTextLabel?.text = model.context
return cell
}
/**
didSelectRowAtIndexPath
*/
override func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
selectedQuiz = collection[indexPath.row]
if selectedQuiz != nil {
performSegueWithIdentifier("showQuestions", sender: nil)
}
}
/**
prepareForSegue
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "showQuestions") {
let cqlvc: CreatedQuestionListViewController = (segue.destinationViewController as? CreatedQuestionListViewController)!
cqlvc.selectedQuiz = selectedQuiz
}
}
/**
canEditRowAtIndexPath
*/
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
/**
commitEditingStyle
*/
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let model = collection[indexPath.row]
if model.isUpload {
let dialog: UIAlertController = UIAlertController(title: model.name, message: "このクイズは公開済みのため削除できません。削除する前に「クイズ公開画面」より公開中止を実施してください", preferredStyle: UIAlertControllerStyle.Alert)
// OK
let okAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
return
})
dialog.addAction(okAction)
self.presentViewController(dialog, animated: true, completion: nil)
return
}
let dialog: UIAlertController = UIAlertController(title: model.name, message: "クイズを削除してもよろしいですか?", preferredStyle: UIAlertControllerStyle.ActionSheet)
// OK
let okAction: UIAlertAction = UIAlertAction(title: "はい", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
model.remove {
self.fetchQuizList()
}
})
// キャンセル
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.Cancel, handler:{
(action: UIAlertAction!) -> Void in
return
})
dialog.addAction(okAction)
dialog.addAction(cancelAction)
presentViewController(dialog, animated: true, completion: nil)
}
}
}
| apache-2.0 | b262dd99970bf21ae9e8e99dfc5c5df4 | 32.613139 | 195 | 0.613898 | 5.424028 | false | false | false | false |
zhangjk4859/MyWeiBoProject | sinaWeibo/sinaWeibo/Classes/Compose/照片选择器/JKPhotoSelectorVC.swift | 1 | 7351 | //
// JKPhotoSelectorVC.swift
// sinaWeibo
//
// Created by 张俊凯 on 16/7/27.
// Copyright © 2016年 张俊凯. All rights reserved.
//
import UIKit
private let JKPhotoSelectorCellReuseIdentifier = "JKPhotoSelectorCellReuseIdentifier"
class JKPhotoSelectorVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//设置子视图
setupUI()
}
private func setupUI()
{
// 添加子控件
view.addSubview(collcetionView)
// 布局子控件
collcetionView.translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collcetionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collcetionView": collcetionView])
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collcetionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collcetionView": collcetionView])
view.addConstraints(cons)
}
// MARK: - 懒加载
private lazy var collcetionView: UICollectionView = {
let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoSelectorViewLayout())
clv.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: JKPhotoSelectorCellReuseIdentifier)
clv.dataSource = self
return clv
}()
lazy var pictureImages = [UIImage]()
}
extension JKPhotoSelectorVC: UICollectionViewDataSource, PhotoSelectorCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pictureImages.count + 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collcetionView.dequeueReusableCellWithReuseIdentifier(JKPhotoSelectorCellReuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
cell.PhotoCellDelegate = self
cell.backgroundColor = UIColor.greenColor()
cell.image = (pictureImages.count == indexPath.item) ? nil : pictureImages[indexPath.item] // 0 1
return cell
}
func photoDidAddSelector(cell: PhotoSelectorCell) {
// 1.判断能否打开照片库
if !UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.PhotoLibrary)
{
print("不能打开相册")
return
}
// 2.创建图片选择器
let vc = UIImagePickerController()
vc.delegate = self
presentViewController(vc, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
print(image)
let newImage = image.imageWithScale(300)
// 1.将当前选中的图片添加到数组中
pictureImages.append(newImage)
collcetionView.reloadData()
// 关闭图片选择器
picker.dismissViewControllerAnimated(true, completion: nil)
}
func photoDidRemoveSelector(cell: PhotoSelectorCell) {
// 1.从数组中移除"当前点击"的图片
let indexPath = collcetionView.indexPathForCell(cell)
pictureImages.removeAtIndex(indexPath!.item)
// 2.刷新表格
collcetionView.reloadData()
}
}
@objc
protocol PhotoSelectorCellDelegate : NSObjectProtocol
{
optional func photoDidAddSelector(cell: PhotoSelectorCell)
optional func photoDidRemoveSelector(cell: PhotoSelectorCell)
}
class PhotoSelectorCell: UICollectionViewCell {
weak var PhotoCellDelegate: PhotoSelectorCellDelegate?
var image: UIImage?
{
didSet{
if image != nil{
removeButton.hidden = false
addButton.setBackgroundImage(image!, forState: UIControlState.Normal)
addButton.userInteractionEnabled = false
}else
{
removeButton.hidden = true
addButton.userInteractionEnabled = true
addButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI()
{
// 1.添加子控件
contentView.addSubview(addButton)
contentView.addSubview(removeButton)
// 2.布局子控件
addButton.translatesAutoresizingMaskIntoConstraints = false
removeButton.translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton])
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton])
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[removeButton]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton])
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-2-[removeButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton])
contentView.addConstraints(cons)
}
// MARK: - 懒加载
private lazy var removeButton: UIButton = {
let btn = UIButton()
btn.hidden = true
btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(PhotoSelectorCell.removeBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
private lazy var addButton: UIButton = {
let btn = UIButton()
btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
btn.addTarget(self, action: #selector(PhotoSelectorCell.addBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
func addBtnClick()
{
PhotoCellDelegate?.photoDidAddSelector!(self)
}
func removeBtnClick()
{
PhotoCellDelegate?.photoDidRemoveSelector!(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class PhotoSelectorViewLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
itemSize = CGSize(width: 80, height: 80)
minimumInteritemSpacing = 10
minimumLineSpacing = 10
sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
}
| mit | 4b62290e8b907974920934901d634848 | 32.586854 | 194 | 0.655577 | 5.469419 | false | false | false | false |
kaltura/playkit-ios | Classes/Events/InterceptorEvent.swift | 1 | 2622 | // ===================================================================================================
// Copyright (C) 2021 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
//
// InterceptorEvent.swift
// PlayKit
//
// Created by Sergey Chausov on 07.07.2021.
//
import Foundation
/// InterceptorEvent is a class that is used to reflect specific PKMediaEntryInterceptor events.
@objc public class InterceptorEvent: PKEvent {
@objc public static let allEventTypes: [InterceptorEvent.Type] = [
cdnSwitched,
sourceUrlSwitched
]
// MARK: - Interceptor Events Static References.
/// Sent by SmartSwitch interceptor plugin, when the playback URL changed with attached CDN code.
/// Currently used by Youbora contentCdn options.
@objc public static let cdnSwitched: InterceptorEvent.Type = CDNSwitched.self
public class CDNSwitched: InterceptorEvent {
public convenience init(cdnCode: String) {
self.init([InterceptorEventDataKeys.cdnCode: cdnCode])
}
}
// Can be sent by any interceptor plugin, when the playback URL is changed with updated url.
@objc public static let sourceUrlSwitched: InterceptorEvent.Type = SourceUrlSwitched.self
public class SourceUrlSwitched: InterceptorEvent {
public convenience init(originalUrl: String, updatedUrl: String) {
self.init([InterceptorEventDataKeys.originalUrl: originalUrl, InterceptorEventDataKeys.updatedUrl: updatedUrl])
}
}
}
@objc public class InterceptorEventDataKeys: NSObject {
public static let cdnCode = "CDNCode"
public static let originalUrl = "OriginalUrl"
public static let updatedUrl = "UpdatedUrl"
}
// MARK: - CDNSwitched
extension PKEvent {
/// CDN code provided by plugins (SmartSwitch)
@objc public var cdnCode: String? {
return self.data?[InterceptorEventDataKeys.cdnCode] as? String
}
}
// MARK: - SourceUrlSwitched
extension PKEvent {
/// SourceUrlSwitched values provided by interceptor plugins
@objc public var originalUrl: String? {
return self.data?[InterceptorEventDataKeys.originalUrl] as? String
}
@objc public var updatedUrl: String? {
return self.data?[InterceptorEventDataKeys.updatedUrl] as? String
}
}
| agpl-3.0 | fb10c2ccc85b489583a3624d0700099a | 33.051948 | 123 | 0.650648 | 4.624339 | false | false | false | false |
danger/danger-swift | Sources/Runner/Commands/RunDangerJS.swift | 1 | 2557 | import Foundation
import Logger
import RunnerLib
func runDangerJSCommandToRunDangerSwift(_ command: DangerCommand, logger: Logger) throws -> Int32 {
guard let dangerJS = try? getDangerCommandPath(logger: logger) else {
logger.logError("Danger JS was not found on the system",
"Please install it with npm or brew",
separator: "\n")
exit(1)
}
let dangerJSVersion = DangerJSVersionFinder.findDangerJSVersion(dangerJSPath: dangerJS)
guard dangerJSVersion.compare(MinimumDangerJSVersion, options: .numeric) != .orderedAscending else {
logger.logError("The installed danger-js version is below the minimum supported version",
"Current version = \(dangerJSVersion)",
"Minimum supported version = \(MinimumDangerJSVersion)",
separator: "\n")
exit(1)
}
let proc = Process()
proc.environment = ProcessInfo.processInfo.environment
proc.launchPath = dangerJS
let dangerOptionsIndexes = DangerSwiftOption.allCases
.compactMap { option -> (DangerSwiftOption, Int)? in
if let index = CommandLine.arguments.firstIndex(of: option.rawValue) {
return (option, index)
} else {
return nil
}
}
let unusedArgs = CommandLine.arguments.enumerated().compactMap { index, arg -> String? in
if dangerOptionsIndexes.contains(where: { index == $0.1 || ($0.0.hasParameter && index == $0.1 + 1) }) {
return nil
}
if arg.contains("danger-swift") || arg == command.rawValue {
return nil
}
return arg
}
var dangerSwiftCommand = "danger-swift"
// Special-case running inside the danger dev dir
let fileManager = FileManager.default
if fileManager.fileExists(atPath: ".build/debug/danger-swift") {
dangerSwiftCommand = ".build/debug/danger-swift"
} else if let firstArg = CommandLine.arguments.first,
fileManager.fileExists(atPath: firstArg) {
dangerSwiftCommand = firstArg
}
proc.arguments = [command.rawValue, "--process", dangerSwiftCommand, "--passURLForDSL"] + unusedArgs
let standardOutput = FileHandle.standardOutput
proc.standardOutput = standardOutput
proc.standardError = standardOutput
logger.debug("Running: \(proc.launchPath!) \(proc.arguments!.joined(separator: " ")) ")
proc.launch()
proc.waitUntilExit()
return proc.terminationStatus
}
| mit | ddde452aeb13bd7bba5ab7449a90e028 | 36.057971 | 112 | 0.640203 | 4.717712 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Support/Data/DManager.swift | 1 | 5477 | import Foundation
import CoreData
class DManager
{
static let sharedInstance:DManager? = DManager()
private let managedObjectContext:NSManagedObjectContext
private let kModelName:String = "DMiniMancera"
private let kModelExtension:String = "momd"
private let kSQLiteExtension:String = ".sqlite"
private init?()
{
let sqliteFile:String = "\(kModelName)\(kSQLiteExtension)"
let storeCoordinatorURL:URL = FileManager.appDirectory.appendingPathComponent(
sqliteFile)
guard
let modelURL:URL = Bundle.main.url(
forResource:kModelName,
withExtension:kModelExtension),
let managedObjectModel:NSManagedObjectModel = NSManagedObjectModel(
contentsOf:modelURL)
else
{
return nil
}
let persistentStoreCoordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(
managedObjectModel:managedObjectModel)
do
{
try persistentStoreCoordinator.addPersistentStore(
ofType:NSSQLiteStoreType,
configurationName:nil,
at:storeCoordinatorURL,
options:nil)
}
catch let error
{
#if DEBUG
print("coredata: \(error.localizedDescription)")
#endif
}
managedObjectContext = NSManagedObjectContext(
concurrencyType:
NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
}
//MARK: public
func save(completion:(() -> ())? = nil)
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
if self.managedObjectContext.hasChanges
{
self.managedObjectContext.perform
{
do
{
try self.managedObjectContext.save()
}
catch let error
{
#if DEBUG
print("CoreData: \(error.localizedDescription)")
#endif
}
completion?()
}
}
else
{
completion?()
}
}
}
func createData(
entityName:String,
completion:@escaping((NSManagedObject?) -> ()))
{
managedObjectContext.perform
{
if let entityDescription:NSEntityDescription = NSEntityDescription.entity(
forEntityName:entityName,
in:self.managedObjectContext)
{
let managedObject:NSManagedObject = NSManagedObject(
entity:entityDescription,
insertInto:self.managedObjectContext)
completion(managedObject)
}
else
{
completion(nil)
}
}
}
func createDataAndWait(entityName:String) -> NSManagedObject?
{
var managedObject:NSManagedObject?
managedObjectContext.performAndWait
{
if let entityDescription:NSEntityDescription = NSEntityDescription.entity(
forEntityName:entityName,
in:self.managedObjectContext)
{
managedObject = NSManagedObject(
entity:entityDescription,
insertInto:self.managedObjectContext)
}
}
return managedObject
}
func fetchData(
entityName:String,
limit:Int = 0,
predicate:NSPredicate? = nil,
sorters:[NSSortDescriptor]? = nil,
completion:@escaping(([NSManagedObject]?) -> ()))
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
let fetchRequest:NSFetchRequest<NSManagedObject> = NSFetchRequest(
entityName:entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sorters
fetchRequest.fetchLimit = limit
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.includesPropertyValues = true
fetchRequest.includesSubentities = true
self.managedObjectContext.perform
{
let results:[NSManagedObject]?
do
{
results = try self.managedObjectContext.fetch(fetchRequest)
}
catch
{
results = nil
}
completion(results)
}
}
}
func delete(data:NSManagedObject, completion:(() -> ())? = nil)
{
managedObjectContext.perform
{
self.managedObjectContext.delete(data)
completion?()
}
}
func deleteAndWait(data:NSManagedObject)
{
managedObjectContext.performAndWait
{
self.managedObjectContext.delete(data)
}
}
}
| mit | 4c94129bddb7c31897c356bc72ab3ffd | 28.766304 | 99 | 0.516158 | 7.048906 | false | false | false | false |
leftdal/youslow | iOS/YouTubeView/YTPlayerEnumerations.swift | 1 | 1050 | //
// YTPlayerEnumerations.swift
// Demo
//
// Created by to0 on 2/1/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import Foundation
enum YTPlayerState: String {
case Unstarted = "-1"
case Ended = "0"
case Playing = "1"
case Paused = "2"
case Buffering = "3"
case Cued = "5"
case Unknown = "unknown"
}
enum YTPlayerQuality: String {
case Small = "small"
case Medium = "medium"
case Large = "large"
case HD720 = "hd720"
case HD1080 = "hd1080"
case HighRes = "highres"
case Auto = "auto"
case Default = "default"
case Unknown = "unknown"
}
enum YTPlayerError: String {
case InvalidParam = "2"
case HTML5 = "5"
case VideoNotFound = "100"
case NotEmbeddable = "101"
case CannotFindVideo = "105"
}
enum YTPlayerCallback: String {
case OnReady = "onReady"
case OnStateChange = "onStateChange"
case OnPlaybackQualityChange = "onPlaybackQualityChange"
case OnError = "onError"
case OnYouTubeIframeAPIReady = "onYouTubeIframeAPIReady"
} | gpl-3.0 | 9ab5ff76093f2acf6141e017f1f406d6 | 20.895833 | 60 | 0.644762 | 3.398058 | false | false | false | false |
ZB0106/MCSXY | MCSXY/MCSXY/Bussniess/Home/Cotrollers/MCHomeController.swift | 1 | 1600 | //
// MCHomeController.swift
// MCSXY
//
// Created by 瞄财网 on 2017/6/19.
// Copyright © 2017年 瞄财网. All rights reserved.
//
import UIKit
class MCHomeController: MCViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel.init()
label.text = "ceshishsishfsioafjaofjaojfoajfajf"
label.frame = CGRect.init(x: 40, y: 200, width: 150, height: 150)
label.backgroundColor = UIColor.clear
self.view .addSubview(label)
let ceshi = UIView.init()
ceshi.backgroundColor = UIColor.red
ceshi.frame = CGRect.init(x: 40, y: 40, width: 150, height: 150)
self.view .addSubview(ceshi)
let iconView = UIImageView.init()
iconView.backgroundColor = UIColor.blue
iconView.frame = CGRect.init(x: 40, y: 360, width: 150, height: 150)
self.view .addSubview(iconView)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | b3248f5cc7b5df637a611c3ab740f006 | 25.864407 | 106 | 0.610095 | 4.24933 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Register/RegisterPickAvatarViewController.swift | 1 | 4843 |
// RegisterPickAvatarViewController.swift
// Yep
//
// Created by NIX on 15/3/18.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import AVFoundation
import YepKit
import YepNetworking
import Proposer
import Navi
import RxSwift
import RxCocoa
final class RegisterPickAvatarViewController: SegueViewController {
private lazy var disposeBag = DisposeBag()
@IBOutlet private weak var avatarImageView: UIImageView!
@IBOutlet private weak var cameraPreviewView: CameraPreviewView!
@IBOutlet private weak var openCameraButton: BorderButton!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = NSLocalizedString("Next", comment: "")
button.enabled = false
button.rx_tap
.subscribeNext({ [weak self] in self?.uploadAvatarAndGotoPickSkills() })
.addDisposableTo(self.disposeBag)
return button
}()
private var avatar = UIImage() {
willSet {
avatarImageView.image = newValue
}
}
private enum PickAvatarState {
case Default
case Captured
}
private var pickAvatarState: PickAvatarState = .Default {
willSet {
switch newValue {
case .Default:
cameraPreviewView.hidden = true
avatarImageView.hidden = false
avatarImageView.image = UIImage.yep_defaultAvatar
nextButton.enabled = false
case .Captured:
cameraPreviewView.hidden = true
avatarImageView.hidden = false
nextButton.enabled = true
}
}
}
deinit {
println("deinit RegisterPickAvatar")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: ""))
navigationItem.rightBarButtonItem = nextButton
navigationItem.hidesBackButton = true
view.backgroundColor = UIColor.whiteColor()
pickAvatarState = .Default
openCameraButton.setTitle(String.trans_buttonChooseFromLibrary, forState: .Normal)
openCameraButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
openCameraButton.backgroundColor = UIColor.yepTintColor()
openCameraButton.rx_tap
.subscribeNext({ [weak self] in self?.openPhotoLibraryPicker() })
.addDisposableTo(disposeBag)
}
// MARK: Actions
private func openPhotoLibraryPicker() {
let openCameraRoll: ProposerAction = { [weak self] in
guard UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) else {
self?.alertCanNotAccessCameraRoll()
return
}
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
imagePicker.allowsEditing = true
self?.presentViewController(imagePicker, animated: true, completion: nil)
}
proposeToAccess(.Photos, agreed: openCameraRoll, rejected: { [weak self] in
self?.alertCanNotAccessCameraRoll()
})
}
private func uploadAvatarAndGotoPickSkills() {
YepHUD.showActivityIndicator()
let image = avatar.largestCenteredSquareImage().resizeToTargetSize(YepConfig.avatarMaxSize())
let imageData = UIImageJPEGRepresentation(image, Config.avatarCompressionQuality())
if let imageData = imageData {
updateAvatarWithImageData(imageData, failureHandler: { (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepHUD.hideActivityIndicator()
}, completion: { newAvatarURLString in
YepHUD.hideActivityIndicator()
SafeDispatch.async { [weak self] in
YepUserDefaults.avatarURLString.value = newAvatarURLString
self?.performSegueWithIdentifier("showRegisterPickSkills", sender: nil)
}
})
}
}
}
// MARK: UIImagePicker
extension RegisterPickAvatarViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
SafeDispatch.async { [weak self] in
self?.avatar = image
self?.pickAvatarState = .Captured
}
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | a5713d810e9cae1b65bff415ac1cf5bb | 28.882716 | 142 | 0.637885 | 5.81851 | false | false | false | false |
darkerk/v2ex | V2EX/ViewControllers/ProfileViewController.swift | 1 | 4801 | //
// ProfileViewController.swift
// V2EX
//
// Created by darker on 2017/3/14.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Moya
import PKHUD
class ProfileViewController: UITableViewController {
@IBOutlet weak var headerView: ProfileHeaderView!
lazy var menuItems = [(#imageLiteral(resourceName: "slide_menu_topic"), "个人"),
(#imageLiteral(resourceName: "slide_menu_message"), "消息"),
(#imageLiteral(resourceName: "slide_menu_favorite"), "收藏"),
(#imageLiteral(resourceName: "slide_menu_setting"), "设置")]
private let disposeBag = DisposeBag()
var navController: UINavigationController? {
return drawerViewController?.centerViewController as? UINavigationController
}
override func viewDidLoad() {
super.viewDidLoad()
AppStyle.shared.themeUpdateVariable.asObservable().subscribe(onNext: { update in
self.updateTheme()
if update {
self.headerView.updateTheme()
self.tableView.reloadData()
}
}).disposed(by: disposeBag)
tableView.delegate = nil
tableView.dataSource = nil
Account.shared.user.asObservable().bind(to: headerView.rx.user).disposed(by: disposeBag)
Account.shared.isLoggedIn.asObservable().subscribe(onNext: {isLoggedIn in
if !isLoggedIn {
self.headerView.logout()
}
}).disposed(by: disposeBag)
Observable.just(menuItems).bind(to: tableView.rx.items) { (tableView, row, item) in
let cell: ProfileMenuViewCell = tableView.dequeueReusableCell()
cell.updateTheme()
cell.configure(image: item.0, text: item.1)
return cell
}.disposed(by: disposeBag)
tableView.rx.itemSelected.subscribe(onNext: {[weak self] indexPath in
guard let `self` = self else { return }
self.tableView.deselectRow(at: indexPath, animated: true)
guard let nav = self.navController else {
return
}
guard Account.shared.isLoggedIn.value else {
self.showLoginView()
return
}
switch indexPath.row {
case 0:
self.drawerViewController?.isOpenDrawer = false
TimelineViewController.show(from: nav, user: Account.shared.user.value)
case 1:
if Account.shared.unreadCount.value > 0 {
Account.shared.unreadCount.value = 0
}
self.drawerViewController?.isOpenDrawer = false
nav.performSegue(withIdentifier: MessageViewController.segueId, sender: nil)
case 2:
self.drawerViewController?.isOpenDrawer = false
nav.performSegue(withIdentifier: FavoriteViewController.segueId, sender: nil)
case 3:
self.drawerViewController?.isOpenDrawer = false
nav.performSegue(withIdentifier: SettingViewController.segueId, sender: nil)
default: break
}
}).disposed(by: disposeBag)
if let cell = tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? ProfileMenuViewCell {
Account.shared.unreadCount.asObservable().bind(to: cell.rx.unread).disposed(by: disposeBag)
}
Account.shared.isDailyRewards.asObservable().flatMapLatest { canRedeem -> Observable<Bool> in
if canRedeem {
return Account.shared.redeemDailyRewards()
}
return Observable.just(false)
}.share(replay: 1).delay(1, scheduler: MainScheduler.instance).subscribe(onNext: { success in
if success {
HUD.showText("已领取每日登录奖励!")
Account.shared.isDailyRewards.value = false
}
}, onError: { error in
print(error.message)
}).disposed(by: disposeBag)
}
@IBAction func loginButtonAction(_ sender: Any) {
if let nav = navController, Account.shared.isLoggedIn.value {
drawerViewController?.isOpenDrawer = false
TimelineViewController.show(from: nav, user: Account.shared.user.value)
}else {
showLoginView()
}
}
func showLoginView() {
drawerViewController?.performSegue(withIdentifier: LoginViewController.segueId, sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | e41a6542bb6e984fa1a60af34b0f35ca | 36.496063 | 105 | 0.597648 | 5.131466 | false | false | false | false |
devincoughlin/swift | test/stmt/foreach.swift | 1 | 6741 | // RUN: %target-typecheck-verify-swift
// Bad containers and ranges
struct BadContainer1 {
}
func bad_containers_1(bc: BadContainer1) {
for e in bc { } // expected-error{{type 'BadContainer1' does not conform to protocol 'Sequence'}}
// expected-error@-1{{variable 'e' is not bound by any pattern}}
}
struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}}
var generate : Int
}
func bad_containers_2(bc: BadContainer2) {
for e in bc { }
// expected-error@-1{{variable 'e' is not bound by any pattern}}
}
struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}}
func makeIterator() { } // expected-note{{candidate can not infer 'Iterator' = '()' because '()' is not a nominal type and so can't conform to 'IteratorProtocol'}}
}
func bad_containers_3(bc: BadContainer3) {
for e in bc { }
// expected-error@-1{{variable 'e' is not bound by any pattern}}
}
struct BadIterator1 {}
struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}} expected-note 2 {{do you want to add protocol stubs?}}
typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'BadContainer4.Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}}
func makeIterator() -> BadIterator1 { }
}
func bad_containers_4(bc: BadContainer4) {
for e in bc { }
// expected-error@-1{{variable 'e' is not bound by any pattern}}
}
// Pattern type-checking
struct GoodRange<Int> : Sequence, IteratorProtocol {
typealias Element = Int
func next() -> Int? {}
typealias Iterator = GoodRange<Int>
func makeIterator() -> GoodRange<Int> { return self }
}
struct GoodTupleIterator: Sequence, IteratorProtocol {
typealias Element = (Int, Float)
func next() -> (Int, Float)? {}
typealias Iterator = GoodTupleIterator
func makeIterator() -> GoodTupleIterator {}
}
protocol ElementProtocol {}
func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) {
var sum : Int
var sumf : Float
for i : Int in gir { sum = sum + i }
for i in gir { sum = sum + i }
for f : Float in gir { sum = sum + f } // expected-error{{cannot convert sequence element type 'GoodRange<Int>.Element' (aka 'Int') to expected type 'Float'}}
for f : ElementProtocol in gir { } // expected-error {{sequence element type 'GoodRange<Int>.Element' (aka 'Int') does not conform to expected protocol 'ElementProtocol'}}
for (i, f) : (Int, Float) in gtr { sum = sum + i }
for (i, f) in gtr {
sum = sum + i
sumf = sumf + f
sum = sum + f // expected-error {{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
for (i, _) : (Int, Float) in gtr { sum = sum + i }
for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{cannot convert sequence element type 'GoodTupleIterator.Element' (aka '(Int, Float)') to expected type '(Int, Int)'}}
for (i, f) in gtr {}
}
func slices(i_s: [Int], ias: [[Int]]) {
var sum = 0
for i in i_s { sum = sum + i }
for ia in ias {
for i in ia {
sum = sum + i
}
}
}
func discard_binding() {
for _ in [0] {}
}
struct X<T> {
var value: T
}
struct Gen<T> : IteratorProtocol {
func next() -> T? { return nil }
}
struct Seq<T> : Sequence {
func makeIterator() -> Gen<T> { return Gen() }
}
func getIntSeq() -> Seq<Int> { return Seq() }
func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}}
func getGenericSeq<T>() -> Seq<T> { return Seq() }
func getXIntSeq() -> Seq<X<Int>> { return Seq() }
func getXIntSeqIUO() -> Seq<X<Int>>! { return nil }
func testForEachInference() {
for i in getIntSeq() { }
// Overloaded sequence resolved contextually
for i: Int in getOvlSeq() { }
for d: Double in getOvlSeq() { }
// Overloaded sequence not resolved contextually
for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}}
// expected-error@-1{{variable 'v' is not bound by any pattern}}
// Generic sequence resolved contextually
for i: Int in getGenericSeq() { }
for d: Double in getGenericSeq() { }
// Inference of generic arguments in the element type from the
// sequence.
for x: X in getXIntSeq() {
let z = x.value + 1
}
for x: X in getOvlSeq() {
let z = x.value + 1
}
// Inference with implicitly unwrapped optional
for x: X in getXIntSeqIUO() {
let z = x.value + 1
}
// Range overloading.
for i: Int8 in 0..<10 { }
for i: UInt in 0...10 { }
}
func testMatchingPatterns() {
// <rdar://problem/21428712> for case parse failure
let myArray : [Int?] = []
for case .some(let x) in myArray {
_ = x
}
// <rdar://problem/21392677> for/case/in patterns aren't parsed properly
class A {}
class B : A {}
class C : A {}
let array : [A] = [A(), B(), C()]
for case (let x as B) in array {
_ = x
}
}
// <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great
func testOptionalSequence() {
let array : [Int]?
for x in array { // expected-error {{value of optional type '[Int]?' must be unwrapped}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
// expected-error@-3{{variable 'x' is not bound by any pattern}}
}
}
// Crash with (invalid) for each over an existential
func testExistentialSequence(s: Sequence) { // expected-error {{protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements}}
for x in s { // expected-error {{value of protocol type 'Sequence' cannot conform to 'Sequence'; only struct/enum/class types can conform to protocols}}
// expected-error@-1{{variable 'x' is not bound by any pattern}}
_ = x
}
}
// Conditional conformance to Sequence and IteratorProtocol.
protocol P { }
struct RepeatedSequence<T> {
var value: T
var count: Int
}
struct RepeatedIterator<T> {
var value: T
var count: Int
}
extension RepeatedIterator: IteratorProtocol where T: P {
typealias Element = T
mutating func next() -> T? {
if count == 0 { return nil }
count = count - 1
return value
}
}
extension RepeatedSequence: Sequence where T: P {
typealias Element = T
typealias Iterator = RepeatedIterator<T>
typealias SubSequence = AnySequence<T>
func makeIterator() -> RepeatedIterator<T> {
return Iterator(value: value, count: count)
}
}
extension Int : P { }
func testRepeated(ri: RepeatedSequence<Int>) {
for x in ri { _ = x }
}
| apache-2.0 | dc4ecb5c980ab59f778c0c791defd9a8 | 28.181818 | 187 | 0.657469 | 3.576127 | false | false | false | false |
chenchangqing/learniosRAC | FRP-Swift/FRP-Swift/Views/Controller/FRPGalleryFlowLayout.swift | 1 | 778 | //
// FRPGalleryFlowLayout.swift
// FRP-Swift
//
// Created by green on 15/9/3.
// Copyright (c) 2015年 green. All rights reserved.
//
import UIKit
class FRPGalleryFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
let screenWidth = UIScreen.mainScreen().bounds.size.width
let itemWidth:CGFloat = (screenWidth - 30)/2
self.itemSize = CGSizeMake(itemWidth, itemWidth)
self.minimumInteritemSpacing = 10
self.minimumLineSpacing = 10
self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
}
}
| gpl-2.0 | 0817567ee0eb66ca6f2daf198f085da7 | 20.555556 | 65 | 0.600515 | 4.485549 | false | false | false | false |
david-mcqueen/Pulser | Heart Rate Monitor - Audio/ViewController.swift | 1 | 21918 | //
// ViewController.swift
// Heart Rate Monitor - Audio
//
// Created by DavidMcQueen on 15/01/2015.
// Copyright (c) 2015 David McQueen. All rights reserved.
//
import UIKit
import CoreBluetooth;
import QuartzCore;
import AVFoundation;
import CoreLocation;
import HealthKit;
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, AVSpeechSynthesizerDelegate, UserSettingsDelegate {
//MARK:- View Variables
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var startStopButton: UIButton!
@IBOutlet weak var BPMLabel: UILabel!
@IBOutlet weak var zoneLabel: UILabel!
@IBOutlet weak var currentDisplayView: UIView!
@IBOutlet weak var connectingLabel: UILabel!
@IBOutlet weak var connectedLabel: UILabel!
@IBOutlet weak var tickDisplayView: UIView!
@IBOutlet weak var HKTick: UIImageView!
@IBOutlet weak var AudioTick: UIImageView!
//MARK:- Bluetooth Constants
let HRM_DEVICE_INFO_SERVICE_UUID = CBUUID(string: "180A");
let HRM_HEART_RATE_SERVICE_UUID = CBUUID(string: "180D");
let HRM_MEASUREMENT_CHARACTERISTIC_UUID = CBUUID(string:"2A37");
let HRM_BODY_LOCATION_CHARACTERISTIC_UUID = CBUUID(string:"2A38");
let HRM_MANUFACTURER_NAME_CHARACTERISTIC_UUID = CBUUID(string:"2A29");
//MARK:- Variables
var centralManager: CBCentralManager!;
var HRMPeripheral: CBPeripheral!;
var services = [];
var connected: Bool = false;
var running: Bool = false;
var attemptReconnect: Bool = false;
var currentUserSettings: UserSettings = UserSettings();
var CurrentBPM:Int = 0;
var lastUpdateTimeInterval: CFTimeInterval?; //Seconds since the last announcement
var delayBetweenAnnouncements: Double = 5.0; //Number of seconds between annoucing, usefurl for when on the edge of a zone
var speechArray:[String] = [];
var audioTimer: NSTimer?;
var healthkitTimer :NSTimer?
var connectTimer: NSTimer?
var uttenenceCounter = 0;
var mySpeechSynthesizer:AVSpeechSynthesizer = AVSpeechSynthesizer()
var error: NSError?;
var session = AVAudioSession.sharedInstance();
//MARK:- View methods
override func viewDidLoad() {
super.viewDidLoad()
mySpeechSynthesizer.delegate = self;
currentUserSettings = loadUserSettings()
connectedToHRM(false);
runningHRM(running);
updateDisplaySettings();
self.connectingLabel.hidden = true;
do {
//Setup the Speech Synthesizer to annouce over the top of other playing audio (reduces other volume whilst uttering)
try session.setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.DuckOthers)
} catch let error1 as NSError {
error = error1
}
services = [HRM_HEART_RATE_SERVICE_UUID, HRM_DEVICE_INFO_SERVICE_UUID];
//Configure Instabug
Instabug.setEmailIsRequired(false);
Instabug.setWillSendCrashReportsImmediately(true);
Instabug.setCommentIsRequired(true);
}
override func viewWillAppear(animated: Bool) {
//Load user settings
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- CBCentralManagerDelegate
//Called when a peripheral is successfully connected
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
peripheral.delegate = self;
peripheral.discoverServices(nil);
self.connected = (peripheral.state == CBPeripheralState.Connected ? true : false);
connectedToHRM(self.connected);
if (attemptReconnect){
runningHRM(attemptReconnect);
running = true;
speechArray.append("Pulser " + NSLocalizedString("REGAINED_CONNECTION", comment: "regained connection to HRM"));
speakAllUtterences()
}
NSLog("Connected: \(self.connected)");
}
//called with the CBPeripheral class as its main input parameter. This contains most of the information there is to know about a BLE peripheral.
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("Discovered \(peripheral.name)")
let localName = advertisementData;
if localName.count > 0 {
print("stop scan")
self.centralManager.stopScan();
print("assign peripheral")
self.HRMPeripheral = peripheral;
print("delegate")
peripheral.delegate = self;
print("connect");
self.centralManager.connectPeripheral(peripheral, options: nil);
}
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("Failed to connect")
self.running = false;
connectedToHRM(false);
runningHRM(false);
displayAlert(
NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("FAILED_TO_CONNECT", comment: "Failed to Connect to HRM")
);
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("Lost Connection");
if (running){
speechArray.append("Pulser " + NSLocalizedString("LOST_CONNECTION", comment: "Lost Connection to HRM"))
speakAllUtterences()
//Attempt to reconnect to HRM
attemptReconnect = true;
centralManager.scanForPeripheralsWithServices(services as? [CBUUID], options: nil);
}else{
displayAlert(NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("LOST_CONNECTION", comment: "Lost Connection to HRM")
);
}
HRMPeripheral = nil;
running = false;
connectedToHRM(false);
runningHRM(false);
}
//Called whenever the device state changes
func centralManagerDidUpdateState(central: CBCentralManager) {
//Determine the state of the peripheral
switch(central.state){
case .PoweredOff:
NSLog("CoreBluetooth BLE hardware is powered off");
self.running = false;
connectedToHRM(false);
runningHRM(false);
connectingLabel.hidden = true;
case .PoweredOn:
NSLog("CoreBluetooth BLE hardware is powered on and ready");
//Add a peripheral that has connected via another app
if (!alreadyConnectedDevice()){
centralManager.scanForPeripheralsWithServices(services as? [CBUUID], options: nil);
connectingLabel.hidden = false;
}
case .Unauthorized:
NSLog("CoreBluetooth BLE state is unauthorized");
self.running = false;
connectedToHRM(false);
runningHRM(false);
connectingLabel.hidden = true;
case .Unknown:
NSLog("CoreBluetooth BLE state is unknown");
self.running = false;
connectedToHRM(false);
runningHRM(false);
connectingLabel.hidden = true;
case .Unsupported:
displayAlert(NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("BLE_NOT_SUPPORTED", comment: "BLE not supported"));
self.running = false;
connectedToHRM(false);
runningHRM(false);
connectingLabel.hidden = true;
default:
self.running = false;
connectedToHRM(false);
runningHRM(false);
connectingLabel.hidden = true;
break;
}
}
//MARK:- CBPeripheralDelegate
//Called when you discover the peripherals available services
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
for service in peripheral.services! {
NSLog("Discovered service: \(service.UUID)")
peripheral.discoverCharacteristics(nil, forService: service as CBService)
}
}
//When you discover the characteristics of a specified service
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if (service.UUID == HRM_HEART_RATE_SERVICE_UUID){
for char in service.characteristics! {
if (char.UUID == HRM_MEASUREMENT_CHARACTERISTIC_UUID){
self.HRMPeripheral.setNotifyValue(true, forCharacteristic: char as CBCharacteristic);
NSLog("Found heart rate measurement characteristic");
}else if (char.UUID == HRM_BODY_LOCATION_CHARACTERISTIC_UUID){
self.HRMPeripheral.readValueForCharacteristic(char as CBCharacteristic);
NSLog("Found body sensor location characteristic");
}
}
}
if (service.UUID == HRM_DEVICE_INFO_SERVICE_UUID){
for char in service.characteristics! {
print(char.UUID, terminator: "")
if (char.UUID == HRM_MANUFACTURER_NAME_CHARACTERISTIC_UUID){
self.HRMPeripheral.readValueForCharacteristic(char as CBCharacteristic);
NSLog("Found a device manufacturer name characteristic");
}
}
}
}
// Invoked when you retrieve a specified characteristic's value, or when the peripheral device notifies your app that the characteristic's value has changed.
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("didUpdateValueForCharacteristic")
if (characteristic.UUID == HRM_MEASUREMENT_CHARACTERISTIC_UUID){
if(running){
self.getHeartBPMData(characteristic, error: error)
}
}
}
func speakData(){
if(self.CurrentBPM > 0 && connected){
if (currentUserSettings.AnnounceAudioShort){
speechArray.append("\(self.CurrentBPM)");
speechArray.append("Zone \(currentUserSettings.CurrentZone.rawValue)");
}else{
speechArray.append("Heart rate is \(self.CurrentBPM) beats per minute");
speechArray.append("Currently in zone \(currentUserSettings.CurrentZone.rawValue)");
}
}else{
speechArray.append(NSLocalizedString("UNABLE_TO_GET_BPM", comment: "Unable to get heart rate"));
}
speakAllUtterences();
}
func saveData(){
writeBPM(Double(self.CurrentBPM));
}
func enoughTimePassedAnnouncement(currentTime: CFTimeInterval) -> Bool {
var delta = CFTimeInterval?()
if let lastUpdate = lastUpdateTimeInterval {
delta = currentTime - lastUpdate
} else {
delta = currentTime
}
lastUpdateTimeInterval = currentTime
return delta > delayBetweenAnnouncements
}
//MARK:- CBCharacteristic helpers
//Get the BPM info
func getHeartBPMData(characteristic: CBCharacteristic!, error: NSError!){
let data = characteristic.value;
var values = [UInt8](count:data!.length, repeatedValue: 0)
data!.getBytes(&values, length: data!.length);
self.CurrentBPM = Int(values[1]);
let newZone = getZoneforBPM(self.CurrentBPM, _zones: self.currentUserSettings.UserZones)
if (newZone != currentUserSettings.CurrentZone && connected){
let zoneStringToSpeak = updateCurrentZoneAndReturnSpeechString(currentUserSettings.CurrentZone, newZone: newZone);
//Only announce the zone change if the user has it turned on
if(currentUserSettings.AnnounceAudioZoneChange && enoughTimePassedAnnouncement(CFAbsoluteTimeGetCurrent())){
speechArray.append(zoneStringToSpeak);
speakAllUtterences();
}
}
displayCurrentHeartRate(self.CurrentBPM, _zone: currentUserSettings.CurrentZone);
}
func updateCurrentZoneAndReturnSpeechString(oldZone: HeartRateZone, newZone: HeartRateZone)->String{
//The speech much be created before the zones are updated!
let speechString = createZoneChangedSpeech(currentUserSettings.CurrentZone, newZone: newZone);
currentUserSettings.CurrentZone = newZone;
return speechString;
}
private func createZoneChangedSpeech(oldZone: HeartRateZone, newZone: HeartRateZone)->String{
if (currentUserSettings.AnnounceAudioShort){
return "Zone \(newZone.rawValue)"
}else{
return "Zones Changed from \(oldZone.rawValue) to \(newZone.rawValue)";
}
}
func displayCurrentHeartRate(_bpm: Int, _zone: HeartRateZone){
BPMLabel.text = String(_bpm);
zoneLabel.text = _zone.rawValue
}
//MARK:- Methods
func connectedToHRM(connected:Bool){
self.connectButton.hidden = connected;
self.startStopButton.hidden = !connected;
connectedLabel.hidden = !connected;
self.connected = connected;
updateDisplaySettings();
if(connected){
connectingLabel.hidden = true;
}
}
func updateDisplaySettings(){
let activeImage: UIImage = UIImage(named: "TickCircle_Active.png")!
let notActiveImage: UIImage = UIImage(named: "TickCircle.png")!;
if (currentUserSettings.AnnounceAudio){
AudioTick.image = activeImage;
}else{
AudioTick.image = notActiveImage;
}
if (currentUserSettings.SaveHealthkit){
HKTick.image = activeImage;
}else{
HKTick.image = notActiveImage;
}
tickDisplayView.hidden = !connected;
}
func runningHRM(isRunning:Bool){
self.currentDisplayView.hidden = !isRunning;
if(connected){
self.connectedLabel.hidden = isRunning;
}
if(isRunning){
//Start a timer
if (currentUserSettings.AnnounceAudio){
toggleAudioTimer(true);
}
if(currentUserSettings.SaveHealthkit){
toggleHealthKitTimer(true);
}
changeButtonText(self.startStopButton, _buttonText: NSLocalizedString("STOP", comment: "Stop"));
}else{
//End the timers
toggleAudioTimer(false)
toggleHealthKitTimer(false);
changeButtonText(self.startStopButton, _buttonText: NSLocalizedString("START", comment: "Start"));
}
}
func toggleAudioTimer(shouldStart: Bool){
if (shouldStart){
//Start a repeating timer for X seconds, to announce BPM changes
audioTimer = NSTimer.scheduledTimerWithTimeInterval(
currentUserSettings.getAudioIntervalSeconds(),
target: self,
selector: Selector("speakData"),
userInfo: nil,
repeats: true
);
}else{
if(audioTimer != nil){
audioTimer?.invalidate();
}
}
}
func resetAudioTimer(){
toggleAudioTimer(false); //First invalidate
toggleAudioTimer(true); //Then start
}
func toggleHealthKitTimer(shouldStart:Bool){
if(shouldStart){
//Start a repeating timer for X seconds, to save BPM to healthkit
healthkitTimer = NSTimer.scheduledTimerWithTimeInterval(currentUserSettings.getHealthkitIntervalSeconds(), target: self, selector: Selector("saveData"), userInfo: nil, repeats: true);
}else{
if(healthkitTimer != nil){
healthkitTimer?.invalidate()
}
}
}
func resetHKTimer(){
toggleHealthKitTimer(false); //First invalidate
toggleHealthKitTimer(true); //Then start
}
@IBAction func startStopPressed(sender: AnyObject) {
if(currentUserSettings.UserZones.count > 0){
running = !running;
attemptReconnect = !running;
runningHRM(running);
let action = running ? NSLocalizedString("STARTING", comment: "Starting") : NSLocalizedString("STOPPING", comment: "Stopping")
speechArray.append("\(action) Pulser");
speakAllUtterences();
}else{
displayAlert(NSLocalizedString("ERROR", comment: "Error"),
message: NSLocalizedString("SETUP_ZONES_FIRST", comment: "Please setup zones first")
);
}
}
func changeButtonText(_button: UIButton, _buttonText: String){
_button.setTitle(_buttonText, forState: UIControlState.Normal);
}
@IBAction func connectPressed(sender: AnyObject) {
attemptReconnect = false; //Manually connect
centralManager = CBCentralManager(delegate: self, queue: nil);
//Check every 2 seconds if the device is connected via another app
centralManager.scanForPeripheralsWithServices(services as? [CBUUID], options: nil);
connectTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("alreadyConnectedDevice"), userInfo: nil, repeats: true);
}
func alreadyConnectedDevice()->Bool{
if(self.HRMPeripheral != nil){
connectTimer?.invalidate();
return true
}
let services = [HRM_HEART_RATE_SERVICE_UUID, HRM_DEVICE_INFO_SERVICE_UUID];
let connectedDevice = centralManager.retrieveConnectedPeripheralsWithServices(services);
//Add a peripheral that has connected via another app
if (connectedDevice.count > 0){
let device = connectedDevice.last!;
self.HRMPeripheral = device;
device.delegate = self;
centralManager.connectPeripheral(device, options: nil)
connectedToHRM(true)
return true;
}
return false;
}
func startSpeaking(){
self.speakNextUtterence();
}
func speakNextUtterence(){
if((speechArray.count > 0)){
let nextUtterence: AVSpeechUtterance = AVSpeechUtterance(string:speechArray[0]);
speechArray.removeAtIndex(0);
nextUtterence.rate = 0.5;
// nextUtterence.voice(AVSpeechSynthesisVoice(language:"en-GB"))
if(self.currentUserSettings.AnnounceAudio && self.running){
self.mySpeechSynthesizer.speakUtterance(nextUtterence);
}
}
}
func speakAllUtterences(){
while((speechArray.count > 0)){
speakNextUtterence();
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueIdentifier.ShowSettings.rawValue{
let settingsViewController = segue.destinationViewController as! SettingsViewController
settingsViewController.delegate = self;
settingsViewController.setUserSettings = currentUserSettings
}
}
//MARK:- AVSpeechSynthesizerDelegate
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didStartSpeechUtterance utterance: AVSpeechUtterance) {
do {
try session.setActive(true)
} catch let error1 as NSError {
error = error1
}
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
do {
try session.setActive(false)
} catch let error1 as NSError {
error = error1
}
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didPauseSpeechUtterance utterance: AVSpeechUtterance) {
do {
try session.setActive(false)
} catch let error1 as NSError {
error = error1
}
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didContinueSpeechUtterance utterance: AVSpeechUtterance) {
do {
try session.setActive(true)
} catch let error1 as NSError {
error = error1
}
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didCancelSpeechUtterance utterance: AVSpeechUtterance) {
do {
try session.setActive(false)
} catch let error1 as NSError {
error = error1
}
}
//MARK:- UpdateSettingsDelegate
func didUpdateUserSettings(newSettings: UserSettings) {
currentUserSettings = newSettings;
updateDisplaySettings();
//Save the settings to NSUserDefaults
saveUserSettings(newSettings);
//reset the timers, as the interval could have changed
if(running){
resetAudioTimer();
resetHKTimer();
}
}
}
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
| gpl-3.0 | 3df454ae1091c6b46b8d0c8af9ecf4ca | 35.049342 | 195 | 0.618076 | 5.261162 | false | false | false | false |
marcplouhinec/tourox-air-ios | touroxair/ViewController.swift | 1 | 8572 | //
// ViewController.swift
// touroxair
//
// Created by Marc Plouhinec on 28/03/16.
// Copyright © 2016 Marc Plouhinec. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: Properties
let carouselItems: [String] = ["StepImage1", "StepImage2"]
@IBOutlet weak var stepImage: UIImageView!
@IBOutlet weak var stepDescriptionLabel: UILabel!
@IBOutlet weak var volumeControl: UISlider!
var errorDialogDelegate : ErrorDialogDelegate?
required init?(coder: NSCoder) {
super.init(coder: coder)
errorDialogDelegate = ErrorDialogDelegate(viewController: self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Initialize the background
updateGradientBackground()
// Initialize the volume control
volumeControl.value = 1
// Start the VoIP service
startVoip()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
stopVoip()
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
updateGradientBackground()
}
// Add or update a radial gradient background to the view
private func updateGradientBackground() {
let screenCentre = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height/2)
let innerColour = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1.0).CGColor
let outterColour = UIColor.blackColor().CGColor
let radialGradientBackground = RadialGradientLayer(center: screenCentre, radius: CGFloat(self.view.frame.size.width * 0.9), colors: [innerColour, outterColour])
radialGradientBackground.frame = self.view!.bounds
if let sublayers = self.view!.layer.sublayers where !sublayers.isEmpty && sublayers[0] is RadialGradientLayer {
self.view!.layer.replaceSublayer(sublayers[0], with: radialGradientBackground)
}
else {
self.view!.layer.insertSublayer(radialGradientBackground, atIndex: 0)
}
radialGradientBackground.setNeedsDisplay()
}
// MARK: VoIP and sound management
@IBAction func volumeValueChanged(sender: UISlider) {
let voipService = ApplicationServices.getVoipService()
voipService.setVolume(volumeControl.value)
}
// Initialize the VoipService and handle errors
private func startVoip() {
NSLog("Start VoIP...")
onVoipConnectionStateChanged(.NOT_CONNECTED)
// Get the current IP address of the WIFI connection and check it is correct
let wifiAddress = NetworkUtils.getWiFiAddress();
if wifiAddress == nil {
showUnrecoverableErrorDialog(NSLocalizedString("no_wifi_connection_error_title", comment: "No WIFI connection detected!"), message: NSLocalizedString("no_wifi_connection_error_message", comment: "Please connect to the guide\'s WIFI router and restart the application."))
return;
}
if !wifiAddress!.hasPrefix("192.168.85.") {
showUnrecoverableErrorDialog(NSLocalizedString("wrong_wifi_connection_error_title", comment: "Wrong WIFI connection detected!"), message: NSLocalizedString("wrong_wifi_connection_error_message", comment: "Please connect to a WIFI network starting with the word \'tourox\' and restart the application."))
return;
}
// Start the VOIP service
let voipService = ApplicationServices.getVoipService()
if voipService.getVoipConnectionState() == .NOT_CONNECTED {
let usernameSuffixIndex = wifiAddress!.rangeOfString(".", options: .BackwardsSearch)?.endIndex
let username = "u" + wifiAddress!.substringFromIndex(usernameSuffixIndex!)
let hostname = "192.168.85.1"
NSLog("Computed configuration: username = %@, hostname = %@", username, hostname)
// Open the connection with the VoIP server
do {
try voipService.initialize({(state: VoipConnectionState) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.onVoipConnectionStateChanged(state)
}
})
let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 1 * Int64(NSEC_PER_SEC)) // Wait 1 second before opening the connection
dispatch_after(time, dispatch_get_main_queue()) {
do {
try voipService.openConnection(username, password: "pass", hostname: hostname)
}
catch VoipServiceError.ConnectionError(let message) {
NSLog("VoIP service connection error: \(message)")
self.showUnrecoverableErrorDialog(NSLocalizedString("unable_to_open_connection_to_voip_service_error_title", comment: "Connection error"), message: NSLocalizedString("unable_to_open_connection_to_voip_service_error_message", comment: "Unable to open a connection to the VoIP service. Please restart the application to try again."))
}
catch {
self.showUnrecoverableErrorDialog(NSLocalizedString("unable_to_open_connection_to_voip_service_error_title", comment: "Connection error"), message: NSLocalizedString("unable_to_open_connection_to_voip_service_error_message", comment: "Unable to open a connection to the VoIP service. Please restart the application to try again."))
}
}
} catch VoipServiceError.InitializationError(let message) {
NSLog("VoIP service initialization error: \(message)")
showUnrecoverableErrorDialog(NSLocalizedString("unable_to_load_voip_service_error_title", comment: "Internal error"), message: NSLocalizedString("unable_to_load_voip_service_error_message", comment: "Unable to load the VoIP service! You may try to restart the application, but if it still doesn\'t work it means your device is incompatible."))
} catch {
showUnrecoverableErrorDialog(NSLocalizedString("unable_to_load_voip_service_error_title", comment: "Internal error"), message: NSLocalizedString("unable_to_load_voip_service_error_message", comment: "Unable to load the VoIP service! You may try to restart the application, but if it still doesn\'t work it means your device is incompatible."))
}
}
NSLog("VoIP started.")
}
private func stopVoip() {
NSLog("Stop VoIP...")
let voipService = ApplicationServices.getVoipService()
voipService.closeConnection()
voipService.destroy()
NSLog("VoIP stopped.")
}
// Restart the VoipService
private func restartVoip() {
stopVoip()
startVoip()
}
// MARK: Error message
class ErrorDialogDelegate: NSObject, UIAlertViewDelegate {
let viewController: ViewController
init(viewController: ViewController) {
self.viewController = viewController
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
self.viewController.restartVoip()
}
}
private func showUnrecoverableErrorDialog(title: String, message: String) {
let alert = UIAlertView()
alert.title = title
alert.message = message
alert.addButtonWithTitle(NSLocalizedString("restart_button", comment: "Restart"))
alert.delegate = errorDialogDelegate
alert.show()
}
// MARK: Steps
private func onVoipConnectionStateChanged(state: VoipConnectionState) {
switch state {
case .NOT_CONNECTED:
stepImage.image = UIImage(named: carouselItems[0])
stepDescriptionLabel.text = NSLocalizedString("step1_description", comment: "Connecting to the router…")
case .UNABLE_TO_CONNECT:
stepImage.image = UIImage(named: carouselItems[0])
stepDescriptionLabel.text = NSLocalizedString("step1_error_description", comment: "Error: unable to connect with the router VoIP!")
case .ONGOING_CALL:
stepImage.image = UIImage(named: carouselItems[1])
stepDescriptionLabel.text = NSLocalizedString("step2_description", comment: "Communication ongoing")
}
}
}
| gpl-3.0 | 47451b200c45336dcf79056ac0970b54 | 46.082418 | 359 | 0.653869 | 4.953179 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ConversationTests+DeliveryConfirmation.swift | 1 | 6245 | //
// 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 XCTest
class ConversationTests_DeliveryConfirmation: ConversationTestsBase {
func testThatItSendsADeliveryConfirmationWhenReceivingAMessageInAOneOnOneConversation() {
// given
XCTAssert(login())
let fromClient = user1?.clients.anyObject() as! MockUserClient
let toClient = selfUser?.clients.anyObject() as! MockUserClient
let textMessage = GenericMessage(content: Text(content: "Hello"))
let conversation = self.conversation(for: selfToUser1Conversation!)
let requestPath = "/conversations/\(conversation!.remoteIdentifier!.transportString())/otr/messages"
// expect
mockTransportSession?.responseGeneratorBlock = { request in
if request.path == requestPath {
guard
let data = request.binaryData,
let otrMessage = try? Proteus_NewOtrMessage(serializedData: data)
else {
XCTFail("Expected OTR message")
return nil
}
XCTAssertEqual(otrMessage.recipients.count, 1)
let recipient = try! XCTUnwrap(otrMessage.recipients.first)
XCTAssertEqual(recipient.user, self.user(for: self.user1)!.userId)
let encryptedData = recipient.clients.first!.text
let decryptedData = MockUserClient.decryptMessage(data: encryptedData, from: toClient, to: fromClient)
let genericMessage = try! GenericMessage(serializedData: decryptedData)
XCTAssertEqual(genericMessage.confirmation.firstMessageID, textMessage.messageID)
}
return nil
}
// when
mockTransportSession?.performRemoteChanges { _ in
do {
self.selfToUser1Conversation?.encryptAndInsertData(from: fromClient, to: toClient, data: try textMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertEqual(conversation?.allMessages.count, 1) // inserted message
guard let request = mockTransportSession?.receivedRequests().last else {return XCTFail()}
XCTAssertEqual((request as AnyObject).path, requestPath)
XCTAssertEqual(conversation?.lastModifiedDate, conversation?.lastMessage?.serverTimestamp)
}
func testThatItSetsAMessageToDeliveredWhenReceivingADeliveryConfirmationMessageInAOneOnOneConversation() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)
var message: ZMClientMessage!
self.userSession?.perform {
message = try! conversation?.appendText(content: "Hello") as? ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
XCTAssertEqual(message.deliveryState, ZMDeliveryState.sent)
let fromClient = user1?.clients.anyObject() as! MockUserClient
let toClient = selfUser?.clients.anyObject() as! MockUserClient
let confirmationMessage = GenericMessage(content: Confirmation(messageId: message.nonce!))
// when
mockTransportSession?.performRemoteChanges { _ in
do {
self.selfToUser1Conversation?.encryptAndInsertData(from: fromClient, to: toClient, data: try confirmationMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
// The confirmation message is not inserted
XCTAssertEqual(conversation?.hiddenMessages.count, 0)
XCTAssertEqual(message.deliveryState, ZMDeliveryState.delivered)
XCTAssertEqual(conversation?.lastModifiedDate, message.serverTimestamp)
}
func testThatItSendsANotificationWhenUpdatingTheDeliveryState() {
// given
XCTAssert(login())
let conversation = self.conversation(for: selfToUser1Conversation!)
var message: ZMClientMessage!
self.userSession?.perform {
message = try! conversation?.appendText(content: "Hello") as? ZMClientMessage
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
XCTAssertEqual(conversation?.hiddenMessages.count, 0)
XCTAssertEqual(message.deliveryState, ZMDeliveryState.sent)
let fromClient = user1!.clients.anyObject() as! MockUserClient
let toClient = selfUser!.clients.anyObject() as! MockUserClient
let confirmationMessage = GenericMessage(content: Confirmation(messageId: message.nonce!, type: .init()))
let convObserver = ConversationChangeObserver(conversation: conversation)
let messageObserver = MessageChangeObserver(message: message)
// when
mockTransportSession?.performRemoteChanges { _ in
do {
self.selfToUser1Conversation?.encryptAndInsertData(from: fromClient, to: toClient, data: try confirmationMessage.serializedData())
} catch {
XCTFail()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
if convObserver!.notifications.count > 0 {
return XCTFail()
}
guard let messageChangeInfo = messageObserver?.notifications.firstObject as? MessageChangeInfo else {
return XCTFail()
}
XCTAssertTrue(messageChangeInfo.deliveryStateChanged)
}
}
| gpl-3.0 | c1d144651e9d3abcbcd7d54053a844f1 | 40.633333 | 146 | 0.667414 | 5.439895 | false | false | false | false |
brentdax/swift | test/Generics/deduction.swift | 2 | 11800 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Deduction of generic arguments
//===----------------------------------------------------------------------===//
func identity<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> Int { return 0 }
struct X { }
struct Y { }
func useIdentity(_ x: Int, y: Float, i32: Int32) {
var x2 = identity(x)
var y2 = identity(y)
// Deduction that involves the result type
x2 = identity(17)
var i32_2 : Int32 = identity(17)
// Deduction where the result type and input type can get different results
var xx : X, yy : Y
xx = identity(yy) // expected-error{{cannot assign value of type 'Y' to type 'X'}}
xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}}
}
// FIXME: Crummy diagnostic!
func twoIdentical<T>(_ x: T, _ y: T) -> T {}
func useTwoIdentical(_ xi: Int, yi: Float) {
var x = xi, y = yi
x = twoIdentical(x, x)
y = twoIdentical(y, y)
x = twoIdentical(x, 1)
x = twoIdentical(1, x)
y = twoIdentical(1.0, y)
y = twoIdentical(y, 1.0)
twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func mySwap<T>(_ x: inout T,
_ y: inout T) {
let tmp = x
x = y
y = tmp
}
func useSwap(_ xi: Int, yi: Float) {
var x = xi, y = yi
mySwap(&x, &x)
mySwap(&y, &y)
mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
// expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}}
mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func takeTuples<T, U>(_: (T, U), _: (U, T)) {
}
func useTuples(_ x: Int, y: Float, z: (Float, Int)) {
takeTuples((x, y), (y, x))
takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
// FIXME: Use 'z', which requires us to fix our tuple-conversion
// representation.
}
func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {}
func passFunction(_ f: (Int) -> Float, x: Int, y: Float) {
acceptFunction(f, x, y)
acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}}
func testReturnTuple(_ x: Int, y: Float) {
returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}}
var _ : (Int, Float) = returnTuple(x)
var _ : (Float, Float) = returnTuple(y)
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) {
confusingArgAndParam(g, f)
confusingArgAndParam(f, g)
}
func acceptUnaryFn<T, U>(_ f: (T) -> U) { }
func acceptUnaryFnSame<T>(_ f: (T) -> T) { }
func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { }
func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { }
func unaryFnIntInt(_: Int) -> Int {}
func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}}
func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}}
// Variable forms of the above functions
var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt
func passOverloadSet() {
// Passing a non-generic function to a generic function
acceptUnaryFn(unaryFnIntInt)
acceptUnaryFnSame(unaryFnIntInt)
// Passing an overloaded function set to a generic function
// FIXME: Yet more terrible diagnostics.
acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}}
acceptUnaryFnSame(unaryFnOvl)
// Passing a variable of function type to a generic function
acceptUnaryFn(unaryFnIntIntVar)
acceptUnaryFnSame(unaryFnIntIntVar)
// Passing a variable of function type to a generic function to an inout parameter
acceptUnaryFnRef(&unaryFnIntIntVar)
acceptUnaryFnSameRef(&unaryFnIntIntVar)
acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
}
func acceptFnFloatFloat(_ f: (Float) -> Float) {}
func acceptFnDoubleDouble(_ f: (Double) -> Double) {}
func passGeneric() {
acceptFnFloatFloat(identity)
acceptFnFloatFloat(identity2)
}
//===----------------------------------------------------------------------===//
// Simple deduction for generic member functions
//===----------------------------------------------------------------------===//
struct SomeType {
func identity<T>(_ x: T) -> T { return x }
func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}}
func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}}
func returnAs<T>() -> T {}
}
func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) {
var st = sti, i = ii, f = fi
i = st.identity(i)
f = st.identity(f)
i = st.identity2(i)
f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}}
i = st.returnAs()
f = st.returnAs()
acceptFnFloatFloat(st.identity)
acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}}
acceptFnDoubleDouble(st.identity2)
}
struct StaticFuncs {
static func chameleon<T>() -> T {}
func chameleon2<T>() -> T {}
}
struct StaticFuncsGeneric<U> {
// FIXME: Nested generics are very broken
// static func chameleon<T>() -> T {}
}
func chameleon<T>() -> T {}
func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) {
var x: Int16
x = StaticFuncs.chameleon()
x = sf.chameleon2()
// FIXME: Nested generics are very broken
// x = sfi.chameleon()
// typealias SFI = StaticFuncsGeneric<Int>
// x = SFI.chameleon()
_ = x
}
//===----------------------------------------------------------------------===//
// Deduction checking for constraints
//===----------------------------------------------------------------------===//
protocol IsBefore {
func isBefore(_ other: Self) -> Bool
}
func min2<T : IsBefore>(_ x: T, _ y: T) -> T {
if y.isBefore(x) { return y }
return x
}
extension Int : IsBefore {
func isBefore(_ other: Int) -> Bool { return self < other }
}
func callMin(_ x: Int, y: Int, a: Float, b: Float) {
_ = min2(x, y)
min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}}
}
func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} // expected-note {{'R.Element' = 'Double'}}
func callRangeOfIsBefore(_ ia: [Int], da: [Double]) {
rangeOfIsBefore(ia.makeIterator())
rangeOfIsBefore(da.makeIterator()) // expected-error{{global function 'rangeOfIsBefore' requires that 'Double' conform to 'IsBefore'}}
}
func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {}
// expected-note@-1 {{where 'A.Element' = 'Int', 'B.Element' = 'Double'}}
func compareIterators() {
var a: [Int] = []
var b: [Double] = []
testEqualIterElementTypes(a.makeIterator(), b.makeIterator())
// expected-error@-1 {{global function 'testEqualIterElementTypes' requires the types 'Int' and 'Double' be equivalent}}
}
protocol P_GI {
associatedtype Y
}
class C_GI : P_GI {
typealias Y = Double
}
class GI_Diff {}
func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {}
// expected-note@-1 {{candidate requires that 'GI_Diff' inherit from 'T.Y' (requirement specified as 'T.Y' : 'GI_Diff' [with T = C_GI])}}
genericInheritsA(C_GI())
// expected-error@-1 {{cannot invoke 'genericInheritsA(_:)' with an argument list of type '(C_GI)'}}
//===----------------------------------------------------------------------===//
// Deduction for member operators
//===----------------------------------------------------------------------===//
protocol Addable {
static func +(x: Self, y: Self) -> Self
}
func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T {
u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
return x+y
}
//===----------------------------------------------------------------------===//
// Deduction for bound generic types
//===----------------------------------------------------------------------===//
struct MyVector<T> { func size() -> Int {} }
func getVectorSize<T>(_ v: MyVector<T>) -> Int {
return v.size()
}
func ovlVector<T>(_ v: MyVector<T>) -> X {}
func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {}
func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) {
var i : Int
i = getVectorSize(vi)
i = getVectorSize(vf)
getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}}
var x : X, y : Y
x = ovlVector(vi)
x = ovlVector(vf)
var vvi : MyVector<MyVector<Int>>
y = ovlVector(vvi)
var yy = ovlVector(vvi)
yy = y
y = yy
}
// <rdar://problem/15104554>
postfix operator <*>
protocol MetaFunction {
associatedtype Result
static postfix func <*> (_: Self) -> Result?
}
protocol Bool_ {}
struct False : Bool_ {}
struct True : Bool_ {}
postfix func <*> <B>(_: Test<B>) -> Int? { return .none }
postfix func <*> (_: Test<True>) -> String? { return .none }
class Test<C: Bool_> : MetaFunction {
typealias Result = Int
} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}}
// rdar://problem/20577950
class DeducePropertyParams {
let badSet: Set = ["Hello"]
}
// SR-69
struct A {}
func foo() {
for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}}
}
let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}}
let oi : Int? = 5
let l = min(3, oi) // expected-error{{value of optional type 'Int?' must be unwrapped}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
}
infix operator +&
func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {}
// expected-note@-1 {{candidate requires that the types 'String' and 'Character' be equivalent (requirement specified as 'R.Element' == 'S.Element' [with R = [String], S = String])}}
func rdar33477726_1() {
var arr: [String] = []
arr +& "hello"
// expected-error@-1 {{binary operator '+&(_:_:)' cannot be applied to operands of type '[String]' and 'String'}}
}
func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {}
// expected-note@-1 {{candidate requires that the types 'Int' and 'Character' be equivalent (requirement specified as 'S' == 'R.Element' [with R = String, S = Int])}}
rdar33477726_2("answer", 42)
// expected-error@-1 {{cannot invoke 'rdar33477726_2(_:_:)' with an argument list of type '(String, Int)'}}
prefix operator +-
prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {}
// expected-note@-1 {{candidate requires that the types 'Character' and 'Int' be equivalent (requirement specified as 'T.Element' == 'Int' [with T = String])}}
+-"hello"
// expected-error@-1 {{unary operator '+-(_:)' cannot be applied to an operand of type 'String'}}
| apache-2.0 | 6ff50a31c1242a0d5449b25f30fbc4e2 | 33.302326 | 182 | 0.609915 | 3.663459 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/HandyJSON/Source/Properties.swift | 4 | 3018 | /*
* Copyright 1999-2101 Alibaba Group.
*
* 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.
*/
//
// Created by zhouzhuo on 07/01/2017.
//
/// An instance property
struct Property {
let key: String
let value: Any
/// An instance property description
struct Description {
public let key: String
public let type: Any.Type
public let offset: Int
public func write(_ value: Any, to storage: UnsafeMutableRawPointer) {
return extensions(of: type).write(value, to: storage.advanced(by: offset))
}
}
}
/// Retrieve properties for `instance`
func getProperties(forInstance instance: Any) -> [Property]? {
if let props = getProperties(forType: type(of: instance)) {
var copy = extensions(of: instance)
let storage = copy.storage()
return props.map {
nextProperty(description: $0, storage: storage)
}
}
return nil
}
private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property {
return Property(
key: description.key,
value: extensions(of: description.type).value(from: storage.advanced(by: description.offset))
)
}
/// Retrieve property descriptions for `type`
func getProperties(forType type: Any.Type) -> [Property.Description]? {
if let nominalType = Metadata.Struct(anyType: type) {
return fetchProperties(nominalType: nominalType)
} else if let nominalType = Metadata.Class(anyType: type) {
return nominalType.properties()
} else if let nominalType = Metadata.ObjcClassWrapper(anyType: type),
let targetType = nominalType.targetType {
return getProperties(forType: targetType)
} else {
return nil
}
}
func fetchProperties<T : NominalType>(nominalType: T) -> [Property.Description]? {
return propertiesForNominalType(nominalType)
}
private func propertiesForNominalType<T : NominalType>(_ type: T) -> [Property.Description]? {
guard let nominalTypeDescriptor = type.nominalTypeDescriptor else {
return nil
}
guard nominalTypeDescriptor.numberOfFields != 0 else {
return []
}
guard let fieldTypes = type.fieldTypes, let fieldOffsets = type.fieldOffsets else {
return nil
}
let fieldNames = nominalTypeDescriptor.fieldNames
return (0..<nominalTypeDescriptor.numberOfFields).map { i in
return Property.Description(key: fieldNames[i], type: fieldTypes[i], offset: fieldOffsets[i])
}
}
| mit | 70b9abcffeeabf3ddf5efbc328f81f34 | 32.910112 | 101 | 0.687541 | 4.280851 | false | false | false | false |
fuku2014/spritekit-original-game | src/scenes/home/HomeScene.swift | 1 | 5607 | //
// HomeScene.swift
// あるきスマホ
//
// Created by admin on 2015/09/06.
// Copyright (c) 2015年 m.fukuzawa. All rights reserved.
//
import UIKit
import SpriteKit
class HomeScene: SKScene,StartBtnDelegate, RankBtnDelegate, SettingBtnDelegate, BattleBtnDelegate {
override func didMoveToView(view: SKView) {
let back = SKSpriteNode(imageNamed:"home_back")
back.xScale = self.size.width/back.size.width
back.yScale = self.size.height/back.size.height
back.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
back.zPosition = 0
self.addChild(back)
let startBtn = StartBtn(imageNamed: "home_btn_start")
startBtn.delegate = self
startBtn.userInteractionEnabled = true
startBtn.position = CGPointMake(CGRectGetMidX(self.frame), self.size.height * 0.35)
startBtn.zPosition = 1
self.addChild(startBtn)
let rankBtn = RankBtn(imageNamed: "home_btn_rank")
rankBtn.delegate = self
rankBtn.xScale = 1 / 5
rankBtn.yScale = 1 / 5
rankBtn.userInteractionEnabled = true
rankBtn.position = CGPointMake(CGRectGetMidX(self.frame) - 65, self.size.height * 0.24)
rankBtn.zPosition = 1
self.addChild(rankBtn)
let battleBtn = BattleBtn(imageNamed: "home_btn_battle")
battleBtn.delegate = self
battleBtn.xScale = 1 / 5
battleBtn.yScale = 1 / 5
battleBtn.userInteractionEnabled = true
battleBtn.position = CGPointMake(CGRectGetMidX(self.frame), self.size.height * 0.24)
battleBtn.zPosition = 1
self.addChild(battleBtn)
let settingBtn = SettingBtn(imageNamed: "home_setting")
settingBtn.userInteractionEnabled = true
settingBtn.delegate = self
settingBtn.position = CGPointMake(CGRectGetMidX(self.frame) + 65, self.size.height * 0.24)
settingBtn.zPosition = 1
self.addChild(settingBtn)
let facebookBtn = FaceBookBtn(imageNamed: "home_facebook")
facebookBtn.userInteractionEnabled = true
facebookBtn.position = CGPointMake(CGRectGetMidX(self.frame) - 65 , self.size.height * 0.12)
facebookBtn.zPosition = 1
self.addChild(facebookBtn)
let tweetBtn = TwitterBtn(msg: "")
tweetBtn.userInteractionEnabled = true
tweetBtn.position = CGPointMake(CGRectGetMidX(self.frame) , self.size.height * 0.12)
tweetBtn.zPosition = 1
self.addChild(tweetBtn)
let helpBtn = HelpBtn(imageNamed: "home_help")
helpBtn.userInteractionEnabled = true
helpBtn.position = CGPointMake(CGRectGetMidX(self.frame) + 65, self.size.height * 0.12)
helpBtn.zPosition = 1
self.addChild(helpBtn)
let highScore = UserData.getHighScore()
let highScoreLabel : SKLabelNode = SKLabelNode(fontNamed: "serif")
highScoreLabel.text = String(highScore) + "点"
highScoreLabel.fontColor = UIColor.redColor()
highScoreLabel.fontSize = 60
highScoreLabel.position = CGPointMake(CGRectGetMidX(self.frame) - 100, self.size.height * 0.6)
highScoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
highScoreLabel.zPosition = 1
self.addChild(highScoreLabel)
}
func viewRank() {
let rankScene = RankScene(size: self.view!.bounds.size)
rankScene.scaleMode = SKSceneScaleMode.AspectFill
rankScene.currentScore = UserData.getHighScore()
rankScene.setup()
rankScene.addBest5()
rankScene.addRank()
self.view!.presentScene(rankScene)
let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false)
rankScene.runAction(sound)
}
func gameStart() {
let playScene = PlayScene(size: self.view!.bounds.size)
playScene.scaleMode = SKSceneScaleMode.AspectFill;
self.view!.presentScene(playScene)
let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false)
playScene.runAction(sound)
// BGMの再生
let vc = UIApplication.sharedApplication().keyWindow?.rootViewController! as! ViewController
vc.changeBGM(playScene)
}
func showSetting() {
let dialog = SettingScene(scene: self, frame:CGRectMake(0, 0, self.view!.bounds.maxX - 50, 350))
self.view!.addSubview(dialog)
}
func presentBattleRooms() {
let roomsScene = RoomsScene(size: self.view!.bounds.size)
roomsScene.scaleMode = SKSceneScaleMode.AspectFill;
self.view!.presentScene(roomsScene)
let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false)
roomsScene.runAction(sound)
roomsScene.refresh()
// BGMの再生
let vc = UIApplication.sharedApplication().keyWindow?.rootViewController! as! ViewController
vc.changeBGM(roomsScene)
}
}
| apache-2.0 | f570cda9eaf26959e6476c64e2975198 | 44.729508 | 117 | 0.593834 | 4.684299 | false | false | false | false |
zfoltin/ImageViewer | ImageViewer/Source/VideoViewController.swift | 2 | 6981 | //
// ImageViewController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/08/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
import AVFoundation
extension VideoView: ItemView {}
class VideoViewController: ItemBaseController<VideoView> {
fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6
let videoURL: URL
let player: AVPlayer
unowned let scrubber: VideoScrubber
let fullHDScreenSizeLandscape = CGSize(width: 1920, height: 1080)
let fullHDScreenSizePortrait = CGSize(width: 1080, height: 1920)
let embeddedPlayButton = UIButton.circlePlayButton(70)
private var autoPlayStarted: Bool = false
private var autoPlayEnabled: Bool = false
init(index: Int, itemCount: Int, fetchImageBlock: @escaping FetchImageBlock, videoURL: URL, scrubber: VideoScrubber, configuration: GalleryConfiguration, isInitialController: Bool = false) {
self.videoURL = videoURL
self.scrubber = scrubber
self.player = AVPlayer(url: self.videoURL)
///Only those options relevant to the paging VideoViewController are explicitly handled here, the rest is handled by ItemViewControllers
for item in configuration {
switch item {
case .videoAutoPlay(let enabled):
autoPlayEnabled = enabled
default: break
}
}
super.init(index: index, itemCount: itemCount, fetchImageBlock: fetchImageBlock, configuration: configuration, isInitialController: isInitialController)
}
override func viewDidLoad() {
super.viewDidLoad()
if isInitialController == true { embeddedPlayButton.alpha = 0 }
embeddedPlayButton.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.view.addSubview(embeddedPlayButton)
embeddedPlayButton.center = self.view.boundsCenter
embeddedPlayButton.addTarget(self, action: #selector(playVideoInitially), for: UIControl.Event.touchUpInside)
self.itemView.player = player
self.itemView.contentMode = .scaleAspectFill
}
override func viewWillAppear(_ animated: Bool) {
self.player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
self.player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
UIApplication.shared.beginReceivingRemoteControlEvents()
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.player.removeObserver(self, forKeyPath: "status")
self.player.removeObserver(self, forKeyPath: "rate")
UIApplication.shared.endReceivingRemoteControlEvents()
super.viewWillDisappear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
performAutoPlay()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.player.pause()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let isLandscape = itemView.bounds.width >= itemView.bounds.height
itemView.bounds.size = aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: self.scrollView.bounds.size)
itemView.center = scrollView.boundsCenter
}
@objc func playVideoInitially() {
self.player.play()
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
}, completion: { [weak self] _ in
self?.embeddedPlayButton.isHidden = true
})
}
override func closeDecorationViews(_ duration: TimeInterval) {
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
self?.itemView.previewImageView.alpha = 1
})
}
override func presentItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) {
let circleButtonAnimation = {
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 1
})
}
super.presentItem(alongsideAnimation: alongsideAnimation) {
circleButtonAnimation()
completion()
}
}
override func displacementTargetSize(forSize size: CGSize) -> CGSize {
let isLandscape = itemView.bounds.width >= itemView.bounds.height
return aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: rotationAdjustedBounds().size)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" || keyPath == "status" {
fadeOutEmbeddedPlayButton()
}
else if keyPath == "contentOffset" {
handleSwipeToDismissTransition()
}
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
func handleSwipeToDismissTransition() {
guard let _ = swipingToDismiss else { return }
embeddedPlayButton.center.y = view.center.y - scrollView.contentOffset.y
}
func fadeOutEmbeddedPlayButton() {
if player.isPlaying() && embeddedPlayButton.alpha != 0 {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
})
}
}
override func remoteControlReceived(with event: UIEvent?) {
if let event = event {
if event.type == UIEvent.EventType.remoteControl {
switch event.subtype {
case .remoteControlTogglePlayPause:
if self.player.isPlaying() {
self.player.pause()
}
else {
self.player.play()
}
case .remoteControlPause:
self.player.pause()
case .remoteControlPlay:
self.player.play()
case .remoteControlPreviousTrack:
self.player.pause()
self.player.seek(to: CMTime(value: 0, timescale: 1))
self.player.play()
default:
break
}
}
}
}
private func performAutoPlay() {
guard autoPlayEnabled else { return }
guard autoPlayStarted == false else { return }
autoPlayStarted = true
embeddedPlayButton.isHidden = true
scrubber.play()
}
}
| mit | b0e5172cc680829fb62a9c5e718a83d7 | 28.82906 | 194 | 0.634814 | 5.267925 | false | false | false | false |
mark-randall/Forms | Pod/Classes/InputViews/FormBaseTextInputView.swift | 1 | 7498 | //
// FormBaseTextInputView.swift
//
// The MIT License (MIT)
//
// Created by mrandall on 12/02/15.
// Copyright © 2015 mrandall. 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 UIKit
//MARK: - Form Input Subviews
public protocol FormInputView: class {
var identifier: String { get }
//var theme: FormInputViewTheme { get set }
var captionLabel: UILabel { get }
var errorLabel: UILabel { get }
func becomeFirstResponder() -> Bool
}
public protocol KeyboardFormIputView: FormInputView {
var textField: UITextField { get }
}
public protocol ButtonFormIputView: FormInputView {
var button: UIButton { get }
}
//MARK: - Form Input Subview Layout
public enum InputSubviews {
case TextField
case CaptionLabel
case ErrorLabel
}
protocol FormBaseTextInputViewLayout {
var inputLayoutAxis: UILayoutConstraintAxis { get set }
var subviewSpacing: Double { get set }
var subviewOrder:[InputSubviews] { get set }
}
//MARK: - Form Input With ViewModel
public protocol FormInputViewModelView: class {
typealias DataType
var viewModel: FormInputViewModel<DataType>? { get }
func bindViewModel()
}
//Base UIView for any FormInputs which require a basic textfield, capture label, error label heirarchy
final class FormBaseTextInputView<T>: UIView {
override class func requiresConstraintBasedLayout() -> Bool {
return true
}
//MARK: - Layout Configuration
var inputViewLayout: InputViewLayout = InputViewLayout() {
didSet {
subviewOrder = inputViewLayout.subviewOrder
stackView.spacing = CGFloat(inputViewLayout.subviewSpacing)
stackView.axis = inputViewLayout.inputLayoutAxis
}
}
//TODO: review access of these
var subviewOrder = [InputSubviews.TextField, InputSubviews.ErrorLabel, InputSubviews.CaptionLabel]
//MARK: - Subviews
lazy var stackView: UIStackView = { [unowned self] in
let stackView = UIStackView()
stackView.axis = .Vertical
stackView.spacing = 2.0
stackView.distribution = .Fill
self.addSubview(stackView)
return stackView
}()
lazy var textField: UITextField = { [unowned self] in
let textField = UITextField()
return textField
}()
lazy var captionLabel: UILabel = { [unowned self] in
let captionLabel = UILabel()
captionLabel.numberOfLines = 0
captionLabel.lineBreakMode = .ByWordWrapping
return captionLabel
}()
lazy var errorLabel: UILabel = { [unowned self] in
let errorLabel = UILabel()
errorLabel.numberOfLines = 0
errorLabel.lineBreakMode = .ByWordWrapping
return errorLabel
}()
//MARK: - Init
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
//MARK: - Layout
override func updateConstraints() {
super.updateConstraints()
addSubviewConstraints()
addSubviews()
}
override func intrinsicContentSize() -> CGSize {
return stackView.intrinsicContentSize()
}
//MARK: - Add Subviews
private var didAddSubviewConstriants = false
private func addSubviewConstraints() {
guard didAddSubviewConstriants == false else { return }
didAddSubviewConstriants = true
//layout subviews
UIView.createConstraints(visualFormatting: [
"H:|-(0)-[stackView]-(0)-|",
"V:|-(0)-[stackView]-(0)-|",
],
views: [
"stackView": stackView,
])
//give the textfield height priority when a view height is defined
let constaint = textField.heightAnchor.constraintGreaterThanOrEqualToConstant(0)
constaint.priority = 999
constaint.active = true
invalidateIntrinsicContentSize()
}
private var didAddSubviews = false
private func addSubviews() {
guard didAddSubviews == false else { return }
didAddSubviews = true
self.subviewOrder.forEach {
switch $0 {
case .TextField:
self.stackView.addArrangedSubview(self.textField)
case .ErrorLabel:
self.stackView.addArrangedSubview(self.errorLabel)
case .CaptionLabel:
self.stackView.addArrangedSubview(self.captionLabel)
}
}
invalidateIntrinsicContentSize()
}
func bindViewModel(viewModel: FormInputViewModel<T>) {
viewModel.displayValueObservable.observe { self.textField.text = $0 }
viewModel.placeholderObservable.observe { self.textField.attributedPlaceholder = $0 }
viewModel.captionObservable.observe {
self.captionLabel.hidden = $0.string.isEmpty
self.captionLabel.attributedText = $0
}
viewModel.errorTextObservable.observe {
self.errorLabel.hidden = $0.string.isEmpty
self.errorLabel.attributedText = $0
}
viewModel.returnKeyTypeObservable.observe { self.textField.returnKeyType = $0 }
viewModel.secureTextEntryObservable.observe { self.textField.secureTextEntry = $0 }
viewModel.keyboardTypeObservable.observe { self.textField.keyboardType = $0 }
viewModel.autocorrectionTypeObservable.observe { self.textField.autocorrectionType = $0 }
viewModel.enabledObservable.observe { self.textField.enabled = $0 }
viewModel.focusedObservable.observe {
if ($0 == true) {
self.textField.becomeFirstResponder()
}
}
self.inputViewLayout = viewModel.inputViewLayout
//layout
viewModel.inputViewLayoutObservable.observeNew {
self.inputViewLayout = $0
//teardown and reflow entire layour
//TODO: diff order
self.didAddSubviews = false
while let arrangedSubView = self.stackView.arrangedSubviews.last {
arrangedSubView.removeFromSuperview()
}
self.addSubviews()
}
}
}
| mit | 36a93384c419c6463d089659ebc3e39a | 29.352227 | 102 | 0.633053 | 5.173913 | false | false | false | false |
jeroendesloovere/examples-swift | Swift-Playgrounds/AdvancedOperators.playground/section-1.swift | 1 | 5263 | // Advanced Operators
// Unlike arithmetic operators in C, arithmetic operators in Swift do not overflow by default. Overflow behavior is trapped and reported as an error. To opt in to overflow behavior, use Swift’s second set of arithmetic operators that overflow by default, such as the overflow addition operator (&+). All of these overflow operators begin with an ampersand (&).
// Bitwise Operators
// Bitwise NOT
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits
// Bitwise AND
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits
// Bitwise OR
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedBits = someBits | moreBits
// Bitwise XOR
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits
// Bitwise Left and Right Shift
let shiftBits: UInt8 = 4
shiftBits << 1
shiftBits << 2
shiftBits << 5
shiftBits << 6
shiftBits >> 2
let pink: UInt32 = 0xCC6699
let redComponent = (pink & 0xFF0000) >> 16
let greenComponent = (pink & 0x00FF00) >> 8
let blueComponent = pink & 0x0000FF
let negativeBits: Int8 = -4
negativeBits << 1
negativeBits << 2
negativeBits << 5
negativeBits << 6
negativeBits >> 2
negativeBits >> 5 // Doesn't overflow
// Overflow Operators
// Overflow addition (&+)
// Overflow subtraction (&-)
// Overflow multiplication (&*)
// Overflow division (&/)
// Overflow remainder (&%)
var potentialOverflow = Int16.max
// potentialOverflow += 1 // This causes an error if it runs
var willOverflow = UInt8.max
willOverflow = willOverflow &+ 1
// Value Underflow
var willUnderflow = UInt8.min
willUnderflow = willUnderflow &- 1
var signedUnderflow = Int8.min
signedUnderflow = signedUnderflow &- 1
// Division by Zero
// Dividing a number by zero (i / 0), or trying to calculate remainder by zero (i % 0), causes an error:
let x = 1
//let y = x / 0 // This causes an error
// However, the overflow versions of these operators (&/ and &%) return a value of zero if you divide by zero:
let y = x &/ 0
// Precedence and Associativity
// Operator associativity defines how operators of the same precedence are grouped together (or associated)—either grouped from the left, or grouped from the right. Think of it as meaning “they associate with the expression to their left,” or “they associate with the expression to their right.
2 + 3 * 4 % 5
// * and % have a higher precedence than +.
// * and & have the same precendence as each other but both associate to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left: (This explanation seems arbitrary to me. Aparently more info in the Expressions chapter)
// Operator Functions
// Infix Operators
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y:4.0)
let combinedVector = vector + anotherVector
// Prefix and Postfix Operators
prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
let alsoPositive = -negative
// Compound Assignment Operators
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
prefix func ++ (inout vector: Vector2D) -> Vector2D {
vector += Vector2D(x: 1.0, y: 1.0)
return vector
}
var toIncrement = Vector2D(x: 3.0, y: 4.0)
let afterIncrement = ++toIncrement
// It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.
// Equivalence Operators
// Custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator (==) and “not equal to” operator (!=).
func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
func != (left: Vector2D, right: Vector2D) -> Bool {
return !(left == right)
}
let twoThree = Vector2D(x: 2.0, y: 3.0)
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
if twoThree == anotherTwoThree {
println("These two vectors are equivilent.")
}
// Custom Operators
// Custom operators can be defined only with the characters / = - + * % < > ! & | ^ . ~
// +++ prefix doubling incrementer
prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) -> Vector2D {
vector += vector
return vector
}
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// Precedence and Associativity for Custom Infix Operators
infix operator +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
| mit | f5d1545c39bc9ce19d33751e1438d0ab | 29.852941 | 361 | 0.71001 | 3.459763 | false | false | false | false |
uasys/swift | test/SILGen/generic_witness.swift | 1 | 2501 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible }
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr immutable_access [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumA2A3InkRzAA3Pen5PaintRpzlAaEP4drawy6StrokeQyd__5paint_qd__6penciltAA6PencilRd__7Texture_AHQZAMRSlFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4drawy5PaintQz5paint_qd__6penciltAA6PencilRd__6StrokeQyd__AFRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| apache-2.0 | 2fda1b17181374fc66243c53455ce8fe | 43.053571 | 372 | 0.631942 | 2.775028 | false | false | false | false |
BenziAhamed/Tracery | CommonTesting/TraceryioSamples.swift | 1 | 4276 | //
// TraceryioSamples.swift
// Tracery
//
// Created by Benzi on 11/03/17.
// Copyright © 2017 Benzi Ahamed. All rights reserved.
//
import XCTest
@testable import Tracery
class TraceryioSamples: XCTestCase {
func testDefaultAnimalExpansions() {
let animals = ["unicorn","raven","sparrow","scorpion","coyote","eagle","owl","lizard","zebra","duck","kitten"]
let t = Tracery {
[ "animal" : animals]
}
for _ in 0..<animals.count {
XCTAssertItemInArray(item: t.expand("#animal#"), array: animals)
}
}
func testDefaultRulesWithinRules() {
let colors = ["orange","blue","white","black","grey","purple","indigo","turquoise"]
let animals = ["unicorn","raven","sparrow","scorpion","coyote","eagle","owl","lizard","zebra","duck","kitten"]
let natureNouns = ["ocean","mountain","forest","cloud","river","tree","sky","sea","desert"]
let names = ["Arjun","Yuuma","Darcy","Mia","Chiaki","Izzi","Azra","Lina"]
let t = Tracery{[
"sentence": ["The #color# #animal# of the #natureNoun# is called #name#"],
"color": colors,
"animal": animals,
"natureNoun": natureNouns,
"name": names
]}
let pattern = "^The \(colors.regexGenerateMatchesAnyItemPattern()) \(animals.regexGenerateMatchesAnyItemPattern()) of the \(natureNouns.regexGenerateMatchesAnyItemPattern()) is called \(names.regexGenerateMatchesAnyItemPattern())$"
let regex = try? NSRegularExpression(pattern: pattern, options: .useUnixLineSeparators)
let output = t.expand("#sentence#")
let match = regex?.firstMatch(in: output, options: NSRegularExpression.MatchingOptions.anchored, range: .init(location: 0, length: output.count))
XCTAssertNotNil(match?.numberOfRanges)
XCTAssertEqual(match!.numberOfRanges, 5)
}
//
// Hierarchical tag storage is present in Tracery
// as a consequence of issue 31
//
// https://github.com/galaxykate/tracery/issues/31
//
func testIssue31_HierarchicalTagsAllowBracesMatchingCrossingRuleLevels() {
let o = TraceryOptions()
o.tagStorageType = .heirarchical
let braces = ["<>","«»","𛰫𛰬","⌜⌝","ᙅᙂ","ᙦᙣ","⁅⁆","⌈⌉","⌊⌋","⟦⟧","⦃⦄","⦗⦘","⫷⫸"]
var braceTypes = braces
.map { braces -> String in
let open = braces.first!
let close = braces.last!
return "[open:\(open)][close:\(close)]"
}
// round and curly braces needs to be escaped
braceTypes.append("[open:\\(][close:\\)]")
braceTypes.append("[open:\\{][close:\\}]")
let t = Tracery(o) {[
"letter": ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P"],
"bracetypes": braceTypes,
"brace": [
"#open##symbol##origin##symbol##close# ",
"#open##symbol##close##origin##open##symbol##close# ",
"#open##symbol##origin##symbol##close##origin# ",
" ",
],
"origin": ["#[symbol:#letter#][#bracetypes#]brace#"]
]}
// Tracery.logLevel = .verbose
let output = t.expand("#origin#")
print(output)
XCTAssertFalse(output.contains("stack overflow"))
// track open and close
// of each brace
var stackOfBraces = [Character]()
func trackBraces(_ c: Character) {
braces
.filter {
$0.range(of: "\(c)") != nil
}
.forEach {
let leftBrace = $0[$0.startIndex]
if leftBrace == c {
stackOfBraces.append(c)
}
else {
let expected = stackOfBraces.popLast()
XCTAssertNotNil(expected)
XCTAssertEqual(expected!, leftBrace)
}
}
}
output.forEach { trackBraces($0) }
XCTAssertEqual(stackOfBraces.count, 0)
}
}
| mit | 1048548b7e814cb4bcf187dc7c3dfa57 | 37.081081 | 239 | 0.520464 | 4.189296 | false | true | false | false |
jpmhouston/GLNotificationBar | Example/GLNotificationBar/ViewController.swift | 1 | 5288 | //
// ViewController.swift
// GLNotificationBar
//
// Created by gokul on 11/11/2016.
// Copyright (c) 2016 gokul. All rights reserved.
//
import UIKit
import AVFoundation
import GLNotificationBar
class ViewController: UIViewController {
@IBOutlet weak var notificationTitle: UITextField!
@IBOutlet weak var notificationMessage: UITextField!
@IBOutlet weak var soundName: UITextField!
@IBOutlet weak var soundType: UITextField!
@IBOutlet weak var vibrate: UISwitch!
@IBOutlet weak var sound: UISwitch!
@IBOutlet weak var notificationAction: UISwitch!
@IBOutlet weak var timeOutLabel: UILabel!
@IBOutlet weak var stepper: UIStepper!
@IBOutlet weak var notificationBarType: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard(_:)))
self.view .addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showNotification(_ sender: AnyObject) {
var style:GLNotificationStyle!
if notificationBarType.selectedSegmentIndex == 0 {
style = .detailedBanner
}else{
style = .simpleBanner
}
let notificationBar = GLNotificationBar(title: notificationTitle.text, message:notificationMessage.text , preferredStyle:style) { (bool) in
let alert = UIAlertController(title: "Handler", message: "Catch didSelectNotification action in GLNotificationBar completion handler.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
if notificationAction.isOn {
//Type: .Cancel
notificationBar.addAction(GLNotifyAction(title: "Cancel", style: .cancel, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply a style that indicates the action cancels the operation and leaves things unchanged.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .Destructive
notificationBar.addAction(GLNotifyAction(title: "Destructive", style: .destructive, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: " Apply a style that indicates the action might change or delete data.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .Default
notificationBar.addAction(GLNotifyAction(title: "Default", style: .default, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply the default style to the action’s button.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .TextInput
notificationBar.addAction(GLNotifyAction(title: "Text Input", style: .textInput, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply a style that indicates the action opens an textinput field helps to respond notification as string.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
// //Type: .OnlyTextInput
//
// notificationBar.addAction(GLNotifyAction(title: "Reply", style: .OnlyTextInput, handler: { (result) in
// let alert = UIAlertController(title: result.actionTitle, message: " Apply a style which removes all other action added and simply adds text field as input to respond notification.", preferredStyle: .Alert)
// alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
// self.presentViewController(alert, animated: true, completion: nil)
// }))
}
notificationBar.showTime(stepper.value)
if sound.isOn {
notificationBar.notificationSound(soundName.text, ofType: soundType.text, vibrate: vibrate.isOn)
}
}
@IBAction func hideKeyboard(_ sender: UIButton!) {
self.view.endEditing(true)
}
@IBAction func timeOutInterval(_ sender: UIStepper) {
timeOutLabel.text = "Time out interval \(String(sender.value))"
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 3c94ae41cb899515c61bb5337488c3cc | 43.05 | 223 | 0.642073 | 4.968045 | false | false | false | false |
Ajunboys/actor-platform | actor-apps/app-ios/Actor/Controllers/Compose/GroupCreateViewController.swift | 25 | 6529 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
class GroupCreateViewController: AAViewController, UITextFieldDelegate {
private var addPhotoButton = UIButton()
private var avatarImageView = UIImageView()
private var hint = UILabel()
private var groupName = UITextField()
private var groupNameFieldSeparator = UIView()
private var image: UIImage?
override init(){
super.init(nibName: nil, bundle: nil)
self.navigationItem.title = NSLocalizedString("CreateGroupTitle", comment: "Compose Title")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: localized("NavigationNext"), style: UIBarButtonItemStyle.Plain, target: self, action: "doNext")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
view.addSubview(addPhotoButton)
view.addSubview(avatarImageView)
view.addSubview(hint)
view.addSubview(groupName)
view.addSubview(groupNameFieldSeparator)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 110, height: 110), false, 0.0);
var context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor);
CGContextFillEllipseInRect(context, CGRectMake(0.0, 0.0, 110.0, 110.0));
CGContextSetStrokeColorWithColor(context, UIColor.RGB(0xd9d9d9).CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextStrokeEllipseInRect(context, CGRectMake(0.5, 0.5, 109.0, 109.0));
let buttonImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
addPhotoButton.exclusiveTouch = true
addPhotoButton.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
addPhotoButton.addTarget(self, action: "photoTap", forControlEvents: UIControlEvents.TouchUpInside)
var addPhotoLabelFirst = UILabel()
addPhotoLabelFirst.text = NSLocalizedString("AuthProfileAddPhoto1", comment: "Title")
addPhotoLabelFirst.font = UIFont.systemFontOfSize(15.0)
addPhotoLabelFirst.backgroundColor = UIColor.clearColor()
addPhotoLabelFirst.textColor = UIColor.RGB(0xd9d9d9)
addPhotoLabelFirst.sizeToFit()
var addPhotoLabelSecond = UILabel()
addPhotoLabelSecond.text = NSLocalizedString("AuthProfileAddPhoto2", comment: "Title")
addPhotoLabelSecond.font = UIFont.systemFontOfSize(15.0)
addPhotoLabelSecond.backgroundColor = UIColor.clearColor()
addPhotoLabelSecond.textColor = UIColor.RGB(0xd9d9d9)
addPhotoLabelSecond.sizeToFit()
addPhotoButton.addSubview(addPhotoLabelFirst)
addPhotoButton.addSubview(addPhotoLabelSecond)
addPhotoLabelFirst.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelFirst.frame.size.width) / 2, 22, addPhotoLabelFirst.frame.size.width, addPhotoLabelFirst.frame.size.height));
addPhotoLabelSecond.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelSecond.frame.size.width) / 2, 22 + 22, addPhotoLabelSecond.frame.size.width, addPhotoLabelSecond.frame.size.height));
// groupName.backgroundColor = UIColor.whiteColor()
groupName.backgroundColor = MainAppTheme.list.bgColor
groupName.textColor = MainAppTheme.list.textColor
groupName.font = UIFont.systemFontOfSize(20)
groupName.keyboardType = UIKeyboardType.Default
groupName.returnKeyType = UIReturnKeyType.Next
groupName.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("CreateGroupNamePlaceholder", comment: "Enter group title"), attributes: [NSForegroundColorAttributeName: MainAppTheme.list.hintColor])
groupName.delegate = self
groupName.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
groupName.autocapitalizationType = UITextAutocapitalizationType.Words
groupNameFieldSeparator.backgroundColor = MainAppTheme.list.separatorColor
hint.text = localized("CreateGroupHint")
hint.font = UIFont.systemFontOfSize(15)
hint.lineBreakMode = .ByWordWrapping
hint.numberOfLines = 0
hint.textColor = MainAppTheme.list.hintColor
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let screenSize = UIScreen.mainScreen().bounds.size
avatarImageView.frame = CGRectMake(20, 20 + 66, 80, 80)
addPhotoButton.frame = avatarImageView.frame
hint.frame = CGRectMake(120, 20 + 66, screenSize.width - 140, 80)
groupName.frame = CGRectMake(20, 106 + 66, screenSize.width - 20, 56.0)
groupNameFieldSeparator.frame = CGRectMake(20, 156 + 66, screenSize.width - 20, 1)
}
func photoTap() {
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.avatarImageView.image != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.avatarImageView.image = nil
self.image = nil
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
self.image = image
self.avatarImageView.image = image.roundImage(80)
})
}
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
groupName.becomeFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
doNext()
return false
}
func doNext() {
var title = groupName.text.trim()
if (title.size() == 0) {
shakeView(groupName, originalX: groupName.frame.origin.x)
return
}
navigateNext(GroupMembersController(title: title, image: image), removeCurrent: true)
}
} | mit | 886c1d022d9e3b97ff16984e2913e7c6 | 43.726027 | 222 | 0.669168 | 5.436303 | false | false | false | false |
iankunneke/TIY-Assignmnts | CoreList/CoreList/CoreTableViewController.swift | 1 | 1997 | //
// CoreTableViewController.swift
// CoreList
//
// Created by ian kunneke on 7/29/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
protocol AddCoreDelegate
{
func coreWasMade(aCore: String)
}
class CoreTableViewController: UITableViewController, AddCoreDelegate
{
var cores = [NSManagedObject]()
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return cores.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CoreCell", forIndexPath: indexPath) as! UITableViewCell
let core = cores[indexPath.row]
cell.textLabel!.text = core.valueForKey("name") as? String
return cell
}
func coreWasMade(aCore: String)
{
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("Core",inManagedObjectContext: managedContext)
let core = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
cores.append(core)
tableView.reloadData()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "AddCoreSegue"
{
let destVC = segue.destinationViewController as! AddCoreViewController
destVC.delegate = self
}
}
}
| cc0-1.0 | 2c733183a8f0dabf53921d01797e639a | 23.060241 | 119 | 0.670506 | 5.173575 | false | false | false | false |
DigitasLabsParis/UnicornHorn | iOSApp/BLE Test/DeviceInfoViewController.swift | 1 | 8710 | //
// DeviceInfoViewController.swift
// Adafruit Bluefruit LE Connect
//
// Displays CBPeripheral Services & Characteristics in a UITableView
//
// Created by Collin Cunningham on 10/24/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import UIKit
import CoreBluetooth
class DeviceInfoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HelpViewControllerDelegate{
@IBOutlet var tableView:UITableView!
@IBOutlet var headerView:UIView!
@IBOutlet var peripheralNameLabel:UILabel!
@IBOutlet var peripheralUUIDLabel:UILabel!
@IBOutlet var helpViewController:HelpViewController!
var delegate:HelpViewControllerDelegate?
// @IBOutlet var serviceCell:UITableViewCell!
// @IBOutlet var characteristicCell:UITableViewCell!
let serviceCellIdentifier = "serviceCell"
let characteristicCellIdentifier = "characteristicCell"
var peripheral:CBPeripheral!
var gattDict:Dictionary<String,String>? //known UUID reference
var serviceToggle:[Bool]! //individual ref for service is open in table
convenience init(cbPeripheral:CBPeripheral, delegate:HelpViewControllerDelegate){
//Separate NIBs for iPhone 3.5", iPhone 4", & iPad
var nibName:NSString
if IS_IPHONE{
nibName = "DeviceInfoViewController_iPhone"
}
else{ //IPAD
nibName = "DeviceInfoViewController_iPad"
}
self.init(nibName: nibName, bundle: NSBundle.mainBundle())
self.peripheral = cbPeripheral
self.delegate = delegate
if let path = NSBundle.mainBundle().pathForResource("GATT-characteristics", ofType: "plist") {
if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, String> {
self.gattDict = dict
}
}
self.serviceToggle = [Bool](count: peripheral.services.count, repeatedValue: false)
}
// convenience init(delegate:HelpViewControllerDelegate){ //FOR SCREENSHOTS
//
// //Separate NIBs for iPhone 3.5", iPhone 4", & iPad
//
// var nibName:NSString
//
// if IS_IPHONE{
// nibName = "DeviceInfoViewController_iPhone"
// }
// else{ //IPAD
// nibName = "DeviceInfoViewController_iPad"
// }
//
// self.init(nibName: nibName, bundle: NSBundle.mainBundle())
//
// self.peripheral = CBPeripheral()
//
// self.delegate = delegate
// }
override func viewDidLoad() {
super.viewDidLoad()
self.helpViewController.delegate = delegate
self.title = peripheral.name
let tvc = UITableViewController(style: UITableViewStyle.Plain)
tvc.tableView = tableView
peripheralNameLabel.text = peripheral.name
peripheralUUIDLabel.text = "UUID: " + peripheral.identifier.UUIDString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var service = peripheral.services[indexPath.section] as CBService
var identifier = characteristicCellIdentifier
var style = UITableViewCellStyle.Subtitle
var title = ""
var detailTitle = ""
var selectable = false
//Service row
if indexPath.row == 0 {
identifier = serviceCellIdentifier
// style = UITableViewCellStyle.Default
title = displayNameforUUID(service.UUID)
detailTitle = "Service"
selectable = true
}
//Characteristic row
else {
let chstc = service.characteristics[indexPath.row-1] as CBCharacteristic
// let dsctr = chstc.descriptors[0] as CBDescriptor
// let uuidString = chstc.UUID.UUIDString
title = displayNameforUUID(chstc.UUID)
if chstc.value != nil { detailTitle = chstc.value.stringRepresentation() }
else { detailTitle = "Characteristic" }
}
var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: style, reuseIdentifier: identifier)
}
//Set up cell
cell?.textLabel.adjustsFontSizeToFitWidth = true
cell?.textLabel.minimumScaleFactor = 0.5
cell?.textLabel.text = title
cell?.detailTextLabel?.text = detailTitle
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell?.userInteractionEnabled = selectable
return cell!
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return peripheral.services.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let service = peripheral.services[section] as? CBService {
//service is open/being viewed
if serviceToggle[section] == true {
return service.characteristics.count + 1
}
//service is closed
else {
return 1
}
}
else {
return 0
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.5
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.5
}
func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.row == 0 {
return 0
}
else {
return 2
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
if let charCount = peripheral.services[section].characteristics?.count {
var attributePathArray:[NSIndexPath] = []
for i in 1...(charCount) {
attributePathArray.append(NSIndexPath(forRow: i, inSection: indexPath.section))
}
//make cell background blue
// tableView.cellForRowAtIndexPath(indexPath)?.backgroundColor = cellSelectionColor
// let cell = tableView.cellForRowAtIndexPath(indexPath)!
// UIView.animateWithDuration(0.25, animations: { () -> Void in
// cell.backgroundColor = UIColor.whiteColor()
// })
animateCellSelection(tableView.cellForRowAtIndexPath(indexPath)!)
tableView.beginUpdates()
if (serviceToggle[section] == true) {
serviceToggle[section] = false
tableView.deleteRowsAtIndexPaths(attributePathArray, withRowAnimation: UITableViewRowAnimation.Fade)
}
else {
serviceToggle[section] = true
tableView.insertRowsAtIndexPaths(attributePathArray, withRowAnimation: UITableViewRowAnimation.Fade)
}
tableView.endUpdates()
}
// tableView.beginUpdates()
// tableView.reloadSection(NSIndexSet(indexesInRange: NSMakeRange(section, section)), withRowAnimation: UITableViewRowAnimation.Fade)
// serviceToggle[section] = !serviceToggle[section]
// tableView.endUpdates()
}
func helpViewControllerDidFinish(controller : HelpViewController){
}
func displayNameforUUID(uuid:CBUUID)->String {
let uuidString = uuid.UUIDString
//Check for matching name
//Find description for UUID
//Old method
// var name:String?
// for idx in 0...(knownUUIDs.count-1) {
// if UUIDsAreEqual(uuid, knownUUIDs[idx]) {
// name = knownUUIDNames[idx]
// break
// }
// }
//use UUID if no name is found
// if name == nil {
// name = uuid.UUIDString
// }
//New method
if let name = gattDict?[uuidString] {
return name
}
else {
return uuidString
}
}
}
| apache-2.0 | 70739aa9e8e938c42219717710363d40 | 30.557971 | 140 | 0.590586 | 5.519645 | false | false | false | false |
abunur/quran-ios | VFoundation/String+Extension.swift | 1 | 2167 | //
// String+Extension.swift
// Quran
//
// Created by Mohamed Afifi on 2/25/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import Foundation
extension String {
public var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
public var pathExtension: String {
return (self as NSString).pathExtension
}
public var stringByDeletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
public var stringByDeletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
public var pathComponents: [String] {
return (self as NSString).pathComponents
}
public func stringByAppendingPath(_ path: String) -> String {
return (self as NSString).appendingPathComponent(path)
}
public func stringByAppendingExtension(_ pathExtension: String) -> String {
return (self as NSString).appendingPathExtension(pathExtension) ?? (self + "." + pathExtension)
}
public func byteOffsetToStringIndex(_ byteOffset: Int) -> String.Index? {
let index = utf8.index(utf8.startIndex, offsetBy: byteOffset)
return index.samePosition(in: self)
}
public func rangeAsNSRange(_ range: Range<String.Index>) -> NSRange {
let rangeStartIndex = range.lowerBound
let rangeEndIndex = range.upperBound
let start = distance(from: startIndex, to: rangeStartIndex)
let length = distance(from: rangeStartIndex, to: rangeEndIndex)
return NSRange(location: start, length: length)
}
}
| gpl-3.0 | 6d77cffab86fd7394faa7724e6dfbac6 | 32.859375 | 103 | 0.699585 | 4.620469 | false | false | false | false |
between40and2/XALG | frameworks/Framework-XALG/Tree/Rep/XALG_Rep_Tree_HuffmanTree.swift | 1 | 1301 | //
// XALG_Rep_Tree_HuffmanTree.swift
// XALG
//
// Created by Juguang Xiao on 03/03/2017.
//
import Swift
class XALG_Rep_Tree_HuffmanTree<Payload> {
typealias NodeType = XALG_Rep_TreeNode_HuffmanTree<Payload>
private var _rootNode : NodeType?
var rootNode : NodeType? {
return _rootNode
}
// p
func buildTree(elements : [Payload], weights: [Int]) {
var pq = XALG_Rep_PriorityQueue__Heap<NodeType>()
{ (a, b) -> Bool in a.weight < b.weight
}
for (e, w) in zip(elements, weights) {
let node = NodeType(payload: e)
// node.payload = e
node.weight = w
pq.enqueue(node)
}
while pq.count > 1 {
let left = pq.dequeue()! // left > right
let right = pq.dequeue()!
let parent = NodeType()
parent.lchild = left
parent.rchild = right
parent.weight = left.weight + right.weight
pq.enqueue(parent)
}
_rootNode = pq.dequeue()!
}
}
class XALG_Rep_TreeNode_HuffmanTree<Payload> : XALG_Rep_TreeNode_BinaryTree<Payload> {
var weight : Int = -1 // or called count
}
| mit | 5abf2edeb7439190bc5fcc204d06a32e | 22.232143 | 86 | 0.509608 | 4.040373 | false | false | false | false |
shajrawi/swift | test/attr/attr_inlinable.swift | 1 | 8676 | // RUN: %target-typecheck-verify-swift -swift-version 5
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-testing
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -enable-testing
@inlinable struct TestInlinableStruct {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to this declaration}}
@inlinable @usableFromInline func redundantAttribute() {}
// expected-warning@-1 {{'@inlinable' declaration is already '@usableFromInline'}}
private func privateFunction() {}
// expected-note@-1{{global function 'privateFunction()' is not '@usableFromInline' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1{{global function 'fileprivateFunction()' is not '@usableFromInline' or public}}
func internalFunction() {}
// expected-note@-1{{global function 'internalFunction()' is not '@usableFromInline' or public}}
@usableFromInline func versionedFunction() {}
public func publicFunction() {}
private struct PrivateStruct {}
// expected-note@-1 3{{struct 'PrivateStruct' is not '@usableFromInline' or public}}
struct InternalStruct {}
// expected-note@-1 3{{struct 'InternalStruct' is not '@usableFromInline' or public}}
@usableFromInline struct VersionedStruct {
@usableFromInline init() {}
}
public struct PublicStruct {
public init() {}
@inlinable public var storedProperty: Int
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
@inlinable public lazy var lazyProperty: Int = 0
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
public func publicInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@usableFromInline' or public}}
@_transparent
@usableFromInline
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
func internalInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@inlinable
private func privateInlinableMethod() {
// expected-error@-2 {{'@inlinable' attribute can only be applied to public declarations, but 'privateInlinableMethod' is private}}
struct Nested {}
// OK
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @usableFromInline attribute).
@usableFromInline
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@usableFromInline' or public}}
@inlinable
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@inlinable' function}}
return requirement()
}
}
enum InternalEnum {
// expected-note@-1 2{{enum 'InternalEnum' is not '@usableFromInline' or public}}
// expected-note@-2 {{type declared here}}
case apple
case orange
}
@inlinable public func usesInternalEnum() {
_ = InternalEnum.apple
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
let _: InternalEnum = .orange
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
}
@usableFromInline enum VersionedEnum {
case apple
case orange
case pear(InternalEnum)
// expected-error@-1 {{type of enum case in '@usableFromInline' enum must be '@usableFromInline' or public}}
case persimmon(String)
}
@inlinable public func usesVersionedEnum() {
_ = VersionedEnum.apple
let _: VersionedEnum = .orange
_ = VersionedEnum.persimmon
}
// Inherited initializers - <rdar://problem/34398148>
@usableFromInline
@_fixed_layout
class Base {
@usableFromInline
init(x: Int) {}
}
@usableFromInline
@_fixed_layout
class Middle : Base {}
@usableFromInline
@_fixed_layout
class Derived : Middle {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// More inherited initializers
@_fixed_layout
public class Base2 {
@inlinable
public init(x: Int) {}
}
@_fixed_layout
@usableFromInline
class Middle2 : Base2 {}
@_fixed_layout
@usableFromInline
class Derived2 : Middle2 {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// Stored property initializer expressions.
//
// Note the behavior here does not depend on the state of the -enable-library-evolution
// flag; the test runs with both the flag on and off. Only the explicit
// presence of a '@_fixed_layout' attribute determines the behavior here.
let internalGlobal = 0
// expected-note@-1 {{let 'internalGlobal' is not '@usableFromInline' or public}}
public let publicGlobal = 0
struct InternalStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
public struct PublicResilientStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
private func privateIntReturningFunc() -> Int { return 0 }
internal func internalIntReturningFunc() -> Int { return 0 }
@_fixed_layout
public struct PublicFixedStructWithInit {
var x = internalGlobal // expected-error {{let 'internalGlobal' is internal and cannot be referenced from a property initializer in a '@_fixed_layout' type}}
var y = publicGlobal // OK
static var z = privateIntReturningFunc() // OK
static var a = internalIntReturningFunc() // OK
}
public struct KeypathStruct {
var x: Int
// expected-note@-1 {{property 'x' is not '@usableFromInline' or public}}
@inlinable public func usesKeypath() {
_ = \KeypathStruct.x
// expected-error@-1 {{property 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
public struct HasInternalSetProperty {
public internal(set) var x: Int // expected-note {{setter for 'x' is not '@usableFromInline' or public}}
@inlinable public mutating func setsX() {
x = 10 // expected-error {{setter for 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
@usableFromInline protocol P {
typealias T = Int
}
extension P {
@inlinable func f() {
_ = T.self // ok, typealias inherits @usableFromInline from P
}
}
| apache-2.0 | fbd3b60dc4e3c122e02129f1307194e4 | 31.252788 | 159 | 0.713117 | 4.338 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/General/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallPulseSync.swift | 66 | 1944 | //
// NVActivityIndicatorAnimationBallPulseSync.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallPulseSync: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - circleSize) / 2
let deltaY = (size.height / 2 - circleSize / 2) / 2
let duration: CFTimeInterval = 0.6
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.07, 0.14, 0.21]
let timingFunciton = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctions = [timingFunciton, timingFunciton, timingFunciton]
animation.values = [0, deltaY, -deltaY, 0]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw circles
for var i = 0; i < 3; i++ {
let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
| apache-2.0 | 434d6951beb94c3b942682d66da07398 | 39.5 | 139 | 0.631687 | 4.718447 | false | false | false | false |
teknologika/Roomy | roomy/AppDelegate.swift | 1 | 1204 | //
// AppDelegate.swift
// roomy
//
// Created by Bruce McLeod on 2/11/2015.
// Copyright © 2015 Bruce McLeod. All rights reserved.
//
import UIKit
let LAST_HOUR = 18
let EARLIEST_HOUR = 8
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var idleTimerControlTimer: NSTimer?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().idleTimerDisabled = true
self.idleTimerControlTimer = NSTimer.init(timeInterval: 60, target: self, selector: "setIdleTimerDisabledWithTimeOfDay", userInfo: nil, repeats: true)
self.setIdleTimerDisabledWithTimeOfDay()
return true
}
func setIdleTimerDisabledWithTimeOfDay() {
let now = NSCalendar.autoupdatingCurrentCalendar().components(NSCalendarUnit.Hour, fromDate: NSDate.init())
var disabled = true
if (now.hour >= LAST_HOUR || now.hour <= EARLIEST_HOUR) {
disabled = false
}
UIApplication.sharedApplication().idleTimerDisabled = disabled
}
}
| mit | 73912bd0438e4c5da29549db1c28586b | 25.152174 | 158 | 0.674979 | 4.73622 | false | false | false | false |
ngageoint/mage-ios | MageTests/Settings/Map/MapSettingsTests.swift | 1 | 2354 | //
// MapSettingsTests.swift
// MAGETests
//
// Created by Daniel Barela on 9/24/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import Quick
import Nimble
import PureLayout
import OHHTTPStubs
import Kingfisher
@testable import MAGE
class MapSettingsTests: KIFSpec {
override func spec() {
describe("MapSettingsTests") {
var mapSettings: MapSettings!
var window: UIWindow!;
beforeEach {
TestHelpers.clearAndSetUpStack();
MageCoreDataFixtures.quietLogging();
UserDefaults.standard.baseServerUrl = "https://magetest";
UserDefaults.standard.mapType = 0;
UserDefaults.standard.locationDisplay = .latlng;
Server.setCurrentEventId(1);
window = TestHelpers.getKeyWindowVisible();
MageCoreDataFixtures.addEvent();
}
afterEach {
FeedService.shared.stop();
HTTPStubs.removeAllStubs();
TestHelpers.clearAndSetUpStack();
MageCoreDataFixtures.clearAllData();
}
it("should unselect a feed") {
waitUntil { done in
MageCoreDataFixtures.addFeedToEvent(eventId: 1, id: "1", title: "My Feed", primaryProperty: "primary", secondaryProperty: "secondary") { (success: Bool, error: Error?) in
done();
}
}
UserDefaults.standard.set(["1"], forKey: "selectedFeeds-1");
mapSettings = MapSettings();
mapSettings.applyTheme(withContainerScheme: MAGEScheme.scheme())
window.rootViewController = mapSettings;
tester().waitForAnimationsToFinish();
tester().waitForView(withAccessibilityLabel: "feed-switch-1");
tester().setOn(false, forSwitchWithAccessibilityLabel: "feed-switch-1");
let selected = UserDefaults.standard.array(forKey: "selectedFeeds-1");
expect(selected).to(beEmpty());
}
}
}
}
| apache-2.0 | b7268f67f8a2a491e487e6efbcb4d7f3 | 33.101449 | 190 | 0.539737 | 6.017903 | false | true | false | false |
MChainZhou/DesignPatterns | Memo/Memo/Simple_2_加强案例/Simple_2_优化案例/BankAccountOriginator.swift | 1 | 1225 | //
// BankAccountOriginator.swift
// Memo
//
// Created by apple on 2017/8/31.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
class BankAccountOriginator: OriginatorProtocol {
//账户对象集合(字典)
//key-value形式(多个)
var entries = [Int:BankAccount]()
//账户id增长属性
var nextId:Int = 1
//总金额
var total:Float = 0
//添加账号
func addEntry(name:String,amount:Float,time:String) {
let entry = BankAccount(id: nextId, name: name, amonut: amount, time: time)
entries[nextId] = entry
nextId += 1
self.total += amount
}
func createMemo() -> MemoProtocol {
return BankAccountMemo(originator: self)
}
func applyMemo(memo: MemoProtocol) {
if let m = memo as? BankAccountMemo {
m.apply(originator: self)
}
}
//输出
func printEntries() {
for entry in self.entries.values.sorted(by: { (b1, b2) -> Bool in
return b1.id < b2.id
}) {
print("id:\(entry.id) 姓名:\(entry.name) 金额:\(entry.amonut) 时间:\(entry.time)")
}
print("--------------------------")
}
}
| mit | 3973aab45661b263fb076f44fa4f8629 | 23.083333 | 88 | 0.550173 | 3.623824 | false | false | false | false |
fabiomassimo/eidolon | KioskTests/Models/SaleArtworkTests.swift | 1 | 5077 | import Quick
import Nimble
import Kiosk
class SaleArtworkTests: QuickSpec {
override func spec() {
var saleArtwork: SaleArtwork!
beforeEach {
let artwork = Artwork.fromJSON([:]) as! Artwork
saleArtwork = SaleArtwork(id: "id", artwork: artwork)
}
it("updates the soldStatus") {
let newArtwork = Artwork.fromJSON([:]) as! Artwork
newArtwork.soldStatus = "sold"
let newSaleArtwork = SaleArtwork(id: "id", artwork: newArtwork)
saleArtwork.updateWithValues(newSaleArtwork)
expect(newSaleArtwork.artwork.soldStatus) == "sold"
}
describe("estimates") {
it("gives no estimtates when no estimates present") {
expect(saleArtwork.estimateString) == "No Estimate"
}
it("gives estimtates when low and high are present") {
saleArtwork.lowEstimateCents = 100_00
saleArtwork.highEstimateCents = 200_00
expect(saleArtwork.estimateString) == "Estimate: $100–$200"
}
it("gives estimtates when low is present") {
saleArtwork.lowEstimateCents = 100_00
expect(saleArtwork.estimateString) == "Estimate: $100"
}
it("gives estimtates when high is present") {
saleArtwork.highEstimateCents = 200_00
expect(saleArtwork.estimateString) == "Estimate: $200"
}
it("indicates that an artwork is not for sale") {
saleArtwork.artwork.soldStatus = "sold"
expect((saleArtwork.forSaleSignal.first() as! Bool)).toEventually( beFalse() )
}
it("indicates that an artwork is for sale") {
saleArtwork.artwork.soldStatus = "anything else"
expect((saleArtwork.forSaleSignal.first() as! Bool)).toEventually( beTrue() )
}
}
describe("reserve status") {
it("gives default number of bids") {
let reserveStatus = saleArtwork.numberOfBidsWithReserveSignal.first() as! String
expect(reserveStatus) == "0 bids placed"
}
describe("with some bids") { () -> Void in
beforeEach {
saleArtwork.bidCount = 1
}
it("gives default number of bids") {
let reserveStatus = saleArtwork.numberOfBidsWithReserveSignal.first() as! String
expect(reserveStatus) == "1 bid placed"
}
it("updates reserve status when reserve status changes") {
var reserveStatus = ""
saleArtwork.numberOfBidsWithReserveSignal.subscribeNext { (newReserveStatus) -> Void in
reserveStatus = newReserveStatus as! String
}
saleArtwork.reserveStatus = ReserveStatus.ReserveNotMet.rawValue
expect(reserveStatus) == "(1 bid placed, Reserve not met)"
}
it("sends new status when reserve status changes") {
var invocations = 0
saleArtwork.numberOfBidsWithReserveSignal.subscribeNext { (newReserveStatus) -> Void in
invocations++
}
saleArtwork.reserveStatus = ReserveStatus.ReserveNotMet.rawValue
// Once for initial subscription, another for update.
expect(invocations) == 2
}
it("updates reserve status when number of bids changes") {
var reserveStatus = ""
saleArtwork.numberOfBidsWithReserveSignal.subscribeNext { (newReserveStatus) -> Void in
reserveStatus = newReserveStatus as! String
}
saleArtwork.bidCount = 2
expect(reserveStatus) == "2 bids placed"
}
it("sends new status when number of bids changes") {
var invocations = 0
saleArtwork.numberOfBidsWithReserveSignal.subscribeNext { (newReserveStatus) -> Void in
invocations++
}
saleArtwork.bidCount = 2
// Once for initial subscription, another for update.
expect(invocations) == 2
}
it("sends new status when highest bid changes") {
var invocations = 0
saleArtwork.numberOfBidsWithReserveSignal.subscribeNext { (newReserveStatus) -> Void in
invocations++
}
saleArtwork.highestBidCents = 1_00
// Once for initial subscription, another for update.
expect(invocations) == 2
}
}
}
}
}
| mit | 9d5bb032911273964f6db0d555a9fead | 36.043796 | 107 | 0.523744 | 5.846774 | false | false | false | false |
tavon321/GluberLabConceptTest | GluberLabConceptTest/GluberLabConceptTest/SplashViewController.swift | 1 | 1475 | //
// SplashViewController.swift
// GluberLabConceptTest
//
// Created by Jaime Laino on 4/19/17.
// Copyright © 2017 Gustavo Mario Londoño Correa. All rights reserved.
//
import UIKit
final class SplashViewController: UIViewController {
fileprivate var firebaseLoginContoller : FirebaseLoginController!
override func viewDidLoad() {
super.viewDidLoad()
configureLogin()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
func signOut() {
firebaseLoginContoller.signOut()
}
@IBAction func unwindToSplash(segue: UIStoryboardSegue) {}
}
private extension SplashViewController {
func configureLogin() {
firebaseLoginContoller = FirebaseLoginController()
firebaseLoginContoller.loginStateDidChange = {
[weak self] user in
self?.updateUI()
}
}
func updateUI() {
guard firebaseLoginContoller.user == nil else {
performSegue(withIdentifier: AppSegueID.showTabController.rawValue, sender: nil)
return
}
presentLogin()
}
func presentLogin() {
let loginViewController = firebaseLoginContoller.authViewController() as! UINavigationController
loginViewController.setNavigationBarHidden(true, animated: true)
present(loginViewController, animated: true, completion: nil)
}
}
| mit | 6a03ada27b235b57cccbc43020406107 | 25.781818 | 104 | 0.65852 | 5.15035 | false | false | false | false |
firebase/FirebaseUI-iOS | samples/swift/FirebaseUI-demo-swift/Samples/Auth/FUICustomPasswordRecoveryViewController.swift | 1 | 2497 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseEmailAuthUI
class FUICustomPasswordRecoveryViewController: FUIPasswordRecoveryViewController, UITextFieldDelegate {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var recoverButton: UIBarButtonItem!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, authUI: FUIAuth, email: String?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil, authUI: authUI, email: email)
emailTextField.text = email
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
//override action of default 'Next' button to use custom layout elements'
self.navigationItem.rightBarButtonItem?.target = self
self.navigationItem.rightBarButtonItem?.action = #selector(onRecover(_:))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//update state of all UI elements (e g disable 'Next' buttons)
self.updateEmailValue(emailTextField)
}
@IBAction func onBack(_ sender: AnyObject) {
self.onBack()
}
@IBAction func onRecover(_ sender: AnyObject) {
if let email = emailTextField.text {
self.recoverEmail(email)
}
}
@IBAction func onCancel(_ sender: AnyObject) {
self.cancelAuthorization()
}
@IBAction func updateEmailValue(_ sender: UITextField) {
if emailTextField == sender, let email = emailTextField.text {
recoverButton.isEnabled = !email.isEmpty
self.didChangeEmail(email)
}
}
@IBAction func onViewSelected(_ sender: AnyObject) {
emailTextField.resignFirstResponder()
}
// MARK: - UITextFieldDelegate methods
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField, let email = textField.text {
self.recoverEmail(email)
}
return false
}
}
| apache-2.0 | a3ef8ab0edf7717f958275507afb0f96 | 29.45122 | 113 | 0.722066 | 4.50722 | false | false | false | false |
BronxDupaix/WaffleLuv | WaffleLuv/InstaPhotosCollectionViewController.swift | 1 | 2658 | //
// InstaPhotosCollectionViewController.swift
// WaffleLuv
//
// Created by Bronson Dupaix on 4/11/16.
// Copyright © 2016 Bronson Dupaix. All rights reserved.
//
import UIKit
import QuartzCore
private let reuseIdentifier = "Cell"
class InstaPhotosCollectionViewController: UICollectionViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
var instaApi = Instagram()
override func viewDidLoad() {
super.viewDidLoad()
if DataStore.sharedInstance.instaPhotos.count <= 19 {
instaApi.fetchInstaPhotos()
print("Photos fetched")
}
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DataStore.sharedInstance.instaPhotos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let photo = DataStore.sharedInstance.instaPhotos[indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as? photoCollectionViewCell
cell?.photo.image = nil
cell?.photo.layer.cornerRadius = 20
cell!.photo.image = photo.image
return cell!
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = self.view.frame.size
return CGSizeMake(size.width / 2.02, size.width / 2.02)
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func collectionView(collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 3
}
}
| apache-2.0 | 6bc1bc724ac4261a7f7afe45f0e14ecd | 29.193182 | 169 | 0.674445 | 5.997743 | false | false | false | false |
zhiquan911/chance_btc_wallet | chance_btc_wallet/chance_btc_wallet/lib/3rd/SwiftQRCode/QRCode.swift | 1 | 10040 | //
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
open class QRCode: NSObject, AVCaptureMetadataOutputObjectsDelegate {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// auto remove sub layers when detection completed
var autoRemoveSubLayers: Bool
/// completion call back
var completedCallBack: ((_ stringValue: String) -> ())?
/// the scan rect, default is the bounds of the scan view, can modify it if need
open var scanFrame: CGRect = CGRect.zero
/// init function
///
/// - returns: the scanner object
public override init() {
self.lineWidth = 4
self.strokeColor = UIColor.green
self.maxDetectedCount = 20
self.autoRemoveSubLayers = false
super.init()
}
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(autoRemoveSubLayers: Bool, lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.green, maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
self.autoRemoveSubLayers = autoRemoveSubLayers
}
deinit {
if session.isRunning {
session.stopRunning()
}
removeAllLayers()
}
// MARK: - Generate QRCode Image
/// generate image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
///
/// - returns: the generated image
class open func generateImage(_ stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25) -> UIImage? {
return generateImage(stringValue, avatarImage: avatarImage, avatarScale: avatarScale, color: CIColor(color: UIColor.black), backColor: CIColor(color: UIColor.white))
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class open func generateImage(_ stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor, backColor: CIColor) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(stringValue.data(using: String.Encoding.utf8, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransform(scaleX: 10, y: 10)
let transformedImage = qrFilter.outputImage!.transformed(by: transform)
let image = UIImage(ciImage: transformedImage)
if avatarImage != nil {
return insertAvatarImage(image, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(_ codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.draw(in: rect)
let avatarSize = CGSize(width: rect.size.width * scale, height: rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.draw(in: CGRect(x: x, y: y, width: avatarSize.width, height: avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
// MARK: - Video Scan
/// prepare scan
///
/// - parameter view: the scan view, the preview layer and the drawing layer will be insert into this view
/// - parameter completion: the completion call back
open func prepareScan(_ view: UIView, completion:@escaping (_ stringValue: String)->()) {
scanFrame = view.bounds
completedCallBack = completion
currentDetectedCount = 0
setupSession()
setupLayers(view)
}
/// start scan
open func startScan() {
clearDrawLayer()
if session.isRunning {
print("the capture session is running")
return
}
session.startRunning()
}
/// stop scan
open func stopScan() {
if !session.isRunning {
print("the capture session is not running")
return
}
session.stopRunning()
}
func setupLayers(_ view: UIView) {
drawLayer.frame = view.bounds
view.layer.insertSublayer(drawLayer, at: 0)
previewLayer.frame = view.layer.bounds
view.layer.insertSublayer(previewLayer, at: 0)
}
func setupSession() {
if session.isRunning {
print("the capture session is running")
return
}
if !session.canAddInput(videoInput!) {
print("can not add input device")
return
}
if !session.canAddOutput(dataOutput) {
print("can not add output device")
return
}
session.addInput(videoInput!)
session.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes;
dataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
}
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
clearDrawLayer()
for dataObject in metadataObjects {
if let codeObject = dataObject as? AVMetadataMachineReadableCodeObject,
let obj = previewLayer.transformedMetadataObject(for: codeObject) as? AVMetadataMachineReadableCodeObject {
if scanFrame.contains(obj.bounds) {
currentDetectedCount = currentDetectedCount + 1
if currentDetectedCount > maxDetectedCount {
session.stopRunning()
completedCallBack!(codeObject.stringValue!)
if autoRemoveSubLayers {
removeAllLayers()
}
}
// transform codeObject
drawCodeCorners(previewLayer.transformedMetadataObject(for: codeObject) as! AVMetadataMachineReadableCodeObject)
}
}
}
}
open func removeAllLayers() {
previewLayer.removeFromSuperlayer()
drawLayer.removeFromSuperlayer()
}
func clearDrawLayer() {
if drawLayer.sublayers == nil {
return
}
for layer in drawLayer.sublayers! {
layer.removeFromSuperlayer()
}
}
func drawCodeCorners(_ codeObject: AVMetadataMachineReadableCodeObject) {
if codeObject.corners.count == 0 {
return
}
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.path = createPath(codeObject.corners as NSArray).cgPath
drawLayer.addSublayer(shapeLayer)
}
func createPath(_ points: NSArray) -> UIBezierPath {
let path = UIBezierPath()
var point = points[0] as! CGPoint
path.move(to: point)
var index = 1
while index < points.count {
point = points[index] as! CGPoint
path.addLine(to: point)
index = index + 1
}
path.close()
return path
}
/// previewLayer
lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
return layer
}()
/// drawLayer
lazy var drawLayer = CALayer()
/// session
lazy var session = AVCaptureSession()
/// input
lazy var videoInput: AVCaptureDeviceInput? = {
if let device = AVCaptureDevice.default(for: .video) {
return try? AVCaptureDeviceInput(device: device)
}
return nil
}()
/// output
lazy var dataOutput = AVCaptureMetadataOutput()
}
| mit | 1ef5f37d01a4be143cb8e936059209d7 | 32.898649 | 173 | 0.599263 | 5.519252 | false | false | false | false |
JohnSundell/SwiftKit | Source/Shared/Direction.swift | 1 | 7381 | import Foundation
import CoreGraphics
import Unbox
/// Protocol defining shared APIs for Direction types
public protocol DirectionType: RawRepresentable, Hashable, StringConvertible, UnboxableByTransform {
/// The number of directions that this type contains
static var count: Int { get }
/// The radian value that represents the angle of this direction
var radianValue: CGFloat { get }
/// Initialize an instance of this Direction type with a string equivalent to a member name
init?(string: String)
/// Return the next clockwise direction
func nextClockwiseDirection() -> Self
/// Return the next counter clockwise direction
func nextCounterClockwiseDirection() -> Self
/// Return the opposite direction
func oppositeDirection() -> Self
/// Attempt to convert this direction into a four way direction
func toFourWayDirection() -> Direction.FourWay?
/// Convert this direction into an eight way direction
func toEightWayDirection() -> Direction.EightWay
}
/// Structure acting as a namespace for enums describing directions
public struct Direction {
/// An enum that describes a direction in any of 4 ways
public enum FourWay: Int, DirectionType {
public typealias UnboxRawValueType = String
case Up
case Right
case Down
case Left
public static var count: Int {
return 4
}
public static func lastValue() -> FourWay {
return .Left
}
/// Whether the direction is Horizontal
public var isHorizontal: Bool {
switch self {
case .Up, .Down:
return false
case .Right, .Left:
return true
}
}
/// Whether the direction is Vertical
public var isVertical: Bool {
return !self.isHorizontal
}
public init?(string: String) {
switch string {
case FourWay.Up.toString():
self = .Up
case FourWay.Right.toString():
self = .Right
case FourWay.Down.toString():
self = .Down
case FourWay.Left.toString():
self = .Left
default:
return nil
}
}
public func toString() -> String {
switch self {
case .Up:
return "Up"
case .Right:
return "Right"
case .Down:
return "Down"
case .Left:
return "Left"
}
}
public func toFourWayDirection() -> Direction.FourWay? {
return self
}
public func toEightWayDirection() -> Direction.EightWay {
return Direction.EightWay(self)
}
}
/// An ennum that describes a direction in any of 8 ways
public enum EightWay: Int, DirectionType {
public typealias UnboxRawValueType = String
case Up
case UpRight
case Right
case RightDown
case Down
case DownLeft
case Left
case LeftUp
public static var count: Int {
return 8
}
public static func lastValue() -> EightWay {
return .LeftUp
}
public static func diagonalDirections() -> [EightWay] {
return [
.UpRight,
.RightDown,
.DownLeft,
.LeftUp
]
}
/// Whether the direction is diagonal
public var isDiagonal: Bool {
return self.toFourWayDirection() == nil
}
public init?(string: String) {
switch string {
case EightWay.Up.toString():
self = .Up
case EightWay.UpRight.toString():
self = .UpRight
case EightWay.Right.toString():
self = .Right
case EightWay.RightDown.toString():
self = .RightDown
case EightWay.Down.toString():
self = .Down
case EightWay.DownLeft.toString():
self = .DownLeft
case EightWay.Left.toString():
self = .Left
case EightWay.LeftUp.toString():
self = .LeftUp
default:
return nil
}
}
public init(_ fourWayDirection: FourWay) {
switch fourWayDirection {
case .Up:
self = .Up
case .Right:
self = .Right
case .Down:
self = .Down
case .Left:
self = .Left
}
}
public func toString() -> String {
switch self {
case .Up:
return "Up"
case .UpRight:
return "UpRight"
case .Right:
return "Right"
case .RightDown:
return "RightDown"
case .Down:
return "Down"
case .DownLeft:
return "DownLeft"
case .Left:
return "Left"
case .LeftUp:
return "LeftUp"
}
}
public func toFourWayDirection() -> Direction.FourWay? {
switch self {
case .Up:
return .Up
case .Right:
return .Right
case .Down:
return .Down
case .Left:
return .Left
case .UpRight, .RightDown, .DownLeft, .LeftUp:
return nil
}
}
public func toEightWayDirection() -> Direction.EightWay {
return self
}
}
}
/// Default implementations of the DirectionType protocol
public extension DirectionType where RawValue: Number, UnboxRawValueType == String {
var radianValue: CGFloat {
return (CGFloat(M_PI * Double(2)) / CGFloat(Self.count())) * CGFloat(self.rawValue)
}
static func firstValue() -> Self {
return Self(rawValue: RawValue(0))!
}
static func transformUnboxedValue(unboxedValue: String) -> Self? {
return self.init(string: unboxedValue)
}
static func unboxFallbackValue() -> Self {
return self.firstValue()
}
func nextClockwiseDirection() -> Self {
return self.nextOrLoopAround()
}
func nextCounterClockwiseDirection() -> Self {
return self.previous() ?? Self(rawValue: RawValue(Self.count - 1))!
}
func oppositeDirection() -> Self {
var direction = self
Repeat(Self.count / 2) {
direction = direction.nextCounterClockwiseDirection()
}
return direction
}
}
/// Extension for Arrays containing Direction values
public extension Array where Element: DirectionType {
func toEightWayDirections() -> [Direction.EightWay] {
var directions: [Direction.EightWay] = []
for direction in self {
directions.append(direction.toEightWayDirection())
}
return directions
}
}
| mit | 3a730f23b176b787e66b5f46a4e84667 | 27.608527 | 100 | 0.517816 | 5.399415 | false | false | false | false |
RiBj1993/CodeRoute | Pods/SwiftyGif/SwiftyGif/SwiftyGifManager.swift | 2 | 3877 | //
// SwiftyGifManager.swift
//
//
import ImageIO
import UIKit
import Foundation
open class SwiftyGifManager {
// A convenient default manager if we only have one gif to display here and there
public static var defaultManager = SwiftyGifManager(memoryLimit: 50)
fileprivate var timer: CADisplayLink?
fileprivate var displayViews: [UIImageView] = []
fileprivate var totalGifSize: Int
fileprivate var memoryLimit: Int
open var haveCache: Bool
/**
Initialize a manager
- Parameter memoryLimit: The number of Mb max for this manager
*/
public init(memoryLimit: Int) {
self.memoryLimit = memoryLimit
self.totalGifSize = 0
self.haveCache = true
self.timer = CADisplayLink(target: self, selector: #selector(self.updateImageView))
self.timer!.add(to: .main, forMode: RunLoopMode.commonModes)
}
/**
Add a new imageView to this manager if it doesn't exist
- Parameter imageView: The UIImageView we're adding to this manager
*/
open func addImageView(_ imageView: UIImageView) {
if self.containsImageView(imageView) { return }
self.totalGifSize += imageView.gifImage!.imageSize!
if self.totalGifSize > memoryLimit && self.haveCache {
self.haveCache = false
for imageView in self.displayViews{
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).sync{
imageView.updateCache()
}
}
}
self.displayViews.append(imageView)
}
/**
Delete an imageView from this manager if it exists
- Parameter imageView: The UIImageView we want to delete
*/
open func deleteImageView(_ imageView: UIImageView){
if let index = self.displayViews.index(of: imageView){
if index >= 0 && index < self.displayViews.count {
self.displayViews.remove(at: index)
self.totalGifSize -= imageView.gifImage!.imageSize!
if self.totalGifSize < memoryLimit && !self.haveCache {
self.haveCache = true
for imageView in self.displayViews{
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).sync{
imageView.updateCache()
}
}
}
}
}
}
/**
Check if an imageView is already managed by this manager
- Parameter imageView: The UIImageView we're searching
- Returns : a boolean for wether the imageView was found
*/
open func containsImageView(_ imageView: UIImageView) -> Bool{
return self.displayViews.contains(imageView)
}
/**
Check if this manager has cache for an imageView
- Parameter imageView: The UIImageView we're searching cache for
- Returns : a boolean for wether we have cache for the imageView
*/
open func hasCache(_ imageView: UIImageView) -> Bool{
if imageView.displaying == false {
return false
}
if imageView.loopCount == -1 || imageView.loopCount >= 5 {
return self.haveCache
}else{
return false
}
}
/**
Update imageView current image. This method is called by the main loop.
This is what create the animation.
*/
@objc func updateImageView(){
for imageView in self.displayViews {
DispatchQueue.main.async{
imageView.image = imageView.currentImage
}
if imageView.isAnimatingGif() {
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).sync{
imageView.updateCurrentImage()
}
}
}
}
}
| apache-2.0 | 88f2ea7d85323938159ffde9702ae8a1 | 31.855932 | 93 | 0.596595 | 5.325549 | false | false | false | false |
russbishop/swift | test/1_stdlib/TestCharacterSet.swift | 1 | 6862 | // 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
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if FOUNDATION_XCTEST
import XCTest
class TestCharacterSetSuper : XCTestCase { }
#else
import StdlibUnittest
class TestCharacterSetSuper { }
#endif
class TestCharacterSet : TestCharacterSetSuper {
let capitalA = UnicodeScalar(0x0041) // LATIN CAPITAL LETTER A
let capitalB = UnicodeScalar(0x0042) // LATIN CAPITAL LETTER B
let capitalC = UnicodeScalar(0x0043) // LATIN CAPITAL LETTER C
func testBasicConstruction() {
// Create a character set
let cs = CharacterSet.letters
// Use some method from it
let invertedCs = cs.inverted
expectTrue(!invertedCs.contains(capitalA), "Character set must not contain our letter")
// Use another method from it
let originalCs = invertedCs.inverted
expectTrue(originalCs.contains(capitalA), "Character set must contain our letter")
}
func testMutability_copyOnWrite() {
var firstCharacterSet = CharacterSet(charactersIn: "ABC")
expectTrue(firstCharacterSet.contains(capitalA), "Character set must contain our letter")
expectTrue(firstCharacterSet.contains(capitalB), "Character set must contain our letter")
expectTrue(firstCharacterSet.contains(capitalC), "Character set must contain our letter")
// Make a 'copy' (just the struct)
var secondCharacterSet = firstCharacterSet
// first: ABC, second: ABC
// Mutate first and verify that it has correct content
firstCharacterSet.remove(charactersIn: "A")
// first: BC, second: ABC
expectTrue(!firstCharacterSet.contains(capitalA), "Character set must not contain our letter")
expectTrue(secondCharacterSet.contains(capitalA), "Copy should not have been mutated")
// Make a 'copy' (just the struct) of the second set, mutate it
let thirdCharacterSet = secondCharacterSet
// first: BC, second: ABC, third: ABC
secondCharacterSet.remove(charactersIn: "B")
// first: BC, second: AC, third: ABC
expectTrue(firstCharacterSet.contains(capitalB), "Character set must contain our letter")
expectTrue(!secondCharacterSet.contains(capitalB), "Character set must not contain our letter")
expectTrue(thirdCharacterSet.contains(capitalB), "Character set must contain our letter")
firstCharacterSet.remove(charactersIn: "C")
// first: B, second: AC, third: ABC
expectTrue(!firstCharacterSet.contains(capitalC), "Character set must not contain our letter")
expectTrue(secondCharacterSet.contains(capitalC), "Character set must not contain our letter")
expectTrue(thirdCharacterSet.contains(capitalC), "Character set must contain our letter")
}
func testMutability_mutableCopyCrash() {
let cs = CharacterSet(charactersIn: "ABC")
(cs as NSCharacterSet).mutableCopy() // this should not crash
}
func testMutability_SR_1782() {
var nonAlphanumeric = CharacterSet.alphanumerics.inverted
nonAlphanumeric.remove(charactersIn: " ") // this should not crash
}
func testRanges() {
// Simple range check
let asciiUppercase = CharacterSet(charactersIn: UnicodeScalar(0x41)...UnicodeScalar(0x5A))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x49)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x5A)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x41)))
expectTrue(!asciiUppercase.contains(UnicodeScalar(0x5B)))
// Some string filtering tests
let asciiLowercase = CharacterSet(charactersIn: UnicodeScalar(0x61)...UnicodeScalar(0x7B))
let testString = "helloHELLOhello"
let expected = "HELLO"
let result = testString.trimmingCharacters(in: asciiLowercase)
expectEqual(result, expected)
}
func testInsertAndRemove() {
var asciiUppercase = CharacterSet(charactersIn: UnicodeScalar(0x41)...UnicodeScalar(0x5A))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x49)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x5A)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x41)))
asciiUppercase.remove(UnicodeScalar(0x49))
expectTrue(!asciiUppercase.contains(UnicodeScalar(0x49)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x5A)))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x41)))
// Zero-length range
asciiUppercase.remove(charactersIn: UnicodeScalar(0x41)..<UnicodeScalar(0x41))
expectTrue(asciiUppercase.contains(UnicodeScalar(0x41)))
asciiUppercase.remove(charactersIn: UnicodeScalar(0x41)..<UnicodeScalar(0x42))
expectTrue(!asciiUppercase.contains(UnicodeScalar(0x41)))
asciiUppercase.remove(charactersIn: "Z")
expectTrue(!asciiUppercase.contains(UnicodeScalar(0x5A)))
}
func testBasics() {
var result : [String] = []
let string = "The quick, brown, fox jumps over the lazy dog - because, why not?"
var set = CharacterSet(charactersIn: ",-")
result = string.components(separatedBy: set)
expectEqual(5, result.count)
set.remove(charactersIn: ",")
set.insert(charactersIn: " ")
result = string.components(separatedBy: set)
expectEqual(14, result.count)
set.remove(" ".unicodeScalars.first!)
result = string.components(separatedBy: set)
expectEqual(2, result.count)
}
}
#if !FOUNDATION_XCTEST
var CharacterSetTests = TestSuite("TestCharacterSet")
CharacterSetTests.test("testBasicConstruction") { TestCharacterSet().testBasicConstruction() }
CharacterSetTests.test("testMutability_copyOnWrite") { TestCharacterSet().testMutability_copyOnWrite() }
CharacterSetTests.test("testMutability_mutableCopyCrash") { TestCharacterSet().testMutability_mutableCopyCrash() }
CharacterSetTests.test("testMutability_SR_1782") { TestCharacterSet().testMutability_SR_1782() }
CharacterSetTests.test("testRanges") { TestCharacterSet().testRanges() }
CharacterSetTests.test("testInsertAndRemove") { TestCharacterSet().testInsertAndRemove() }
CharacterSetTests.test("testBasics") { TestCharacterSet().testBasics() }
runAllTests()
#endif
| apache-2.0 | d75ba5efee1634b91d2258c1dd4b714a | 41.8875 | 114 | 0.685369 | 4.815439 | false | true | false | false |
JakeLin/IBAnimatable | Sources/Protocols/Designable/PlaceholderDesignable.swift | 2 | 2833 | //
// Created by Jake Lin on 11/19/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
public protocol PlaceholderDesignable: class {
/**
`color` within `::-webkit-input-placeholder`, `::-moz-placeholder` or `:-ms-input-placeholder`
*/
var placeholderColor: UIColor? { get set }
var placeholderText: String? { get set }
}
public extension PlaceholderDesignable where Self: UITextField {
var placeholderText: String? { get { return "" } set {} }
func configurePlaceholderColor() {
let text = placeholder ?? placeholderText
if let placeholderColor = placeholderColor, let placeholder = text {
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: placeholderColor])
}
}
}
public extension PlaceholderDesignable where Self: UITextView {
func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) {
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholderText
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
update(placeholderLabel, using: &placeholderLabelConstraints)
}
func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) {
var format = "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]"
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
format = "V:|-(\(textContainerInset.top))-[placeholder]"
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
let constant = -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
newConstraints.append(NSLayoutConstraint(item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: constant))
removeConstraints(constraints)
addConstraints(newConstraints)
constraints = newConstraints
}
}
| mit | 31daa8f853a9dc498792400ef883f638 | 41.268657 | 119 | 0.624647 | 6.421769 | false | false | false | false |
GenericDataSource/GenericDataSource | Example/Example/RootViewController.swift | 1 | 1909 | //
// RootViewController.swift
// Example
//
// Created by Mohamed Afifi on 3/28/16.
// Copyright © 2016 Mohamed Afifi. All rights reserved.
//
import UIKit
import GenericDataSource
class RootViewController: UITableViewController {
private var dataSource: BasicBlockDataSource<Example, BasicTableViewCell>?
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .automatic
}
let dataSource = BasicBlockDataSource<Example, BasicTableViewCell>() { (item: Example, cell: BasicTableViewCell, indexPath) -> Void in
cell.textLabel?.text = item.title
cell.contentView.backgroundColor = nil
cell.accessoryType = .disclosureIndicator
}
// Need to keep a strong reference to our data source.
self.dataSource = dataSource
// register the cell
tableView.ds_register(cellClass: BasicTableViewCell.self)
// bind the data source to the table view
tableView.ds_useDataSource(dataSource)
dataSource.items = Service.getExamples()
// optionally adding a selection handler
let selectionHandler = BlockSelectionHandler<Example, BasicTableViewCell>()
selectionHandler.didSelectBlock = { [weak self] dataSource, _, indexPath in
let item = dataSource.item(at: indexPath)
self?.performSegue(withIdentifier: item.segue, sender: self)
}
dataSource.setSelectionHandler(selectionHandler)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let indexPath = dataSource?.ds_reusableViewDelegate?.ds_indexPathsForSelectedItems().first {
let item = dataSource?.item(at: indexPath)
segue.destination.title = item?.title
}
}
}
| mit | aa53ac2ffea425f3fc8ea2753323f257 | 33.690909 | 142 | 0.671384 | 5.088 | false | false | false | false |
nua-schroers/mvvm-frp | 42_MVVM_FRP-App_WarningDialog/MatchGame/MatchGame/Controller/MainViewController.swift | 3 | 3784 | //
// ViewController.swift
// MatchGame
//
// Created by Dr. Wolfram Schroers on 5/26/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
/// The view controller of the first screen responsible for the game.
class MainViewController: MVVMViewController {
// MARK: The corresponding view model (view first)
/// The main screen view model.
var viewModel = MainViewModel()
// MARK: Lifecycle/workflow management
override func viewDidLoad() {
super.viewDidLoad()
// Data bindings: wire up the label texts.
self.gameStateLabel.rac_text <~ self.viewModel.gameState
self.moveReportLabel.rac_text <~ self.viewModel.moveReport
// Wire up the buttons to the view model actions.
self.takeOneButton.addTarget(self.viewModel.takeOneAction, action: CocoaAction<Any>.selector, for: .touchUpInside)
self.takeTwoButton.addTarget(self.viewModel.takeTwoAction, action: CocoaAction<Any>.selector, for: .touchUpInside)
self.takeThreeButton.addTarget(self.viewModel.takeThreeAction, action: CocoaAction<Any>.selector, for: .touchUpInside)
self.infoButton.addTarget(self.viewModel.infoButtonAction, action: CocoaAction<Any>.selector, for: .touchUpInside)
// Wire up the button "enabled" states.
self.takeTwoButton.rac_enabled <~ self.viewModel.buttonTwoEnabled
self.takeThreeButton.rac_enabled <~ self.viewModel.buttonThreeEnabled
// Wire up the match view activities (reset and remove matches with animation).
self.viewModel.resetMatchView.producer.startWithValues { (count) in
self.matchPileView.setMatches(count)
}
self.viewModel.removeFromMatchView.producer.skip(first: 1).startWithValues { (count) in
self.matchPileView.removeMatches(count)
}
// Handle screen transitions when requested.
let transitionSubscriber = Signal<Void, Never>.Observer(value: { self.transitionToSettings() } )
viewModel.transitionSignal.observe(transitionSubscriber)
// Handle dialogs.
self.commonBindings(self.viewModel)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Direct method call when view appears.
self.viewModel.viewWillAppear()
}
// MARK: User Interface
/// The label at the top displaying the current game state.
@IBOutlet weak var gameStateLabel: UILabel!
/// The move report label beneath the game state label.
@IBOutlet weak var moveReportLabel: UILabel!
/// The graphical match pile.
@IBOutlet weak var matchPileView: MatchPileView!
/// The "Take 1" button.
@IBOutlet weak var takeOneButton: UIButton!
/// The "Take 2" button.
@IBOutlet weak var takeTwoButton: UIButton!
/// The "Take 3" button.
@IBOutlet weak var takeThreeButton: UIButton!
/// The "Info" button.
@IBOutlet weak var infoButton: UIButton!
// MARK: Private
fileprivate func transitionToSettings() {
// Instantiate the settings screen view controller and configure the UI transition.
let settingsController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
settingsController.modalPresentationStyle = .currentContext
settingsController.modalTransitionStyle = .flipHorizontal
// Establish VM<->VM bindings.
self.viewModel.configure(settingsController.viewModel)
// Perform the transition.
self.present(settingsController,
animated: true,
completion: nil)
}
}
| mit | 4ba43b1b2b9c75e961d4087dc846901d | 35.728155 | 167 | 0.694158 | 4.88129 | false | false | false | false |
mictab/Hacker-News-iOS | Hacker News/Hacker News/HNApi.swift | 1 | 2239 | //
// HNApi.swift
// Hacker News
//
// Created by Michel Tabari on 5/29/16.
// Copyright © 2016 Michel Tabari. All rights reserved.
//
import Foundation
import Firebase
class HNApi {
// MARK: Properties
let storyNumLimit: UInt = 60
let dateFormatter = NSDateFormatter()
let firebase = Firebase(url: "https://hacker-news.firebaseio.com/v0/")
func getStories(storyType: String, completionHandler: ([Story]?, NSError?) -> ()) {
let item = "item"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var storiesMap = [Int:Story]()
let dataQuery = firebase.childByAppendingPath(storyType).queryLimitedToFirst(storyNumLimit)
var stories = [Story]()
dataQuery.observeSingleEventOfType(.Value, withBlock: {
snapshot in let ids = snapshot.value as! [Int]
for id in ids {
let dataQuery = self.firebase.childByAppendingPath(item).childByAppendingPath(String(id))
dataQuery.observeSingleEventOfType(.Value, withBlock: {
snapshot in storiesMap[id] = self.getStoryDetail(snapshot)
if storiesMap.count == Int(self.storyNumLimit) {
for id in ids {
stories.append(storiesMap[id]!)
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
print("GETTING STORIES")
completionHandler(stories, nil)
}
})
}
})
}
private func getStoryDetail(snapshot: FDataSnapshot) -> Story {
self.dateFormatter.dateFormat = "HH:mm"
let title = snapshot.value["title"] as! String
let url = snapshot.value["url"] as? String
let author = snapshot.value["by"] as! String
let score = snapshot.value["score"] as! Int
let time = NSDate(timeIntervalSince1970: snapshot.value["time"] as! Double)
let dateString = dateFormatter.stringFromDate(time)
return Story(title: title, url: url, author: author, score: score, time: dateString)
}
}
let hnApi = HNApi() | mit | e101cf305d0877aab911fd876cda42e4 | 36.949153 | 105 | 0.596068 | 4.802575 | false | false | false | false |
64characters/Telephone | UseCasesTestDoubles/TimerSpy.swift | 1 | 998 | //
// TimerSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
public final class TimerSpy: Timer {
public let interval: Double = 0
public let action: () -> Void = {}
public private(set) var didCallInvalidate = false
public private(set) var invalidateCallCount = 0
public init() {}
public func invalidate() {
didCallInvalidate = true
invalidateCallCount += 1
}
}
| gpl-3.0 | 45e74b550bef7980e4322207481f8ee3 | 28.294118 | 72 | 0.701807 | 4.25641 | false | false | false | false |
nixzhu/MonkeyKing | Sources/MonkeyKing/MonkeyKing+OpenURL.swift | 1 | 886 |
import UIKit
extension MonkeyKing {
public class func openScheme(_ scheme: String, options: [UIApplication.OpenExternalURLOptionsKey: Any] = [:], completionHandler: OpenSchemeCompletionHandler? = nil) {
shared.openSchemeCompletionHandler = completionHandler
shared.deliverCompletionHandler = nil
shared.payCompletionHandler = nil
shared.oauthCompletionHandler = nil
let handleErrorResult: () -> Void = {
shared.openSchemeCompletionHandler = nil
completionHandler?(.failure(.apiRequest(.unrecognizedError(response: nil))))
}
if let url = URL(string: scheme) {
UIApplication.shared.open(url, options: options) { flag in
if !flag {
handleErrorResult()
}
}
} else {
handleErrorResult()
}
}
}
| mit | b88e83d61a1f7b0ba31433b36f5cc778 | 30.642857 | 170 | 0.609481 | 5.572327 | false | false | false | false |
smogun/KVLHelpers | KVLHelpers/KVLHelpers/Extensions/UIImage+Extension.swift | 1 | 4007 | //
// UIImage+Extension.swift
// Pods
//
// Created by Misha Koval on 18/04/2016.
//
//
import UIKit
@objc public extension UIImage {
@objc func imageByApplyingAlpha(_ alpha: CGFloat) -> UIImage!
{
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0);
let ctx:CGContext? = UIGraphicsGetCurrentContext();
let area = CGRect(x: CGFloat(0), y: CGFloat(0), width: self.size.width, height: self.size.height);
ctx!.scaleBy(x: CGFloat(1), y: CGFloat(-1));
ctx!.translateBy(x: CGFloat(0), y: -area.size.height);
ctx!.setBlendMode(.multiply);
ctx!.setAlpha(alpha);
ctx!.draw(self.cgImage!, in: area);
let newImage:UIImage? = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@objc func imageRotatedTo(orientation: UIImage.Orientation) -> UIImage
{
UIGraphicsBeginImageContext(self.size);
let context = UIGraphicsGetCurrentContext()!
if orientation == .right {
context.rotate (by: degreesToRadians(deg: CGFloat(90)));
} else if orientation == .left {
context.rotate (by: degreesToRadians(deg: CGFloat(-90)));
} else if orientation == .down {
// NOTHING
} else if orientation == .up {
context.rotate (by: degreesToRadians(deg: CGFloat(90)));
}
self.draw(at: CGPoint(x: 0, y: 0))
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext();
return image;
}
@objc func imageRotatedByDegrees(_ degrees: CGFloat) -> UIImage
{
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox:UIView = UIView(frame:CGRect(x: CGFloat(0), y: CGFloat(0), width: self.size.width, height: self.size.height));
let t:CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / CGFloat(180.0));
rotatedViewBox.transform = t;
let rotatedSize:CGSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
let bitmap:CGContext? = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap!.translateBy(x: rotatedSize.width/CGFloat(2), y: rotatedSize.height/CGFloat(2));
// // Rotate the image context
bitmap!.rotate(by: (degrees * CGFloat.pi / CGFloat(180.0)));
// Now, draw the rotated/scaled image into the context
bitmap!.scaleBy(x: CGFloat(1.0), y: CGFloat(-1.0));
bitmap!.draw(self.cgImage!, in: CGRect(x: -self.size.width / CGFloat(2), y: -self.size.height / CGFloat(2), width: self.size.width, height: self.size.height));
let newImage:UIImage? = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage!;
}
@objc static func imageFromColor(_ color: UIColor!) -> UIImage
{
return UIImage.imageFromColor(color, size:CGSize(width: CGFloat(1), height: CGFloat(1)));
}
@objc static func imageFromColor(_ color: UIColor!, size: CGSize) -> UIImage
{
let rect:CGRect = CGRect(x: CGFloat(0), y: CGFloat(0), width: size.width, height: size.height);
UIGraphicsBeginImageContext(rect.size);
let context:CGContext? = UIGraphicsGetCurrentContext();
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image:UIImage? = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!;
}
func degreesToRadians(deg: CGFloat) -> CGFloat
{
return deg * .pi/CGFloat(180)
}
}
| mit | 05918f4c9381b59d8b91b0feaa098302 | 33.543103 | 167 | 0.61143 | 4.742012 | false | false | false | false |
aliceatlas/daybreak | Classes/SBTabbarItem.swift | 1 | 10911 | /*
SBTabbarItem.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
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.
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.
*/
class SBTabbarItem: SBView {
unowned var tabbar: SBTabbar
private var _tag: Int = -1
override var tag: Int {
get { return _tag }
set(tag) { _tag = tag }
}
var image: NSImage?
var closeSelector: Selector = nil
var selectSelector: Selector = nil
private var downInClose = false
private var dragInClose = false
private var area: NSTrackingArea!
lazy var progressIndicator: SBCircleProgressIndicator = {
let progressIndicator = SBCircleProgressIndicator(frame: self.progressRect)
progressIndicator.autoresizingMask = .ViewMinXMargin
return progressIndicator
}()
var progress: CGFloat {
get { return progressIndicator.progress }
set(progress) { progressIndicator.progress = progress }
}
override var keyView: Bool {
willSet {
progressIndicator.keyView = newValue
}
}
override var toolbarVisible: Bool {
didSet {
if toolbarVisible != oldValue {
progressIndicator.toolbarVisible = toolbarVisible
needsDisplay = true
}
}
}
var title: String = "" {
didSet {
if title != oldValue {
needsDisplay = true
}
}
}
var selected: Bool = false {
didSet {
if selected != oldValue {
progressIndicator.selected = selected
needsDisplay = true
}
}
}
var closable: Bool = false {
didSet {
if closable != oldValue {
needsDisplay = true
}
}
}
init(frame: NSRect, tabbar: SBTabbar) {
self.tabbar = tabbar
super.init(frame: frame)
area = NSTrackingArea(rect: bounds, options: [.MouseEnteredAndExited, .MouseMoved, .ActiveAlways, .InVisibleRect], owner: self, userInfo: nil)
addSubview(progressIndicator)
addTrackingArea(area)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// MARK: Rects
var closableRect: CGRect {
let across: CGFloat = 12.0;
let margin: CGFloat = (bounds.size.height - across) / 2
return CGRectMake(margin, margin, across, across)
}
var progressRect: CGRect {
let across: CGFloat = 18.0
let margin: CGFloat = (bounds.size.height - across) / 2
return CGRectMake(bounds.size.width - margin - across, margin, across, across)
}
// MARK: Exec
func executeShouldClose() {
if target?.respondsToSelector(closeSelector) ?? false {
NSApp.sendAction(closeSelector, to: target, from: self)
}
}
func executeShouldSelect() {
if target?.respondsToSelector(selectSelector) ?? false {
NSApp.sendAction(selectSelector, to: target, from: self)
}
}
// MARK: Event
override func mouseDown(event: NSEvent) {
let location = event.locationInWindow
let point = convertPoint(location, fromView: nil)
dragInClose = false
if closable {
downInClose = closableRect.contains(point)
if downInClose {
// Close
dragInClose = true
needsDisplay = true
}
}
if !dragInClose {
superview!.mouseDown(event)
if !selected {
executeShouldSelect()
} else {
tabbar.executeShouldReselect(self)
}
}
}
override func mouseDragged(event: NSEvent) {
let location = event.locationInWindow
let point = convertPoint(location, fromView: nil)
if downInClose {
// Close
let close = closableRect.contains(point)
if dragInClose != close {
dragInClose = close
needsDisplay = true
}
} else {
superview!.mouseDragged(event)
}
}
override func mouseMoved(event: NSEvent) {
if tabbar.canClosable {
let location = event.locationInWindow
let point = convertPoint(location, fromView: nil)
superview!.mouseMoved(event)
if bounds.contains(point) {
tabbar.constructClosableTimerForItem(self)
} else {
tabbar.applyDisclosableAllItem()
}
}
}
override func mouseEntered(event: NSEvent) {
superview!.mouseEntered(event)
}
override func mouseExited(event: NSEvent) {
superview!.mouseExited(event)
if tabbar.canClosable {
tabbar.applyDisclosableAllItem()
}
}
override func mouseUp(event: NSEvent) {
let location = event.locationInWindow
let point = convertPoint(location, fromView: nil)
if downInClose {
// Close
if closable && closableRect.contains(point) {
executeShouldClose()
}
} else {
superview!.mouseUp(event)
}
dragInClose = false
downInClose = false
needsDisplay = true
}
override func menuForEvent(event: NSEvent) -> NSMenu {
return tabbar.menuForItem(self)
}
// MARK: Drawing
override func drawRect(rect: NSRect) {
var path: NSBezierPath!
var strokePath: NSBezierPath!
var grayScaleDown: CGFloat!
var grayScaleUp: CGFloat!
var strokeGrayScale: CGFloat!
var titleLeftMargin: CGFloat = 10.0
let titleRightMargin = bounds.size.width - progressRect.origin.x
// Paths
// Gray scales
if selected {
path = SBRoundedPath(CGRectInset(bounds, 0.0, 0.0), 4.0, 0.0, false, true)
strokePath = SBRoundedPath(CGRectInset(bounds, 0.5, 0.5), 4.0, 0.0, false, true)
grayScaleDown = CGFloat(keyView ? 140 : 207) / CGFloat(255.0)
grayScaleUp = CGFloat(keyView ? 175 : 222) / CGFloat(255.0)
strokeGrayScale = 0.2
} else {
path = SBRoundedPath(CGRectInset(bounds, 0.0, 1.0), 4.0, 0.0, true, false)
strokePath = SBRoundedPath(CGRectInset(bounds, 0.5, 1.0), 4.0, 0.0, true, false)
grayScaleDown = (keyView ? 130 : 207) / CGFloat(255.0)
grayScaleUp = (keyView ? 140 : 207) / CGFloat(255.0)
strokeGrayScale = 0.4
}
// Frame
let strokeColor = NSColor(deviceWhite: strokeGrayScale, alpha: 1.0)
let gradient = NSGradient(startingColor: NSColor(deviceWhite: grayScaleDown, alpha: 1.0),
endingColor: NSColor(deviceWhite: grayScaleUp, alpha: 1.0))!
gradient.drawInBezierPath(path, angle: 90)
// Stroke
strokeColor.set()
strokePath.lineWidth = 0.5
strokePath.stroke()
if closable {
// Close button
var p = CGPointZero
let across = closableRect.size.width
let length: CGFloat = 10.0
let margin = closableRect.origin.x
let lineWidth: CGFloat = 2
let center = margin + across / 2
let closeGrayScale: CGFloat = dragInClose ? 0.2 : 0.4
let xPath = NSBezierPath()
let t = NSAffineTransform()
t.translateXBy(center, yBy: center)
t.rotateByDegrees(-45)
p.x = -length / 2
xPath.moveToPoint(t.transformPoint(p))
p.x = length / 2
xPath.lineToPoint(t.transformPoint(p))
p.x = 0
p.y = -length / 2
xPath.moveToPoint(t.transformPoint(p))
p.y = length / 2
xPath.lineToPoint(t.transformPoint(p))
// Ellipse
NSColor(deviceWhite: closeGrayScale, alpha: 1.0).set()
path = NSBezierPath(ovalInRect: closableRect)
path.lineWidth = lineWidth
path.fill()
// Close
NSColor(deviceWhite: grayScaleUp, alpha: 1.0).set()
xPath.lineWidth = lineWidth
xPath.stroke()
titleLeftMargin = across + margin * 2
}
if !title.isEmpty {
// Title
var size = NSZeroSize
var r = NSZeroRect
let width = bounds.size.width - titleLeftMargin - titleRightMargin
let shadow = NSShadow()
let paragraphStyle = NSMutableParagraphStyle()
shadow.shadowColor = NSColor(calibratedWhite: 1.0, alpha: 1.0)
shadow.shadowOffset = NSMakeSize(0, -0.5)
shadow.shadowBlurRadius = 0.5
paragraphStyle.lineBreakMode = .ByTruncatingTail
let attributes = [
NSFontAttributeName: NSFont.boldSystemFontOfSize(12.0),
NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.1, alpha: 1.0),
NSShadowAttributeName: shadow,
NSParagraphStyleAttributeName: paragraphStyle]
size = title.sizeWithAttributes(attributes)
r.size = size
if size.width > width {
r.size.width = width
}
r.origin.x = titleLeftMargin + (width - r.size.width) / 2
r.origin.y = (bounds.size.height - r.size.height) / 2
title.drawInRect(r, withAttributes: attributes)
}
}
} | bsd-2-clause | f614bb83c769fcb46fa6925dced5189a | 33.314465 | 150 | 0.584823 | 4.823607 | false | false | false | false |
mercadopago/px-ios | px-templates/VIP.xctemplate/Without header/___FILEBASENAME___Factory.swift | 1 | 729 | import UIKit
enum ___FILEBASENAMEASIDENTIFIER___ {
static func make() -> ViewController<___VARIABLE_productName:identifier___View, ___VARIABLE_productName:identifier___InteractorProtocol> {
let view = ___VARIABLE_productName:identifier___View()
let presenter = ___VARIABLE_productName:identifier___Presenter()
let repository = ___VARIABLE_productName:identifier___Repository()
let interactor = ___VARIABLE_productName:identifier___Interactor(presenter: presenter, repository: repository)
let controller = ___VARIABLE_productName:identifier___ViewController(customView: view, interactor: interactor)
presenter.controller = controller
return controller
}
}
| mit | 11aa18e904b59e81b8c55379983b0e11 | 51.071429 | 142 | 0.705075 | 5.564885 | false | false | false | false |
lionheart/LionheartCurrencyTextField | Example/Pods/LionheartExtensions/Pod/Classes/Core/UIView+LionheartExtensions.swift | 1 | 11899 | //
// Copyright 2016 Lionheart Software LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import Foundation
public typealias LayoutDictionary = [String: Any]
/// Auto Layout and general utility methods for `UIView`.
public extension UIView {
/**
Remove all subviews of the calling `UIView`.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
func removeSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
/**
Center the calling `UIView` on the X-axis, with optional margins to the right and left.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: March 9, 2016
*/
@available(iOS 9, *)
func centerOnXAxis(width: CGFloat? = nil) {
centerXAnchor.constraint(equalTo: (superview?.centerXAnchor)!).isActive = true
guard let width = width else {
return
}
setWidth(width)
}
/**
Center the calling `UIView` on the Y-axis, with optional margins to the top and bottom.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: March 9, 2016
*/
@available(iOS 9, *)
func centerOnYAxis(height: CGFloat? = nil) {
centerYAnchor.constraint(equalTo: (superview?.centerYAnchor)!).isActive = true
guard let height = height else {
return
}
setHeight(height)
}
/**
Set the height of this view to a specified value using Auto Layout.
- parameter height: A `Float` specifying the view's height.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func setHeight(_ height: CGFloat) {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
/**
Set the width of this view to a specified value using Auto Layout.
- parameter width: A `Float` specifying the view's width.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func setWidth(_ width: CGFloat) {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
/**
Set the size of the view using Auto Layout.
- parameter size: A `CGSize` specifying the view's size.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9.0, *)
func setContentSize(_ size: CGSize) {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
@available(iOS 9, *)
func fillHorizontalMarginsOfSuperview(margin: CGFloat = 0) {
guard let superview = superview else {
return
}
let margins = superview.layoutMarginsGuide
leftAnchor.constraint(equalTo: margins.leftAnchor, constant: margin).isActive = true
rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -margin).isActive = true
}
/**
Pin the view's horizontal edges to the left and right of its superview.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func fillWidthOfSuperview() {
fillWidthOfSuperview(margin: 0)
}
/**
Pin the view's vertical edges to the top and bottom of its superview.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func fillHeightOfSuperview() {
fillHeightOfSuperview(margin: 0)
}
/**
Pin the view's horizontal edges to the left and right of its superview with a margin.
- parameter margin: A `CGFloat` representing the horizontal margin.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func fillWidthOfSuperview(margin: CGFloat) {
guard let superview = superview else {
return
}
leftAnchor.constraint(equalTo: superview.leftAnchor, constant: margin).isActive = true
rightAnchor.constraint(equalTo: superview.rightAnchor, constant: -margin).isActive = true
}
/**
Pin the view's vertical edges to the top and bottom of its superview with a margin.
- parameter margin: A `CGFloat` representing the vertical margin.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func fillHeightOfSuperview(margin: CGFloat) {
guard let superview = superview else {
return
}
topAnchor.constraint(equalTo: superview.topAnchor, constant: margin).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -margin).isActive = true
}
/**
Pin the view's edges to the top, bottom, left, and right of its superview with a margin.
- parameter axis: Optional. Specify only when you want to pin the view to a particular axis.
- parameter margin: A `CGFloat` representing the vertical margin.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@available(iOS 9, *)
func fillSuperview(_ axis: UILayoutConstraintAxis? = nil, margin: CGFloat = 0) {
if let axis = axis {
switch (axis) {
case .horizontal:
fillWidthOfSuperview(margin: margin)
case .vertical:
fillHeightOfSuperview(margin: margin)
}
}
else {
fillWidthOfSuperview(margin: margin)
fillHeightOfSuperview(margin: margin)
}
}
/**
Apply the specified visual format constraints to the current view. The "view" placeholder is used in the provided VFL string. Usage can best be illustrated through examples:
Pin a `UIView` to the left and right of its superview with a 20px margin:
```
let view = UIView()
view.addVisualFormatConstraints("|-20-[view]-20-|")
```
Set a view to be at least 36px high, and at least 16px from the top of its superview.
```
view.addVisualFormatConstraints("V:|-(>=16)-[view(>36)]")
```
- parameter format: The format specification for the constraints. For more information, see Visual Format Language in Auto Layout Guide.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@discardableResult
func addVisualFormatConstraints(_ format: String, metrics: LayoutDictionary? = nil) -> [NSLayoutConstraint] {
let views = ["view": self]
return UIView.addVisualFormatConstraints(format, metrics: metrics, views: views)
}
/**
Apply the VFL format constraints to the specified views, with the provided metrics.
- parameter format: The format specification for the constraints. For more information, see Visual Format Language in Auto Layout Guide.
- parameter metrics: A dictionary of constants that appear in the visual format string. The dictionary’s keys must be the string values used in the visual format string. Their values must be NSNumber objects.
- parameter views: A dictionary of views that appear in the visual format string. The keys must be the string values used in the visual format string, and the values must be the view objects.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
@discardableResult
class func addVisualFormatConstraints(_ format: String, metrics: LayoutDictionary? = nil, views: LayoutDictionary) -> [NSLayoutConstraint] {
let options = NSLayoutFormatOptions(rawValue: 0)
let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views)
NSLayoutConstraint.activate(constraints)
return constraints
}
/**
Return the given distance from a view to a specified `CGPoint`.
- parameter point: The `CGPoint` to measure the distance to.
- Returns: A `Float` representing the distance to the specified `CGPoint`.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: February 17, 2016
*/
func distance(toPoint point: CGPoint) -> Float {
if frame.contains(point) {
return 0
}
var closest: CGPoint = frame.origin
let size = frame.size
if frame.origin.x + size.width < point.x {
closest.x += size.width
}
else if point.x > frame.origin.x {
closest.x = point.x
}
if frame.origin.y + size.height < point.y {
closest.y += size.height
}
else if point.y > frame.origin.y {
closest.y = point.y
}
let a = powf(Float(closest.y-point.y), 2)
let b = powf(Float(closest.x-point.x), 2)
return sqrtf(a + b)
}
// MARK - Misc
/**
Returns a 1x1 `CGRect` in the center of the calling `UIView`.
- Returns: A 1x1 `CGRect`.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: March 9, 2016
*/
var centerRect: CGRect {
return CGRect(x: center.x, y: center.y, width: 1, height: 1)
}
/**
Return an `Array` of recursive subviews matching the provided test. This method is incredibly helpful in returning all descendants of a given view of a certain type. For instance:
```
let view = UIView()
let subview = UILabel()
let label1 = UILabel()
let label2 = UILabel()
view.addSubview(subview)
view.addSubview(label1)
subview.addSubview(label2)
let labels: [UILabel] = view.descendantViewsOfType()
```
`labels` will contain both `label1` and `label2`.
- Returns: An `Array` of `UIView`s of type `T`.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: March 9, 2016
*/
func descendantViewsOfType<T>(passingTest test: (T) -> Bool = { _ in true }) -> [T] {
var views: [T] = []
for view in subviews {
if let view = view as? T, test(view) {
views.append(view)
}
views.append(contentsOf: view.descendantViewsOfType(passingTest: test))
}
return views
}
/**
This method simply returns the last object in `descendantViewsOfType(passingTest:)`.
- Returns: A view of type `T`.
- author: Daniel Loewenherz
- copyright: ©2016 Lionheart Software LLC
- Date: March 9, 2016
*/
func lastDescendantViewOfType<T>(passingTest test: (T) -> Bool = { i in true }) -> T? {
return descendantViewsOfType(passingTest: test).last
}
}
public extension Array where Element: UIView {
func removeFromSuperviews() {
forEach { $0.removeFromSuperview() }
}
}
| apache-2.0 | f295bb957afe2dee4294b56700d39534 | 32.277311 | 213 | 0.637626 | 4.454443 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Scene/SkyBox.swift | 1 | 5590 | //
// SkyBox.swift
// CesiumKit
//
// Created by Ryan Walklin on 15/08/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
/**
* A sky box around the scene to draw stars. The sky box is defined using the True Equator Mean Equinox (TEME) axes.
* <p>
* This is only supported in 3D. The sky box is faded out when morphing to 2D or Columbus view. The size of
* the sky box must not exceed {@link Scene#maximumCubeMapSize}.
* </p>
*
* @alias SkyBox
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {Object} [options.sources] The source URL or <code>Image</code> object for each of the six cube map faces. See the example below.
* @param {Boolean} [options.show=true] Determines if this primitive will be shown.
*
* @see Scene#skyBox
* @see Transforms.computeTemeToPseudoFixedMatrix
*
* @example
* scene.skyBox = new Cesium.SkyBox({
* sources : {
* positiveX : 'skybox_px.png',
* negativeX : 'skybox_nx.png',
* positiveY : 'skybox_py.png',
* negativeY : 'skybox_ny.png',
* positiveZ : 'skybox_pz.png',
* negativeZ : 'skybox_nz.png'
* }
* });
*/
class SkyBox {
var sources: CubeMapSources {
didSet {
_sourcesUpdated = true
}
}
fileprivate var _sourcesUpdated: Bool = true
/**
* Determines if the sky box will be shown.
*
* @type {Boolean}
* @default true
*/
var show: Bool = true
fileprivate var _command: DrawCommand
fileprivate var _cubemap: Texture? = nil
convenience init (sources: [String]) {
self.init(sources: CubeMap.loadImagesForSources(sources))
}
init (sources: CubeMapSources) {
self.sources = sources
_cubemap = nil
_command = DrawCommand(
modelMatrix: Matrix4.identity
)
_command.owner = self
}
/**
* Called when {@link Viewer} or {@link CesiumWidget} render the scene to
* get the draw commands needed to render this primitive.
* <p>
* Do not call this function directly. This is documented just to
* list the exceptions that may be propagated when the scene is rendered:
* </p>
*
* @exception {DeveloperError} this.sources is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties.
* @exception {DeveloperError} this.sources properties must all be the same type.
*/
func update (_ frameState: FrameState) -> DrawCommand? {
if !show {
return nil
}
guard let context = frameState.context else {
return nil
}
if frameState.mode != .scene3D && frameState.mode != SceneMode.morphing {
return nil
}
// The sky box is only rendered during the render pass; it is not pickable, it doesn't cast shadows, etc.
if !frameState.passes.render {
return nil
}
if _sourcesUpdated {
let width = Int(sources.positiveX.width)
_cubemap = Texture(
context: context,
options: TextureOptions(
source: .cubeMap(sources),
width: width,
height: width,
cubeMap: true,
flipY: true,
usage: .ShaderRead
)
)
_sourcesUpdated = false
}
if _command.vertexArray == nil {
let uniformMap = SkyBoxUniformMap()
uniformMap.cubemap = _cubemap
_command.uniformMap = uniformMap
let geometry = BoxGeometry(
fromDimensions: Cartesian3(x: 2.0, y: 2.0, z: 2.0),
vertexFormat : VertexFormat.PositionOnly()
).createGeometry(context)
let attributeLocations = GeometryPipeline.createAttributeLocations(geometry)
_command.vertexArray = VertexArray(
fromGeometry: geometry,
context: context,
attributeLocations: attributeLocations
)
_command.pipeline = RenderPipeline.fromCache(
context: context,
vertexShaderSource: ShaderSource(sources: [Shaders["SkyBoxVS"]!]),
fragmentShaderSource: ShaderSource(sources: [Shaders["SkyBoxFS"]!]),
vertexDescriptor: VertexDescriptor(attributes: _command.vertexArray!.attributes),
depthStencil: context.depthTexture,
blendingState: .AlphaBlend()
)
_command.uniformMap?.uniformBufferProvider = _command.pipeline!.shaderProgram.createUniformBufferProvider(context.device, deallocationBlock: nil)
_command.renderState = RenderState(
device: context.device,
cullFace: .front
)
}
if _cubemap == nil {
return nil
}
return _command
}
class func getDefaultSkyBoxUrl (_ face: String) -> String {
return "tycho2t3_80_" + face + ".jpg"
}
}
private class SkyBoxUniformMap: NativeUniformMap {
var cubemap : Texture?
var uniformBufferProvider: UniformBufferProvider! = nil
var uniformDescriptors: [UniformDescriptor] = []
lazy var uniformUpdateBlock: UniformUpdateBlock = { buffer in
return [self.cubemap!]
}
}
| apache-2.0 | bd783656e6398a64d95b0c96b38f7036 | 30.404494 | 157 | 0.57746 | 4.394654 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Scene/Globe.swift | 1 | 15802 | //
// Globe.swift
// CesiumKit
//
// Created by Ryan Walklin on 15/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
/**
* The globe rendered in the scene, including its terrain ({@link Globe#terrainProvider})
* and imagery layers ({@link Globe#imageryLayers}). Access the globe using {@link Scene#globe}.
*
* @alias Globe
* @constructor
*
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] Determines the size and shape of the
* globe.
*/
class Globe {
let ellipsoid: Ellipsoid
var imageryLayers: ImageryLayerCollection
fileprivate var _surfaceShaderSet: GlobeSurfaceShaderSet!
fileprivate var _surface: QuadtreePrimitive!
var surfaceTilesToRenderCount: Int {
return _surface.tilesToRender.count
}
var debugString: String? {
return _surface.debugDisplayString
}
/**
* The terrain provider providing surface geometry for this globe.
* @type {TerrainProvider}
*/
var terrainProvider: TerrainProvider
fileprivate var _mode = SceneMode.scene3D
/**
* Determines if the globe will be shown.
*
* @type {Boolean}
* @default true
*/
var show = true
/**
* The normal map to use for rendering waves in the ocean. Setting this property will
* only have an effect if the configured terrain provider includes a water mask.
*
* @type {String}
* @default buildModuleUrl('Assets/Textures/waterNormalsSmall.jpg')
*/
fileprivate var _oceanNormalMap: Texture? = nil
var oceanNormalMapUrl: String? = /*buildModuleUrl("Assets/Textures*/"waterNormalsSmall.jpg"
fileprivate var _oceanNormalMapUrl: String? = nil
fileprivate var _oceanNormalMapChanged = false
/**
* The maximum screen-space error used to drive level-of-detail refinement. Higher
* values will provide better performance but lower visual quality.
*
* @type {Number}
* @default 2
*/
var maximumScreenSpaceError: Double = 2.0
/**
* The size of the terrain tile cache, expressed as a number of tiles. Any additional
* tiles beyond this number will be freed, as long as they aren't needed for rendering
* this frame. A larger number will consume more memory but will show detail faster
* when, for example, zooming out and then back in.
*
* @type {Number}
* @default 100
*/
var tileCacheSize = 100
/**
* Enable lighting the globe with the sun as a light source.
*
* @type {Boolean}
* @default false
*/
var enableLighting = false
/**
* True if an animated wave effect should be shown in areas of the globe
* covered by water; otherwise, false. This property is ignored if the
* <code>terrainProvider</code> does not provide a water mask.
*
* @type {Boolean}
* @default true
*/
var showWaterEffect = true
/**
* True if primitives such as billboards, polylines, labels, etc. should be depth-tested
* against the terrain surface, or false if such primitives should always be drawn on top
* of terrain unless they're on the opposite side of the globe. The disadvantage of depth
* testing primitives against terrain is that slight numerical noise or terrain level-of-detail
* switched can sometimes make a primitive that should be on the surface disappear underneath it.
*
* @type {Boolean}
* @default false
*
*/
var depthTestAgainstTerrain = false
fileprivate var _zoomedOutOceanSpecularIntensity: Float = 0.5
/**
* Gets or sets the color of the globe when no imagery is available.
* @memberof Globe.prototype
* @type {Color}
*/
var baseColor: Cartesian4 {
get {
return _surface.tileProvider.baseColor
}
set (value) {
let tileProvider = _surface.tileProvider
tileProvider.baseColor = value
}
}
/**
* Gets an event that's raised when the length of the tile load queue has changed since the last render frame. When the load queue is empty,
* all terrain and imagery for the current view have been loaded. The event passes the new length of the tile load queue.
*
* @memberof Globe.prototype
* @type {Event}
*/
var tileLoadProgressEvent: Event {
return _surface.tileLoadProgressEvent
}
init(ellipsoid: Ellipsoid = Ellipsoid.wgs84, terrain: Bool, lighting: Bool) {
if terrain {
terrainProvider = CesiumTerrainProvider(
url: "https://assets.cesium.com",
requestVertexNormals: true,
requestWaterMask: true
)
} else {
terrainProvider = EllipsoidTerrainProvider(
ellipsoid : ellipsoid
)
}
self.enableLighting = lighting
self.ellipsoid = ellipsoid
imageryLayers = ImageryLayerCollection()
}
func createComparePickTileFunction(_ rayOrigin: Cartesian3) -> ((GlobeSurfaceTile, GlobeSurfaceTile) -> Bool) {
func comparePickTileFunction(_ a: GlobeSurfaceTile, b: GlobeSurfaceTile) -> Bool {
let aDist = a.pickBoundingSphere.distanceSquaredTo(rayOrigin)
let bDist = b.pickBoundingSphere.distanceSquaredTo(rayOrigin)
return aDist < bDist
}
return comparePickTileFunction
}
/**
* Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
*
* @param {Ray} ray The ray to test for intersection.
* @param {Scene} scene The scene.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.
*
* @example
* // find intersection of ray through a pixel and the globe
* var ray = viewer.camera.getPickRay(windowCoordinates);
* var intersection = globe.pick(ray, scene);
*/
func pick(_ ray: Ray, scene: Scene) -> Cartesian3? {
let mode = scene.mode
//let projection = scene.mapProjection
var sphereIntersections = [GlobeSurfaceTile]()
let tilesToRender = _surface.tilesToRender
for tile in tilesToRender {
if tile.data == nil {
continue
}
let tileData = tile.data!
var boundingVolume = tileData.pickBoundingSphere
if mode != .scene3D {
assertionFailure("unimplemented")
/*BoundingSphere.fromRectangleWithHeights2D(tile.rectangle, projection, tileData.minimumHeight, tileData.maximumHeight, boundingVolume);
Cartesian3.fromElements(boundingVolume.center.z, boundingVolume.center.x, boundingVolume.center.y, boundingVolume.center);*/
} else {
boundingVolume = tileData.boundingSphere3D
}
if IntersectionTests.raySphere(ray, sphere: boundingVolume) != nil {
sphereIntersections.append(tileData)
}
}
sphereIntersections.sort(by: createComparePickTileFunction(ray.origin))
for sphereIntersection in sphereIntersections {
if let intersection = sphereIntersection.pick(ray, mode: scene.mode, projection: scene.mapProjection, cullBackFaces: true) {
return intersection
}
}
return nil
}
/**
* Get the height of the surface at a given cartographic.
*
* @param {Cartographic} cartographic The cartographic for which to find the height.
* @returns {Number|undefined} The height of the cartographic or undefined if it could not be found.
*/
func getHeight(_ cartographic: Cartographic) -> Double? {
//FIXME: Unimplemented
/*
var scratchGetHeightCartesian = new Cartesian3();
var scratchGetHeightIntersection = new Cartesian3();
var scratchGetHeightCartographic = new Cartographic();
var scratchGetHeightRay = new Ray();
//>>includeStart('debug', pragmas.debug);
if (!defined(cartographic)) {
throw new DeveloperError('cartographic is required');
}
//>>includeEnd('debug');
var levelZeroTiles = this._surface._levelZeroTiles;
if (!defined(levelZeroTiles)) {
return;
}
var tile;
var i;
var length = levelZeroTiles.length;
for (i = 0; i < length; ++i) {
tile = levelZeroTiles[i];
if (Rectangle.contains(tile.rectangle, cartographic)) {
break;
}
}
if (!defined(tile) || !Rectangle.contains(tile.rectangle, cartographic)) {
return undefined;
}
while (tile.renderable) {
var children = tile.children;
length = children.length;
for (i = 0; i < length; ++i) {
tile = children[i];
if (Rectangle.contains(tile.rectangle, cartographic)) {
break;
}
}
}
while (defined(tile) && (!defined(tile.data) || !defined(tile.data.pickTerrain))) {
tile = tile.parent;
}
if (!defined(tile)) {
return undefined;
}
var ellipsoid = this._surface._tileProvider.tilingScheme.ellipsoid;
var cartesian = ellipsoid.cartographicToCartesian(cartographic, scratchGetHeightCartesian);
var ray = scratchGetHeightRay;
Cartesian3.normalize(cartesian, ray.direction);
var intersection = tile.data.pick(ray, undefined, undefined, false, scratchGetHeightIntersection);
if (!defined(intersection)) {
return undefined;
}
return ellipsoid.cartesianToCartographic(intersection, scratchGetHeightCartographic).height;*/return 0.0
}
/**
* @private
*/
func beginFrame(_ frameState: inout FrameState) {
if !show {
return
}
/*if !terrainProvider.ready {
return
}*/
if _surface == nil {
_surfaceShaderSet = GlobeSurfaceShaderSet(
baseVertexShaderSource: ShaderSource(sources: [Shaders["GroundAtmosphere"]!, Shaders["GlobeVS"]!]),
baseFragmentShaderSource: ShaderSource(sources: [Shaders["GlobeFS"]!])
)
_surface = QuadtreePrimitive(
tileProvider: GlobeSurfaceTileProvider(
terrainProvider: terrainProvider,
imageryLayers: imageryLayers,
surfaceShaderSet: _surfaceShaderSet
)
)
}
guard let context = frameState.context else {
return
}
let width = context.width
let height = context.height
if width == 0 || height == 0 {
return
}
let hasWaterMask = showWaterEffect && terrainProvider.ready && terrainProvider.hasWaterMask
if hasWaterMask && oceanNormalMapUrl != _oceanNormalMapUrl {
// url changed, load new normal map asynchronously
_oceanNormalMapUrl = oceanNormalMapUrl
if let oceanNormalMapUrl = oceanNormalMapUrl {
let oceanMapOperation = NetworkOperation(url: oceanNormalMapUrl)
oceanMapOperation.completionBlock = {
if (oceanNormalMapUrl != self.oceanNormalMapUrl) {
// url changed while we were loading
return
}
guard let oceanNormalMapImage = CGImage.from(oceanMapOperation.data) else {
self._oceanNormalMap = nil
return
}
let oceanNormalMap = Texture(
context: context,
options: TextureOptions(
source: TextureSource.image(oceanNormalMapImage),
pixelFormat: .rgba8Unorm,
flipY: true,
usage: .ShaderRead
)
)
DispatchQueue.main.async(execute: {
self._oceanNormalMap = oceanNormalMap
})
}
oceanMapOperation.enqueue()
} else {
_oceanNormalMap = nil
}
}
let mode = frameState.mode
if (frameState.passes.render) {
// Don't show the ocean specular highlights when zoomed out in 2D and Columbus View.
if mode == .scene3D {
_zoomedOutOceanSpecularIntensity = 0.5
} else {
_zoomedOutOceanSpecularIntensity = 0.0
}
_surface.maximumScreenSpaceError = maximumScreenSpaceError
_surface.tileCacheSize = tileCacheSize
let tileProvider = _surface.tileProvider
tileProvider.terrainProvider = terrainProvider
tileProvider.zoomedOutOceanSpecularIntensity = _zoomedOutOceanSpecularIntensity
tileProvider.hasWaterMask = hasWaterMask
tileProvider.oceanNormalMap = _oceanNormalMap
tileProvider.enableLighting = enableLighting
_surface.beginFrame(&frameState)
}
/*if (frameState.passes.pick && mode == .Scene3D) {
// Not actually pickable, but render depth-only so primitives on the backface
// of the globe are not picked.
_surface.beginFrame(&frameState)
}*/
}
/**
* @private
*/
func update (_ frameState: inout FrameState) {
if !show {
return
}
if (frameState.passes.render) {
_surface.update(&frameState)
}
if (frameState.passes.pick) {
_surface.update(&frameState)
}
}
func endFrame (_ frameState: inout FrameState) {
if !show {
return
}
if frameState.passes.render {
_surface.endFrame(&frameState)
}
}
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @returns {undefined}
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see Globe#isDestroyed
*
* @example
* globe = globe && globe.destroy();
*/
deinit {
/*this._surfaceShaderSet = this._surfaceShaderSet && this._surfaceShaderSet.destroy();
this._depthCommand.shaderProgram = this._depthCommand.shaderProgram && this._depthCommand.shaderProgram.destroy();
this._depthCommand.vertexArray = this._depthCommand.vertexArray && this._depthCommand.vertexArray.destroy();
this._surface = this._surface && this._surface.destroy();
this._oceanNormalMap = this._oceanNormalMap && this._oceanNormalMap.destroy();
return destroyObject(this);*/
}
}
| apache-2.0 | 7426e93440efe3665fa3328f0920f66c | 33.12959 | 152 | 0.592836 | 4.797207 | false | false | false | false |
paulsamuels/DiffCoverage | DiffCoverageTests/Unit/GitTests.swift | 1 | 5913 | //
// GitTests.swift
// DiffCoverage
//
// Created by Paul Samuels on 15/01/2017.
// Copyright © 2017 Paul Samuels. All rights reserved.
//
import XCTest
class GitTests: XCTestCase {
func testItCalculatesAChangeSet() {
let invocationRecorder = configuredInvocationRecorder()
let git = Git(invoker: invocationRecorder.bash)
let calulationResult = git.calculateModifiedLines(for: "abcdef..mnopqr")
if invocationRecorder.unexpectedInvocations.count > 0 {
XCTFail(invocationRecorder.unexpectedInvocations.joined(separator: ", "))
}
let expected = [
"SomeProject/Models/Car.swift" : Set([11, 13]),
"SomeProject/Models/Bike.swift" : Set([11, 13, 15]),
]
XCTAssertEqual(expected, calulationResult.changedLinesByFile)
XCTAssertEqual(5, calulationResult.lineCount)
}
//swiftlint:disable function_body_length
private func configuredInvocationRecorder() -> InvocationRecorder {
let invocationRecorder = InvocationRecorder()
/// This command gets all the relevant SHAs
/// for the commit range
invocationRecorder.expect(
command: "git rev-list abcdef..mnopqr",
result: [
"ghijklzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
"mnopqrzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
]
)
/// This command gets the files that have been modified
/// within the commit range
invocationRecorder.expect(
command: "git diff --diff-filter=d --name-only abcdef..mnopqr",
result: [
"SomeProject/Models/Car.swift",
"SomeProject/Models/Bike.swift",
"SomeProject/dir with spaces/Boat.swift"
]
)
/// The following commands are then used to get the annotations
/// for each of the files that have been modified
/// within the commit range
//swiftlint:disable line_length
invocationRecorder.expect(
command: "git annotate -l --porcelain \"SomeProject/Models/Car.swift\"",
result: [
"ghijklzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 11 11 3",
"author Paul Samuels",
"author-mail <[email protected]>",
"author-time 1484344541",
"author-tz +0000",
"committer Paul Samuels",
"committer-mail <[email protected]>",
"committer-time 1484477044",
"committer-tz +0000",
"summary Initial Commit",
"boundary",
"SomeProject/Models/Car.swift",
"\tstruct Car {",
"9498bdbb7346445585ec71e746263c624eba51cc 12 12",
"\t let make: String",
"mnopqrzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 13 13",
"\t}",
]
)
invocationRecorder.expect(
command: "git annotate -l --porcelain \"SomeProject/Models/Bike.swift\"",
result: [
"ghijklzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 11 11 3",
"author Paul Samuels",
"author-mail <[email protected]>",
"author-time 1484344541",
"author-tz +0000",
"committer Paul Samuels",
"committer-mail <[email protected]>",
"committer-time 1484477044",
"committer-tz +0000",
"summary Initial Commit",
"boundary",
"SomeProject/Models/Bike.swift",
"\tstruct Bike {",
"ghijklzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 13 13",
"\t let make: String",
"ghijklzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 15 15",
"\t}",
]
)
invocationRecorder.expect(
command: "git annotate -l --porcelain \"SomeProject/dir with spaces/Boat.swift\"",
result: [
"notacommitwithintherangeweareinterestedin 11 11 3",
"author Paul Samuels",
"author-mail <[email protected]>",
"author-time 1484344541",
"author-tz +0000",
"committer Paul Samuels",
"committer-mail <[email protected]>",
"committer-time 1484477044",
"committer-tz +0000",
"summary Initial Commit",
"boundary",
"SomeProject/dir with spaces/Boat.swift",
"\tstruct Boat {",
"ghijknotacommitwithintherangeweareinterestedinlzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 13 13",
"\t let make: String",
"notacommitwithintherangeweareinterestedin 15 15",
"\t}",
]
)
//swiftlint:enable line_length
return invocationRecorder
}
//swiftlint:enable function_body_length
}
class InvocationRecorder {
var invocations = [String]()
var unexpectedInvocations = [String]()
var cannedResults = [CannedResult]()
func expect(command: String, result: [String]) {
cannedResults.append(CannedResult(command: command, result: result))
}
@discardableResult
func bash(_ command: String) throws -> [String] {
self.invocations.append(command)
guard let index = self.cannedResults.index(where: { $0.command == command }) else {
self.unexpectedInvocations.append(command)
return []
}
return self.cannedResults.remove(at: index).result
}
struct CannedResult {
let command: String
let result: [String]
}
}
| mit | 8ad4c6b7612a2a6f5b58073f90933038 | 35.04878 | 106 | 0.550237 | 4.353461 | false | false | false | false |
sigmonky/hearthechanges | iHearChangesSwift/User Interface/MixPane.swift | 1 | 2815 | //
// MixPane.swift
// ComponentSwitch
//
// Created by Weinstein, Randy - Nick.com on 9/9/16.
// Copyright © 2016 atomicobject. All rights reserved.
//
import UIKit
protocol MixPaneDelegate: class {
func muteUnmuteVoice(_ sender:MixPane, voiceToChange:Int, voiceState:Bool)
}
class MixPane: UIViewController {
weak var delegate:MixPaneDelegate?
enum voiceState {
case voiceOn
case voiceOff
}
var voiceStates = [Bool]()
@IBOutlet weak var voice1Btn: UIButton!
@IBOutlet weak var voice2Btn: UIButton!
@IBOutlet weak var voice3Btn: UIButton!
@IBOutlet weak var voice4Btn: UIButton!
@IBOutlet weak var voice5Btn: UIButton!
@IBAction func muteOrUnmuteVoice(_ sender: UIButton) {
print(sender.tag)
var isSounding:Bool
if voiceStates[sender.tag - 1] {
isSounding = false
voiceStates[sender.tag - 1] = false
sender.setTitle("Voice \(sender.tag) muted", for: UIControlState.normal)
} else {
isSounding = true
voiceStates[sender.tag - 1] = true
sender.setTitle("Voice \(sender.tag)", for: UIControlState.normal)
}
delegate?.muteUnmuteVoice(self,voiceToChange:sender.tag,voiceState:isSounding)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showVoices(voices:Int,appState:AppState) {
voiceStates = appState.voiceStates
for i in 0..<5{
if let button = self.view.viewWithTag(i+1) as? UIButton
{
button.isHidden = true
}
}
for i in 0..<voices{
if let button = self.view.viewWithTag(i+1) as? UIButton
{
var theCurrenTitle:String
if (voiceStates[i]) {
theCurrenTitle = "Voice \(i+1)"
} else {
theCurrenTitle = "Voice \(i+1) muted"
}
button.setTitle(theCurrenTitle, for: UIControlState.normal)
button.isHidden = false
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0ab3a1e19dc980bca23d2e824efee689 | 27.14 | 106 | 0.578536 | 4.583062 | false | false | false | false |
adrfer/swift | test/Prototypes/MutableIndexableDict.swift | 3 | 14586 | // RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control %s -o %t.out
// RUN: %target-run %t.out | FileCheck %s
// REQUIRES: executable_test
// General Mutable, CollectionType, Value-Type Collections
// =================================================
//
// Basic copy-on-write (COW) requires a container's data to be copied
// into new storage before it is modified, to avoid changing the data
// of other containers that may share the data. There is one
// exception: when we know the container has the only reference to the
// data, we can elide the copy. This COW optimization is crucial for
// the performance of mutating algorithms.
//
// Some container elements (Characters in a String, key/value pairs in
// an open-addressing hash table) are not traversable with a fixed
// size offset, so incrementing/decrementing indices requires looking
// at the contents of the container. The current interface for
// incrementing/decrementing indices of an CollectionType is the usual ++i,
// --i. Therefore, for memory safety, the indices need to keep a
// reference to the container's underlying data so that it can be
// inspected. But having multiple outstanding references to the
// underlying data defeats the COW optimization.
//
// The way out is to count containers referencing the data separately
// from indices that reference the data. When deciding to elide the
// copy and modify the data directly---as long as we don't violate
// memory safety of any outstanding indices---we only need to be
// sure that no other containers are referencing the data.
//
// Implementation
// --------------
//
// Currently we use a data structure like this:
//
// Dictionary<K,V> (a struct)
// +---+
// | * |
// +-|-+
// |
// V DictionaryBufferOwner<K,V>
// +----------------+
// | * [refcount#1] |
// +-|--------------+
// |
// V FixedSizedRefArrayOfOptional<Pair<K,V>>
// +-----------------------------------------+
// | [refcount#2] [...element storage...] |
// +-----------------------------------------+
// ^
// +-|-+
// | * | Dictionary<K,V>.Index (a struct)
// +---+
//
//
// In reality, we'd optimize by allocating the DictionaryBufferOwner
// /inside/ the FixedSizedRefArrayOfOptional, and override the dealloc
// method of DictionaryBufferOwner to do nothing but release its
// reference.
//
// Dictionary<K,V> (a struct)
// +---+
// | * |
// +-|-+
// | +---+
// | | |
// | | V FixedSizeRefArrayOfOptional<Pair<K,V>>
// +---|--|-------------------------------------------+
// | | | |
// | | | [refcount#2] [...element storage...] |
// | | | |
// | V | DictionaryBufferOwner<K,V> |
// | +----|--------------+ |
// | | * [refcount#1] | |
// | +-------------------+ |
// +--------------------------------------------------+
// ^
// +-|-+
// | * | Dictionary<K,V>.Index (a struct)
// +---+
//
// Index Invalidation
// ------------------
//
// Indexing a container, "c[i]", uses the integral offset stored in
// the index to access the elements referenced by the container. The
// buffer referenced by the index is only used to increment and
// decrement the index. Most of the time, these two buffers will be
// identical, but they need not always be. For example, if one
// ensures that a Dictionary has sufficient capacity to avoid
// reallocation on the next element insertion, the following works
//
// var (i, found) = d.find(k) // i is associated with d's buffer
// if found {
// var e = d // now d is sharing its data with e
// e[newKey] = newValue // e now has a unique copy of the data
// return e[i] // use i to access e
// }
//
// The result should be a set of iterator invalidation rules familiar
// to anyone familiar with the C++ standard library. Note that
// because all accesses to a dictionary buffer are bounds-checked,
// this scheme never compromises memory safety.
import Swift
class FixedSizedRefArrayOfOptionalStorage<T> : _HeapBufferStorage<Int, T?> {
deinit {
let buffer = Buffer(self)
for i in 0..<buffer.value {
(buffer.baseAddress + i).destroy()
}
}
}
struct FixedSizedRefArrayOfOptional<T>
{
typealias Storage = FixedSizedRefArrayOfOptionalStorage<T>
let buffer: Storage.Buffer
init(capacity: Int)
{
buffer = Storage.Buffer(Storage.self, capacity, capacity)
for var i = 0; i < capacity; ++i {
(buffer.baseAddress + i).initialize(.None)
}
buffer.value = capacity
}
subscript(i: Int) -> T? {
get {
assert(i >= 0 && i < buffer.value)
return (buffer.baseAddress + i).memory
}
nonmutating
set {
assert(i >= 0 && i < buffer.value)
(buffer.baseAddress + i).memory = newValue
}
}
var count: Int {
get {
return buffer.value
}
nonmutating
set(newValue) {
buffer.value = newValue
}
}
}
struct DictionaryElement<Key: Hashable, Value> {
var key: Key
var value: Value
}
class DictionaryBufferOwner<Key: Hashable, Value> {
typealias Element = DictionaryElement<Key, Value>
typealias Buffer = FixedSizedRefArrayOfOptional<Element>
init(minimumCapacity: Int = 2) {
// Make sure there's a representable power of 2 >= minimumCapacity
assert(minimumCapacity <= (Int.max >> 1) + 1)
var capacity = 2
while capacity < minimumCapacity {
capacity <<= 1
}
buffer = Buffer(capacity: capacity)
}
var buffer: Buffer
}
func == <Element>(lhs: DictionaryIndex<Element>, rhs: DictionaryIndex<Element>) -> Bool {
return lhs.offset == rhs.offset
}
struct DictionaryIndex<Element> : BidirectionalIndexType {
typealias Index = DictionaryIndex<Element>
func predecessor() -> Index {
var j = self.offset
while --j > 0 {
if buffer[j] != nil {
return Index(buffer: buffer, offset: j)
}
}
return self
}
func successor() -> Index {
var i = self.offset + 1
// FIXME: Can't write the simple code pending
// <rdar://problem/15484639> Refcounting bug
while i < buffer.count /*&& !buffer[i]*/ {
// FIXME: workaround for <rdar://problem/15484639>
if buffer[i] != nil {
break
}
// end workaround
i += 1
}
return Index(buffer: buffer, offset: i)
}
var buffer: FixedSizedRefArrayOfOptional<Element>
var offset: Int
}
struct Dictionary<Key: Hashable, Value> : CollectionType, SequenceType {
typealias _Self = Dictionary<Key, Value>
typealias BufferOwner = DictionaryBufferOwner<Key, Value>
typealias Buffer = BufferOwner.Buffer
typealias Element = BufferOwner.Element
typealias Index = DictionaryIndex<Element>
/// \brief Create a dictionary with at least the given number of
/// elements worth of storage. The actual capacity will be the
/// smallest power of 2 that's >= minimumCapacity.
init(minimumCapacity: Int = 2) {
_owner = BufferOwner(minimumCapacity: minimumCapacity)
}
var startIndex: Index {
return Index(buffer: _buffer, offset: -1).successor()
}
var endIndex: Index {
return Index(buffer: _buffer, offset: _buffer.count)
}
subscript(i: Index) -> Element {
get {
return _buffer[i.offset]!
}
set(keyValue) {
assert(keyValue.key == self[i].key)
_buffer[i.offset] = .Some(keyValue)
}
}
var _maxLoadFactorInverse = 1.0 / 0.75
var maxLoadFactor : Double {
get {
return 1.0 / _maxLoadFactorInverse
}
mutating
set(newValue) {
// 1.0 might be useful for testing purposes; anything more is
// crazy
assert(newValue <= 1.0)
_maxLoadFactorInverse = 1.0 / newValue
}
}
subscript(key: Key) -> Value {
get {
return self[find(key).0].value
}
mutating
set(value) {
var (i, found) = find(key)
// count + 2 below ensures that we don't fill in the last hole
var minCapacity = found
? capacity
: max(Int(Double(count + 1) * _maxLoadFactorInverse), count + 2)
if (_ensureUniqueBuffer(minCapacity)) {
i = find(key).0
}
_buffer[i.offset] = Element(key: key, value: value)
if !found {
++_count
}
}
}
var capacity : Int {
return _buffer.count
}
var _bucketMask : Int {
return capacity - 1
}
/// \brief Ensure this Dictionary holds a unique reference to its
/// buffer having at least minimumCapacity elements. Return true
/// iff this results in a change of capacity.
mutating func _ensureUniqueBuffer(minimumCapacity: Int) -> Bool {
var isUnique: Bool = isUniquelyReferencedNonObjC(&_owner)
if !isUnique || capacity < minimumCapacity {
var newOwner = _Self(minimumCapacity: minimumCapacity)
print("reallocating with isUnique: \(isUnique) and capacity \(capacity)=>\(newOwner.capacity)")
for i in 0..<capacity {
var x = _buffer[i]
if x != nil {
if capacity == newOwner.capacity {
newOwner._buffer[i] = x
}
else {
newOwner[x!.key] = x!.value
}
}
}
newOwner._count = count
Swift.swap(&self, &newOwner)
return self.capacity != newOwner.capacity
}
return false
}
func _bucket(k: Key) -> Int {
return k.hashValue & _bucketMask
}
func _next(bucket: Int) -> Int {
return (bucket + 1) & _bucketMask
}
func _prev(bucket: Int) -> Int {
return (bucket - 1) & _bucketMask
}
func _find(k: Key, startBucket: Int) -> (Index,Bool) {
var bucket = startBucket
// The invariant guarantees there's always a hole, so we just loop
// until we find one.
assert(count < capacity)
while true {
var keyVal = _buffer[bucket]
if (keyVal == nil) || keyVal!.key == k {
return (Index(buffer: _buffer, offset: bucket), keyVal != nil)
}
bucket = _next(bucket)
}
}
func find(k: Key) -> (Index,Bool) {
return _find(k, startBucket: _bucket(k))
}
mutating
func deleteKey(k: Key) -> Bool {
var start = _bucket(k)
var (pos, found) = _find(k, startBucket: start)
if !found {
return false
}
// remove the element
_buffer[pos.offset] = .None
--_count
// If we've put a hole in a chain of contiguous elements, some
// element after the hole may belong where the new hole is.
var hole = pos.offset
// Find the last bucket in the contiguous chain
var lastInChain = hole
for var b = _next(lastInChain); _buffer[b] != nil; b = _next(b) {
lastInChain = b
}
// Relocate out-of-place elements in the chain, repeating until
// none are found.
while hole != lastInChain {
// Walk backwards from the end of the chain looking for
// something out-of-place.
var b: Int
for b = lastInChain; b != hole; b = _prev(b) {
var idealBucket = _bucket(_buffer[b]!.key)
// Does this element belong between start and hole? We need
// two separate tests depending on whether [start,hole] wraps
// around the end of the buffer
var c0 = idealBucket >= start
var c1 = idealBucket <= hole
if start < hole ? (c0 && c1) : (c0 || c1) {
break // found it
}
}
if b == hole { // No out-of-place elements found; we're done adjusting
break
}
// Move the found element into the hole
_buffer[hole] = _buffer[b]
_buffer[b] = .None
hole = b
}
return true
}
var count : Int {
return _count
}
var _count: Int = 0
var _owner: BufferOwner
var _buffer: Buffer {
return _owner.buffer
}
// Satisfying SequenceType
func generate() -> IndexingGenerator<_Self> {
return IndexingGenerator(self)
}
}
func == <K: Equatable, V: Equatable>(
lhs: Dictionary<K,V>, rhs: Dictionary<K,V>
) -> Bool {
if lhs.count != rhs.count {
return false
}
for lhsElement in lhs {
var (pos, found) = rhs.find(lhsElement.key)
// FIXME: Can't write the simple code pending
// <rdar://problem/15484639> Refcounting bug
/*
if !found || rhs[pos].value != lhsElement.value {
return false
}
*/
if !found {
return false
}
if rhs[pos].value != lhsElement.value {
return false
}
}
return true
}
func != <K: Equatable, V: Equatable>(
lhs: Dictionary<K,V>, rhs: Dictionary<K,V>
) -> Bool {
return !(lhs == rhs)
}
//
// Testing
//
// CHECK: testing
print("testing")
var d0 = Dictionary<Int, String>()
d0[0] = "zero"
print("Inserting #2")
// CHECK-NEXT: Inserting #2
d0[1] = "one"
// CHECK-NEXT: reallocating with isUnique: true and capacity 2=>4
d0[2] = "two"
var d1 = d0
print("copies are equal: \(d1 == d0)")
// CHECK-NEXT: copies are equal: true
d1[3] = "three"
// CHECK-NEXT: reallocating with isUnique: false and capacity 4=>8
print("adding a key to one makes them unequal: \(d1 != d0)")
// CHECK-NEXT: adding a key to one makes them unequal: true
d1.deleteKey(3)
print("deleting that key makes them equal again: \(d1 == d0)")
// ---------
class X : CustomStringConvertible {
var constructed : Bool
var id = 0
init() {print("X()"); constructed = true}
init(_ anID : Int) {
print("X(\(anID))")
id = anID; constructed = true
}
deinit {
print("~X(\(id))")
constructed = false
}
var description: String {
return "X(\(id))"
}
}
extension String {
init(_ x: X) {
self = "X(\(x.id))"
}
}
func display(v : Dictionary<Int, X>) {
print("[ ", terminator: "")
var separator = ""
for p in v {
print("\(separator) \(p.key) : \(p.value)", terminator: "")
separator = ", "
}
print(" ]")
}
func test() {
var v = Dictionary<Int, X>()
v[1] = X(1)
// CHECK: X(1)
display(v)
// CHECK-NEXT: [ 1 : X(1) ]
v[2] = X(2)
// CHECK-NEXT: X(2)
// CHECK-NEXT: reallocating with isUnique: true and capacity 2=>4
display(v)
// CHECK-NEXT: [ 1 : X(1), 2 : X(2) ]
v[3] = X(3)
// CHECK-NEXT: X(3)
display(v)
// CHECK-NEXT: [ 1 : X(1), 2 : X(2), 3 : X(3) ]
v[4] = X(4)
// CHECK-NEXT: X(4)
// CHECK-NEXT: reallocating with isUnique: true and capacity 4=>8
display(v)
// CHECK-NEXT: [ 1 : X(1), 2 : X(2), 3 : X(3), 4 : X(4) ]
// CHECK: ~X(1)
// CHECK: ~X(2)
// CHECK: ~X(3)
// CHECK: ~X(4)
}
test()
| apache-2.0 | fd4a554594f1f2a42f0b140cb7580290 | 25.665448 | 101 | 0.585836 | 3.666667 | false | false | false | false |
Alexandra-Institute/crowd-app | CrowdApp/RunViewController.swift | 1 | 7614 | //
// RunViewController.swift
// CrowdApp
//
// Created by Daniel Andersen on 25/11/14.
//
//
import UIKit
import CoreMotion
import AVFoundation
class RunViewController: UIViewController {
@IBOutlet weak var doubleTapToReturnLabel: UILabel!
var motionManager: CMMotionManager!
var mode: Int! = 0
var motionLastYaw: Double = 0.0
var angle: Double = 0.0
var colorLeft: UIColor! = UIColor.redColor()
var colorRight: UIColor! = UIColor.blueColor()
var colorUp: UIColor! = UIColor.greenColor()
var colorDown: UIColor! = UIColor.yellowColor()
var colorMovement: UIColor! = UIColor.whiteColor()
var colorAudio1: UIColor! = UIColor.greenColor()
var colorAudio2Red: CGFloat = 1.0
var colorAudio2Green: CGFloat = 1.0
var colorAudio2Blue: CGFloat = 0.0
var threshold: Double!
var flashEnabled: Bool!
var audioMeter: AudioMeter!
override func viewDidLoad() {
super.viewDidLoad()
self.initializeMotionManager()
self.initializeAudioMeter()
}
override func viewDidAppear(animated: Bool) {
UIView.animateKeyframesWithDuration(1.0, delay: 2.0, options: UIViewKeyframeAnimationOptions.allZeros, animations: { () -> Void in
self.doubleTapToReturnLabel.alpha = 0.0
}, { (Bool cancelled) -> Void in
self.doubleTapToReturnLabel.hidden = true
})
}
override func viewWillDisappear(animated: Bool) {
if (self.motionManager != nil) {
self.motionManager.stopAccelerometerUpdates()
}
if (self.audioMeter != nil) {
self.audioMeter.endAudioMetering()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initializeMotionManager() {
if (self.mode > 1) {
return
}
self.motionManager = CMMotionManager()
if (self.motionManager.accelerometerAvailable) {
self.motionManager.accelerometerUpdateInterval = 0.02
self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (accelerometerData: CMAccelerometerData!, error: NSError!) -> Void in
self.updateVisualization(accelerometerData)
})
}
}
func initializeAudioMeter() {
if (self.mode < 2) {
return
}
self.audioMeter = AudioMeter(samplePeriod: 0.1)
self.audioMeter.beginAudioMeteringWithCallback { (value: Double) -> Void in
self.updateVisualization(value)
}
}
func updateVisualization(accelerometerData: CMAccelerometerData!) {
switch (self.mode) {
case 0:
updateVisualizationMode1(accelerometerData)
break
case 1:
updateVisualizationMode2(accelerometerData)
break
default:
break
}
}
func updateVisualization(value: Double!) {
switch (self.mode) {
case 2:
updateVisualizationMode3(value)
break
case 3:
updateVisualizationMode4(value)
break
default:
break
}
}
func updateVisualizationMode1(accelerometerData: CMAccelerometerData!) {
if (abs(accelerometerData.acceleration.z) > 0.4 && abs(accelerometerData.acceleration.z) <= 0.9) {
return;
}
if (abs(accelerometerData.acceleration.z) > 0.9) {
self.view.backgroundColor = UIColor.blackColor()
return
}
self.angle = atan2(accelerometerData.acceleration.x, accelerometerData.acceleration.y)
if (self.angle < 0) {
self.angle += M_PI * 2
}
var color: UIColor
var buffer = M_PI / 16
if (angle >= M_PI * 2 - M_PI_4 + buffer || angle < M_PI_2 - M_PI_4 - buffer) {
self.view.backgroundColor = self.colorUp
}
if (angle >= M_PI_2 - M_PI_4 + buffer && angle < M_PI - M_PI_4 - buffer) {
self.view.backgroundColor = self.colorLeft
}
if (angle >= M_PI - M_PI_4 + buffer && angle < M_PI + M_PI_2 - M_PI_4 - buffer) {
self.view.backgroundColor = self.colorDown
}
if (angle >= M_PI + M_PI_2 - M_PI_4 + buffer && angle < M_PI * 2 - M_PI_4 - buffer) {
self.view.backgroundColor = self.colorRight
}
}
func updateVisualizationMode2(accelerometerData: CMAccelerometerData!) {
var force = accelerometerData.acceleration.x * accelerometerData.acceleration.x + accelerometerData.acceleration.y*accelerometerData.acceleration.y + accelerometerData.acceleration.z*accelerometerData.acceleration.z
force = abs(1.0 - force)
if (force > ((self.threshold * 50.0) + 3.0)) {
self.turnFlashOn()
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector:Selector("turnFlashOff"), userInfo:nil, repeats:false)
self.view.backgroundColor = self.colorMovement
UIView.animateKeyframesWithDuration(0.3, delay:0.0, options:UIViewKeyframeAnimationOptions.allZeros, animations: { () -> Void in
self.view.backgroundColor = UIColor.blackColor()
}, completion: nil)
}
}
func updateVisualizationMode3(value: Double!) {
var force = self.logarithmicThresholded(value)
if (force > 0.5) {
self.turnFlashOn()
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector:Selector("turnFlashOff"), userInfo:nil, repeats:false)
self.view.backgroundColor = self.colorAudio1
UIView.animateKeyframesWithDuration(0.3, delay:0.0, options:UIViewKeyframeAnimationOptions.allZeros, animations: { () -> Void in
self.view.backgroundColor = UIColor.blackColor()
}, completion: nil)
}
}
func updateVisualizationMode4(value: Double!) {
var force = self.logarithmicThresholded(value)
self.view.backgroundColor = UIColor(red: self.colorAudio2Red, green: self.colorAudio2Green, blue: self.colorAudio2Blue, alpha: CGFloat(force))
}
func logarithmicThresholded(value: Double!) -> Double! {
var l = log10(value) // [-inf, 0]
l = (l + 1.0 + (1.0 - self.threshold)) // [-inf, 1]
return max(0.0, min(1.0, l))
}
func turnFlashOn() {
self.toggleTorc(true)
}
func turnFlashOff() {
self.toggleTorc(false)
}
func toggleTorc(toggle: Bool!) {
if (!self.flashEnabled.boolValue) {
return
}
var captureDeviceClass: AnyClass! = NSClassFromString("AVCaptureDevice");
if (captureDeviceClass != nil) {
var device: AVCaptureDevice! = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo);
if (device.hasTorch && device.hasFlash){
device.lockForConfiguration(nil);
if (toggle.boolValue) {
device.torchMode = AVCaptureTorchMode.On
device.flashMode = AVCaptureFlashMode.On
} else {
device.torchMode = AVCaptureTorchMode.Off
device.flashMode = AVCaptureFlashMode.Off
}
device.unlockForConfiguration()
}
}
}
@IBAction func doubleTapped(sender: UITapGestureRecognizer) {
self.navigationController?.popViewControllerAnimated(true)
}
}
| lgpl-3.0 | 040decf90f1985d60248ad70f832d12e | 33.452489 | 223 | 0.606514 | 4.537545 | false | false | false | false |
astralbodies/CleanRooms | CleanRoomsTests/MockNSURLSession.swift | 1 | 2688 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
// Based off of http://swiftandpainless.com/stubbing-nsurlsession-with-dependency-injection/
class MockNSURLSession: NSURLSession {
var completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?
static var mockResponse: (data: NSData?, urlResponse: NSURLResponse?, error: NSError?) = (data: nil, urlResponse: nil, error: nil)
override class func sharedSession() -> NSURLSession {
return MockNSURLSession()
}
override func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask {
self.completionHandler = completionHandler
return MockTask(response: MockNSURLSession.mockResponse, completionHandler: completionHandler)
}
override func dataTaskWithURL(url: NSURL, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask {
self.completionHandler = completionHandler
return MockTask(response: MockNSURLSession.mockResponse, completionHandler: completionHandler)
}
class MockTask: NSURLSessionDataTask {
typealias Response = (data: NSData?, urlResponse: NSURLResponse?, error: NSError?)
var mockResponse: Response
let completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?
init(response: Response, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) {
self.mockResponse = response
self.completionHandler = completionHandler
}
override func resume() {
completionHandler!(mockResponse.data, mockResponse.urlResponse, mockResponse.error)
}
}
}
| mit | efd86303bd9b1e3cccac26b0fee75c62 | 45.344828 | 148 | 0.758185 | 4.950276 | false | false | false | false |
AlexLittlejohn/OMDBMovies | OMDBMovies/Networking/MovieSearchRequest.swift | 1 | 2346 | //
// MovieSearchRequest.swift
// OMDBMovies
//
// Created by Alex Littlejohn on 2016/04/04.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
let searchURL = NSURL(string: "http://www.omdbapi.com/")
typealias MovieSearchResults = (total: Int, movies: [MovieResult])
typealias MovieSearchRequestCompletion = (results: MovieSearchResults?, error: ErrorType?) -> Void
struct MovieSearchRequest {
let searchTerm: String
}
extension MovieSearchRequest {
func work(completion: MovieSearchRequestCompletion) -> NSURLSessionDataTask? {
guard let escaped = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()),
url = NSURL(string: "?type=movie&s=\(escaped)", relativeToURL: searchURL) else {
completion(results: nil, error: MovieSearchRequestError.InvalidSearchTerm)
return nil
}
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
dispatch_async(dispatch_get_main_queue()) {
guard let data = data, results = self.deserializeResults(data) else {
completion(results: nil, error: MovieSearchRequestError.InvalidResults)
return
}
completion(results: results, error: nil)
}
}
task.resume()
return task
}
func deserializeResults(data: NSData) -> MovieSearchResults? {
guard let JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments),
JSONDictionary = JSON as? NSDictionary,
response = JSONDictionary["Response"]?.boolValue,
total = JSONDictionary["totalResults"]?.integerValue,
movieObjects = JSONDictionary["Search"] as? NSArray where response else {
return nil
}
var movies = [MovieResult]()
for movieObject in movieObjects {
guard let dictionary = movieObject as? JSONObject else {
continue
}
let result = MovieResult(JSON: dictionary)
movies.append(result)
}
return (total, movies)
}
}
| mit | 1b0f2646103ec7256430b6c6a86cf833 | 33.485294 | 121 | 0.611514 | 5.453488 | false | false | false | false |
C4Framework/C4iOS | C4/UI/Image+Generator.swift | 2 | 2208 | // Copyright © 2014 C4
//
// 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 QuartzCore
import UIKit
extension Image {
/// Applies a generator to the receiver's contents.
///
/// - parameter generator: a Generator
public func generate(_ generator: Generator) {
let crop = CIFilter(name: "CICrop")!
crop.setDefaults()
crop.setValue(CIVector(cgRect: CGRect(self.bounds)), forKey: "inputRectangle")
let generatorFilter = generator.createCoreImageFilter()
crop.setValue(generatorFilter.outputImage, forKey: "inputImage")
if var outputImage = crop.outputImage {
let scale = CGAffineTransform(scaleX: 1, y: -1)
outputImage = outputImage.transformed(by: scale)
output = outputImage
//Need to output a CGImage that matches the current image's extent, {0, -h, w, h}
let cgimg = CIContext().createCGImage(self.output, from: outputImage.extent)
self.imageView.image = UIImage(cgImage: cgimg!)
_originalSize = Size(outputImage.extent.size)
} else {
print("Failed to generate outputImage: \(#function)")
}
}
}
| mit | 438574d70849d8c142743a9c03ddbca5 | 45.957447 | 93 | 0.700952 | 4.665962 | false | false | false | false |
jeffreybergier/SwiftLint | Source/SwiftLintFramework/Rules/UnusedClosureParameterRule.swift | 1 | 8633 | //
// UnusedClosureParameterRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/15/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct UnusedClosureParameterRule: ASTRule, ConfigurationProviderRule, CorrectableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "unused_closure_parameter",
name: "Unused Closure Parameter",
description: "Unused parameter in a closure should be replaced with _.",
nonTriggeringExamples: [
"[1, 2].map { $0 + 1 }\n",
"[1, 2].map({ $0 + 1 })\n",
"[1, 2].map { number in\n number + 1 \n}\n",
"[1, 2].map { _ in\n 3 \n}\n",
"[1, 2].something { number, idx in\n return number * idx\n}\n",
"let isEmpty = [1, 2].isEmpty()\n",
"violations.sorted(by: { lhs, rhs in \n return lhs.location > rhs.location\n})\n",
"rlmConfiguration.migrationBlock.map { rlmMigration in\n" +
"return { migration, schemaVersion in\n" +
"rlmMigration(migration.rlmMigration, schemaVersion)\n" +
"}\n" +
"}",
"genericsFunc { (a: Type, b) in\n" +
"a + b\n" +
"}\n",
"var label: UILabel = { (lbl: UILabel) -> UILabel in\n" +
" lbl.backgroundColor = .red\n" +
" return lbl\n" +
"}(UILabel())\n"
],
triggeringExamples: [
"[1, 2].map { ↓number in\n return 3\n}\n",
"[1, 2].map { ↓number in\n return numberWithSuffix\n}\n",
"[1, 2].map { ↓number in\n return 3 // number\n}\n",
"[1, 2].map { ↓number in\n return 3 \"number\"\n}\n",
"[1, 2].something { number, ↓idx in\n return number\n}\n",
"genericsFunc { (↓number: TypeA, idx: TypeB) in return idx\n}\n"
],
corrections: [
"[1, 2].map { ↓number in\n return 3\n}\n":
"[1, 2].map { _ in\n return 3\n}\n",
"[1, 2].map { ↓number in\n return numberWithSuffix\n}\n":
"[1, 2].map { _ in\n return numberWithSuffix\n}\n",
"[1, 2].map { ↓number in\n return 3 // number\n}\n":
"[1, 2].map { _ in\n return 3 // number\n}\n",
"[1, 2].map { ↓number in\n return 3 \"number\"\n}\n":
"[1, 2].map { _ in\n return 3 \"number\"\n}\n",
"[1, 2].something { number, ↓idx in\n return number\n}\n":
"[1, 2].something { number, _ in\n return number\n}\n",
"genericsFunc(closure: { (↓int: Int) -> Void in // do something\n}\n":
"genericsFunc(closure: { (_: Int) -> Void in // do something\n}\n",
"genericsFunc { (↓a, ↓b: Type) -> Void in\n}\n":
"genericsFunc { (_, _: Type) -> Void in\n}\n",
"genericsFunc { (↓a: Type, ↓b: Type) -> Void in\n}\n":
"genericsFunc { (_: Type, _: Type) -> Void in\n}\n",
"genericsFunc { (↓a: Type, ↓b) -> Void in\n}\n":
"genericsFunc { (_: Type, _) -> Void in\n}\n",
"genericsFunc { (a: Type, ↓b) -> Void in\nreturn a\n}\n":
"genericsFunc { (a: Type, _) -> Void in\nreturn a\n}\n"
]
)
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return violationRanges(in: file, dictionary: dictionary, kind: kind).map { range, name in
let reason = "Unused parameter \"\(name)\" in a closure should be replaced with _."
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location),
reason: reason)
}
}
private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable],
kind: SwiftExpressionKind) -> [(range: NSRange, name: String)] {
guard kind == .call,
!isClosure(dictionary: dictionary),
let offset = dictionary.offset,
let length = dictionary.length,
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let bodyLength = dictionary.bodyLength,
bodyLength > 0 else {
return []
}
let rangeStart = nameOffset + nameLength
let rangeLength = (offset + length) - (nameOffset + nameLength)
let parameters = dictionary.enclosedVarParameters
let contents = file.contents.bridge()
return parameters.flatMap { param -> (NSRange, String)? in
guard let paramOffset = param.offset,
let name = param.name,
name != "_",
let regex = try? NSRegularExpression(pattern: name,
options: [.ignoreMetacharacters]),
let range = contents.byteRangeToNSRange(start: rangeStart, length: rangeLength)
else {
return nil
}
let paramLength = name.bridge().length
let matches = regex.matches(in: file.contents, options: [], range: range).ranges()
for range in matches {
guard let byteRange = contents.NSRangeToByteRange(start: range.location,
length: range.length),
// if it's the parameter declaration itself, we should skip
byteRange.location != paramOffset,
case let tokens = file.syntaxMap.tokens(inByteRange: byteRange),
// a parameter usage should be only one token
tokens.count == 1 else {
continue
}
// found a usage, there's no violation!
if let token = tokens.first, SyntaxKind(rawValue: token.type) == .identifier,
token.offset == byteRange.location, token.length == byteRange.length {
return nil
}
}
if let range = contents.byteRangeToNSRange(start: paramOffset, length: paramLength) {
return (range, name)
}
return nil
}
}
private func isClosure(dictionary: [String: SourceKitRepresentable]) -> Bool {
return dictionary.name.flatMap { name -> Bool in
let length = name.bridge().length
let range = NSRange(location: 0, length: length)
return regex("\\A\\s*\\{").firstMatch(in: name, options: [], range: range) != nil
} ?? false
}
private func violationRanges(in file: File,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
return dictionary.substructure.flatMap { subDict -> [NSRange] in
guard let kindString = subDict.kind,
let kind = SwiftExpressionKind(rawValue: kindString) else {
return []
}
return violationRanges(in: file, dictionary: subDict) +
violationRanges(in: file, dictionary: subDict, kind: kind).map({ $0.0 })
}
}
private func violationRanges(in file: File) -> [NSRange] {
return violationRanges(in: file, dictionary: file.structure.dictionary).sorted { lhs, rhs in
lhs.location < rhs.location
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: "_")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
| mit | 67c2e2b5e6a7f98cc219782ddf9cfd4c | 44.957219 | 101 | 0.533861 | 4.445939 | false | false | false | false |
gogunskiy/The-Name | NameMe/Classes/UserInterface/ViewControllers/NMNameDetailsViewController/views/NMNameDetailsNotesCell.swift | 1 | 1293 | //
// NMNameDetailsNotesCell.swift
// NameMe
//
// Created by Vladimir Gogunsky on 1/9/15.
// Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved.
//
import UIKit
class NMNameDetailsNotesCell : NMNameDetailsBaseCell {
@IBOutlet var notesLabel : UILabel!
weak var delegate : NMNameDetailsNotesCellDelegate!
override func update(nameDetails: NMNameItem?) {
notesLabel.text = nameDetails?.notes?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
setNeedsLayout()
}
override func layoutSubviews() {
if !notesLabel.text!.isEmpty && notesLabel.frame.size.height != height {
notesLabel.frame = CGRectMake(8, 0, CGRectGetWidth(bounds) - 16, 0)
notesLabel.sizeToFit()
notesLabel.frame = CGRectMake(8, 0, CGRectGetWidth(notesLabel.bounds) - 16, CGRectGetHeight(notesLabel.bounds) + 16.0)
if notesLabel.frame.size.height < 44.0 {
notesLabel.frame.size.height = 44.0
}
height = CGRectGetHeight(notesLabel.bounds)
delegate?.didReloadNotesCellItem();
}
}
}
protocol NMNameDetailsNotesCellDelegate : NSObjectProtocol {
func didReloadNotesCellItem();
} | mit | b489940d7b467c7a30b9599ac80f39eb | 29.093023 | 130 | 0.651199 | 4.505226 | false | false | false | false |
EZ-NET/CodePiece | CodePiece/Windows/CodePieceMain/MainViewController+Fields.swift | 1 | 4044 | //
// MainViewController+Fields.swift
// CodePiece
//
// Created by Tomohiro Kumagai on 1/19/16.
// Copyright © 2016 EasyStyle G.K. All rights reserved.
//
import Cocoa
import ESTwitter
enum ReplyStyle {
case NormalPost
case ReplyPost
case ChainPost
}
// FIXME: プロトコルにする必要があるのか再検討。当初は MainViewController が肥大化するのをプロトコルで避けたのかもしれないが、今に思うと用途が違う印象。
protocol FieldsController {
var codeScrollView: NSScrollView! { get }
var codeTextView: CodeTextView! { get }
var descriptionTextField: DescriptionTextField! { get }
var hashTagTextField: HashtagTextField! { get }
var languagePopUpButton: NSPopUpButton! { get }
var languageWatermark: WatermarkLabel! { get }
var hashtagWatermark: WatermarkLabel! { get }
var postButton: NSButton! { get }
var descriptionCountLabel: NSTextField! { get }
func updateControlsDisplayText()
func updateTweetTextCount()
func updatePostButtonTitle()
func updateLanguageWatermark()
func updateHashtagWatermark()
func getPostButtonTitle() -> String
func clearReplyingStatus()
func clearCodeText()
func clearDescriptionText()
func clearHashtags()
}
extension FieldsController {
func updateWatermark() {
updateLanguageWatermark()
updateHashtagWatermark()
}
}
extension MainViewController : FieldsController {
func updateLanguageWatermark() {
languageWatermark.stringValue = selectedLanguage.description
updateHashtagWatermark()
}
func updateHashtagWatermark() {
let hashtags = customHashtagsExcludeLanguageHashtag + [selectedLanguage.hashtag]
hashtagWatermark.stringValue = hashtags.twitterDisplayText
}
}
extension FieldsController {
func clearContents() {
clearCodeText()
clearDescriptionText()
clearReplyingStatus()
updateControlsDisplayText()
}
func focusToDefaultControl() {
focusToCodeArea()
}
func focusToCodeArea() {
codeScrollView.becomeFirstResponder()
}
func focusToDescription() {
descriptionTextField.becomeFirstResponder()
}
func focusToHashtag() {
hashTagTextField.becomeFirstResponder()
}
func focusToLanguage() {
// MARK: 😒 I don't know how to show NSPopUpButton's submenu manually. The corresponding menu item is disabled too.
}
}
extension FieldsController where Self : PostDataManageable {
func updateTweetTextCount() {
descriptionCountLabel.stringValue = String(descriptionCountForPost)
descriptionCountLabel.textColor = .neutralColor
}
}
// extension FieldsController where Self : ViewControllerSelectionAndRepliable {
extension MainViewController {
func getPostButtonTitle() -> String {
switch replyStyle {
case .NormalPost:
return codeTextView.hasCode ? "Post Gist" : "Tweet"
case .ReplyPost:
return "Reply"
case .ChainPost:
return "Chain Post"
}
}
var replyStyle: ReplyStyle {
guard let status = statusForReplyTo else {
return .NormalPost
}
if NSApp.twitterController.isMyTweet(status: status) {
return .ChainPost
}
else {
return descriptionTextField.containsScreenName(screenName: status.user.screenName) ? .ReplyPost : .NormalPost
}
}
var isReplying: Bool {
switch replyStyle {
case .NormalPost:
return false
case .ReplyPost:
return true
case .ChainPost:
return true
}
}
}
extension FieldsController where Self : KeyValueChangeable {
func updateControlsDisplayText() {
updateTweetTextCount()
updatePostButtonTitle()
updateWatermark()
}
func updatePostButtonTitle() {
postButton.title = getPostButtonTitle()
}
func clearCodeText() {
withChangeValue(for: "canPost") {
codeTextView.clearCodeText()
}
}
func clearDescriptionText() {
withChangeValue(for: "canPost") {
descriptionTextField.clearTwitterText()
}
}
func clearHashtags() {
withChangeValue(for: "canPost") {
hashTagTextField.hashtags = []
updateHashtagWatermark()
}
}
}
| gpl-3.0 | 831736631b072f8ac0eb8ee707d1c103 | 17.657143 | 116 | 0.731496 | 3.752874 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/GutenbergWeb/GutenbergWebViewController.swift | 1 | 7143 | import UIKit
import WebKit
import Gutenberg
class GutenbergWebViewController: GutenbergWebSingleBlockViewController, WebKitAuthenticatable, NoResultsViewHost {
enum GutenbergWebError: Error {
case wrongEditorUrl(String?)
}
let authenticator: RequestAuthenticator?
private let url: URL
private let progressView = WebProgressView()
private let userId: String
let gutenbergReadySemaphore = DispatchSemaphore(value: 0)
init(with post: AbstractPost, block: Block) throws {
authenticator = GutenbergRequestAuthenticator(blog: post.blog)
userId = "\(post.blog.userID ?? 1)"
guard
let siteURL = post.blog.homeURL,
// Use wp-admin URL since Calypso URL won't work retriving the block content.
let editorURL = URL(string: "\(siteURL)/wp-admin/post-new.php")
else {
throw GutenbergWebError.wrongEditorUrl(post.blog.homeURL as String?)
}
url = editorURL
try super.init(block: block, userId: userId, isWPOrg: !post.blog.isHostedAtWPcom)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
addNavigationBarElements()
showLoadingMessage()
addProgressView()
startObservingWebView()
waitForGutenbergToLoad(fallback: showTroubleshootingInstructions)
}
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard
let object = object as? WKWebView,
object == webView,
let keyPath = keyPath
else {
return
}
switch keyPath {
case #keyPath(WKWebView.estimatedProgress):
progressView.progress = Float(webView.estimatedProgress)
progressView.isHidden = webView.estimatedProgress == 1
default:
assertionFailure("Observed change to web view that we are not handling")
}
}
override func getRequest(for webView: WKWebView, completion: @escaping (URLRequest) -> Void) {
authenticatedRequest(for: url, on: webView) { (request) in
completion(request)
}
}
override func onPageLoadScripts() -> [WKUserScript] {
return [
loadCustomScript(named: "extra-localstorage-entries", with: userId)
].compactMap { $0 }
}
override func onGutenbergReadyScripts() -> [WKUserScript] {
return [
loadCustomScript(named: "remove-nux")
].compactMap { $0 }
}
override func onGutenbergLoadStyles() -> [WKUserScript] {
return [
loadCustomStyles(named: "external-style-overrides")
].compactMap { $0 }
}
override func onGutenbergReady() {
super.onGutenbergReady()
navigationItem.rightBarButtonItem?.isEnabled = true
DispatchQueue.main.async { [weak self] in
self?.hideNoResults()
self?.gutenbergReadySemaphore.signal()
}
}
private func loadCustomScript(named name: String, with argument: String? = nil) -> WKUserScript? {
do {
return try SourceFile(name: name, type: .js).jsScript(with: argument)
} catch {
assertionFailure("Failed to load `\(name)` JS script for Unsupported Block Editor: \(error)")
return nil
}
}
private func loadCustomStyles(named name: String, with argument: String? = nil) -> WKUserScript? {
do {
return try SourceFile(name: name, type: .css).jsScript(with: argument)
} catch {
assertionFailure("Failed to load `\(name)` CSS script for Unsupported Block Editor: \(error)")
return nil
}
}
private func addNavigationBarElements() {
let buttonTitle = NSLocalizedString("Continue", comment: "Apply changes localy to single block edition in the web block editor")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: buttonTitle,
style: .done,
target: self,
action: #selector(onSaveButtonPressed)
)
navigationItem.rightBarButtonItem?.isEnabled = false
}
private func showLoadingMessage() {
let title = NSLocalizedString("Loading the block editor.", comment: "Loading message shown while the Unsupported Block Editor is loading.")
let subtitle = NSLocalizedString("Please ensure the block editor is enabled on your site. If it is not enabled, it will not load.", comment: "Message asking users to make sure that the block editor is enabled on their site in order for the Unsupported Block Editor to load properly.")
configureAndDisplayNoResults(on: view, title: title, subtitle: subtitle, accessoryView: NoResultsViewController.loadingAccessoryView())
}
private func waitForGutenbergToLoad(fallback: @escaping () -> Void) {
DispatchQueue.global(qos: .background).async { [weak self] in
let timeout: TimeInterval = 15
// blocking call
if self?.gutenbergReadySemaphore.wait(timeout: .now() + timeout) == .timedOut {
DispatchQueue.main.async {
fallback()
}
}
}
}
private func showTroubleshootingInstructions() {
let title = NSLocalizedString("Unable to load the block editor right now.", comment: "Title message shown when the Unsupported Block Editor fails to load.")
let subtitle = NSLocalizedString("Please ensure the block editor is enabled on your site and try again.", comment: "Subtitle message shown when the Unsupported Block Editor fails to load. It asks users to verify that the block editor is enabled on their site before trying again.")
// This does nothing if the "no results" screen is not currently displayed, which is the intended behavior
updateNoResults(title: title, subtitle: subtitle, image: "cloud")
}
private func startObservingWebView() {
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [.new], context: nil)
}
private func addProgressView() {
progressView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressView)
NSLayoutConstraint.activate([
progressView.topAnchor.constraint(equalTo: view.topAnchor),
progressView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
progressView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
}
extension GutenbergWebViewController {
override func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
super.webView(webView, didCommit: navigation)
if webView.url?.absoluteString.contains("reauth=1") ?? false {
hideNoResults()
removeCoverViewAnimated()
}
}
}
| gpl-2.0 | 2d75162e815622a4c50611e5db28a659 | 39.355932 | 292 | 0.656447 | 5.12043 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.