repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
White-Label/Swift-SDK | Example/WhiteLabel/MixtapeTableViewController.swift | 1 | 5362 | //
// MixtapeTableViewController.swift
//
// Created by Alex Givens http://alexgivens.com on 7/28/16
// Copyright © 2016 Noon Pacific LLC http://noonpacific.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import CoreData
import WhiteLabel
class MixtapeTableViewController: UITableViewController {
var collection: WLCollection!
var fetchedResultsController: NSFetchedResultsController<WLMixtape>!
let paging = PagingGenerator(startPage: 1)
override func viewDidLoad() {
super.viewDidLoad()
title = collection.title
refreshControl?.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
// Setup fetched results controller
let fetchRequest = WLMixtape.sortedFetchRequest(forCollection: self.collection)
let managedObjectContext = CoreDataStack.shared.backgroundManagedObjectContext
fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: nil,
cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
// Setup the paging generator with White Label
paging.next = { page, completionMarker in
if page == 1 {
WLMixtape.deleteMixtapes(forCollection: self.collection)
}
WhiteLabel.ListMixtapes(inCollection: self.collection, page: page) { result, total, pageSize in
switch result {
case .success(let mixtapes):
if mixtapes.count < pageSize {
self.paging.reachedEnd()
}
completionMarker(true)
case .failure(let error):
debugPrint(error)
completionMarker(false)
}
}
}
paging.getNext() // Initial load
}
@objc func handleRefresh(refreshControl: UIRefreshControl) {
paging.reset()
paging.getNext() {
refreshControl.endRefreshing()
}
}
// MARK: Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.Mixtape, for: indexPath)
let mixtape = fetchedResultsController.object(at: indexPath)
cell.textLabel?.text = mixtape.title
cell.detailTextLabel?.text = String(mixtape.trackCount)
return cell
}
// MARK: Delegate
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if // Infinite scroll trigger
let cellCount = tableView.dataSource?.tableView(tableView, numberOfRowsInSection: indexPath.section),
indexPath.row == cellCount - 1,
paging.isFetchingPage == false,
paging.didReachEnd == false
{
paging.getNext()
}
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard
segue.identifier == SegueIdentifier.MixtapesToTracks,
let trackTableViewController = segue.destination as? TrackTableViewController,
let selectedIndexPath = tableView.indexPathsForSelectedRows?[0]
else {
return
}
let mixtape = fetchedResultsController.object(at: selectedIndexPath)
trackTableViewController.mixtape = mixtape
}
}
extension MixtapeTableViewController: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.reloadData()
}
}
| mit |
necrowman/CRLAlamofireFuture | Examples/SimpleWatchOSCarthage/SimpleWatchOSCarthage WatchKit Extension/InterfaceController.swift | 56 | 839 | //
// InterfaceController.swift
// SimpleWatchOSCarthage WatchKit Extension
//
// Created by Ruslan Yupyn on 7/5/16.
// Copyright © 2016 Crossroad Labs. All rights reserved.
//
import WatchKit
import Foundation
import CRLAlamofireFuture
class InterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
print(CRLAlamofireFuture.instance.frameworkFunctionExample())
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| mit |
WhisperSystems/Signal-iOS | SignalMessaging/attachments/OWSVideoPlayer.swift | 1 | 2587 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import AVFoundation
@objc
public protocol OWSVideoPlayerDelegate: class {
func videoPlayerDidPlayToCompletion(_ videoPlayer: OWSVideoPlayer)
}
@objc
public class OWSVideoPlayer: NSObject {
@objc
public let avPlayer: AVPlayer
let audioActivity: AudioActivity
let shouldLoop: Bool
@objc
weak public var delegate: OWSVideoPlayerDelegate?
@objc
convenience public init(url: URL) {
self.init(url: url, shouldLoop: false)
}
@objc
public init(url: URL, shouldLoop: Bool) {
self.avPlayer = AVPlayer(url: url)
self.audioActivity = AudioActivity(audioDescription: "[OWSVideoPlayer] url:\(url)", behavior: .playback)
self.shouldLoop = shouldLoop
super.init()
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidPlayToCompletion(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
}
// MARK: Dependencies
var audioSession: OWSAudioSession {
return Environment.shared.audioSession
}
// MARK: Playback Controls
@objc
public func pause() {
avPlayer.pause()
audioSession.endAudioActivity(self.audioActivity)
}
@objc
public func play() {
let success = audioSession.startAudioActivity(self.audioActivity)
assert(success)
guard let item = avPlayer.currentItem else {
owsFailDebug("video player item was unexpectedly nil")
return
}
if item.currentTime() == item.duration {
// Rewind for repeated plays, but only if it previously played to end.
avPlayer.seek(to: CMTime.zero)
}
avPlayer.play()
}
@objc
public func stop() {
avPlayer.pause()
avPlayer.seek(to: CMTime.zero)
audioSession.endAudioActivity(self.audioActivity)
}
@objc(seekToTime:)
public func seek(to time: CMTime) {
avPlayer.seek(to: time)
}
// MARK: private
@objc
private func playerItemDidPlayToCompletion(_ notification: Notification) {
self.delegate?.videoPlayerDidPlayToCompletion(self)
if shouldLoop {
avPlayer.seek(to: CMTime.zero)
avPlayer.play()
} else {
audioSession.endAudioActivity(self.audioActivity)
}
}
}
| gpl-3.0 |
practicalswift/swift | validation-test/compiler_crashers_fixed/02038-llvm-bitstreamcursor-readvbr.swift | 65 | 580 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol d : a {
protocol a {
protocol a {
}
func c: [B
protocol b = {
}
}
protocol b {
}() -> {
return !.substringWithRange(T>(".A: k.init(f.startIndex)(2, T>) {
class B<b: b: c]()
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureQRCodeScanner/Sources/FeatureQRCodeScannerUI/QRCodeScanner/QRCodeScannerViewOverlay.swift | 1 | 9547 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Localization
import UIKit
final class QRCodeScannerViewOverlay: UIView {
private enum Images {
case cameraRoll
case connectedDapps
case flashDisabled
case flashEnabled
case target
private var name: String {
switch self {
case .cameraRoll:
return "camera-roll-button"
case .connectedDapps:
return "connectedDappsIcon"
case .flashDisabled:
return "flashDisabled"
case .flashEnabled:
return "flashEnabled"
case .target:
return "target"
}
}
var image: UIImage? {
UIImage(
named: name,
in: .featureQRCodeScannerUI,
with: nil
)
}
}
/// The area that the QR code must be within.
var scannableFrame: CGRect {
// We want a 280x280 square.
let halfAxis: CGFloat = 140
// We have the target coordinate space bounds.
let targetBounds = targetCoordinateSpace.bounds
// We create a rect representing a 280x280 square in the middle of target.
let targetSquare = CGRect(
x: targetBounds.midX - halfAxis,
y: targetBounds.midY - halfAxis,
width: 2 * halfAxis,
height: 2 * halfAxis
)
// We convert the rect from the target coordinate space into ours.
return convert(targetSquare, from: targetCoordinateSpace)
}
private let viewModel: QRCodeScannerOverlayViewModel
private let scanningViewFinder = UIView()
private let flashButton = UIButton()
private let cameraRollButton = UIButton()
private let connectedDappsButton = UIButton()
private let subtitleLabel = UILabel()
private let titleLabel = UILabel()
private var cancellables = [AnyCancellable]()
private let targetCoordinateSpace: UICoordinateSpace
private let cameraRollButtonSubject = PassthroughSubject<Void, Never>()
private let flashButtonSubject = PassthroughSubject<Void, Never>()
private let connectedDAppsButtonSubject = PassthroughSubject<Void, Never>()
private let targetImageView = UIImageView(image: Images.target.image)
init(viewModel: QRCodeScannerOverlayViewModel, targetCoordinateSpace: UICoordinateSpace) {
self.viewModel = viewModel
self.targetCoordinateSpace = targetCoordinateSpace
super.init(frame: .zero)
setupSubviews()
viewModel.scanSuccess
.receive(on: DispatchQueue.main)
.sink { [weak self] result in
switch result {
case .success(let success):
self?.setScanningBorder(color: success ? .successBorder : .idleBorder)
case .failure:
self?.setScanningBorder(color: .errorBorder)
}
}
.store(in: &cancellables)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setScanningBorder(color: UIColor) {
UIView.animate(withDuration: 0.3) {
self.targetImageView.tintColor = color
}
}
private func setupSubviews() {
backgroundColor = UIColor.darkFadeBackground.withAlphaComponent(0.9)
setupButtons()
setupLabels()
setupBorderView()
}
private func setupLabels() {
viewModel.titleLabelContent
.receive(on: DispatchQueue.main)
.sink { [weak self] in
self?.titleLabel.content = $0
}
.store(in: &cancellables)
addSubview(subtitleLabel)
subtitleLabel.layoutToSuperview(.leading, offset: 24)
subtitleLabel.layoutToSuperview(.trailing, offset: -24)
subtitleLabel.layoutToSuperview(.top, offset: 16)
subtitleLabel.numberOfLines = 0
viewModel.subtitleLabelContent
.receive(on: DispatchQueue.main)
.sink { [weak self] in
self?.subtitleLabel.content = $0
}
.store(in: &cancellables)
}
private func setupButtons() {
addSubview(flashButton)
addSubview(cameraRollButton)
addSubview(targetImageView)
addSubview(connectedDappsButton)
cameraRollButton.addTarget(self, action: #selector(onCameraRollTap), for: .touchUpInside)
cameraRollButton.layout(size: .edge(44))
cameraRollButton.layoutToSuperview(.trailing, offset: -44)
cameraRollButton.layoutToSuperview(.bottom, offset: -64)
flashButton.layout(size: .edge(44))
flashButton.layoutToSuperview(.centerX)
flashButton.layout(edge: .top, to: .bottom, of: targetImageView, offset: 20)
flashButton.addTarget(self, action: #selector(onFlashButtonTap), for: .touchUpInside)
connectedDappsButton.layoutToSuperview(.bottom, offset: -50)
connectedDappsButton.layoutToSuperview(.centerX)
connectedDappsButton.layout(dimension: .height, to: 48)
viewModel
.cameraRollButtonVisibility
.map(\.isHidden)
.receive(on: RunLoop.main)
.sink { [weak self] in
self?.cameraRollButton.isHidden = $0
}
.store(in: &cancellables)
viewModel
.dAppsButtonVisibility
.map(\.isHidden)
.receive(on: RunLoop.main)
.sink { [weak self] in
self?.connectedDappsButton.isHidden = $0
}
.store(in: &cancellables)
viewModel
.dAppsButtonTitle
.receive(on: RunLoop.main)
.sink { [weak self] in
self?.connectedDappsButton.setTitle($0, for: .normal)
}
.store(in: &cancellables)
cameraRollButtonSubject
.eraseToAnyPublisher()
.throttle(
for: .milliseconds(200),
scheduler: DispatchQueue.global(qos: .background),
latest: false
)
.sink { [weak self] in self?.viewModel.cameraTapRelay.send($0) }
.store(in: &cancellables)
viewModel
.flashEnabled
.receive(on: RunLoop.main)
.sink { [weak self] enabled in
self?.flashButton.isSelected = enabled
}
.store(in: &cancellables)
flashButtonSubject
.eraseToAnyPublisher()
.throttle(
for: .milliseconds(200),
scheduler: DispatchQueue.global(qos: .background),
latest: false
)
.sink { [weak self] in self?.viewModel.flashTapRelay.send($0) }
.store(in: &cancellables)
connectedDAppsButtonSubject
.eraseToAnyPublisher()
.throttle(
for: .milliseconds(200),
scheduler: DispatchQueue.global(qos: .background),
latest: false
)
.receive(on: DispatchQueue.main)
.sink { [weak self] in self?.viewModel.connectedDAppsTapped?() }
.store(in: &cancellables)
cameraRollButton.setImage(Images.cameraRoll.image, for: .normal)
connectedDappsButton.setImage(Images.connectedDapps.image, for: .normal)
connectedDappsButton.titleLabel?.font = UIFont.main(.medium, 16)
connectedDappsButton.setTitleColor(.tertiaryButton, for: .normal)
connectedDappsButton.layer.cornerRadius = 24
connectedDappsButton.backgroundColor = .mediumBackground
connectedDappsButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 34)
connectedDappsButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
connectedDappsButton.addTarget(self, action: #selector(onConnectedDAppsButtonTap), for: .touchUpInside)
flashButton.setImage(Images.flashDisabled.image, for: .normal)
flashButton.setImage(Images.flashEnabled.image, for: .selected)
flashButton.setImage(Images.flashEnabled.image, for: .highlighted)
}
override func layoutSubviews() {
super.layoutSubviews()
let scannableFrame = scannableFrame
setupLayerMask(frame: scannableFrame)
targetImageView.frame.origin = scannableFrame.origin.applying(CGAffineTransform(translationX: -12, y: -12))
}
/// Sets up layers mask given the frame provided.
private func setupLayerMask(frame: CGRect) {
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
let path = UIBezierPath(rect: bounds)
path.append(
.init(
roundedRect: scannableFrame,
byRoundingCorners: .allCorners,
cornerRadii: .edge(8)
)
)
maskLayer.fillRule = .evenOdd
maskLayer.path = path.cgPath
layer.mask = maskLayer
}
private func setupBorderView() {
targetImageView.tintColor = .idleBorder
targetImageView.frame.origin = scannableFrame.origin
}
@objc private func onCameraRollTap() {
cameraRollButtonSubject.send()
}
@objc private func onFlashButtonTap() {
flashButtonSubject.send()
}
@objc private func onConnectedDAppsButtonTap() {
connectedDAppsButtonSubject.send()
}
}
| lgpl-3.0 |
guillermo-ag-95/App-Development-with-Swift-for-Students | 2 - Introduction to UIKit/6 - Loops/lab/Lab - Loops.playground/Pages/6. App Exercise - Finding Movements.xcplaygroundpage/Contents.swift | 1 | 2252 | /*:
## App Exercise - Finding Movements
>These exercises reinforce Swift concepts in the context of a fitness tracking app.
You decide you want your app's users to be able to put in a heart rate range they would like to hit, and then you want the app to suggest movements where historically the user has reached that heart rate range. The dictionary `movementHeartRates` below contains keys corresponding to the movements that the app has tracked, and values corresponding to the average heart rate of the user that your fitness tracker has monitored historically during the given movement.
Loop through `movementHeartRates` below and if the heart rate doesn't fall between `lowHR` and `highHR`, continue to the next movement and heart rate. Otherwise, print "You could go <INSERT MOVEMENT HERE>".
*/
let lowHR = 110
let highHR = 125
var movementHeartRates: [String: Int] = ["Walking": 85, "Running": 120, "Swimming": 130, "Cycling": 128, "Skiing": 114, "Climbing": 129]
for (movement, heartRate) in movementHeartRates {
if heartRate > lowHR && heartRate < highHR {
print("You could go \(movement)")
}
}
/*:
_Copyright © 2017 Apple Inc._
_Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:_
_The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software._
_THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE._
*/
//: [Previous](@previous) | page 6 of 6
| mit |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/Former/Former/Cells/FormSelectorDatePickerCell.swift | 2 | 2894 | //
// FormSelectorDatePickerCell.swift
// Former-Demo
//
// Created by Ryo Aoyama on 8/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
open class FormSelectorDatePickerCell: FormCell, SelectorDatePickerFormableRow {
// MARK: Public
open var selectorDatePicker: UIDatePicker?
open var selectorAccessoryView: UIView?
public private(set) weak var titleLabel: UILabel!
public private(set) weak var displayLabel: UILabel!
public func formTitleLabel() -> UILabel? {
return titleLabel
}
public func formDisplayLabel() -> UILabel? {
return displayLabel
}
open func formDefaultDisplayLabelText() -> String? {
return "Not Set"
}
open func formDefaultDisplayDate() -> NSDate? {
return NSDate()
}
open override func updateWithRowFormer(_ rowFormer: RowFormer) {
super.updateWithRowFormer(rowFormer)
rightConst.constant = (accessoryType == .none) ? -15 : 0
}
open override func setup() {
super.setup()
let titleLabel = UILabel()
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(titleLabel, at: 0)
self.titleLabel = titleLabel
let displayLabel = UILabel()
displayLabel.textColor = .lightGray
displayLabel.textAlignment = .right
displayLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(displayLabel, at: 0)
self.displayLabel = displayLabel
let constraints = [
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[title]-0-|",
options: [],
metrics: nil,
views: ["title": titleLabel]
),
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[display]-0-|",
options: [],
metrics: nil,
views: ["display": displayLabel]
),
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-15-[title]-10-[display(>=0)]",
options: [],
metrics: nil,
views: ["title": titleLabel, "display": displayLabel]
)
].flatMap { $0 }
let rightConst = NSLayoutConstraint(
item: displayLabel,
attribute: .trailing,
relatedBy: .equal,
toItem: contentView,
attribute: .trailing,
multiplier: 1,
constant: 0
)
contentView.addConstraints(constraints + [rightConst])
self.rightConst = rightConst
}
// MARK: Private
private weak var rightConst: NSLayoutConstraint!
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Extensions/Sources/SwiftExtensions/Scale.swift | 1 | 1799 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import CoreGraphics
public struct Scale<X: BinaryFloatingPoint> {
public var domain: [X] { didSet { update() } }
public var domainUsed: [X] { map.map(\.domain) }
public var range: [X] { didSet { update() } }
public var rangeUsed: [X] { map.map(\.range) }
public private(set) var map: [(domain: X, range: X)] = []
public var inverse: Scale { Scale(domain: range, range: domain) }
public init(domain: [X] = [0, 1], range: [X] = [0, 1]) {
self.domain = domain
self.range = range
update()
}
mutating func update() {
map = zip(domain, range).sorted(by: <)
}
public func scale(_ x: X, _ f: (X) -> X) -> X {
switch map.count {
case 0:
return x
case 1:
return map[0].domain - x + map[0].range
default:
if x <= map[0].domain { return map[0].range }
var from = map[0]
for to in map[1..<map.count] {
if x < to.domain {
let y = f((x - from.domain) / (to.domain - from.domain))
let a = (1 - y) * from.range + y * to.range
precondition(!a.isNaN)
return a
}
from = to
}
return map[map.index(before: map.endIndex)].range
}
}
}
extension Scale {
@inlinable public func linear(_ x: X) -> X {
scale(x) { x in x }
}
}
extension Scale where X: ExpressibleByFloatLiteral {
@inlinable public func pow(_ x: X, exp: X = 2) -> X {
scale(x) { x in pow(x, exp: exp) }
}
@inlinable public func sin(_ x: X) -> X {
scale(x) { x in sin((x - 0.5) * .pi) * 0.5 + 0.5 }
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/NativeBitcoin/UnspentOutputs/SpendableUnspentOutputs.swift | 1 | 574 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
public struct SpendableUnspentOutputs: Equatable {
public let absoluteFee: BigUInt
public let amount: BigUInt
public let change: BigUInt
public let spendableOutputs: [UnspentOutput]
init(
spendableOutputs: [UnspentOutput],
absoluteFee: BigUInt,
amount: BigUInt,
change: BigUInt
) {
self.spendableOutputs = spendableOutputs
self.absoluteFee = absoluteFee
self.amount = amount
self.change = change
}
}
| lgpl-3.0 |
huonw/swift | validation-test/compiler_crashers_fixed/25486-llvm-foldingset-swift-tupletype-nodeequals.swift | 65 | 468 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func a{class b<T{class c<let a{func g:struct Q<T where g:P{protocol A
| apache-2.0 |
M2Mobi/Marky-Mark | Example/Tests/Rules/Inline/LinkRuleTests.swift | 1 | 5268 | //
// Created by Maren Osnabrug on 10-05-16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import XCTest
@testable import markymark
class LinkRuleTests: XCTestCase {
var sut: LinkRule!
override func setUp() {
super.setUp()
sut = LinkRule()
}
func testRecognizesLines() {
XCTAssertTrue(sut.recognizesLines(["[Alt text](image.png)"]))
XCTAssertFalse((sut.recognizesLines([""])))
XCTAssertTrue(sut.recognizesLines([#"[Alt text](image.png "some title")"#]))
}
func test_DoesNotRecognizeLines_When_PrefixedWithExclamationMark() {
XCTAssertFalse((sut.recognizesLines([""])))
XCTAssertFalse((sut.recognizesLines(["! [Alt text](image.png)"])))
XCTAssertFalse((sut.recognizesLines([#""#])))
}
func test_GetAllMatchesReturnsZero_When_InvalidInput() {
// Assert
XCTAssert(sut.getAllMatches(["(https://www.google.com)"]).isEmpty)
XCTAssert(sut.getAllMatches(["[Google]"]).isEmpty)
XCTAssert(sut.getAllMatches([""]).isEmpty)
}
func testCreateMarkDownItemWithLinesCreatesCorrectItem() {
// Act
let markDownItem = sut.createMarkDownItemWithLines(["[Google](http://www.google.com)"])
// Assert
XCTAssert(markDownItem is LinkMarkDownItem)
}
func testCreateMarkDownItemContainsCorrectLink() {
// Act
let markDownItem = sut.createMarkDownItemWithLines(["[Google](http://www.google.com)"])
let markDownItem2 = sut.createMarkDownItemWithLines(["[Youtube](http://www.youtube.com)"])
// Assert
XCTAssertEqual((markDownItem as! LinkMarkDownItem).content, "Google")
XCTAssertEqual((markDownItem as! LinkMarkDownItem).url, "http://www.google.com")
XCTAssertEqual((markDownItem2 as! LinkMarkDownItem).content, "Youtube")
XCTAssertEqual((markDownItem2 as! LinkMarkDownItem).url, "http://www.youtube.com")
}
func testGetAllMatches() {
// Arrange
let expectedMatchesRange = NSRange(location: 0, length: 32)
let expectedMatchesRange2 = NSRange(location: 38, length: 32)
// Act + Assert
XCTAssertEqual(sut.getAllMatches(["[Google]"]).count, 0)
XCTAssertEqual(sut.getAllMatches(["(https://www.google.com)"]).count, 0)
XCTAssertEqual(sut.getAllMatches(["[Google](https://www.google.com)"]), [expectedMatchesRange])
XCTAssertEqual(sut.getAllMatches([""]).count, 0)
XCTAssertEqual(
sut.getAllMatches(["[Google](https://www.google.com) test [Google](https://www.google.com)"]),
[expectedMatchesRange, expectedMatchesRange2]
)
XCTAssertEqual(
sut.getAllMatches([#"[Google](https://www.google.com) test [Google](https://www.google.com "a11y title")"#]),
[
NSRange(location: 0, length: 32),
NSRange(location: 38, length: 45)
]
)
}
func test_ParsesItem_When_InputMatches() throws {
// Arrange
let cases: [(String, String, String, UInt)] = [
(
#"[Google plain link](https://google.com)"#,
"Google plain link",
"https://google.com",
#line
),
(
#"[Google w/ title](http://www.google.com "with custom title")"#,
"Google w/ title",
"http://www.google.com",
#line
),
(
#"[Simple link](https://google.nl)"#,
"Simple link",
"https://google.nl",
#line
),
(
#"Inside [another link](http://m2mobi.com/) sentence"#,
"another link",
"http://m2mobi.com/",
#line
),
(
#"Inside [another link](http://m2mobi.com/ "with custom title") sentence"#,
"another link",
"http://m2mobi.com/",
#line
),
(
#"[Underscored link](https://google.nl/?param=a_b_c)"#,
"Underscored link",
"https://google.nl/?param=a_b_c",
#line
),
(
#"[Underscored link 2](https://google.nl/?param=a_b_c&d=e)"#,
"Underscored link 2",
"https://google.nl/?param=a_b_c&d=e",
#line
),
(
#"[Underscored link 4](https://google.nl/?param=a_b_c&d=e_f_g)"#,
"Underscored link 4",
"https://google.nl/?param=a_b_c&d=e_f_g",
#line
)
]
for (input, content, url, line) in cases {
// Act
let output = sut.createMarkDownItemWithLines([input])
// Assert
let linkMarkDownItem = try XCTUnwrap(output as? LinkMarkDownItem)
XCTAssertEqual(linkMarkDownItem.content, content, line: line)
XCTAssertEqual(linkMarkDownItem.url, url, line: line)
}
}
}
| mit |
maxim-pervushin/HyperHabit | HyperHabit/TodayExtension/Src/Data/TodayDataSource.swift | 1 | 1157 | //
// Created by Maxim Pervushin on 23/11/15.
// Copyright (c) 2015 Maxim Pervushin. All rights reserved.
//
import Foundation
class TodayDataSource: DataSource {
var todayReports: [Report] {
let habits = dataProvider.habits
var reports = dataProvider.reportsForDate(NSDate())
for habit in habits {
var createReport = true
for report in reports {
// TODO: Find better solution
if report.habitName == habit.name {
createReport = false
break;
}
}
if createReport {
reports.append(Report(habit: habit, repeatsDone: 0, date: NSDate()))
}
}
return reports.sort({ $0.habitName > $1.habitName })
}
var completedReports: [Report] {
return todayReports.filter {
return $0.completed
}
}
var incompletedReports: [Report] {
return todayReports.filter {
return !$0.completed
}
}
func saveReport(report: Report) -> Bool {
return dataProvider.saveReport(report)
}
}
| mit |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/Ads.swift | 1 | 694 | //
// Ads.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 13/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import UIKit
import GoogleMobileAds
struct Ads
{
static let bannerAdId = "ca-app-pub-3582986480189311/1490068786"
static let localBannerAdId = "ca-app-pub-3582986480189311/8489481588"
static var bannerView : GADBannerView?
static func createRequest() -> GADRequest
{
let request = GADRequest()
request.testDevices = [
"Simulator",
"4ccb6d94e22bce9a7212f16cc927c429",//iPad
"cc0b7644c90c4ab95e0150938951def3" //iPhone
]
return request
}
}
| apache-2.0 |
tutsplus/iOS-OnDemandResources-StarterProject | ODR Introduction/DetailViewController.swift | 1 | 1764 | //
// DetailViewController.swift
// ODR Introduction
//
// Created by Davis Allie on 26/09/2015.
// Copyright © 2015 tutsplus. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
@IBOutlet weak var image3: UIImageView!
@IBOutlet weak var image4: UIImageView!
var tagToLoad: String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.displayImages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayImages() {
if colorTags.contains(tagToLoad) {
image1.image = UIImage(named: tagToLoad + " Circle")
image2.image = UIImage(named: tagToLoad + " Square")
image3.image = UIImage(named: tagToLoad + " Star")
image4.image = UIImage(named: tagToLoad + " Hexagon")
} else if shapeTags.contains(tagToLoad) {
image1.image = UIImage(named: "Red " + tagToLoad)
image2.image = UIImage(named: "Blue " + tagToLoad)
image3.image = UIImage(named: "Green " + tagToLoad)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-2-clause |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/TextFormattingProvidingTableViewController.swift | 1 | 4120 | enum TextStyleType: Int {
case paragraph
case heading = 2 // Heading is 2 equals (we don't show a heading choice for 1 equals variant)
case subheading1 = 3
case subheading2 = 4
case subheading3 = 5
case subheading4 = 6
var name: String {
switch self {
case .paragraph:
return "Paragraph"
case .heading:
return "Heading"
case .subheading1:
return "Sub-heading 1"
case .subheading2:
return "Sub-heading 2"
case .subheading3:
return "Sub-heading 3"
case .subheading4:
return "Sub-heading 4"
}
}
}
enum TextSizeType: String {
case normal
case big
case small
var name: String {
switch self {
case .normal:
return "Normal"
case .big:
return "Big"
case .small:
return "Small"
}
}
}
class TextFormattingProvidingTableViewController: UITableViewController, TextFormattingProviding {
weak var delegate: TextFormattingDelegate?
var theme = Theme.standard
open var titleLabelText: String? {
return nil
}
open var shouldSetCustomTitleLabel: Bool {
return true
}
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = titleLabelText
label.sizeToFit()
return label
}()
private lazy var closeButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: #imageLiteral(resourceName: "close"), style: .plain, target: self, action: #selector(close(_:)))
return button
}()
final var selectedTextStyleType: TextStyleType = .paragraph {
didSet {
guard navigationController != nil else {
return
}
tableView.reloadData()
}
}
final var selectedTextSizeType: TextSizeType = .normal {
didSet {
guard navigationController != nil else {
return
}
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if shouldSetCustomTitleLabel {
leftAlignTitleItem()
}
setCloseButton()
navigationItem.backBarButtonItem?.title = titleLabelText
apply(theme: theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
private func leftAlignTitleItem() {
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleLabel)
}
private func setCloseButton() {
navigationItem.rightBarButtonItem = closeButton
}
private func updateTitleLabel() {
titleLabel.font = UIFont.wmf_font(.headline, compatibleWithTraitCollection: traitCollection)
titleLabel.sizeToFit()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateTitleLabel()
}
@objc private func close(_ sender: UIBarButtonItem) {
delegate?.textFormattingProvidingDidTapClose()
}
// MARK: Text & button selection messages
open func textSelectionDidChange(isRangeSelected: Bool) {
selectedTextStyleType = .paragraph
selectedTextSizeType = .normal
}
open func buttonSelectionDidChange(button: SectionEditorButton) {
switch button.kind {
case .heading(let type):
selectedTextStyleType = type
case .textSize(let type):
selectedTextSizeType = type
default:
break
}
}
open func disableButton(button: SectionEditorButton) {
}
}
extension TextFormattingProvidingTableViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
tableView.backgroundColor = theme.colors.inputAccessoryBackground
titleLabel.textColor = theme.colors.primaryText
}
}
| mit |
rbaladron/SwiftProgramaParaiOS | Ejercicios/Cadenas.playground/Contents.swift | 1 | 133 | //: Playground - noun: a place where people can play
import UIKit
print("lista de deportes: \n\t1. 🏀 \n\t2. ⚽️ \n\t3. 🏊") | mit |
Mirmeca/Mirmeca | Mirmeca/CommentGateway.swift | 1 | 1118 | //
// CommentGateway.swift
// Mirmeca
//
// Created by solal on 2/08/2015.
// Copyright (c) 2015 Mirmeca. All rights reserved.
//
import Alamofire
import ObjectMapper
public struct CommentGateway: GatewayProtocol {
private var url: String?
public init(endpoint: String, env: String?) {
let env = MirmecaEnv.sharedInstance.getEnv(env)
self.url = "\(env)/\(endpoint)"
}
public func request(completion: (value: AnyObject?, error: NSError?) -> Void) {
Alamofire.request(.GET, self.url!).responseJSON { (_, _, JSON, _) in
var value: Comment?
var error: NSError?
if (JSON != nil) {
if let mappedObject = Mapper<Comment>().map(JSON) {
value = mappedObject
} else {
error = NSError(domain: self.url!, code: 303, userInfo: nil)
}
} else {
error = NSError(domain: self.url!, code: 302, userInfo: nil)
}
completion(value: value, error: error)
}
}
}
| mit |
Wojcik/AKFeedler | AKFeedler/Views/AKItemCell.swift | 1 | 326 | //
// AKItemCell.swift
// AKFeedler
//
// Created by Anton Kovalev on 3/19/16.
// Copyright © 2016 Anton Kovalev. All rights reserved.
//
import UIKit
class AKItemCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
func fillWithItem(item:AKItem){
self.titleLabel.text = item.title
}
}
| mit |
tktsubota/CareKit | Sample/OCKSample/AppDelegate.swift | 1 | 1982 | /*
Copyright (c) 2016, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
window?.tintColor = Colors.red.color
return true
}
}
| bsd-3-clause |
zhiquan911/chance_btc_wallet | chance_btc_wallet/Pods/CHPageCardView/CHPageCardView/Classes/CHPageCardFlowLayout.swift | 2 | 3849 | //
// CHPageCardFlowLayout.swift
// Pods
//
// Created by Chance on 2017/2/27.
//
//
import UIKit
protocol CHPageCardFlowLayoutDelegate: class {
func scrollToPageIndex(index: Int)
}
/// 卡片组内元素布局控制
/// 教程在http://llyblog.com/2016/09/01/iOS卡片控件的实现/
class CHPageCardFlowLayout: UICollectionViewFlowLayout {
var previousOffsetX: CGFloat = 0
/// 当前页码
var pageNum: Int = 0
weak var delegate: CHPageCardFlowLayoutDelegate?
/// 重载准备方法
override func prepare() {
super.prepare()
//滑动方向
self.scrollDirection = .horizontal
//计算cell超出显示的宽度
let width = ((self.collectionView!.frame.size.width - self.itemSize.width) - (self.minimumLineSpacing * 2)) / 2
//每个section的间距
self.sectionInset = UIEdgeInsetsMake(0, self.minimumLineSpacing + width, 0, self.minimumLineSpacing + width)
}
/// 控制元素布局的属性的动态变化
///
/// - Parameter rect:
/// - Returns:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
let visibleRect = CGRect(
x: self.collectionView!.contentOffset.x,
y: self.collectionView!.contentOffset.y,
width: self.collectionView!.frame.size.width,
height: self.collectionView!.frame.size.height)
let offset = visibleRect.midX
for attribute in attributes! {
let distance = offset - attribute.center.x
// 越往中心移动,值越小,从而显示就越大
// 同样,超过中心后,越往左、右走,显示就越小
let scaleForDistance = distance / self.itemSize.width
// 0.1可调整,值越大,显示就越小
let scaleForCell = 1 - 0.1 * fabs(scaleForDistance)
//只在Y轴方向做缩放,这样中间的那个distance = 0,不进行缩放,非中心的缩小
attribute.transform3D = CATransform3DMakeScale(1, scaleForCell, 1)
attribute.zIndex = 1
//渐变
let scaleForAlpha = 1 - fabsf(Float(scaleForDistance)) * 0.6
attribute.alpha = CGFloat(scaleForAlpha)
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
/// 控制滑动元素目标落点的位置
///
/// - Parameters:
/// - proposedContentOffset:
/// - velocity:
/// - Returns:
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// 分页以1/3处
if proposedContentOffset.x > self.previousOffsetX + self.itemSize.width / 3.0 {
self.previousOffsetX += self.itemSize.width + self.minimumLineSpacing
self.pageNum = Int(self.previousOffsetX / (self.itemSize.width + self.minimumLineSpacing))
self.delegate?.scrollToPageIndex(index: self.pageNum)
} else if proposedContentOffset.x < self.previousOffsetX - self.itemSize.width / 3.0 {
self.previousOffsetX -= self.itemSize.width + self.minimumLineSpacing
self.pageNum = Int(self.previousOffsetX / (self.itemSize.width + self.minimumLineSpacing))
self.delegate?.scrollToPageIndex(index: self.pageNum)
}
//将当前cell移动到屏幕中间位置
let newPoint = CGPoint(x: self.previousOffsetX, y: proposedContentOffset.y)
return newPoint
}
}
| mit |
achimk/Cars | CarsApp/CarsAppTests/Features/Cars/Add/Converters/CarInputWhitespaceTrimmerTests.swift | 1 | 591 | //
// CarInputWhitespaceTrimmerTests.swift
// CarsApp
//
// Created by Joachim Kret on 01/08/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import XCTest
import Nimble
@testable import CarsApp
final class CarInputWhitespaceTrimmerTests: XCTestCase {
func testConverter() {
let converter = CarInputWhitespaceTrimmer.create()
expect(converter.run(" ")).to(equal(""))
expect(converter.run(" a ")).to(equal("a"))
expect(converter.run(" a a ")).to(equal("a a"))
expect(converter.run(" a a ")).to(equal("a a"))
}
}
| mit |
cwaffles/Soulcast | Soulcast/put.swift | 1 | 7689 |
import UIKit
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
extension UIViewController {
func addChildVC(_ vc: UIViewController) {
addChildViewController(vc)
view.addSubview(vc.view)
vc.didMove(toParentViewController: vc)
}
func removeChildVC(_ vc: UIViewController) {
vc.willMove(toParentViewController: nil)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
}
func name() -> String {
return NSStringFromClass(type(of: self)).components(separatedBy: ".").last!
}
func navigationBarHeight() -> CGFloat {
if let navController = navigationController {
return navController.navigationBar.height
} else {
return 0
}
}
func put(_ aSubview:UIView, inside thisView:UIView, onThe position:Position, withPadding padding:CGFloat) {
view.put(aSubview, inside: thisView, onThe: position, withPadding: padding)
}
func put(_ aView:UIView, besideAtThe position:Position, of relativeView:UIView, withSpacing spacing:CGFloat) {
view.put(aView, atThe: position, of: relativeView, withSpacing: spacing)
}
}
enum Position {
case left
case right
case top
case bottom
case topLeft
case topRight
case bottomLeft
case bottomRight
}
protocol PutAware {
func wasPut()
}
extension UIView { //put
convenience init(width theWidth:CGFloat, height theHeight: CGFloat) {
self.init()
self.frame = CGRect(x: 0, y: 0, width: theWidth, height: theHeight)
}
func put(_ aSubview:UIView, inside thisView:UIView, onThe position:Position, withPadding padding:CGFloat) {
assert(aSubview.width <= thisView.width &&
aSubview.height <= thisView.height,
"The subview is too large to fit inside this view!")
if position == .left || position == .right {
assert(aSubview.width + 2 * padding < thisView.width,
"The padding is too wide!")
}
if position == .top || position == .bottom {
assert(aSubview.height + 2 * padding < thisView.height,
"The padding is too high!")
}
if let aLabel = aSubview as? UILabel { aLabel.sizeToFit() }
var subRect: CGRect = CGRect.zero
switch position {
case .left:
subRect = CGRect(
x: padding,
y: thisView.midHeight - aSubview.midHeight,
width: aSubview.width,
height: aSubview.height)
case .right:
subRect = CGRect(
x: thisView.width - padding - aSubview.width,
y: thisView.midHeight - aSubview.midHeight,
width: aSubview.width,
height: aSubview.height)
case .top:
subRect = CGRect(
x: thisView.midWidth - aSubview.midWidth,
y: padding,
width: aSubview.width,
height: aSubview.height)
case .bottom:
subRect = CGRect(
x: thisView.midWidth - aSubview.midWidth,
y: thisView.height - padding - aSubview.height,
width: aSubview.width,
height: aSubview.height)
case .topLeft:
subRect = CGRect(
x: padding,
y: padding,
width: aSubview.width,
height: aSubview.height)
case .topRight:
subRect = CGRect(
x: thisView.width - padding - aSubview.width,
y: padding,
width: aSubview.width,
height: aSubview.height)
case .bottomLeft:
subRect = CGRect(
x: padding,
y: thisView.height - padding - aSubview.height,
width: aSubview.width,
height: aSubview.height)
case .bottomRight:
subRect = CGRect(
x: thisView.width - padding - aSubview.width,
y: thisView.height - padding - aSubview.height,
width: aSubview.width,
height: aSubview.height)
}
aSubview.frame = subRect
if aSubview.superview != thisView{
thisView.addSubview(aSubview)
}
(aSubview as? PutAware)?.wasPut()
}
func put(_ aView:UIView, atThe position:Position, of relativeView:UIView, withSpacing spacing:CGFloat) {
let diagonalSpacing:CGFloat = spacing / sqrt(2.0)
switch position {
case .left:
aView.center = CGPoint(
x: relativeView.minX - aView.width/2 - spacing,
y: relativeView.midY)
case .right:
aView.center = CGPoint(
x: relativeView.maxX + aView.width/2 + spacing,
y: relativeView.midY)
case .top:
aView.center = CGPoint(
x: relativeView.midX,
y: relativeView.minY - aView.height/2 - spacing)
case .bottom:
aView.center = CGPoint(
x: relativeView.midX,
y: relativeView.maxY + aView.height/2 + spacing)
case .topLeft:
aView.center = CGPoint(
x: relativeView.minX - aView.width/2 - diagonalSpacing,
y: relativeView.minY - aView.height/2 - diagonalSpacing)
case .topRight:
aView.center = CGPoint(
x: relativeView.maxX + aView.width/2 + diagonalSpacing,
y: relativeView.minY - aView.height/2 - diagonalSpacing)
case .bottomLeft:
aView.center = CGPoint(
x: relativeView.minX - aView.width/2 - diagonalSpacing,
y: relativeView.maxY + aView.height/2 + diagonalSpacing)
case .bottomRight:
aView.center = CGPoint(
x: relativeView.maxX + aView.width/2 + diagonalSpacing,
y: relativeView.maxY + aView.height/2 + diagonalSpacing)
}
if let relativeSuperview = relativeView.superview {
relativeSuperview.addSubview(aView)
}
(aView as? PutAware)?.wasPut()
}
func resize(toWidth width:CGFloat, toHeight height:CGFloat) {
frame = CGRect(x: minX, y: minY, width: width, height: height)
(self as? PutAware)?.wasPut()
}
func reposition(toX newX:CGFloat, toY newY:CGFloat) {
frame = CGRect(x: newX, y: newY, width: width, height: height)
(self as? PutAware)?.wasPut()
}
func shift(toRight deltaX:CGFloat, toBottom deltaY:CGFloat) {
frame = CGRect(x: minX + deltaX, y: minY + deltaY, width: width, height: height)
(self as? PutAware)?.wasPut()
}
var width: CGFloat { return frame.width }
var height: CGFloat { return frame.height }
var minX: CGFloat { return frame.minX }
var minY: CGFloat { return frame.minY }
var midX: CGFloat { return frame.midX }
var midY: CGFloat { return frame.midY }
var midWidth: CGFloat { return frame.width/2 }
var midHeight: CGFloat { return frame.height/2 }
var maxX: CGFloat { return frame.maxX }
var maxY: CGFloat { return frame.maxY }
}
enum FontStyle: String {
case Regular = "Regular"
case DemiBold = "DemiBold"
case Medium = "Medium"
}
func brandFont(_ style: FontStyle? = .DemiBold, size:CGFloat? = 16) -> UIFont {
return UIFont(name: "AvenirNext-" + style!.rawValue, size: size!)!
}
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func imageFromUrl(_ url:URL) -> UIImage {
let data = try? Data(contentsOf: url)
return UIImage(data: data!)!
}
extension UIView {
func animate(to theFrame: CGRect, completion: @escaping () -> () = {}) {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.frame = theFrame
}, completion: { (finished:Bool) -> Void in
completion()
})
}
func addShadow() {
layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
layer.shadowOffset = CGSize.zero
layer.shadowOpacity = 1
layer.shadowRadius = 7
}
func addThinShadow() {
layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
layer.shadowOffset = CGSize.zero
layer.shadowOpacity = 1
layer.shadowRadius = 1
}
}
| mit |
looker-open-source/sdk-codegen | swift/looker/Tests/lookerTests/apiConfigTests.swift | 1 | 2211 | /**
MIT License
Copyright (c) 2021 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import XCTest
@testable import looker
fileprivate let testRootPath = URL(fileURLWithPath: #file).pathComponents
.prefix(while: { $0 != "Tests" }).joined(separator: "/").dropFirst()
fileprivate let repoPath : String = testRootPath + "/../../"
fileprivate let localIni : String = ProcessInfo.processInfo.environment["LOOKERSDK_INI"] ?? (repoPath + "looker.ini")
class apiConfigTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testApiConfigFile() {
let config = try? ApiConfig(localIni)
XCTAssertFalse((config?.verify_ssl!)!)
XCTAssertEqual(config?.timeout, 31)
}
func testBadConfigFile() {
XCTAssertThrowsError(try ApiConfig("bad.ini")) {
let thrownError = $0
XCTAssertEqual(thrownError.localizedDescription, "bad.ini does not exist")
}
}
}
| mit |
sora0077/iTunesMusic | Sources/iTunesMusic.swift | 1 | 2851 | //
// iTunesMusic.swift
// iTunesMusic
//
// Created by 林達也 on 2016/06/07.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
import Himotoki
import RxSwift
import RealmSwift
public let player: Player = Player2()
typealias Decodable = Himotoki.Decodable
private let realmObjectTypes: [RealmSwift.Object.Type] = [
_Media.self,
_GenresCache.self,
_Collection.self,
_ChartUrls.self,
_HistoryCache.self,
_DiskCacheCounter.self,
_SearchCache.self,
_SearchTrendsCache.self,
_ArtistCache.self,
_Artist.self,
_RssUrls.self,
_RssItem.self,
_MyPlaylist.self,
_MyPlaylistCache.self,
_AlbumCache.self,
_HistoryRecord.self,
_Genre.self,
_TrackMetadata.self,
_Track.self,
_RssCache.self,
_Review.self,
_ReviewCache.self
]
private let configuration: Realm.Configuration = {
var config = Realm.Configuration()
config.objectTypes = realmObjectTypes
config.fileURL = launchOptions.location.url
return config
}()
public enum RealmLocation {
case `default`
case group(String)
var url: URL {
switch self {
case .default:
let path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
return URL(fileURLWithPath: path).appendingPathComponent("itunes.realm")
case .group(let identifier):
let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: identifier)
return dir!.appendingPathComponent("itunes.realm")
}
}
}
public struct LaunchOptions {
public var location: RealmLocation
public init(location: RealmLocation = .default) {
self.location = location
}
}
private var launchOptions: LaunchOptions!
public func migrateRealm(from: RealmLocation, to: RealmLocation) throws {
let (from, to) = (from.url, to.url)
if from == to { return }
let manager = FileManager.default
if manager.fileExists(atPath: to.absoluteString) {
return
}
if !manager.fileExists(atPath: from.absoluteString) {
return
}
try manager.moveItem(at: from, to: to)
try manager.removeItem(at: from)
}
public func deleteRealm(from: RealmLocation) throws {
try FileManager.default.removeItem(at: from.url)
}
public func launch(with options: LaunchOptions = LaunchOptions()) {
launchOptions = options
player.install(middleware: Model.History.shared)
player.install(middleware: Model.DiskCache.shared)
}
public func iTunesRealm() -> Realm {
// swiftlint:disable:next force_try
return try! Realm(configuration: configuration)
}
extension Realm {
public func delete<Base: RealmCollection>(_ objects: RandomAccessSlice<Base>) where Base.Element: Object {
delete(Array(objects))
}
}
| mit |
TMTBO/TTAImagePickerController | TTAImagePickerController/Classes/Views/TTAAssetCollectionViewCell.swift | 1 | 5460 | //
// TTAAssetCollectionViewCell.swift
// Pods-TTAImagePickerController_Example
//
// Created by TobyoTenma on 17/06/2017.
//
import Photos
protocol TTAAssetCollectionViewCellDelegate: class {
func canOperateCell(cell: TTAAssetCollectionViewCell) -> (canOperate: Bool, asset: PHAsset?)
func assetCell(_ cell: TTAAssetCollectionViewCell, asset: PHAsset, isSelected: Bool)
}
class TTAAssetCollectionViewCell: UICollectionViewCell {
struct AssetCollectionViewCellConst {
let selectButtonMargin: CGFloat = 3
let selectButtonHeight: CGFloat = 26
let selectButtonWidth: CGFloat = 26
}
weak var delegate: TTAAssetCollectionViewCellDelegate?
/// The tint color which item was selected, default is `UIColor(colorLiteralRed: 0, green: 122.0 / 255.0, blue: 1, alpha: 1)`
public var selectItemTintColor: UIColor? {
didSet {
selectButton.selectItemTintColor = selectItemTintColor
}
}
fileprivate let imageView = UIImageView()
fileprivate let selectButton = TTASelectButton()
fileprivate let videoComponentView = TTAAssetComponentView()
fileprivate let lightUpLayer = CALayer()
fileprivate let const = AssetCollectionViewCellConst()
override init(frame: CGRect) {
super.init(frame: frame)
_setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
_layoutViews()
}
}
// MARK: - UI
fileprivate extension TTAAssetCollectionViewCell {
func _setupUI() {
_createViews()
_configViews()
_layoutViews()
}
func _createViews() {
contentView.addSubview(imageView)
contentView.addSubview(selectButton)
contentView.addSubview(videoComponentView)
layer.addSublayer(lightUpLayer)
}
func _configViews() {
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
layer.drawsAsynchronously = true
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
selectButton.selectItemTintColor = selectItemTintColor
selectButton.autoresizingMask = [.flexibleTopMargin, .flexibleRightMargin]
selectButton.addTarget(self, action: #selector(didClickSelectButton(_:)), for: .touchUpInside)
lightUpLayer.backgroundColor = UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1).cgColor
lightUpLayer.opacity = 0
}
func _layoutViews() {
imageView.frame = contentView.bounds
selectButton.frame = CGRect(x: bounds.maxX - const.selectButtonWidth - const.selectButtonMargin,
y: const.selectButtonMargin,
width: const.selectButtonWidth,
height: const.selectButtonHeight)
videoComponentView.frame = CGRect(x: 0, y: bounds.height - TTAAssetComponentView.height(), width: bounds.width, height: TTAAssetComponentView.height())
lightUpLayer.frame = contentView.bounds
}
}
// MARK: - Data
extension TTAAssetCollectionViewCell {
func configCell(with config: TTAAssetConfig) {
self.tag = config.tag;
self.delegate = config.delegate;
configState(isSelected: config.isSelected)
configImage(with: nil)
configComponentView(with: config)
guard config.canSelect else {
selectButton.isHidden = !config.canSelect
return
}
self.selectItemTintColor = config.selectItemTintColor
}
func configState(isSelected: Bool) {
guard selectButton.isSelected != isSelected else { return }
selectButton.selectState = isSelected ? .selected : .default
}
func configImage(with image: UIImage?) {
imageView.image = image
}
func configComponentView(with config: TTAAssetConfig) {
if config.isVideo {
videoComponentView.isHidden = false
videoComponentView.update(with: config.videoInfo)
} else if config.isGif {
videoComponentView.isHidden = false
videoComponentView.update(isGif: true)
} else {
videoComponentView.isHidden = true
}
}
func lightUp() {
// MARK: - Animations
func _lightupAnimation() -> CABasicAnimation {
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 0
animation.toValue = 1
animation.duration = 0.9
animation.repeatCount = 3
animation.autoreverses = true
animation.isRemovedOnCompletion = true
return animation
}
lightUpLayer.add(_lightupAnimation(), forKey: nil)
}
}
// MARK: - Actions
extension TTAAssetCollectionViewCell {
@objc func didClickSelectButton(_ button: TTASelectButton) {
guard let (canOperate, asset) = delegate?.canOperateCell(cell: self),
canOperate == true, let operateAsset = asset else { return }
button.selectState = button.selectState == .selected ? .default : .selected
delegate?.assetCell(self, asset: operateAsset, isSelected: button.isSelected)
}
}
| mit |
akane/Akane | Tests/Akane/Binding/Observation/DisplayObservationTests.swift | 1 | 3803 | //
// DisplayObservationTests.swift
// AkaneTests
//
// Created by pjechris on 15/01/2018.
// Copyright © 2018 fr.akane. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable import Akane
class DisplayObservationTests : QuickSpec {
override func spec() {
var observation: DisplayObservationStub!
var container: ContainerMock!
var ctx: ContextMock!
beforeEach {
container = ContainerMock()
ctx = ContextMock()
let observer = ViewObserver(container: container, context: ctx)
observation = DisplayObservationStub(view: ViewMock(frame: .zero),
container: container,
observer: observer)
}
describe("to(params:)") {
it("binds on view") {
observation.to(params: ())
expect(observation.view.bindCalled) == 1
}
context("view is of type Wrapped") {
it("asks container for component") {
observation.to(params: ViewModelMock())
expect(container.componentForViewCalled) == 1
}
}
context("view model is injectable") {
it("injects/resolves view model") {
observation.to(params: ())
expect(ctx.resolvedCalledCount) == 1
}
context("view model injected") {
var viewModel: ViewModelMock!
beforeEach {
viewModel = ViewModelMock()
observation.view.params = viewModel
}
it("binds with existing view model") {
observation.view.bindChecker = { _, params in
expect(params) === viewModel
}
observation.to(params: ())
}
}
}
}
}
}
extension DisplayObservationTests {
class DisplayObservationStub : DisplayObservation<ViewMock> {
}
class ContextMock : Context {
private(set) var resolvedCalledCount = 0
func resolve<T>(_ type: T.Type, parameters: T.InjectionParameters) -> T where T : ComponentViewModel, T : Injectable, T : Paramaterized {
self.resolvedCalledCount += 1
return T.init(resolver: self, parameters: parameters)
}
}
class ContainerMock : UIViewController, ComponentContainer {
var componentForViewCalled = 0
func component<View: Wrapped>(for view: View) -> View.Wrapper {
self.componentForViewCalled += 1
return View.Wrapper.init(coder: NSCoder.empty())!
}
}
class ViewModelMock : ComponentViewModel, Injectable, Paramaterized {
typealias Parameters = Void
var params: Void
required convenience init(resolver: DependencyResolver, parameters: Void) {
self.init()
}
init() {
self.params = ()
}
}
class ViewMock : UIView, ComponentDisplayable, Wrapped {
typealias Wrapper = ComponentMock
var bindCalled = 0
var bindChecker: ((ViewObserver, DisplayObservationTests.ViewModelMock) -> ())? = nil
func bindings(_ observer: ViewObserver, params: ViewModelMock) {
}
func bind(_ observer: ViewObserver, params: DisplayObservationTests.ViewModelMock) {
self.bindChecker?(observer, params)
self.bindCalled += 1
}
}
class ComponentMock : UIViewController, ComponentController {
typealias ViewType = ViewMock
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/07150-std-function-func-swift-constraints-constraintsystem-simplifytype.swift | 11 | 436 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
class a {
class a {
init(((e : b { func b
protocol A : A"\(([Void{
func b
var f = 0
protocol c : BooleanType, g = c
let a {
protocol A {
protocol A : BooleanType, U, g = 0
protocol A : A: a {
protocol c : c<I : A"\() {
func a
typealias e : e
protocol A : a {
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/13924-swift-sourcemanager-getmessage.swift | 11 | 218 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var f = {
{
}
protocol A {
deinit {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/18812-swift-sourcemanager-getmessage.swift | 11 | 204 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a( = {
class B {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/26514-swift-parser-skipsingle.swift | 7 | 309 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class d
let b{
struct S<T where B:d{
class A{
class n{
let v:d a{
{
{
{{{{{{{{{{
{{{{{{{
{
{
{{{
{
{{
{
{{
{{
{
{{{{
{{
{
{
{{{{{{
{{{{{
a<
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08280-swift-sourcemanager-getmessage.swift | 11 | 273 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S {
let a {
[ ( ) ( ) {
extension NSData {
{
{
}
}
class c {
protocol c {
{
}
{
{
}
}
class
case ,
| mit |
CoderSLZeng/SLWeiBo | SLWeiBo/SLWeiBo/Classes/Home/Model/StatusViewModel.swift | 1 | 2769 | //
// StatusViewModel.swift
// SLWeiBo
//
// Created by Anthony on 17/3/14.
// Copyright © 2017年 SLZeng. All rights reserved.
//
import UIKit
class StatusViewModel {
// MARK:- 定义属性
var status : Status?
/// cell的高度
var cellHeight : CGFloat = 0
// MARK:- 对数据处理的属性
/// 处理过的微博来源
var sourceText : String?
/// 处理过的微博创建时间
var createAtText : String?
/// 处理过的用户认证图标
var verifiedImage : UIImage?
/// 处理过的用户会员图标
var vipImage : UIImage?
// 处理过的用户头像的地址
var profileURL : URL?
/// 处理微博配图的数据
var picURLs : [URL] = [URL]()
// MARK:- 自定义构造函数
init(status : Status) {
self.status = status
// 1.对来源处理
if let source = status.source, source != "" {
// 1.1.获取起始位置和截取的长度
let startIndex = (source as NSString).range(of: ">").location + 1
let length = (source as NSString).range(of: "</").location - startIndex
// 1.2.截取字符串
sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: length))
}
// 2.处理时间
if let createAt = status.created_at {
createAtText = Date.createDateString(createAt)
}
// 3.处理认证
let verifiedType = status.user?.verified_type ?? -1
switch verifiedType {
case 0:
verifiedImage = UIImage(named: "avatar_vip")
case 2, 3, 5:
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220:
verifiedImage = UIImage(named: "avatar_grassroot")
default:
verifiedImage = nil
}
// 4.处理会员图标
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
// 5.用户头像的处理
let profileURLString = status.user?.profile_image_url ?? ""
profileURL = URL(string: profileURLString)
// 6.处理配图数据
// 6.1判断获取微博或转发配图
let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let picURLDicts = picURLDicts {
for picURLDict in picURLDicts {
guard let picURLString = picURLDict["thumbnail_pic"] else {
continue
}
picURLs.append(URL(string: picURLString)!)
}
}
}
}
| mit |
mofneko/swift-layout | add-on/AutolayoutPullArea.swift | 1 | 1925 | //
// AutolayoutPullArea.swift
// swift-layout
//
// Created by grachro on 2014/09/15.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class AutolayoutPullArea:ScrollViewPullArea {
private var _minHeight:CGFloat
private var _maxHeight:CGFloat
var topConstraint:NSLayoutConstraint?
var headerConstraint:NSLayoutConstraint?
let view = UIView()
private var _layout:Layout?
var layout:Layout {
get {return _layout!}
}
var pullCallback:((viewHeight:CGFloat, pullAreaHeight:CGFloat) -> Void)? = nil
init(minHeight:CGFloat, maxHeight:CGFloat, superview:UIView) {
self._minHeight = minHeight
self._maxHeight = maxHeight
_layout = Layout.addSubView(view, superview: superview)
.horizontalCenterInSuperview()
.leftIsSameSuperview()
.rightIsSameSuperview()
.top(-self._maxHeight).fromSuperviewTop().lastConstraint(&topConstraint)
.height(self._maxHeight).lastConstraint(&headerConstraint)
}
}
//implements ScrollViewPullArea
extension AutolayoutPullArea {
func minHeight() -> CGFloat {
return _minHeight
}
func maxHeight() -> CGFloat {
return _maxHeight
}
func animationSpeed() -> NSTimeInterval {
return 0.4
}
func show(viewHeight viewHeight:CGFloat, pullAreaHeight:CGFloat) {
if viewHeight < pullAreaHeight {
self.topConstraint?.constant = -((pullAreaHeight - viewHeight) / 2 + viewHeight)
} else {
self.topConstraint?.constant = -viewHeight
}
self.headerConstraint?.constant = viewHeight
view.superview?.layoutIfNeeded()
self.pullCallback?(viewHeight: viewHeight, pullAreaHeight:pullAreaHeight)
view.layoutIfNeeded()
}
}
| mit |
Sorix/CloudCore | Source/Classes/Save/ObjectToRecord/CoreDataRelationship.swift | 1 | 2590 | //
// CoreDataRelationship.swift
// CloudCore
//
// Created by Vasily Ulianov on 04.02.17.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import CoreData
import CloudKit
class CoreDataRelationship {
typealias Class = CoreDataRelationship
let value: Any
let description: NSRelationshipDescription
/// Initialize Core Data Attribute with properties and value
/// - Returns: `nil` if it is not an attribute (possible it is relationship?)
init?(value: Any, relationshipName: String, entity: NSEntityDescription) {
guard let description = Class.relationshipDescription(for: relationshipName, in: entity) else {
// it is not a relationship
return nil
}
self.description = description
self.value = value
}
private static func relationshipDescription(for lookupName: String, in entity: NSEntityDescription) -> NSRelationshipDescription? {
for (name, description) in entity.relationshipsByName {
if lookupName == name { return description }
}
return nil
}
/// Make reference(s) for relationship
///
/// - Returns: `CKReference` or `[CKReference]`
func makeRecordValue() throws -> Any? {
if self.description.isToMany {
if value is NSOrderedSet {
throw CloudCoreError.orderedSetRelationshipIsNotSupported(description)
}
guard let objectsSet = value as? NSSet else { return nil }
var referenceList = [CKReference]()
for (_, managedObject) in objectsSet.enumerated() {
guard let managedObject = managedObject as? NSManagedObject,
let reference = try makeReference(from: managedObject) else { continue }
referenceList.append(reference)
}
if referenceList.isEmpty { return nil }
return referenceList
} else {
guard let object = value as? NSManagedObject else { return nil }
return try makeReference(from: object)
}
}
private func makeReference(from managedObject: NSManagedObject) throws -> CKReference? {
let action: CKReferenceAction
if case .some(NSDeleteRule.cascadeDeleteRule) = description.inverseRelationship?.deleteRule {
action = .deleteSelf
} else {
action = .none
}
guard let record = try managedObject.restoreRecordWithSystemFields() else {
// That is possible if method is called before all managed object were filled with recordData
// That may cause possible reference corruption (Core Data -> iCloud), but it is not critical
assertionFailure("Managed Object doesn't have stored record information, should be reported as a framework bug")
return nil
}
return CKReference(record: record, action: action)
}
}
| mit |
byu-oit-appdev/ios-byuSuite | byuSuite/Classes/Reusable/Clients/PersonPhotoClient2.swift | 1 | 884 | //
// PersonPhotoClient.swift
// byuSuite
//
// Created by Alex Boswell on 12/20/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
private let BASE_URL = "https://api.byu.edu/domains/legacy/identity/person/idphoto/v1/"
class PersonPhotoClient2: ByuClient2 {
static func getPhoto(callback: @escaping (UIImage?, ByuError?) -> Void) {
ByuCredentialManager.getPersonSummary { (personSummary, error) in
if let personSummary = personSummary {
let request = ByuRequest2(url: super.url(base: BASE_URL, queryParams: ["p": personSummary.personId]))
ByuRequestManager.instance.makeRequest(request, callback: { (response) in
if response.succeeded, let data = response.data {
callback(UIImage(data: data), nil)
} else {
callback(nil, response.error)
}
})
} else {
callback(nil, PERSON_SUMMARY_ERROR)
}
}
}
}
| apache-2.0 |
brave/browser-ios | Providers/Profile.swift | 2 | 11818 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Alamofire
import Foundation
import ReadingList
import Shared
import Storage
import XCGLogger
import SwiftKeychainWrapper
import Deferred
private let log = Logger.syncLogger
public let NotificationProfileDidStartSyncing = NSNotification.Name(rawValue: "NotificationProfileDidStartSyncing")
public let NotificationProfileDidFinishSyncing = NSNotification.Name(rawValue: "NotificationProfileDidFinishSyncing")
public let ProfileRemoteTabsSyncDelay: TimeInterval = 0.1
typealias EngineIdentifier = String
class ProfileFileAccessor: FileAccessor {
convenience init(profile: Profile) {
self.init(localName: profile.localName())
}
init(localName: String) {
let profileDirName = "profile.\(localName)"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: String
let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier
if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: sharedContainerIdentifier) {
rootPath = url.path
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0])
}
super.init(rootPath: URL(fileURLWithPath: rootPath).appendingPathComponent(profileDirName).path)
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: BookmarksModelFactorySource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource { get }
// var favicons: Favicons { get }
var prefs: NSUserDefaultsPrefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage { get }
var certStore: CertStore { get }
func shutdown()
func reopen()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
}
open class BrowserProfile: Profile {
fileprivate let name: String
fileprivate let keychain: KeychainWrapper
internal let files: FileAccessor
weak fileprivate var app: UIApplication?
/**
* N.B., BrowserProfile is used from our extensions, often via a pattern like
*
* BrowserProfile(…).foo.saveSomething(…)
*
* This can break if BrowserProfile's initializer does async work that
* subsequently — and asynchronously — expects the profile to stick around:
* see Bug 1218833. Be sure to only perform synchronous actions here.
*/
init(localName: String, app: UIApplication?) {
log.debug("Initing profile \(localName) on thread \(Thread.current).")
self.name = localName
self.files = ProfileFileAccessor(localName: localName)
self.app = app
let baseBundleIdentifier = AppInfo.baseBundleIdentifier
if !baseBundleIdentifier.isEmpty {
self.keychain = KeychainWrapper(serviceName: baseBundleIdentifier)
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
self.keychain = KeychainWrapper.standard
}
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onProfileDidFinishSyncing(_:)), name: NotificationProfileDidFinishSyncing, object: nil)
notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onPrivateDataClearedHistory(_:)), name: NotificationPrivateDataClearedHistory, object: nil)
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account metadata.")
self.removeAccountMetadata()
self.removeExistingAuthenticationInfo()
prefs.clearAll()
}
// Always start by needing invalidation.
// This is the same as self.history.setTopSitesNeedsInvalidation, but without the
// side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread.
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func reopen() {
log.debug("Reopening profile.")
if dbCreated {
db.reopenIfClosed()
}
if loginsDBCreated {
loginsDB.reopenIfClosed()
}
}
func shutdown() {
log.debug("Shutting down profile.")
if self.dbCreated {
db.forceClose()
}
if self.loginsDBCreated {
loginsDB.forceClose()
}
}
func onLocationChange(_ info: [String : AnyObject]) {
if let v = info["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = info["url"] as? URL, !isIgnoredURL(url),
let title = info["title"] as? NSString {
// Only record local vists if the change notification originated from a non-private tab
if !(info["isPrivate"] as? Bool ?? false) {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: Date.nowMicroseconds(), type: visitType)
succeed().upon() { _ in // move off main thread
self.history.addLocalVisit(visit)
}
}
history.setTopSitesNeedsInvalidation()
} else {
log.debug("Ignoring navigation.")
}
}
// These selectors run on which ever thread sent the notifications (not the main thread)
@objc
func onProfileDidFinishSyncing(_ notification: Notification) {
history.setTopSitesNeedsInvalidation()
}
@objc
func onPrivateDataClearedHistory(_ notification: Notification) {
// Immediately invalidate the top sites cache
// Brave does not use, profile sqlite store for sites
// history.refreshTopSitesCache()
}
deinit {
log.debug("Deiniting profile \(self.localName).")
NotificationCenter.default.removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil)
}
func localName() -> String {
return name
}
lazy var queue: TabQueue = {
withExtendedLifetime(self.history) {
return SQLiteQueue(db: self.db)
}
}()
fileprivate var dbCreated = false
lazy var db: BrowserDB = {
let value = BrowserDB(filename: "browser.db", files: self.files)
self.dbCreated = true
return value
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
fileprivate lazy var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage = {
return SQLiteHistory(db: self.db, prefs: self.prefs)
}()
var favicons: Favicons {
return self.places
}
var history: BrowserHistory & SyncableHistory & ResettableSyncStorage {
return self.places
}
lazy var bookmarks: BookmarksModelFactorySource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
withExtendedLifetime(self.places) {
return MergedSQLiteBookmarks(db: self.db)
}
}()
lazy var mirrorBookmarks: BookmarkBufferStorage & BufferItemSource = {
// Yeah, this is lazy. Sorry.
return self.bookmarks as! MergedSQLiteBookmarks
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
func makePrefs() -> NSUserDefaultsPrefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: NSUserDefaultsPrefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy var remoteClientsAndTabs: RemoteClientsAndTabs & ResettableSyncStorage & AccountRemovalDelegate = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var certStore: CertStore = {
return CertStore()
}()
open func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
@discardableResult func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
lazy var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage = {
return SQLiteLogins(db: self.loginsDB)
}()
// This is currently only used within the dispatch_once block in loginsDB, so we don't
// have to worry about races giving us two keys. But if this were ever to be used
// elsewhere, it'd be unsafe, so we wrap this in a dispatch_once, too.
fileprivate lazy var loginsKey: String? = {
let key = "sqlcipher.key.logins.db"
if self.keychain.hasValue(forKey: key) {
return KeychainWrapper.standard.string(forKey: key)
}
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
self.keychain.set(secret, forKey: key)
return secret
}()
fileprivate var loginsDBCreated = false
fileprivate lazy var loginsDB: BrowserDB = {
struct Singleton {
static var instance: BrowserDB!
}
Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
self.loginsDBCreated = true
return Singleton.instance
}()
func removeAccountMetadata() {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
self.keychain.removeObject(forKey: self.name + ".account")
}
func removeExistingAuthenticationInfo() {
self.keychain.setAuthenticationInfo(nil)
}
}
| mpl-2.0 |
brave/browser-ios | ClientTests/SearchEnginesTests.swift | 3 | 7358 | /* 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/. */
@testable import Client
import Foundation
import XCTest
import Shared
private let DefaultSearchEngineName = "Yahoo"
private let ExpectedEngineNames = ["Amazon.com", "Bing", "DuckDuckGo", "Google", "Twitter", "Wikipedia", "Yahoo"]
class SearchEnginesTests: XCTestCase {
func testIncludesExpectedEngines() {
// Verify that the set of shipped engines includes the expected subset.
let engines = SearchEngines(prefs: MockProfilePrefs()).orderedEngines
XCTAssertTrue(engines.count >= ExpectedEngineNames.count)
for engineName in ExpectedEngineNames {
XCTAssertTrue((engines.filter { engine in engine.shortName == engineName }).count > 0)
}
}
func testDefaultEngineOnStartup() {
// If this is our first run, Yahoo should be first for the en locale.
let prefs = MockProfilePrefs()
let engines = SearchEngines(prefs: prefs)
XCTAssertEqual(engines.defaultEngine.shortName, DefaultSearchEngineName)
XCTAssertEqual(engines.orderedEngines[0].shortName, DefaultSearchEngineName)
}
func testDefaultEngine() {
let prefs = MockProfilePrefs()
let engines = SearchEngines(prefs: prefs)
let engineSet = engines.orderedEngines
engines.defaultEngine = engineSet[0]
XCTAssertTrue(engines.isEngineDefault(engineSet[0]))
XCTAssertFalse(engines.isEngineDefault(engineSet[1]))
// The first ordered engine is the default.
XCTAssertEqual(engines.orderedEngines[0].shortName, engineSet[0].shortName)
engines.defaultEngine = engineSet[1]
XCTAssertFalse(engines.isEngineDefault(engineSet[0]))
XCTAssertTrue(engines.isEngineDefault(engineSet[1]))
// The first ordered engine is the default.
XCTAssertEqual(engines.orderedEngines[0].shortName, engineSet[1].shortName)
let engines2 = SearchEngines(prefs: prefs)
// The default engine should have been persisted.
XCTAssertTrue(engines2.isEngineDefault(engineSet[1]))
// The first ordered engine is the default.
XCTAssertEqual(engines.orderedEngines[0].shortName, engineSet[1].shortName)
}
func testOrderedEngines() {
let prefs = MockProfilePrefs()
let engines = SearchEngines(prefs: prefs)
engines.orderedEngines = [ExpectedEngineNames[4], ExpectedEngineNames[2], ExpectedEngineNames[0]].map { name in
for engine in engines.orderedEngines {
if engine.shortName == name {
return engine
}
}
XCTFail("Could not find engine: \(name)")
return engines.orderedEngines.first!
}
XCTAssertEqual(engines.orderedEngines[0].shortName, ExpectedEngineNames[4])
XCTAssertEqual(engines.orderedEngines[1].shortName, ExpectedEngineNames[2])
XCTAssertEqual(engines.orderedEngines[2].shortName, ExpectedEngineNames[0])
let engines2 = SearchEngines(prefs: prefs)
// The ordering should have been persisted.
XCTAssertEqual(engines2.orderedEngines[0].shortName, ExpectedEngineNames[4])
XCTAssertEqual(engines2.orderedEngines[1].shortName, ExpectedEngineNames[2])
XCTAssertEqual(engines2.orderedEngines[2].shortName, ExpectedEngineNames[0])
// Remaining engines should be appended in alphabetical order.
XCTAssertEqual(engines2.orderedEngines[3].shortName, ExpectedEngineNames[1])
XCTAssertEqual(engines2.orderedEngines[4].shortName, ExpectedEngineNames[3])
XCTAssertEqual(engines2.orderedEngines[5].shortName, ExpectedEngineNames[5])
XCTAssertEqual(engines2.orderedEngines[6].shortName, ExpectedEngineNames[6])
}
func testQuickSearchEngines() {
let prefs = MockProfilePrefs()
let engines = SearchEngines(prefs: prefs)
let engineSet = engines.orderedEngines
// You can't disable the default engine.
engines.defaultEngine = engineSet[1]
engines.disableEngine(engineSet[1])
XCTAssertTrue(engines.isEngineEnabled(engineSet[1]))
// The default engine is not included in the quick search engines.
XCTAssertEqual(0, engines.quickSearchEngines.filter { engine in engine.shortName == engineSet[1].shortName }.count)
// Enable and disable work.
engines.enableEngine(engineSet[0])
XCTAssertTrue(engines.isEngineEnabled(engineSet[0]))
XCTAssertEqual(1, engines.quickSearchEngines.filter { engine in engine.shortName == engineSet[0].shortName }.count)
engines.disableEngine(engineSet[0])
XCTAssertFalse(engines.isEngineEnabled(engineSet[0]))
XCTAssertEqual(0, engines.quickSearchEngines.filter { engine in engine.shortName == engineSet[0].shortName }.count)
// Setting the default engine enables it.
engines.defaultEngine = engineSet[0]
XCTAssertTrue(engines.isEngineEnabled(engineSet[1]))
// Setting the order may change the default engine, which enables it.
engines.orderedEngines = [engineSet[2], engineSet[1], engineSet[0]]
XCTAssertTrue(engines.isEngineDefault(engineSet[2]))
XCTAssertTrue(engines.isEngineEnabled(engineSet[2]))
// The enabling should be persisted.
engines.enableEngine(engineSet[2])
engines.disableEngine(engineSet[1])
engines.enableEngine(engineSet[0])
let engines2 = SearchEngines(prefs: prefs)
XCTAssertTrue(engines2.isEngineEnabled(engineSet[2]))
XCTAssertFalse(engines2.isEngineEnabled(engineSet[1]))
XCTAssertTrue(engines2.isEngineEnabled(engineSet[0]))
}
func testSearchSuggestionSettings() {
let prefs = MockProfilePrefs()
let engines = SearchEngines(prefs: prefs)
// By default, you should see an opt-in, and suggestions are disabled.
XCTAssertTrue(engines.shouldShowSearchSuggestionsOptIn)
XCTAssertFalse(engines.shouldShowSearchSuggestions)
// Setting should be persisted.
engines.shouldShowSearchSuggestionsOptIn = false
engines.shouldShowSearchSuggestions = true
let engines2 = SearchEngines(prefs: prefs)
XCTAssertFalse(engines2.shouldShowSearchSuggestionsOptIn)
XCTAssertTrue(engines2.shouldShowSearchSuggestions)
}
func testDirectoriesForLanguageIdentifier() {
XCTAssertEqual(
SearchEngines.directoriesForLanguageIdentifier("nl", basePath: "/tmp", fallbackIdentifier: "en"),
["/tmp/nl", "/tmp/en"]
)
XCTAssertEqual(
SearchEngines.directoriesForLanguageIdentifier("en-US", basePath: "/tmp", fallbackIdentifier: "en"),
["/tmp/en-US", "/tmp/en"]
)
XCTAssertEqual(
SearchEngines.directoriesForLanguageIdentifier("es-MX", basePath: "/tmp", fallbackIdentifier: "en"),
["/tmp/es-MX", "/tmp/es", "/tmp/en"]
)
XCTAssertEqual(
SearchEngines.directoriesForLanguageIdentifier("zh-Hans-CN", basePath: "/tmp", fallbackIdentifier: "en"),
["/tmp/zh-Hans-CN", "/tmp/zh-CN", "/tmp/zh", "/tmp/en"]
)
}
}
| mpl-2.0 |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Operations/Generators/Oscillators/squareWave.swift | 3 | 950 | //
// squareWave.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
extension AKOperation {
/// This is a bandlimited square oscillator ported from the "square" function
/// from the Faust programming language.
///
/// - returns: AKOperation
/// - parameter frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0, Maximum: 20000)
/// - parameter amplitude: Output amplitude (Default: 1.0, Minimum: 0, Maximum: 10)
/// - parameter pulseWidth: Duty cycle width (range 0-1). (Default: 0.5, Minimum: 0, Maximum: 1)
///
public static func squareWave(
frequency frequency: AKParameter = 440,
amplitude: AKParameter = 1.0,
pulseWidth: AKParameter = 0.5
) -> AKOperation {
return AKOperation("(\(frequency) \(amplitude) \(pulseWidth) blsquare)")
}
}
| apache-2.0 |
mattfenwick/TodoRx | TodoRx/TodoFlow/TodoFlowPresenter.swift | 1 | 4479 | //
// TodoFlowPresenter.swift
// TodoRx
//
// Created by Matt Fenwick on 7/19/17.
// Copyright © 2017 mf. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class TodoFlowPresenter:
TodoListInteractor,
CreateTodoInteractor,
EditTodoInteractor {
private let todoModel: Driver<TodoModel>
private let commandSubject = PublishSubject<TodoCommand>()
private let disposeBag = DisposeBag()
private let accumulator: (TodoModel, TodoCommand) -> (TodoModel, Observable<TodoCommand>?)
init(interactor: TodoFlowInteractor) {
let commands = commandSubject
.asDriver { error in
assert(false, "this should never happen -- \(error)")
return Driver.empty()
}
.startWith(.initialState)
.startWith(.fetchSavedTodos)
let accumulator = todoFlowAccumulator(interactor: interactor)
let todoOutput: Driver<(TodoModel, Observable<TodoCommand>?)> = commands.scan(
(TodoModel.empty, nil),
accumulator: { old, command in
accumulator(old.0, command)
})
self.accumulator = accumulator
todoModel = todoOutput.map { tuple in tuple.0 }
let states: Driver<(TodoState, TodoState)> = todoModel
.map { $0.state }
.scan((TodoState.todoList, TodoState.todoList),
accumulator: { previous, current in (previous.1, current) })
presentCreateItemView = states
.map { (pair: (TodoState, TodoState)) -> Void? in
switch pair {
case (.todoList, .create): return ()
default: return nil
}
}
.filterNil()
dismissCreateItemView = states
.map { (pair: (TodoState, TodoState)) -> Void? in
switch pair {
case (.create, .todoList): return ()
default: return nil
}
}
.filterNil()
presentEditItemView = states
.map { (pair: (TodoState, TodoState)) -> EditTodoIntent? in
switch pair {
case let (.todoList, .edit(item)): return item.editTodo
default: return nil
}
}
.filterNil()
dismissEditItemView = states
.map { (pair: (TodoState, TodoState)) -> Void? in
switch pair {
case (.edit, .todoList): return ()
default: return nil
}
}
.filterNil()
// 2-part actions that need to get something dumped back into the command/scan loop
let feedback: Driver<Observable<TodoCommand>> = todoOutput
.map { tuple in tuple.1 }
.filterNil()
feedback
.flatMap {
$0.asDriver(onErrorRecover: { error in
assert(false, "unexpected error: \(error)")
return Driver.empty()
})
}
.drive(onNext: commandSubject.onNext)
.disposed(by: disposeBag)
}
// MARK: - for the flow controller
let presentCreateItemView: Driver<Void>
let dismissCreateItemView: Driver<Void>
let presentEditItemView: Driver<EditTodoIntent>
let dismissEditItemView: Driver<Void>
// MARK: - EditTodoInteractor
func editTodoDidTapCancel() {
commandSubject.onNext(.cancelEdit)
}
func editTodoDidTapSave(item: EditTodoIntent) {
commandSubject.onNext(.updateItem(item))
}
// MARK: - CreateTodoInteractor
func createTodoCancel() {
commandSubject.onNext(.cancelCreate)
}
func createTodoSave(item: CreateTodoIntent) {
commandSubject.onNext(.createNewItem(item))
}
// MARK: - TodoListInteractor
func todoListDidTapItem(id: String) {
commandSubject.onNext(.showUpdateView(id: id))
}
func todoListShowCreate() {
commandSubject.onNext(.showCreateView)
}
func todoListToggleItemIsFinished(id: String) {
commandSubject.onNext(.toggleItemIsFinished(id: id))
}
func todoListDeleteItem(id: String) {
commandSubject.onNext(.deleteItem(id: id))
}
lazy private (set) var todoListItems: Driver<[TodoListItem]> = self.todoModel
.map { model in model.items.map { $0.todoListItem } }
.distinctUntilChanged(==)
}
| mit |
material-components/material-components-ios | components/Snackbar/tests/unit/SnackbarManagerSwiftTests.swift | 2 | 2284 | // Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import MaterialComponents.MaterialSnackbar
class SnackbarManagerSwiftTests: XCTestCase {
override func tearDown() {
MDCSnackbarManager.default.dismissAndCallCompletionBlocks(withCategory: nil)
super.tearDown()
}
func testMessagesResumedWhenTokenIsDeallocated() {
// Given
let expectation = self.expectation(description: "completion")
let suspendedMessage = MDCSnackbarMessage(text: "")
suspendedMessage.duration = 0.05
suspendedMessage.completionHandler = { (userInitiated) -> Void in
expectation.fulfill()
}
// Encourage the runtime to deallocate the token immediately
autoreleasepool {
var token = MDCSnackbarManager.default.suspendAllMessages()
MDCSnackbarManager.default.show(suspendedMessage)
token = nil
// When
XCTAssertNil(token, "Ensuring that the compiler knows we're reading this variable")
}
// Then
// Swift unit tests are sometimes slower, need to wait a little longer
self.waitForExpectations(timeout: 3.0, handler: nil)
}
func testHasMessagesShowingOrQueued() {
let message = MDCSnackbarMessage(text: "foo1")
message.duration = 10
MDCSnackbarManager.default.show(message)
let expectation = self.expectation(description: "has_shown_message")
// We need to dispatch_async in order to assure that the assertion happens after showMessage:
// actually displays the message.
DispatchQueue.main.async {
XCTAssertTrue(MDCSnackbarManager.default.hasMessagesShowingOrQueued())
expectation.fulfill()
}
self.waitForExpectations(timeout: 3.0, handler: nil)
}
}
| apache-2.0 |
liuCodeBoy/Ant | Ant/Ant/LunTan/Detials/Model/RentOut/LunTanDetialModel.swift | 1 | 3238 | //
// LunTanDetialModel.swift
// Ant
//
// Created by Weslie on 2017/8/15.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
import SDWebImage
//import MJExtension
class LunTanDetialModel: NSObject {
var listCellType : Int?
var id : NSNumber?
var picture: [String]?
var title: String?
var house_type: String?
var house_source: String?
var price: String?
var rent_way: String?
var empty_time: Int?
var area: String?
var label: String?
var content: String?
var contact_name: String?
var contact_phone: String?
var weixin: String?
var qq: String?
var email: String?
//MARK: - 求租
var type: Int?
// MARK:- 求职
var education: String?
var expect_wage: String?
var experience: String?
var industry_id: Int?
var job_nature: String?
var self_info: String? //同城交友
var time: Int? //同城交友
var visa: String?
//汽车买卖
var company_address: String?
var company_internet: String?
var company_name: String?
//同城交友
var age: String?
var constellation: String?
var felling_state: String?
var friends_request: String?
var height: String?
var hometown: String?
var job: String?
var name: String?
var sex: String?
var weight: String?
// MARK:- 处理完的数据
var labelItems: [String]?
lazy var pictureArray: [URL] = [URL]()
var checkinTime: String?
lazy var connactDict: [[String : String]] = [[String : String]]()
var industry: String?
var want_job_creat: String?
init(dict: [String: AnyObject]){
super.init()
setValuesForKeys(dict)
//处理模型的数据
// if let pictureArray = picture {
// for urlItem in pictureArray {
// let url = URL(string: urlItem)
// self.pictureArray.append(url!)
// }
// }
if let check = empty_time {
checkinTime = Date.createDateString(String(check))
}
if let labels = label {
labelItems = labels.components(separatedBy: ",")
}
//联系人信息
if let name = self.contact_name {
connactDict.append(["联系人" : name])
}
if let phone = self.contact_phone {
connactDict.append(["电话" : phone])
}
if let weixin = self.weixin {
connactDict.append(["微信" : weixin])
}
if let qq = self.qq {
connactDict.append(["QQ" : qq])
}
if let email = self.email {
connactDict.append(["邮箱" : email])
}
//求职信息
if let industry = self.industry_id {
switch industry {
case 3:
self.industry = "web攻城狮"
default:
self.industry = "sb"
}
}
if let creat = self.time {
want_job_creat = Date.createDateString(String(creat))
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) { }
}
| apache-2.0 |
EstefaniaGilVaquero/ciceIOS | APP_CompartirContacto/SYBContactosTableViewController.swift | 1 | 2268 | //
// SYBContactosTableViewController.swift
// APP_CompartirContacto
//
// Created by cice on 9/9/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class SYBContactosTableViewController: UITableViewController {
//MARK: - VARIABLES LOCALES GLOBALES
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return contactosArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SYBTableViewCell
// Configure the cell...
contactosDiccionario = contactosArray.objectAtIndex(indexPath.row) as! NSDictionary
let firstName = contactosDiccionario["firstName"] as! String
let lastName = contactosDiccionario["lastName"] as! String
let description = contactosDiccionario["description"] as! String
let imageName = contactosDiccionario["imageName"] as! String
let imageCustom = UIImage(named: imageName)
cell.myNombreL.text = firstName
cell.myApellidoLBL.text = lastName
cell.myDescripcionLBL.text = description
cell.myImageIV.image = imageCustom
return cell
}
//MARK: - IBACTION
}
| apache-2.0 |
miletliyusuf/VisionDetect | VisionDetect/VisionDetect.swift | 1 | 16931 | //
// VisionDetect.swift
// VisionDetect
//
// Created by Yusuf Miletli on 8/21/17.
// Copyright © 2017 Miletli. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
import AVFoundation
import ImageIO
public protocol VisionDetectDelegate: AnyObject {
func didNoFaceDetected()
func didFaceDetected()
func didSmile()
func didNotSmile()
func didBlinked()
func didNotBlinked()
func didWinked()
func didNotWinked()
func didLeftEyeClosed()
func didLeftEyeOpened()
func didRightEyeClosed()
func didRightEyeOpened()
}
///Makes every method is optional
public extension VisionDetectDelegate {
func didNoFaceDetected() { }
func didFaceDetected() { }
func didSmile() { }
func didNotSmile() { }
func didBlinked() { }
func didNotBlinked() { }
func didWinked() { }
func didNotWinked() { }
func didLeftEyeClosed() { }
func didLeftEyeOpened() { }
func didRightEyeClosed() { }
func didRightEyeOpened() { }
}
public enum VisionDetectGestures {
case face
case noFace
case smile
case noSmile
case blink
case noBlink
case wink
case noWink
case leftEyeClosed
case noLeftEyeClosed
case rightEyeClosed
case noRightEyeClosed
}
open class VisionDetect: NSObject {
public weak var delegate: VisionDetectDelegate? = nil
public enum DetectorAccuracy {
case BatterySaving
case HigherPerformance
}
public enum CameraDevice {
case ISightCamera
case FaceTimeCamera
}
public typealias TakenImageStateHandler = ((UIImage) -> Void)
public var onlyFireNotificatonOnStatusChange : Bool = true
public var visageCameraView : UIView = UIView()
//Private properties of the detected face that can be accessed (read-only) by other classes.
private(set) var faceDetected : Bool?
private(set) var faceBounds : CGRect?
private(set) var faceAngle : CGFloat?
private(set) var faceAngleDifference : CGFloat?
private(set) var leftEyePosition : CGPoint?
private(set) var rightEyePosition : CGPoint?
private(set) var mouthPosition : CGPoint?
private(set) var hasSmile : Bool?
private(set) var isBlinking : Bool?
private(set) var isWinking : Bool?
private(set) var leftEyeClosed : Bool?
private(set) var rightEyeClosed : Bool?
//Private variables that cannot be accessed by other classes in any way.
private var faceDetector : CIDetector?
private var videoDataOutput : AVCaptureVideoDataOutput?
private var videoDataOutputQueue : DispatchQueue?
private var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
private var captureSession : AVCaptureSession = AVCaptureSession()
private let notificationCenter : NotificationCenter = NotificationCenter.default
private var currentOrientation : Int?
private let stillImageOutput = AVCapturePhotoOutput()
private var detectedGestures:[VisionDetectGestures] = []
private var takenImageHandler: TakenImageStateHandler?
private var takenImage: UIImage? {
didSet {
if let image = self.takenImage {
takenImageHandler?(image)
}
}
}
public init(cameraPosition: CameraDevice, optimizeFor: DetectorAccuracy) {
super.init()
currentOrientation = convertOrientation(deviceOrientation: UIDevice.current.orientation)
switch cameraPosition {
case .FaceTimeCamera : self.captureSetup(position: AVCaptureDevice.Position.front)
case .ISightCamera : self.captureSetup(position: AVCaptureDevice.Position.back)
}
var faceDetectorOptions : [String : AnyObject]?
switch optimizeFor {
case .BatterySaving : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyLow as AnyObject]
case .HigherPerformance : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyHigh as AnyObject]
}
self.faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: faceDetectorOptions)
}
public func addTakenImageChangeHandler(handler: TakenImageStateHandler?) {
self.takenImageHandler = handler
}
//MARK: SETUP OF VIDEOCAPTURE
public func beginFaceDetection() {
self.captureSession.startRunning()
setupSaveToCameraRoll()
}
public func endFaceDetection() {
self.captureSession.stopRunning()
}
private func setupSaveToCameraRoll() {
if captureSession.canAddOutput(stillImageOutput) {
captureSession.addOutput(stillImageOutput)
}
}
public func saveTakenImageToPhotos() {
if let image = self.takenImage {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
public func takeAPicture() {
if self.stillImageOutput.connection(with: .video) != nil {
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first ?? nil
let previewFormat = [String(kCVPixelBufferPixelFormatTypeKey): previewPixelType,
String(kCVPixelBufferWidthKey): 160,
String(kCVPixelBufferHeightKey): 160]
settings.previewPhotoFormat = previewFormat as [String : Any]
self.stillImageOutput.capturePhoto(with: settings, delegate: self)
}
}
private func captureSetup(position: AVCaptureDevice.Position) {
var captureError: NSError?
var captureDevice: AVCaptureDevice?
let devices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.builtInWideAngleCamera],
mediaType: .video,
position: position
).devices
for testedDevice in devices {
if ((testedDevice as AnyObject).position == position) {
captureDevice = testedDevice
}
}
if (captureDevice == nil) {
captureDevice = AVCaptureDevice.default(for: .video)
}
var deviceInput : AVCaptureDeviceInput?
do {
if let device = captureDevice {
deviceInput = try AVCaptureDeviceInput(device: device)
}
} catch let error as NSError {
captureError = error
deviceInput = nil
}
captureSession.sessionPreset = .high
if (captureError == nil) {
if let input = deviceInput,
captureSession.canAddInput(input) {
captureSession.addInput(input)
}
self.videoDataOutput = AVCaptureVideoDataOutput()
self.videoDataOutput?.videoSettings = [
String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_32BGRA)
]
self.videoDataOutput?.alwaysDiscardsLateVideoFrames = true
self.videoDataOutputQueue = DispatchQueue(label: "VideoDataOutputQueue")
self.videoDataOutput?.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue)
if let output = self.videoDataOutput,
captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
}
visageCameraView.frame = UIScreen.main.bounds
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = UIScreen.main.bounds
previewLayer.videoGravity = .resizeAspectFill
visageCameraView.layer.addSublayer(previewLayer)
}
private func addItemToGestureArray(item:VisionDetectGestures) {
if !self.detectedGestures.contains(item) {
self.detectedGestures.append(item)
}
}
var options : [String : AnyObject]?
//TODO: 🚧 HELPER TO CONVERT BETWEEN UIDEVICEORIENTATION AND CIDETECTORORIENTATION 🚧
private func convertOrientation(deviceOrientation: UIDeviceOrientation) -> Int {
var orientation: Int = 0
switch deviceOrientation {
case .portrait:
orientation = 6
case .portraitUpsideDown:
orientation = 2
case .landscapeLeft:
orientation = 3
case .landscapeRight:
orientation = 4
default : orientation = 1
}
return orientation
}
}
// MARK: - AVCapturePhotoCaptureDelegate
extension VisionDetect: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation(),
let image = UIImage(data: imageData) {
self.takenImage = image
}
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension VisionDetect: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
var sourceImage = CIImage()
if takenImage == nil {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer!).toOpaque()
let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue()
sourceImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
}
else {
if let ciImage = takenImage?.ciImage {
sourceImage = ciImage
}
}
options = [
CIDetectorSmile: true as AnyObject,
CIDetectorEyeBlink: true as AnyObject,
CIDetectorImageOrientation: 6 as AnyObject
]
let features = self.faceDetector!.features(in: sourceImage, options: options)
if (features.count != 0) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == false) {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
} else {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
self.faceDetected = true
for feature in features as! [CIFaceFeature] {
faceBounds = feature.bounds
if (feature.hasFaceAngle) {
if (faceAngle != nil) {
faceAngleDifference = CGFloat(feature.faceAngle) - faceAngle!
} else {
faceAngleDifference = CGFloat(feature.faceAngle)
}
faceAngle = CGFloat(feature.faceAngle)
}
if (feature.hasLeftEyePosition) {
leftEyePosition = feature.leftEyePosition
}
if (feature.hasRightEyePosition) {
rightEyePosition = feature.rightEyePosition
}
if (feature.hasMouthPosition) {
mouthPosition = feature.mouthPosition
}
if (feature.hasSmile) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == false) {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
} else {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
hasSmile = feature.hasSmile
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == true) {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
} else {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
hasSmile = feature.hasSmile
}
if (feature.leftEyeClosed || feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isWinking == false) {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
} else {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
isWinking = true
if (feature.leftEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.leftEyeClosed == false) {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
} else {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
leftEyeClosed = feature.leftEyeClosed
}
if (feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.rightEyeClosed == false) {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
} else {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
rightEyeClosed = feature.rightEyeClosed
}
if (feature.leftEyeClosed && feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == false) {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
} else {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
isBlinking = true
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == true) {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
}
if (self.isWinking == true) {
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
}
if (self.leftEyeClosed == true) {
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
}
if (self.rightEyeClosed == true) {
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
} else {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
isBlinking = false
isWinking = false
leftEyeClosed = feature.leftEyeClosed
rightEyeClosed = feature.rightEyeClosed
}
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == true) {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
} else {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
self.faceDetected = false
}
}
}
| mit |
rnystrom/GitHawk | Classes/Issues/Labels/IssueLabelsSectionController.swift | 1 | 3786 | //
// IssueLabelsSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 5/20/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
protocol IssueLabelTapSectionControllerDelegate: class {
func didTapIssueLabel(owner: String, repo: String, label: String)
}
final class IssueLabelsSectionController: ListBindingSectionController<IssueLabelsModel>,
ListBindingSectionControllerDataSource,
ListBindingSectionControllerSelectionDelegate {
private let issue: IssueDetailsModel
private var sizeCache = [String: CGSize]()
private let lockedModel = Constants.Strings.locked
private weak var tapDelegate: IssueLabelTapSectionControllerDelegate?
init(issue: IssueDetailsModel, tapDelegate: IssueLabelTapSectionControllerDelegate) {
self.issue = issue
self.tapDelegate = tapDelegate
super.init()
minimumInteritemSpacing = Styles.Sizes.labelSpacing
minimumLineSpacing = Styles.Sizes.labelSpacing
let row = Styles.Sizes.rowSpacing
inset = UIEdgeInsets(top: row, left: 0, bottom: row/2, right: 0)
dataSource = self
selectionDelegate = self
}
// MARK: ListBindingSectionControllerDataSource
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
viewModelsFor object: Any
) -> [ListDiffable] {
guard let object = self.object else { return [] }
var viewModels: [ListDiffable] = [object.status]
if object.locked {
viewModels.append(lockedModel as ListDiffable)
}
viewModels += object.labels as [ListDiffable]
return viewModels
}
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
sizeForViewModel viewModel: Any,
at index: Int
) -> CGSize {
let key: String
if let viewModel = viewModel as? RepositoryLabel {
key = viewModel.name
} else {
if let viewModel = viewModel as? IssueLabelStatusModel {
key = "status-\(viewModel.status.title)"
} else {
key = "locked-key"
}
}
if let size = sizeCache[key] {
return size
}
let size: CGSize
if let viewModel = viewModel as? RepositoryLabel {
size = LabelListCell.size(viewModel.name)
} else {
if let viewModel = viewModel as? IssueLabelStatusModel {
size = IssueLabelStatusCell.size(viewModel.status.title)
} else {
size = IssueLabelStatusCell.size(lockedModel)
}
}
sizeCache[key] = size
return size
}
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
cellForViewModel viewModel: Any,
at index: Int
) -> UICollectionViewCell & ListBindable {
let cellType: AnyClass
switch viewModel {
case is RepositoryLabel: cellType = LabelListCell.self
default: cellType = IssueLabelStatusCell.self
}
guard let cell = collectionContext?.dequeueReusableCell(of: cellType, for: self, at: index) as? UICollectionViewCell & ListBindable
else { fatalError("Missing context or wrong cell") }
return cell
}
// MARK: ListBindingSectionControllerSelectionDelegate
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didSelectItemAt index: Int, viewModel: Any) {
guard let viewModel = viewModel as? RepositoryLabel else { return }
tapDelegate?.didTapIssueLabel(owner: issue.owner, repo: issue.repo, label: viewModel.name)
}
}
| mit |
giginet/Toybox | Sources/ToyboxKit/PlaygroundBuilder.swift | 1 | 2426 | import Foundation
private func metadata(version: String, platform: Platform) -> String {
let targetPlatform = String(describing: platform).lowercased()
return """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='\(version)' target-platform='\(targetPlatform)'>
<timeline fileName='timeline.xctimeline'/>
</playground>
"""
}
private let defaultContent = """
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
"""
private let defaultContentForMac = """
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
"""
private func defaultContent(for platform: Platform) -> Data {
let content: String
switch platform {
case .iOS, .tvOS:
content = defaultContent
case .macOS:
content = defaultContentForMac
}
return content.data(using: .utf8)!
}
class PlaygroundBuilder {
private let metadataFileName = "contents.xcplayground"
private let contentsFileName = "Contents.swift"
private let fileManager: FileManager = .default
private let playgroundVersion = "5.0.0"
enum Error: Swift.Error {
case invalidPath(URL)
case creationFailure
}
func build(for platform: Platform, to destination: URL) throws -> URL {
do {
try fileManager.createDirectory(at: destination, withIntermediateDirectories: false, attributes: nil)
} catch {
throw Error.invalidPath(destination)
}
let metadataURL = destination.appendingPathComponent(metadataFileName)
let metadataContent = metadata(version: playgroundVersion, platform: platform).data(using: .utf8)
guard fileManager.createFile(atPath: metadataURL.path,
contents: metadataContent,
attributes: nil) else {
throw Error.creationFailure
}
let contentsURL = destination.appendingPathComponent(contentsFileName)
let contentData = defaultContent(for: platform)
guard fileManager.createFile(atPath: contentsURL.path,
contents: contentData,
attributes: nil) else {
throw Error.creationFailure
}
return destination
}
}
| mit |
HaloWang/SwiftFFNN | FFNN/ViewController.swift | 1 | 926 | //
// ViewController.swift
// FFNN
//
// Created by 王策 on 16/7/3.
// Copyright © 2016年 王策. All rights reserved.
//
import UIKit
import SwiftyJSON
class ViewController: UIViewController {
let ffnn = FFNN(inputCount: 3, hiddenCount: 5, outputCount: 1)
override func viewDidLoad() {
super.viewDidLoad()
let data = DataGenerator.generateItems(1000)
for (index, item) in data.enumerated() {
_ = ffnn.update([item.male, item.single, item.age])
ffnn.backpropagate([item.frequency])
if index % 10 == 0 {
let testData = DataGenerator.getPerson()
let result = ffnn.update([testData.male, testData.single, testData.age])
let answer = testData.frequency
print(result[0] - answer)
}
}
_ = DataGenerator.getPerson()
}
}
| mit |
cruinh/CuriosityPhotos | CuriosityRover/PhotoViewController.swift | 1 | 2279 | //
// PhotoViewController.swift
// CuriosityRover
//
// Created by Matt Hayes on 3/9/16.
//
//
import Foundation
import UIKit
class PhotoViewController: UIViewController, UIScrollViewDelegate {
weak var image: UIImage?
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var scrollView: UIScrollView?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var photoInfo: CuriosityRoverData.PhotoInfo?
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView?.minimumZoomScale = 1.0
self.scrollView?.maximumZoomScale = 6.0
populatePhoto()
refreshTitle()
}
func populatePhoto() {
if let imageURL = photoInfo?.img_src {
activityIndicator?.startAnimating()
CuriosityPhotoRepository.getImage(fromURL: imageURL, completion: { [weak self](image, error) -> Void in
guard self != nil else { print("self was nil: \(#file):\(#line)"); return }
if let image = image {
self!.imageView?.image = image
} else {
print("error: photo url invalid: \(imageURL)")
}
self!.activityIndicator?.stopAnimating()
})
} else {
print("error: photo url was nil")
}
}
func refreshTitle() {
var titleString = photoInfo?.camera?.name ?? ""
if let earthDate = photoInfo?.earth_date {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
titleString = titleString + " " + dateFormatter.string(from: earthDate as Date)
}
title = titleString
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? PhotoInfoController {
destinationViewController.photoInfo = self.photoInfo
}
}
@IBAction func dismiss(_ sender: UIButton?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
| mit |
debugsquad/nubecero | nubecero/Model/AdminUsers/MAdminUsersItem.swift | 1 | 480 | import Foundation
class MAdminUsersItem
{
let userId:MSession.UserId
let created:TimeInterval
let lastSession:TimeInterval
let diskUsed:Int
let status:MSession.Status
init(userId:MSession.UserId, firebaseUser:FDatabaseModelUser)
{
self.userId = userId
created = firebaseUser.created
lastSession = firebaseUser.session.timestamp
diskUsed = firebaseUser.diskUsed
status = firebaseUser.session.status
}
}
| mit |
mihaicris/learn | 20140901 BlurrySideBar/BlurrySidebar/ViewController.swift | 1 | 706 | //
// ViewController.swift
// BlurrySidebar
//
// Created by mihai.cristescu on 26/05/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SideBarDelegate {
var sideBar: SideBar!
override func viewDidLoad() {
super.viewDidLoad()
sideBar = SideBar(sourceView: self.view,
menuItems: ["NEW", "EDIT", "ABOUT"])
sideBar.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sideBar(_ sideBar: SideBar, didSelectButtonAt index: Int) {
}
}
| mit |
seanhenry/Chain | Chain/PassiveLink.swift | 1 | 440 | //
// PassiveLink.swift
//
// Copyright © 2016 Sean Henry. All rights reserved.
//
import Swift
open class PassiveLink<PassedType>: Link<PassedType, PassedType> {
public override init() {}
override open var initial: ChainResult<PassedType, Swift.Error> {
didSet {
result = initial
}
}
open func finish() {
previous = nil
next?.initial = result
next?.run()
}
}
| mit |
1170197998/Swift-DEMO | Algorithm/Algorithm/AppDelegate.swift | 1 | 2173 | //
// AppDelegate.swift
// Algorithm
//
// Created by ShaoFeng on 2016/12/21.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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:.
}
}
| apache-2.0 |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBAActiveTask+Dictionary.swift | 1 | 2683 | //
// SBAActiveTask+Dictionary.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension NSDictionary: SBAActiveTask {
var taskTypeName: String? {
return self["taskType"] as? String
}
public var taskType: SBAActiveTaskType {
return SBAActiveTaskType(name: taskTypeName)
}
public var intendedUseDescription: String? {
return self["intendedUseDescription"] as? String
}
public var taskOptions: [String : AnyObject]? {
return self["taskOptions"] as? [String : AnyObject]
}
public var predefinedExclusions: ORKPredefinedTaskOption? {
guard let exclusions = self["predefinedExclusions"] as? UInt else { return nil }
return ORKPredefinedTaskOption(rawValue: exclusions)
}
public var localizedSteps: [SBASurveyItem]? {
guard let steps = self["localizedSteps"] as? [AnyObject] else { return nil }
return steps.map({ return ($0 as? SBASurveyItem) ?? NSDictionary() })
}
}
| bsd-3-clause |
tardieu/swift | test/decl/func/throwing_functions.swift | 10 | 5741 | // RUN: %target-typecheck-verify-swift
enum Exception : Error { case A }
// Basic syntax ///////////////////////////////////////////////////////////////
func bar() throws -> Int { return 0 }
func foo() -> Int { return 0 }
// Currying ///////////////////////////////////////////////////////////////////
func curry1() {
}
func curry1Throws() throws {
}
func curry2() -> () -> () {
return curry1
}
func curry2Throws() throws -> () -> () {
return curry1
}
func curry3() -> () throws -> () {
return curry1Throws
}
func curry3Throws() throws -> () throws -> () {
return curry1Throws
}
var a : () -> () -> () = curry2
var b : () throws -> () -> () = curry2Throws
var c : () -> () throws -> () = curry3
var d : () throws -> () throws -> () = curry3Throws
// Partial application ////////////////////////////////////////////////////////
protocol Parallelogram {
static func partialApply1(_ a: Int) throws
}
func partialApply2<T: Parallelogram>(_ t: T) {
_ = T.partialApply1
}
// Overload resolution/////////////////////////////////////////////////////////
func barG<T>(_ t : T) throws -> T { return t }
func fooG<T>(_ t : T) -> T { return t }
var bGE: (_ i: Int) -> Int = barG // expected-error{{invalid conversion from throwing function of type '(_) throws -> _' to non-throwing function type '(Int) -> Int'}}
var bg: (_ i: Int) throws -> Int = barG
var fG: (_ i: Int) throws -> Int = fooG
func fred(_ callback: (UInt8) throws -> ()) throws { }
func rachel() -> Int { return 12 }
func donna(_ generator: () throws -> Int) -> Int { return generator() } // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}}
_ = donna(rachel)
func barT() throws -> Int { return 0 } // expected-note{{}}
func barT() -> Int { return 0 } // expected-error{{invalid redeclaration of 'barT()'}}
func fooT(_ callback: () throws -> Bool) {} //OK
func fooT(_ callback: () -> Bool) {}
// Throwing and non-throwing types are not equivalent.
struct X<T> { }
func specializedOnFuncType1(_ x: X<(String) throws -> Int>) { }
func specializedOnFuncType2(_ x: X<(String) -> Int>) { }
func testSpecializedOnFuncType(_ xThrows: X<(String) throws -> Int>,
xNonThrows: X<(String) -> Int>) {
specializedOnFuncType1(xThrows) // ok
specializedOnFuncType1(xNonThrows) // expected-error{{cannot convert value of type 'X<(String) -> Int>' to expected argument type 'X<(String) throws -> Int>'}}
specializedOnFuncType2(xThrows) // expected-error{{cannot convert value of type 'X<(String) throws -> Int>' to expected argument type 'X<(String) -> Int>'}}
specializedOnFuncType2(xNonThrows) // ok
}
// Subtyping
func subtypeResult1(_ x: (String) -> ((Int) -> String)) { }
func testSubtypeResult1(_ x1: (String) -> ((Int) throws -> String),
x2: (String) -> ((Int) -> String)) {
subtypeResult1(x1) // expected-error{{cannot convert value of type '(String) -> ((Int) throws -> String)' to expected argument type '(String) -> ((Int) -> String)'}}
subtypeResult1(x2)
}
func subtypeResult2(_ x: (String) -> ((Int) throws -> String)) { }
func testSubtypeResult2(_ x1: (String) -> ((Int) throws -> String),
x2: (String) -> ((Int) -> String)) {
subtypeResult2(x1)
subtypeResult2(x2)
}
func subtypeArgument1(_ x: (_ fn: ((String) -> Int)) -> Int) { }
func testSubtypeArgument1(_ x1: (_ fn: ((String) -> Int)) -> Int,
x2: (_ fn: ((String) throws -> Int)) -> Int) {
subtypeArgument1(x1)
subtypeArgument1(x2)
}
func subtypeArgument2(_ x: (_ fn: ((String) throws -> Int)) -> Int) { }
func testSubtypeArgument2(_ x1: (_ fn: ((String) -> Int)) -> Int,
x2: (_ fn: ((String) throws -> Int)) -> Int) {
subtypeArgument2(x1) // expected-error{{cannot convert value of type '(((String) -> Int)) -> Int' to expected argument type '(((String) throws -> Int)) -> Int'}}
subtypeArgument2(x2)
}
// Closures
var c1 = {() throws -> Int in 0}
var c2 : () throws -> Int = c1 // ok
var c3 : () -> Int = c1 // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c4 : () -> Int = {() throws -> Int in 0} // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c5 : () -> Int = { try c2() } // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}}
var c6 : () throws -> Int = { do { _ = try c2() } ; return 0 }
var c7 : () -> Int = { do { try c2() } ; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c8 : () -> Int = { do { _ = try c2() } catch _ { var x = 0 } ; return 0 } // expected-warning {{initialization of variable 'x' was never used; consider replacing with assignment to '_' or removing it}}
var c9 : () -> Int = { do { try c2() } catch Exception.A { var x = 0 } ; return 0 }// expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c10 : () -> Int = { throw Exception.A; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}}
var c11 : () -> Int = { try! c2() }
var c12 : () -> Int? = { try? c2() }
// Initializers
struct A {
init(doomed: ()) throws {}
}
func fi1() throws {
A(doomed: ()) // expected-error {{call can throw but is not marked with 'try'}} // expected-warning{{unused}}
}
struct B {
init() throws {}
init(foo: Int) {}
}
B(foo: 0) // expected-warning{{unused}}
| apache-2.0 |
spacedrabbit/FollowButtonConcept | FollowButtonConcept/ProfileViewController.swift | 1 | 3542 | //
// ViewController.swift
// FollowButtonConcept
//
// Created by Louis Tur on 5/3/16.
// Copyright © 2016 SRLabs. All rights reserved.
//
import UIKit
import SnapKit
internal struct ConceptColors {
static let LightBlue: UIColor = UIColor(colorLiteralRed: 130.0/255.0, green: 222.0/255.0, blue: 255.0/255.0, alpha: 1.0)
static let MediumBlue: UIColor = UIColor(colorLiteralRed: 113.0/255.0, green: 156.0/255.0, blue: 255.0/255.0, alpha: 1.0)
static let OffWhite: UIColor = UIColor(colorLiteralRed: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: 1.0)
static let DarkText: UIColor = UIColor(colorLiteralRed: 100.0/255.0, green: 100.0/255.0, blue: 150.0/255.0, alpha: 1.0)
}
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.grayColor()
self.setupViewHierarchy()
self.configureConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.followButton.updateCornerRadius()
self.drawGradientIn(self.profileTopSectionView)
}
// MARK: - UI Updates
// ------------------------------------------------------------
internal func drawGradientIn(view: UIView) {
self.view.layoutIfNeeded()
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [ConceptColors.LightBlue.CGColor, ConceptColors.MediumBlue.CGColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPointMake(0.0, 0.0)
gradientLayer.endPoint = CGPointMake(1.0, 1.0)
view.layer.addSublayer(gradientLayer)
}
// MARK: - Layout
internal func configureConstraints() {
self.profileBackgroundView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view).offset(60.0)
make.left.equalTo(self.view).offset(22.0)
make.right.equalTo(self.view).inset(22.0)
make.bottom.equalTo(self.view).inset(60.0)
}
self.profileTopSectionView.snp_makeConstraints { (make) -> Void in
make.top.left.right.equalTo(self.profileBackgroundView)
make.bottom.equalTo(self.profileBottomSectionView.snp_top)
}
self.profileBottomSectionView.snp_makeConstraints { (make) -> Void in
make.left.right.bottom.equalTo(self.profileBackgroundView)
make.top.equalTo(self.profileBackgroundView.snp_centerY).multipliedBy(1.30)
}
self.followButton.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self.profileBottomSectionView.snp_top)
make.centerX.equalTo(self.profileBottomSectionView)
make.height.width.greaterThanOrEqualTo(0.0).priority(990.0)
}
}
internal func setupViewHierarchy() {
self.view.addSubview(profileBackgroundView)
self.profileBackgroundView.addSubview(self.profileTopSectionView)
self.profileBackgroundView.addSubview(self.profileBottomSectionView)
self.profileBackgroundView.addSubview(self.followButton)
}
// MARK: - Lazy Instances
lazy var profileBackgroundView: UIView = {
let view: UIView = UIView()
view.layer.cornerRadius = 12.0
view.clipsToBounds = true
return view
}()
lazy var profileTopSectionView: UIView = {
let view: UIView = UIView()
return view
}()
lazy var profileBottomSectionView: UIView = {
let view: UIView = UIView()
view.backgroundColor = ConceptColors.OffWhite
return view
}()
lazy var followButton: FollowButton = FollowButton()
}
| mit |
dabing1022/AlgorithmRocks | Books/TheArtOfProgrammingByJuly.playground/Pages/1-1 RotateString.xcplaygroundpage/Contents.swift | 1 | 2200 | //: [Previous](@previous)
/*:
给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。
*/
/*: 暴力移位法 */
class Solution {
func leftShiftOne(var string: [Character], length: Int) -> [Character] {
if let firstCharacter = string.first {
for i in 1..<length {
string[i - 1] = string[i]
}
string[length - 1] = firstCharacter
}
return string
}
func leftRotateString(string: [Character], length: Int, var m: Int) -> [Character] {
var resultString = string
while (m > 0) {
resultString = leftShiftOne(resultString, length: string.count)
m = m - 1
}
return resultString
}
}
var string: [Character] = ["I", "L", "O", "V", "E", "Y", "O", "U"]
var string2: [Character] = []
Solution().leftShiftOne(string, length: string.count)
Solution().leftShiftOne(string2, length: string.count)
Solution().leftRotateString(string, length: string.count, m: 7)
/*: 三步反转法 */
class Solution2 {
func reverseString(var string: [Character], var from: Int, var to: Int) -> [Character] {
while (from < to) {
let tmp = string[from]
string[from++] = string[to]
string[to--] = tmp
}
return string
}
func leftRotateString(string: [Character], length: Int, var m: Int) -> [Character] {
m %= length
var resultString = string
resultString = reverseString(resultString, from: 0, to: m - 1)
resultString = reverseString(resultString, from: m, to: length - 1)
resultString = reverseString(resultString, from: 0, to: length - 1)
return resultString
}
}
Solution2().reverseString(string, from: 0, to: 2)
Solution2().leftRotateString(string, length: string.count, m: 7)
//: [Next](@next)
| mit |
mansoor92/MaksabComponents | MaksabComponents/Classes/Registeration/PhoneNumberAlertTemplateViewController.swift | 1 | 3138 | //
// PhoneNumberAlertViewController.swift
// Pods
//
// Created by Incubasys on 31/07/2017.
//
//
import UIKit
import StylingBoilerPlate
open class PhoneNumberAlertTemplateViewController: UIViewController, NibLoadableView {
@IBOutlet weak public var labelTitle: TitleLabel!
@IBOutlet weak public var labelDescription: TextLabel!
@IBOutlet weak public var fieldPhoneNumber: UITextField!
@IBOutlet weak public var fieldPhoneCode: UITextField!
@IBOutlet weak public var btnCancel: UIButton!
@IBOutlet weak public var btnRegister: UIButton!
@IBOutlet weak public var errorLbl: UILabel!
let bundle = Bundle(for: PhoneNumberAlertTemplateViewController.classForCoder())
override open func viewDidLoad() {
super.viewDidLoad()
labelTitle.text = Bundle.localizedStringFor(key: "phone-no-required")
labelDescription.text = Bundle.localizedStringFor(key: "phone-no-required-description")
btnCancel.setTitle(Bundle.localizedStringFor(key: "alert-action-Cancel"), for: .normal)
btnRegister.setTitle(Bundle.localizedStringFor(key: "phone-no-register"), for: .normal)
fieldPhoneNumber.placeholder = Bundle.localizedStringFor(key: "phone-no-enter-number")
fieldPhoneCode.text = Bundle.localizedStringFor(key: "phone-no-country-code")
errorLbl.textColor = UIColor.appColor(color: .Destructive)
errorLbl.font = UIFont.appFont(font: .RubikRegular, pontSize: 10)
fieldPhoneNumber.delegate = self
fieldPhoneCode.delegate = self
fieldPhoneCode.clearButtonMode = .never
fieldPhoneNumber.becomeFirstResponder()
}
@IBAction func actionCancel(_ sender: Any) {
self.view.endEditing(true)
cancelTapped()
}
func cancelTapped(){
self.dismiss(animated: true, completion: nil)
}
@IBAction func actionRegister(_ sender: UIButton) {
guard let phoneNo = getPhoneNo() else {
errorLbl.text = Bundle.localizedStringFor(key: "phone-no-must-be-twelve-digits")
fieldPhoneCode.shake()
fieldPhoneNumber.shake()
return
}
self.view.endEditing(true)
registerTapped(phoneNo: phoneNo)
}
open func registerTapped(phoneNo: String){}
public func getPhoneNo() -> String? {
return RegisterationTemplateViewController.getValidPhoneNoFrom(fieldCode: fieldPhoneCode, fieldPhoneNo: fieldPhoneNumber)
}
}
extension PhoneNumberAlertTemplateViewController: UITextFieldDelegate{
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
errorLbl.text = ""
if textField == fieldPhoneCode{
return RegisterationTemplateViewController.handlePhoneCode(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
}else{
return RegisterationTemplateViewController.handlePhoneNumber(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
}
}
}
| mit |
dkm/gcc-explorer | examples/swift/Max_array.swift | 3 | 418 | // Imperative style array of maximum values per index
func imperativeMaxArray(x: [Int], y: [Int]) -> [Int] {
var maxima: [Int] = []
let count = min(x.count, y.count)
for index in 0..<count {
maxima.append(max(x[index], y[index]))
}
return maxima
}
// Functional style array of maximum values per index
func functionalMaxArray(x: [Int], y: [Int]) -> [Int] {
return zip(x, y).map(max)
}
| bsd-2-clause |
ja-mes/experiments | Old/Random/test project/test project/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// test project
//
// Created by James Brown on 11/24/15.
// Copyright © 2015 James Brown. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/Session.swift | 1 | 2384 | //
// Session.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 1.3.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// Session keeps track of user choices within and between sessions
class Session
{
// ATTRIBUTES ---------------
static let instance = Session()
private static let KEY_ACCOUNT = "agricola_account"
private static let KEY_USERNAME = "agricola_username"
private static let KEY_PASSWORD = "agricola_password"
private static let KEY_PROJECT = "agricola_project"
private static let KEY_AVATAR = "agricola_avatar"
private static let KEY_BOOK = "agricola_book"
private var keyChain = KeychainSwift()
// COMPUTED PROPERTIES -------
var projectId: String?
{
get { return self[Session.KEY_PROJECT] }
set { self[Session.KEY_PROJECT] = newValue }
}
var avatarId: String?
{
get { return self[Session.KEY_AVATAR] }
set { self[Session.KEY_AVATAR] = newValue }
}
var bookId: String?
{
get { return self[Session.KEY_BOOK] }
set { self[Session.KEY_BOOK] = newValue }
}
var accountId: String?
{
get { return self[Session.KEY_ACCOUNT] }
set { self[Session.KEY_ACCOUNT] = newValue }
}
private(set) var userName: String?
{
get { return self[Session.KEY_USERNAME] }
set { self[Session.KEY_USERNAME] = newValue }
}
private(set) var password: String?
{
get { return self[Session.KEY_PASSWORD] }
set { self[Session.KEY_PASSWORD] = newValue }
}
// Whether the current session is authorized (logged in)
var isAuthorized: Bool { return userName != nil && password != nil && accountId != nil}
// INIT -----------------------
private init()
{
// Instance accessed statically
}
// SUBSCRIPT ---------------
private subscript(key: String) -> String?
{
get { return keyChain.get(key) }
set
{
print("STATUS: Session changed: \(key) = \(newValue.or("empty"))")
if let newValue = newValue
{
keyChain.set(newValue, forKey: key)
}
else
{
keyChain.delete(key)
}
}
}
// OTHER METHODS -----------
// Notice that this is the couchbase username, not the one typed by the user
func logIn(accountId: String, userName: String, password: String)
{
self.accountId = accountId
self.userName = userName
self.password = password
}
func logout()
{
self.password = nil
self.userName = nil
self.accountId = nil
}
}
| mit |
raykle/CustomTransition | TabbarControllerTransition/TabbarControllerTransition/SecondViewController.swift | 1 | 892 | //
// SecondViewController.swift
// TabbarControllerTransition
//
// Created by guomin on 16/4/6.
// Copyright © 2016年 iBinaryOrg. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
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.
}
/*
// 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 |
honghaoz/Wattpad-Life | Wattpad Life/Controller/CustomCollectionViewCell.swift | 1 | 868 | //
// CustomCollectionViewCell.swift
// Wattpad Life
//
// Created by Rajul Arora on 2014-09-26.
// Copyright (c) 2014 HonghaoZ. All rights reserved.
//
import UIKit
class CustomCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var avatarName: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configureCell(url:NSURL, name:NSString) {
avatarImage.setImageWithURL(url)
avatarImage.layer.cornerRadius = avatarImage.frame.size.width/2.0
avatarImage.clipsToBounds = true
//avatarImage.setTranslatesAutoresizingMaskIntoConstraints(false)
//avatarName.setTranslatesAutoresizingMaskIntoConstraints(false)
avatarName.text = name
avatarName.adjustsFontSizeToFitWidth = true
}
}
| apache-2.0 |
darthpelo/SurviveAmsterdam | mobile/Pods/QuadratTouch/Source/Shared/Endpoints/Endpoint.swift | 3 | 2807 | //
// Endpoint.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public func +=<K, V> (inout left: Dictionary<K, V>, right: Dictionary<K, V>?) -> Dictionary<K, V> {
if right != nil {
for (k, v) in right! {
left.updateValue(v, forKey: k)
}
}
return left
}
public class Endpoint {
weak var session : Session?
private let baseURL : NSURL
var endpoint: String {
return ""
}
init(session: Session) {
self.session = session
self.baseURL = NSURL(string:session.configuration.server.apiBaseURL) as NSURL!
}
func getWithPath(path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
return self.taskWithPath(path, parameters: parameters, HTTPMethod: "GET", completionHandler: completionHandler)
}
func postWithPath(path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
return self.taskWithPath(path, parameters: parameters, HTTPMethod: "POST", completionHandler: completionHandler)
}
func uploadTaskFromURL(fromURL: NSURL, path: String,
parameters: Parameters?, completionHandler: ResponseClosure?) -> Task {
let request = self.requestWithPath(path, parameters: parameters, HTTPMethod: "POST")
let task = UploadTask(session: self.session!, request: request, completionHandler: completionHandler)
task.fileURL = fromURL
return task
}
private func taskWithPath(path: String, parameters: Parameters?,
HTTPMethod: String, completionHandler: ResponseClosure?) -> Task {
let request = self.requestWithPath(path, parameters: parameters, HTTPMethod: HTTPMethod)
return DataTask(session: self.session!, request: request, completionHandler: completionHandler)
}
private func requestWithPath(path: String, parameters: Parameters?, HTTPMethod: String) -> Request {
var sessionParameters = session!.configuration.parameters()
if sessionParameters[Parameter.oauth_token] == nil {
do {
let accessToken = try session!.keychain.accessToken()
if let accessToken = accessToken {
sessionParameters[Parameter.oauth_token] = accessToken
}
} catch {
}
}
let request = Request(baseURL: self.baseURL, path: (self.endpoint + "/" + path),
parameters: parameters, sessionParameters: sessionParameters, HTTPMethod: HTTPMethod)
request.timeoutInterval = session!.configuration.timeoutInterval
return request
}
}
| mit |
hhroc/yellr-ios | Yellr/Yellr/PollViewController.swift | 1 | 7022 | //
// PollViewController.swift
// Yellr
//
// Created by Debjit Saha on 8/9/15.
// Copyright (c) 2015 wxxi. All rights reserved.
//
import UIKit
class PollViewController : UIViewController, UIScrollViewDelegate {
@IBOutlet weak var mediaContainer: UIScrollView!
@IBOutlet weak var pollQuestionLabel: UILabel!
var pollOptionsTrack = [Int:Bool]()
var pollQuestion: String = ""
var pollOptions = [String]()
var pollId:Int = 0
var pollOptionSelectedTag:Int = 0
var latitude:String = ""
var longitude:String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.mediaContainer.delegate = self;
self.mediaContainer.scrollEnabled = true;
self.mediaContainer.showsVerticalScrollIndicator = true
self.mediaContainer.indicatorStyle = .Default
self.setupPoll()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func viewDidLayoutSubviews() {
self.mediaContainer.contentSize = CGSize(width:self.mediaContainer.frame.width, height: 600)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func cancelTapped(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil);
}
@IBAction func submitTapped(sender: UIBarButtonItem) {
Yellr.println(pollOptionSelectedTag - 100200)
let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
spinningActivity.labelText = "Posting"
spinningActivity.userInteractionEnabled = false
if (pollOptionSelectedTag == 0) {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Please choose an option first")
} else {
post(["media_type":"text", "media_file":"text", "media_text":String(pollOptionSelectedTag - 100200)], method: "upload_media", latitude: self.latitude, longitude: self.longitude) { (succeeded: Bool, msg: String) -> () in
Yellr.println("Media Uploaded : " + msg)
if (msg != "NOTHING" && msg != "Error") {
post(["assignment_id":String(self.pollId), "media_objects":"[\""+msg+"\"]"], method:"publish_post", latitude:self.latitude, longitude:self.longitude) { (succeeded: Bool, msg: String) -> () in
Yellr.println("Post Added : " + msg)
if (msg != "NOTHING") {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
//TODO: show success
self.processPollDone("Thanks!")
//save used assignment ID / poll ID in UserPrefs to grey out used assignment item
let asdefaults = NSUserDefaults.standardUserDefaults()
var savedAssignmentIds = ""
if asdefaults.objectForKey(YellrConstants.Keys.RepliedToAssignments) == nil {
} else {
savedAssignmentIds = asdefaults.stringForKey(YellrConstants.Keys.RepliedToAssignments)!
}
asdefaults.setObject(savedAssignmentIds + "[" + String(self.pollId) + "]", forKey: YellrConstants.Keys.RepliedToAssignments)
asdefaults.synchronize()
} else {
//fail toast
Yellr.println("Poll + Text Upload failed")
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Failed! Please try again.")
}
}
} else {
Yellr.println("Text Upload failed")
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
self.processPollDone("Failed! Please try again.")
}
}
}
}
//MARK: poll setup functions
func setupPoll() {
var button: UIButton!
var buttonPaddingTop: CGFloat
let buttonWidth: CGFloat = UIScreen.mainScreen().bounds.size.width - 35.0
Yellr.println(buttonWidth)
self.pollQuestionLabel.text = self.pollQuestion
self.pollQuestionLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.pollQuestionLabel.numberOfLines = 0
self.pollQuestionLabel.sizeToFit()
var i = 0;
for po in pollOptions {
buttonPaddingTop = 50.0 * CGFloat(i)
button = UIButton(type: UIButtonType.System)
button.setTitle(po, forState: UIControlState.Normal)
button.frame = CGRectMake(0.0, buttonPaddingTop, buttonWidth, 40.0)
button.addTarget(self, action: Selector("pollButtonTouched:"), forControlEvents: UIControlEvents.TouchUpInside)
button.tag = 100200 + i
pollOptionsTrack[button.tag] = false
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow)
button.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow).CGColor
self.mediaContainer.addSubview(button)
i++
//CGRectMake
}
}
func pollButtonTouched(sender: UIButton!) {
for (tag,status) in pollOptionsTrack {
let tmpButton = self.view.viewWithTag(tag) as? UIButton
tmpButton!.backgroundColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow)
tmpButton!.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.very_light_yellow).CGColor
pollOptionsTrack[tag] = false
Yellr.println("\(status)")
}
pollOptionSelectedTag = sender.tag
pollOptionsTrack[sender.tag] = true
sender.backgroundColor = UIColorFromRGB(YellrConstants.Colors.dark_yellow)
sender.layer.borderColor = UIColorFromRGB(YellrConstants.Colors.dark_yellow).CGColor
}
func processPollDone(mesg: String) {
let spinningActivityFail = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
spinningActivityFail.customView = UIView()
spinningActivityFail.mode = MBProgressHUDMode.CustomView
spinningActivityFail.labelText = mesg
//spinningActivityFail.yOffset = iOS8 ? 225 : 175
spinningActivityFail.hide(true, afterDelay: NSTimeInterval(2.5))
}
} | mit |
prot3ct/Ventio | Ventio/Ventio/Config/API.swift | 1 | 752 | import Foundation
public final class API
{
private static let ventioApiUrl = "https://ios-db.herokuapp.com"
internal static let signInUrl = "\(ventioApiUrl)/api/auth/login"
internal static let registerUrl = "\(ventioApiUrl)/api/auth/register"
internal static let createEventUrl = "\(ventioApiUrl)/api/events"
static func eventsForCurrentUserUrl(username: String) -> String {
return "\(ventioApiUrl)/api/events/\(username)"
}
static func addFriendForCurrentUserUrl(username: String) -> String{
return "\(ventioApiUrl)/api/\(username)/friends"
}
static func getFriendsForCurrentUserUrl(username: String) -> String {
return "\(ventioApiUrl)/api/\(username)/friends"
}
}
| apache-2.0 |
glessard/swift-channels | ChannelsTests/MergeTest.swift | 1 | 2646 | //
// MergeTest.swift
// Channels
//
// Created by Guillaume Lessard on 2015-01-15.
// Copyright (c) 2015 Guillaume Lessard. All rights reserved.
//
import Darwin
import Foundation
import XCTest
@testable import Channels
class MergeTests: XCTestCase
{
let outerloopcount = 10
let innerloopcount = 6_000
func testPerformanceMerge()
{
self.measure() {
var chans = [Receiver<Int>]()
for _ in 0..<self.outerloopcount
{
let c = SBufferedChan<Int>(self.innerloopcount)
async {
for j in 1...self.innerloopcount { c.put(j) }
c.close()
}
chans.append(Receiver(c))
}
let c = chans.merge()
var total = 0
while let _ = c.receive()
{
total += 1
}
XCTAssert(total == self.outerloopcount*self.innerloopcount, "Incorrect merge (\(total)) in \(#function)")
}
}
func testPerformanceMergeUnbuffered()
{
self.measure() {
var chans = [Receiver<Int>]()
for _ in 0..<self.outerloopcount
{
let c = QUnbufferedChan<Int>()
async {
for j in 1...self.innerloopcount { c.put(j) }
c.close()
}
chans.append(Receiver(c))
}
let c = chans.merge()
var total = 0
while let _ = c.receive()
{
total += 1
}
XCTAssert(total == self.outerloopcount*self.innerloopcount, "Incorrect merge (\(total)) in \(#function)")
}
}
func testPerformanceRoundRobinMerge()
{
self.measure() {
var chans = [Receiver<Int>]()
for _ in 0..<self.outerloopcount
{
let c = SBufferedChan<Int>(self.innerloopcount)
async {
for j in 1...self.innerloopcount { c.put(j) }
c.close()
}
chans.append(Receiver(c))
}
let c = mergeRR(chans)
var total = 0
while let _ = c.receive()
{
total += 1
}
XCTAssert(total == self.outerloopcount*self.innerloopcount, "Incorrect merge (\(total)) in \(#function)")
}
}
func testPerformanceRoundRobinMergeUnbuffered()
{
self.measure() {
var chans = [Receiver<Int>]()
for _ in 0..<self.outerloopcount
{
let c = QUnbufferedChan<Int>()
async {
for j in 1...self.innerloopcount { c.put(j) }
c.close()
}
chans.append(Receiver(c))
}
let c = mergeRR(chans)
var total = 0
while let _ = c.receive()
{
total += 1
}
XCTAssert(total == self.outerloopcount*self.innerloopcount, "Incorrect merge (\(total)) in \(#function)")
}
}
}
| mit |
stephentyrone/swift | test/Driver/PrivateDependencies/malformed-fine.swift | 5 | 3770 | // RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/malformed-after-fine/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST-NOT: Handled
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: Handled other.swift
// CHECK-SECOND: Handled main.swift
// RUN: touch -t 201401240007 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
// CHECK-THIRD: Handled main.swift
// CHECK-THIRD: Handled other.swift
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/malformed-after-fine/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: touch -t 201401240006 %t/main.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s
// RUN: touch -t 201401240007 %t/main.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s
// CHECK-FOURTH-NOT: Handled other.swift
// CHECK-FOURTH: Handled main.swift
// CHECK-FOURTH-NOT: Handled other.swift
| apache-2.0 |
mibaldi/IOS_MIMO_APP | iosAPP/ingredients/IngredientsViewController.swift | 1 | 4405 | //
// IngredientsViewController.swift
// iosAPP
//
// Created by MIMO on 14/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import UIKit
class IngredientsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
@IBOutlet weak var categorias: UICollectionView!
let reuseIdentifier = "cell"
var items = [Dictionary<String,AnyObject>]()
var category = ""
var screenWidth = UIScreen.mainScreen().bounds.width
var screenHeight = UIScreen.mainScreen().bounds.height
var myLayout = UICollectionViewFlowLayout()
@IBOutlet weak var ingredientsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setText()
categoryInit()
myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
myLayout.minimumInteritemSpacing = 0
myLayout.minimumLineSpacing = 0
if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation){
screenWidth = UIScreen.mainScreen().bounds.width
screenHeight = UIScreen.mainScreen().bounds.height
print("POO")
myLayout.itemSize = CGSize(width:screenWidth/4 , height: screenHeight/3)
}else{
myLayout.itemSize = CGSize(width: screenWidth/3, height: screenHeight/5.5)
}
self.categorias.setCollectionViewLayout(myLayout, animated: false)
}
func setText(){
ingredientsLabel.text = NSLocalizedString("INGREDIENTS",comment:"Ingredientes")
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
screenWidth = UIScreen.mainScreen().bounds.width
screenHeight = UIScreen.mainScreen().bounds.height
if (toInterfaceOrientation.isLandscape){
myLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
myLayout.minimumInteritemSpacing = 0
myLayout.minimumLineSpacing = 0
myLayout.itemSize = CGSize(width:screenHeight/4 , height: screenWidth/3)
}else{
myLayout.itemSize = CGSize(width: screenHeight/3, height: screenWidth/5.5)
}
self.categorias.setCollectionViewLayout(myLayout, animated: false)
}
func categoryInit(){
let filePath = NSBundle.mainBundle().pathForResource("Category", ofType: "json")
let jsonData = NSData.init(contentsOfFile: filePath!)
do {
let objOrigen = try NSJSONSerialization.JSONObjectWithData(jsonData!,
options: [.MutableContainers, .MutableLeaves]) as! [String:AnyObject]
for category in objOrigen["Categories"] as! [[String:AnyObject]] {
items.append(category)
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCollectionViewCell
cell.categoryLabel.text = self.items[indexPath.item]["category"] as? String
var image = self.items[indexPath.item]["image"] as! String
if(image == ""){
image = "Carne"
}
cell.image.image = UIImage(named: image)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
category = items[indexPath.row]["category"] as! String
performSegueWithIdentifier("ingredientsCategory", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let segueID = segue.identifier{
if segueID == "ingredientsCategory"{
if let destinoVC = segue.destinationViewController as? IngredientListViewController{
destinoVC.category = self.category
}
}
}
}
}
| apache-2.0 |
kokuyoku82/NumSwift | NumSwift/Source/FFT.swift | 1 | 11893 | //
// Dear maintainer:
//
// When I wrote this code, only I and God
// know what it was.
// Now, only God knows!
//
// So if you are done trying to 'optimize'
// this routine (and failed),
// please increment the following counter
// as warning to the next guy:
//
// var TotalHoursWastedHere = 0
//
// Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
import Accelerate
/**
Complex-to-Complex Fast Fourier Transform.
- Note: we use radix-2 fft. As a result, it may process only partial input
data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns:
- `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func fft(realp:[Double], imagp: [Double]) -> (realp:[Double], imagp:[Double]) {
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputRealp = [Double](realp[0..<fftN])
var inputImagp = [Double](imagp[0..<fftN])
var fftCoefRealp = [Double](count: fftN, repeatedValue:0.0)
var fftCoefImagp = [Double](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD)
vDSP_DFT_ExecuteD(setup, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp)
// destroy setup.
vDSP_DFT_DestroySetupD(setup)
return (fftCoefRealp, fftCoefImagp)
}
/**
Complex-to-Complex Fast Fourier Transform.
- Note: that we use radix-2 fft. As a result, it may process only partial input
data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func fft(realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputRealp = [Float](realp[0..<fftN])
var inputImagp = [Float](imagp[0..<fftN])
var fftCoefRealp = [Float](count: fftN, repeatedValue:0.0)
var fftCoefImagp = [Float](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD)
vDSP_DFT_Execute(setup, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp)
// destroy setup.
vDSP_DFT_DestroySetup(setup)
return (fftCoefRealp, fftCoefImagp)
}
/**
Complex-to-Complex Inverse Fast Fourier Transform.
- Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process
only partial input data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func ifft(realp:[Double], imagp:[Double]) -> (realp:[Double], imagp:[Double]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputCoefRealp = [Double](realp[0..<fftN])
var inputCoefImagp = [Double](imagp[0..<fftN])
var outputRealp = [Double](count: fftN, repeatedValue:0.0)
var outputImagp = [Double](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE)
vDSP_DFT_ExecuteD(setup, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp)
// normalization of ifft
var scale = Double(fftN)
var normalizedOutputRealp = [Double](count: fftN, repeatedValue:0.0)
var normalizedOutputImagp = [Double](count: fftN, repeatedValue:0.0)
vDSP_vsdivD(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN))
vDSP_vsdivD(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN))
// destroy setup.
vDSP_DFT_DestroySetupD(setup)
return (normalizedOutputRealp, normalizedOutputImagp)
}
/**
Complex-to-Complex Inverse Fast Fourier Transform.
- Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process
only partial input data depending on the # of data is of power of 2 or not.
- Parameters:
- realp: real part of input data
- imagp: imaginary part of input data
- Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named
attributes, `realp` and `imagp`.
*/
public func ifft(realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){
let log2N = vDSP_Length(log2f(Float(realp.count)))
let fftN = Int(1 << log2N)
// buffers.
var inputCoefRealp = [Float](realp[0..<fftN])
var inputCoefImagp = [Float](imagp[0..<fftN])
var outputRealp = [Float](count: fftN, repeatedValue:0.0)
var outputImagp = [Float](count: fftN, repeatedValue:0.0)
// setup DFT and execute.
let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE)
defer {
// destroy setup.
vDSP_DFT_DestroySetup(setup)
}
vDSP_DFT_Execute(setup, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp)
// normalization of ifft
var scale = Float(fftN)
var normalizedOutputRealp = [Float](count: fftN, repeatedValue:0.0)
var normalizedOutputImagp = [Float](count: fftN, repeatedValue:0.0)
vDSP_vsdiv(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN))
vDSP_vsdiv(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN))
return (normalizedOutputRealp, normalizedOutputImagp)
}
/**
Convolution with Fast Fourier Transform
Perform convolution by Fast Fourier Transform
- Parameters:
- x: input array for convolution.
- y: input array for convolution.
- mode: mode of the convolution.
- "full": return full result (default).
- "same": return result with the same length as the longest input arrays between x and y.
- "valid": only return the result given for points where two arrays overlap completely.
- Returns: the result of the convolution of x and y.
*/
public func fft_convolve(x:[Double], y:[Double], mode:String = "full") -> [Double] {
var longArray:[Double]
var shortArray:[Double]
if x.count < y.count {
longArray = [Double](y)
shortArray = [Double](x)
} else {
longArray = [Double](x)
shortArray = [Double](y)
}
let N = longArray.count
let M = shortArray.count
let convN = N+M-1
let convNPowTwo = leastPowerOfTwo(convN)
longArray = pad(longArray, toLength:convNPowTwo, value:0.0)
shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0)
let zeros = [Double](count:convNPowTwo, repeatedValue:0.0)
var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros)
var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros)
// setup input buffers for vDSP_zvmulD
// long array:
var coefLongArrayComplex = DSPDoubleSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp)
// short array:
var coefShortArrayComplex = DSPDoubleSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp)
// setup output buffers for vDSP_zvmulD
var coefConvRealp = [Double](count:convNPowTwo, repeatedValue:0.0)
var coefConvImagp = [Double](count:convNPowTwo, repeatedValue:0.0)
var coefConvComplex = DSPDoubleSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp)
// Elementwise Complex Multiplication
vDSP_zvmulD(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1,
&coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1))
// ifft
var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp)
// Remove padded zeros
convResult = [Double](convResult[0..<convN])
// modify the result according mode before return
let finalResult:[Double]
switch mode {
case "same":
let numOfResultToBeRemoved = convN - N
let toBeRemovedHalf = numOfResultToBeRemoved / 2
if numOfResultToBeRemoved % 2 == 0 {
finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)])
} else {
finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)])
}
case "valid":
finalResult = [Double](convResult[(M-1)..<(convN-M+1)])
default:
finalResult = convResult
}
return finalResult
}
/**
Convolution with Fast Fourier Transform
Perform convolution by Fast Fourier Transform
- Parameters:
- x: input array for convolution.
- y: input array for convolution.
- mode: mode of the convolution.
- "full": return full result (default).
- "same": return result with the same length as the longest input array between x and y.
- "valid": only return the result given for points where two arrays overlap completely.
- Returns: the result of the convolution of x and y.
*/
public func fft_convolve(x:[Float], y:[Float], mode:String = "full") -> [Float] {
var longArray:[Float]
var shortArray:[Float]
if x.count < y.count {
longArray = [Float](y)
shortArray = [Float](x)
} else {
longArray = [Float](x)
shortArray = [Float](y)
}
let N = longArray.count
let M = shortArray.count
let convN = N+M-1
let convNPowTwo = leastPowerOfTwo(convN)
longArray = pad(longArray, toLength:convNPowTwo, value:0.0)
shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0)
let zeros = [Float](count:convNPowTwo, repeatedValue:0.0)
var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros)
var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros)
// setup input buffers for vDSP_zvmulD
// long array:
var coefLongArrayComplex = DSPSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp)
// short array:
var coefShortArrayComplex = DSPSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp)
// setup output buffers for vDSP_zvmulD
var coefConvRealp = [Float](count:convNPowTwo, repeatedValue:0.0)
var coefConvImagp = [Float](count:convNPowTwo, repeatedValue:0.0)
var coefConvComplex = DSPSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp)
// Elementwise Complex Multiplication
vDSP_zvmul(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1,
&coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1))
// ifft
var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp)
// Remove padded zeros
convResult = [Float](convResult[0..<convN])
// modify the result according mode before return
let finalResult:[Float]
switch mode {
case "same":
let numOfResultToBeRemoved = convN - N
let toBeRemovedHalf = numOfResultToBeRemoved / 2
if numOfResultToBeRemoved % 2 == 0 {
finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)])
} else {
finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)])
}
case "valid":
finalResult = [Float](convResult[(M-1)..<(convN-M+1)])
default:
finalResult = convResult
}
return finalResult
} | mit |
hooman/swift | test/SILOptimizer/invalid_escaping_captures.swift | 13 | 10207 | // RUN: %target-swift-frontend -emit-sil %s -verify
// RUN: %target-swift-frontend -emit-sil %s -verify
func takesEscaping(_: @escaping () -> ()) {}
func takesNonEscaping(_ fn: () -> ()) { fn() }
func badClosureCaptureInOut1(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
takesEscaping { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
}
}
func badClosureCaptureInOut2(x: inout Int, b: Bool) { // expected-note 2{{parameter 'x' is declared 'inout'}}
takesEscaping(b ? { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
} : { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x -= 1 // expected-note {{captured here}}
})
}
func badClosureCaptureNoEscape1(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
takesEscaping { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
}
}
func badClosureCaptureNoEscape2(y: () -> (), b: Bool) { // expected-note 2{{parameter 'y' is implicitly non-escaping}}
takesEscaping(b ? { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
} : { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
y() // expected-note {{captured here}}
})
}
func badClosureCaptureNoEscape3(y: () -> ()) {
let yy = (y, y)
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
yy.0() // expected-note {{captured here}}
}
}
func badClosureCaptureNoEscape4(y: () -> (), z: () -> (), b: Bool) {
let x = b ? y : z
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
x() // expected-note {{captured here}}
}
}
func badLocalFunctionCaptureInOut1(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() {
x += 1 // expected-note {{captured here}}
}
takesEscaping(local) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
func badLocalFunctionCaptureInOut2(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() {
x += 1 // expected-note {{captured here}}
}
takesEscaping { // expected-error {{escaping closure captures 'inout' parameter 'x'}}
local() // expected-note {{captured indirectly by this call}}
}
}
func badLocalFunctionCaptureInOut3(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local1() {
x += 1 // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
func badLocalFunctionCaptureNoEscape1(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local() {
y() // expected-note {{captured here}}
}
takesEscaping(local) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
func badLocalFunctionCaptureNoEscape2(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local() {
y() // expected-note {{captured here}}
}
takesEscaping { // expected-error {{escaping closure captures non-escaping parameter 'y'}}
local() // expected-note {{captured indirectly by this call}}
}
}
func badLocalFunctionCaptureNoEscape3(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local1() {
y() // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
func badLocalFunctionCaptureNoEscape4(y: () -> ()) { // expected-note {{parameter 'y' is implicitly non-escaping}}
func local1() {
takesNonEscaping(y) // expected-note {{captured here}}
}
func local2() {
local1() // expected-note {{captured indirectly by this call}}
}
takesEscaping(local2) // expected-error {{escaping local function captures non-escaping parameter 'y'}}
}
// Capturing 'self' produces a different diagnostic.
struct SelfCapture {
var a: Int
mutating func badLocalFunctionCaptureInOut() {
// FIXME: The 'captured here' location chosen here is not ideal, because
// the original closure is formed in a closure that is nested inside the
// local function. That's a funny edge case that trips up the heuristics.
func _foo() {
a += 1
takesEscaping { // expected-error {{escaping closure captures mutating 'self' parameter}}
_foo() // expected-note {{captured here}}
}
}
}
}
// Make sure reabstraction thunks don't cause problems.
func takesEscapingGeneric<T>(_: @escaping () -> T) {}
func testGenericClosureReabstraction(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
takesEscapingGeneric { () -> Int in // expected-error {{escaping closure captures 'inout' parameter 'x'}}
x += 1 // expected-note {{captured here}}
return 0
}
}
func testGenericLocalFunctionReabstraction(x: inout Int) { // expected-note {{parameter 'x' is declared 'inout'}}
func local() -> Int {
x += 1 // expected-note {{captured here}}
return 0
}
takesEscapingGeneric(local) // expected-error {{escaping local function captures 'inout' parameter 'x'}}
}
// Make sure that withoutActuallyEscaping counts as a safe use.
func goodUseOfNoEscapeClosure(fn: () -> (), fn2: () -> ()) {
withoutActuallyEscaping(fn) { _fn in
takesEscaping(_fn)
}
}
// Some random regression tests
infix operator ~>
protocol Target {}
func ~> <Target, Arg0, Result>(x: inout Target, f: @escaping (_: inout Target, _: Arg0) -> Result) -> (Arg0) -> Result {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
return { f(&x, $0) } // expected-note {{captured here}}
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
}
func ~> (x: inout Int, f: @escaping (_: inout Int, _: Target) -> Target) -> (Target) -> Target {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
return { f(&x, $0) } // expected-note {{captured here}}
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
}
func addHandler(_: @escaping () -> ()) {}
public struct SelfEscapeFromInit {
public init() {
addHandler { self.handler() }
// expected-error@-1 {{escaping closure captures mutating 'self' parameter}}
// expected-note@-2 {{captured here}}
}
public mutating func handler() {}
}
func autoclosureTakesEscaping(_ x: @escaping @autoclosure () ->Int) {}
// Test that captures of escaping autoclosure are diagnosed correctly.
func badCaptureInAutoclosure(x: inout Int) {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
// expected-note@-2 {{parameter 'x' is declared 'inout'}}
autoclosureTakesEscaping(x)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
autoclosureTakesEscaping((x + 1) - 100)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
}
// Test that transitive captures in autoclosures are diagnosed correctly.
func badTransitiveCaptureInClosures(x: inout Int) -> ((Int) -> Void) {
// expected-note@-1 {{parameter 'x' is declared 'inout'}}
// expected-note@-2 {{parameter 'x' is declared 'inout'}}
// expected-note@-3 {{parameter 'x' is declared 'inout'}}
// Test capture of x by an autoclosure within a non-escaping closure.
let _ = { (y: Int) in
autoclosureTakesEscaping(x + y)
// expected-error@-1 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-2 {{pass a copy of 'x'}}
}
// Test capture of x by an autoclosure within an escaping closure.
let escapingClosure = { (y: Int) in
// expected-error@-1 {{escaping closure captures 'inout' parameter 'x'}}
autoclosureTakesEscaping(x + y)
// expected-note@-1 {{captured indirectly by this call}}
// expected-note@-2 {{captured here}}
// expected-error@-4 {{escaping autoclosure captures 'inout' parameter 'x'}}
// expected-note@-5 {{pass a copy of 'x'}}
}
return escapingClosure
}
// Test that captures of mutating 'self' in escaping autoclosures are diagnosed correctly.
struct S {
var i = 0
init() {
autoclosureTakesEscaping(i)
// expected-error@-1 {{escaping autoclosure captures mutating 'self' parameter}}
// expected-note@-2 {{pass a copy of 'self'}}
}
mutating func method() {
autoclosureTakesEscaping(i)
// expected-error@-1 {{escaping autoclosure captures mutating 'self' parameter}}
// expected-note@-2 {{pass a copy of 'self'}}
}
}
// Test that we look through the SILBoxType used for a 'var' binding
func badNoEscapeCaptureThroughVar(_ fn: () -> ()) {
var myFunc = fn // expected-warning {{never mutated}} // expected-note {{captured here}}
takesEscaping { // expected-error {{escaping closure captures non-escaping value}}
myFunc()
}
}
@inline(never)
func takeNoEscapeReturnGetter(f: ()->()->Int64) -> ()->Int64 { return f() }
// Test that invalid escaping capture diagnostics are run on nested
// closures before exclusivity diagnostics are run. Exclusivity
// diagnostics need to inspect all referenced closures that capture
// inouts. Also ensure that exclusivity diagnostics does not crash
// when verifying that a closure that captures inout does not escape
// as long as a previous diagnostic error is present.
struct TestInoutEscapeInClosure {
var someValue: Int64 = 0
mutating func testInoutEscapeInClosure() -> () -> Int64 {
return takeNoEscapeReturnGetter {
return { return someValue } // expected-error {{escaping closure captures mutating 'self' parameter}}
// expected-note@-1 {{captured here}}
}
}
}
| apache-2.0 |
cismet/belis-app | belis-app/SimpleInfoCell.swift | 1 | 3225 | //
// SimpleInfoCell.swift
// belis-app
//
// Created by Thorsten Hell on 16/03/15.
// Copyright (c) 2015 cismet. All rights reserved.
//
import Foundation
class SimpleInfoCell : UITableViewCell, CellDataUI {
func fillFromCellData(_ cellData: CellData) {
if let d=cellData as? SimpleInfoCellData{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.none
}else if let d=cellData as? SimpleInfoCellDataWithDetails{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.disclosureIndicator
}else if let d=cellData as? SimpleInfoCellDataWithDetailsDrivenByWholeObject{
super.textLabel!.text=d.data
accessoryType=UITableViewCellAccessoryType.disclosureIndicator
}
}
func getPreferredCellHeight() -> CGFloat {
return CGFloat(44)
}
}
class SimpleInfoCellData : CellData {
var data: String
init(data:String){
self.data=data
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
}
class SimpleInfoCellDataWithDetails : CellData,SimpleCellActionProvider {
var data: String
var details: [String: [CellData]] = ["main":[]]
var sections: [String]
var actions: [BaseEntityAction]?
init(data:String,details:[String: [CellData]], sections: [String]){
self.data=data
self.details=details
self.sections=sections
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
@objc func action(_ vc:UIViewController) {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
detailVC.sections=sections
detailVC.setCellData(details)
vc.navigationController?.pushViewController(detailVC, animated: true)
}
}
class SimpleInfoCellDataWithDetailsDrivenByWholeObject : CellData,SimpleCellActionProvider {
var detailObject: BaseEntity?
var data: String
var showSubActions: Bool
//var mvc: MainViewController
init(data:String,detailObject: BaseEntity, showSubActions:Bool){
assert(detailObject is CellDataProvider)
self.data=data
self.detailObject=detailObject
self.showSubActions=showSubActions
}
@objc func getCellReuseIdentifier() -> String {
return "simple"
}
@objc func action(_ vc:UIViewController) {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
detailVC.sections=(detailObject as! CellDataProvider).getDataSectionKeys()
detailVC.setCellData((detailObject as! CellDataProvider).getAllData())
detailVC.objectToShow=detailObject
if showSubActions {
if let actionProvider = detailObject as? ActionProvider {
let action = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: detailVC, action:#selector(DetailVC.moreAction))
detailVC.navigationItem.rightBarButtonItem = action
detailVC.actions=actionProvider.getAllActions()
}
}
vc.navigationController?.pushViewController(detailVC, animated: true)
}
}
| mit |
Paladinfeng/Weibo-Swift | Weibo/Weibo/Classes/Tools/Lib/SandBoxPath/NSString+Path.swift | 1 | 854 | //
// NSString+Path.swift
// Weibo
//
// Created by Paladinfeng on 15/12/8.
// Copyright © 2015年 Paladinfeng. All rights reserved.
//
import UIKit
extension NSString{
func appendDocumentPath() -> String {
return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(self.lastPathComponent)
}
func appendCachePath() -> String {
return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(self.lastPathComponent)
}
func appendTempPath() -> String {
return (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(self.lastPathComponent)
}
}
| mit |
mozilla-mobile/firefox-ios | Client/Frontend/Home/Blurrable.swift | 2 | 683 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
// Conveniance protocol to have a blur on a collection view cell
// Currently used on the homepage cells
protocol Blurrable: UICollectionViewCell {
var shouldApplyWallpaperBlur: Bool { get }
func adjustBlur(theme: Theme)
}
extension Blurrable {
var shouldApplyWallpaperBlur: Bool {
guard !UIAccessibility.isReduceTransparencyEnabled else { return false }
return WallpaperManager().currentWallpaper.type != .defaultWallpaper
}
}
| mpl-2.0 |
sharath-cliqz/browser-ios | Client/Frontend/Widgets/Menu/Items/MenuItem.swift | 2 | 516 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
protocol MenuItem {
var title: String { get }
var action: MenuAction { get }
var secondaryAction: MenuAction? { get }
var animation: Animatable? { get }
func iconForState(_ appState: AppState) -> UIImage?
func selectedIconForState(_ appState: AppState) -> UIImage?
}
| mpl-2.0 |
Prosumma/Parsimonious | Parsimonious/ParseError.swift | 1 | 4117 | //
// ParseError.swift
// Parsimonious
//
// Created by Gregory Higley on 2019-03-19.
// Copyright © 2019 Prosumma LLC.
//
// Licensed under the MIT license: https://opensource.org/licenses/MIT
// Permission is granted to use, copy, modify, and redistribute the work.
// Full license information available in the project LICENSE file.
//
import Foundation
/**
A marker protocol indicating a parsing error.
Combinators such as `|` look for this marker
protocol when deciding whether to handle the
error or rethrow it.
Parsimonious has only one class that implements
this protocol: `ParseError`.
See the documentation for `ParseError` on
the philosophy behind errors and error handling
in Parsimonious.
*/
public protocol ParsingError: Error {}
/**
An error that occurs as a result of parser failure.
There really only is one kind of parser failure: a parser was not satisfied.
_Why_ it was not satisfied is a mere detail, but there are really only two
possibilities. In the first case, something unexpected was encountered and
the parser failed to match. In the second case, EOF was encountered and the
parser failed to match. This is true even in the case of a `count` combinator
whose count was unsatisfied. If we say `count(7, parser)` but the underlying
parser was only matched 6 times, we must ask why it was only matched 6 times.
There are only two possibilites: something unexpected or EOF.
Why throw errors at all? A parser is a function with the signature
`(Context<C>) throws -> T`. The return type of a parser is the value matched,
so we indicate failure with an error. Instead of this, we might have defined
a parser as `(Context<C>) -> Result<T, Error>`. This certainly would have
worked, but the problem is the greater ceremony required to deal with it. It
is primarily for this reason that parsers throw errors. By throwing errors,
we can use much more natural syntax to backtrack when a parser fails, e.g.,
```
func match<C, T>(_ parsers: Parser<C, T>...) -> Parser<C, [T]> {
return transact { context in
var values: [T] = []
for parser in parsers {
try values.append(context <- parser)
}
return values
}
}
```
In the example above any error thrown by `try` simply escapes the current
scope and is propagated up. This is exactly what we want and is very
natural in Swift.
Parsers begin parsing at a certain position in the underlying collection.
When a parser fails, it rewinds to the position at which it started and
then throws a `ParseError`.
Some combinators swallow `ParseError`s. For instance, the `optional` combinator
swallows any underlying `ParseError` and returns an optional, e.g.,
```
let s: String? = try context <- optionalS(string("ok"))
```
If the string "ok" is not matched, then `s` will be `nil`. The `|` combinator
swallows the `ParseError` thrown by the left-hand side but not by the right-hand
side:
```
char("a") | char("e")
```
If the character "a" fails to match, then `|` will attempt to match "e", if that fails then
the `ParseError` will be allowed to propagate. Very often it is best to use the `fail` combinator
in this situation to make the error clearer:
```
char("a") | char("e") | fail("Tried and failed to match a or e.")
```
*/
public struct ParseError<Contents: Collection>: ParsingError {
/// An optional, purely informational message.
public let message: String?
/**
The index in the collection at which some parser failed
to match.
*/
public let index: Contents.Index
/// An inner error, if any.
public let inner: Error?
/**
Initializes a `ParseError`.
- parameter index: The index at which some parser failed to match.
- parameter message: An optional, purely informational message.
*/
public init(_ index: Contents.Index, message: String? = nil, inner: Error? = nil) {
self.index = index
self.message = message
self.inner = inner
}
}
public func <?><C: Collection, T>(parser: @escaping Parser<C, T>, error: String) -> Parser<C, T> {
parser | fail(error)
}
| mit |
emersonbroga/LocationSwift | LocationSwift/BackgroundTaskManager.swift | 1 | 3015 | //
// BackgroundTaskManager.swift
// LocationSwift
//
// Created by Emerson Carvalho on 5/21/15.
// Copyright (c) 2015 Emerson Carvalho. All rights reserved.
//
import Foundation
import UIKit
class BackgroundTaskManager : NSObject {
var bgTaskIdList : NSMutableArray?
var masterTaskId : UIBackgroundTaskIdentifier?
override init() {
super.init()
self.bgTaskIdList = NSMutableArray()
self.masterTaskId = UIBackgroundTaskInvalid
}
class func sharedBackgroundTaskManager() -> BackgroundTaskManager? {
struct Static {
static var sharedBGTaskManager : BackgroundTaskManager?
static var onceToken : dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
Static.sharedBGTaskManager = BackgroundTaskManager()
}
return Static.sharedBGTaskManager
}
func beginNewBackgroundTask() -> UIBackgroundTaskIdentifier? {
var application : UIApplication = UIApplication.sharedApplication()
var bgTaskId : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
bgTaskId = application.beginBackgroundTaskWithExpirationHandler({
print("background task \(bgTaskId as Int) expired\n")
})
if self.masterTaskId == UIBackgroundTaskInvalid {
self.masterTaskId = bgTaskId
print("started master task \(self.masterTaskId)\n")
} else {
// add this ID to our list
print("started background task \(bgTaskId as Int)\n")
self.bgTaskIdList!.addObject(bgTaskId)
//self.endBackgr
}
return bgTaskId
}
func endBackgroundTask(){
self.drainBGTaskList(false)
}
func endAllBackgroundTasks() {
self.drainBGTaskList(true)
}
func drainBGTaskList(all:Bool) {
//mark end of each of our background task
var application: UIApplication = UIApplication.sharedApplication()
let endBackgroundTask : Selector = "endBackgroundTask"
var count: Int = self.bgTaskIdList!.count
for (var i = (all==true ? 0:1); i<count; i++) {
var bgTaskId : UIBackgroundTaskIdentifier = self.bgTaskIdList!.objectAtIndex(0) as! Int
print("ending background task with id \(bgTaskId as Int)\n")
application.endBackgroundTask(bgTaskId)
self.bgTaskIdList!.removeObjectAtIndex(0)
}
if self.bgTaskIdList!.count > 0 {
print("kept background task id \(self.bgTaskIdList!.objectAtIndex(0))\n")
}
if all == true {
print("no more background tasks running\n")
application.endBackgroundTask(self.masterTaskId!)
self.masterTaskId = UIBackgroundTaskInvalid
} else {
print("kept master background task id \(self.masterTaskId)\n")
}
}
} | mit |
primetimer/PrimeFactors | PrimeFactors/Classes/PUtil.swift | 1 | 1471 | //
// PUtil.swift
// PFactors
//
// Created by Stephan Jancar on 17.10.17.
//
import Foundation
import BigInt
public extension BigUInt {
func issquare() -> Bool {
let r2 = self.squareRoot()
if r2 * r2 == self { return true }
return false
}
// Cubic Root
func iroot3()->BigUInt {
if self == 0 { return 0 }
if self < 8 { return 1 }
var x0 = self
var x1 = self
repeat {
x1 = self / x0 / x0
x1 = x1 + 2 * x0
x1 = x1 / 3
if (x0 == x1) || (x0 == x1+1) || (x1 == x0 + 1) {
if x1 * x1 * x1 > self {
return x1 - 1
}
return x1
}
x0 = x1
} while true
}
}
//Quadratwurzel und kubische Wurzel mittels Floating Point Arithmetik
public extension UInt64 {
func squareRoot()->UInt64 {
var r2 = UInt64(sqrt(Double(self)+0.5))
while (r2+1) * (r2+1) <= self {
r2 = r2 + 1
}
return r2
}
func issquare() -> Bool {
let r2 = self.squareRoot()
if r2 * r2 == self { return true }
return false
}
// Cubic Root
func iroot3()->UInt64 {
var r3 = UInt64(pow(Double(self)+0.5, 1.0 / 3.0))
while (r3+1) * (r3+1) * (r3+1) <= self {
r3 = r3 + 1
}
return r3
}
func NumBits() -> UInt64 {
var v = self
var c : UInt64 = 0
while v != 0 {
v = v & (v - 1) //Brian Kernighan's method
c = c + 1
}
return c
}
func greatestCommonDivisor(with b: UInt64) -> UInt64 {
var x = self
var y = b
while y > 0 {
let exc = x
x = y
y = exc % y
}
return x
}
}
| mit |
jtbandes/swift-compiler-crashes | fixed/26353-swift-typechecker-getinterfacetypefrominternaltype.swift | 7 | 247 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func A{
struct Q<a:b
protocol A{
typealias e
typealias e:AnyObject
}class b:A
| mit |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/NewCamera/Presenter/NewCameraPresenter.swift | 1 | 6078 | final class NewCameraPresenter:
NewCameraModule
{
// MARK: - Dependencies
private let interactor: NewCameraInteractor
private let router: NewCameraRouter
// MARK: - Config
private let shouldAllowFinishingWithNoPhotos: Bool
// MARK: - Init
init(
interactor: NewCameraInteractor,
router: NewCameraRouter,
shouldAllowFinishingWithNoPhotos: Bool)
{
self.interactor = interactor
self.router = router
self.shouldAllowFinishingWithNoPhotos = shouldAllowFinishingWithNoPhotos
}
// MARK: - Weak properties
weak var view: NewCameraViewInput? {
didSet {
setUpView()
}
}
// MARK: - NewCameraModule
var onFinish: ((NewCameraModule, NewCameraModuleResult) -> ())?
var configureMediaPicker: ((MediaPickerModule) -> ())?
func focusOnModule() {
router.focusOnCurrentModule()
}
// MARK: - Private
private func setUpView() {
view?.setFlashButtonVisible(interactor.isFlashAvailable)
view?.setFlashButtonOn(interactor.isFlashEnabled)
view?.setDoneButtonTitle(localized("Done"))
view?.setPlaceholderText(localized("Select at least one photo"))
view?.setHintText(localized("Place the object inside the frame and take a photo"))
view?.setAccessDeniedTitle(localized("To take photo"))
view?.setAccessDeniedMessage(localized("Allow %@ to use your camera", appName()))
view?.setAccessDeniedButtonTitle(localized("Allow access to camera"))
view?.onCloseButtonTap = { [weak self] in
guard let strongSelf = self else { return }
self?.onFinish?(strongSelf, .cancelled)
}
view?.onDoneButtonTap = { [weak self] in
guard let strongSelf = self else { return }
self?.onFinish?(strongSelf, .finished)
}
view?.onLastPhotoThumbnailTap = { [weak self] in
guard
let strongSelf = self,
let selectedItems = self?.interactor.selectedImagesStorage.images
else { return }
let data = strongSelf.interactor.mediaPickerData
.bySettingMediaPickerItems(selectedItems)
.bySelectingLastItem()
self?.router.showMediaPicker(
data: data,
overridenTheme: nil,
configure: { module in
self?.configureMediaPicker?(module)
}
)
}
view?.onToggleCameraButtonTap = { [weak self] in
self?.interactor.toggleCamera { _ in }
}
view?.onFlashToggle = { [weak self] isFlashEnabled in
guard let strongSelf = self else { return }
if !strongSelf.interactor.setFlashEnabled(isFlashEnabled) {
strongSelf.view?.setFlashButtonOn(!isFlashEnabled)
}
}
view?.onCaptureButtonTap = { [weak self] in
self?.view?.setCaptureButtonState(.nonInteractive)
self?.view?.animateFlash()
self?.interactor.takePhoto { photo in
guard let photo = photo else { return }
self?.interactor.selectedImagesStorage.addItem(MediaPickerItem(photo))
self?.adjustCaptureButtonAvailability()
self?.view?.animateCapturedPhoto(photo.image) { finalizeAnimation in
self?.adjustSelectedPhotosBar {
finalizeAnimation()
}
}
}
}
view?.onAccessDeniedButtonTap = {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
}
bindAdjustmentsToViewControllerLifecycle()
interactor.observeLatestLibraryPhoto { [weak self] imageSource in
self?.view?.setLatestPhotoLibraryItemImage(imageSource)
}
interactor.observeCameraAuthorizationStatus { [weak self] accessGranted in
self?.view?.setAccessDeniedViewVisible(!accessGranted)
}
}
private func bindAdjustmentsToViewControllerLifecycle() {
var didDisappear = false
var viewDidLayoutSubviewsBefore = false
view?.onViewWillAppear = { _ in
guard didDisappear else { return }
DispatchQueue.main.async {
self.adjustSelectedPhotosBar {}
self.adjustCaptureButtonAvailability()
}
}
view?.onViewDidDisappear = { _ in
didDisappear = true
}
view?.onViewDidLayoutSubviews = {
guard !viewDidLayoutSubviewsBefore else { return }
DispatchQueue.main.async {
self.adjustSelectedPhotosBar {}
}
viewDidLayoutSubviewsBefore = true
}
}
private func adjustSelectedPhotosBar(completion: @escaping () -> ()) {
let images = interactor.selectedImagesStorage.images
let state: SelectedPhotosBarState = images.isEmpty
? (shouldAllowFinishingWithNoPhotos ? .placeholder : .hidden)
: .visible(SelectedPhotosBarData(
lastPhoto: images.last?.image,
penultimatePhoto: images.count > 1 ? images[images.count - 2].image : nil,
countString: "\(images.count) фото"
))
view?.setSelectedPhotosBarState(state, completion: completion)
}
private func adjustCaptureButtonAvailability() {
view?.setCaptureButtonState(interactor.canAddItems() ? .enabled : .disabled)
}
private func appName() -> String {
return Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String ?? ""
}
}
| mit |
khizkhiz/swift | test/SILGen/decls.swift | 2 | 5762 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen %s | FileCheck %s
// CHECK-LABEL: sil hidden @_TF5decls11void_returnFT_T_
// CHECK: = tuple
// CHECK: return
func void_return() {
}
// CHECK-LABEL: sil hidden @_TF5decls14typealias_declFT_T_
func typealias_decl() {
typealias a = Int
}
// CHECK-LABEL: sil hidden @_TF5decls15simple_patternsFT_T_
func simple_patterns() {
_ = 4
var _ : Int
}
// CHECK-LABEL: sil hidden @_TF5decls13named_patternFT_Si
func named_pattern() -> Int {
var local_var : Int = 4
var defaulted_var : Int // Defaults to zero initialization
return local_var + defaulted_var
}
func MRV() -> (Int, Float, (), Double) {}
// CHECK-LABEL: sil hidden @_TF5decls14tuple_patternsFT_T_
func tuple_patterns() {
var (a, b) : (Int, Float)
// CHECK: [[AADDR1:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBA:%.*]] = project_box [[AADDR1]]
// CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[PBA]]
// CHECK: [[BADDR1:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBB:%.*]] = project_box [[BADDR1]]
// CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[PBB]]
var (c, d) = (a, b)
// CHECK: [[CADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBC:%.*]] = project_box [[CADDR]]
// CHECK: [[DADDR:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBD:%.*]] = project_box [[DADDR]]
// CHECK: copy_addr [[AADDR]] to [initialization] [[PBC]]
// CHECK: copy_addr [[BADDR]] to [initialization] [[PBD]]
// CHECK: [[EADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBE:%.*]] = project_box [[EADDR]]
// CHECK: [[FADDR:%[0-9]+]] = alloc_box $Float
// CHECK: [[PBF:%.*]] = project_box [[FADDR]]
// CHECK: [[GADDR:%[0-9]+]] = alloc_box $()
// CHECK: [[HADDR:%[0-9]+]] = alloc_box $Double
// CHECK: [[PBH:%.*]] = project_box [[HADDR]]
// CHECK: [[EFGH:%[0-9]+]] = apply
// CHECK: [[E:%[0-9]+]] = tuple_extract {{.*}}, 0
// CHECK: [[F:%[0-9]+]] = tuple_extract {{.*}}, 1
// CHECK: [[H:%[0-9]+]] = tuple_extract {{.*}}, 2
// CHECK: store [[E]] to [[PBE]]
// CHECK: store [[F]] to [[PBF]]
// CHECK: store [[H]] to [[PBH]]
var (e,f,g,h) : (Int, Float, (), Double) = MRV()
// CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBI:%.*]] = project_box [[IADDR]]
// CHECK-NOT: alloc_box $Float
// CHECK: copy_addr [[AADDR]] to [initialization] [[PBI]]
// CHECK: [[B:%[0-9]+]] = load [[BADDR]]
// CHECK-NOT: store [[B]]
var (i,_) = (a, b)
// CHECK: [[JADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBJ:%.*]] = project_box [[JADDR]]
// CHECK-NOT: alloc_box $Float
// CHECK: [[KADDR:%[0-9]+]] = alloc_box $()
// CHECK-NOT: alloc_box $Double
// CHECK: [[J_K_:%[0-9]+]] = apply
// CHECK: [[J:%[0-9]+]] = tuple_extract {{.*}}, 0
// CHECK: [[K:%[0-9]+]] = tuple_extract {{.*}}, 2
// CHECK: store [[J]] to [[PBJ]]
var (j,_,k,_) : (Int, Float, (), Double) = MRV()
}
// CHECK-LABEL: sil hidden @_TF5decls16simple_arguments
// CHECK: bb0(%0 : $Int, %1 : $Int):
// CHECK: [[X:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: store %0 to [[PBX]]
// CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBY:%[0-9]+]] = project_box [[Y]]
// CHECK-NEXT: store %1 to [[PBY]]
func simple_arguments(x: Int, y: Int) -> Int {
var x = x
var y = y
return x+y
}
// CHECK-LABEL: sil hidden @_TF5decls14tuple_argument
// CHECK: bb0(%0 : $Int, %1 : $Float):
// CHECK: [[UNIT:%[0-9]+]] = tuple ()
// CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $())
func tuple_argument(x: (Int, Float, ())) {
}
// CHECK-LABEL: sil hidden @_TF5decls14inout_argument
// CHECK: bb0(%0 : $*Int, %1 : $Int):
// CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBX:%.*]] = project_box [[X_LOCAL]]
// CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBY:%[0-9]+]] = project_box [[YADDR]]
// CHECK: copy_addr [[PBY]] to [[PBX]]
func inout_argument(x: inout Int, y: Int) {
var y = y
x = y
}
var global = 42
// CHECK-LABEL: sil hidden @_TF5decls16load_from_global
func load_from_global() -> Int {
return global
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: [[VALUE:%[0-9]+]] = load [[ADDR]]
// CHECK: return [[VALUE]]
}
// CHECK-LABEL: sil hidden @_TF5decls15store_to_global
func store_to_global(x: Int) {
var x = x
global = x
// CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[PBX:%.*]] = project_box [[XADDR]]
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: copy_addr [[PBX]] to [[ADDR]]
// CHECK: return
}
struct S {
var x:Int
// CHECK-LABEL: sil hidden @_TFV5decls1SCf
init() {
x = 219
}
init(a:Int, b:Int) {
x = a + b
}
}
// CHECK-LABEL: StructWithStaticVar.init
// rdar://15821990 - Don't emit default value for static var in instance init()
struct StructWithStaticVar {
static var a : String = ""
var b : String = ""
init() {
}
}
// <rdar://problem/17405715> lazy property crashes silgen of implicit memberwise initializer
// CHECK-LABEL: // decls.StructWithLazyField.init
// CHECK-NEXT: sil hidden @_TFV5decls19StructWithLazyFieldC{{.*}} : $@convention(thin) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField {
struct StructWithLazyField {
lazy var once : Int = 42
let someProp = "Some value"
}
// <rdar://problem/21057425> Crash while compiling attached test-app.
// CHECK-LABEL: // decls.test21057425
func test21057425() {
var x = 0, y: Int = 0
}
func useImplicitDecls() {
_ = StructWithLazyField(once: 55)
}
| apache-2.0 |
53ningen/RxHttp | RxHttp/DefaultRxHttpClient.swift | 1 | 4627 | import RxSwift
import RxCocoa
import Foundation
public class DefaultRxHttpClient: RxHttpClient {
private let defaultTimeoutSec: NSTimeInterval
public init(defaultTimeoutSec: NSTimeInterval) {
self.defaultTimeoutSec = defaultTimeoutSec
}
public func get(url: NSURL) -> Observable<(NSData, NSHTTPURLResponse)> {
return get(url, parameters: nil, headers: nil, timeoutSec: nil)
}
public func get(url: NSURL, parameters: [RequestParameter]) -> Observable<(NSData, NSHTTPURLResponse)> {
return get(url, parameters: parameters, headers: nil, timeoutSec: nil)
}
public func get(url: NSURL, parameters: [RequestParameter], headers: [RequestHeader]) -> Observable<(NSData, NSHTTPURLResponse)> {
return get(url, parameters: parameters, headers: headers, timeoutSec: nil)
}
public func get(url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval?) -> Observable<(NSData, NSHTTPURLResponse)> {
return action(.GET, url: url, parameters: parameters, headers: headers, timeoutSec: timeoutSec)
}
public func post(url: NSURL) -> Observable<(NSData, NSHTTPURLResponse)> {
return post(url, parameters: nil, headers: nil, timeoutSec: nil)
}
public func post(url: NSURL, parameters: [RequestParameter]) -> Observable<(NSData, NSHTTPURLResponse)> {
return post(url, parameters: parameters, headers: nil, timeoutSec: nil)
}
public func post(url: NSURL, parameters: [RequestParameter], headers: [RequestHeader]) -> Observable<(NSData, NSHTTPURLResponse)> {
return post(url, parameters: parameters, headers: headers, timeoutSec: nil)
}
public func post(url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval?) -> Observable<(NSData, NSHTTPURLResponse)> {
return action(.POST, url: url, parameters: parameters, headers: headers, timeoutSec: timeoutSec)
}
public func put(url: NSURL) -> Observable<(NSData, NSHTTPURLResponse)> {
return put(url, parameters: nil, headers: nil, timeoutSec: nil)
}
public func put(url: NSURL, parameters: [RequestParameter]) -> Observable<(NSData, NSHTTPURLResponse)> {
return put(url, parameters: parameters, headers: nil, timeoutSec: nil)
}
public func put(url: NSURL, parameters: [RequestParameter], headers: [RequestHeader]) -> Observable<(NSData, NSHTTPURLResponse)> {
return put(url, parameters: parameters, headers: headers, timeoutSec: nil)
}
public func put(url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval?) -> Observable<(NSData, NSHTTPURLResponse)> {
return action(.PUT, url: url, parameters: parameters, headers: headers, timeoutSec: timeoutSec)
}
public func delete(url: NSURL) -> Observable<(NSData, NSHTTPURLResponse)> {
return delete(url, parameters: nil, headers: nil, timeoutSec: nil)
}
public func delete(url: NSURL, parameters: [RequestParameter]) -> Observable<(NSData, NSHTTPURLResponse)> {
return delete(url, parameters: parameters, headers: nil, timeoutSec: nil)
}
public func delete(url: NSURL, parameters: [RequestParameter], headers: [RequestHeader]) -> Observable<(NSData, NSHTTPURLResponse)> {
return delete(url, parameters: parameters, headers: headers, timeoutSec: nil)
}
public func delete(url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval? = nil) -> Observable<(NSData, NSHTTPURLResponse)> {
return action(.DELETE, url: url, parameters: parameters, headers: headers, timeoutSec: timeoutSec)
}
public func execute(method: HttpMethod, url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval?) -> Observable<(NSData, NSHTTPURLResponse)> {
return action(method, url: url, parameters: parameters, headers: headers, timeoutSec: timeoutSec)
}
private func action(method: HttpMethod, url: NSURL, parameters: [RequestParameter]?, headers: [RequestHeader]?, timeoutSec: NSTimeInterval?) -> Observable<(NSData, NSHTTPURLResponse)> {
if let request = URLUtils.createRequest(method, url: url, params: parameters, headers: headers, timeoutSec: timeoutSec ?? defaultTimeoutSec) {
return NSURLSession.sharedSession().rx_response(request)
} else {
return Observable.error(NSError(domain: "RxHttp", code: 1, userInfo: nil))
}
}
}
| mit |
sol/aeson | tests/JSONTestSuite/parsers/test_Freddy_20161018/test_Freddy/JSONDecodable.swift | 10 | 7789 | //
// JSONDecodable.swift
// Freddy
//
// Created by Matthew D. Mathias on 3/24/15.
// Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//
/// A protocol to provide functionality for creating a model object with a `JSON`
/// value.
public protocol JSONDecodable {
/// Creates an instance of the model with a `JSON` instance.
/// - parameter json: An instance of a `JSON` value from which to
/// construct an instance of the implementing type.
/// - throws: Any `JSON.Error` for errors derived from inspecting the
/// `JSON` value, or any other error involved in decoding.
init(json: JSON) throws
}
extension Double: JSONDecodable {
/// An initializer to create an instance of `Double` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Double` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
if case let .double(double) = json {
self = double
} else if case let .int(int) = json {
self = Double(int)
} else if case let .string(string) = json, let s = Double(string) {
self = s
} else {
throw JSON.Error.valueNotConvertible(value: json, to: Double.self)
}
}
}
extension Int: JSONDecodable {
/// An initializer to create an instance of `Int` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Int` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
if case let .double(double) = json, double <= Double(Int.max) {
self = Int(double)
} else if case let .int(int) = json {
self = int
} else if case let .string(string) = json, let int = Int(string) {
self = int
} else if case let .string(string) = json,
let double = Double(string),
let decimalSeparator = string.characters.index(of: "."),
let int = Int(String(string.characters.prefix(upTo: decimalSeparator))),
double == Double(int) {
self = int
} else {
throw JSON.Error.valueNotConvertible(value: json, to: Int.self)
}
}
}
extension String: JSONDecodable {
/// An initializer to create an instance of `String` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `String` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
switch json {
case let .string(string):
self = string
case let .int(int):
self = String(int)
case let .bool(bool):
self = String(bool)
case let .double(double):
self = String(double)
default:
throw JSON.Error.valueNotConvertible(value: json, to: String.self)
}
}
}
extension Bool: JSONDecodable {
/// An initializer to create an instance of `Bool` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Bool` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
guard case let .bool(bool) = json else {
throw JSON.Error.valueNotConvertible(value: json, to: Bool.self)
}
self = bool
}
}
extension RawRepresentable where RawValue: JSONDecodable {
/// An initializer to create an instance of `RawRepresentable` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `RawRepresentable` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
let raw = try json.decode(type: RawValue.self)
guard let value = Self(rawValue: raw) else {
throw JSON.Error.valueNotConvertible(value: json, to: Self.self)
}
self = value
}
}
internal extension JSON {
/// Retrieves a `[JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Array`.
/// - returns: An `Array` of `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getArray(from json: JSON) throws -> [JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Array.
guard case let .array(array) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Array<JSON>)
}
return array
}
/// Retrieves a `[String: JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Dictionary`.
/// - returns: An `Dictionary` of `String` mapping to `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getDictionary(from json: JSON) throws -> [String: JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, JSON>)
}
return dictionary
}
/// Attempts to decode many values from a descendant JSON array at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Array` of some type conforming to `JSONDecodable`.
/// - returns: An `Array` of `Decoded` elements.
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`, as
/// well as any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedArray<Decoded: JSONDecodable>(from json: JSON) throws -> [Decoded] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
// This implementation also doesn't do the `type = Type.self` trick.
return try getArray(from: json).map(Decoded.init)
}
/// Attempts to decode many values from a descendant JSON object at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Dictionary` of some type conforming to `JSONDecodable`.
/// - returns: A `Dictionary` of string keys and `Decoded` values.
/// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)` or
/// any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedDictionary<Decoded: JSONDecodable>(from json: JSON) throws -> [Swift.String: Decoded] {
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, Decoded>)
}
var decodedDictionary = Swift.Dictionary<String, Decoded>(minimumCapacity: dictionary.count)
for (key, value) in dictionary {
decodedDictionary[key] = try Decoded(json: value)
}
return decodedDictionary
}
}
| bsd-3-clause |
maxsokolov/TableKit | Demo/Classes/Presentation/Views/NibTableViewCell.swift | 3 | 300 | import UIKit
import TableKit
class NibTableViewCell: UITableViewCell, ConfigurableCell {
@IBOutlet weak var titleLabel: UILabel!
static var defaultHeight: CGFloat? {
return 100
}
func configure(with number: Int) {
titleLabel.text = "\(number)"
}
}
| mit |
anirudh24seven/wikipedia-ios | Wikipedia/Code/WMFTableOfContentsPresentationController.swift | 1 | 10452 | import UIKit
import Masonry
// MARK: - Delegate
@objc public protocol WMFTableOfContentsPresentationControllerTapDelegate {
func tableOfContentsPresentationControllerDidTapBackground(controller: WMFTableOfContentsPresentationController)
}
public class WMFTableOfContentsPresentationController: UIPresentationController {
var displaySide = WMFTableOfContentsDisplaySideLeft
var displayMode = WMFTableOfContentsDisplayModeModal
// MARK: - init
public required init(presentedViewController: UIViewController, presentingViewController: UIViewController?, tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate) {
self.tapDelegate = tapDelegate
super.init(presentedViewController: presentedViewController, presentingViewController: presentedViewController)
}
weak public var tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate?
public var minimumVisibleBackgroundWidth: CGFloat = 60.0
public var maximumTableOfContentsWidth: CGFloat = 300.0
public var closeButtonLeadingPadding: CGFloat = 10.0
public var closeButtonTopPadding: CGFloat = 0.0
public var statusBarEstimatedHeight: CGFloat = 20.0
// MARK: - Views
lazy var statusBarBackground: UIView = {
let view = UIView(frame: CGRect(x: CGRectGetMinX(self.containerView!.bounds), y: CGRectGetMinY(self.containerView!.bounds), width: CGRectGetWidth(self.containerView!.bounds), height: self.statusBarEstimatedHeight))
view.autoresizingMask = .FlexibleWidth
let statusBarBackgroundBottomBorder = UIView(frame: CGRectMake(CGRectGetMinX(view.bounds), CGRectGetMaxY(view.bounds), CGRectGetWidth(view.bounds), 0.5))
statusBarBackgroundBottomBorder.autoresizingMask = .FlexibleWidth
view.backgroundColor = UIColor.whiteColor()
statusBarBackgroundBottomBorder.backgroundColor = UIColor.lightGrayColor()
view.addSubview(statusBarBackgroundBottomBorder)
return view
}()
lazy var closeButton:UIButton = {
let button = UIButton(frame: CGRectZero)
button.setImage(UIImage(named: "close"), forState: UIControlState.Normal)
button.tintColor = UIColor.blackColor()
button.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)), forControlEvents: .TouchUpInside)
button.accessibilityHint = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-hint")
button.accessibilityLabel = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-label")
return button
}()
lazy var backgroundView :UIVisualEffectView = {
let view = UIVisualEffectView(frame: CGRectZero)
view.autoresizingMask = .FlexibleWidth
view.effect = UIBlurEffect(style: .Light)
view.alpha = 0.0
let tap = UITapGestureRecognizer.init()
tap.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)))
view.addGestureRecognizer(tap)
view.addSubview(self.statusBarBackground)
view.addSubview(self.closeButton)
return view
}()
func updateButtonConstraints() {
self.closeButton.mas_remakeConstraints({ make in
make.width.equalTo()(44)
make.height.equalTo()(44)
switch self.displaySide {
case WMFTableOfContentsDisplaySideLeft:
make.trailing.equalTo()(self.closeButton.superview!.mas_trailing).offset()(0 - self.closeButtonLeadingPadding)
if(self.traitCollection.verticalSizeClass == .Compact){
make.top.equalTo()(self.closeButtonTopPadding)
}else{
make.top.equalTo()(self.closeButtonTopPadding + self.statusBarEstimatedHeight)
}
break
case WMFTableOfContentsDisplaySideRight:
make.leading.equalTo()(self.closeButton.superview!.mas_leading).offset()(self.closeButtonLeadingPadding)
if(self.traitCollection.verticalSizeClass == .Compact){
make.top.equalTo()(self.closeButtonTopPadding)
}else{
make.top.equalTo()(self.closeButtonTopPadding + self.statusBarEstimatedHeight)
}
break
case WMFTableOfContentsDisplaySideCenter:
fallthrough
default:
make.leading.equalTo()(self.closeButton.superview!.mas_leading).offset()(self.closeButtonLeadingPadding)
make.bottom.equalTo()(self.closeButton.superview!.mas_bottom).offset()(self.closeButtonTopPadding)
}
return ()
})
}
func didTap(tap: UITapGestureRecognizer) {
self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self);
}
// MARK: - Accessibility
func togglePresentingViewControllerAccessibility(accessible: Bool) {
self.presentingViewController.view.accessibilityElementsHidden = !accessible
}
// MARK: - UIPresentationController
override public func presentationTransitionWillBegin() {
// Add the dimming view and the presented view to the heirarchy
self.backgroundView.frame = self.containerView!.bounds
self.containerView!.addSubview(self.backgroundView)
if(self.traitCollection.verticalSizeClass == .Compact){
self.statusBarBackground.hidden = true
}
updateButtonConstraints()
self.containerView!.addSubview(self.presentedView()!)
// Hide the presenting view controller for accessibility
self.togglePresentingViewControllerAccessibility(false)
switch displaySide {
case WMFTableOfContentsDisplaySideCenter:
self.presentedView()?.layer.cornerRadius = 10
self.presentedView()?.clipsToBounds = true
self.presentedView()?.layer.borderColor = UIColor.wmf_lightGrayColor().CGColor
self.presentedView()?.layer.borderWidth = 1.0
self.closeButton.setImage(UIImage(named: "toc-close-blue"), forState: .Normal)
self.statusBarBackground.hidden = true
break
default:
//Add shadow to the presented view
self.presentedView()?.layer.shadowOpacity = 0.5
self.presentedView()?.layer.shadowOffset = CGSize(width: 3, height: 5)
self.presentedView()?.clipsToBounds = false
self.closeButton.setImage(UIImage(named: "close"), forState: .Normal)
self.statusBarBackground.hidden = false
}
// Fade in the dimming view alongside the transition
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 1.0
}, completion:nil)
}
}
override public func presentationTransitionDidEnd(completed: Bool) {
if !completed {
self.backgroundView.removeFromSuperview()
}
}
override public func dismissalTransitionWillBegin() {
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 0.0
}, completion:nil)
}
}
override public func dismissalTransitionDidEnd(completed: Bool) {
if completed {
self.backgroundView.removeFromSuperview()
self.togglePresentingViewControllerAccessibility(true)
self.presentedView()?.layer.cornerRadius = 0
self.presentedView()?.layer.borderWidth = 0
self.presentedView()?.layer.shadowOpacity = 0
self.presentedView()?.clipsToBounds = true
}
}
override public func frameOfPresentedViewInContainerView() -> CGRect {
var frame = self.containerView!.bounds;
var bgWidth = self.minimumVisibleBackgroundWidth
var tocWidth = frame.size.width - bgWidth
if(tocWidth > self.maximumTableOfContentsWidth){
tocWidth = self.maximumTableOfContentsWidth
bgWidth = frame.size.width - tocWidth
}
frame.origin.y = UIApplication.sharedApplication().statusBarFrame.size.height + 0.5;
switch displaySide {
case WMFTableOfContentsDisplaySideCenter:
frame.origin.y += 10
frame.origin.x += 0.5*bgWidth
frame.size.height -= 80
break
case WMFTableOfContentsDisplaySideRight:
frame.origin.x += bgWidth
break
default:
break
}
frame.size.width = tocWidth
return frame
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator)
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.frame = self.containerView!.bounds
let frame = self.frameOfPresentedViewInContainerView()
self.presentedView()!.frame = frame
}, completion:nil)
}
override public func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
if newCollection.verticalSizeClass == .Compact
{
self.statusBarBackground.hidden = true;
}
if newCollection.verticalSizeClass == .Regular
{
self.statusBarBackground.hidden = false;
}
coordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.updateButtonConstraints()
}, completion:nil)
}
}
| mit |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift | 9 | 5407 | //
// AnimatedImage.swift
// Kingfisher
//
// Created by onevcat on 2018/09/26.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ImageIO
/// Represents a set of image creating options used in Kingfisher.
public struct ImageCreatingOptions {
/// The target scale of image needs to be created.
public let scale: CGFloat
/// The expected animation duration if an animated image being created.
public let duration: TimeInterval
/// For an animated image, whether or not all frames should be loaded before displaying.
public let preloadAll: Bool
/// For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
public let onlyFirstFrame: Bool
/// Creates an `ImageCreatingOptions` object.
///
/// - Parameters:
/// - scale: The target scale of image needs to be created. Default is `1.0`.
/// - duration: The expected animation duration if an animated image being created.
/// A value less or equal to `0.0` means the animated image duration will
/// be determined by the frame data. Default is `0.0`.
/// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
/// Default is `false`.
/// - onlyFirstFrame: For an animated image, whether or not only the first image should be
/// loaded as a static image. It is useful for preview purpose of an animated image.
/// Default is `false`.
public init(
scale: CGFloat = 1.0,
duration: TimeInterval = 0.0,
preloadAll: Bool = false,
onlyFirstFrame: Bool = false)
{
self.scale = scale
self.duration = duration
self.preloadAll = preloadAll
self.onlyFirstFrame = onlyFirstFrame
}
}
// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
// hold the images for later use.
class GIFAnimatedImage {
let images: [Image]
let duration: TimeInterval
init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else {
return nil
}
if frameCount == 1 {
gifDuration = .infinity
} else {
// Get current animated GIF frame duration
gifDuration += GIFAnimatedImage.getFrameDuration(from: imageSource, at: i)
}
images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
if options.onlyFirstFrame { break }
}
self.images = images
self.duration = gifDuration
}
// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
let defaultFrameDuration = 0.1
guard let gifInfo = gifInfo else { return defaultFrameDuration }
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else { return defaultFrameDuration }
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
}
// Calculates frame duration at a specific index for a gif from an `imageSource`.
static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
as? [String: Any] else { return 0.0 }
let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
return getFrameDuration(from: gifInfo)
}
}
| mit |
overtake/TelegramSwift | Telegram-Mac/GroupCallSettingsController.swift | 1 | 47216 | //
// GroupCallSettingsController.swift
// Telegram
//
// Created by Mikhail Filimonov on 25/11/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import TelegramCore
import InAppSettings
import Postbox
import HotKey
import ColorPalette
private final class Arguments {
let sharedContext: SharedAccountContext
let toggleInputAudioDevice:(String?)->Void
let toggleOutputAudioDevice:(String?)->Void
let toggleInputVideoDevice:(String?)->Void
let finishCall:()->Void
let updateDefaultParticipantsAreMuted: (Bool)->Void
let updateSettings: (@escaping(VoiceCallSettings)->VoiceCallSettings)->Void
let checkPermission:()->Void
let showTooltip:(String)->Void
let switchAccount:(PeerId)->Void
let startRecording:()->Void
let stopRecording:()->Void
let resetLink:()->Void
let setNoiseSuppression:(Bool)->Void
let reduceMotions:(Bool)->Void
let selectVideoRecordOrientation:(GroupCallSettingsState.VideoOrientation)->Void
let toggleRecordVideo: ()->Void
let copyToClipboard:(String)->Void
let toggleHideKey:()->Void
let revokeStreamKey: ()->Void
init(sharedContext: SharedAccountContext,
toggleInputAudioDevice: @escaping(String?)->Void,
toggleOutputAudioDevice:@escaping(String?)->Void,
toggleInputVideoDevice:@escaping(String?)->Void,
finishCall:@escaping()->Void,
updateDefaultParticipantsAreMuted: @escaping(Bool)->Void,
updateSettings: @escaping(@escaping(VoiceCallSettings)->VoiceCallSettings)->Void,
checkPermission:@escaping()->Void,
showTooltip: @escaping(String)->Void,
switchAccount: @escaping(PeerId)->Void,
startRecording: @escaping()->Void,
stopRecording: @escaping()->Void,
resetLink: @escaping()->Void,
setNoiseSuppression:@escaping(Bool)->Void,
reduceMotions:@escaping(Bool)->Void,
selectVideoRecordOrientation:@escaping(GroupCallSettingsState.VideoOrientation)->Void,
toggleRecordVideo: @escaping()->Void,
copyToClipboard:@escaping(String)->Void,
toggleHideKey:@escaping()->Void,
revokeStreamKey: @escaping()->Void) {
self.sharedContext = sharedContext
self.toggleInputAudioDevice = toggleInputAudioDevice
self.toggleOutputAudioDevice = toggleOutputAudioDevice
self.toggleInputVideoDevice = toggleInputVideoDevice
self.finishCall = finishCall
self.updateDefaultParticipantsAreMuted = updateDefaultParticipantsAreMuted
self.updateSettings = updateSettings
self.checkPermission = checkPermission
self.showTooltip = showTooltip
self.switchAccount = switchAccount
self.startRecording = startRecording
self.stopRecording = stopRecording
self.resetLink = resetLink
self.setNoiseSuppression = setNoiseSuppression
self.reduceMotions = reduceMotions
self.selectVideoRecordOrientation = selectVideoRecordOrientation
self.toggleRecordVideo = toggleRecordVideo
self.copyToClipboard = copyToClipboard
self.toggleHideKey = toggleHideKey
self.revokeStreamKey = revokeStreamKey
}
}
final class GroupCallSettingsView : View {
fileprivate let tableView:TableView = TableView()
private let titleContainer = View()
fileprivate let backButton: ImageButton = ImageButton()
private let title: TextView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(tableView)
addSubview(titleContainer)
titleContainer.addSubview(backButton)
titleContainer.addSubview(title)
let backColor = NSColor(srgbRed: 175, green: 170, blue: 172, alpha: 1.0)
title.userInteractionEnabled = false
title.isSelectable = false
let icon = #imageLiteral(resourceName: "Icon_NavigationBack").precomposed(backColor)
let activeIcon = #imageLiteral(resourceName: "Icon_NavigationBack").precomposed(backColor.withAlphaComponent(0.7))
backButton.set(image: icon, for: .Normal)
backButton.set(image: activeIcon, for: .Highlight)
_ = backButton.sizeToFit(.zero, NSMakeSize(24, 24), thatFit: true)
let layout = TextViewLayout.init(.initialize(string: strings().voiceChatSettingsTitle, color: GroupCallTheme.customTheme.textColor, font: .medium(.header)))
layout.measure(width: frame.width - 200)
title.update(layout)
tableView.getBackgroundColor = {
GroupCallTheme.windowBackground.withAlphaComponent(1)
}
updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
// super.updateLocalizationAndTheme(theme: theme)
backgroundColor = GroupCallTheme.windowBackground
titleContainer.backgroundColor = GroupCallTheme.windowBackground
title.backgroundColor = GroupCallTheme.windowBackground
}
override func layout() {
super.layout()
titleContainer.frame = NSMakeRect(0, 0, frame.width, 54)
tableView.frame = NSMakeRect(0, titleContainer.frame.maxY, frame.width, frame.height - titleContainer.frame.height)
backButton.centerY(x: 90)
let f = titleContainer.focus(title.frame.size)
title.setFrameOrigin(NSMakePoint(max(126, f.minX), f.minY))
}
}
struct GroupCallSettingsState : Equatable {
enum VideoOrientation : Equatable {
case landscape
case portrait
var rawValue: Bool {
switch self {
case .portrait:
return true
case .landscape:
return false
}
}
}
var hasPermission: Bool?
var title: String?
var displayAsList: [FoundPeer]?
var recordName: String?
var recordVideo: Bool
var videoOrientation: VideoOrientation
var hideKey: Bool = true
var credentials: GroupCallStreamCredentials?
}
private let _id_leave_chat = InputDataIdentifier.init("_id_leave_chat")
private let _id_reset_link = InputDataIdentifier.init("_id_reset_link")
private let _id_input_audio = InputDataIdentifier("_id_input_audio")
private let _id_output_audio = InputDataIdentifier("_id_output_audio")
private let _id_micro = InputDataIdentifier("_id_micro")
private let _id_speak_admin_only = InputDataIdentifier("_id_speak_admin_only")
private let _id_speak_all_members = InputDataIdentifier("_id_speak_all_members")
private let _id_input_mode_always = InputDataIdentifier("_id_input_mode_always")
private let _id_input_mode_ptt = InputDataIdentifier("_id_input_mode_ptt")
private let _id_ptt = InputDataIdentifier("_id_ptt")
private let _id_input_mode_ptt_se = InputDataIdentifier("_id_input_mode_ptt_se")
private let _id_input_mode_toggle = InputDataIdentifier("_id_input_mode_toggle")
private let _id_noise_suppression = InputDataIdentifier("_id_noise_suppression")
private let _id_server_url = InputDataIdentifier("_id_server_url")
private let _id_stream_key = InputDataIdentifier("_id_stream_key")
private let _id_revoke_stream_key = InputDataIdentifier("_id_revoke_stream_key")
private let _id_input_chat_title = InputDataIdentifier("_id_input_chat_title")
private let _id_input_record_title = InputDataIdentifier("_id_input_record_title")
private let _id_listening_link = InputDataIdentifier("_id_listening_link")
private let _id_speaking_link = InputDataIdentifier("_id_speaking_link")
private let _id_reduce_motion = InputDataIdentifier("_id_reduce_motion")
private let _id_record_video_toggle = InputDataIdentifier("_id_record_video_toggle")
private func _id_peer(_ id:PeerId) -> InputDataIdentifier {
return InputDataIdentifier("_id_peer_\(id.toInt64())")
}
private func groupCallSettingsEntries(callState: GroupCallUIState, devices: IODevices, uiState: GroupCallSettingsState, settings: VoiceCallSettings, context: AccountContext, peer: Peer, accountPeer: Peer, joinAsPeerId: PeerId, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
let theme = GroupCallTheme.customTheme
var sectionId: Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .customModern(10)))
sectionId += 1
let state = callState.state
if state.canManageCall {
// entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
// index += 1
entries.append(.input(sectionId: sectionId, index: index, value: .string(uiState.title), error: nil, identifier: _id_input_chat_title, mode: .plain, data: .init(viewType: .singleItem, pasteFilter: nil, customTheme: theme), placeholder: nil, inputPlaceholder: strings().voiceChatSettingsTitlePlaceholder, filter: { $0 }, limit: 40))
index += 1
}
if let list = uiState.displayAsList {
if !list.isEmpty {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
struct Tuple : Equatable {
let peer: FoundPeer
let viewType: GeneralViewType
let selected: Bool
let status: String?
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsDisplayAsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let tuple = Tuple(peer: FoundPeer(peer: accountPeer, subscribers: nil), viewType: uiState.displayAsList == nil || uiState.displayAsList?.isEmpty == false ? .firstItem : .singleItem, selected: accountPeer.id == joinAsPeerId, status: strings().voiceChatSettingsDisplayAsPersonalAccount)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("self"), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: tuple.peer.peer, account: context.account, context: context, stableId: stableId, height: 50, photoSize: NSMakeSize(36, 36), titleStyle: ControlStyle(font: .medium(.title), foregroundColor: theme.textColor, highlightColor: .white), statusStyle: ControlStyle(foregroundColor: theme.grayTextColor), status: tuple.status, inset: NSEdgeInsets(left: 30, right: 30), interactionType: .plain, generalType: .selectable(tuple.selected), viewType: tuple.viewType, action: {
arguments.switchAccount(tuple.peer.peer.id)
}, customTheme: theme)
}))
index += 1
for peer in list {
var status: String?
if let subscribers = peer.subscribers {
if peer.peer.isChannel {
status = strings().voiceChatJoinAsChannelCountable(Int(subscribers))
} else if peer.peer.isSupergroup || peer.peer.isGroup {
status = strings().voiceChatJoinAsGroupCountable(Int(subscribers))
}
}
var viewType = bestGeneralViewType(list, for: peer)
if list.first == peer {
if list.count == 1 {
viewType = .lastItem
} else {
viewType = .innerItem
}
}
let tuple = Tuple(peer: peer, viewType: viewType, selected: peer.peer.id == joinAsPeerId, status: status)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_peer(peer.peer.id), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: tuple.peer.peer, account: context.account, context: context, stableId: stableId, height: 50, photoSize: NSMakeSize(36, 36), titleStyle: ControlStyle(font: .medium(.title), foregroundColor: theme.textColor, highlightColor: .white), statusStyle: ControlStyle(foregroundColor: theme.grayTextColor), status: tuple.status, inset: NSEdgeInsets(left: 30, right: 30), interactionType: .plain, generalType: .selectable(tuple.selected), viewType: tuple.viewType, action: {
arguments.switchAccount(tuple.peer.peer.id)
}, customTheme: theme)
}))
}
}
} else {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("loading"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralLoadingRowItem(initialSize, stableId: stableId, viewType: .lastItem)
}))
index += 1
}
if state.canManageCall && state.scheduleTimestamp == nil {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let recordTitle: String
let recordPlaceholder: String = strings().voiecChatSettingsRecordPlaceholder1
if callState.peer.isChannel || callState.peer.isGigagroup {
recordTitle = strings().voiecChatSettingsRecordLiveTitle
} else if !callState.videoActive(.list).isEmpty {
recordTitle = strings().voiecChatSettingsRecordVideoTitle
} else {
recordTitle = strings().voiecChatSettingsRecordTitle
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(recordTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let recordingStartTimestamp = state.recordingStartTimestamp
if recordingStartTimestamp == nil {
entries.append(.input(sectionId: sectionId, index: index, value: .string(uiState.recordName), error: nil, identifier: _id_input_record_title, mode: .plain, data: .init(viewType: .firstItem, pasteFilter: nil, customTheme: theme), placeholder: nil, inputPlaceholder: recordPlaceholder, filter: { $0 }, limit: 40))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_record_video_toggle, data: .init(name: strings().voiceChatSettingsRecordIncludeVideo, color: theme.textColor, type: .switchable(uiState.recordVideo), viewType: .innerItem, action: arguments.toggleRecordVideo, theme: theme)))
index += 1
if uiState.recordVideo {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("video_orientation"), equatable: InputDataEquatable(uiState), comparable: nil, item: { initialSize, stableId in
return GroupCallVideoOrientationRowItem(initialSize, stableId: stableId, viewType: .innerItem, account: context.account, customTheme: theme, selected: uiState.videoOrientation, select: arguments.selectVideoRecordOrientation)
}))
index += 1
}
}
struct Tuple : Equatable {
let recordingStartTimestamp: Int32?
let viewType: GeneralViewType
}
let tuple = Tuple(recordingStartTimestamp: recordingStartTimestamp, viewType: recordingStartTimestamp == nil ? .lastItem : .singleItem)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("recording"), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return GroupCallRecorderRowItem(initialSize, stableId: stableId, viewType: tuple.viewType, account: context.account, startedRecordedTime: tuple.recordingStartTimestamp, customTheme: theme, start: arguments.startRecording, stop: arguments.stopRecording)
}))
index += 1
}
if state.canManageCall, let defaultParticipantMuteState = state.defaultParticipantMuteState, !state.isStream {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPermissionsTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
let isMuted = defaultParticipantMuteState == .muted
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_speak_all_members, data: InputDataGeneralData(name: strings().voiceChatSettingsAllMembers, color: theme.textColor, type: .selectable(!isMuted), viewType: .firstItem, enabled: true, action: {
arguments.updateDefaultParticipantsAreMuted(false)
}, theme: theme)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_speak_admin_only, data: InputDataGeneralData(name: strings().voiceChatSettingsOnlyAdmins, color: theme.textColor, type: .selectable(isMuted), viewType: .lastItem, enabled: true, action: {
arguments.updateDefaultParticipantsAreMuted(true)
}, theme: theme)))
index += 1
}
if !state.isStream {
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let microDevice = settings.audioInputDeviceId == nil ? devices.audioInput.first : devices.audioInput.first(where: { $0.uniqueID == settings.audioInputDeviceId })
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().callSettingsInputTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_audio, data: .init(name: strings().callSettingsInputText, color: theme.textColor, type: .contextSelector(settings.audioInputDeviceId == nil ? strings().callSettingsDeviceDefault : microDevice?.localizedName ?? strings().callSettingsDeviceDefault, [SPopoverItem(strings().callSettingsDeviceDefault, {
arguments.toggleInputAudioDevice(nil)
})] + devices.audioInput.map { value in
return SPopoverItem(value.localizedName, {
arguments.toggleInputAudioDevice(value.uniqueID)
})
}), viewType: microDevice == nil ? .singleItem : .firstItem, theme: theme)))
index += 1
if let microDevice = microDevice {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_micro, equatable: InputDataEquatable(microDevice.uniqueID), comparable: nil, item: { initialSize, stableId -> TableRowItem in
return MicrophonePreviewRowItem(initialSize, stableId: stableId, context: arguments.sharedContext, viewType: .lastItem, customTheme: theme)
}))
index += 1
}
}
if case .sectionId = entries.last {
} else {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
let outputDevice = devices.audioOutput.first(where: { $0.uniqueID == settings.audioOutputDeviceId })
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsOutput), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_output_audio, data: .init(name: strings().voiceChatSettingsOutputDevice, color: theme.textColor, type: .contextSelector(outputDevice?.localizedName ?? strings().callSettingsDeviceDefault, [SPopoverItem(strings().callSettingsDeviceDefault, {
arguments.toggleOutputAudioDevice(nil)
})] + devices.audioOutput.map { value in
return SPopoverItem(value.localizedName, {
arguments.toggleOutputAudioDevice(value.uniqueID)
})
}), viewType: .singleItem, theme: theme)))
index += 1
if !state.isStream {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalkTitle), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_toggle, data: .init(name: strings().voiceChatSettingsPushToTalkEnabled, color: theme.textColor, type: .switchable(settings.mode != .none), viewType: .singleItem, action: {
if settings.mode == .none {
arguments.checkPermission()
}
arguments.updateSettings {
$0.withUpdatedMode($0.mode == .none ? .pushToTalk : .none)
}
}, theme: theme)))
index += 1
switch settings.mode {
case .none:
break
default:
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsInputMode), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_always, data: .init(name: strings().voiceChatSettingsInputModeAlways, color: theme.textColor, type: .selectable(settings.mode == .always), viewType: .firstItem, action: {
arguments.updateSettings {
$0.withUpdatedMode(.always)
}
}, theme: theme)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_ptt, data: .init(name: strings().voiceChatSettingsInputModePushToTalk, color: theme.textColor, type: .selectable(settings.mode == .pushToTalk), viewType: .lastItem, action: {
arguments.updateSettings {
$0.withUpdatedMode(.pushToTalk)
}
}, theme: theme)))
index += 1
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalk), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_ptt, equatable: InputDataEquatable(settings.pushToTalk), comparable: nil, item: { initialSize, stableId -> TableRowItem in
return PushToTalkRowItem(initialSize, stableId: stableId, settings: settings.pushToTalk, update: { value in
arguments.updateSettings {
$0.withUpdatedPushToTalk(value)
}
}, checkPermission: arguments.checkPermission, viewType: .singleItem)
}))
index += 1
if let permission = uiState.hasPermission {
if !permission {
let text: String
if #available(macOS 10.15, *) {
text = strings().voiceChatSettingsPushToTalkAccess
} else {
text = strings().voiceChatSettingsPushToTalkAccessOld
}
entries.append(.desc(sectionId: sectionId, index: index, text: .customMarkdown(text, linkColor: GroupCallTheme.speakLockedColor, linkFont: .bold(11.5), linkHandler: { permission in
PermissionsManager.openInputMonitoringPrefs()
}), data: .init(color: GroupCallTheme.speakLockedColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
} else {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPushToTalkDesc), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .modern(position: .single, insets: NSEdgeInsetsMake(0, 16, 0, 0)))))
index += 1
}
}
}
}
if !state.isStream {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPerformanceHeader), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_noise_suppression, data: InputDataGeneralData(name: strings().voiceChatSettingsNoiseSuppression, color: theme.textColor, type: .switchable(settings.noiseSuppression), viewType: .singleItem, enabled: true, action: {
arguments.setNoiseSuppression(!settings.noiseSuppression)
}, theme: theme)))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsPerformanceDesc), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textBottomItem)))
index += 1
}
if state.canManageCall, peer.groupAccess.isCreator {
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
if !state.isStream {
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_reset_link, data: InputDataGeneralData(name: strings().voiceChatSettingsResetLink, color: GroupCallTheme.customTheme.accentColor, type: .none, viewType: .firstItem, enabled: true, action: arguments.resetLink, theme: theme)))
index += 1
} else if let credentials = uiState.credentials {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatSettingsRTMP), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textTopItem)))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_server_url, equatable: .init(uiState), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPServerURL, copyMenuText: strings().textCopy, labelColor: theme.textColor, textColor: theme.accentColor, backgroundColor: theme.backgroundColor, text: credentials.url, context: nil, viewType: .firstItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.url)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.url)
}, textFont: .code(.title), accentColor: theme.accentColor, borderColor: theme.borderColor)
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_stream_key, equatable: .init(uiState), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPStreamKey, copyMenuText: strings().textCopy, labelColor: theme.textColor, textColor: theme.accentColor, backgroundColor: theme.backgroundColor, text: credentials.streamKey, context: nil, viewType: .innerItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.streamKey)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.streamKey)
}, textFont: .code(.title), hideText: uiState.hideKey, toggleHide: arguments.toggleHideKey, accentColor: theme.accentColor, borderColor: theme.borderColor)
}))
index += 1
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_revoke_stream_key, data: InputDataGeneralData(name: strings().voiceChatRTMPRevoke, color: GroupCallTheme.speakLockedColor, type: .none, viewType: .lastItem, enabled: true, action: arguments.revokeStreamKey, theme: theme)))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatRTMPInfo), data: .init(color: GroupCallTheme.grayStatusColor, viewType: .textBottomItem)))
index += 1
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
}
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_leave_chat, data: InputDataGeneralData(name: strings().voiceChatSettingsEnd, color: GroupCallTheme.speakLockedColor, type: .none, viewType: state.isStream ? .singleItem : .lastItem, enabled: true, action: arguments.finishCall, theme: theme)))
index += 1
}
entries.append(.sectionId(sectionId, type: .customModern(20)))
sectionId += 1
return entries
}
// entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_input_mode_ptt_se, data: .init(name: "Sound Effects", color: .white, type: .switchable(settings.pushToTalkSoundEffects), viewType: .lastItem, action: {
// updateSettings {
// $0.withUpdatedSoundEffects(!$0.pushToTalkSoundEffects)
// }
// }, theme: theme)))
// index += 1
//
final class GroupCallSettingsController : GenericViewController<GroupCallSettingsView> {
fileprivate let sharedContext: SharedAccountContext
fileprivate let call: PresentationGroupCall
private let disposable = MetaDisposable()
private let context: AccountContext
private let monitorPermissionDisposable = MetaDisposable()
private let actualizeTitleDisposable = MetaDisposable()
private let displayAsPeersDisposable = MetaDisposable()
private let credentialsDisposable = MetaDisposable()
private let callState: Signal<GroupCallUIState, NoError>
init(sharedContext: SharedAccountContext, context: AccountContext, callState: Signal<GroupCallUIState, NoError>, call: PresentationGroupCall) {
self.sharedContext = sharedContext
self.call = call
self.callState = callState
self.context = context
super.init()
bar = .init(height: 0)
}
private var tableView: TableView {
return genericView.tableView
}
private var firstTake: Bool = true
override func firstResponder() -> NSResponder? {
if self.window?.firstResponder == self.window || self.window?.firstResponder == tableView.documentView {
var first: NSResponder? = nil
var isRecordingPushToTalk: Bool = false
tableView.enumerateViews { view -> Bool in
if let view = view as? PushToTalkRowView {
if view.mode == .editing {
isRecordingPushToTalk = true
return false
}
}
return true
}
if !isRecordingPushToTalk {
tableView.enumerateViews { view -> Bool in
first = view.firstResponder
if first != nil, self.firstTake {
if let item = view.item as? InputDataRowDataValue {
switch item.value {
case let .string(value):
let value = value ?? ""
if !value.isEmpty {
return true
}
default:
break
}
}
}
return first == nil
}
self.firstTake = false
return first
} else {
return window?.firstResponder
}
}
return window?.firstResponder
}
override func escapeKeyAction() -> KeyHandlerResult {
return .rejected
}
override var enableBack: Bool {
return true
}
deinit {
disposable.dispose()
monitorPermissionDisposable.dispose()
actualizeTitleDisposable.dispose()
displayAsPeersDisposable.dispose()
credentialsDisposable.dispose()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_ = self.window?.makeFirstResponder(nil)
window?.set(mouseHandler: { [weak self] event -> KeyHandlerResult in
guard let `self` = self else {return .rejected}
let index = self.tableView.row(at: self.tableView.documentView!.convert(event.locationInWindow, from: nil))
if index > -1, let view = self.tableView.item(at: index).view {
if view.mouseInsideField {
if self.window?.firstResponder != view.firstResponder {
_ = self.window?.makeFirstResponder(view.firstResponder)
return .invoked
}
}
}
return .invokeNext
}, with: self, for: .leftMouseUp, priority: self.responderPriority)
}
private func fetchData() -> [InputDataIdentifier : InputDataValue] {
var values:[InputDataIdentifier : InputDataValue] = [:]
tableView.enumerateItems { item -> Bool in
if let identifier = (item.stableId.base as? InputDataEntryId)?.identifier {
if let item = item as? InputDataRowDataValue {
values[identifier] = item.value
}
}
return true
}
return values
}
private var getState:(()->GroupCallSettingsState?)? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.genericView.tableView._mouseDownCanMoveWindow = true
let context = self.context
let peerId = self.call.peerId
let initialState = GroupCallSettingsState(hasPermission: nil, title: nil, recordVideo: true, videoOrientation: .landscape)
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((GroupCallSettingsState) -> GroupCallSettingsState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
monitorPermissionDisposable.set((KeyboardGlobalHandler.getPermission() |> deliverOnMainQueue).start(next: { value in
updateState { current in
var current = current
current.hasPermission = value
return current
}
}))
getState = { [weak stateValue] in
return stateValue?.with { $0 }
}
actualizeTitleDisposable.set(call.state.start(next: { state in
updateState { current in
var current = current
if current.title == nil {
current.title = state.title
}
return current
}
}))
displayAsPeersDisposable.set(combineLatest(queue: prepareQueue,call.displayAsPeers, context.account.postbox.peerView(id: context.peerId)).start(next: { list, peerView in
updateState { current in
var current = current
current.displayAsList = list
return current
}
}))
genericView.backButton.set(handler: { [weak self] _ in
self?.navigationController?.back()
}, for: .Click)
let sharedContext = self.sharedContext
let arguments = Arguments(sharedContext: sharedContext, toggleInputAudioDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedAudioInputDeviceId(value)
}).start()
}, toggleOutputAudioDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedAudioOutputDeviceId(value)
}).start()
}, toggleInputVideoDevice: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedCameraInputDeviceId(value)
}).start()
}, finishCall: { [weak self] in
guard let window = self?.window else {
return
}
confirm(for: window, header: strings().voiceChatSettingsEndConfirmTitle, information: strings().voiceChatSettingsEndConfirm, okTitle: strings().voiceChatSettingsEndConfirmOK, successHandler: { [weak self] _ in
guard let call = self?.call, let window = self?.window else {
return
}
_ = showModalProgress(signal: call.sharedContext.endGroupCall(terminate: true), for: window).start()
}, appearance: darkPalette.appearance)
}, updateDefaultParticipantsAreMuted: { [weak self] value in
self?.call.updateDefaultParticipantsAreMuted(isMuted: value)
}, updateSettings: { f in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, f).start()
}, checkPermission: {
updateState { current in
var current = current
current.hasPermission = KeyboardGlobalHandler.hasPermission()
return current
}
}, showTooltip: { [weak self] text in
if let window = self?.window {
showModalText(for: window, text: text)
}
}, switchAccount: { [weak self] peerId in
self?.call.reconnect(as: peerId)
}, startRecording: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRecordingStartTitle, information: strings().voiceChatRecordingStartText1, okTitle: strings().voiceChatRecordingStartOK, successHandler: { _ in
self?.call.setShouldBeRecording(true, title: stateValue.with { $0.recordName }, videoOrientation: stateValue.with { $0.recordVideo ? $0.videoOrientation.rawValue : nil})
})
}
}, stopRecording: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRecordingStopTitle, information: strings().voiceChatRecordingStopText, okTitle: strings().voiceChatRecordingStopOK, successHandler: { [weak window] _ in
self?.call.setShouldBeRecording(false, title: nil, videoOrientation: nil)
if let window = window {
showModalText(for: window, text: strings().voiceChatToastStop)
}
})
}
}, resetLink: { [weak self] in
self?.call.resetListenerLink()
if let window = self?.window {
showModalText(for: window, text: strings().voiceChatSettingsResetLinkSuccess)
}
}, setNoiseSuppression: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedNoiseSuppression(value)
}).start()
}, reduceMotions: { value in
_ = updateVoiceCallSettingsSettingsInteractively(accountManager: sharedContext.accountManager, {
$0.withUpdatedVisualEffects(value)
}).start()
}, selectVideoRecordOrientation: { value in
updateState { current in
var current = current
current.videoOrientation = value
return current
}
}, toggleRecordVideo: {
updateState { current in
var current = current
current.recordVideo = !current.recordVideo
return current
}
}, copyToClipboard: { [weak self] value in
copyToClipboard(value)
if let window = self?.window {
showModalText(for: window, text: strings().contextAlertCopied)
}
}, toggleHideKey: {
updateState { current in
var current = current
current.hideKey = !current.hideKey
return current
}
}, revokeStreamKey: { [weak self] in
if let window = self?.window {
confirm(for: window, header: strings().voiceChatRTMPRevoke, information: strings().voiceChatRTMPRevokeInfo, okTitle: strings().alertYes, cancelTitle: strings().alertNO, successHandler: { [weak self] _ in
let signal = self?.call.engine.calls.getGroupCallStreamCredentials(peerId: .init(peerId.toInt64()), revokePreviousCredentials: true)
if let signal = signal {
_ = showModalProgress(signal: signal, for: window).start(next: { value in
updateState { current in
var current = current
current.credentials = value
return current
}
})
}
}, appearance: GroupCallTheme.customTheme.appearance)
}
})
let previousEntries:Atomic<[AppearanceWrapperEntry<InputDataEntry>]> = Atomic(value: [])
let inputDataArguments = InputDataArguments(select: { _, _ in }, dataUpdated: { [weak self] in
guard let `self` = self else {
return
}
let data = self.fetchData()
var previousTitle: String? = stateValue.with { $0.title }
updateState { current in
var current = current
current.title = data[_id_input_chat_title]?.stringValue ?? current.title
current.recordName = data[_id_input_record_title]?.stringValue ?? current.title
return current
}
let title = stateValue.with({ $0.title })
if previousTitle != title, let title = title {
self.call.updateTitle(title, force: false)
}
})
let initialSize = self.atomicSize
let joinAsPeer: Signal<PeerId, NoError> = self.call.joinAsPeerIdValue
let rtmp_credentials: Signal<GroupCallStreamCredentials?, NoError>
if let peer = self.call.peer, peer.groupAccess.isCreator {
let credentials = self.call.engine.calls.getGroupCallStreamCredentials(peerId: .init(self.call.peerId.toInt64()), revokePreviousCredentials: false)
|> map(Optional.init)
|> `catch` { _ -> Signal<GroupCallStreamCredentials?, NoError> in
return .single(nil)
}
rtmp_credentials = .single(nil) |> then(credentials)
} else {
rtmp_credentials = .single(nil)
}
credentialsDisposable.set(rtmp_credentials.start(next: { value in
updateState { current in
var current = current
current.credentials = value
return current
}
}))
let signal: Signal<TableUpdateTransition, NoError> = combineLatest(queue: prepareQueue, sharedContext.devicesContext.signal, voiceCallSettings(sharedContext.accountManager), appearanceSignal, self.call.account.postbox.loadedPeerWithId(self.call.peerId), self.call.account.postbox.loadedPeerWithId(context.peerId), joinAsPeer, self.callState, statePromise.get()) |> mapToQueue { devices, settings, appearance, peer, accountPeer, joinAsPeerId, state, uiState in
let entries = groupCallSettingsEntries(callState: state, devices: devices, uiState: uiState, settings: settings, context: context, peer: peer, accountPeer: accountPeer, joinAsPeerId: joinAsPeerId, arguments: arguments).map { AppearanceWrapperEntry(entry: $0, appearance: appearance) }
return prepareInputDataTransition(left: previousEntries.swap(entries), right: entries, animated: true, searchState: nil, initialSize: initialSize.with { $0 }, arguments: inputDataArguments, onMainQueue: false)
} |> deliverOnMainQueue
disposable.set(signal.start(next: { [weak self] value in
self?.genericView.tableView.merge(with: value)
self?.readyOnce()
}))
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
backgroundColor = GroupCallTheme.windowBackground.withAlphaComponent(1)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let state = getState?(), let title = state.title {
self.call.updateTitle(title, force: true)
}
self.window?.removeObserver(for: self)
}
override func backKeyAction() -> KeyHandlerResult {
return .invokeNext
}
override func returnKeyAction() -> KeyHandlerResult {
self.navigationController?.back()
return super.returnKeyAction()
}
}
| gpl-2.0 |
Davidde94/StemCode_iOS | StemCode/StemCode/Code/Window/StemItemView.swift | 1 | 713 | //
// StemItemView.swift
// StemCode
//
// Created by David Evans on 26/04/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import UIKit
import StemProjectKit
typealias StemItemViewDelegate = StemFileViewDelegate & StemGroupViewDelegate
protocol StemItemView where Self: UIView {
associatedtype StemItemType: StemItem
var delegate: StemItemViewDelegate! { get set }
var nameLabel: UILabel! { get }
var imageView: UIImageView! { get }
var selectionView: UIView! { get }
var stemItem: StemItemType! { get }
var selected: Bool { get }
func setItem(_ item: StemItemType, openFile: StemFile)
func select(_ sender: Any?)
}
| mit |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/HackerRank/EvenTree/EvenTree.swift | 1 | 1687 | //
// EvenTree.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 29/06/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import Foundation
//https://www.hackerrank.com/challenges/even-tree
class EvenTree: NSObject {
// MARK: Edges
class func totalEdgesRemovedToFormForestOfEvenTrees(numberOfNodes: Int, edges: [[Int]]) -> Int {
let nodes = buildNodes(numberOfNodes: numberOfNodes)
connectEdges(nodes: nodes, edges: edges)
var totalEdgesRemoved = 0
for node in nodes {
if node.parent != nil { // skip root
let count = nodesInTree(root: node)
if count % 2 == 0 {
totalEdgesRemoved += 1
}
}
}
return totalEdgesRemoved
}
// MARK: Build
class func buildNodes(numberOfNodes: Int) -> [EvenTreeNode] {
var nodes = [EvenTreeNode]()
for i in 0..<numberOfNodes {
let node = EvenTreeNode(value: i)
nodes.append(node)
}
return nodes
}
class func connectEdges(nodes: [EvenTreeNode], edges: [[Int]]) {
for edge in edges {
let child = nodes[edge[0]]
let parent = nodes[edge[1]]
parent.addChild(child: child)
}
}
// MARK: DFS
class func nodesInTree(root: EvenTreeNode) -> Int {
var count = 1 // start at 1 as you need to count the root node
for child in root.children {
count += nodesInTree(root: child)
}
return count
}
}
| mit |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Controllers/RootViewController.swift | 1 | 16466 | //
// RootViewController.swift
// zhuishushenqi
//
// Created by Nory Cao on 16/9/16.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
let AllChapterUrl = "http://api.zhuishushenqi.com/ctoc/57df797cb061df9e19b8b030"
class RootViewController: UIViewController {
let kHeaderViewHeight:CGFloat = 5
fileprivate let kHeaderBigHeight:CGFloat = 44
fileprivate let kCellHeight:CGFloat = 60
// 采用dict保存书架中的书籍
var bookshelf:[String:Any]?
// 保存所有书籍的id
var books:[String]?
var bookShelfArr:[BookDetail]?
var updateInfoArr:[UpdateInfo]?
var segMenu:SegMenu!
var bookShelfLB:UILabel!
var communityView:CommunityView!
var headerView:UIView!
var reachability:Reachability?
var semaphore:DispatchSemaphore!
var totalCacheChapter:Int = 0
var curCacheChapter:Int = 0
private var tipImageView:UIImageView!
private var recView:QSLaunchRecView!
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = self.kCellHeight
tableView.estimatedRowHeight = self.kCellHeight
tableView.estimatedSectionHeaderHeight = self.kHeaderViewHeight
tableView.sectionFooterHeight = CGFloat.leastNonzeroMagnitude
tableView.qs_registerCellClass(SwipableCell.self)
// let refresh = PullToRefresh(height: 50, position: .top, tip: "正在刷新")
// tableView.addPullToRefresh(refresh, action: {
// self.requetShelfMsg()
// self.requestBookShelf()
// self.updateInfo()
// })
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupReachability(IMAGE_BASEURL, useClosures: false)
self.startNotifier()
NotificationCenter.default.addObserver(self, selector: #selector(bookShelfUpdate(noti:)), name: Notification.Name(rawValue: BOOKSHELF_ADD), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(bookShelfUpdate(noti:)), name: Notification.Name(rawValue: BOOKSHELF_DELETE), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showRecommend), name: Notification.Name(rawValue:SHOW_RECOMMEND), object: nil)
self.setupSubviews()
self.requetShelfMsg()
self.requestBookShelf()
self.updateInfo()
}
func removeBook(book:BookDetail){
if let books = self.books {
var index = 0
for bookid in books {
if book._id == bookid {
self.books?.remove(at: index)
self.bookshelf?.removeValue(forKey: bookid)
BookManager.shared.deleteBook(book: book)
}
index += 1
}
}
}
@objc func bookShelfUpdate(noti:Notification){
let name = noti.name.rawValue
if let book = noti.object as? BookDetail {
if name == BOOKSHELF_ADD {
self.bookshelf?[book._id] = book
self.books?.append(book._id)
BookManager.shared.addBook(book: book)
} else {
removeBook(book: book)
}
}
//先刷新书架,然后再请求
self.tableView.reloadData()
self.updateInfo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = UIColor.cyan
self.navigationController?.navigationBar.barTintColor = UIColor ( red: 0.7235, green: 0.0, blue: 0.1146, alpha: 1.0 )
UIApplication.shared.isStatusBarHidden = false
// 刷新书架
self.bookshelf = BookManager.shared.books
}
@objc private func showRecommend(){
// animate
let recommend = ZSRecommend()
recommend.show(boyTipCallback: { (btn) in
}, girlTipCallback: { (btn) in
}) { (btn) in
}
// let nib = UINib(nibName: "QSLaunchRecView", bundle: nil)
// recView = nib.instantiate(withOwner: nil, options: nil).first as? QSLaunchRecView
// recView.frame = self.view.bounds
// recView.alpha = 0.0
// recView.closeCallback = { (btn) in
// self.dismissRecView()
// }
// recView.boyTipCallback = { (btn) in
// self.fetchRecList(index: 0)
// self.perform(#selector(self.dismissRecView), with: nil, afterDelay: 1)
// }
//
// recView?.girlTipCallback = { (btn) in
// self.fetchRecList(index: 1)
// self.perform(#selector(self.dismissRecView), with: nil, afterDelay: 1)
// }
// KeyWindow?.addSubview(recView)
// UIView.animate(withDuration: 0.35, animations: {
// self.recView.alpha = 1.0
// }) { (finished) in
//
// }
}
func fetchRecList(index:Int){
let gender = ["male","female"]
let recURL = "\(BASEURL)/book/recommend?gender=\(gender[index])"
zs_get(recURL, parameters: nil) { (response) in
if let books = response?["books"] {
if let models = [BookDetail].deserialize(from: books as? [Any]) as? [BookDetail] {
ZSBookManager.shared.addBooks(books: models)
BookManager.shared.modifyBookshelf(books: models)
self.tableView.reloadData()
}
self.updateInfo()
}
}
}
func showUserTipView(){
tipImageView = UIImageView(frame: self.view.bounds)
tipImageView.image = UIImage(named: "add_book_hint")
tipImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissTipView(sender:)))
tipImageView.addGestureRecognizer(tap)
KeyWindow?.addSubview(tipImageView)
}
@objc func dismissTipView(sender:Any){
tipImageView.removeFromSuperview()
}
@objc func dismissRecView(){
UIView.animate(withDuration: 0.35, animations: {
self.recView.alpha = 0.0
}) { (finished) in
self.recView.removeFromSuperview()
self.showUserTipView()
}
}
@objc func leftAction(_ btn:UIButton){
SideVC.showLeftViewController()
}
@objc func rightAction(_ btn:UIButton){
SideVC.showRightViewController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
}
extension RootViewController:UITableViewDataSource,UITableViewDelegate{
//MARK: - UITableViewDataSource and UITableViewDelegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let keys = books?.count {
return keys
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SwipableCell? = tableView.qs_dequeueReusableCell(SwipableCell.self)
cell?.delegate = self
if let id = books?[indexPath.row] {
if let value = bookshelf?.valueForKey(key: id) as? BookDetail {
cell?.configureCell(model: value)
}
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.kCellHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if bookShelfLB.text == nil || bookShelfLB.text == ""{
return kHeaderViewHeight
}
return kHeaderBigHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let id = self.books?[indexPath.row] {
if let value = bookshelf?.valueForKey(key: id) as? BookDetail {
let viewController = QSTextRouter.createModule(bookDetail:value,callback: { (book:BookDetail) in
let beginDate = Date()
self.bookshelf = BookManager.shared.modifyBookshelf(book:book)
tableView.reloadRow(at: indexPath, with: .automatic)
let endDate = Date()
let time = endDate.timeIntervalSince(beginDate as Date)
QSLog("用时\(time)")
})
self.present(viewController, animated: true, completion: nil)
}
// 进入阅读,当前书籍移到最前面
self.books?.remove(at: indexPath.row)
self.books?.insert(id, at: 0)
let deadline = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline:deadline , execute: {
self.tableView.reloadData()
})
}
}
}
extension RootViewController:ComnunityDelegate{
//MARK: - CommunityDelegate
func didSelectCellAtIndex(_ index:Int){
if index == 3{
let lookVC = LookBookViewController()
SideVC.navigationController?.pushViewController(lookVC, animated: true)
}else
if index == 5 {
let historyVC = ReadHistoryViewController()
SideVC.navigationController?.pushViewController(historyVC, animated: true)
} else if (index == 1) {
let rootVC = ZSRootViewController()
SideVC.navigationController?.pushViewController(rootVC, animated: true)
}
// else if (index == 2) {
// let rootVC = ZSForumViewController()
// SideVC.navigationController?.pushViewController(rootVC, animated: true)
// }
else{
let dynamicVC = DynamicViewController()
SideVC.navigationController?.pushViewController(dynamicVC, animated: true)
}
}
}
extension RootViewController:SwipableCellDelegate{
func swipableCell(swipableCell: SwipableCell, didSelectAt index: Int) {
}
func swipeCell(clickAt: Int,model:BookDetail,cell:SwipableCell,selected:Bool) {
if clickAt == 0 {
if selected == false {
// 取消下载
return
}
let indexPath = tableView.indexPath(for: cell)
// 选择一种缓存方式后,缓存按钮变为选中状态,小说图标变为在缓存中
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let firstAcion = UIAlertAction(title: "全本缓存", style: .default, handler: { (action) in
self.cacheChapter(book: model, startChapter: 0,indexPath: indexPath)
})
let secondAction = UIAlertAction(title: "从当前章节缓存", style: .default, handler: { (action) in
self.cacheChapter(book: model, startChapter: model.chapter,indexPath: indexPath)
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
})
alert.addAction(firstAcion)
alert.addAction(secondAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
else if clickAt == 3 {
self.removeBook(book: model)
self.tableView.reloadData()
}
}
func cacheChapter(book:BookDetail,startChapter:Int,indexPath:IndexPath?){
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .prepare
// 使用信号量控制,避免创建过多线程浪费性能
semaphore = DispatchSemaphore(value: 5)
if let chapters = book.book?.chapters {
self.totalCacheChapter = chapters.count
let group = DispatchGroup()
let global = DispatchQueue.global(qos: .userInitiated)
for index in startChapter..<chapters.count {
global.async(group: group){
if chapters[index].content == "" {
self.fetchChapter(index: index,bookDetail: book,indexPath: indexPath)
let timeout:Double? = 30.00
let timeouts = timeout.flatMap { DispatchTime.now() + $0 }
?? DispatchTime.distantFuture
_ = self.semaphore.wait(timeout: timeouts)
}else {
self.totalCacheChapter -= 1
let cell:SwipableCell = self.tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
if self.totalCacheChapter == self.curCacheChapter {
cell.state = .finish
}
}
}
}
}
}
func fetchChapter(index:Int,bookDetail:BookDetail,indexPath: IndexPath?){
let chapters = bookDetail.chapters
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .download
if index >= (chapters?.count ?? 0) {
cell.state = .none
return
}
var link:NSString = "\(chapters?[index].object(forKey: "link") ?? "")" as NSString
link = link.urlEncode() as NSString
let url = "\(CHAPTERURL)/\(link)?k=22870c026d978c75&t=1489933049"
zs_get(url, parameters: nil) { (response) in
DispatchQueue.global().async {
if let json = response as? Dictionary<String, Any> {
QSLog("JSON:\(json)")
if let chapter = json["chapter"] as? Dictionary<String, Any> {
self.cacheSuccessHandler(chapterIndex: index, chapter: chapter, bookDetail: bookDetail,indexPath: indexPath)
} else {
self.cacheFailureHandler(chapterIndex: index)
}
}else{
self.cacheFailureHandler(chapterIndex:index)
}
}
}
}
}
extension RootViewController:SegMenuDelegate{
func didSelectAtIndex(_ index: Int) {
QSLog("选择了第\(index)个")
if index == 1{
communityView.models = self.bookShelfArr ?? []
}
communityView.isHidden = (index == 0 ? true:false)
}
func cacheSuccessHandler(chapterIndex:Int,chapter: Dictionary<String, Any>,bookDetail:BookDetail,indexPath:IndexPath?){
let cell:SwipableCell = tableView.cellForRow(at: indexPath ?? IndexPath(row: 0, section: 0)) as! SwipableCell
cell.state = .download
if curCacheChapter == totalCacheChapter - 1 {
// 缓存完成
cell.state = .finish
}
self.updateChapter(chapterIndex: chapterIndex, chapter: chapter, bookDetail: bookDetail, indexPath: indexPath)
self.semaphore.signal()
}
func cacheFailureHandler(chapterIndex:Int){
QSLog("下载失败第\(chapterIndex)章节")
self.semaphore.signal()
}
// 更新当前model,更新本地保存model
func updateChapter(chapterIndex:Int,chapter: Dictionary<String, Any>,bookDetail:BookDetail,indexPath:IndexPath?){
if let chapters = bookDetail.book?.chapters {
if chapterIndex < chapters.count {
let qsChapter = chapters[chapterIndex]
qsChapter.content = chapter["body"] as? String ?? ""
bookDetail.book.chapters[chapterIndex] = qsChapter
BookManager.shared.modifyBookshelf(book: bookDetail)
}
}
}
}
| mit |
huangboju/Moots | UICollectionViewLayout/uicollectionview-layouts-kit-master/collection-layout-ios/ViewController.swift | 1 | 530 | //
// ViewController.swift
// collection-flow-layout-ios
//
// Created by Astemir Eleev on 16/04/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
S1U/True-Random | True Random/True Random/ViewController.swift | 1 | 610 | //
// ViewController.swift
// True Random
//
// Created by Stephen on 04/10/2017.
// Copyright © 2017 S1U. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let randomInteger = RandomInteger()
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = ""
randomInteger.from(min: 1, max: 33, count: 6) {
randomNums in
self.label.text = "\(randomNums)"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 |
huangboju/Moots | Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Post/PostDetailContent.swift | 1 | 1719 | //
// PostDetailContent.swift
// RedditOs
//
// Created by Thomas Ricouard on 10/07/2020.
//
import SwiftUI
import Backend
import AVKit
import KingfisherSwiftUI
struct PostDetailContent: View {
let listing: SubredditPost
@Binding var redrawLink: Bool
@ViewBuilder
var body: some View {
if let text = listing.selftext ?? listing.description {
Text(text)
.font(.body)
.fixedSize(horizontal: false, vertical: true)
}
if let video = listing.secureMedia?.video {
HStack {
Spacer()
VideoPlayer(player: AVPlayer(url: video.url))
.frame(width: min(500, CGFloat(video.width)),
height: min(500, CGFloat(video.height)))
Spacer()
}
} else if let url = listing.url, let realURL = URL(string: url) {
if realURL.pathExtension == "jpg" || realURL.pathExtension == "png" {
HStack {
Spacer()
KFImage(realURL)
.resizable()
.aspectRatio(contentMode: .fit)
.background(Color.gray)
.frame(maxHeight: 400)
.padding()
Spacer()
}
} else if listing.selftext == nil || listing.selftext?.isEmpty == true {
LinkPresentationView(url: realURL, redraw: $redrawLink)
}
}
}
}
struct PostDetailContent_Previews: PreviewProvider {
static var previews: some View {
PostDetailContent(listing: static_listing, redrawLink: .constant(false))
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1412-swift-constraints-constraintlocator-profile.swift | 13 | 352 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g<T, length: b: A {
class A {
class func f<T -> String {
func ^() {
protocol C {
}
func b: H) -> V {
}
}
assert() {
}
self.init(T>]
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/05595-swift-lexer-leximpl.swift | 11 | 251 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case c,
([Void{
func b
{
case c, U) -> Void{
case c,
class
}
class
case c,
case
| mit |
nasust/LeafViewer | LeafViewer/classes/ViewMode/ViewMode.swift | 1 | 368 | //
// Created by hideki on 2017/06/22.
// Copyright (c) 2017 hideki. All rights reserved.
//
import Foundation
enum ViewMode: Int {
case original //実寸表示
case automaticZoom //常に画面に合わせて拡大
case justWindow //常にウィンドウに合わせる
case reduceDisplayLargerScreen //画面より大きい場合、縮小する
}
| gpl-3.0 |
alimysoyang/CommunicationDebugger | CommunicationDebugger/AYHelper.swift | 1 | 19700 | //
// AYHelper.swift
// CommunicationDebugger
//
// Created by alimysoyang on 15/11/23.
// Copyright © 2015年 alimysoyang. All rights reserved.
//
import Foundation
import UIKit
// MARK: - 全局枚举类型
/**
手机屏幕尺寸
- kPST_3_5: 3.5寸,4s以前
- kPST_4: 4寸,5、5c、5s
- kPST_4_7: 4.7寸,6
- kPST_5_5: 5.5寸,6plus
- kPSTUnkown: 其它尺寸
*/
enum PhoneSizeType:Int
{
case kPST_3_5 = 0
case kPST_4
case kPST_4_7
case kPST_5_5
case kPSTUnkown
}
/**
服务类型
- kCMSTServer: 服务端
- kCMSTClient: 客户端
*/
enum ServiceType:Int
{
case kCMSTServer = 0
case kCMSTClient
}
/**
通讯类型
- kCMSTUDP: UDP方式
- kCMSTTCP: TCP方式
*/
enum SocketType:Int
{
case kCMSTUDP = 0
case kCMSTTCP
}
/**
通讯传输的字符集
- kCMSCSGBK: GBK字符集
- kCMSCSUTF8: UTF8字符集
*/
enum SocketCharacetSet:Int
{
case kCMSCSGBK = 0
case kCMSCSUTF8
}
/**
通讯的消息类型
- kCMSMTSend: 发送
- kCMSMTReceived: 接收
- kCMSMTNotification: 通知
- kCMSMTErrorNotification: 错误数据的通知(文字采用红色)
*/
enum SocketMessageType:Int
{
case kCMSMTSend = 0
case kCMSMTReceived
case kCMSMTNotification
case kCMSMTErrorNotification
}
/**
通讯数据状态
- kCMMSuccess: 发送、接收成功
- kCMMSFailed: 发送失败
- kCMMSErrorData: 发送、接收数据无法解析
- kCMMSValideAddress: 发送的无效地址
*/
enum MessageStatus:Int
{
case kCMMSuccess = 0
case kCMMSFailed
case kCMMSErrorData
case kCMMSValideAddress
}
/**
项目助手单元
*/
class AYHelper: NSObject
{
// MARK: - properties
// MARK: - 通讯配置文件名
class var configFileName: String
{
return "cmparams";
}
// MARK: - app配置文件名
class var sconfigFileName: String
{
return "apparams";
}
// MARK: - 屏幕宽度
class var screenWidth:CGFloat
{
return UIScreen.mainScreen().bounds.size.width;
}
class var singleLine:CGFloat
{
return 1.0 / UIScreen.mainScreen().scale;
}
// MARK: - 12号字体
class var p12Font:UIFont
{
return UIFont.systemFontOfSize(12.0);
}
// MARK: - 15号字体
class var p15Font:UIFont
{
return UIFont.systemFontOfSize(15.0);
}
// MARK: - 默认背景色
class var defaultBackgroundColor:UIColor
{
return UIColor(red: 249.0 / 255.0, green: 247.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0);
//return UIColor(red: 235.0 / 255.0 , green: 235.0 / 255.0, blue: 235.0 / 255.0, alpha: 1.0);
}
// MARK: - 默认弹出式的背景色
class var defaultPopBackgroundColor:UIColor
{
return UIColor(red: 249.0 / 255.0, green: 247.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0);
}
class var dateformatter : NSDateFormatter
{
struct sharedInstance
{
static var onceToken:dispatch_once_t = 0;
static var staticInstance:NSDateFormatter? = nil;
}
dispatch_once(&sharedInstance.onceToken, { () -> Void in
sharedInstance.staticInstance = NSDateFormatter();
sharedInstance.staticInstance?.dateFormat = "yyyy-MM-dd HH:mm:ss";
});
return sharedInstance.staticInstance!;
}
// MARK: - life cycle
override init()
{
super.init();
}
deinit
{
}
// MARK: - static methods
// MARK: - 判断当前设备的屏幕类型
class func currentDevicePhoneSizeType()->PhoneSizeType
{
var retVal:PhoneSizeType = .kPSTUnkown;
let currentModeSize:CGSize = UIScreen.mainScreen().currentMode!.size;
var isSame:Bool = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(1242, 2208), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_5_5;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(750, 1334), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_4_7;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(640, 1136), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_4;
}
else
{
isSame = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(640, 960), currentModeSize) : false;
if (isSame)
{
retVal = .kPST_3_5
}
}
}
}
return retVal;
}
// MARK: - 获取本地IP地址
class func getIPAddress()->String
{
var addresses = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0
{
// For each interface ...
for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next)
{
let flags = Int32(ptr.memory.ifa_flags)
var addr = ptr.memory.ifa_addr.memory
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)
{
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6)
{
// Convert interface address to a human readable string:
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0)
{
if let address = String.fromCString(hostname)
{
addresses.append(address)
}
}
}
}
}
freeifaddrs(ifaddr);
}
if (addresses.count > 0)
{
return addresses[0];
}
return NSLocalizedString("UnkownIP", comment: "");
}
// MARK: - 16进制字符转单字节
class func charsToByte(highChar:unichar, lowChar:unichar)->UInt8
{
var highb:unichar;
var lowb:unichar;
var tmpb:unichar;
if (highChar >= 48 && highChar <= 57)
{
tmpb = 48;
}
else if (highChar >= 65 && highChar <= 70)
{
tmpb = 55;
}
else
{
tmpb = 87;
}
highb = (highChar - tmpb) * 16;
if (lowChar >= 48 && lowChar <= 57)
{
tmpb = 48;
}
else if (lowChar >= 65 && lowChar <= 70)
{
tmpb = 55;
}
else
{
tmpb = 87;
}
lowb = lowChar - tmpb;
return UInt8(highb + lowb);
}
class func parseReceivedData(receivedData:NSData)->AYHReceivedData
{
let retVal:AYHReceivedData = AYHReceivedData();
if (AYHCMParams.sharedInstance.rHexData)
{
retVal.receivedMsg = receivedData.toHexString("");
}
else
{
if (AYHCMParams.sharedInstance.rCharacterSet == .kCMSCSGBK)
{
retVal.receivedMsg = NSString(data: receivedData, encoding: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))) as? String;
}
else
{
retVal.receivedMsg = NSString(data: receivedData, encoding: NSUTF8StringEncoding) as? String;
}
}
guard let _ = retVal.receivedMsg else
{
retVal.receivedDataResultType = .kCMMSErrorData;
retVal.receivedMsg = String(format: "%@:\n%@", NSLocalizedString("ReceivedDataUnkown", comment: "ReceivedDataUnkown"), receivedData.toHexString(""));
return retVal;
}
return retVal;
}
}
// MARK: - String扩展
extension String
{
/**
字符串去除空格
- returns: 更新后的字符串
*/
func trim()->String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet());
}
/**
判断当前字符串是不是合法的IP地址
:returns: true,false
*/
func isValideIPAddress()->Bool
{
var retVal:Bool = false;
do
{
let regx:NSRegularExpression = try NSRegularExpression(pattern: "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$", options: NSRegularExpressionOptions.CaseInsensitive);
let nStr:NSString = self as NSString;
let matches = regx.matchesInString(self, options:[], range: NSMakeRange(0, nStr.length));
retVal = matches.count > 0;
} catch let error as NSError
{
retVal = false;
debugPrint("isValideIPAddress:\(error)");
}
return retVal;
}
/**
判断当前字符串是不是一个有效的16进制字符串
:returns: true,false
*/
func isValideHexString()->Bool
{
let compareHex = "01234567890abcdefABCDEF";
let cs:NSCharacterSet = NSCharacterSet(charactersInString: compareHex).invertedSet;
let filtereds:NSArray = self.componentsSeparatedByCharactersInSet(cs) as NSArray;
let filtered:String = filtereds.componentsJoinedByString("");
return self == filtered;
}
/**
将普通字符串或16进制字符串转成NSData
:param: hexData true,false
:param: characterSetType 字符集类型0-GBK,1-UTF8,默认1-UTF8
:returns: NSData
*/
func toNSData(hexData:Bool, characterSetType:Int = 1)->NSData?
{
var retVal:NSData?;
let nStr:NSString = self as NSString;
if (hexData)
{
if (self.isValideHexString())
{
let length:Int = nStr.length / 2;
var values:[UInt8] = [UInt8](count:length, repeatedValue:0);
var i:Int = 0;
var j:Int = 0;
while (i < length * 2)
{
let highChar:unichar = nStr.characterAtIndex(i);
let lowChar:unichar = nStr.characterAtIndex(i + 1);
values[j] = AYHelper.charsToByte(highChar, lowChar: lowChar);
i += 2;
j++;
}
retVal = NSData(bytes: values, length: length);
}
}
else
{
if (characterSetType == 0)//GBK
{
retVal = self.dataUsingEncoding(CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)));
}
else
{
retVal = self.dataUsingEncoding(NSUTF8StringEncoding);
}
}
return retVal;
}
}
// MARK: - NSData扩展
extension NSData
{
/**
NSData转成16进制字符串
:param: seperatorChar 分割字符,可以为空
:returns: 16进制字符串
*/
func toHexString(seperatorChar:String?)->String
{
var retVal:String = "";
let count:Int = self.length / sizeof(UInt8);
var bytes:[UInt8] = [UInt8](count:count, repeatedValue:0);
self.getBytes(&bytes, length: count * sizeof(UInt8));
for index in 0..<count
{
if let sChar = seperatorChar
{
if (index == count - 1)
{
retVal += String(format: "%02X", bytes[index]);
}
else
{
retVal += (String(format: "%02X", bytes[index]) + sChar);
}
}
else
{
retVal += String(format: "%02X", bytes[index]);
}
}
return retVal;
}
}
extension NSDate
{
func currentDateToStartDateAndEndDate()->(startDate:NSDate?, endDate:NSDate?)
{
let calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!;
let compents:NSDateComponents = calendar.components([.NSYearCalendarUnit, .NSMonthCalendarUnit, .NSDayCalendarUnit, .NSHourCalendarUnit, .NSMinuteCalendarUnit, .NSSecondCalendarUnit], fromDate: self);
compents.hour = 0;
compents.minute = 0;
compents.second = 0;
let startDate:NSDate? = calendar.dateFromComponents(compents);
compents.hour = 23;
compents.minute = 59;
compents.second = 59;
let endData:NSDate? = calendar.dateFromComponents(compents);
return (startDate, endData);
}
func anyDateToStartDateAndEndDate(daySpace:Int)->(startDate:NSDate?, endDate:NSDate?)
{
let calendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!;
let compents:NSDateComponents = calendar.components([.NSYearCalendarUnit, .NSMonthCalendarUnit, .NSDayCalendarUnit, .NSHourCalendarUnit, .NSMinuteCalendarUnit, .NSSecondCalendarUnit], fromDate: self);
compents.hour = 0;
compents.minute = 0;
compents.second = 0;
var tmpDate:NSDate? = calendar.dateFromComponents(compents);
if let _ = tmpDate
{
tmpDate = tmpDate!.dateByAddingTimeInterval(NSTimeInterval(daySpace * 86400));
return tmpDate!.currentDateToStartDateAndEndDate();
}
return (nil, nil);
}
}
// MARK: - UIColor扩展
extension UIColor
{
/**
16进制字符串颜色值转UIColor
- parameter hexColor: 16进制字符串
- parameter alpha: 透明度,默认1.0
- returns: UIColor
*/
public convenience init?(hexColor:String, alpha:CGFloat = 1.0)
{
var hex = hexColor
if hex.hasPrefix("#")
{
hex = hex.substringFromIndex(hex.startIndex.advancedBy(1));
}
if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil)
{
if hex.characters.count == 3
{
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1));
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2)));
let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2));
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex;
}
let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2));
let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2), end: hex.startIndex.advancedBy(4)));
let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4), end: hex.startIndex.advancedBy(6)));
var redInt: CUnsignedInt = 0;
var greenInt: CUnsignedInt = 0;
var blueInt: CUnsignedInt = 0;
NSScanner(string: redHex).scanHexInt(&redInt);
NSScanner(string: greenHex).scanHexInt(&greenInt);
NSScanner(string: blueHex).scanHexInt(&blueInt);
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: alpha);
}
else
{
self.init();
return nil;
}
}
/**
整型数据转UIColor,可以是16进制整型数据
- parameter rgb: RGB颜色整型值
- parameter alpha: 透明度,默认1.0
- returns: UIColor
*/
public convenience init(rgb:Int,alpha:CGFloat = 1.0)
{
let red:CGFloat = CGFloat((rgb & 0xFF0000) >> 16) / 255.0;
let green:CGFloat = CGFloat((rgb & 0x00FF00) >> 8) / 255.0;
let blue:CGFloat = CGFloat(rgb & 0x0000FF) / 255.0;
self.init(red:red, green:green, blue:blue, alpha:alpha);
}
}
// MARK:- CGSize 扩展
extension CGSize
{
public func isEqualSize(compareSize:CGSize)->Bool
{
if (self.width == compareSize.width && self.height == compareSize.height)
{
return true;
}
return false;
}
}
extension UIView
{
enum AlertViewType:Int
{
case kAVTSuccess = 0
case kAVTFailed
case kAVTNone
}
func alert(msg:String, alertType:AlertViewType)
{
let hud:MBProgressHUD = MBProgressHUD.showHUDAddedTo(self, animated: true);
hud.labelText = msg;
hud.removeFromSuperViewOnHide = true;
if (alertType == .kAVTNone)
{
hud.customView = UIView();
}
else
{
var image:UIImage = UIImage(named: "alertsuccess")!;
if (alertType == .kAVTFailed)
{
image = UIImage(named: "alertfailed")!;
}
hud.customView = UIImageView(image: image);
}
hud.mode = MBProgressHUDMode.CustomView;
self.addSubview(hud);
hud.show(true);
hud.hide(true, afterDelay: 2.0);
}
func showLoadAlert(msg:String)
{
let hud:MBProgressHUD = MBProgressHUD.showHUDAddedTo(self, animated: true);
hud.labelText = msg;
// hud.dimBackground = true;背景加入渐变颜色
//hud.mode = MBProgressHUDMode.Indeterminate;
hud.tag = 1010;
self.addSubview(hud);
self.bringSubviewToFront(hud);
hud.show(true);
}
func hideLoadAlert()
{
self.viewWithTag(1010)?.removeFromSuperview();
MBProgressHUD.hideHUDForView(self, animated: true);
}
}
// MARK:- UIViewController 扩展
extension UIViewController
{
public func showAlertTip(tipMessage:String)
{
if #available(iOS 8.0, *)
{
let alertController:UIAlertController = UIAlertController(title:NSLocalizedString("Information", comment: ""), message: tipMessage, preferredStyle: UIAlertControllerStyle.Alert);
let alertAction:UIAlertAction = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in
alertController.dismissViewControllerAnimated(true, completion: { () -> Void in
});
});
alertController.addAction(alertAction);
self.presentViewController(alertController, animated: true, completion: nil);
}
else
{
let alertView:UIAlertView = UIAlertView(title: NSLocalizedString("Information", comment: ""), message: tipMessage, delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: ""));
alertView.show();
}
}
} | mit |
BeitIssieShapiro/IssieBoard | EducKeyboard/InitTemplates.swift | 2 | 4570 | //
// InitTemplates.swift
// IssieBoard
//
// Created by Even Sapir, Uriel on 4/3/16.
// Copyright © 2016 sap. All rights reserved.
//
import UIKit
import CoreData
class InitTemplates: NSObject {
static func loadPlists(){
let UserSettings = UserDefaults(suiteName: MasterViewController.groupName)!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
for index in [1,2,3] {
let bundlePath = Bundle.main.path(forResource: "DocumentationDefaultTemplates" + String(index), ofType: "plist")
let templateDictionary1 = NSMutableDictionary(contentsOfFile: bundlePath!)
var fullArray = Constants.KEYS_ARRAY
fullArray.append("configurationName")
let configSetEntity = NSEntityDescription.entity(forEntityName: "ConfigSet", in: managedObjectContext)
let configSetObject = NSManagedObject(entity: configSetEntity!, insertInto: managedObjectContext)
//configSetObject.setValue(self.textField.text, forKey:"configurationName")
for key in fullArray{
let currentValue = templateDictionary1?.value(forKey: key)
var coreDataKey = "i" + String(key.characters.dropFirst())
if(key == "configurationName")
{
coreDataKey = key
}
if(currentValue != nil){
configSetObject.setValue(currentValue, forKey:coreDataKey)
if(index==1){
UserSettings.setValue(currentValue, forKey:key)
}
}
}
do{
try managedObjectContext.save()
UserSettings.synchronize()
}catch let error as NSError{
print("could not save configurtion set \(error.description)")
}
}
}
static func ifNeededSetToDefault(){
let UserSettings = UserDefaults(suiteName: MasterViewController.groupName)!
let cString: String? = UserSettings.string(forKey: KEY_ISSIE_KEYBOARD_BACKGROUND_COLOR)
if(cString == nil){
resetToDefaultTemplate()
}
}
static func resetToDefaultTemplate(){
let UserSettings = UserDefaults(suiteName: MasterViewController.groupName)!
let bundlePath = Bundle.main.path(forResource: "DocumentationDefaultTemplates1", ofType: "plist")
let templateDictionary1 = NSMutableDictionary(contentsOfFile: bundlePath!)
var fullArray = Constants.KEYS_ARRAY
fullArray.append("configurationName")
//configSetObject.setValue(self.textField.text, forKey:"configurationName")
for key in fullArray{
let currentValue = templateDictionary1?.value(forKey: key)
if(currentValue != nil){
UserSettings.setValue(currentValue, forKey:key)
}
}
UserSettings.synchronize()
}
static func createNewInitIndicator(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let initIndicatorEntity = NSEntityDescription.entity(forEntityName: "DidCreateDefaultTemplates", in: managedObjectContext)
let initIndicatorObject = NSManagedObject(entity: initIndicatorEntity!, insertInto: managedObjectContext)
//configSetObject.setValue(self.textField.text, forKey:"configurationName")
initIndicatorObject.setValue(true, forKey:"didInit")
do{
try managedObjectContext.save()
}catch let error as NSError{
print("could not save configurtion set \(error.description)")
}
}
static func loadDefaultTemplates(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DidCreateDefaultTemplates")
do{
let didInitIndicator = try managedObjectContext.fetch(fetchRequest)
if (didInitIndicator.count == 0){
InitTemplates.loadPlists()
createNewInitIndicator()
}
else{
// ifNeededSetToDefault()
}
} catch let error as NSError{
print("could not fetch Indicator \(error), \(error.userInfo)")
}
}
}
| apache-2.0 |
MarcoSantarossa/SwiftyToggler | Tests/Feature/FeatureTests.swift | 1 | 2563 | //
// FeatureTests.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@testable import SwiftyToggler
import XCTest
class FeatureTests: XCTestCase {
func test_Init_PayloadNil_PayloadIsNil() {
let feature = Feature<Any>(payload: nil)
XCTAssertNil(feature.payload)
}
func test_Init_GenericTypeString_PayloadIsString() {
let feature = Feature(payload: "payload")
guard let payload = feature.payload else {
XCTFail()
return
}
XCTAssertTrue(type(of: payload) == String.self)
}
func test_Init_ValidPayload_PayloadIsSet() {
let feature = Feature(payload: "payload")
guard let payload = feature.payload else {
XCTFail()
return
}
XCTAssertEqual(payload, "payload")
}
func test_Init_DefaultIsEnable_IsEnableIsFalse() {
let feature = Feature<Any>(payload: nil)
XCTAssertFalse(feature.isEnabled)
}
func test_Init_IsEnableTrue_IsEnableIsTrue() {
let feature = Feature<Any>(payload: nil, isEnabled: true)
XCTAssertTrue(feature.isEnabled)
}
func test_Main_ThrowsFatalError() {
let feature = Feature(payload: "payload")
expectFatalError(expectedMessage: "Feature base class: main method not implemented") {
feature.main()
}
}
}
| mit |
sbanil/VideoBrowser | VideoBrowser/VideoListCell.swift | 1 | 371 | //
// VideoListCell.swift
// VideoBrowser
//
// Created by Sanghubattla, Anil on 11/7/15.
// Copyright © 2015 teamcakes. All rights reserved.
//
import Foundation
import UIKit
class VideoListcell: UITableViewCell {
@IBOutlet weak var videoPreview: UIImageView!
@IBOutlet weak var videoName: UILabel!
@IBOutlet weak var videoLength: UILabel!
} | apache-2.0 |
cinnamon/MPFramework | MPFramework/Extensions/UIAlertController+extension.swift | 1 | 505 | //
// UIAlertController+extension.swift
// MPFramework
//
// Created by 이인재 on 2016.11.03.
// Copyright © 2016 magentapink. All rights reserved.
//
extension UIAlertController {
public convenience init(title: String?, message: String?, confirmTitle: String, confirm: ((UIAlertAction) -> Void)?) {
self.init(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: confirmTitle, style: .default, handler: confirm)
addAction(confirmAction)
}
}
| apache-2.0 |
raysarebest/Hello | Hello/MHAppDelegate.swift | 1 | 2625 | //
// AppDelegate.swift
// Hello
//
// Created by Michael Hulet on 11/24/15.
// Copyright © 2015 Michael Hulet. All rights reserved.
//
import UIKit
import Foundation
//MARK: Important Constants
///String constant designated as an NSUserDefaults key for the last phrase view controller to be displayed onscreen
let MHLastDisplayingViewControllerIndexKey = "last"
//MARK: - App Delegate
///The main app delegate class
@UIApplicationMain class MHAppDelegate: UIResponder, UIApplicationDelegate{
//MARK: Properties
var window: UIWindow?
//MARK: UIApplicationDelegate Conformance
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool{
// Override point for customization after application launch.
NSUserDefaults.standardUserDefaults().registerDefaults([MHLastDisplayingViewControllerIndexKey : 0])
return true
}
func applicationWillResignActive(application: UIApplication) -> Void{
// 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) -> Void{
// 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) -> Void{
// 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) -> Void{
// 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) -> Void{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
} | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.