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 |
---|---|---|---|---|---|
bradhilton/Piper | Sources/Piper.swift | 1 | 3295 | //
// Piper.swift
// Piper
//
// Created by Bradley Hilton on 2/1/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
import Foundation
public protocol Finally {
associatedtype Result
func finally(queue: NSOperationQueue, handler: Result -> Void)
}
public struct EmptyOperation : Finally {
public func finally(queue: NSOperationQueue, handler: Void -> Void) {
queue.addOperationWithBlock { handler() }
}
}
public struct DelayOperation<Input : Finally> : Finally {
var input: Input
var delay: Double
var queue: NSOperationQueue
public func finally(queue: NSOperationQueue, handler: Input.Result -> Void) {
input.finally(self.queue) { input in
let dispatchDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.delay * Double(NSEC_PER_SEC)))
let dispatchQueue = queue.underlyingQueue ?? dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)
dispatch_after(dispatchDelay, dispatchQueue) { handler(input) }
}
}
init(input: Input, delay: Double, queue: NSOperationQueue = NSOperationQueue()) {
self.input = input
self.delay = delay
self.queue = queue
}
}
public struct Operation<Input : Finally, Out> : Finally {
var input: Input
var operation: Input.Result -> Out
var queue: NSOperationQueue
public func finally(queue: NSOperationQueue = NSOperationQueue.mainQueue(), handler: Out -> Void) {
input.finally(self.queue) { input in
let out = self.operation(input)
queue.addOperationWithBlock {
handler(out)
}
}
}
public func after(delay: Double) -> Operation<DelayOperation<Operation>, Out> {
return Operation<DelayOperation<Operation>, Out>(input: DelayOperation(input: self, delay: delay), operation: { $0 }, queue: queue)
}
public func main<T>(operation: Out -> T) -> Operation<Operation, T> {
return queue(NSOperationQueue.mainQueue(), operation: operation)
}
public func background<T>(operation: Out -> T) -> Operation<Operation, T> {
return queue(NSOperationQueue(), operation: operation)
}
public func queue<T>(queue: NSOperationQueue, operation: Out -> T) -> Operation<Operation, T> {
return Operation<Operation, T>(input: self, operation: operation, queue: queue)
}
public func execute() {
finally(NSOperationQueue()) { _ in }
}
}
public func after(delay: Double) -> Operation<DelayOperation<EmptyOperation>, Void> {
let queue = NSOperationQueue()
return Operation<DelayOperation<EmptyOperation>, Void>(input: DelayOperation(input: EmptyOperation(), delay: delay), operation: { $0 }, queue: queue)
}
public func main<T>(operation: Void -> T) -> Operation<EmptyOperation, T> {
return queue(NSOperationQueue.mainQueue(), operation: operation)
}
public func background<T>(operation: Void -> T) -> Operation<EmptyOperation, T> {
return queue(NSOperationQueue(), operation: operation)
}
public func queue<T>(queue: NSOperationQueue, operation: Void -> T) -> Operation<EmptyOperation, T> {
return Operation<EmptyOperation, T>(input: EmptyOperation(), operation: operation, queue: queue)
}
| mit |
andrewBatutin/SwiftYamp | SwiftYamp/Models/UserMessageHeaderFrame.swift | 1 | 1566 | //
// UserMessageHeaderFrame.swift
// SwiftYamp
//
// Created by Andrey Batutin on 6/13/17.
// Copyright © 2017 Andrey Batutin. All rights reserved.
//
import Foundation
import ByteBackpacker
public struct UserMessageHeaderFrame: Equatable, YampFrame {
let uid:[UInt8]
let size:UInt8
let uri:String
public static func ==(lhs: UserMessageHeaderFrame, rhs: UserMessageHeaderFrame) -> Bool {
return lhs.uid == rhs.uid && lhs.size == rhs.size && lhs.uri == rhs.uri
}
public init(uid: [UInt8], size: UInt8, uri: String) {
self.uid = uid
self.size = size
self.uri = uri
}
public init(data: Data) throws {
let dataSize = data.count
if dataSize < 17 { throw SerializationError.WrongDataFrameSize(dataSize) }
uid = Array(data.subdata(in: 0..<16))
size = data[16]
let offset:Int = 17 + Int(size)
if dataSize != offset { throw SerializationError.WrongDataFrameSize(dataSize) }
let s = data.subdata(in: 17..<offset)
guard let str = String(data: s, encoding: String.Encoding.utf8) else {
throw SerializationError.UnexpectedError
}
uri = str
}
public func toData() throws -> Data {
var r = self.uid
r = r + ByteBackpacker.pack(self.size)
guard let encStr = self.uri.data(using: .utf8) else{
throw SerializationError.UnexpectedError
}
var res = Data(bytes: r)
res.append(encStr)
return res
}
}
| mit |
btorch/swift-setup | templates/proxy/etc/init.d/memcached.swift | 1 | 3361 | #! /bin/bash
### BEGIN INIT INFO
# Provides: memcached
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $local_fs
# Should-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start memcached daemon
# Description: Start up memcached, a high-performance memory caching daemon
### END INIT INFO
# Usage:
# cp /etc/memcached.conf /etc/memcached_server1.conf
# cp /etc/memcached.conf /etc/memcached_server2.conf
# start all instances:
# /etc/init.d/memcached start
# start one instance:
# /etc/init.d/memcached start server1
# stop all instances:
# /etc/init.d/memcached stop
# stop one instance:
# /etc/init.d/memcached stop server1
# There is no "status" command.
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/memcached
DAEMONNAME=memcached
DAEMONBOOTSTRAP=/usr/share/memcached/scripts/start-memcached
DESC=memcached
test -x $DAEMON || exit 0
test -x $DAEMONBOOTSTRAP || exit 0
set -e
. /lib/lsb/init-functions
# Edit /etc/default/memcached to change this.
ENABLE_MEMCACHED=no
test -r /etc/default/memcached && . /etc/default/memcached
FILES=(/etc/memcached_*.conf)
# check for alternative config schema
if [ -r "${FILES[0]}" ]; then
CONFIGS=()
for FILE in "${FILES[@]}";
do
# remove prefix
NAME=${FILE#/etc/}
# remove suffix
NAME=${NAME%.conf}
# check optional second param
if [ $# -ne 2 ];
then
# add to config array
CONFIGS+=($NAME)
elif [ "memcached_$2" == "$NAME" ];
then
# use only one memcached
CONFIGS=($NAME)
break;
fi;
done;
if [ ${#CONFIGS[@]} == 0 ];
then
echo "Config not exist for: $2" >&2
exit 1
fi;
else
CONFIGS=(memcached)
fi;
CONFIG_NUM=${#CONFIGS[@]}
for ((i=0; i < $CONFIG_NUM; i++)); do
NAME=${CONFIGS[${i}]}
PIDFILE="/var/run/${NAME}.pid"
case "$1" in
start)
echo -n "Starting $DESC: "
if [ $ENABLE_MEMCACHED = yes ]; then
ulimit -n 8192
start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- /etc/${NAME}.conf $PIDFILE
echo "$NAME."
else
echo "$NAME disabled in /etc/default/memcached."
fi
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --oknodo --retry 5 --pidfile $PIDFILE --exec $DAEMON
echo "$NAME."
rm -f $PIDFILE
;;
restart|force-reload)
#
# If the "reload" option is implemented, move the "force-reload"
# option to the "reload" entry above. If not, "force-reload" is
# just the same as "restart".
#
echo -n "Restarting $DESC: "
start-stop-daemon --stop --quiet --oknodo --retry 5 --pidfile $PIDFILE
rm -f $PIDFILE
if [ $ENABLE_MEMCACHED = yes ]; then
ulimit -n 8192
start-stop-daemon --start --quiet --exec "$DAEMONBOOTSTRAP" -- /etc/${NAME}.conf $PIDFILE
echo "$NAME."
else
echo "$NAME disabled in /etc/default/memcached."
fi
;;
status)
status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
exit 1
;;
esac
done;
exit 0
| apache-2.0 |
longitachi/ZLPhotoBrowser | Example/Example/Kingfisher/General/KingfisherManager.swift | 1 | 33256 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// The downloading progress block type.
/// The parameter value is the `receivedSize` of current response.
/// The second parameter is the total expected data length from response's "Content-Length" header.
/// If the expected length is not available, this block will not be called.
public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void)
/// Represents the result of a Kingfisher retrieving image task.
public struct RetrieveImageResult {
/// Gets the image object of this result.
public let image: KFCrossPlatformImage
/// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved.
/// If the image is just downloaded from network, `.none` will be returned.
public let cacheType: CacheType
/// The `Source` which this result is related to. This indicated where the `image` of `self` is referring.
public let source: Source
/// The original `Source` from which the retrieve task begins. It can be different from the `source` property.
/// When an alternative source loading happened, the `source` will be the replacing loading target, while the
/// `originalSource` will be kept as the initial `source` which issued the image loading process.
public let originalSource: Source
}
/// A struct that stores some related information of an `KingfisherError`. It provides some context information for
/// a pure error so you can identify the error easier.
public struct PropagationError {
/// The `Source` to which current `error` is bound.
public let source: Source
/// The actual error happens in framework.
public let error: KingfisherError
}
/// The downloading task updated block type. The parameter `newTask` is the updated new task of image setting process.
/// It is a `nil` if the image loading does not require an image downloading process. If an image downloading is issued,
/// this value will contain the actual `DownloadTask` for you to keep and cancel it later if you need.
public typealias DownloadTaskUpdatedBlock = ((_ newTask: DownloadTask?) -> Void)
/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache,
/// to provide a set of convenience methods to use Kingfisher for tasks.
/// You can use this class to retrieve an image via a specified URL from web or cache.
public class KingfisherManager {
/// Represents a shared manager used across Kingfisher.
/// Use this instance for getting or storing images with Kingfisher.
public static let shared = KingfisherManager()
// Mark: Public Properties
/// The `ImageCache` used by this manager. It is `ImageCache.default` by default.
/// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
/// used instead.
public var cache: ImageCache
/// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default.
/// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
/// used instead.
public var downloader: ImageDownloader
/// Default options used by the manager. This option will be used in
/// Kingfisher manager related methods, as well as all view extension methods.
/// You can also passing other options for each image task by sending an `options` parameter
/// to Kingfisher's APIs. The per image options will overwrite the default ones,
/// if the option exists in both.
public var defaultOptions = KingfisherOptionsInfo.empty
// Use `defaultOptions` to overwrite the `downloader` and `cache`.
private var currentDefaultOptions: KingfisherOptionsInfo {
return [.downloader(downloader), .targetCache(cache)] + defaultOptions
}
private let processingQueue: CallbackQueue
private convenience init() {
self.init(downloader: .default, cache: .default)
}
/// Creates an image setting manager with specified downloader and cache.
///
/// - Parameters:
/// - downloader: The image downloader used to download images.
/// - cache: The image cache which stores memory and disk images.
public init(downloader: ImageDownloader, cache: ImageCache) {
self.downloader = downloader
self.cache = cache
let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)"
processingQueue = .dispatch(DispatchQueue(label: processQueueName))
}
// MARK: - Getting Images
/// Gets an image from a given resource.
/// - Parameters:
/// - resource: The `Resource` object defines data information like key or URL.
/// - options: Options to use when creating the image.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
/// main queue.
/// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This
/// usually happens when an alternative source is used to replace the original (failed)
/// task. You can update your reference of `DownloadTask` if you want to manually `cancel`
/// the new task.
/// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
/// from the `options.callbackQueue`. If not specified, the main queue will be used.
/// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
/// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
///
/// - Note:
/// This method will first check whether the requested `resource` is already in cache or not. If cached,
/// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
/// will download the `resource`, store it in cache, then call `completionHandler`.
@discardableResult
public func retrieveImage(
with resource: Resource,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
return retrieveImage(
with: resource.convertToSource(),
options: options,
progressBlock: progressBlock,
downloadTaskUpdated: downloadTaskUpdated,
completionHandler: completionHandler
)
}
/// Gets an image from a given resource.
///
/// - Parameters:
/// - source: The `Source` object defines data information from network or a data provider.
/// - options: Options to use when creating the image.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
/// main queue.
/// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This
/// usually happens when an alternative source is used to replace the original (failed)
/// task. You can update your reference of `DownloadTask` if you want to manually `cancel`
/// the new task.
/// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
/// from the `options.callbackQueue`. If not specified, the main queue will be used.
/// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
/// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
///
/// - Note:
/// This method will first check whether the requested `source` is already in cache or not. If cached,
/// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
/// will try to load the `source`, store it in cache, then call `completionHandler`.
///
public func retrieveImage(
with source: Source,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
let options = currentDefaultOptions + (options ?? .empty)
var info = KingfisherParsedOptionsInfo(options)
if let block = progressBlock {
info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
return retrieveImage(
with: source,
options: info,
downloadTaskUpdated: downloadTaskUpdated,
completionHandler: completionHandler)
}
func retrieveImage(
with source: Source,
options: KingfisherParsedOptionsInfo,
downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
let retrievingContext = RetrievingContext(options: options, originalSource: source)
var retryContext: RetryContext?
func startNewRetrieveTask(
with source: Source,
downloadTaskUpdated: DownloadTaskUpdatedBlock?
) {
let newTask = self.retrieveImage(with: source, context: retrievingContext) { result in
handler(currentSource: source, result: result)
}
downloadTaskUpdated?(newTask)
}
func failCurrentSource(_ source: Source, with error: KingfisherError) {
// Skip alternative sources if the user cancelled it.
guard !error.isTaskCancelled else {
completionHandler?(.failure(error))
return
}
if let nextSource = retrievingContext.popAlternativeSource() {
startNewRetrieveTask(with: nextSource, downloadTaskUpdated: downloadTaskUpdated)
} else {
// No other alternative source. Finish with error.
if retrievingContext.propagationErrors.isEmpty {
completionHandler?(.failure(error))
} else {
retrievingContext.appendError(error, to: source)
let finalError = KingfisherError.imageSettingError(
reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors)
)
completionHandler?(.failure(finalError))
}
}
}
func handler(currentSource: Source, result: (Result<RetrieveImageResult, KingfisherError>)) -> Void {
switch result {
case .success:
completionHandler?(result)
case .failure(let error):
if let retryStrategy = options.retryStrategy {
let context = retryContext?.increaseRetryCount() ?? RetryContext(source: source, error: error)
retryContext = context
retryStrategy.retry(context: context) { decision in
switch decision {
case .retry(let userInfo):
retryContext?.userInfo = userInfo
startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated)
case .stop:
failCurrentSource(currentSource, with: error)
}
}
} else {
// Skip alternative sources if the user cancelled it.
guard !error.isTaskCancelled else {
completionHandler?(.failure(error))
return
}
if let nextSource = retrievingContext.popAlternativeSource() {
retrievingContext.appendError(error, to: currentSource)
startNewRetrieveTask(with: nextSource, downloadTaskUpdated: downloadTaskUpdated)
} else {
// No other alternative source. Finish with error.
if retrievingContext.propagationErrors.isEmpty {
completionHandler?(.failure(error))
} else {
retrievingContext.appendError(error, to: currentSource)
let finalError = KingfisherError.imageSettingError(
reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors)
)
completionHandler?(.failure(finalError))
}
}
}
}
}
return retrieveImage(
with: source,
context: retrievingContext)
{
result in
handler(currentSource: source, result: result)
}
}
private func retrieveImage(
with source: Source,
context: RetrievingContext,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask?
{
let options = context.options
if options.forceRefresh {
return loadAndCacheImage(
source: source,
context: context,
completionHandler: completionHandler)?.value
} else {
let loadedFromCache = retrieveImageFromCache(
source: source,
context: context,
completionHandler: completionHandler)
if loadedFromCache {
return nil
}
if options.onlyFromCache {
let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey))
completionHandler?(.failure(error))
return nil
}
return loadAndCacheImage(
source: source,
context: context,
completionHandler: completionHandler)?.value
}
}
func provideImage(
provider: ImageDataProvider,
options: KingfisherParsedOptionsInfo,
completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?)
{
guard let completionHandler = completionHandler else { return }
provider.data { result in
switch result {
case .success(let data):
(options.processingQueue ?? self.processingQueue).execute {
let processor = options.processor
let processingItem = ImageProcessItem.data(data)
guard let image = processor.process(item: processingItem, options: options) else {
options.callbackQueue.execute {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: processingItem))
completionHandler(.failure(error))
}
return
}
let finalImage = options.imageModifier?.modify(image) ?? image
options.callbackQueue.execute {
let result = ImageLoadingResult(image: finalImage, url: nil, originalData: data)
completionHandler(.success(result))
}
}
case .failure(let error):
options.callbackQueue.execute {
let error = KingfisherError.imageSettingError(
reason: .dataProviderError(provider: provider, error: error))
completionHandler(.failure(error))
}
}
}
}
private func cacheImage(
source: Source,
options: KingfisherParsedOptionsInfo,
context: RetrievingContext,
result: Result<ImageLoadingResult, KingfisherError>,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?
)
{
switch result {
case .success(let value):
let needToCacheOriginalImage = options.cacheOriginalImage &&
options.processor != DefaultImageProcessor.default
let coordinator = CacheCallbackCoordinator(
shouldWaitForCache: options.waitForCache, shouldCacheOriginal: needToCacheOriginalImage)
// Add image to cache.
let targetCache = options.targetCache ?? self.cache
targetCache.store(
value.image,
original: value.originalData,
forKey: source.cacheKey,
options: options,
toDisk: !options.cacheMemoryOnly)
{
_ in
coordinator.apply(.cachingImage) {
let result = RetrieveImageResult(
image: value.image,
cacheType: .none,
source: source,
originalSource: context.originalSource
)
completionHandler?(.success(result))
}
}
// Add original image to cache if necessary.
if needToCacheOriginalImage {
let originalCache = options.originalCache ?? targetCache
originalCache.storeToDisk(
value.originalData,
forKey: source.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
expiration: options.diskCacheExpiration)
{
_ in
coordinator.apply(.cachingOriginalImage) {
let result = RetrieveImageResult(
image: value.image,
cacheType: .none,
source: source,
originalSource: context.originalSource
)
completionHandler?(.success(result))
}
}
}
coordinator.apply(.cacheInitiated) {
let result = RetrieveImageResult(
image: value.image,
cacheType: .none,
source: source,
originalSource: context.originalSource
)
completionHandler?(.success(result))
}
case .failure(let error):
completionHandler?(.failure(error))
}
}
@discardableResult
func loadAndCacheImage(
source: Source,
context: RetrievingContext,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask.WrappedTask?
{
let options = context.options
func _cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>) {
cacheImage(
source: source,
options: options,
context: context,
result: result,
completionHandler: completionHandler
)
}
switch source {
case .network(let resource):
let downloader = options.downloader ?? self.downloader
let task = downloader.downloadImage(
with: resource.downloadURL, options: options, completionHandler: _cacheImage
)
// The code below is neat, but it fails the Swift 5.2 compiler with a runtime crash when
// `BUILD_LIBRARY_FOR_DISTRIBUTION` is turned on. I believe it is a bug in the compiler.
// Let's fallback to a traditional style before it can be fixed in Swift.
//
// https://github.com/onevcat/Kingfisher/issues/1436
//
// return task.map(DownloadTask.WrappedTask.download)
if let task = task {
return .download(task)
} else {
return nil
}
case .provider(let provider):
provideImage(provider: provider, options: options, completionHandler: _cacheImage)
return .dataProviding
}
}
/// Retrieves image from memory or disk cache.
///
/// - Parameters:
/// - source: The target source from which to get image.
/// - key: The key to use when caching the image.
/// - url: Image request URL. This is not used when retrieving image from cache. It is just used for
/// `RetrieveImageResult` callback compatibility.
/// - options: Options on how to get the image from image cache.
/// - completionHandler: Called when the image retrieving finishes, either with succeeded
/// `RetrieveImageResult` or an error.
/// - Returns: `true` if the requested image or the original image before being processed is existing in cache.
/// Otherwise, this method returns `false`.
///
/// - Note:
/// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in
/// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher
/// will try to check whether an original version of that image is existing or not. If there is already an
/// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store
/// back to cache for later use.
func retrieveImageFromCache(
source: Source,
context: RetrievingContext,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool
{
let options = context.options
// 1. Check whether the image was already in target cache. If so, just get it.
let targetCache = options.targetCache ?? cache
let key = source.cacheKey
let targetImageCached = targetCache.imageCachedType(
forKey: key, processorIdentifier: options.processor.identifier)
let validCache = targetImageCached.cached &&
(options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory)
if validCache {
targetCache.retrieveImage(forKey: key, options: options) { result in
guard let completionHandler = completionHandler else { return }
options.callbackQueue.execute {
result.match(
onSuccess: { cacheResult in
let value: Result<RetrieveImageResult, KingfisherError>
if let image = cacheResult.image {
value = result.map {
RetrieveImageResult(
image: image,
cacheType: $0.cacheType,
source: source,
originalSource: context.originalSource
)
}
} else {
value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
}
completionHandler(value)
},
onFailure: { _ in
completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
}
)
}
}
return true
}
// 2. Check whether the original image exists. If so, get it, process it, save to storage and return.
let originalCache = options.originalCache ?? targetCache
// No need to store the same file in the same cache again.
if originalCache === targetCache && options.processor == DefaultImageProcessor.default {
return false
}
// Check whether the unprocessed image existing or not.
let originalImageCacheType = originalCache.imageCachedType(
forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier)
let canAcceptDiskCache = !options.fromMemoryCacheOrRefresh
let canUseOriginalImageCache =
(canAcceptDiskCache && originalImageCacheType.cached) ||
(!canAcceptDiskCache && originalImageCacheType == .memory)
if canUseOriginalImageCache {
// Now we are ready to get found the original image from cache. We need the unprocessed image, so remove
// any processor from options first.
var optionsWithoutProcessor = options
optionsWithoutProcessor.processor = DefaultImageProcessor.default
originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in
result.match(
onSuccess: { cacheResult in
guard let image = cacheResult.image else {
assertionFailure("The image (under key: \(key) should be existing in the original cache.")
return
}
let processor = options.processor
(options.processingQueue ?? self.processingQueue).execute {
let item = ImageProcessItem.image(image)
guard let processedImage = processor.process(item: item, options: options) else {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: item))
options.callbackQueue.execute { completionHandler?(.failure(error)) }
return
}
var cacheOptions = options
cacheOptions.callbackQueue = .untouch
let coordinator = CacheCallbackCoordinator(
shouldWaitForCache: options.waitForCache, shouldCacheOriginal: false)
targetCache.store(
processedImage,
forKey: key,
options: cacheOptions,
toDisk: !options.cacheMemoryOnly)
{
_ in
coordinator.apply(.cachingImage) {
let value = RetrieveImageResult(
image: processedImage,
cacheType: .none,
source: source,
originalSource: context.originalSource
)
options.callbackQueue.execute { completionHandler?(.success(value)) }
}
}
coordinator.apply(.cacheInitiated) {
let value = RetrieveImageResult(
image: processedImage,
cacheType: .none,
source: source,
originalSource: context.originalSource
)
options.callbackQueue.execute { completionHandler?(.success(value)) }
}
}
},
onFailure: { _ in
// This should not happen actually, since we already confirmed `originalImageCached` is `true`.
// Just in case...
options.callbackQueue.execute {
completionHandler?(
.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
)
}
}
)
}
return true
}
return false
}
}
class RetrievingContext {
var options: KingfisherParsedOptionsInfo
let originalSource: Source
var propagationErrors: [PropagationError] = []
init(options: KingfisherParsedOptionsInfo, originalSource: Source) {
self.originalSource = originalSource
self.options = options
}
func popAlternativeSource() -> Source? {
guard var alternativeSources = options.alternativeSources, !alternativeSources.isEmpty else {
return nil
}
let nextSource = alternativeSources.removeFirst()
options.alternativeSources = alternativeSources
return nextSource
}
@discardableResult
func appendError(_ error: KingfisherError, to source: Source) -> [PropagationError] {
let item = PropagationError(source: source, error: error)
propagationErrors.append(item)
return propagationErrors
}
}
class CacheCallbackCoordinator {
enum State {
case idle
case imageCached
case originalImageCached
case done
}
enum Action {
case cacheInitiated
case cachingImage
case cachingOriginalImage
}
private let shouldWaitForCache: Bool
private let shouldCacheOriginal: Bool
private let stateQueue: DispatchQueue
private var threadSafeState: State = .idle
private (set) var state: State {
set { stateQueue.sync { threadSafeState = newValue } }
get { stateQueue.sync { threadSafeState } }
}
init(shouldWaitForCache: Bool, shouldCacheOriginal: Bool) {
self.shouldWaitForCache = shouldWaitForCache
self.shouldCacheOriginal = shouldCacheOriginal
let stateQueueName = "com.onevcat.Kingfisher.CacheCallbackCoordinator.stateQueue.\(UUID().uuidString)"
self.stateQueue = DispatchQueue(label: stateQueueName)
}
func apply(_ action: Action, trigger: () -> Void) {
switch (state, action) {
case (.done, _):
break
// From .idle
case (.idle, .cacheInitiated):
if !shouldWaitForCache {
state = .done
trigger()
}
case (.idle, .cachingImage):
if shouldCacheOriginal {
state = .imageCached
} else {
state = .done
trigger()
}
case (.idle, .cachingOriginalImage):
state = .originalImageCached
// From .imageCached
case (.imageCached, .cachingOriginalImage):
state = .done
trigger()
// From .originalImageCached
case (.originalImageCached, .cachingImage):
state = .done
trigger()
default:
assertionFailure("This case should not happen in CacheCallbackCoordinator: \(state) - \(action)")
}
}
}
| mit |
AckeeCZ/ACKategories | ACKategories-iOSTests/ReusableViewTests.swift | 1 | 1585 | import ACKategories
import UIKit
import XCTest
final class ReusableViewTests: XCTestCase {
func test_tableViewCellPrototype_isCached() {
final class CustomCell: UITableViewCell { }
let tableView = UITableView()
let prototype = tableView.prototypeCell(type: CustomCell.self)
let prototype2 = tableView.prototypeCell(type: CustomCell.self)
XCTAssertTrue(prototype === prototype2)
XCTAssertFalse(prototype === CustomCell())
}
func test_collectionViewCellPrototype_isCached() {
final class CustomCell: UICollectionViewCell { }
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let prototype = collectionView.prototypeCell(type: CustomCell.self)
let prototype2 = collectionView.prototypeCell(type: CustomCell.self)
XCTAssertTrue(prototype === prototype2)
XCTAssertFalse(prototype === CustomCell())
}
func test_collectionViewSupplementaryViewPrototype_isCached() {
final class CustomView: UICollectionReusableView { }
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let prototype = collectionView.prototypeSupplementaryView(ofKind: "view", type: CustomView.self)
let prototype2 = collectionView.prototypeSupplementaryView(ofKind: "view", type: CustomView.self)
XCTAssertTrue(prototype === prototype2)
XCTAssertFalse(prototype === CustomView())
}
}
| mit |
antitypical/Manifold | Manifold/Telescope.swift | 1 | 577 | // Copyright © 2015 Rob Rix. All rights reserved.
public enum Telescope {
indirect case Recursive(Name, Telescope)
indirect case Argument(Name, Term, Telescope)
case End
public func fold(recur: Term, terminal: Term, combine: (Name, Term, Term) -> Term) -> Term {
switch self {
case .End:
return terminal
case let .Recursive(name, rest):
return combine(name, recur, rest.fold(recur, terminal: terminal, combine: combine))
case let .Argument(name, type, rest):
return combine(name, type, rest.fold(recur, terminal: terminal, combine: combine))
}
}
}
| mit |
Orion98MC/FSM.swift | FSM.swift | 1 | 3523 | //
// FSM.swift
// A Finite State Machine in Swift
//
// Copyright © 2017 Thierry Passeron. All rights reserved.
//
import Foundation
public class FSM<StateType: Equatable, EventType: Equatable> {
public struct StateTransition: CustomStringConvertible {
var event: EventType
var state: StateType
var target: () -> StateType?
init(event: EventType, state: StateType, target: @escaping () -> StateType?) {
self.event = event
self.state = state
self.target = target
}
public var description: String { return "\(event)@\(state)" }
}
public class StateDefinition {
var state: StateType
var onEnter: (() -> Void)?
var onLeave: (() -> Void)?
var onCycle: (() -> Void)?
init(_ state: StateType) {
self.state = state
}
}
public var name: String?
public var debugMode: Bool = false // Shows some NSLog when set to true
private var definitions: [StateDefinition] = []
private var transitions: [StateTransition] = []
private var stateDefinition: StateDefinition {
didSet {
previousState = oldValue.state
}
}
public var state: StateType { return stateDefinition.state }
public var lastEvent: EventType?
public var previousState: StateType?
public init(withDefinitions definitions: [StateDefinition], configure: ((FSM) -> Void)? = nil) {
self.definitions = definitions
self.stateDefinition = definitions.first!
configure?(self)
}
public init(withStates states: [StateType], configure: ((FSM) -> Void)? = nil) {
self.definitions = states.map({ StateDefinition($0) })
self.stateDefinition = definitions.first!
configure?(self)
}
public func transition(on event: EventType, from state: StateType, to target: @escaping @autoclosure () -> StateType?) {
transitions.append(StateTransition(event: event, state: state, target: target))
}
public func transition(on event: EventType, from states: [StateType], to target: @escaping @autoclosure () -> StateType?) {
for state in states {
transitions.append(StateTransition(event: event, state: state, target: target))
}
}
public func transition(on event: EventType, from state: StateType, with target: @escaping () -> StateType?) {
transitions.append(StateTransition(event: event, state: state, target: target))
}
public func definedState(_ state: StateType) -> StateDefinition? {
return definitions.filter({ $0.state == state }).first
}
public func setState(_ state: StateType) {
if debugMode { NSLog("FSM(\(name ?? "?")) SetState \(state)") }
let definition = definedState(state)!
definition.state = state
guard definition.state != self.state else {
stateDefinition = definition
stateDefinition.onCycle?()
return
}
stateDefinition.onLeave?()
stateDefinition = definition
stateDefinition.onEnter?()
}
public func event(_ event: EventType) {
if debugMode { NSLog("FSM(\(name ?? "?")) Event: \(event)") }
lastEvent = event
guard let transition = transitions.filter({ $0.event == event && $0.state == state }).first else {
if debugMode { NSLog("FSM(\(name ?? "?")) No transition for \(event)@\(state) in \(self.transitions)") }
return
}
guard let targetState = transition.target() else {
if debugMode { NSLog("FSM(\(name ?? "?")) No target state! State unchanged: \(state)") }
return
}
setState(targetState)
}
}
| mit |
tablexi/txi-ios-bootstrap | Pod/Classes/Managers/ObserverManager.swift | 1 | 4334 | //
// TypedNotifications.swift
// Table XI
//
// Created by Daniel Hodos on 7/3/15.
// Copyright © 2015 Table XI. All rights reserved.
import Foundation
/// A value object that provides a strongly-typed conceptualization of a Notification.
///
/// This uses a generic (A) to hold reference to the payload that is being notified.
/// This payload can be:
///
/// - a type, e.g. `Notification<String>`, `Notification<SomeCustomStruct>`, etc.
/// - a tuple, for when there's multiple pieces to the payload, e.g. `Notification<(index: Int, name: String?)>`
/// - `Notificatin<Void>`, for when there's no payload data
/// - etc.
public struct Notification<A> {
public init() {}
/// The name of the notification; we generate a random UUID here, since the Notification
/// object's identity alone can be used for uniqueness.
let name = NSUUID().uuidString
/// Posts this notification with the given payload, from the given object.
///
/// - Parameters:
/// - value: A payload (defined when the Notification is initialized).
/// - object: An optional object that is posting this Notification; often this is nil.
public func post(value: A, fromObject object: AnyObject?) {
let userInfo = ["value": Box(value)]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object, userInfo: userInfo)
}
/// Posts this notification with the given payload, but not from any specific object.
///
/// - Parameters:
/// - value: A payload (defined when the Notification is initialized).
public func post(value: A) {
post(value: value, fromObject: nil)
}
}
/// A class that provides a way to observe our strongly-typed Notifications via NSNotificationCenter,
/// while also automatically cleaning up after themselves (when this object is deinitialized, it removes
/// the observer that was added to the notification center).
class NotificationObserver {
/// When calling addObserverForName, NSNotificationCenter returns some sort of opaque object.
/// We don't care what it is, we just need a reference to it so that we can remove it from the
/// NSNotificationCenter when this object goes out of scope.
private let observer: NSObjectProtocol
/// Observes a given notification from a given optional Object.
///
/// Parameters:
/// - notification: a Notification object
/// - object: an optional Object; if nil is passed, then the object that posts the notification will not matter.
/// - block: a closure that gets called with the Notification's payload
init<A>(_ notification: Notification<A>, fromObject object: AnyObject?, block aBlock: @escaping (A) -> ()) {
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: notification.name), object: object, queue: nil) { note in
if let value = (note.userInfo?["value"] as? Box<A>)?.unbox {
aBlock(value)
} else {
assert(false, "Couldn't understand user info")
}
}
}
/// Observes a given notification.
///
/// Parameters:
/// - notification: a Notification object
/// - block: a closure that gets called with the Notification's payload
convenience init<A>(_ notification: Notification<A>, block aBlock: @escaping (A) -> ()) {
self.init(notification, fromObject: nil, block: aBlock)
}
/// When this object goes out of scope, it will remove the observer from the notification
/// center, i.e. it will clean up after itself.
deinit {
NotificationCenter.default.removeObserver(observer)
}
}
public class ObserverManager {
var observers = Array<NotificationObserver>()
public init(){}
public func observeNotification<A>(notification: Notification<A>, block aBlock: @escaping (A) -> ()) {
observeNotification(notification: notification, fromObject: nil, block: aBlock)
}
public func observeNotification<A>(notification: Notification<A>, fromObject object: AnyObject?, block aBlock: @escaping (A) -> ()) {
let newObserver = NotificationObserver(notification, fromObject: object, block: aBlock)
self.observers.append(newObserver)
}
}
/// Boxing allows for wrapping a value type (e.g. any sort of struct) in a reference type (i.e. a class).
final private class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
| mit |
Josscii/iOS-Demos | UIWebViewProgressDemo/UIWebViewProgressDemo/ProgressView.swift | 1 | 2408 | //
// ProgressView.swift
// UIWebViewProgressDemo
//
// Created by Josscii on 2017/8/6.
// Copyright © 2017年 Josscii. All rights reserved.
//
import UIKit
class ProgressView: UIView {
var progressLayer: CAShapeLayer!
var progressPath: UIBezierPath!
override init(frame: CGRect) {
super.init(frame: frame)
progressLayer = CAShapeLayer()
progressLayer.frame = bounds
progressLayer.strokeColor = UIColor.red.cgColor
progressLayer.lineWidth = 2
progressLayer.strokeEnd = 0
let path = UIBezierPath()
path.move(to: .zero)
path.addLine(to: CGPoint(x: progressLayer.bounds.maxX, y: 0))
progressLayer.path = path.cgPath
layer.addSublayer(progressLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startAnimation() {
if (progressLayer.animation(forKey: "start") != nil) ||
(progressLayer.animation(forKey: "finish") != nil) {
return
}
progressLayer.strokeEnd = 0
progressLayer.opacity = 1
let keyFrameAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
keyFrameAnimation.values = [0, 0.5, 0.8]
keyFrameAnimation.keyTimes = [0, 0.4, 1]
keyFrameAnimation.duration = 10
keyFrameAnimation.isRemovedOnCompletion = false
keyFrameAnimation.fillMode = "forwards"
progressLayer.add(keyFrameAnimation, forKey: "start")
}
func finishAnimation() {
if (progressLayer.animation(forKey: "finish") != nil) {
return
}
progressLayer.strokeEnd = (progressLayer.presentation()! as CAShapeLayer).strokeEnd
progressLayer.removeAnimation(forKey: "start")
let anim = CABasicAnimation(keyPath: "strokeEnd")
anim.toValue = 1
anim.duration = 0.3
anim.isRemovedOnCompletion = false
anim.fillMode = "forwards"
anim.delegate = self
progressLayer.add(anim, forKey: "finish")
}
}
extension ProgressView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
progressLayer.strokeEnd = 1
progressLayer.removeAnimation(forKey: "finish")
progressLayer.opacity = 0
}
}
| mit |
cliffano/swaggy-jenkins | clients/swift5/generated/OpenAPIClient/Classes/OpenAPIs/Models/PipelineBranchesitem.swift | 1 | 2509 | //
// PipelineBranchesitem.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
public struct PipelineBranchesitem: Codable, JSONEncodable, Hashable {
public var displayName: String?
public var estimatedDurationInMillis: Int?
public var name: String?
public var weatherScore: Int?
public var latestRun: PipelineBranchesitemlatestRun?
public var organization: String?
public var pullRequest: PipelineBranchesitempullRequest?
public var totalNumberOfPullRequests: Int?
public var _class: String?
public init(displayName: String? = nil, estimatedDurationInMillis: Int? = nil, name: String? = nil, weatherScore: Int? = nil, latestRun: PipelineBranchesitemlatestRun? = nil, organization: String? = nil, pullRequest: PipelineBranchesitempullRequest? = nil, totalNumberOfPullRequests: Int? = nil, _class: String? = nil) {
self.displayName = displayName
self.estimatedDurationInMillis = estimatedDurationInMillis
self.name = name
self.weatherScore = weatherScore
self.latestRun = latestRun
self.organization = organization
self.pullRequest = pullRequest
self.totalNumberOfPullRequests = totalNumberOfPullRequests
self._class = _class
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case displayName
case estimatedDurationInMillis
case name
case weatherScore
case latestRun
case organization
case pullRequest
case totalNumberOfPullRequests
case _class
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(displayName, forKey: .displayName)
try container.encodeIfPresent(estimatedDurationInMillis, forKey: .estimatedDurationInMillis)
try container.encodeIfPresent(name, forKey: .name)
try container.encodeIfPresent(weatherScore, forKey: .weatherScore)
try container.encodeIfPresent(latestRun, forKey: .latestRun)
try container.encodeIfPresent(organization, forKey: .organization)
try container.encodeIfPresent(pullRequest, forKey: .pullRequest)
try container.encodeIfPresent(totalNumberOfPullRequests, forKey: .totalNumberOfPullRequests)
try container.encodeIfPresent(_class, forKey: ._class)
}
}
| mit |
smoope/ios-sdk | Pod/Classes/SPInvitationList.swift | 1 | 901 | /*
* Copyright 2016 smoope GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class SPInvitationList: SPPagedList<SPInvitation> {
public required init(data: [String: AnyObject]) {
super.init(data: data)
self.content = (data["_embedded"]!["invitations"] as! [AnyObject])
.map { v in
SPInvitation(data: v as! [String: AnyObject])
}
}
} | apache-2.0 |
samodom/UIKitSwagger | UIKitSwaggerTests/Tests/GestureRecognizerEnablingTests.swift | 1 | 1269 | //
// GestureRecognizerEnablingTests.swift
// UIKitSwagger
//
// Created by Sam Odom on 12/6/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import UIKit
import XCTest
class GestureRecognizerEnablingTests: XCTestCase {
var enabledRecognizer = UITapGestureRecognizer()
var disabledRecognizer = UIRotationGestureRecognizer()
override func setUp() {
super.setUp()
enabledRecognizer.enabled = true
disabledRecognizer.enabled = false
}
func testEnablingDisabledGestureRecognizer() {
disabledRecognizer.enable()
XCTAssertTrue(disabledRecognizer.enabled, "The disabled recognizer should be enabled")
}
func testNotDisablingEnabledGestureRecognizer() {
enabledRecognizer.enable()
XCTAssertTrue(enabledRecognizer.enabled, "The enabled recognizer should not be disabled")
}
func testDisablingEnabledGestureRecognizer() {
enabledRecognizer.disable()
XCTAssertFalse(enabledRecognizer.enabled, "The enabled recognizer should be disabled")
}
func testNotEnablingDisabledGestureRecognizer() {
disabledRecognizer.disable()
XCTAssertFalse(disabledRecognizer.enabled, "The disabled recognizer should not be enabled")
}
}
| mit |
bitjammer/swift | test/IRGen/type_layout_objc.swift | 1 | 3641 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
import Foundation
class C {}
class O: NSObject {}
struct SSing { var x: Int64 }
struct SMult { var x, y: Int64 }
struct SMult2 { var x, y: C }
struct SMult3 { var x, y: C }
struct GSing<T> { var x: T }
struct GMult<T> { var x, y: T }
enum ESing { case X(Int64) }
enum EMult { case X(Int64), Y(Int64) }
@_alignment(4)
struct CommonLayout { var x,y,z,w: Int8 }
// CHECK: @_T016type_layout_objc14TypeLayoutTestVMP = hidden global {{.*}} @create_generic_metadata_TypeLayoutTest
// CHECK: define private %swift.type* @create_generic_metadata_TypeLayoutTest
struct TypeLayoutTest<T> {
// -- dynamic layout, projected from metadata
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1
// CHECK: [[T_VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]]
// CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 17
// CHECK: store i8** [[T_LAYOUT]]
var z: T
// -- native class, use standard NativeObject value witness
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_T0BoWV, i32 17)
var a: C
// -- ObjC class, use standard UnknownObject value witness
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_T0BOWV, i32 17)
var b: O
// -- Single-element struct, shares layout of its field (Builtin.Int64)
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_T0Bi64_WV, i32 17)
var c: SSing
// -- Multi-element structs use open-coded layouts
// CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_16_8_0_pod, i32 0, i32 0)
var d: SMult
// CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_7fffffff_bt, i32 0, i32 0)
// CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_1000_bt, i32 0, i32 0)
var e: SMult2
// CHECK-64: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_16_8_7fffffff_bt, i32 0, i32 0)
// CHECK-32: store i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @type_layout_8_4_1000_bt, i32 0, i32 0)
var f: SMult3
// -- Single-case enum, shares layout of its field (Builtin.Int64)
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_T0Bi64_WV, i32 17)
var g: ESing
// -- Multi-case enum, open-coded layout
// CHECK: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @type_layout_9_8_0_pod, i32 0, i32 0)
var h: EMult
// -- Single-element generic struct, shares layout of its field (T)
// CHECK: [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE_WITNESSES]], i32 17
// CHECK: store i8** [[T_LAYOUT]]
var i: GSing<T>
// -- Multi-element generic struct, need to derive from metadata
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T016type_layout_objc5GMultVMa(%swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], {{i32|i64}} -1
// CHECK: [[VALUE_WITNESSES:%.*]] = load i8**, i8*** [[T1]]
// CHECK: [[LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[VALUE_WITNESSES]], i32 17
// CHECK: store i8** [[LAYOUT]]
var j: GMult<T>
// -- Common layout, reuse common value witness table layout
// CHECK: store i8** getelementptr (i8*, i8** @_T0Bi32_WV, i32 17)
var k: CommonLayout
}
| apache-2.0 |
nicksweet/Clink | Clink/Classes/Clink.swift | 1 | 16539 | //
// Clink.swift
// clink
//
// Created by Nick Sweet on 6/16/17.
//
import Foundation
import CoreBluetooth
public class Clink: NSObject, BluetoothStateManager {
static public let shared = Clink()
public var connectedPeerIds: [String] {
return self.centralManager.retrieveConnectedPeripherals(withServices: [CBUUID(string: clinkServiceId)]).map {
$0.identifier.uuidString
}
}
fileprivate var activePeripherals: [CBPeripheral] = []
fileprivate var activePairingTasks = [PairingTask]()
fileprivate var notificationHandlers = [UUID: NotificationHandler]()
fileprivate var propertyDescriptors = [PropertyDescriptor]()
fileprivate var activeReadRequests = [CBUUID: Data]()
fileprivate var readOperations = [ReadOperation]()
fileprivate var writeOperations = [WriteOperation]()
fileprivate var service = CBMutableService(type: CBUUID(string: clinkServiceId), primary: true)
fileprivate lazy var centralManager: CBCentralManager = {
return CBCentralManager(delegate: self, queue: Clink.Configuration.dispatchQueue)
}()
fileprivate lazy var peripheralManager: CBPeripheralManager = {
return CBPeripheralManager(delegate: self, queue: Clink.Configuration.dispatchQueue)
}()
// MARK: - STATIC PEER CRUD METHODS
/**
Update the value for the given property name of the local peer.
Updating local peer attributes via this method will subsequently invoke any registered notification handlers
on paired connected remote peers with a notification of case `.updated` and the peers ID as an associated type.
- parameters:
- value: The new property value of the local peer
- property: The name of the local peer property to set as a string
*/
public static func set(value: Any, forProperty property: Clink.PeerPropertyKey) {
Clink.shared.once(manager: Clink.shared.peripheralManager, hasState: .poweredOn, invoke: { res in
if case let .error(err) = res { return print(err) }
if
let propertyDescriptorIndex = Clink.shared.propertyDescriptors.index(where: { $0.name == property }),
let propertyDescriptor = Clink.shared.propertyDescriptors.filter({ $0.name == property }).first,
let serviceChars = Clink.shared.service.characteristics as? [CBMutableCharacteristic],
let char = serviceChars.filter({ $0.uuid.uuidString == propertyDescriptor.characteristicId }).first
{
Clink.shared.propertyDescriptors[propertyDescriptorIndex] = PropertyDescriptor(
name: property,
value: value,
characteristicId: char.uuid.uuidString
)
let writeOperation = WriteOperation(
propertyDescriptor: Clink.shared.propertyDescriptors[propertyDescriptorIndex],
characteristicId: char.uuid.uuidString)
Clink.shared.writeOperations.append(writeOperation)
Clink.shared.resumeWriteOperations()
} else {
var chars = Clink.shared.service.characteristics ?? [CBCharacteristic]()
let charId = CBUUID(string: UUID().uuidString)
let char = CBMutableCharacteristic(type: charId, properties: .notify, value: nil, permissions: .readable)
let service = CBMutableService(type: CBUUID(string: clinkServiceId), primary: true)
let propertyDescriptor = PropertyDescriptor(
name: property,
value: value,
characteristicId: charId.uuidString
)
chars.append(char)
service.characteristics = chars
guard let charIdData = charId.uuidString.data(using: .utf8) else { return }
Clink.shared.service = service
Clink.shared.propertyDescriptors.append(propertyDescriptor)
Clink.shared.peripheralManager.removeAllServices()
Clink.shared.peripheralManager.add(service)
}
})
}
public static func get<T: ClinkPeer>(peerWithId peerId: String) -> T? {
return Clink.Configuration.peerManager.getPeer(withId: peerId)
}
public static func get(peerWithId peerId: String) -> Clink.DefaultPeer? {
return Clink.Configuration.peerManager.getPeer(withId: peerId)
}
public static func delete(peerWithId peerId: String) {
Clink.Configuration.peerManager.delete(peerWithId: peerId)
}
// MARK: - PRIVATE METHODS
fileprivate func connect(peerWithId peerId: String) {
Clink.Configuration.dispatchQueue.async {
if
let uuid = UUID(uuidString: peerId),
let i = self.activePeripherals.index(where: { $0.identifier == uuid }),
self.activePeripherals[i].state == .connected
{
return
}
guard
let peripheralId = UUID(uuidString: peerId),
let peripheral = self.centralManager.retrievePeripherals(withIdentifiers: [peripheralId]).first
else { return }
peripheral.delegate = self
if let i = self.activePeripherals.index(where: { $0.identifier.uuidString == peerId }) {
self.activePeripherals[i] = peripheral
} else {
self.activePeripherals.append(peripheral)
}
self.centralManager.connect(peripheral, options: nil)
}
}
private func connectKnownPeers() {
self.once(manager: centralManager, hasState: .poweredOn, invoke: { result in
switch result {
case .error(let err):
self.publish(notification: .error(err))
case .success:
for peripheralId in Clink.Configuration.peerManager.getKnownPeerIds() {
self.connect(peerWithId: peripheralId)
}
}
})
}
fileprivate func resumeWriteOperations() {
Clink.Configuration.dispatchQueue.async {
var successfull = true
while successfull {
guard
let writeOperation = self.writeOperations.first,
let chars = self.service.characteristics,
let char = chars.filter({ $0.uuid.uuidString == writeOperation.characteristicId }).first as? CBMutableCharacteristic
else {
break
}
if let packet = writeOperation.nextPacket() {
successfull = self.peripheralManager.updateValue(
packet,
for: char,
onSubscribedCentrals: writeOperation.centrals)
if successfull {
writeOperation.removeFirstPacketFromQueue()
}
} else {
self.writeOperations.removeFirst()
}
}
}
}
fileprivate func publish(notification: Clink.Notification) {
Clink.Configuration.dispatchQueue.async {
for (_, handler) in self.notificationHandlers {
handler(notification)
}
}
}
// MARK: - PUBLIC METHODS
override private init() {
super.init()
once(manager: peripheralManager, hasState: .poweredOn, invoke: { result in
switch result {
case .error(let err): self.publish(notification: .error(err))
case .success:
self.peripheralManager.add(self.service)
self.connectKnownPeers()
}
})
}
/**
Calling this method will cause Clink to begin scanning for eligible peers.
When the first eligible peer is found, Clink will attempt to connect to it, archive it if successfull,
and call any registered notification handlers passing a notification of case `.discovered(ClinkPeer)
with the discovered peer as an associated type. Clink will then attempt to maintain
a connection to the discovered peer when ever it is in range, handeling reconnects automatically.
For a remote peer to become eligible for discovery, it must also be scanning and in close physical proximity
(a few inches)
*/
public func startClinking() {
let task = PairingTask()
task.delegate = self
task.startPairing()
activePairingTasks.append(task)
}
public func stopClinking() {
for task in activePairingTasks {
task.delegate = nil
task.cancelPairing()
}
activePairingTasks.removeAll()
}
public func addNotificationHandler(_ handler: @escaping Clink.NotificationHandler) -> Clink.NotificationRegistrationToken {
let token = NotificationRegistrationToken()
let connectedPeerIds = self.centralManager.retrieveConnectedPeripherals(withServices: [self.service.uuid]).map { $0.identifier.uuidString }
notificationHandlers[token] = handler
handler(.initial(connectedPeerIds: connectedPeerIds))
return token
}
public func removeNotificationHandler(forToken token: Clink.NotificationRegistrationToken) {
notificationHandlers.removeValue(forKey: token)
}
}
// MARK: - PERIPHERAL MANAGER DELEGATE METHODS
extension Clink: CBPeripheralDelegate {
public final func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
peripheral.discoverServices([self.service.uuid])
}
public final func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if error != nil { self.publish(notification: .error(.unknownError("\(#function) error"))) }
guard let services = peripheral.services else { return }
for service in services where service.uuid == self.service.uuid {
peripheral.discoverCharacteristics(nil, for: service)
}
}
public final func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if error != nil { self.publish(notification: .error(.unknownError("\(#function) error"))) }
guard let characteristics = service.characteristics, service.uuid == self.service.uuid else { return }
for characteristic in characteristics {
peripheral.setNotifyValue(characteristic.properties == .notify, for: characteristic)
}
}
public final func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard let dataValue = characteristic.value, characteristic.service.uuid.uuidString == clinkServiceId else { return }
let readOperation: ReadOperation
if let operation = self.readOperations.filter({ $0.characteristic == characteristic && $0.peripheral == peripheral}).first {
readOperation = operation
} else {
readOperation = ReadOperation(peripheral: peripheral, characteristic: characteristic)
readOperation.delegate = self
self.readOperations.append(readOperation)
}
readOperation.append(packet: dataValue)
}
}
// MARK: - CENTRAL MANAGER DELEGATE METHODS
extension Clink: CBCentralManagerDelegate {
public final func centralManagerDidUpdateState(_ central: CBCentralManager) {
// required central manager delegate method. do nothing.
}
public final func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([self.service.uuid])
publish(notification: .connected(peerWithId: peripheral.identifier.uuidString))
}
public final func centralManager(
_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?)
{
if error != nil { self.publish(notification: .error(.unknownError("ERROR: \(#function)"))) }
let peerId = peripheral.identifier.uuidString
self.publish(notification: .disconnected(peerWithId: peerId))
self.connect(peerWithId: peerId)
}
public final func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
if error != nil { self.publish(notification: .error(.unknownError("ERROR: \(#function)"))) }
peripheral.delegate = self
if let i = self.activePeripherals.index(where: { $0.identifier == peripheral.identifier }) {
self.activePeripherals[i] = peripheral
} else {
self.activePeripherals.append(peripheral)
}
self.centralManager.connect(peripheral, options: nil)
}
}
// MARK: - PERIPHERAL MANAGER DELEGATE METHODS
extension Clink: CBPeripheralManagerDelegate {
public final func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
// required peripheral manager delegate method. do nothing.
}
public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
print("did subscribe")
guard let prop = propertyDescriptors.filter({ $0.characteristicId == characteristic.uuid.uuidString }).first else { return }
let writeOperation = WriteOperation(propertyDescriptor: prop, characteristicId: characteristic.uuid.uuidString)
writeOperation.centrals = [central]
writeOperations.append(writeOperation)
resumeWriteOperations()
}
public final func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
resumeWriteOperations()
}
}
// MARK: - PAIRING TASK DELEGATE METHODS
extension Clink: PairingTaskDelegate {
func pairingTask(_ task: PairingTask, didFinishPairingWithPeripheral peripheral: CBPeripheral) {
Clink.Configuration.dispatchQueue.async {
task.delegate = nil
let peerId = peripheral.identifier.uuidString
if let i = self.activePairingTasks.index(of: task) {
self.activePairingTasks.remove(at: i)
}
Clink.Configuration.peerManager.createPeer(withId: peerId)
self.publish(notification: .clinked(peerWithId: peerId))
self.connect(peerWithId: peerId)
}
}
func pairingTask(_ task: PairingTask, didCatchError error: Clink.OpperationError) {
task.delegate = nil
if let i = self.activePairingTasks.index(of: task) {
self.activePairingTasks.remove(at: i)
}
self.publish(notification: .error(error))
}
}
extension Clink: ReadOperationDelegate {
func readOperation(operation: ReadOperation, didFailWithError error: ReadOperationError) {
switch error {
case .couldNotParsePropertyDescriptor: print("couldNotParsePropertyDescriptor")
case .noPacketsRecieved: print("no packets recieved")
}
if let i = readOperations.index(of: operation) {
readOperations.remove(at: i)
}
}
func readOperation(operation: ReadOperation, didCompleteWithPropertyDescriptor descriptor: PropertyDescriptor) {
Clink.Configuration.peerManager.update(
value: descriptor.value,
forKey: descriptor.name,
ofPeerWithId: operation.peripheral.identifier.uuidString)
if let i = readOperations.index(of: operation) {
readOperations.remove(at: i)
}
self.publish(notification: .updated(
value: descriptor.value,
key: descriptor.name,
peerId: operation.peripheral.identifier.uuidString))
}
}
| mit |
tinysun212/swift-windows | test/Constraints/optional.swift | 1 | 7139 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
func markUsed<T>(_ t: T) {}
class A {
@objc func do_a() {}
@objc(do_b_2:) func do_b(_ x: Int) {}
@objc func do_b(_ x: Float) {}
@objc func do_c(x: Int) {}
@objc func do_c(y: Int) {}
}
func test0(_ a: AnyObject) {
a.do_a?()
a.do_b?(1)
a.do_b?(5.0)
a.do_c?(1) // expected-error {{cannot invoke value of function type with argument list '(Int)'}}
a.do_c?(x: 1)
}
func test1(_ a: A) {
a?.do_a() // expected-error {{cannot use optional chaining on non-optional value of type 'A'}} {{4-5=}}
a!.do_a() // expected-error {{cannot force unwrap value of non-optional type 'A'}} {{4-5=}}
// Produce a specialized diagnostic here?
a.do_a?() // expected-error {{cannot use optional chaining on non-optional value of type '() -> ()'}} {{9-10=}}
}
// <rdar://problem/15508756>
extension Optional {
func bind<U>(_ f: (Wrapped) -> U?) -> U? {
switch self {
case .some(let x):
return f(x)
case .none:
return .none
}
}
}
var c: String? = Optional<Int>(1)
.bind {(x: Int) in markUsed("\(x)!"); return "two" }
func test4() {
func foo() -> Int { return 0 }
func takes_optfn(_ f : () -> Int?) -> Int? { return f() }
_ = takes_optfn(foo)
func takes_objoptfn(_ f : () -> AnyObject?) -> AnyObject? { return f() }
func objFoo() -> AnyObject { return A() }
_ = takes_objoptfn(objFoo) // okay
func objBar() -> A { return A() }
_ = takes_objoptfn(objBar) // okay
}
func test5() -> Int? {
return nil
}
func test6<T>(_ x : T) {
// FIXME: this code should work; T could be Int? or Int??
// or something like that at runtime. rdar://16374053
_ = x as? Int? // expected-error {{cannot downcast from 'T' to a more optional type 'Int?'}}
}
class B : A { }
func test7(_ x : A) {
_ = x as? B? // expected-error{{cannot downcast from 'A' to a more optional type 'B?'}}
}
func test8(_ x : AnyObject?) {
let _ : A = x as! A
}
// Partial ordering with optionals
func test9_helper<T>(_ x: T) -> Int { }
func test9_helper<T>(_ x: T?) -> Double { }
func test9(_ i: Int, io: Int?) {
let result = test9_helper(i)
var _: Int = result
let result2 = test9_helper(io)
let _: Double = result2
}
protocol P { }
func test10_helper<T : P>(_ x: T) -> Int { }
func test10_helper<T : P>(_ x: T?) -> Double { }
extension Int : P { }
func test10(_ i: Int, io: Int?) {
let result = test10_helper(i)
var _: Int = result
let result2 = test10_helper(io)
var _: Double = result2
}
var z: Int? = nil
z = z ?? 3
var fo: Float? = 3.14159
func voidOptional(_ handler: () -> ()?) {}
func testVoidOptional() {
let noop: () -> Void = {}
voidOptional(noop)
let optNoop: (()?) -> ()? = { return $0 }
voidOptional(optNoop)
}
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func testTernaryWithNil<T>(b: Bool, s: String, i: Int, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let t1 = b ? s : nil
let _: Double = t1 // expected-error{{value of type 'String?'}}
let t2 = b ? nil : i
let _: Double = t2 // expected-error{{value of type 'Int?'}}
let t3 = b ? "hello" : nil
let _: Double = t3 // expected-error{{value of type 'String?'}}
let t4 = b ? nil : 1
let _: Double = t4 // expected-error{{value of type 'Int?'}}
let t5 = b ? (s, i) : nil
let _: Double = t5 // expected-error{{value of type '(String, Int)?}}
let t6 = b ? nil : (i, s)
let _: Double = t6 // expected-error{{value of type '(Int, String)?}}
let t7 = b ? ("hello", 1) : nil
let _: Double = t7 // expected-error{{value of type '(String, Int)?}}
let t8 = b ? nil : (1, "hello")
let _: Double = t8 // expected-error{{value of type '(Int, String)?}}
let t9 = b ? { $0 * 2 } : nil
let _: Double = t9 // expected-error{{value of type '((Int) -> Int)?}}
let t10 = b ? nil : { $0 * 2 }
let _: Double = t10 // expected-error{{value of type '((Int) -> Int)?}}
let t11 = b ? a : nil
let _: Double = t11 // expected-error{{value of type 'Any?'}}
let t12 = b ? nil : a
let _: Double = t12 // expected-error{{value of type 'Any?'}}
let t13 = b ? t : nil
let _: Double = t13 // expected-error{{value of type 'T?'}}
let t14 = b ? nil : t
let _: Double = t14 // expected-error{{value of type 'T?'}}
let t15 = b ? m : nil
let _: Double = t15 // expected-error{{value of type 'T.Type?'}}
let t16 = b ? nil : m
let _: Double = t16 // expected-error{{value of type 'T.Type?'}}
let t17 = b ? p : nil
let _: Double = t17 // expected-error{{value of type '(Proto1 & Proto2)?'}}
let t18 = b ? nil : p
let _: Double = t18 // expected-error{{value of type '(Proto1 & Proto2)?'}}
let t19 = b ? arr : nil
let _: Double = t19 // expected-error{{value of type '[Int]?'}}
let t20 = b ? nil : arr
let _: Double = t20 // expected-error{{value of type '[Int]?'}}
let t21 = b ? opt : nil
let _: Double = t21 // expected-error{{value of type 'Int?'}}
let t22 = b ? nil : opt
let _: Double = t22 // expected-error{{value of type 'Int?'}}
let t23 = b ? iou : nil
let _: Double = t23 // expected-error{{value of type 'Int?'}}
let t24 = b ? nil : iou
let _: Double = t24 // expected-error{{value of type 'Int?'}}
let t25 = b ? n : nil
let _: Double = t25 // expected-error{{value of type 'Nilable'}}
let t26 = b ? nil : n
let _: Double = t26 // expected-error{{value of type 'Nilable'}}
}
// inference with IUOs
infix operator ++++
protocol PPPP {
static func ++++(x: Self, y: Self) -> Bool
}
func compare<T: PPPP>(v: T, u: T!) -> Bool {
return v ++++ u
}
func sr2752(x: String?, y: String?) {
_ = x.map { xx in
y.map { _ in "" } ?? "\(xx)"
}
}
// SR-3248 - Invalid diagnostic calling implicitly unwrapped closure
var sr3248 : ((Int) -> ())!
sr3248?(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
sr3248!(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
sr3248(a: 2) // expected-error {{extraneous argument label 'a:' in call}}
struct SR_3248 {
var callback: (([AnyObject]) -> Void)!
}
SR_3248().callback?("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
SR_3248().callback!("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
SR_3248().callback("test") // expected-error {{cannot convert value of type 'String' to expected argument type '[AnyObject]'}}
_? = nil // expected-error {{'nil' requires a contextual type}}
_?? = nil // expected-error {{'nil' requires a contextual type}}
// rdar://problem/29993596
func takeAnyObjects(_ lhs: AnyObject?, _ rhs: AnyObject?) { }
infix operator !====
func !====(_ lhs: AnyObject?, _ rhs: AnyObject?) -> Bool { return false }
func testAnyObjectImplicitForce(lhs: AnyObject?!, rhs: AnyObject?) {
if lhs !==== rhs { }
takeAnyObjects(lhs, rhs)
}
// SR-4056
protocol P1 { }
class C1: P1 { }
protocol P2 {
var prop: C1? { get }
}
class C2 {
var p1: P1?
var p2: P2?
var computed: P1? {
return p1 ?? p2?.prop
}
}
| apache-2.0 |
ccloveswift/CLSCommon | Classes/Core/extension_CGSize.swift | 1 | 1364 | //
// extension_CGSize.swift
// Pods
//
// Created by Cc on 2017/8/25.
//
//
import Foundation
public extension CGSize {
/// 当前的size 适配到preview size上,如果size 远小于preview size 不放大
///
/// - Parameter previewSize: 需要显示的大小
/// - Returns: 合适的size
public func e_GetMaxFullSize(previewSize: CGSize) -> CGSize {
// 图片size 比例
let OrgImgBiLi: CGFloat = self.width / self.height // 1 / 2
let previewBiLi: CGFloat = previewSize.width / previewSize.height // 2 / 1
if OrgImgBiLi > previewBiLi {
// 宽缩放到相等
let newW = self.width > previewSize.width ? previewSize.width : self.width
let newH = newW / OrgImgBiLi
return CGSize(width: newW, height: newH)
}
else if OrgImgBiLi < previewBiLi {
// 高缩放到相等
let newH = self.height > previewSize.height ? previewSize.height : self.height
let newW = OrgImgBiLi * newH
return CGSize(width: newW, height: newH)
}
else {
// 相等
if (self.width > previewSize.width) {
return previewSize
}
else {
return self
}
}
}
}
| mit |
MessageKit/MessageKit | Example/Sources/Models/MockUser.swift | 1 | 1261 | // MIT License
//
// Copyright (c) 2017-2019 MessageKit
//
// 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 MessageKit
struct MockUser: SenderType, Equatable {
var senderId: String
var displayName: String
}
| mit |
PureSwift/GATT | Sources/DarwinGATT/Extensions/Integer.swift | 1 | 443 | //
// Integer.swift
// GATT
//
// Created by Alsey Coleman Miller on 8/24/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
internal extension UInt16 {
/// Initializes value from two bytes.
init(bytes: (UInt8, UInt8)) {
self = unsafeBitCast(bytes, to: UInt16.self)
}
/// Converts to two bytes.
var bytes: (UInt8, UInt8) {
return unsafeBitCast(self, to: (UInt8, UInt8).self)
}
}
| mit |
bgerstle/wikipedia-ios | Wikipedia/Code/SDImageCache+PromiseKit.swift | 1 | 1871 | //
// SDImageCache+PromiseKit.swift
// Wikipedia
//
// Created by Brian Gerstle on 7/1/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import Foundation
import PromiseKit
import SDWebImage
public typealias DiskQueryResult = (cancellable: Cancellable?, promise: Promise<(UIImage, ImageOrigin)>)
extension SDImageCache {
public func queryDiskCacheForKey(key: String) -> DiskQueryResult {
let (promise, fulfill, reject) = Promise<(UIImage, ImageOrigin)>.pendingPromise()
// queryDiskCache will return nil if the image is in memory
let diskQueryOperation: NSOperation? = self.queryDiskCacheForKey(key, done: { image, cacheType -> Void in
if image != nil {
fulfill((image, asImageOrigin(cacheType)))
} else {
reject(WMFImageControllerError.DataNotFound)
}
})
if let diskQueryOperation = diskQueryOperation {
// make sure promise is rejected if the operation is cancelled
self.KVOController.observe(diskQueryOperation,
keyPath: "isCancelled",
options: NSKeyValueObservingOptions.New)
{ _, _, change in
let value = change[NSKeyValueChangeNewKey] as! NSNumber
if value.boolValue {
reject(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
}
}
// tear down observation when operation finishes
self.KVOController.observe(diskQueryOperation,
keyPath: "isFinished",
options: NSKeyValueObservingOptions())
{ [weak self] _, object, _ in
self?.KVOController.unobserve(object)
}
}
return (diskQueryOperation, promise)
}
}
| mit |
taiphamtiki/TikiTool | TikiTool/Box/BoxViewModel.swift | 1 | 767 | //
// BoxViewModel.swift
// TikiTool
//
// Created by ZickOne on 2/7/17.
// Copyright © 2017 ZickOne. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Firebase
class BoxViewModel {
var segmentObsever : Observable<[BoxItem]>!
var boxs = [BoxItem]()
init() {
setup()
}
func setup()
{
self.segmentObsever = createListBoxObssever()
}
func createListBoxObssever() -> Observable<[BoxItem]> {
return Observable.create { observer in
APIManager.shareInstance.getListBox(onCompletion: { (listBox) in
observer.onNext(listBox)
self.boxs = listBox
observer.onCompleted()
})
return Disposables.create()
}
}
}
| mit |
clappr/clappr-ios | Tests/Extensions/UIImageViewTests.swift | 1 | 3029 | import Quick
import Nimble
import OHHTTPStubs
@testable import Clappr
class UIImageViewTests: QuickSpec {
override func spec() {
describe(".UIImageViewTests") {
describe("get image from url") {
beforeEach {
OHHTTPStubs.removeAllStubs()
}
context("when the response is 200") {
beforeEach {
stub(condition: isExtension("png") && isHost("test200")) { _ in
let image = UIImage(named: "poster", in: Bundle(for: UIImageViewTests.self), compatibleWith: nil)!
let data = image.pngData()
return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: ["Content-Type":"image/png"])
}
}
it("sets image") {
let url = URL(string: "https://test200/poster.png")
let imageView = UIImageView()
imageView.setImage(from: url!)
expect(imageView.image).toEventuallyNot(beNil())
}
}
context("when the response is different of 200") {
beforeEach {
stub(condition: isExtension("png") && isHost("test400")) { _ in
return OHHTTPStubsResponse(data: Data(), statusCode: 400, headers: [:])
}
}
it("doesn't set image") {
let url = URL(string: "https://test400/poster.png")
let imageView = UIImageView()
imageView.setImage(from: url!)
expect(imageView.image).toEventually(beNil())
}
}
context("when repeat the same request") {
var requestCount: Int!
beforeEach {
requestCount = 0
stub(condition: isExtension("png") && isHost("test.io")) { _ in
requestCount += 1
let image = UIImage(named: "poster", in: Bundle(for: UIImageViewTests.self), compatibleWith: nil)!
let data = image.pngData()
return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: ["Content-Type":"image/png"])
}
}
it("uses image from cache") {
let url = URL(string: "https://test.io/poster.png")
let imageView = UIImageView()
imageView.setImage(from: url!)
expect(imageView.image).toEventuallyNot(beNil())
imageView.setImage(from: url!)
expect(requestCount).to(equal(1))
}
}
}
}
}
}
| bsd-3-clause |
SoneeJohn/WWDC | CommunitySupport/CMSSubscriptionManager.swift | 1 | 494 | //
// CMSSubscriptionManager.swift
// WWDC
//
// Created by Guilherme Rambo on 15/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import CloudKit
internal final class CMSSubscriptionManager {
private let defaults = UserDefaults.standard
var profileSubscriptionCreated: Bool {
get {
return defaults.bool(forKey: #function)
}
set {
defaults.set(newValue, forKey: #function)
}
}
}
| bsd-2-clause |
fancymax/12306ForMac | 12306ForMac/UserControls/TrainTableRowView.swift | 1 | 765 | //
// TrainTableRowView.swift
// 12306ForMac
//
// Created by fancymax on 16/6/10.
// Copyright © 2016年 fancy. All rights reserved.
//
import Cocoa
class TrainTableRowView: NSTableRowView {
override var isOpaque: Bool {
return false
}
override var isSelected: Bool {
didSet {
updateSubviewsInterestedInSelectionState()
}
}
fileprivate func updateSubviewsInterestedInSelectionState() {
guard subviews.count > 0 else { return }
for view in subviews {
if view.isKind(of: TrainTableCellView.self) {
let stationCellView = view as! TrainTableCellView
stationCellView.selected = isSelected
}
}
}
}
| mit |
rudkx/swift | test/ModuleInterface/features.swift | 1 | 6452 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck -swift-version 5 -module-name FeatureTest -emit-module-interface-path - -enable-library-evolution -disable-availability-checking %s | %FileCheck %s
// REQUIRES: concurrency
// REQUIRES: concurrency
// Ensure that when we emit a Swift interface that makes use of new features,
// the uses of those features are guarded by appropriate #if's that allow older
// compilers to skip over the uses of newer features.
// CHECK: #if compiler(>=5.3) && $SpecializeAttributeWithAvailability
// CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 12; where T == Swift.Int)
// CHECK: public func specializeWithAvailability<T>(_ t: T)
// CHECK: #else
// CHECK: public func specializeWithAvailability<T>(_ t: T)
// CHECK: #endif
@_specialize(exported: true, availability: macOS 12, *; where T == Int)
public func specializeWithAvailability<T>(_ t: T) {
}
// CHECK: #if compiler(>=5.3) && $Actors
// CHECK-NEXT: public actor MyActor
// CHECK: @_semantics("defaultActor") nonisolated final public var unownedExecutor: _Concurrency.UnownedSerialExecutor {
// CHECK-NEXT: get
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: #endif
public actor MyActor {
}
// CHECK: #if compiler(>=5.3) && $Actors
// CHECK-NEXT: extension FeatureTest.MyActor
public extension MyActor {
// CHECK-NOT: $Actors
// CHECK: testFunc
func testFunc() async { }
// CHECK: }
// CHECK-NEXT: #endif
}
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: globalAsync
// CHECK-NEXT: #endif
public func globalAsync() async { }
// CHECK: @_marker public protocol MP {
// CHECK-NEXT: }
@_marker public protocol MP { }
// CHECK: @_marker public protocol MP2 : FeatureTest.MP {
// CHECK-NEXT: }
@_marker public protocol MP2: MP { }
// CHECK-NOT: #if compiler(>=5.3) && $MarkerProtocol
// CHECK: public protocol MP3 : AnyObject, FeatureTest.MP {
// CHECK-NEXT: }
public protocol MP3: AnyObject, MP { }
// CHECK: extension FeatureTest.MP2 {
// CHECK-NEXT: func inMP2
extension MP2 {
public func inMP2() { }
}
// CHECK: class OldSchool : FeatureTest.MP {
public class OldSchool: MP {
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: takeClass()
// CHECK-NEXT: #endif
public func takeClass() async { }
}
// CHECK: class OldSchool2 : FeatureTest.MP {
public class OldSchool2: MP {
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: takeClass()
// CHECK-NEXT: #endif
public func takeClass() async { }
}
// CHECK: #if compiler(>=5.3) && $RethrowsProtocol
// CHECK-NEXT: @rethrows public protocol RP
@rethrows public protocol RP {
func f() throws -> Bool
}
// CHECK: public struct UsesRP {
public struct UsesRP {
// CHECK: #if compiler(>=5.3) && $RethrowsProtocol
// CHECK-NEXT: public var value: FeatureTest.RP? {
// CHECK-NOT: #if compiler(>=5.3) && $RethrowsProtocol
// CHECK: get
public var value: RP? {
nil
}
}
// CHECK: #if compiler(>=5.3) && $RethrowsProtocol
// CHECK-NEXT: public struct IsRP
public struct IsRP: RP {
// CHECK-NEXT: public func f()
public func f() -> Bool { }
// CHECK-NOT: $RethrowsProtocol
// CHECK-NEXT: public var isF:
// CHECK-NEXT: get
public var isF: Bool {
f()
}
}
// CHECK: #if compiler(>=5.3) && $RethrowsProtocol
// CHECK-NEXT: public func acceptsRP
public func acceptsRP<T: RP>(_: T) { }
// CHECK-NOT: #if compiler(>=5.3) && $MarkerProtocol
// CHECK: extension Swift.Array : FeatureTest.MP where Element : FeatureTest.MP {
extension Array: FeatureTest.MP where Element : FeatureTest.MP { }
// CHECK: }
// CHECK-NOT: #if compiler(>=5.3) && $MarkerProtocol
// CHECK: extension FeatureTest.OldSchool : Swift.UnsafeSendable {
extension OldSchool: UnsafeSendable { }
// CHECK-NEXT: }
// CHECK: #if compiler(>=5.3) && $GlobalActors
// CHECK-NEXT: @globalActor public struct SomeGlobalActor
@globalActor
public struct SomeGlobalActor {
public static let shared = MyActor()
}
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: func runSomethingSomewhere
// CHECK-NEXT: #endif
public func runSomethingSomewhere(body: () async -> Void) { }
// CHECK: #if compiler(>=5.3) && $Sendable
// CHECK-NEXT: func runSomethingConcurrently(body: @Sendable () ->
// CHECK-NEXT: #endif
public func runSomethingConcurrently(body: @Sendable () -> Void) { }
// CHECK: #if compiler(>=5.3) && $Actors
// CHECK-NEXT: func stage
// CHECK-NEXT: #endif
public func stage(with actor: MyActor) { }
// CHECK: #if compiler(>=5.3) && $AsyncAwait && $Sendable && $InheritActorContext
// CHECK-NEXT: func asyncIsh
// CHECK-NEXT: #endif
public func asyncIsh(@_inheritActorContext operation: @Sendable @escaping () async -> Void) { }
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: #if $UnsafeInheritExecutor
// CHECK-NEXT: @_unsafeInheritExecutor public func unsafeInheritExecutor() async
// CHECK-NEXT: #else
// CHECK-NEXT: public func unsafeInheritExecutor() async
// CHECK-NEXT: #endif
// CHECK-NEXT: #endif
@_unsafeInheritExecutor
public func unsafeInheritExecutor() async {}
// CHECK: #if compiler(>=5.3) && $AsyncAwait
// CHECK-NEXT: #if $UnsafeInheritExecutor
// CHECK-NEXT: @_specialize{{.*}}
// CHECK-NEXT: @_unsafeInheritExecutor public func multipleSuppressible<T>(value: T) async
// CHECK-NEXT: #elsif $SpecializeAttributeWithAvailability
// CHECK-NEXT: @_specialize{{.*}}
// CHECK-NEXT: public func multipleSuppressible<T>(value: T) async
// CHECK-NEXT: #else
// CHECK-NEXT: public func multipleSuppressible<T>(value: T) async
// CHECK-NEXT: #endif
// CHECK-NEXT: #endif
@_unsafeInheritExecutor
@_specialize(exported: true, availability: SwiftStdlib 5.1, *; where T == Int)
public func multipleSuppressible<T>(value: T) async {}
// CHECK: #if compiler(>=5.3) && $UnavailableFromAsync
// CHECK-NEXT: @_unavailableFromAsync(message: "Test") public func unavailableFromAsyncFunc()
// CHECK-NEXT: #else
// CHECK-NEXT: public func unavailableFromAsyncFunc()
// CHECK-NEXT: #endif
@_unavailableFromAsync(message: "Test")
public func unavailableFromAsyncFunc() { }
// CHECK: #if compiler(>=5.3) && $NoAsyncAvailability
// CHECK-NEXT: @available(*, noasync, message: "Test")
// CHECK-NEXT: public func noAsyncFunc()
// CHECK-NEXT: #else
// CHECK-NEXT: public func noAsyncFunc()
// CHECK-NEXT: #endif
@available(*, noasync, message: "Test")
public func noAsyncFunc() { }
// CHECK-NOT: extension FeatureTest.MyActor : Swift.Sendable
| apache-2.0 |
PlutoMa/SwiftProjects | 023.Side Navigation/SideNavigation/SideNavigation/ViewController.swift | 1 | 562 | //
// ViewController.swift
// SideNavigation
//
// Created by Dareway on 2017/11/3.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let imageView = UIImageView(frame: view.bounds)
imageView.image = UIImage(named: "ViewController")
view.addSubview(imageView)
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
| mit |
Monits/swift-compiler-crashes | fixed/23088-swift-inflightdiagnostic-highlight.swift | 11 | 212 | // 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 b{
class A:A
protocol A:e
let f=Void{
| mit |
verticon/VerticonsToolbox | VerticonsToolbox/Broadcaster.swift | 1 | 3199 | //
// Broadcaster
// VerticonsToolbox
//
// Created by Robert Vaessen on 4/10/17.
// Copyright © 2017 Verticon. All rights reserved.
//
import Foundation
public protocol ListenerManagement {
func removeListener()
}
private protocol ListenerWrapper: class {
func deliver(event: Any)
}
open class Broadcaster<EventType> {
public typealias EventHandler = (EventType) -> ()
fileprivate var wrappers = [ListenerWrapper]()
public init() {}
public var listenerCount: Int {
get {
return wrappers.count
}
}
public func broadcast(_ event: EventType) {
for wrapper in self.wrappers {
wrapper.deliver(event: event)
}
}
// The addListener signature might seem odd. Here is an example usage:
//
// class Listener {
// func eventHandler(data: (String, String)) {
// print("Hello \(data.0) \(data.1)")
// }
// }
//
// let listener = Listener()
// let broadcaster = Broadcaster<(String, String)>()
// let manager = broadcaster.addListener(listener, handlerClassMethod: Listener.eventHandler)
// broadcaster.broadcast(("Chris", "Lattner")) // Prints "Hello Chris Lattner"
// manager.removeListener()
//
// addListener is taking advantage of the fact that the invocation of a method directly upon a class type
// produces a curried function that has captured the class instance argument - have a look at the Wrapper's
// deliver method. This is, in fact, how instance methods actually work. The reason for employing this
// technique is to proscribe the use of closures with their inherent risk of retain cycles (do you ever forget
// to use a capture list such as [unowned self]?). Instead of a closure with a captured self, addListener
// receives the instance directly so that it can be stored weakly in the Wrapper, thus ensuring that all
// will be well.
//
open func addListener<ListenerType: AnyObject>(_ listener: ListenerType, handlerClassMethod: @escaping (ListenerType) -> EventHandler) -> ListenerManagement {
let wrapper = Wrapper(listener: listener, handlerClassMethod: handlerClassMethod, broadcaster: self)
wrappers.append(wrapper)
return wrapper
}
}
private class Wrapper<ListenerType: AnyObject, EventType> : ListenerWrapper, ListenerManagement {
let broadcaster: Broadcaster<EventType>
weak var listener: ListenerType?
let handlerClassMethod: (ListenerType) -> (EventType) -> ()
init(listener: ListenerType, handlerClassMethod: @escaping (ListenerType) -> (EventType) -> (), broadcaster: Broadcaster<EventType>) {
self.broadcaster = broadcaster;
self.listener = listener
self.handlerClassMethod = handlerClassMethod
}
func deliver(event: Any) {
if let listener = listener {
handlerClassMethod(listener)(event as! EventType)
}
else {
removeListener()
}
}
func removeListener() {
broadcaster.wrappers = broadcaster.wrappers.filter { $0 !== self }
}
}
| mit |
noughts/SwiftTestLib | SwiftTestLibDemoTests/SwiftTestLibDemoTests.swift | 1 | 925 | //
// SwiftTestLibDemoTests.swift
// SwiftTestLibDemoTests
//
// Created by noughts on 2014/12/03.
// Copyright (c) 2014年 noughts. All rights reserved.
//
import UIKit
import XCTest
class SwiftTestLibDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Xiomara7/bookiao-ios | bookiao-ios/CustomCellHistory.swift | 1 | 3412 | //
// CustomCell.swift
// bookiao-ios
//
// Created by Xiomara on 10/6/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
import UIKit
class CustomCellHistory: UITableViewCell {
let custom = CustomDesign()
struct Config {
static let topPadding: CGFloat = 20.0
static let bottomPadding: CGFloat = 30.0
static let leftPadding: CGFloat = 30.0
static let rightPadding: CGFloat = 30.0
}
let priceLabel: UILabel!
let titleLabel: UILabel!
let subtitleLabel: UILabel!
let imageRight: UIImageView!
class var defaultHeight: CGFloat {
return 84.0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(reuseIdentifier: String!) {
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
self.opaque = true
titleLabel = UILabel(frame: CGRectZero)
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.font = UIFont.systemFontOfSize(16.0)
titleLabel.textAlignment = .Left
titleLabel.textColor = custom.UIColorFromRGB(0x545454)
contentView.addSubview(titleLabel)
subtitleLabel = UILabel(frame: CGRectZero)
subtitleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
subtitleLabel.font = UIFont.systemFontOfSize(12.0)
subtitleLabel.textAlignment = .Right
subtitleLabel.textColor = custom.UIColorFromRGB(0x545454)
contentView.addSubview(subtitleLabel)
priceLabel = UILabel(frame: CGRectZero)
priceLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
priceLabel.font = UIFont.systemFontOfSize(20.0)
priceLabel.textAlignment = .Right
priceLabel.textColor = custom.UIColorFromRGB(0x545454)
contentView.addSubview(priceLabel)
// let imageR = UIImage(named: "check.png")
// imageRight = UIImageView(image: imageR)
// contentView.addSubview(imageRight)
}
override func updateConstraints() {
// titleLabel.autoPinEdge(.Top, toEdge: .Left, ofView: titleLabel, withOffset: 3.0)
titleLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: Config.topPadding)
titleLabel.autoPinEdgeToSuperviewEdge(.Left, withInset: Config.leftPadding)
subtitleLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: Config.bottomPadding)
subtitleLabel.autoPinEdgeToSuperviewEdge(.Left, withInset: Config.leftPadding)
priceLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: Config.topPadding)
priceLabel.autoPinEdgeToSuperviewEdge(.Right, withInset: Config.rightPadding)
// imageRight.autoPinEdgeToSuperviewEdge(.Bottom, withInset: Config.bottomPadding - 30)
// imageRight.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
// titleLabel.autoPinEdge(.Left, toEdge: .Right, ofView: titleLabel, withOffset: 2.0)
// priceLabel.autoPinEdge(.Right, toEdge: .Left, ofView: priceLabel, withOffset:-2.0)
super.updateConstraints()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
jessegrosjean/BirchOutline | Common/Sources/MutationType.swift | 1 | 1874 | //
// MutationType.swift
// BirchOutline
//
// Created by Jesse Grosjean on 7/23/16.
// Copyright © 2016 Jesse Grosjean. All rights reserved.
//
import Foundation
import JavaScriptCore
public enum MutationKind {
case attribute
case body
case children
}
public protocol MutationType: AnyObject {
var target: ItemType { get }
var type: MutationKind { get }
var addedItems: [ItemType]? { get }
var removedItems: [ItemType]? { get }
var previousSibling: ItemType? { get }
var nextSibling: ItemType? { get }
}
open class Mutation: MutationType {
open var jsMutation: JSValue
init(jsMutation: JSValue) {
self.jsMutation = jsMutation
}
open var target: ItemType {
return jsMutation.forProperty("target")
}
open var type: MutationKind {
switch jsMutation.forProperty("type").toString() {
case "attribute":
return .attribute
case "body":
return .body
case "children":
return .children
default:
assert(false, "Unexpected mutation type string")
return .attribute // swift compiler error otherwise
}
}
open var addedItems: [ItemType]? {
if let addedItems = jsMutation.forProperty("addedItems").selfOrNil() {
return addedItems.toItemTypeArray()
}
return nil
}
open var removedItems: [ItemType]? {
if let removedItems = jsMutation.forProperty("removedItems").selfOrNil() {
return removedItems.toItemTypeArray()
}
return nil
}
open var previousSibling: ItemType? {
return jsMutation.forProperty("previousSibling").selfOrNil()
}
open var nextSibling: ItemType? {
return jsMutation.forProperty("nextSibling").selfOrNil()
}
}
| mit |
e78l/swift-corelibs-foundation | Foundation/DateComponentsFormatter.swift | 1 | 7191 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/* DateComponentsFormatter provides locale-correct and flexible string formatting of quantities of time, such as "1 day" or "1h 10m", as specified by NSDateComponents. For formatting intervals of time (such as "2PM to 5PM"), see DateIntervalFormatter. DateComponentsFormatter is thread-safe, in that calling methods on it from multiple threads will not cause crashes or incorrect results, but it makes no attempt to prevent confusion when one thread sets something and another thread isn't expecting it to change.
*/
@available(*, unavailable, message: "Not supported in swift-corelibs-foundation")
open class DateComponentsFormatter : Formatter {
public enum UnitsStyle : Int {
case positional // "1:10; may fall back to abbreviated units in some cases, e.g. 3d"
case abbreviated // "1h 10m"
case short // "1hr, 10min"
case full // "1 hour, 10 minutes"
case spellOut // "One hour, ten minutes"
case brief // "1hr 10min"
}
public struct ZeroFormattingBehavior : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let none = ZeroFormattingBehavior(rawValue: 0) //drop none, pad none
public static let `default` = ZeroFormattingBehavior(rawValue: 1 << 0) //Positional units: drop leading zeros, pad other zeros. All others: drop all zeros.
public static let dropLeading = ZeroFormattingBehavior(rawValue: 1 << 1) // Off: "0h 10m", On: "10m"
public static let dropMiddle = ZeroFormattingBehavior(rawValue: 1 << 2) // Off: "1h 0m 10s", On: "1h 10s"
public static let dropTrailing = ZeroFormattingBehavior(rawValue: 1 << 3) // Off: "1h 0m", On: "1h"
public static let dropAll = [ZeroFormattingBehavior.dropLeading, ZeroFormattingBehavior.dropMiddle, ZeroFormattingBehavior.dropTrailing]
public static let pad = ZeroFormattingBehavior(rawValue: 1 << 16) // Off: "1:0:10", On: "01:00:10"
}
public override init() {
NSUnsupported()
}
public required init?(coder: NSCoder) {
NSUnsupported()
}
/* 'obj' must be an instance of NSDateComponents.
*/
open override func string(for obj: Any?) -> String? { NSUnsupported() }
open func string(from components: DateComponents) -> String? { NSUnsupported() }
/* Normally, DateComponentsFormatter will calculate as though counting from the current date and time (e.g. in February, 1 month formatted as a number of days will be 28). -stringFromDate:toDate: calculates from the passed-in startDate instead.
See 'allowedUnits' for how the default set of allowed units differs from -stringFromDateComponents:.
Note that this is still formatting the quantity of time between the dates, not the pair of dates itself. For strings like "Feb 22nd - Feb 28th", use DateIntervalFormatter.
*/
open func string(from startDate: Date, to endDate: Date) -> String? { NSUnsupported() }
/* Convenience method for formatting a number of seconds. See 'allowedUnits' for how the default set of allowed units differs from -stringFromDateComponents:.
*/
open func string(from ti: TimeInterval) -> String? { NSUnsupported() }
open class func localizedString(from components: DateComponents, unitsStyle: UnitsStyle) -> String? { NSUnsupported() }
/* Choose how to indicate units. For example, 1h 10m vs 1:10. Default is DateComponentsFormatter.UnitsStyle.positional.
*/
open var unitsStyle: UnitsStyle
/* Bitmask of units to include. Set to 0 to get the default behavior. Note that, especially if the maximum number of units is low, unit collapsing is on, or zero dropping is on, not all allowed units may actually be used for a given NSDateComponents. Default value is the components of the passed-in NSDateComponents object, or years | months | weeks | days | hours | minutes | seconds if passed an NSTimeInterval or pair of NSDates.
Allowed units are:
NSCalendarUnitYear
NSCalendarUnitMonth
NSCalendarUnitWeekOfMonth (used to mean "quantity of weeks")
NSCalendarUnitDay
NSCalendarUnitHour
NSCalendarUnitMinute
NSCalendarUnitSecond
Specifying any other NSCalendarUnits will result in an exception.
*/
open var allowedUnits: NSCalendar.Unit
/* Bitmask specifying how to handle zeros in units. This includes both padding and dropping zeros so that a consistent number digits are displayed, causing updating displays to remain more stable. Default is DateComponentsFormatter.ZeroFormattingBehavior.default.
If the combination of zero formatting behavior and style would lead to ambiguous date formats (for example, 1:10 meaning 1 hour, 10 seconds), DateComponentsFormatter will throw an exception.
*/
open var zeroFormattingBehavior: ZeroFormattingBehavior
/* Specifies the locale and calendar to use for formatting date components that do not themselves have calendars. Defaults to NSAutoupdatingCurrentCalendar. If set to nil, uses the gregorian calendar with the en_US_POSIX locale.
*/
/*@NSCopying*/ open var calendar: Calendar?
/* Choose whether non-integer units should be used to handle display of values that can't be exactly represented with the allowed units. For example, if minutes aren't allowed, then "1h 30m" could be formatted as "1.5h". Default is NO.
*/
open var allowsFractionalUnits: Bool
/* Choose whether or not, and at which point, to round small units in large values to zero.
Examples:
1h 10m 30s, maximumUnitCount set to 0: "1h 10m 30s"
1h 10m 30s, maximumUnitCount set to 2: "1h 10m"
10m 30s, maximumUnitCount set to 0: "10m 30s"
10m 30s, maximumUnitCount set to 2: "10m 30s"
Default is 0, which is interpreted as unlimited.
*/
open var maximumUnitCount: Int
/* Choose whether to express largest units just above the threshold for the next lowest unit as a larger quantity of the lower unit. For example: "1m 3s" vs "63s". Default is NO.
*/
open var collapsesLargestUnit: Bool
/* Choose whether to indicate that the allowed units/insignificant units choices lead to inexact results. In some languages, simply prepending "about " to the string will produce incorrect results; this handles those cases correctly. Default is NO.
*/
open var includesApproximationPhrase: Bool
/* Choose whether to produce strings like "35 minutes remaining". Default is NO.
*/
open var includesTimeRemainingPhrase: Bool
/*
Currently unimplemented, will be removed in a future seed.
*/
open var formattingContext: Context
}
| apache-2.0 |
yuxiuyu/TrendBet | TrendBetting_0531换首页/Pods/Charts/Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift | 4 | 5153 | //
// LineChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet
{
@objc(LineChartMode)
public enum Mode: Int
{
case linear
case stepped
case cubicBezier
case horizontalBezier
}
private func initialize()
{
// default color
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
public required init()
{
super.init()
initialize()
}
public override init(values: [ChartDataEntry]?, label: String?)
{
super.init(values: values, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The drawing mode for this line dataset
///
/// **default**: Linear
open var mode: Mode = Mode.linear
private var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
open var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue
if _cubicIntensity > 1.0
{
_cubicIntensity = 1.0
}
if _cubicIntensity < 0.05
{
_cubicIntensity = 0.05
}
}
}
/// The radius of the drawn circles.
open var circleRadius = CGFloat(8.0)
/// The hole radius of the drawn circles
open var circleHoleRadius = CGFloat(4.0)
open var circleColors = [NSUIColor]()
/// - returns: The color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
open func getCircleColor(atIndex index: Int) -> NSUIColor?
{
let size = circleColors.count
let index = index % size
if index >= size
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
open func setCircleColor(_ color: NSUIColor)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(color)
}
open func setCircleColors(_ colors: NSUIColor...)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(contentsOf: colors)
}
/// Resets the circle-colors array and creates a new one
open func resetCircleColors(_ index: Int)
{
circleColors.removeAll(keepingCapacity: false)
}
/// If true, drawing circles is enabled
open var drawCirclesEnabled = true
/// - returns: `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var isDrawCirclesEnabled: Bool { return drawCirclesEnabled }
/// The color of the inner circle (the circle-hole).
open var circleHoleColor: NSUIColor? = NSUIColor.white
/// `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var drawCircleHoleEnabled = true
/// - returns: `true` if drawing the circle-holes is enabled, `false` ifnot.
open var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled }
/// This is how much (in pixels) into the dash pattern are we starting from.
open var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var lineDashLengths: [CGFloat]?
/// Line cap type, default is CGLineCap.Butt
open var lineCapType = CGLineCap.butt
/// formatter for customizing the position of the fill-line
private var _fillFormatter: IFillFormatter = DefaultFillFormatter()
/// Sets a custom IFillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
open var fillFormatter: IFillFormatter?
{
get
{
return _fillFormatter
}
set
{
_fillFormatter = newValue ?? DefaultFillFormatter()
}
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineChartDataSet
copy.circleColors = circleColors
copy.circleRadius = circleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.lineCapType = lineCapType
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCircleHoleEnabled = drawCircleHoleEnabled
copy.mode = mode
return copy
}
}
| apache-2.0 |
romankisil/eqMac2 | native/shared/Package.swift | 1 | 1256 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Shared",
platforms: [
.macOS(.v10_10)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Shared",
targets: [
"Shared"
]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(
url: "https://github.com/apple/swift-atomics.git",
.upToNextMajor(from: "1.0.0") // or `.upToNextMinor
)
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Shared",
dependencies: [
.product(name: "Atomics", package: "swift-atomics")
],
path: "Source"
)
],
swiftLanguageVersions: [
.version("5")
]
)
| mit |
emilstahl/swift | validation-test/compiler_crashers_fixed/26926-swift-typechecker-checkinheritanceclause.swift | 13 | 287 | // 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
var f{{class B<T where g:P{let a{{}var f{{if{{var f{{{if{func f{for b=e
| apache-2.0 |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Gallery/ChallengesGalleriesRequest.swift | 1 | 2133 | //
// ChallengesGalleriesRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
class ChallengesGalleriesRequest: Request {
override var method: RequestMethod { return .get }
override var parameters: Dictionary<String, AnyObject> { return prepareParameters() }
override var endpoint: String { return "galleries" }
fileprivate let page: Int?
fileprivate let perPage: Int?
init(page: Int?, perPage: Int?) {
self.page = page
self.perPage = perPage
}
fileprivate func prepareParameters() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
params["filter[challenge]"] = true as AnyObject
params["sort"] = "challenge_published_at" as AnyObject
if let page = page {
params["page"] = page as AnyObject
}
if let perPage = perPage {
params["per_page"] = perPage as AnyObject
}
return params
}
}
| mit |
blokadaorg/blokada | ios/App/UI/Settings/LevelView.swift | 1 | 2375 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
struct LevelView: View {
@State var level = 1
@State var animate = false
@State var point = UnitPoint(x: 1, y: 1)
var body: some View {
ZStack(alignment: .leading) {
Rectangle()
.fill(Color(UIColor.systemGray5))
.mask(
Image(systemName: "chart.bar.fill")
.resizable()
.aspectRatio(contentMode: .fit)
)
Rectangle()
.fill(LinearGradient(gradient:
Gradient(colors: [Color.cActivePlusGradient, Color.cActivePlus]),
startPoint: .top, endPoint: point)
)
.mask(
Image(systemName: "chart.bar.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.mask(
HStack {
Rectangle()
Rectangle().opacity(level >= 2 ? 1 : 0)
Rectangle().opacity(level >= 3 ? 1 : 0)
}
)
)
}
// .onAppear {
// if self.animate {
// withAnimation(Animation.easeInOut(duration: 3).repeatForever(autoreverses: true)) {
// self.point = UnitPoint(x: 0, y: 0)
// }
// }
// }
}
}
struct LevelView_Previews: PreviewProvider {
static var previews: some View {
Group {
LevelView(animate: true)
.previewLayout(.fixed(width: 256, height: 256))
LevelView(level: 2, animate: true)
.previewLayout(.fixed(width: 256, height: 256))
.environment(\.colorScheme, .dark)
.background(Color.black)
LevelView(level: 3)
.previewLayout(.fixed(width: 256, height: 256))
LevelView()
.previewLayout(.fixed(width: 128, height: 128))
}
}
}
| mpl-2.0 |
anthonyApptist/Poplur | Poplur/SignUpScreen.swift | 1 | 6259 | //
// SignUpScreen.swift
// Poplur
//
// Created by Mark Meritt on 2016-11-21.
// Copyright © 2016 Apptist. All rights reserved.
//
import UIKit
class SignUpScreen: PoplurScreen {
var usernameBtn: CircleButton!
var passwordBtn: CircleButton!
var nameTextField: CustomTextFieldContainer!
var pwTextField: CustomTextFieldContainer!
var entered = false
let checkMarkImg = UIImage(named: "checkmark")
override func viewDidLoad() {
super.viewDidLoad()
self.name = PoplurScreenName.signUp
self.setScreenDirections(current: self, leftScreen: HomeScreen(), rightScreen: nil, downScreen: nil, middleScreen: ProfileScreen(), upScreen: nil)
self.setRemoteEnabled(leftFunc: true, rightFunc: false, downFunc: false, middleFunc: false, upFunc: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(false)
backgroundImageView.frame = CGRect(x: 0, y: 0, width: 375, height:667)
backgroundImage = UIImage(named: "bitmap")!
backgroundImageView.image = backgroundImage
let banner = UIView(frame: CGRect(x: 0, y: 354, width: 375, height: 42))
banner.backgroundColor = UIColor.black
self.view.addSubview(banner)
let label = UILabel(frame: CGRect(x: 31, y: 364, width: 313, height: 21))
label.font = UIFont(name: "MyriadPro-Cond", size: 21.6)
label.text = "sign up to begin voting"
label.textAlignment = .center
label.textColor = UIColor.white
label.setSpacing(space: 2.08)
self.view.addSubview(label)
usernameBtn = CircleButton(frame: CGRect(x: 27, y: 61, width: 95.4, height:91.2))
usernameBtn.addText(string: "name", color: 0)
usernameBtn.setColorClear()
self.view.addSubview(usernameBtn)
passwordBtn = CircleButton(frame: CGRect(x: 27, y: 174.8, width:95.4, height: 91.2))
passwordBtn.addText(string: "pw", color: 0)
passwordBtn.setColorClear()
self.view.addSubview(passwordBtn)
nameTextField = CustomTextFieldContainer(frame: CGRect(x: 134.4, y: 89.5, width:215.6, height: 36.6))
self.view.addSubview(nameTextField)
pwTextField = CustomTextFieldContainer(frame: CGRect(x: 134.4, y:201.5, width: 215.6, height: 36.6))
self.view.addSubview(pwTextField)
nameTextField.setup(placeholder: "Email", validator: "email", type: "email")
pwTextField.setup(placeholder: "Password", validator: "required", type: "password")
self.nameTextField.textField.delegate = self
self.pwTextField.textField.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
ErrorHandler.sharedInstance.errorMessageView.resetImagePosition()
if(textField == nameTextField.textField) {
self.usernameBtn.animateRadius(scale: 1.5, soundOn: false)
}
if(textField == pwTextField.textField) {
self.passwordBtn.animateRadius(scale: 1.5, soundOn: false)
}
}
override func textFieldDidEndEditing(_ textField: UITextField) {
ErrorHandler.sharedInstance.errorMessageView.resetImagePosition()
textField.resignFirstResponder()
if !entered {
if nameTextField.textField.text?.isEmpty == false && pwTextField.textField.text?.isEmpty == false {
self.setRemoteEnabled(leftFunc: true, rightFunc: false, downFunc: false, middleFunc: true, upFunc: false)
self.remote.middleBtn?.setColourVerifiedGreen()
self.remote.middleBtn?.animateWithNewImage(scale: 1.2, soundOn: true, image: checkMarkImg!)
self.remote.middleBtn?.addTarget(self, action: #selector(self.loginButtonFunction(_:)), for: .touchUpInside)
entered = true
}
}
}
func validate(showError: Bool) -> Bool {
ErrorHandler.sharedInstance.errorMessageView.resetImagePosition()
if(!nameTextField.validate()) {
if(showError) {
if(nameTextField.validationError == "blank") {
ErrorHandler.sharedInstance.show(message: "Email Field Cannot Be Blank", container: self)
}
if(nameTextField.validationError == "not_email") {
ErrorHandler.sharedInstance.show(message: "You should double-check that email address....", container: self)
}
}
return false
}
if(!pwTextField.validate()) {
if(showError) {
if(pwTextField.validationError == "blank") {
ErrorHandler.sharedInstance.show(message: "Password Field Cannot Be Blank", container: self)
}
}
return false
}
return true
}
func loginButtonFunction(_ sender: AnyObject) {
_ = validate(showError: true)
if(!validate(showError: true)) {
return
} else {
AuthService.instance.login(email: self.nameTextField.textField.text!, password: self.pwTextField.textField.text!) {
Completion in
if(Completion.0 == nil) {
self.app.userDefaults.set(self.nameTextField.textField.text!, forKey: "userName")
self.app.userDefaults.synchronize()
currentState = remoteStates[4]
print("remote state is: " + currentState)
NotificationCenter.default.post(name: myNotification, object: nil, userInfo: ["message": currentState])
} else {
ErrorHandler.sharedInstance.show(message: Completion.0!, container: self)
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
nameTextField.textField.resignFirstResponder()
pwTextField.textField.resignFirstResponder()
}
}
| apache-2.0 |
Ramotion/reel-search | Package.swift | 1 | 1528 | // swift-tools-version:5.1
//
// Package.swift
//
// Copyright (c) Ramotion (https://www.ramotion.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 PackageDescription
let package = Package(
name: "ReelSearch",
platforms: [
.iOS(.v8)
],
products: [
.library(name: "RAMReel",
targets: ["RAMReel"]),
],
targets: [
.target(name: "RAMReel",
path: "RAMReel")
],
swiftLanguageVersions: [.v5]
)
| mit |
sport1online/PagingMenuController | Example/PagingMenuControllerDemo2/RootViewControoler.swift | 3 | 2841 | //
// RootViewControoler.swift
// PagingMenuControllerDemo
//
// Created by Cheng-chien Kuo on 5/14/16.
// Copyright © 2016 kitasuke. All rights reserved.
//
import UIKit
import PagingMenuController
private struct PagingMenuOptions: PagingMenuControllerCustomizable {
private let viewController1 = ViewController1()
private let viewController2 = ViewController2()
fileprivate var componentType: ComponentType {
return .all(menuOptions: MenuOptions(), pagingControllers: pagingControllers)
}
fileprivate var pagingControllers: [UIViewController] {
return [viewController1, viewController2]
}
fileprivate struct MenuOptions: MenuViewCustomizable {
var displayMode: MenuDisplayMode {
return .segmentedControl
}
var itemsOptions: [MenuItemViewCustomizable] {
return [MenuItem1(), MenuItem2()]
}
}
fileprivate struct MenuItem1: MenuItemViewCustomizable {
var displayMode: MenuItemDisplayMode {
return .text(title: MenuItemText(text: "First Menu"))
}
}
fileprivate struct MenuItem2: MenuItemViewCustomizable {
var displayMode: MenuItemDisplayMode {
return .text(title: MenuItemText(text: "Second Menu"))
}
}
}
class RootViewControoler: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.white
let options = PagingMenuOptions()
let pagingMenuController = PagingMenuController(options: options)
pagingMenuController.view.frame.origin.y += 64
pagingMenuController.view.frame.size.height -= 64
pagingMenuController.onMove = { state in
switch state {
case let .willMoveController(menuController, previousMenuController):
print(previousMenuController)
print(menuController)
case let .didMoveController(menuController, previousMenuController):
print(previousMenuController)
print(menuController)
case let .willMoveItem(menuItemView, previousMenuItemView):
print(previousMenuItemView)
print(menuItemView)
case let .didMoveItem(menuItemView, previousMenuItemView):
print(previousMenuItemView)
print(menuItemView)
case .didScrollStart:
print("Scroll start")
case .didScrollEnd:
print("Scroll end")
}
}
addChildViewController(pagingMenuController)
view.addSubview(pagingMenuController.view)
pagingMenuController.didMove(toParentViewController: self)
}
}
| mit |
iThinkerYZ/Swift_Currying | Swift之柯里化函数/Swift之柯里化函数/ViewController.swift | 1 | 4194 | //
// ViewController.swift
// Swift之柯里化函数
//
// Created by yz on 15/4/28.
// Copyright (c) 2015年 yz. 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.
// 创建柯里化类的实例
var curryInstance = Curry()
/*** 调用手动实现的柯里化函数 **/
var r: Int = curryInstance.add(10)(b: 20)(c: 30)
// 可能很多人都是第一次看这样的调用,感觉有点不可思议。
// 让我们回顾下OC创建对象 [[Person alloc] init],这种写法应该都见过吧,就是一下发送了两个消息,alloc返回一个实例,再用实例调用init初始化,上面也是一样,一下调用多个函数,每次调用都会返回一个函数,然后再次调用这个返回的函数。
/***** 柯里化函数分解调用 *****/
// 让我来帮你们拆解下,更容易看懂
// curryInstance.add(10): 调用一个接收参数a,并且返回一个接收参数b的函数,并且这个函数又返回一个接收参数c,返回值为Int类型的函数
// functionB: 一个接收参数b的函数,并且这个函数又返回一个接收参数c,返回值为Int类型的函数
var functionB = curryInstance.add(10)
// functionB(b: 20):调用一个接收参数b的函数,并且这个函数又返回一个接收参数c,返回值为Int类型的函数
// functionC: 一个接收参数c,返回值为Int类型的函数
var functionC = functionB(b: 20)
// functionC(c: 30): 调用一个接收参数c,返回值为Int类型的函数
// result: 函数的返回值
var res: Int = functionC(c: 30);
// 这里会有疑问?,为什么不是调用curryInstance.add(a: 10),而是curryInstance.add(10),functionB(b: 20),functionC(c: 30),怎么就有b,c,这是因为func add(a: Int) -> (b:Int) -> (c: Int) -> Int这个方法中a是第一个参数,默认是没有外部参数名,只有余下的参数才有外部参数名,b,c都属于余下的参数。
/***** 系统的柯里化函数调用 *****/
var result: Int = curryInstance.addCur(10)(b: 20)(c: 30)
/***** 系统的柯里化函数拆解调用 *****/
// curryInstance.addCur(10) : 调用一个接收参数a,并且返回一个接收参数b的函数,并且这个函数又返回一个接收参数c,返回值为Int类型的函数
// 注意:Swift是强类型语言,这里没有报错,说明调用系统柯里化函数返回的类型和手动的functionB类型一致
// functionB: 一个接收参数b的函数,并且这个函数又返回一个接收参数c,返回值为Int类型的函数
functionB = curryInstance.addCur(10)
// functionC: 一个接收参数c,返回值为Int类型的函数
functionC = functionB(b: 20)
// result: 函数的返回值
res = functionC(c: 30)
// 打印 60,60,60说明手动实现的柯里化函数,和系统的一样。
println("\(r),\(res),\(result)")
/************************************ 华丽的分割线 *********************************************/
/*************************** 实例方法的另一种调用方式(柯里化)************************************/
// 创建柯里化类的实例
var curryingInstance = Currying()
// 调用function方法
Currying.function(curryingInstance)()
// 拆解调用function方法
// 1.获取function方法
let function = Currying.function(curryingInstance)
// 2.调用function方法
function()
// 步骤都是一样,首先获取实例方法,在调用实例方法,实例方法怎么调用,就不需要在教了。
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/27177-swift-funcdecl-setdeserializedsignature.swift | 13 | 370 | // 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
let c{b<:{var a{{{{var b{protocol a{struct S{{}struct A{class B{struct S{class A{func a{class A{var:{let a{{enum a{let a{{enum S{class A{enum b{var b{{b=a
| apache-2.0 |
gobetti/Swift | SocialFramework/SocialFramework/ViewController.swift | 1 | 2965 | //
// ViewController.swift
// SocialFramework
//
// Created by Carlos Butron on 02/12/14.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import Social
import Accounts
class ViewController: UIViewController {
@IBAction func facebook(sender: UIButton) {
let url: NSURL = NSURL(string: "http://www.google.es")!
let fbController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbController.setInitialText("")
fbController.addURL(url)
let completionHandler = {(result:SLComposeViewControllerResult) -> () in
fbController.dismissViewControllerAnimated(true, completion:nil)
switch(result){
case SLComposeViewControllerResult.Cancelled:
print("User canceled", terminator: "")
case SLComposeViewControllerResult.Done:
print("User posted", terminator: "")
}
}
fbController.completionHandler = completionHandler
self.presentViewController(fbController, animated: true, completion:nil)
}
@IBAction func twitter(sender: UIButton) {
let image: UIImage = UIImage(named: "image2.png")!
let twitterController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twitterController.setInitialText("")
twitterController.addImage(image)
let completionHandler = {(result:SLComposeViewControllerResult) -> () in
twitterController.dismissViewControllerAnimated(true, completion: nil)
switch(result){
case SLComposeViewControllerResult.Cancelled:
print("User canceled", terminator: "")
case SLComposeViewControllerResult.Done:
print("User tweeted", terminator: "")
}
}
twitterController.completionHandler = completionHandler
self.presentViewController(twitterController, animated: true, completion: nil)
}
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 |
SebastianBoldt/Jelly | Jelly/Classes/public/Models/Protocols/PresentationSizeProtocol.swift | 1 | 124 | import Foundation
public protocol PresentationSizeProtocol: PresentationWidthProvider, PresentationHeightProvider {
}
| mit |
jihun-kang/ios_a2big_sdk | A2bigSDK/Animator.swift | 1 | 5239 | import UIKit
/// Responsible for parsing GIF data and decoding the individual frames.
public class Animator {
/// Number of frame to buffer.
var frameBufferCount = 50
/// Specifies whether GIF frames should be resized.
var shouldResizeFrames = false
/// Responsible for loading individual frames and resizing them if necessary.
var frameStore: FrameStore?
/// Tracks whether the display link is initialized.
private var displayLinkInitialized: Bool = false
/// A delegate responsible for displaying the GIF frames.
private weak var delegate: GIFAnimatable!
/// Responsible for starting and stopping the animation.
private lazy var displayLink: CADisplayLink = { [unowned self] in
self.displayLinkInitialized = true
let display = CADisplayLink(target: DisplayLinkProxy(target: self), selector: #selector(DisplayLinkProxy.onScreenUpdate))
display.isPaused = true
return display
}()
/// Introspect whether the `displayLink` is paused.
var isAnimating: Bool {
return !displayLink.isPaused
}
/// Total frame count of the GIF.
var frameCount: Int {
return frameStore?.frameCount ?? 0
}
/// Creates a new animator with a delegate.
///
/// - parameter view: A view object that implements the `GIFAnimatable` protocol.
///
/// - returns: A new animator instance.
public init(withDelegate delegate: GIFAnimatable) {
self.delegate = delegate
}
/// Checks if there is a new frame to display.
fileprivate func updateFrameIfNeeded() {
guard let store = frameStore else { return }
store.shouldChangeFrame(with: displayLink.duration) {
if $0 { delegate.animatorHasNewFrame() }
}
}
/// Prepares the animator instance for animation.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
func prepareForAnimation(withGIFNamed imageName: String, size: CGSize, contentMode: UIViewContentMode) {
guard let extensionRemoved = imageName.components(separatedBy: ".")[safe: 0],
let imagePath = Bundle.main.url(forResource: extensionRemoved, withExtension: "gif"),
let data = try? Data(contentsOf: imagePath) else { return }
prepareForAnimation(withGIFData: data, size: size, contentMode: contentMode)
}
/// Prepares the animator instance for animation.
///
/// - parameter imageData: GIF image data.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
func prepareForAnimation(withGIFData imageData: Data, size: CGSize, contentMode: UIViewContentMode) {
frameStore = FrameStore(data: imageData, size: size, contentMode: contentMode, framePreloadCount: frameBufferCount)
frameStore?.shouldResizeFrames = shouldResizeFrames
frameStore?.prepareFrames()
attachDisplayLink()
}
/// Add the display link to the main run loop.
private func attachDisplayLink() {
displayLink.add(to: .main, forMode: RunLoopMode.commonModes)
}
deinit {
if displayLinkInitialized {
displayLink.invalidate()
}
}
/// Start animating.
func startAnimating() {
if frameStore?.isAnimatable ?? false {
displayLink.isPaused = false
}
}
/// Stop animating.
func stopAnimating() {
displayLink.isPaused = true
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
func animate(withGIFNamed imageName: String, size: CGSize, contentMode: UIViewContentMode) {
prepareForAnimation(withGIFNamed: imageName, size: size, contentMode: contentMode)
startAnimating()
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
func animate(withGIFData imageData: Data, size: CGSize, contentMode: UIViewContentMode) {
prepareForAnimation(withGIFData: imageData, size: size, contentMode: contentMode)
startAnimating()
}
/// Stop animating and nullify the frame store.
func prepareForReuse() {
stopAnimating()
frameStore = nil
}
/// Gets the current image from the frame store.
///
/// - returns: An optional frame image to display.
func activeFrame() -> UIImage? {
return frameStore?.currentFrameImage
}
}
/// A proxy class to avoid a retain cycyle with the display link.
fileprivate class DisplayLinkProxy {
/// The target animator.
private weak var target: Animator?
/// Create a new proxy object with a target animator.
///
/// - parameter target: An animator instance.
///
/// - returns: A new proxy instance.
init(target: Animator) { self.target = target }
/// Lets the target update the frame if needed.
@objc func onScreenUpdate() { target?.updateFrameIfNeeded() }
}
| apache-2.0 |
ruslanskorb/CoreStore | Sources/CSDataStack+Observing.swift | 1 | 8311 | //
// CSDataStack+Observing.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CSDataStack
@available(macOS 10.12, *)
extension CSDataStack {
/**
Creates a `CSObjectMonitor` for the specified `NSManagedObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `NSManagedObject`.
- parameter object: the `NSManagedObject` to observe changes from
- returns: an `ObjectMonitor` that monitors changes to `object`
*/
@objc
public func monitorObject(_ object: NSManagedObject) -> CSObjectMonitor {
return self.bridgeToSwift.monitorObject(object).bridgeToObjectiveC
}
/**
Creates a `CSListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `CSListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: a `CSListMonitor` instance that monitors changes to the list
*/
@objc
public func monitorListFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> CSListMonitor {
Internals.assert(
Thread.isMainThread,
"Attempted to observe objects from \(Internals.typeName(self)) outside the main thread."
)
Internals.assert(
fetchClauses.contains { $0 is CSOrderBy },
"A CSListMonitor requires a CSOrderBy clause."
)
return ListMonitor(
dataStack: self.bridgeToSwift,
from: from.bridgeToSwift,
sectionBy: nil,
applyFetchClauses: { (fetchRequest) in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
}
).bridgeToObjectiveC
}
/**
Asynchronously creates a `CSListMonitor` for a list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `CSListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `CSListMonitor` instance
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
@objc
public func monitorListByCreatingAsynchronously(_ createAsynchronously: @escaping (CSListMonitor) -> Void, from: CSFrom, fetchClauses: [CSFetchClause]) {
Internals.assert(
Thread.isMainThread,
"Attempted to observe objects from \(Internals.typeName(self)) outside the main thread."
)
Internals.assert(
fetchClauses.contains { $0 is CSOrderBy },
"A CSListMonitor requires an CSOrderBy clause."
)
_ = ListMonitor(
dataStack: self.bridgeToSwift,
from: from.bridgeToSwift,
sectionBy: nil,
applyFetchClauses: { (fetchRequest) in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
},
createAsynchronously: {
createAsynchronously($0.bridgeToObjectiveC)
}
)
}
/**
Creates a `CSListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter sectionBy: a `CSSectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: a `CSListMonitor` instance that monitors changes to the list
*/
@objc
public func monitorSectionedListFrom(_ from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) -> CSListMonitor {
Internals.assert(
Thread.isMainThread,
"Attempted to observe objects from \(Internals.typeName(self)) outside the main thread."
)
Internals.assert(
fetchClauses.contains { $0 is CSOrderBy },
"A CSListMonitor requires an CSOrderBy clause."
)
return ListMonitor(
dataStack: self.bridgeToSwift,
from: from.bridgeToSwift,
sectionBy: sectionBy.bridgeToSwift,
applyFetchClauses: { (fetchRequest) in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
}
).bridgeToObjectiveC
}
/**
Asynchronously creates a `CSListMonitor` for a sectioned list of `NSManagedObject`s that satisfy the specified fetch clauses. Multiple `CSListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `CSListMonitor` instance
- parameter from: a `CSFrom` clause indicating the entity type
- parameter sectionBy: a `CSSectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `CSFetchClause` instances for fetching the object list. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
*/
public func monitorSectionedListByCreatingAsynchronously(_ createAsynchronously: @escaping (CSListMonitor) -> Void, from: CSFrom, sectionBy: CSSectionBy, fetchClauses: [CSFetchClause]) {
Internals.assert(
Thread.isMainThread,
"Attempted to observe objects from \(Internals.typeName(self)) outside the main thread."
)
Internals.assert(
fetchClauses.contains { $0 is CSOrderBy },
"A CSListMonitor requires an CSOrderBy clause."
)
_ = ListMonitor(
dataStack: self.bridgeToSwift,
from: from.bridgeToSwift,
sectionBy: sectionBy.bridgeToSwift,
applyFetchClauses: { (fetchRequest) in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
},
createAsynchronously: {
createAsynchronously($0.bridgeToObjectiveC)
}
)
}
}
| mit |
khizkhiz/swift | test/Generics/materializable_restrictions.swift | 3 | 618 | // RUN: %target-parse-verify-swift
func test15921520() {
var x: Int = 0
func f<T>(x: T) {} // expected-note{{in call to function 'f'}}
f(&x) // expected-error{{generic parameter 'T' could not be inferred}}
}
func test20807269() {
var x: Int = 0
func f<T>(x: T) {}
f(1, &x) // expected-error{{extra argument in call}}
}
func test15921530() {
struct X {}
func makef<T>() -> (T) -> () { // expected-note {{in call to function 'makef'}}
return {
x in ()
}
}
var _: (inout X) -> () = makef() // expected-error{{generic parameter 'T' could not be inferred}}
}
| apache-2.0 |
MartinMajewski/ToolShelf-4-3Dconnexion | ToolShelf-4-3Dconnexion/ConnexionAuxiliaries.swift | 1 | 1117 | //
// ConnexionAuxiliaries.swift
// ToolShelf-4-3Dconnexion
//
// Created by Martin Majewski on 01.11.15.
// Copyright © 2015 MartinMajewski.net. All rights reserved.
//
import Foundation
struct ConnexionAuxiliaries{
static func GetStringFrom(DeviceState ds: ConnexionDeviceState) -> String!{
return "--------------------------\n" +
"Version:\t\(ds.version)\n" +
"Client:\t\(ds.client)\n" +
"Command:\t\(ds.command)\n" +
"Param:\t\(ds.param)\n" +
"Value:\t\(ds.value)\n" +
"Time:\t\(ds.time)\n" +
"Report:\t\(ds.report)\n" +
"Buttons8:\t\(ds.buttons8)\n" +
"Axis:\t\(ds.axis)\n" +
"Address:\t\(ds.address)\n" +
"Buttons:\t\(ds.buttons)"
}
static func GetStringFrom(DevicePrefs dp: ConnexionDevicePrefs) -> String!{
return "--------------------------\n" +
"type:\t\(dp.type)\n" +
"version:\t\(dp.version)\n" +
"deviceID:\t\(dp.deviceID)\n" +
"appSignature:\t\(dp.appSignature)\n" +
"mainSpeed:\t\(dp.mainSpeed)\n" +
"zoomOnY:\t\(dp.zoomOnY)\n" +
"dominant:\t\(dp.dominant)\n" +
"gamma:\t\(dp.gamma)\n" +
"intersect:\t\(dp.intersect)\n"
}
} | mit |
khizkhiz/swift | benchmark/single-source/NSStringConversion.swift | 2 | 761 | //===--- NSStringConversion.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// <rdar://problem/19003201>
import TestsUtils
import Foundation
public func run_NSStringConversion(N: Int) {
let test:NSString = NSString(cString: "test", encoding: NSASCIIStringEncoding)!
for _ in 1...N * 10000 {
test as String
}
}
| apache-2.0 |
seanoshea/computer-science-in-swift | computer-science-in-swiftTests/EvenFibonacciTest.swift | 1 | 1424 | // Copyright (c) 2015-2016 Sean O'Shea. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
class EvenFibonacciTest: XCTestCase {
var evenFibonacci = EvenFibonacci()
func testSumOfEvenNumberedFibonacciTerms() {
let lessThanFourMillion = evenFibonacci.sumOfEvenNumberedFibonacciTerms()
XCTAssert(lessThanFourMillion == 19544084)
}
}
| mit |
comyarzaheri/Partita | Partita/TunerView.swift | 1 | 5081 | //
// TunerView.swift
// Partita
//
// Copyright (c) 2015 Comyar Zaheri. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// MARK: Imports
import UIKit
import WMGaugeView
import BFPaperButton
// MARK:- TunerView
class TunerView: UIView {
// MARK: Properties
let pitchLabel: UILabel
let gaugeView: WMGaugeView
let actionButton: BFPaperButton
fileprivate let titleLabel: UILabel
fileprivate let pitchTitleLabel: UILabel
// MARK: Creating a TunerView
override init(frame: CGRect) {
titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 32, weight: UIFontWeightLight)
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textColor = UIColor.textColor()
titleLabel.textAlignment = .center
titleLabel.text = "Tuner"
gaugeView = WMGaugeView()
gaugeView.maxValue = 50.0
gaugeView.minValue = -50.0
gaugeView.needleWidth = 0.01
gaugeView.needleHeight = 0.4
gaugeView.scaleDivisions = 10
gaugeView.scaleEndAngle = 270
gaugeView.scaleStartAngle = 90
gaugeView.scaleSubdivisions = 5
gaugeView.showScaleShadow = false
gaugeView.needleScrewRadius = 0.05
gaugeView.scaleDivisionsLength = 0.05
gaugeView.scaleDivisionsWidth = 0.007
gaugeView.scaleSubdivisionsLength = 0.02
gaugeView.scaleSubdivisionsWidth = 0.002
gaugeView.backgroundColor = UIColor.clear
gaugeView.needleStyle = WMGaugeViewNeedleStyleFlatThin
gaugeView.needleScrewStyle = WMGaugeViewNeedleScrewStylePlain
gaugeView.innerBackgroundStyle = WMGaugeViewInnerBackgroundStyleFlat
gaugeView.scalesubdivisionsaligment = WMGaugeViewSubdivisionsAlignmentCenter
gaugeView.scaleFont = UIFont.systemFont(ofSize: 0.05, weight: UIFontWeightUltraLight)
pitchTitleLabel = UILabel()
pitchTitleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFontWeightLight)
pitchTitleLabel.adjustsFontSizeToFitWidth = true
pitchTitleLabel.textColor = UIColor.textColor()
pitchTitleLabel.textAlignment = .center
pitchTitleLabel.text = "Pitch"
pitchLabel = UILabel()
pitchLabel.font = UIFont.systemFont(ofSize: 32, weight: UIFontWeightLight)
pitchLabel.adjustsFontSizeToFitWidth = true
pitchLabel.textColor = UIColor.textColor()
pitchLabel.textAlignment = .center
pitchLabel.text = "--"
actionButton = BFPaperButton(raised: false)
actionButton.setTitle("Start", for: .normal)
actionButton.backgroundColor = UIColor.actionButtonColor()
actionButton.setTitleColor(UIColor.white, for: .normal)
actionButton.setTitleColor(UIColor(white: 1.0, alpha: 0.5), for: .highlighted)
super.init(frame: frame)
addSubview(titleLabel)
addSubview(gaugeView)
addSubview(pitchTitleLabel)
addSubview(pitchLabel)
addSubview(actionButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIView
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = CGRect(x: 0.0, y: 30, width: bounds.width, height: bounds.height / 18.52)
gaugeView.frame = CGRect(x: 0, y: ((bounds).height - (bounds).width) / 2.0, width: (bounds).width, height: (bounds).width)
pitchTitleLabel.frame = CGRect(x: 0, y: gaugeView.frame.origin.y + 0.85 * (gaugeView.bounds).height, width: (bounds).width, height: (bounds).height / 23.82)
pitchLabel.frame = CGRect(x: 0, y: pitchTitleLabel.frame.origin.y + pitchTitleLabel.frame.height, width: bounds.width, height: bounds.height / 18.52)
actionButton.frame = CGRect(x: 0, y: (bounds).height - 55, width: (bounds).width, height: 55)
actionButton.tapCircleDiameter = 0.75 * (bounds).width
}
}
| mit |
cemolcay/MusicTheory | Sources/MusicTheory/NoteValue.swift | 1 | 3742 | //
// NoteValue.swift
// MusicTheory iOS
//
// Created by Cem Olcay on 21.06.2018.
// Copyright © 2018 cemolcay. All rights reserved.
//
// https://github.com/cemolcay/MusicTheory
//
import Foundation
// MARK: - NoteValueType
/// Defines the types of note values.
public enum NoteValueType: Int, Codable, CaseIterable, Hashable, CustomStringConvertible {
/// Four bar notes.
case fourBars
/// Two bar notes.
case twoBars
/// One bar note.
case oneBar
/// Two whole notes.
case doubleWhole
/// Whole note.
case whole
/// Half note.
case half
/// Quarter note.
case quarter
/// Eighth note.
case eighth
/// Sixteenth note.
case sixteenth
/// Thirtysecond note.
case thirtysecond
/// Sixtyfourth note.
case sixtyfourth
/// The note value's duration in beats.
public var rate: Double {
switch self {
case .fourBars: return 16.0 / 1.0
case .twoBars: return 8.0 / 1.0
case .oneBar: return 4.0 / 1.0
case .doubleWhole: return 2.0 / 1.0
case .whole: return 1.0 / 1.0
case .half: return 1.0 / 2.0
case .quarter: return 1.0 / 4.0
case .eighth: return 1.0 / 8.0
case .sixteenth: return 1.0 / 16.0
case .thirtysecond: return 1.0 / 32.0
case .sixtyfourth: return 1.0 / 64.0
}
}
/// Returns the string representation of the note value type.
public var description: String {
switch self {
case .fourBars: return "4 Bars"
case .twoBars: return "2 Bars"
case .oneBar: return "1 Bar"
case .doubleWhole: return "2/1"
case .whole: return "1/1"
case .half: return "1/2"
case .quarter: return "1/4"
case .eighth: return "1/8"
case .sixteenth: return "1/16"
case .thirtysecond: return "1/32"
case .sixtyfourth: return "1/64"
}
}
}
// MARK: - NoteModifier
/// Defines the length of a `NoteValue`
public enum NoteModifier: Double, Codable, CaseIterable, CustomStringConvertible {
/// No additional length.
case `default` = 1
/// Adds half of its own value.
case dotted = 1.5
/// Three notes of the same value.
case triplet = 0.6667
/// Five of the indicated note value total the duration normally occupied by four.
case quintuplet = 0.8
/// The string representation of the modifier.
public var description: String {
switch self {
case .default: return ""
case .dotted: return "D"
case .triplet: return "T"
case .quintuplet: return "Q"
}
}
}
// MARK: - NoteValue
/// Calculates how many notes of a single `NoteValueType` is equivalent to a given `NoteValue`.
///
/// - Parameters:
/// - noteValue: The note value to be measured.
/// - noteValueType: The note value type to measure the length of the note value.
/// - Returns: Returns how many notes of a single `NoteValueType` is equivalent to a given `NoteValue`.
public func / (noteValue: NoteValue, noteValueType: NoteValueType) -> Double {
return noteValue.modifier.rawValue * noteValueType.rate / noteValue.type.rate
}
/// Defines the duration of a note beatwise.
public struct NoteValue: Codable, CustomStringConvertible {
/// Type that represents the duration of note.
public var type: NoteValueType
/// Modifier for `NoteType` that modifies the duration.
public var modifier: NoteModifier
/// Initilize the NoteValue with its type and optional modifier.
///
/// - Parameters:
/// - type: Type of note value that represents note duration.
/// - modifier: Modifier of note value. Defaults `default`.
public init(type: NoteValueType, modifier: NoteModifier = .default) {
self.type = type
self.modifier = modifier
}
/// Returns the string representation of the note value.
public var description: String {
return "\(type)\(modifier)"
}
}
| mit |
wuleijun/Zeus | Zeus/Views/BorderButton.swift | 1 | 1065 | //
// BorderButton.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/12.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
@IBDesignable
class BorderButton: UIButton {
lazy var topLineLayer:CAShapeLayer = {
let topLayer = CAShapeLayer()
topLayer.lineWidth = 1
topLayer.strokeColor = UIColor.zeusBorderColor().CGColor
return topLayer
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.addSublayer(topLineLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let topPath = UIBezierPath()
topPath.moveToPoint(CGPoint(x: 0, y: 0.5))
topPath.addLineToPoint(CGPoint(x: CGRectGetWidth(bounds), y: 0.5))
topLineLayer.path = topPath.CGPath
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/02796-swift-typebase-isequal.swift | 11 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct Q<T where c=g{
var d{
struct S{
func c(a
struct
let b=0 | mit |
igormatyushkin014/Visuality | Demo/Visuality/VisualityDemo/VisualityDemo/ViewControllers/Main/MainViewController.swift | 1 | 1338 | //
// MainViewController.swift
// VisualityDemo
//
// Created by Igor Matyushkin on 21.09.15.
// Copyright © 2015 Igor Matyushkin. All rights reserved.
//
import UIKit
import Visuality
class MainViewController: UIViewController {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
// MARK: Deinitializer
deinit {
// Remove references
_circleView = nil
}
// MARK: Outlets
@IBOutlet fileprivate weak var containerForCircleView: ContainerView!
// MARK: Variables & properties
fileprivate var _circleView: CircleView!
fileprivate var circleView: CircleView {
get {
return _circleView
}
}
// MARK: Public methods
override func viewDidLoad() {
super.viewDidLoad()
// Initialize circle view
self.containerForCircleView.setContentView(ofType: CircleView.self, fromNib: .byClassName, locatedInBundle: .main) { (contentView) in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Private methods
// MARK: Actions
// MARK: Protocol methods
}
| mit |
radex/swift-compiler-crashes | crashes-duplicates/09239-swift-sourcemanager-getmessage.swift | 11 | 240 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension Array {
let a {
for {
deinit {
class c {
init {
class
case ,
| mit |
RyuichiTanimoto/FoundationUtilities | Example/FoundationUtilities/ViewController.swift | 1 | 961 | //
// ViewController.swift
// FoundationUtilities
//
// Created by RyuichiTanimoto on 01/03/2017.
// Copyright (c) 2017 RyuichiTanimoto. All rights reserved.
//
import UIKit
import FoundationUtilities
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url = URL(string: "https://hoge")!
let request = URLRequest(url: url)
let result = URLSession(configuration: .default).synchronousDataTask(with: request)
if let e = result.error {
print("NG")
print(e)
} else {
print("OK")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
afnan-ahmad/Swift-Google-Maps-API | GooglePlaces/GooglePlacesTests/PlaceAutocompleteTests.swift | 1 | 3824 | //
// PlaceAutocompleteTests.swift
// GooglePlacesTests
//
// Created by Honghao Zhang on 2016-02-12.
// Copyright © 2016 Honghao Zhang. All rights reserved.
//
import XCTest
@testable import GooglePlaces
class PlaceAutocompleteTests: XCTestCase {
typealias LocationCoordinate2D = GoogleMapsService.LocationCoordinate2D
override func setUp() {
super.setUp()
GooglePlaces.provide(apiKey: "AIzaSyDftpY3fi6x_TL4rntL8pgZb-A8mf6D0Ss")
}
override func tearDown() {
super.tearDown()
}
func testAPIIsInvalid() {
let expectation = self.expectation(description: "results")
GooglePlaces.provide(apiKey: "fake_key")
GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in
XCTAssertNotNil(error)
XCTAssertNotNil(response)
XCTAssertNotNil(response?.errorMessage)
XCTAssertEqual(response?.status, GooglePlaces.StatusCode.requestDenied)
expectation.fulfill()
}
waitForExpectations(timeout: 5.0, handler: nil)
}
func testAPIIsValid() {
let expectation = self.expectation(description: "results")
GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(response)
XCTAssertEqual(response?.status, GooglePlaces.StatusCode.ok)
expectation.fulfill()
}
waitForExpectations(timeout: 5.0, handler: nil)
}
func testResultsReturned() {
let expectation = self.expectation(description: "It has at least one result returned for `pub`")
GooglePlaces.placeAutocomplete(forInput: "pub") { (response, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(response)
XCTAssertEqual(response!.status, GooglePlaces.StatusCode.ok)
XCTAssertTrue(response!.predictions.count > 0)
expectation.fulfill()
}
waitForExpectations(timeout: 5.0, handler: nil)
}
func testResultsMatchedSubstrings() {
let expectation = self.expectation(description: "It has at least one result returned for `pub`")
let query = "Pub"
GooglePlaces.placeAutocomplete(forInput: query, locationCoordinate: LocationCoordinate2D(latitude: 43.4697354, longitude: -80.5397377), radius: 10000) { (response, error) -> Void in
XCTAssertNil(error)
XCTAssertNotNil(response)
XCTAssertEqual(response!.status, GooglePlaces.StatusCode.ok)
XCTAssertTrue(response!.predictions.count > 0)
guard let predictions = response?.predictions else {
XCTAssert(false, "prediction is nil")
return
}
for prediction in predictions {
XCTAssertEqual(prediction.matchedSubstring[0].length, query.characters.count)
guard let description = prediction.description,
let length = prediction.matchedSubstring[0].length,
let offset = prediction.matchedSubstring[0].offset else {
XCTAssert(false, "length/offset is nil")
return
}
let start = description.index(description.startIndex, offsetBy: offset)
let end = description.index(description.startIndex, offsetBy: offset + length)
let substring = description.substring(with: start ..< end)
XCTAssertEqual(substring.lowercased(), query.lowercased())
}
expectation.fulfill()
}
waitForExpectations(timeout: 5.0, handler: nil)
}
}
| mit |
HeMet/MVVMKitDemos | MVVMKitDemos/GoTo.swift | 1 | 589 | //
// GoTo.swift
// MVVMKitDemos
//
// Created by Евгений Губин on 18.07.15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import MVVMKit
struct GoTo {
static let root = present(!DemosListViewController.self).withinNavView().asRoot()
// Segue must be manual
static let segueIntegrationDemo = present(!StubViewController.self).withSegue("SegueIntegrationSegue") { stubViewModel in
return [stubViewModel]
}
static let simpleTransitionDemo = present(!StubViewController.self).withTransition(Transitions.show)
} | mit |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.SupportedFirmwareUpdateConfiguration.swift | 1 | 2167 | import Foundation
public extension AnyCharacteristic {
static func supportedFirmwareUpdateConfiguration(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Supported Firmware Update Configuration",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.supportedFirmwareUpdateConfiguration(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func supportedFirmwareUpdateConfiguration(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Supported Firmware Update Configuration",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .supportedFirmwareUpdateConfiguration,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit |
davbeck/PG.swift | Sources/pg/Query.swift | 1 | 6972 | import Foundation
/// An SQL query
public struct Query {
/// A query specific error
///
/// - wrongNumberOfBindings: When updating the bindings of a query, if it has a prepared statement the number of bindings must match the number of prepared bindings.
/// - mismatchedBindingType: When updating the bindings of a query, if it has a prepared statement the types of the bindings must match.
public enum Error: Swift.Error {
case wrongNumberOfBindings
case mismatchedBindingType(value: Any?, index: Int, expectedType: Any.Type?)
}
/// A prepared statement for reuse of a query
public final class Statement: Equatable {
/// The name of the statement used on the server
public let name: String
/// The text of the SQL query
///
/// This could either represent the entire query (if bindings are empty) or the statement part of the query with `$x` placeholders for the bindings.
public let string: String
/// The types to use for the statement, or nil to not specify a type
public let bindingTypes: [PostgresCodable.Type?]
fileprivate init(name: String = UUID().uuidString, string: String, bindingTypes: [PostgresCodable.Type?]) {
self.name = name
self.string = string
self.bindingTypes = bindingTypes
}
/// Statements are ony equal to themselves, even if 2 different statements have the same name and types.
public static func == (_ lhs: Statement, _ rhs: Statement) -> Bool {
return lhs === rhs
}
}
/// Indicates if the more complicated extended excecution workflow needs to be used
///
/// While any query can use the extended excecution workflow, using the simple query interface is faster because only a single message needs to be sent to the server. However, if the query has bindings or a previously prepared statement it must use the extended workflow.
public var needsExtendedExcecution: Bool {
if self.bindings.count > 0 || self.statement != nil {
return true
} else {
return false
}
}
/// The statement to use between excecutions of a query
///
/// If this is not nil the statement will be reused between calls. If it is nil, a new statement will be generated each time.
private(set) public var statement: Statement?
/// The types of the bindings values
///
/// Due to a limitation in the current version of swift, we cannot get the types of nil values.
public var currentBindingTypes: [PostgresCodable.Type?] {
return self.bindings.map({ value in
if let value = value {
return type(of: value)
} else {
// unfortunately swift doesn't keep track of nil types
// maybe in swift 4 we can conform Optional to PostgresCodable when it's wrapped type is?
return nil
}
})
}
/// Create and return a new prepared statement for the receiver
///
/// Normally a query is prepared and excecuted at the same time. However, if you have a query that gets reused often, even if it's bindings change between calls, you can optimize performance by reusing the same query and statement.
///
/// This method generates a statement locally, but does not prepare it with the server. Creating a statement indicates to the Client that the query should be reused. If a query has a statement set, calling `Client.exec` will automatically prepare the statement, and subsequent calls to exec on the same connection will reuse the statement. You can also explicitly prepare it using `Client.prepare`.
///
/// - Note: that once a query has a statement set, it's binding types are locked in and an error will be thrown if you try to update them with different types.
///
/// - Parameter name: The name to be used for the statement on the server. Names must be uique accross connections and it is recommended that you use the default, which will generate a UUID.
/// - Parameter types: The types to use for the prepared statement. Defaulst to `currentBindingTypes`.
/// - Returns: The statement that was created. This is also set on the receiver.
public mutating func createStatement(withName name: String = UUID().uuidString, types: [PostgresCodable.Type?]? = nil) -> Statement {
let statement = Statement(name: name, string: string, bindingTypes: types ?? self.currentBindingTypes)
self.statement = statement
return statement
}
/// The text of the SQL query
///
/// This could either represent the entire query (if bindings are empty) or the statement part of the query with `$x` placeholders for the bindings.
public let string: String
/// The values to bind the query to
///
/// It is highly recommended that any dynamic or user generated values be used as bindings and not embeded in the query string. Bindings are processed on the server and escaped to avoid SQL injection.
public private(set) var bindings: [PostgresCodable?]
/// Emitted when the query is excecuted, either successfully or with an error
public let completed = EventEmitter<Result<QueryResult>>()
/// Update the bindings with new values
///
/// If you are reusing a query, you can change the bindings between executions. However the types must match the types in `statement` or an error will be thrown.
///
/// If there is no prepared statement for the receiver, this just sets the values in bindings.
///
/// - Parameter bindings: The new values to bind to.
/// - Throws: Query.Error if there is a prepared statement and it's types do not match.
public mutating func update(bindings: [PostgresCodable?]) throws {
if let statement = statement {
guard bindings.count == statement.bindingTypes.count else { throw Error.wrongNumberOfBindings }
// swift 4 should support 3 way zip
for (index, (binding, bindingType)) in zip(bindings.indices, zip(bindings, statement.bindingTypes)) {
if let binding = binding, type(of: binding) != bindingType {
throw Error.mismatchedBindingType(value: binding, index: index, expectedType: bindingType)
}
}
}
self.bindings = bindings
}
/// Create a new query
///
/// - Parameters:
/// - string: The query string. Note that string interpolation should be strongly avoided. Use bindings instead.
/// - bindings: Any value bindings for the query string. Index 0 matches `$1` in the query string.
public init(_ string: String, bindings: [PostgresCodable?]) {
self.string = string
self.bindings = bindings
}
/// Create a new query
///
/// - Parameters:
/// - string: The query string. Note that string interpolation should be strongly avoided. Use bindings instead.
/// - bindings: Any value bindings for the query string. Index 0 matches `$1` in the query string.
public init(_ string: String, _ bindings: PostgresCodable?...) {
self.init(string, bindings: bindings)
}
}
extension Query: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
}
| mit |
shorlander/firefox-ios | Client/Frontend/Strings.swift | 1 | 44138 | /* 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
public struct Strings {}
/// Return the main application bundle. Even if called from an extension. If for some reason we cannot find the
/// application bundle, the current bundle is returned, which will then result in an English base language string.
private func applicationBundle() -> Bundle {
let bundle = Bundle.main
guard bundle.bundleURL.pathExtension == "appex", let applicationBundleURL = (bundle.bundleURL as NSURL).deletingLastPathComponent?.deletingLastPathComponent() else {
return bundle
}
return Bundle(url: applicationBundleURL) ?? bundle
}
// SendTo extension.
extension Strings {
public static let SendToCancelButton = NSLocalizedString("SendTo.Cancel.Button", bundle: applicationBundle(), value: "Cancel", comment: "Button title for cancelling SendTo screen")
public static let SendToErrorOKButton = NSLocalizedString("SendTo.Error.OK.Button", bundle: applicationBundle(), value: "OK", comment: "OK button to dismiss the error prompt.")
public static let SendToErrorTitle = NSLocalizedString("SendTo.Error.Title", bundle: applicationBundle(), value: "The link you are trying to share cannot be shared.", comment: "Title of error prompt displayed when an invalid URL is shared.")
public static let SendToErrorMessage = NSLocalizedString("SendTo.Error.Message", bundle: applicationBundle(), value: "Only HTTP and HTTPS links can be shared.", comment: "Message in error prompt explaining why the URL is invalid.")
}
// ShareTo extension.
extension Strings {
public static let ShareToCancelButton = NSLocalizedString("ShareTo.Cancel.Button", bundle: applicationBundle(), value: "Cancel", comment: "Button title for cancelling Share screen")
}
// Top Sites.
extension Strings {
public static let TopSitesEmptyStateDescription = NSLocalizedString("TopSites.EmptyState.Description", value: "Your most visited sites will show up here.", comment: "Description label for the empty Top Sites state.")
public static let TopSitesEmptyStateTitle = NSLocalizedString("TopSites.EmptyState.Title", value: "Welcome to Top Sites", comment: "The title for the empty Top Sites state")
public static let TopSitesRemoveButtonAccessibilityLabel = NSLocalizedString("TopSites.RemovePage.Button", value: "Remove page - %@", comment: "Button shown in editing mode to remove this site from the top sites panel.")
}
// Activity Stream.
extension Strings {
public static let HighlightIntroTitle = NSLocalizedString("ActivityStream.HighlightIntro.Title", value: "Be on the Lookout", comment: "The title that appears for the introduction to highlights in AS.")
public static let HighlightIntroDescription = NSLocalizedString("ActivityStream.HighlightIntro.Description", value: "Firefox will place things here that you've discovered on the web so you can find your way back to the great articles, videos, bookmarks and other pages", comment: "The detailed text that explains what highlights are in AS.")
public static let ASPageControlButton = NSLocalizedString("ActivityStream.PageControl.Button", value: "Next Page", comment: "The page control button that lets you switch between pages in top sites")
public static let ASHighlightsTitle = NSLocalizedString("ActivityStream.Highlights.SectionTitle", value: "Visit Again", comment: "Section title label for Visit again section")
public static let ASTopSitesTitle = NSLocalizedString("ActivityStream.TopSites.SectionTitle", value: "Top Sites", comment: "Section title label for Top Sites")
public static let HighlightVistedText = NSLocalizedString("ActivityStream.Highlights.Visited", value: "Visited", comment: "The description of a highlight if it is a site the user has visited")
public static let HighlightBookmarkText = NSLocalizedString("ActivityStream.Highlights.Bookmark", value: "Bookmarked", comment: "The description of a highlight if it is a site the user has bookmarked")
}
// Home Panel Context Menu.
extension Strings {
public static let OpenInNewTabContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.OpenInNewTab", value: "Open in New Tab", comment: "The title for the Open in New Tab context menu action for sites in Home Panels")
public static let OpenInNewPrivateTabContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.OpenInNewPrivateTab", value: "Open in New Private Tab", comment: "The title for the Open in New Private Tab context menu action for sites in Home Panels")
public static let BookmarkContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.Bookmark", value: "Bookmark", comment: "The title for the Bookmark context menu action for sites in Home Panels")
public static let RemoveBookmarkContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.RemoveBookmark", value: "Remove Bookmark", comment: "The title for the Remove Bookmark context menu action for sites in Home Panels")
public static let DeleteFromHistoryContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.DeleteFromHistory", value: "Delete from History", comment: "The title for the Delete from History context menu action for sites in Home Panels")
public static let ShareContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.Share", value: "Share", comment: "The title for the Share context menu action for sites in Home Panels")
public static let RemoveContextMenuTitle = NSLocalizedString("HomePanel.ContextMenu.Remove", value: "Remove", comment: "The title for the Remove context menu action for sites in Home Panels")
public static let PinTopsiteActionTitle = NSLocalizedString("ActivityStream.ContextMenu.PinTopsite", value: "Pin to Top Sites", comment: "The title for the pinning a topsite action")
public static let RemovePinTopsiteActionTitle = NSLocalizedString("ActivityStream.ContextMenu.RemovePinTopsite", value: "Remove Pinned Site", comment: "The title for removing a pinned topsite action")
}
// Settings.
extension Strings {
public static let SettingsClearPrivateDataClearButton = NSLocalizedString("Settings.ClearPrivateData.Clear.Button", value: "Clear Private Data", comment: "Button in settings that clears private data for the selected items.")
public static let SettingsClearPrivateDataSectionName = NSLocalizedString("Settings.ClearPrivateData.SectionName", value: "Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
public static let SettingsClearPrivateDataTitle = NSLocalizedString("Settings.ClearPrivateData.Title", value: "Clear Private Data", comment: "Title displayed in header of the setting panel.")
public static let SettingsDisconnectAlertTitle = NSLocalizedString("Settings.Disconnect.Title", value: "Disconnect?", comment: "Title of the alert when prompting the user asking to disconnect.")
public static let SettingsDisconnectButton = NSLocalizedString("Settings.Disconnect.Button", value: "Disconnect", comment: "Button displayed at the bottom of settings page allowing users to Disconnect from FxA")
public static let SettingsDisconnectDestructiveAction = NSLocalizedString("Settings.Disconnect.DestructiveButton", value: "Disconnect", comment: "Destructive action button in alert when user is prompted for disconnect")
public static let SettingsSearchDoneButton = NSLocalizedString("Settings.Search.Done.Button", value: "Done", comment: "Button displayed at the top of the search settings.")
public static let SettingsSearchEditButton = NSLocalizedString("Settings.Search.Edit.Button", value: "Edit", comment: "Button displayed at the top of the search settings.")
}
// Error pages.
extension Strings {
public static let ErrorPagesAdvancedButton = NSLocalizedString("ErrorPages.Advanced.Button", value: "Advanced", comment: "Label for button to perform advanced actions on the error page")
public static let ErrorPagesAdvancedWarning1 = NSLocalizedString("ErrorPages.AdvancedWarning1.Text", value: "Warning: we can't confirm your connection to this website is secure.", comment: "Warning text when clicking the Advanced button on error pages")
public static let ErrorPagesAdvancedWarning2 = NSLocalizedString("ErrorPages.AdvancedWarning2.Text", value: "It may be a misconfiguration or tampering by an attacker. Proceed if you accept the potential risk.", comment: "Additional warning text when clicking the Advanced button on error pages")
public static let ErrorPagesCertWarningDescription = NSLocalizedString("ErrorPages.CertWarning.Description", value: "The owner of %@ has configured their website improperly. To protect your information from being stolen, Firefox has not connected to this website.", comment: "Warning text on the certificate error page")
public static let ErrorPagesCertWarningTitle = NSLocalizedString("ErrorPages.CertWarning.Title", value: "This Connection is Untrusted", comment: "Title on the certificate error page")
public static let ErrorPagesGoBackButton = NSLocalizedString("ErrorPages.GoBack.Button", value: "Go Back", comment: "Label for button to go back from the error page")
public static let ErrorPagesVisitOnceButton = NSLocalizedString("ErrorPages.VisitOnce.Button", value: "Visit site anyway", comment: "Button label to temporarily continue to the site from the certificate error page")
}
// Logins Helper.
extension Strings {
public static let LoginsHelperSaveLoginButtonTitle = NSLocalizedString("LoginsHelper.SaveLogin.Button", value: "Save Login", comment: "Button to save the user's password")
public static let LoginsHelperDontSaveButtonTitle = NSLocalizedString("LoginsHelper.DontSave.Button", value: "Don’t Save", comment: "Button to not save the user's password")
public static let LoginsHelperUpdateButtonTitle = NSLocalizedString("LoginsHelper.Update.Button", value: "Update", comment: "Button to update the user's password")
}
// History Panel
extension Strings {
public static let SyncedTabsTableViewCellTitle = NSLocalizedString("HistoryPanel.SyncedTabsCell.Title", value: "Synced Devices", comment: "Title for the Synced Tabs Cell in the History Panel")
public static let HistoryBackButtonTitle = NSLocalizedString("HistoryPanel.HistoryBackButton.Title", value: "History", comment: "Title for the Back to History button in the History Panel")
public static let EmptySyncedTabsPanelStateTitle = NSLocalizedString("HistoryPanel.EmptySyncedTabsState.Title", value: "Firefox Sync", comment: "Title for the empty synced tabs state in the History Panel")
public static let EmptySyncedTabsPanelStateDescription = NSLocalizedString("HistoryPanel.EmptySyncedTabsState.Description", value: "Sign in to view open tabs on your other devices.", comment: "Description for the empty synced tabs state in the History Panel")
public static let EmptySyncedTabsPanelNullStateDescription = NSLocalizedString("HistoryPanel.EmptySyncedTabsNullState.Description", value: "Your tabs from other devices show up here.", comment: "Description for the empty synced tabs null state in the History Panel")
public static let SyncedTabsTableViewCellDescription = NSLocalizedString("HistoryPanel.SyncedTabsCell.Description.Pluralized", value: "%d device(s) connected", comment: "Description that corresponds with a number of devices connected for the Synced Tabs Cell in the History Panel")
public static let HistoryPanelEmptyStateTitle = NSLocalizedString("HistoryPanel.EmptyState.Title", value: "Websites you've visited recently will show up here.", comment: "Title for the History Panel empty state.")
public static let RecentlyClosedTabsButtonTitle = NSLocalizedString("HistoryPanel.RecentlyClosedTabsButton.Title", value: "Recently Closed", comment: "Title for the Recently Closed button in the History Panel")
public static let RecentlyClosedTabsPanelTitle = NSLocalizedString("RecentlyClosedTabsPanel.Title", value: "Recently Closed", comment: "Title for the Recently Closed Tabs Panel")
public static let FirefoxHomePage = NSLocalizedString("Firefox.HomePage.Title", value: "Firefox Home Page", comment: "Title for firefox about:home page in tab history list")
}
// Syncing
extension Strings {
public static let SyncingMessageWithEllipsis = NSLocalizedString("Sync.SyncingEllipsis.Label", value: "Syncing…", comment: "Message displayed when the user's account is syncing with ellipsis at the end")
public static let SyncingMessageWithoutEllipsis = NSLocalizedString("Sync.Syncing.Label", value: "Syncing", comment: "Message displayed when the user's account is syncing with no ellipsis")
public static let FirstTimeSyncLongTime = NSLocalizedString("Sync.FirstTimeMessage.Label", value: "Your first sync may take a while", comment: "Message displayed when the user syncs for the first time")
public static let FirefoxSyncOfflineTitle = NSLocalizedString("SyncState.Offline.Title", value: "Sync is offline", comment: "Title for Sync status message when Sync failed due to being offline")
public static let FirefoxSyncNotStartedTitle = NSLocalizedString("SyncState.NotStarted.Title", value: "Sync is unavailable", comment: "Title for Sync status message when Sync failed to start.")
public static let FirefoxSyncPartialTitle = NSLocalizedString("SyncState.Partial.Title", value: "Sync is experiencing issues syncing %@", comment: "Title for Sync status message when a component of Sync failed to complete, where %@ represents the name of the component, i.e. Sync is experiencing issues syncing Bookmarks")
public static let FirefoxSyncFailedTitle = NSLocalizedString("SyncState.Failed.Title", value: "Syncing has failed", comment: "Title for Sync status message when synchronization failed to complete")
public static let FirefoxSyncTroubleshootTitle = NSLocalizedString("Settings.TroubleShootSync.Title", value: "Troubleshoot", comment: "Title of link to help page to find out how to solve Sync issues")
public static func localizedStringForSyncComponent(_ componentName: String) -> String? {
switch componentName {
case "bookmarks":
return NSLocalizedString("SyncState.Bookmark.Title", value: "Bookmarks", comment: "The Bookmark sync component, used in SyncState.Partial.Title")
case "clients":
return NSLocalizedString("SyncState.Clients.Title", value: "Remote Clients", comment: "The Remote Clients sync component, used in SyncState.Partial.Title")
case "tabs":
return NSLocalizedString("SyncState.Tabs.Title", value: "Tabs", comment: "The Tabs sync component, used in SyncState.Partial.Title")
case "logins":
return NSLocalizedString("SyncState.Logins.Title", value: "Logins", comment: "The Logins sync component, used in SyncState.Partial.Title")
case "history":
return NSLocalizedString("SyncState.History.Title", value: "History", comment: "The History sync component, used in SyncState.Partial.Title")
default: return nil
}
}
}
//Hotkey Titles
extension Strings {
public static let ReloadPageTitle = NSLocalizedString("Hotkeys.Reload.DiscoveryTitle", value: "Reload Page", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let BackTitle = NSLocalizedString("Hotkeys.Back.DiscoveryTitle", value: "Back", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let ForwardTitle = NSLocalizedString("Hotkeys.Forward.DiscoveryTitle", value: "Forward", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let FindTitle = NSLocalizedString("Hotkeys.Find.DiscoveryTitle", value: "Find", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let SelectLocationBarTitle = NSLocalizedString("Hotkeys.SelectLocationBar.DiscoveryTitle", value: "Select Location Bar", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let NewTabTitle = NSLocalizedString("Hotkeys.NewTab.DiscoveryTitle", value: "New Tab", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let NewPrivateTabTitle = NSLocalizedString("Hotkeys.NewPrivateTab.DiscoveryTitle", value: "New Private Tab", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let CloseTabTitle = NSLocalizedString("Hotkeys.CloseTab.DiscoveryTitle", value: "Close Tab", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let ShowNextTabTitle = NSLocalizedString("Hotkeys.ShowNextTab.DiscoveryTitle", value: "Show Next Tab", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
public static let ShowPreviousTabTitle = NSLocalizedString("Hotkeys.ShowPreviousTab.DiscoveryTitle", value: "Show Previous Tab", comment: "Label to display in the Discoverability overlay for keyboard shortcuts")
}
// Home page.
extension Strings {
public static let SettingsHomePageSectionName = NSLocalizedString("Settings.HomePage.SectionName", value: "Homepage", comment: "Label used as an item in Settings. When touched it will open a dialog to configure the home page and its uses.")
public static let SettingsHomePageTitle = NSLocalizedString("Settings.HomePage.Title", value: "Homepage Settings", comment: "Title displayed in header of the setting panel.")
public static let SettingsHomePageUIPositionTitle = NSLocalizedString("Settings.HomePage.UI.Toggle.Title", value: "Show Homepage Icon In Menu", comment: "Label used as an item in Settings. User can toggle this setting to show the home page button in menu, or on toolbar.")
public static let SettingsHomePageUIPositionSubtitle = NSLocalizedString("Settings.HomePage.UI.Toggle.Subtitle", value: "Otherwise show in the toolbar", comment: "Label displayed under the 'Show Homepage Icon In Menu' option. It describes the effect of this setting when disabled.")
public static let SettingsHomePageURLSectionTitle = NSLocalizedString("Settings.HomePage.URL.Title", value: "Current Homepage", comment: "Title of the setting section containing the URL of the current home page.")
public static let SettingsHomePageUseCurrentPage = NSLocalizedString("Settings.HomePage.UseCurrent.Button", value: "Use Current Page", comment: "Button in settings to use the current page as home page.")
public static let SettingsHomePagePlaceholder = NSLocalizedString("Settings.HomePage.URL.Placeholder", value: "Enter a webpage", comment: "Placeholder text in the homepage setting when no homepage has been set.")
public static let SettingsHomePageUseCopiedLink = NSLocalizedString("Settings.HomePage.UseCopiedLink.Button", value: "Use Copied Link", comment: "Button in settings to use the current link on the clipboard as home page.")
public static let SettingsHomePageUseDefault = NSLocalizedString("Settings.HomePage.UseDefault.Button", value: "Use Default", comment: "Button in settings to use the default home page. If no default is set, then this button isn't shown.")
public static let SettingsHomePageClear = NSLocalizedString("Settings.HomePage.Clear.Button", value: "Clear", comment: "Button in settings to clear the home page.")
public static let SetHomePageDialogTitle = NSLocalizedString("HomePage.Set.Dialog.Title", value: "Do you want to use this web page as your home page?", comment: "Alert dialog title when the user opens the home page for the first time.")
public static let SetHomePageDialogMessage = NSLocalizedString("HomePage.Set.Dialog.Message", value: "You can change this at any time in Settings", comment: "Alert dialog body when the user opens the home page for the first time.")
public static let SetHomePageDialogYes = NSLocalizedString("HomePage.Set.Dialog.OK", value: "Set Homepage", comment: "Button accepting changes setting the home page for the first time.")
public static let SetHomePageDialogNo = NSLocalizedString("HomePage.Set.Dialog.Cancel", value: "Cancel", comment: "Button cancelling changes setting the home page for the first time.")
}
// New tab choice settings
extension Strings {
public static let SettingsNewTabSectionName = NSLocalizedString("Settings.NewTab.SectionName", value: "New Tab", comment: "Label used as an item in Settings. When touched it will open a dialog to configure the new tab behaviour.")
public static let SettingsNewTabTitle = NSLocalizedString("Settings.NewTab.Title", value: "New Tab Settings", comment: "Title displayed in header of the setting panel.")
public static let SettingsNewTabTopSites = NSLocalizedString("Settings.NewTab.Option.TopSites", value: "Show your Top Sites", comment: "Option in settings to show top sites when you open a new tab")
public static let SettingsNewTabBookmarks = NSLocalizedString("Settings.NewTab.Option.Bookmarks", value: "Show your Bookmarks", comment: "Option in settings to show bookmarks when you open a new tab")
public static let SettingsNewTabHistory = NSLocalizedString("Settings.NewTab.Option.History", value: "Show your History", comment: "Option in settings to show history when you open a new tab")
public static let SettingsNewTabReadingList = NSLocalizedString("Settings.NewTab.Option.ReadingList", value: "Show your Reading List", comment: "Option in settings to show reading list when you open a new tab")
public static let SettingsNewTabBlankPage = NSLocalizedString("Settings.NewTab.Option.BlankPage", value: "Show a Blank Page", comment: "Option in settings to show a blank page when you open a new tab")
public static let SettingsNewTabHomePage = NSLocalizedString("Settings.NewTab.Option.HomePage", value: "Show your Homepage", comment: "Option in settings to show your homepage when you open a new tab")
public static let SettingsNewTabDescription = NSLocalizedString("Settings.NewTab.Description", value: "When you open a New Tab:", comment: "A description in settings of what the new tab choice means")
}
// Open With Settings
extension Strings {
public static let SettingsOpenWithSectionName = NSLocalizedString("Settings.OpenWith.SectionName", value: "Open With", comment: "Label used as an item in Settings. When touched it will open a dialog to configure the open with (mail links) behaviour.")
public static let SettingsOpenWithPageTitle = NSLocalizedString("Settings.OpenWith.PageTitle", value: "Open mail links in", comment: "Title for Open With Settings")
}
// Third Party Search Engines
extension Strings {
public static let ThirdPartySearchEngineAdded = NSLocalizedString("Search.ThirdPartyEngines.AddSuccess", value: "Added Search engine!", comment: "The success message that appears after a user sucessfully adds a new search engine")
public static let ThirdPartySearchAddTitle = NSLocalizedString("Search.ThirdPartyEngines.AddTitle", value: "Add Search Provider?", comment: "The title that asks the user to Add the search provider")
public static let ThirdPartySearchAddMessage = NSLocalizedString("Search.ThirdPartyEngines.AddMessage", value: "The new search engine will appear in the quick search bar.", comment: "The message that asks the user to Add the search provider explaining where the search engine will appear")
public static let ThirdPartySearchCancelButton = NSLocalizedString("Search.ThirdPartyEngines.Cancel", value: "Cancel", comment: "The cancel button if you do not want to add a search engine.")
public static let ThirdPartySearchOkayButton = NSLocalizedString("Search.ThirdPartyEngines.OK", value: "OK", comment: "The confirmation button")
public static let ThirdPartySearchFailedTitle = NSLocalizedString("Search.ThirdPartyEngines.FailedTitle", value: "Failed", comment: "A title explaining that we failed to add a search engine")
public static let ThirdPartySearchFailedMessage = NSLocalizedString("Search.ThirdPartyEngines.FailedMessage", value: "The search provider could not be added.", comment: "A title explaining that we failed to add a search engine")
public static let CustomEngineFormErrorTitle = NSLocalizedString("Search.ThirdPartyEngines.FormErrorTitle", value: "Failed", comment: "A title stating that we failed to add custom search engine.")
public static let CustomEngineFormErrorMessage = NSLocalizedString("Search.ThirdPartyEngines.FormErrorMessage", value: "Please fill all fields correctly.", comment: "A message explaining fault in custom search engine form.")
public static let CustomEngineDuplicateErrorTitle = NSLocalizedString("Search.ThirdPartyEngines.DuplicateErrorTitle", value: "Failed", comment: "A title stating that we failed to add custom search engine.")
public static let CustomEngineDuplicateErrorMessage = NSLocalizedString("Search.ThirdPartyEngines.DuplicateErrorMessage", value: "A search engine with this title or URL has already been added.", comment: "A message explaining fault in custom search engine form.")
}
// Bookmark Management
extension Strings {
public static let BookmarksTitle = NSLocalizedString("Bookmarks.Title.Label", value: "Title", comment: "The label for the title of a bookmark")
public static let BookmarksURL = NSLocalizedString("Bookmarks.URL.Label", value: "URL", comment: "The label for the URL of a bookmark")
public static let BookmarksFolder = NSLocalizedString("Bookmarks.Folder.Label", value: "Folder", comment: "The label to show the location of the folder where the bookmark is located")
public static let BookmarksNewFolder = NSLocalizedString("Bookmarks.NewFolder.Label", value: "New Folder", comment: "The button to create a new folder")
public static let BookmarksFolderName = NSLocalizedString("Bookmarks.FolderName.Label", value: "Folder Name", comment: "The label for the title of the new folder")
public static let BookmarksFolderLocation = NSLocalizedString("Bookmarks.FolderLocation.Label", value: "Location", comment: "The label for the location of the new folder")
}
// Tabs Delete All Undo Toast
extension Strings {
public static let TabsDeleteAllUndoTitle = NSLocalizedString("Tabs.DeleteAllUndo.Title", value: "%d tab(s) closed", comment: "The label indicating that all the tabs were closed")
public static let TabsDeleteAllUndoAction = NSLocalizedString("Tabs.DeleteAllUndo.Button", value: "Undo", comment: "The button to undo the delete all tabs")
}
//Clipboard Toast
extension Strings {
public static let GoToCopiedLink = NSLocalizedString("ClipboardToast.GoToCopiedLink.Title", value: "Go to copied link?", comment: "Message displayed when the user has a copied link on the clipboard")
public static let GoButtonTittle = NSLocalizedString("ClipboardToast.GoToCopiedLink.Button", value: "Go", comment: "The button to open a new tab with the copied link")
}
// errors
extension Strings {
public static let UnableToDownloadError = NSLocalizedString("Downloads.Error.Message", value: "Downloads aren't supported in Firefox yet.", comment: "The message displayed to a user when they try and perform the download of an asset that Firefox cannot currently handle.")
public static let UnableToAddPassErrorTitle = NSLocalizedString("AddPass.Error.Title", value: "Failed to Add Pass", comment: "Title of the 'Add Pass Failed' alert. See https://support.apple.com/HT204003 for context on Wallet.")
public static let UnableToAddPassErrorMessage = NSLocalizedString("AddPass.Error.Message", value: "An error occured while adding the pass to Wallet. Please try again later.", comment: "Text of the 'Add Pass Failed' alert. See https://support.apple.com/HT204003 for context on Wallet.")
public static let UnableToAddPassErrorDismiss = NSLocalizedString("AddPass.Error.Dismiss", value: "OK", comment: "Button to dismiss the 'Add Pass Failed' alert. See https://support.apple.com/HT204003 for context on Wallet.")
public static let UnableToOpenURLError = NSLocalizedString("OpenURL.Error.Message", value: "Firefox cannot open the page because it has an invalid address.", comment: "The message displayed to a user when they try to open a URL that cannot be handled by Firefox, or any external app.")
public static let UnableToOpenURLErrorTitle = NSLocalizedString("OpenURL.Error.Title", value: "Cannot Open Page", comment: "Title of the message shown when the user attempts to navigate to an invalid link.")
}
// open in
extension Strings {
public static let OpenInDownloadHelperAlertTitle = NSLocalizedString("Downloads.Alert.Title", value: "Firefox Downloads", comment: "The title of the alert box asking the user if they want to use another app to open a file.")
public static let OpenInDownloadHelperAlertMessage = NSLocalizedString("Downloads.Alert.Message", value: "Firefox is unable to download or display this file. Would you like to open it in another app?", comment: "The message of the alert box asking the user if they want to use another app to open a file.")
public static let OpenInDownloadHelperAlertConfirm = NSLocalizedString("Downloads.Alert.Confirm", value: "Yes", comment: "The label of the button the user will press to be presented with a list of other apps to open a file in")
public static let OpenInDownloadHelperAlertCancel = NSLocalizedString("Downloads.Alert.Cancel", value: "No", comment: "The label of the button the user will press to reject the option to open a file in another application")
}
// Add Custom Search Engine
extension Strings {
public static let SettingsAddCustomEngine = NSLocalizedString("Settings.AddCustomEngine", value: "Add Search Engine", comment: "The button text in Search Settings that opens the Custom Search Engine view.")
public static let SettingsAddCustomEngineTitle = NSLocalizedString("Settings.AddCustomEngine.Title", value: "Add Search Engine", comment: "The title of the Custom Search Engine view.")
public static let SettingsAddCustomEngineTitleLabel = NSLocalizedString("Settings.AddCustomEngine.TitleLabel", value: "Title", comment: "The title for the field which sets the title for a custom search engine.")
public static let SettingsAddCustomEngineURLLabel = NSLocalizedString("Settings.AddCustomEngine.URLLabel", value: "URL", comment: "The title for URL Field")
public static let SettingsAddCustomEngineTitlePlaceholder = NSLocalizedString("Settings.AddCustomEngine.TitlePlaceholder", value: "Search Engine", comment: "The placeholder for Title Field when saving a custom search engine.")
public static let SettingsAddCustomEngineURLPlaceholder = NSLocalizedString("Settings.AddCustomEngine.URLPlaceholder", value: "URL (Replace Query with %s)", comment: "The placeholder for URL Field when saving a custom search engine")
public static let SettingsAddCustomEngineSaveButtonText = NSLocalizedString("Settings.AddCustomEngine.SaveButtonText", value: "Save", comment: "The text on the Save button when saving a custom search engine")
}
// Context menu ButtonToast instances.
extension Strings {
public static let ContextMenuButtonToastNewTabOpenedLabelText = NSLocalizedString("ContextMenu.ButtonToast.NewTabOpened.LabelText", value: "New Tab opened", comment: "The label text in the Button Toast for switching to a fresh New Tab.")
public static let ContextMenuButtonToastNewTabOpenedButtonText = NSLocalizedString("ContextMenu.ButtonToast.NewTabOpened.ButtonText", value: "Switch", comment: "The button text in the Button Toast for switching to a fresh New Tab.")
public static let ContextMenuButtonToastNewPrivateTabOpenedLabelText = NSLocalizedString("ContextMenu.ButtonToast.NewPrivateTabOpened.LabelText", value: "New Private Tab opened", comment: "The label text in the Button Toast for switching to a fresh New Private Tab.")
public static let ContextMenuButtonToastNewPrivateTabOpenedButtonText = NSLocalizedString("ContextMenu.ButtonToast.NewPrivateTabOpened.ButtonText", value: "Switch", comment: "The button text in the Button Toast for switching to a fresh New Private Tab.")
}
// Receiving tabs sent from other devices.
extension Strings {
public static let SentTabViewActionTitle = NSLocalizedString("SentTab.ViewPage", value: "View", comment: "Button title displayed in a notification when a sent tab has been received. Tapping on the button will open the URL.")
public static let SentTabBookmarkActionTitle = NSLocalizedString("SentTab.BookmarkPage", value: "Bookmark", comment: "Button title displayed in a notification when a sent tab has been received. Tapping on the button will add the URL as a bookmark.")
public static let SentTabAddToReadingListActionTitle = NSLocalizedString("SentTab.AddToReadingList", value: "Add to Reading List", comment: "Button title displayed in a notification when a sent tab has been received. Tapping on the button will add the page to the reading list.")
}
// Sent tabs notifications. These are displayed when the app is backgrounded or the device is locked.
extension Strings {
// zero tabs
public static let SentTab_NoTabArrivingNotification_title = NSLocalizedString("SentTab.NoTabArrivingNotification.title", value: "Firefox Sync", comment: "Title of notification received after a spurious message from FxA has been received.")
public static let SentTab_NoTabArrivingNotification_body =
NSLocalizedString("SentTab.NoTabArrivingNotification.body", value: "Tap to begin", comment: "Body of notification received after a spurious message from FxA has been received.")
// one or more tabs
public static let SentTab_TabArrivingNotification_NoDevice_title = NSLocalizedString("SentTab_TabArrivingNotification_NoDevice_title", value: "Tab received", comment: "Title of notification shown when the device is sent one or more tabs from an unnamed device.")
public static let SentTab_TabArrivingNotification_NoDevice_body = NSLocalizedString("SentTab_TabArrivingNotification_NoDevice_body", value: "New tab arrived from another device.", comment: "Body of notification shown when the device is sent one or more tabs from an unnamed device.")
public static let SentTab_TabArrivingNotification_WithDevice_title = NSLocalizedString("SentTab_TabArrivingNotification_WithDevice_title", value: "Tab received from %@", comment: "Title of notification shown when the device is sent one or more tabs from the named device. %@ is the placeholder for the device name. This device name will be localized by that device.")
public static let SentTab_TabArrivingNotification_WithDevice_body = NSLocalizedString("SentTab_TabArrivingNotification_WithDevice_body", value: "New tab arrived in %@", comment: "Body of notification shown when the device is sent one or more tabs from the named device. %@ is the placeholder for the app name.")
}
// Additional messages sent via Push from FxA
extension Strings {
public static let FxAPush_DeviceDisconnected_ThisDevice_title = NSLocalizedString("FxAPush_DeviceDisconnected_ThisDevice_title", value: "Sync Disconnected", comment: "Title of a notification displayed when this device has been disconnected by another device.")
public static let FxAPush_DeviceDisconnected_ThisDevice_body = NSLocalizedString("FxAPush_DeviceDisconnected_ThisDevice_body", value: "This device has been successfully disconnected from Firefox Sync.", comment: "Body of a notification displayed when this device has been disconnected from FxA by another device.")
public static let FxAPush_DeviceDisconnected_title = NSLocalizedString("FxAPush_DeviceDisconnected_title", value: "Sync Disconnected", comment: "Title of a notification displayed when named device has been disconnected from FxA.")
public static let FxAPush_DeviceDisconnected_body = NSLocalizedString("FxAPush_DeviceDisconnected_body", value: "Firefox Sync has disconnected %@", comment: "Body of a notification displayed when named device has been disconnected from FxA. %@ refers to the name of the disconnected device.")
public static let FxAPush_DeviceDisconnected_UnknownDevice_body = NSLocalizedString("FxAPush_DeviceDisconnected_UnknownDevice_body", value: "A device has disconnected from Firefox Sync", comment: "Body of a notification displayed when unnamed device has been disconnected from FxA.")
public static let FxAPush_DeviceConnected_title = NSLocalizedString("FxAPush_DeviceConnected_title", value: "Sync Connected", comment: "Title of a notification displayed when another device has connected to FxA.")
public static let FxAPush_DeviceConnected_body = NSLocalizedString("FxAPush_DeviceConnected_body", value: "Firefox Sync has connected to %@", comment: "Title of a notification displayed when another device has connected to FxA. %@ refers to the name of the newly connected device.")
}
// Reader Mode.
extension Strings {
public static let ReaderModeAvailableVoiceOverAnnouncement = NSLocalizedString("ReaderMode.Available.VoiceOverAnnouncement", value: "Reader Mode available", comment: "Accessibility message e.g. spoken by VoiceOver when Reader Mode becomes available.")
public static let ReaderModeResetFontSizeAccessibilityLabel = NSLocalizedString("Reset text size", comment: "Accessibility label for button resetting font size in display settings of reader mode")
}
// QR Code scanner.
extension Strings {
public static let ScanQRCodeViewTitle = NSLocalizedString("ScanQRCode.View.Title", value: "Scan QR Code", comment: "Title for the QR code scanner view.")
public static let ScanQRCodeInstructionsLabel = NSLocalizedString("ScanQRCode.Instructions.Label", value: "Align QR code within frame to scan", comment: "Text for the instructions label, displayed in the QR scanner view")
}
// App menu.
extension Strings {
public static let AppMenuNewTabTitleString = NSLocalizedString("Menu.NewTabAction.Title", tableName: "Menu", value: "New Tab", comment: "Label for the button, displayed in the menu, used to open a new tab")
public static let AppMenuNewPrivateTabTitleString = NSLocalizedString("Menu.NewPrivateTabAction.Title", tableName: "Menu", value: "New Private Tab", comment: "Label for the button, displayed in the menu, used to open a new private tab.")
public static let AppMenuAddBookmarkTitleString = NSLocalizedString("Menu.AddBookmarkAction.Title", tableName: "Menu", value: "Add Bookmark", comment: "Label for the button, displayed in the menu, used to create a bookmark for the current website.")
public static let AppMenuRemoveBookmarkTitleString = NSLocalizedString("Menu.RemoveBookmarkAction.Title", tableName: "Menu", value: "Remove Bookmark", comment: "Label for the button, displayed in the menu, used to delete an existing bookmark for the current website.")
public static let AppMenuFindInPageTitleString = NSLocalizedString("Menu.FindInPageAction.Title", tableName: "Menu", value: "Find In Page", comment: "Label for the button, displayed in the menu, used to open the toolbar to search for text within the current page.")
public static let AppMenuViewDesktopSiteTitleString = NSLocalizedString("Menu.ViewDekstopSiteAction.Title", tableName: "Menu", value: "Request Desktop Site", comment: "Label for the button, displayed in the menu, used to request the desktop version of the current website.")
public static let AppMenuViewMobileSiteTitleString = NSLocalizedString("Menu.ViewMobileSiteAction.Title", tableName: "Menu", value: "Request Mobile Site", comment: "Label for the button, displayed in the menu, used to request the mobile version of the current website.")
public static let AppMenuScanQRCodeTitleString = NSLocalizedString("Menu.ScanQRCodeAction.Title", tableName: "Menu", value: "Scan QR Code", comment: "Label for the button, displayed in the menu, used to open the QR code scanner.")
public static let AppMenuSettingsTitleString = NSLocalizedString("Menu.OpenSettingsAction.Title", tableName: "Menu", value: "Settings", comment: "Label for the button, displayed in the menu, used to open the Settings menu.")
public static let AppMenuCloseAllTabsTitleString = NSLocalizedString("Menu.CloseAllTabsAction.Title", tableName: "Menu", value: "Close All Tabs", comment: "Label for the button, displayed in the menu, used to close all tabs currently open.")
public static let AppMenuOpenHomePageTitleString = NSLocalizedString("Menu.OpenHomePageAction.Title", tableName: "Menu", value: "Home", comment: "Label for the button, displayed in the menu, used to navigate to the home page.")
public static let AppMenuSetHomePageTitleString = NSLocalizedString("Menu.SetHomePageAction.Title", tableName: "Menu", value: "Set Homepage", comment: "Label for the button, displayed in the menu, used to set the homepage if none is currently set.")
public static let AppMenuSharePageTitleString = NSLocalizedString("Menu.SendPageAction.Title", tableName: "Menu", value: "Send", comment: "Label for the button, displayed in the menu, used to open the share dialog.")
public static let AppMenuTopSitesTitleString = NSLocalizedString("Menu.OpenTopSitesAction.AccessibilityLabel", tableName: "Menu", value: "Top Sites", comment: "Accessibility label for the button, displayed in the menu, used to open the Top Sites home panel.")
public static let AppMenuBookmarksTitleString = NSLocalizedString("Menu.OpenBookmarksAction.AccessibilityLabel", tableName: "Menu", value: "Bookmarks", comment: "Accessibility label for the button, displayed in the menu, used to open the Bbookmarks home panel.")
public static let AppMenuHistoryTitleString = NSLocalizedString("Menu.OpenHistoryAction.AccessibilityLabel", tableName: "Menu", value: "History", comment: "Accessibility label for the button, displayed in the menu, used to open the History home panel.")
public static let AppMenuReadingListTitleString = NSLocalizedString("Menu.OpenReadingListAction.AccessibilityLabel", tableName: "Menu", value: "Reading List", comment: "Accessibility label for the button, displayed in the menu, used to open the Reading list home panel.")
public static let AppMenuButtonAccessibilityLabel = NSLocalizedString("Toolbar.Menu.AccessibilityLabel", value: "Menu", comment: "Accessibility label for the Menu button.")
public static let AppMenuNightModeTurnOnLabel = NSLocalizedString("Menu.NightModeTurnOnAction.Label", value: "Night Mode", comment: "Label for the button, displayed in the menu, used to turn night mode on. 'Turn On' is an indication of state, and thus redundant.")
public static let AppMenuNightModeTurnOffLabel = NSLocalizedString("Menu.NightModeTurnOffAction.Label", value: "Night Mode Off", comment: "Label for the button, displayed in the menu, used to turn night mode off. 'Off' is only displayed when the mode is on.")
public static let AppMenuNoImageModeTurnOnLabel = NSLocalizedString("Menu.NoImageModeTurnOnAction.Label", value: "Hide Images", comment: "Label for the button, displayed in the menu, used to turn no image mode on.")
public static let AppMenuNoImageModeTurnOffLabel = NSLocalizedString("Menu.NoImageModeTurnOffAction.Label", value: "Show Images", comment: "Label for the button, displayed in the menu, used to turn no image mode off.")
}
// Snackbar shown when tapping app store link
extension Strings {
public static let ExternalLinkToAppStore_ConfirmationTitle = NSLocalizedString("ExternalLink.ConfirmMessage", value: "Open this link in the App Store app?", comment: "Question shown to user when tapping a link that opens the App Store app")
}
// MARK: Deprecated Strings (to be removed in next version)
private let logOut = NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account")
private let logOutQuestion = NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert")
private let logOutDestructive = NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert")
| mpl-2.0 |
ResearchSuite/ResearchSuiteExtensions-iOS | source/Core/Classes/EnhancedMultipleChoice/RSEnhancedMultipleChoiceBaseCellController.swift | 1 | 5169 | //
// RSEnhancedMultipleChoiceBaseCellController.swift
// ResearchSuiteExtensions
//
// Created by James Kizer on 4/25/18.
//
import UIKit
import ResearchKit
open class RSEnhancedMultipleChoiceBaseCellController: NSObject, RSEnhancedMultipleChoiceCellController, RSEnhancedMultipleChoiceCellDelegate, RSEnhancedMultipleChoiceCellControllerGenerator {
open class func supports(textChoice: RSTextChoiceWithAuxiliaryAnswer) -> Bool {
return textChoice.auxiliaryItem == nil
}
open class func generate(textChoice: RSTextChoiceWithAuxiliaryAnswer, choiceSelection: RSEnahncedMultipleChoiceSelection?, onValidationFailed: ((String) -> ())?, onAuxiliaryItemResultChanged: (() -> ())?) -> RSEnhancedMultipleChoiceCellController? {
return self.init(
textChoice: textChoice,
choiceSelection: choiceSelection,
onValidationFailed: onValidationFailed,
onAuxiliaryItemResultChanged: onAuxiliaryItemResultChanged
)
}
weak var managedCell: RSEnhancedMultipleChoiceCell?
open func onClearForReuse(cell: RSEnhancedMultipleChoiceCell) {
self.managedCell = nil
}
open var firstResponderView: UIView? {
// assert(self.managedCell != nil)
return self.managedCell
}
var wasFocused: Bool = false
open func setFocused(isFocused: Bool) {
if isFocused {
self.firstResponderView?.becomeFirstResponder()
}
else {
self.firstResponderView?.resignFirstResponder()
}
}
//this needs to be done by child
open var isValid: Bool {
guard let auxiliaryItem = self.auxiliaryItem else {
return true
}
if auxiliaryItem.isOptional {
return true
}
else {
return self.auxiliaryItemResult != nil
}
}
//ok for base
open func configureCell(cell: RSEnhancedMultipleChoiceCell, selected: Bool) {
assert(selected == self.isSelected)
cell.configure(forTextChoice: self.textChoice, delegate: self)
// cell.setSelected(self.isSelected, animated: false)
cell.updateUI(selected: self.isSelected, animated: false, updateResponder: false)
// cell.updateUI(selected: false, animated: false, updateResponder: false)
cell.setNeedsLayout()
self.managedCell = cell
}
//ok for base
open func clearAnswer() {
self.selected = false
self.validatedResult = nil
}
//needs to be implemented by child
open var choiceSelection: RSEnahncedMultipleChoiceSelection? {
guard self.isSelected else {
return nil
}
assert(self.isValid)
guard self.isValid else {
return nil
}
return RSEnahncedMultipleChoiceSelection(identifier: self.textChoice.identifier, value: self.textChoice.value, auxiliaryResult: self.auxiliaryItemResult)
}
//ok for base
open func setSelected(selected: Bool, cell: RSEnhancedMultipleChoiceCell) {
self.selected = selected
}
//ok for base
open var identifier: String {
return self.textChoice.identifier
}
//ok for base
public let textChoice: RSTextChoiceWithAuxiliaryAnswer
//ok for base
open var auxiliaryItem: ORKFormItem? {
return self.textChoice.auxiliaryItem
}
//ok for base
open var hasAuxiliaryItem: Bool {
return self.textChoice.auxiliaryItem != nil
}
//ok for base
open var isSelected: Bool {
return self.selected
}
//needs to be implemented by child
public func viewForAuxiliaryItem(item: ORKFormItem, cell: RSEnhancedMultipleChoiceCell) -> UIView? {
assertionFailure("Not Implemented")
return nil
}
//ok for base
open var isAuxiliaryItemOptional: Bool? {
return self.auxiliaryItem?.isOptional
}
//ok for base
open var isAuxiliaryItemValid: Bool? {
return false
}
open var onValidationFailed: ((String) -> ())?
open var onAuxiliaryItemResultChanged: (() -> ())?
open var auxiliaryItemResult: ORKResult? {
return self.validatedResult
}
open var validatedResult: ORKResult? {
didSet {
self.onAuxiliaryItemResultChanged?()
}
}
// private var currentText: String?
private var selected: Bool
required public init?(textChoice: RSTextChoiceWithAuxiliaryAnswer, choiceSelection: RSEnahncedMultipleChoiceSelection?, onValidationFailed: ((String) -> ())?, onAuxiliaryItemResultChanged: (() -> ())?) {
self.textChoice = textChoice
self.selected = choiceSelection != nil
self.validatedResult = choiceSelection?.auxiliaryResult
self.onValidationFailed = onValidationFailed
self.onAuxiliaryItemResultChanged = onAuxiliaryItemResultChanged
//initialize based on choice selection
super.init()
}
}
| apache-2.0 |
tanuva/ampacheclient | AmpacheClient/AlbumDetailViewController.swift | 1 | 2445 | //
// AlbumDetailViewController.swift
// AmpacheClient
//
// Created by Marcel on 12.10.14.
// Copyright (c) 2014 FileTrain. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
import CoreData
class AlbumDetailViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {
var albums: Array<Album>?
var context: NSManagedObjectContext
var player: AVQueuePlayer
required init(coder aDecoder: NSCoder) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
context = appDel.managedObjectContext!
player = appDel.player!
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showPlayerSegue") {
let dest = (segue.destinationViewController as UINavigationController).viewControllers[0] as PlayerViewController
let path = (view as UITableView).indexPathForSelectedRow()!
let album = albums![path.section]
var songs = Array<Song>()
for i in path.row ..< album.songs.count {
let albumSongs = album.songs.allObjects as Array<Song>
songs.append(albumSongs[i])
}
dest.setPlaylist(songs)
}
}
// UITableView Data Source
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier: String = "SongCell"
//the tablecell is optional to see if we can reuse cell
var cell : ButtonTableViewCell?
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? ButtonTableViewCell
if let album = albums?[indexPath.section] {
// cell?.textLabel?.text = (album.songs.allObjects[indexPath.row] as Song).name
// cell?.detailTextLabel?.text = album.artist.name
let songs = album.songs.allObjects
cell?.song = songs[indexPath.row] as? Song
cell?.lblTitle.text = cell?.song?.name
cell?.player = player
}
else {
"Unknown album id: \(indexPath.row)"
}
return cell!
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return albums?[section].name ?? "Unknown album"
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return albums?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return albums?[section].songs.count ?? 0
}
}
| unlicense |
debugsquad/Hyperborea | Hyperborea/Controller/CRecent.swift | 1 | 1791 | import UIKit
class CRecent:CController
{
private weak var controllerSearch:CSearch!
private(set) var model:MRecent?
private(set) weak var viewRecent:VRecent!
init(controllerSearch:CSearch)
{
self.controllerSearch = controllerSearch
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewRecent:VRecent = VRecent(controller:self)
self.viewRecent = viewRecent
view = viewRecent
}
override func viewDidLoad()
{
super.viewDidLoad()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncLoad()
}
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
parentController.statusBarAppareance(statusBarStyle:UIStatusBarStyle.lightContent)
viewRecent.animateShow()
}
//MARK: private
private func asyncLoad()
{
guard
let recent:[DEntry] = MSession.sharedInstance.settings?.recent?.array as? [DEntry]
else
{
return
}
model = MRecent(entries:recent)
viewRecent.refresh()
}
//MARK: public
func back()
{
parentController.statusBarAppareance(statusBarStyle:UIStatusBarStyle.default)
parentController.dismissAnimateOver(completion:nil)
}
func selectItem(item:MRecentEntry)
{
back()
controllerSearch.showDefinition(
wordId:item.wordId,
word:item.word,
languageRaw:item.languageRaw,
region:item.region)
}
}
| mit |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/Plans/PlanComparisonViewController.swift | 1 | 7655 | import UIKit
import WordPressShared
class PlanComparisonViewController: UIViewController {
private let embedIdentifier = "PageViewControllerEmbedSegue"
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var divider: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var planStackView: UIStackView!
var service: PlanService? = nil
var activePlan: Plan?
var currentPlan: Plan = defaultPlans[0] {
didSet {
if currentPlan != oldValue {
updateForCurrentPlan()
}
}
}
private var currentIndex: Int {
return allPlans.indexOf(currentPlan) ?? 0
}
private lazy var viewControllers: [PlanDetailViewController] = {
return self.allPlans.map { plan in
let isActive = self.activePlan == plan
let controller = PlanDetailViewController.controllerWithPlan(plan, isActive: isActive)
return controller
}
}()
private let allPlans = defaultPlans
lazy private var cancelXButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "gridicons-cross"), style: .Plain, target: self, action: #selector(PlanPostPurchaseViewController.closeTapped))
button.accessibilityLabel = NSLocalizedString("Close", comment: "Dismiss the current view")
return button
}()
class func controllerWithInitialPlan(plan: Plan, activePlan: Plan? = nil, planService: PlanService) -> PlanComparisonViewController {
let storyboard = UIStoryboard(name: "Plans", bundle: NSBundle.mainBundle())
let controller = storyboard.instantiateViewControllerWithIdentifier(NSStringFromClass(self)) as! PlanComparisonViewController
controller.activePlan = activePlan
controller.currentPlan = plan
controller.service = planService
return controller
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = WPStyleGuide.greyLighten30()
divider.backgroundColor = WPStyleGuide.greyLighten30()
pageControl.currentPageIndicatorTintColor = WPStyleGuide.grey()
pageControl.pageIndicatorTintColor = WPStyleGuide.grey().colorWithAlphaComponent(0.5)
navigationItem.leftBarButtonItem = cancelXButton
initializePlanDetailViewControllers()
updateForCurrentPlan()
fetchFeatures()
}
private func fetchFeatures() {
service?.updateAllPlanFeatures({ [weak self] in
self?.viewControllers.forEach { $0.viewModel = .Ready($0.plan) }
}, failure: { [weak self] error in
self?.viewControllers.forEach { $0.viewModel = .Error(String(error))
}
})
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
// If the view is changing size (e.g. on rotation, or multitasking), scroll to the correct page boundary based on the new size
coordinator.animateAlongsideTransition({ context in
self.scrollView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * size.width, y: 0), animated: false)
}, completion: nil)
}
override func shouldAutorotate() -> Bool {
return false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollToPage(currentIndex, animated: false)
}
func initializePlanDetailViewControllers() {
for controller in viewControllers {
addChildViewController(controller)
controller.view.translatesAutoresizingMaskIntoConstraints = false
planStackView.addArrangedSubview(controller.view)
controller.view.shouldGroupAccessibilityChildren = true
controller.view.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 1.0).active = true
controller.view.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
controller.view.bottomAnchor.constraintEqualToAnchor(divider.topAnchor).active = true
controller.didMoveToParentViewController(self)
}
}
func updateForCurrentPlan() {
title = currentPlan.title
updatePageControl()
for (index, viewController) in viewControllers.enumerate() {
viewController.view.accessibilityElementsHidden = index != currentIndex
}
}
// MARK: - IBActions
@IBAction private func closeTapped() {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func pageControlChanged() {
guard !scrollView.dragging else {
// If the user is currently dragging, reset the change and ignore it
pageControl.currentPage = currentIndex
return
}
// Stop the user interacting whilst we animate a scroll
scrollView.userInteractionEnabled = false
var targetPage = currentIndex
if pageControl.currentPage > currentIndex {
targetPage += 1
} else if pageControl.currentPage < currentIndex {
targetPage -= 1
}
scrollToPage(targetPage, animated: true)
}
private func updatePageControl() {
pageControl?.currentPage = currentIndex
}
}
extension PlanComparisonViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
// Ignore programmatic scrolling
if scrollView.dragging {
currentPlan = allPlans[currentScrollViewPage()]
}
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var targetPage = currentIndex
switch direction {
case .Right: targetPage -= 1
case .Left: targetPage += 1
default: break
}
let success = scrollToPage(targetPage, animated: false)
if success {
accessibilityAnnounceCurrentPlan()
}
return success
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
scrollView.userInteractionEnabled = true
accessibilityAnnounceCurrentPlan()
}
private func accessibilityAnnounceCurrentPlan() {
let currentViewController = viewControllers[currentIndex]
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, currentViewController.planTitleLabel)
}
private func currentScrollViewPage() -> Int {
// Calculate which plan's VC is at the center of the view
let pageWidth = scrollView.bounds.width
let centerX = scrollView.contentOffset.x + (pageWidth / 2)
let currentPage = Int(floor(centerX / pageWidth))
// Keep it within bounds
return currentPage.clamp(min: 0, max: allPlans.count - 1)
}
/// - returns: True if there was valid page to scroll to, false if we've reached the beginning / end
private func scrollToPage(page: Int, animated: Bool) -> Bool {
guard allPlans.indices.contains(page) else { return false }
let pageWidth = view.bounds.width
scrollView.setContentOffset(CGPoint(x: CGFloat(page) * pageWidth, y: 0), animated: animated)
currentPlan = allPlans[page]
return true
}
}
| gpl-2.0 |
ylovesy/CodeFun | wuzhentao/Maximum.swift | 1 | 311 | class Solution {
func maximumProduct(_ nums: [Int]) -> Int {
let sorts = nums.sorted()
let count = nums.count
let sum1 = sorts[0] * sorts[1] * sorts[count - 1]
let sum2 = sorts[count - 1] * sorts[count - 2] * sorts[count - 3]
return max(sum1, sum2)
}
}
| apache-2.0 |
jtbandes/swift-compiler-crashes | crashes-fuzzing/28081-swift-inflightdiagnostic.swift | 2 | 232 | // 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<{{}print{}class A{class D{struct E{class u{struct X<T:T.a
| mit |
acrocat/EverLayout | Source/Protocols/EverLayoutDelegate.swift | 1 | 1276 | // EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public protocol EverLayoutDelegate : class
{
func layout (_ layout : EverLayout , didLoadOnView view : UIView)
}
| mit |
chinlam91/edx-app-ios | Source/DiscussionTopic.swift | 3 | 1489 | //
// DiscussionTopic.swift
// edX
//
// Created by Akiva Leffert on 7/6/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public struct DiscussionTopic {
public let id: String?
public let name: String?
public let children: [DiscussionTopic]
public let depth : UInt
public let icon : Icon?
public init(id: String?, name: String?, children: [DiscussionTopic], depth : UInt = 0, icon : Icon? = nil) {
self.id = id
self.name = name
self.children = children
self.depth = depth
self.icon = icon
}
init?(json: JSON, depth : UInt = 0) {
if let name = json["name"].string {
self.id = json["id"].string
self.name = name
self.depth = depth
self.icon = nil
let childJSON = json["children"].array ?? []
self.children = childJSON.mapSkippingNils {
return DiscussionTopic(json: $0, depth : depth + 1)
}
}
else {
return nil
}
}
public static func linearizeTopics(topics : [DiscussionTopic]) -> [DiscussionTopic] {
var result : [DiscussionTopic] = []
var queue : [DiscussionTopic] = Array(topics.reverse())
while queue.count > 0 {
let topic = queue.removeLast()
result.append(topic)
queue.appendContentsOf(Array(topic.children.reverse()))
}
return result
}
}
| apache-2.0 |
feliperuzg/CleanExample | CleanExampleTests/Authentication/Data/Repository/DataSource/AuthenticationMockDataSourceSpec.swift | 1 | 1241 | //
// AuthenticationMockDataSourceSpec.swift
// CleanExampleTests
//
// Created by Felipe Ruz on 19-07-17.
// Copyright © 2017 Felipe Ruz. All rights reserved.
//
import XCTest
@testable import CleanExample
class AuthenticationMockDataSourceSpec: XCTestCase {
let locator = AuthenticationServiceLocator()
func testAuthenticationDataSourceCanReturnEntity() {
let sut = locator.dataSource
let exp = expectation(description: "testLoginDataSourceCanReturnEntity")
let entity = LoginEntity(userName: "Juan", password: "1234")
sut.executeLogin(with: entity) { (token, error) in
XCTAssertNotNil(token)
XCTAssertNil(error)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testAuthenticationDataSourceCanReturnError() {
let sut = locator.dataSource
let exp = expectation(description: "testLoginDataSourceCanReturnError")
let entity = LoginEntity(userName: "", password: "")
sut.executeLogin(with: entity) { (token, error) in
XCTAssertNotNil(error)
XCTAssertNil(token)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
}
| mit |
jordidekock/Colorblinds | ColorBlinds/SecondViewController.swift | 1 | 379 | //
// SecondViewController.swift
// ColorBlinds
//
// Created by Jordi de Kock on 28-08-16.
// Copyright © 2016 Jordi de Kock. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Colorblinds"
self.view.backgroundColor = .blue
}
}
| mit |
WhiskerzAB/PlaygroundTDD | PlaygroundTDD.playground/Contents.swift | 1 | 191 | import XCTest
let playgroundObserver = PlaygroundTestObserver()
XCTestObservationCenter.shared.addTestObserver(playgroundObserver)
let sud = [FibonacciTest.self]
TestRunner.run(tests: sud)
| mit |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 2 - Robot Maze 2/Functions 1/Functions 1.playground/Pages/Functions with Params.xcplaygroundpage/Contents.swift | 1 | 723 | //: [Previous](@previous)
/*:
## Functions with Params
We'll create some Students for this example.
*/
struct Student {
let name: String
var age: Int
var school: String
}
var gabrielle = Student(name: "Gabrielle", age: 21, school: "University of California-Berkeley")
var jessica = Student(name: "Jessica", age: 21, school: "University of Wisconsin-Madison")
var jarrod = Student(name: "Jarrod", age: 19, school: "University of Alabama-Huntsville")
//: Defining and using a function with parameters.
func sayHelloToStudent(student: Student) {
print("Hello, \(student.name)!")
}
sayHelloToStudent(student: gabrielle)
sayHelloToStudent(student: jessica)
sayHelloToStudent(student: jarrod)
//: [Next](@next) | mit |
k-o-d-e-n/CGLayout | Example/CGLayout/AppDelegate.swift | 1 | 2299 | //
// AppDelegate.swift
// CGLayout
//
// Created by k-o-d-e-n on 08/31/2017.
// Copyright (c) 2017 k-o-d-e-n. All rights reserved.
//
import UIKit
import CGLayout
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
let isRTL = true
CGLConfiguration.default.isRTLMode = isRTL
UIView.appearance().semanticContentAttribute = isRTL ? .forceRightToLeft : .forceLeftToRight
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 |
gtchance/FirebaseSwift | Source/Firebase.swift | 1 | 9376 | //
// Firebase.swift
// FirebaseSwift
//
// Created by Graham Chance on 10/15/16.
//
//
import Foundation
import Just
/// This class models an object that can send requests to Firebase, such as POST, GET PATCH and DELETE.
public final class Firebase {
/// Google OAuth2 access token
public var accessToken: String?
/// Legacy Database auth token. You can use the deprecated Firebase Database Secret.
/// You should use the new accessToken instead.
/// See more details here: https://firebase.google.com/docs/database/rest/auth
@available(*, deprecated) public var auth: String?
/// Base URL (e.g. http://myapp.firebaseio.com)
public let baseURL: String
/// Timeout of http operations
public var timeout: Double = 30.0 // seconds
private let headers = ["Accept": "application/json"]
/// Constructor
///
/// - Parameters:
/// - baseURL: Base URL (e.g. http://myapp.firebaseio.com)
/// - auth: Database auth token
public init(baseURL: String = "", accessToken: String? = nil) {
self.accessToken = accessToken
var url = baseURL
if url.characters.last != Character("/") {
url.append(Character("/"))
}
self.baseURL = url
}
/// Performs a synchronous PUT at base url plus given path.
///
/// - Parameters:
/// - path: path to append to base url
/// - value: data to set
/// - Returns: value of set data if successful
public func setValue(path: String, value: Any) -> [String: Any]? {
return put(path: path, value: value)
}
/// Performs an asynchronous PUT at base url plus given path.
///
/// - Parameters:
/// - path: path to append to base url.
/// - value: data to set
/// - asyncCompletion: called on completion with the value of set data if successful.
public func setValue(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
put(path: path, value: value, asyncCompletion: asyncCompletion)
}
/// Performs a synchronous POST at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to post
/// - Returns: value of posted data if successful
public func post(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .post, complete: nil)
}
/// Performs an asynchronous POST at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to post
/// - asyncCompletion: called on completion with the value of posted data if successful.
public func post(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .post, complete: asyncCompletion)
}
/// Performs an synchronous PUT at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to put
/// - Returns: Value of put data if successful
public func put(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .put, complete: nil)
}
/// Performs an asynchronous PUT at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to put
/// - asyncCompletion: called on completion with the value of put data if successful.
public func put(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .put, complete: asyncCompletion)
}
/// Performs a synchronous PATCH at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to patch
/// - Returns: value of patched data if successful
public func patch(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .patch, complete: nil)
}
/// Performs an asynchronous PATCH at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: value to patch
/// - asyncCompletion: called on completion with the value of patched data if successful.
public func patch(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .patch, complete: asyncCompletion)
}
/// Performs a synchronous DELETE at given path from the base url.
///
/// - Parameter path: path to append to the base url
public func delete(path: String) {
let url = completeURLWithPath(path: path)
_ = HTTPMethod.delete.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil, nil)
}
/// Performs an asynchronous DELETE at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - asyncCompletion: called on completion
public func delete(path: String,
asyncCompletion: @escaping () -> Void) {
let url = completeURLWithPath(path: path)
_ = HTTPMethod.delete.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil) { _ in
asyncCompletion()
}
}
/// Performs a synchronous GET at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - Returns: resulting data if successful
public func get(path: String) -> Any? {
return get(path: path, complete: nil)
}
/// Performs an asynchronous GET at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - asyncCompletion: called on completion with the resulting data if successful.
public func get(path: String,
asyncCompletion: @escaping ((Any?) -> Void)) {
get(path: path, complete: asyncCompletion)
}
@discardableResult
private func get(path: String, complete: ((Any?) -> Void)?) -> Any? {
let url = completeURLWithPath(path: path)
let completionHandler = createCompletionHandler(method: .get, callback: complete)
let httpResult = HTTPMethod.get.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil, completionHandler)
guard complete == nil else { return nil }
return process(httpResult: httpResult, method: .get)
}
@discardableResult
private func write(value: Any,
path: String,
method: HTTPMethod,
complete: (([String: Any]?) -> Void)? = nil) -> [String: Any]? {
let url = completeURLWithPath(path: path)
let json: Any? = JSONSerialization.isValidJSONObject(value) ? value : [".value": value]
let callback: ((Any?) -> Void)? = complete == nil ? nil : { result in
complete?(result as? [String: Any])
}
let completionHandler = createCompletionHandler(method: method, callback: callback)
let result = method.justRequest(url, [:], [:], json, headers, [:], nil, [:],
false, timeout, nil, nil, nil, completionHandler)
guard complete == nil else { return nil }
return process(httpResult: result, method: method) as? [String : Any]
}
private func completeURLWithPath(path: String) -> String {
var url = baseURL + path + ".json"
if let accessToken = accessToken {
url += "?access_token=" + accessToken
} else if let auth = auth {
url += "?auth=" + auth
}
return url
}
private func process(httpResult: HTTPResult, method: HTTPMethod) -> Any? {
if let e = httpResult.error {
print("ERROR FirebaseSwift-\(method.rawValue) message: \(e.localizedDescription)")
return nil
}
guard httpResult.content != nil else {
print("ERROR FirebaseSwift-\(method.rawValue) message: No content in http response.")
return nil
}
if let json = httpResult.contentAsJSONMap() {
return json
} else {
print("ERROR FirebaseSwift-\(method.rawValue) message: Failed to parse json response. Status code: \(String(describing: httpResult.statusCode))")
return nil
}
}
private func createCompletionHandler(method: HTTPMethod,
callback: ((Any?) -> Void)?) -> ((HTTPResult) -> Void)? {
if let callback = callback {
let completionHandler: ((HTTPResult) -> Void)? = { result in
callback(self.process(httpResult: result, method: method))
}
return completionHandler
}
return nil
}
}
| mit |
USAssignmentWarehouse/EnglishNow | EnglishNow/Controller/Chat/DetailChatViewController.swift | 1 | 12938 | //
// DetailChatViewController.swift
// EnglishNow
//
// Created by Nha T.Tran on 6/11/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class DetailChatViewController: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
// MARK: -declare
var currentContact: Contact?
var messages = [Message]()
var isTheFirstLoad: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = currentContact?.name
collectionView?.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 58, right: 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = UIColor.white
collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellId)
//to handle event click on anywhere on screen to disappear keyboard
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
self.collectionView?.backgroundView = UIView(frame:(self.collectionView?.bounds)!)
self.collectionView?.backgroundView!.addGestureRecognizer(tapGestureRecognizer)
if isTheFirstLoad == true{
isTheFirstLoad = false
loadMessage()
}
setupInputComponents()
viewScrollButton()
}
func handleTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
// MARK: -collectionview datasource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatMessageCell
let message = messages[indexPath.item]
cell.bubbleWidthAnchor?.constant = estimateFrameForText(message.text!).width + 32
//if the message is of other user
if message.fromId != Auth.auth().currentUser?.uid{
cell.bubbleView.backgroundColor = UIColor(red:229/255, green: 232/255, blue:232/255, alpha: 1.0)
cell.textView.textColor = UIColor.black
cell.bubbleViewRightAnchor?.isActive = false
cell.bubbleViewLeftAnchor?.isActive = true
cell.profileImageView.isHidden = false
cell.profileImageView.image = currentContact?.avatar
}
//if the message is of current user
else {
cell.bubbleView.backgroundColor = UIColor(red:30/255, green: 136/255, blue: 229/255, alpha: 1.0)
cell.textView.textColor = UIColor.white
cell.bubbleViewRightAnchor?.isActive = true
cell.bubbleViewLeftAnchor?.isActive = false
cell.profileImageView.isHidden = true
}
cell.textView.text = message.text
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var height: CGFloat = 80
//get estimated height somehow????
if let text = messages[indexPath.item].text {
height = estimateFrameForText(text).height + 20
}
return CGSize(width: view.frame.width, height: height)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "SegueProfile", sender: nil)
}
// MARK: -setup view
//to handle event scroll the last item up to
func viewScrollButton() {
let lastItem = collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
if (lastItem >= 0){
let indexPath: IndexPath = IndexPath.init(item: lastItem, section: 0) as IndexPath
print("lastItem: \(indexPath.row)")
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: false)
}
}
lazy var inputTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Enter message..."
textField.translatesAutoresizingMaskIntoConstraints = false
textField.backgroundColor = UIColor.white
textField.delegate = self
return textField
}()
let cellId = "cellId"
fileprivate func estimateFrameForText(_ text: String) -> CGRect {
let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)], context: nil)
}
func setupInputComponents() {
let containerView = UIView()
containerView.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
containerView.layer.borderWidth = 1.0
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
//ios9 constraint anchors
//x,y,w,h
containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor , constant: -40.0).isActive = true
containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
let sendButton = UIButton(type: .system)
sendButton.backgroundColor = UIColor.blue
sendButton.setTitle("Send", for: UIControlState())
sendButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
containerView.addSubview(sendButton)
//x,y,w,h
sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
containerView.addSubview(inputTextField)
//x,y,w,h
inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true
inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
let separatorLineView = UIView()
separatorLineView.backgroundColor = UIColor(red: 220, green: 220, blue: 220, alpha: 1.0)
separatorLineView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(separatorLineView)
//x,y,w,h
separatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
separatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
separatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
separatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
func handleSend() {
saveMessage(receiceId: (currentContact?.id)!)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
handleSend()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: -load data from firebase to show on screen
func loadMessage(){
if let user = Auth.auth().currentUser{
let queryRef = Database.database().reference().child("message/private").observe(.value, with: { (snapshot) -> Void in
//go to each message in private tree
for item in snapshot.children {
let message = item as! DataSnapshot
let uid = message.key
//if the message is betweent user and other
if uid.range(of:user.uid) != nil{
let listId = uid.components(separatedBy: " ")
//if the message is between user and current user
if listId[0] == self.currentContact?.id || listId[1] == self.currentContact?.id{
self.messages.removeAll()
let temp = message.value as! [String:AnyObject]
let numberMessage = temp.count
var count = 1
//get all message betweent user nad current user
for msg in message.children{
if count < numberMessage {
let userDict = (msg as! DataSnapshot).value as! [String:AnyObject]
if userDict.count >= 3{
let sender = userDict["sender"] as! String
let text = userDict["text"] as! String
let time = userDict["time"] as! TimeInterval
self.messages.append(Message(fromId: sender, text: text, timestamp: time))
//reload collectionview
self.collectionView?.reloadData()
self.viewScrollButton()
}
count += 1
}
}
}
}
}
})
}
}
// MARK: -handle send message event
func saveMessage(receiceId: String){
let user = Auth.auth().currentUser
//create message'id
var child : String?
if (user?.uid)! > receiceId{
child = (user?.uid)! + " " + receiceId
}else{
child = receiceId + " " + (user?.uid)!
}
let userRef = Database.database().reference().child("message").child("private").child(child!)
//save the lastest message
userRef.child("lastest_text").setValue(inputTextField.text)
let childRef = userRef.childByAutoId()
if (user?.uid)! != nil && inputTextField.text != nil && Date.timeIntervalBetween1970AndReferenceDate != nil{
childRef.child("sender").setValue((user?.uid)!)
childRef.child("text").setValue(inputTextField.text)
childRef.child("time").setValue(Date.timeIntervalBetween1970AndReferenceDate)
//messages.append(Message(fromId: user!.uid, text: inputTextField.text!, timestamp: Date.timeIntervalBetween1970AndReferenceDate))
}
self.messages.removeAll()
inputTextField.text = ""
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.collectionView?.endEditing(true)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SegueProfile"{
let des = segue.destination as! ProfileVC
des.currentID = (currentContact?.id)!
}
}
}
| apache-2.0 |
muzcity/MZGoneView | Example/MZGoneView/AppDelegate.swift | 1 | 2168 | //
// AppDelegate.swift
// MZGoneView
//
// Created by muzcity on 10/15/2017.
// Copyright (c) 2017 muzcity. 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 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 |
kbelter/SnazzyList | SnazzyList/Classes/src/CollectionView/Services/Cells/ImageGalleryCollectionCell.swift | 1 | 2508 | //
// ImageGalleryCollectionCell.swift
// Dms
//
// Created by Kevin on 10/29/18.
// Copyright © 2018 DMS. All rights reserved.
//
/// This cell will fit the cases were you need to show an image.
/// The size must be define outside the cell, and the image will use that specific size.
/// Screenshot: https://github.com/datamindedsolutions/noteworth-ios-documentation/blob/master/CollectionView%20Shared%20Cells/ImageGalleryCollectionCell.png?raw=true
final class ImageGalleryCollectionCell: UICollectionViewCell {
let mainImageView = UIImageView(image: nil, contentMode: .scaleAspectFill)
override init(frame: CGRect) {
super.init(frame: .zero)
setupViews()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var configFile: ImageGalleryCollectionCellConfigFile?
}
extension ImageGalleryCollectionCell: GenericCollectionCellProtocol {
func collectionView(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, with item: Any) {
guard let configFile = item as? ImageGalleryCollectionCellConfigFile else { return }
self.configFile = configFile
mainImageView.contentMode = configFile.contentMode
DispatchQueue.main.async { [weak self] in
self?.mainImageView.image = configFile.image
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let configFile = self.configFile else { return }
configFile.actions?.tapGalleryImage(image: configFile.image)
}
}
private extension ImageGalleryCollectionCell {
private func setupViews() {
setupBackground()
setupMainImageView()
}
private func setupMainImageView() {
contentView.addSubview(mainImageView)
}
private func setupConstraints() {
mainImageView.bind(withConstant: 0.0, boundType: .full)
}
}
struct ImageGalleryCollectionCellConfigFile {
var image: UIImage
let contentMode: UIView.ContentMode
weak var actions: ImageGalleryTableActions?
init(image: UIImage, contentMode: UIView.ContentMode, actions: ImageGalleryTableActions?) {
self.image = image
self.contentMode = contentMode
self.actions = actions
}
}
public protocol ImageGalleryTableActions: class {
func tapGalleryImage(image: UIImage)
}
| apache-2.0 |
2345Team/Swifter-Tips | 4.Sequence/Sequence/SequenceUITests/SequenceUITests.swift | 1 | 1242 | //
// SequenceUITests.swift
// SequenceUITests
//
// Created by yangbin on 16/6/13.
// Copyright © 2016年 yangbin. All rights reserved.
//
import XCTest
class SequenceUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
RevenueCat/purchases-ios | Sources/Networking/HTTPClient/HTTPStatusCode.swift | 1 | 2100 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// HTTPStatusCode.swift
//
// Created by César de la Vega on 4/19/21.
//
import Foundation
enum HTTPStatusCode {
case success
case createdSuccess
case redirect
case notModified
case invalidRequest
case notFoundError
case internalServerError
case networkConnectTimeoutError
case other(Int)
private static let knownStatus: Set<HTTPStatusCode> = [
.success,
.createdSuccess,
.redirect,
.notModified,
.invalidRequest,
.notFoundError,
.internalServerError,
.networkConnectTimeoutError
]
private static let statusByCode: [Int: HTTPStatusCode] = Self.knownStatus.dictionaryWithKeys { $0.rawValue }
}
extension HTTPStatusCode: RawRepresentable {
init(rawValue: Int) {
self = Self.statusByCode[rawValue] ?? .other(rawValue)
}
var rawValue: Int {
switch self {
case .success: return 200
case .createdSuccess: return 201
case .redirect: return 300
case .notModified: return 304
case .invalidRequest: return 400
case .notFoundError: return 404
case .internalServerError: return 500
case .networkConnectTimeoutError: return 599
case let .other(code): return code
}
}
}
extension HTTPStatusCode: ExpressibleByIntegerLiteral {
init(integerLiteral value: IntegerLiteralType) {
self.init(rawValue: value)
}
}
extension HTTPStatusCode: Hashable {}
extension HTTPStatusCode: Codable {}
extension HTTPStatusCode {
var isSuccessfulResponse: Bool {
return 200...299 ~= self.rawValue
}
var isServerError: Bool {
return 500...599 ~= self.rawValue
}
var isSuccessfullySynced: Bool {
return !(self.isServerError || self == .notFoundError)
}
}
| mit |
jpedrosa/sua_nc | Sources/socket.swift | 2 | 8970 |
import Glibc
public typealias CSocketAddress = sockaddr
public struct SocketAddress {
public var hostName: String
public var status: Int32 = 0
public init(hostName: String) {
self.hostName = hostName
}
mutating func prepareHints() -> addrinfo {
status = 0 // Reset the status in case of subsequent calls.
var hints = addrinfo()
hints.ai_family = AF_INET
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
hints.ai_flags = AI_ADDRCONFIG
hints.ai_protocol = Int32(IPPROTO_TCP)
return hints
}
// This returns a value equivalent to a call to the C function inet_addr.
// It can be used to supply the address to a line of code such as this one:
// address.sin_addr.s_addr = inet_addr(ipString)
// E.g.
// var sa = SocketAddress(hostName: "google.com")
// address.sin_addr.s_addr = sa.ip4ToUInt32()
mutating public func ip4ToUInt32() -> UInt32? {
var hints = prepareHints()
var info = UnsafeMutablePointer<addrinfo>()
status = getaddrinfo(hostName, nil, &hints, &info)
defer {
freeaddrinfo(info)
}
if status == 0 {
return withUnsafePointer(&info.memory.ai_addr.memory) { ptr -> UInt32 in
let sin = UnsafePointer<sockaddr_in>(ptr)
return sin.memory.sin_addr.s_addr
}
}
return nil
}
// Obtain the string representation of the resolved IP4 address.
mutating public func ip4ToString() -> String? {
var hints = prepareHints()
var info = UnsafeMutablePointer<addrinfo>()
status = getaddrinfo(hostName, nil, &hints, &info)
defer {
freeaddrinfo(info)
}
if status == 0 {
return withUnsafePointer(&info.memory.ai_addr.memory) { ptr -> String? in
let len = INET_ADDRSTRLEN
let sin = UnsafePointer<sockaddr_in>(ptr)
var sin_addr = sin.memory.sin_addr
var descBuffer = [CChar](count: Int(len), repeatedValue: 0)
if inet_ntop(AF_INET, &sin_addr, &descBuffer, UInt32(len)) != nil {
return String.fromCString(descBuffer)
}
return nil
}
}
return nil
}
// Obtain a list of the string representations of the resolved IP4 addresses.
mutating public func ip4ToStringList() -> [String]? {
var hints = prepareHints()
var info = UnsafeMutablePointer<addrinfo>()
status = getaddrinfo(hostName, nil, &hints, &info)
defer {
freeaddrinfo(info)
}
if status == 0 {
var r: [String] = []
var h = info.memory
while true {
let fam = h.ai_family
let len = INET_ADDRSTRLEN
var sockaddr = h.ai_addr.memory
withUnsafePointer(&sockaddr) { ptr in
let sin = UnsafePointer<sockaddr_in>(ptr)
var sin_addr = sin.memory.sin_addr
var descBuffer = [CChar](count: Int(len), repeatedValue: 0)
if inet_ntop(fam, &sin_addr, &descBuffer, UInt32(len)) != nil {
r.append(String.fromCString(descBuffer) ?? "")
}
}
let next = h.ai_next
if next == nil {
break
} else {
h = next.memory
}
}
return r
}
return nil
}
// Obtain the string representation of the resolved IP6 address.
mutating public func ip6ToString() -> String? {
var hints = prepareHints()
hints.ai_family = AF_INET6
var info = UnsafeMutablePointer<addrinfo>()
status = getaddrinfo(hostName, nil, &hints, &info)
defer {
freeaddrinfo(info)
}
if status == 0 {
return withUnsafePointer(&info.memory.ai_addr.memory) { ptr -> String? in
let len = INET6_ADDRSTRLEN
var sa = [Int8](count: Int(len), repeatedValue: 0)
if getnameinfo(&info.memory.ai_addr.memory,
UInt32(sizeof(sockaddr_in6)), &sa, UInt32(len), nil, 0,
hints.ai_flags) == 0 {
return String.fromCString(sa)
}
return nil
}
}
return nil
}
// It will try to resolve the IP4 address and will return a C sockaddr based
// on it, or the typealias we created for it called CSocketAddress.
// This then could be used in a follow up call to the C bind function.
// E.g.
// if let sa = ip4ToCSocketAddress(port) {
// var address = sa
// let addrlen = UInt32(sizeofValue(address))
// return bind(fd, &address, addrlen)
// }
mutating public func ip4ToCSocketAddress(port: UInt16) -> CSocketAddress? {
var address = sockaddr_in()
address.sin_family = UInt16(AF_INET)
if let na = ip4ToUInt32() {
address.sin_addr.s_addr = na
address.sin_port = port.bigEndian
return withUnsafePointer(&address) { ptr -> sockaddr in
return UnsafePointer<sockaddr>(ptr).memory
}
}
return nil
}
// Handy method that does a couple of things in one go. It will first try
// to resolve the given address. Upon success, it will try to bind it to the
// given socket file descriptor and port.
// If it fails to resolve the address it will return nil. And if it fails to
// bind it will return -1.
// E.g.
// var socketAddress = SocketAddress(hostName: "127.0.0.1")
// if let br = socketAddress.ip4Bind(fd, port: 9123) {
// if br == -1 {
// print("Error: Could not start the server. Port may already be " +
// "in use by another process.")
// exit(1)
// }
// // Continue the socket setup here. [...]
// } else {
// print("Error: could not resolve the address.")
// let msg = socketAddress.errorMessage ?? ""
// print("Error message: \(msg)")
// exit(1)
// }
mutating public func ip4Bind(fd: Int32, port: UInt16) -> Int32? {
if let sa = ip4ToCSocketAddress(port) {
var address = sa
let addrlen = UInt32(sizeofValue(address))
return bind(fd, &address, addrlen)
}
return nil
}
// When an address cannot be resolved, this will return an error message that
// could be used to inform the user with.
public var errorMessage: String? {
return String.fromCString(gai_strerror(status))
}
}
public struct Socket {
var fd: Int32
public init(fd: Int32) {
self.fd = fd
}
public func write(string: String) -> Int {
return Sys.writeString(fd, string: string)
}
public func writeBytes(bytes: [UInt8], maxBytes: Int) -> Int {
return Sys.writeBytes(fd, bytes: bytes, maxBytes: maxBytes)
}
public func read(inout buffer: [UInt8], maxBytes: Int) -> Int {
return recv(fd, &buffer, maxBytes, 0)
}
public func close() {
Sys.close(fd)
}
}
public class ServerSocket {
var socketAddress: SocketAddress
var clientAddr = sockaddr_in()
var clientAddrLen: UInt32 = 0
var cSocketAddress: CSocketAddress
var fd: Int32
public init(hostName: String, port: UInt16) throws {
clientAddrLen = UInt32(sizeofValue(clientAddr))
socketAddress = SocketAddress(hostName: hostName)
fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
if fd == -1 {
throw ServerSocketError.SocketStart
}
if fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 {
throw ServerSocketError.CloexecSetup
}
var v = 1
if setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v,
socklen_t(sizeofValue(v))) == -1 {
throw ServerSocketError.ReuseAddrSetup
}
if let sa = socketAddress.ip4ToCSocketAddress(port) {
cSocketAddress = sa
var address = sa
let addrlen = UInt32(sizeofValue(address))
if bind(fd, &address, addrlen) == -1 {
throw ServerSocketError.Bind(message: "Port may be in use by " +
"another process.")
}
listen(fd, SOMAXCONN)
} else {
throw ServerSocketError.Address(message:
socketAddress.errorMessage ?? "")
}
}
public func accept() -> Socket? {
let fd = rawAccept()
if fd != -1 {
return Socket(fd: fd)
}
return nil
}
func ensureProcessCleanup() {
var sa = sigaction()
sigemptyset(&sa.sa_mask)
sa.sa_flags = SA_NOCLDWAIT
sigaction(SIGCHLD, &sa, nil)
}
public func spawnAccept(fn: (Socket) -> Void) throws {
ensureProcessCleanup();
// Create the child process.
let cfd = rawAccept()
if cfd == -1 {
throw ServerSocketError.Accept
}
let pid = fork()
if pid < 0 {
throw ServerSocketError.Fork
}
if pid == 0 {
// This is the child process.
defer {
// Ensure the process exits cleanly.
exit(0)
}
Sys.close(fd)
fn(Socket(fd: cfd))
} else {
Sys.close(cfd)
}
}
// Returns the client file descriptor directly.
public func rawAccept() -> Int32 {
return Glibc.accept(fd, &cSocketAddress, &clientAddrLen)
}
public func close() {
Sys.close(fd)
fd = -1
}
}
enum ServerSocketError: ErrorType {
case Address(message: String)
case Bind(message: String)
case SocketStart
case CloexecSetup
case ReuseAddrSetup
case Fork
case Accept
}
| apache-2.0 |
DarrenKong/firefox-ios | XCUITests/NoImageTests.swift | 3 | 1607 | /* 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 XCTest
let NoImageButtonIdentifier = "menu-NoImageMode"
let ContextMenuIdentifier = "Context Menu"
class NoImageTests: BaseTestCase {
private func showImages() {
navigator.goto(BrowserTabMenu)
app.tables[ContextMenuIdentifier].cells[NoImageButtonIdentifier].tap()
navigator.nowAt(BrowserTab)
}
private func hideImages() {
navigator.goto(BrowserTabMenu)
app.tables.cells[NoImageButtonIdentifier].tap()
navigator.nowAt(BrowserTab)
}
private func checkShowImages() {
navigator.goto(BrowserTabMenu)
waitforExistence(app.tables.cells[NoImageButtonIdentifier])
navigator.goto(BrowserTab)
}
private func checkHideImages() {
navigator.goto(BrowserTabMenu)
waitforExistence(app.tables.cells[NoImageButtonIdentifier])
navigator.goto(BrowserTab)
}
// Functionality is tested by UITests/NoImageModeTests, here only the UI is updated properly
func testImageOnOff() {
// Go to a webpage, and select no images or hide images, check it's hidden or not
navigator.openNewURL(urlString: "www.google.com")
waitUntilPageLoad()
// Select hide images, and check the UI is updated
hideImages()
checkShowImages()
// Select show images, and check the UI is updated
showImages()
checkHideImages()
}
}
| mpl-2.0 |
MoooveOn/Advanced-Frameworks | SideMenu/SideMenu/SideMenu/ViewController.swift | 1 | 593 | //
// ViewController.swift
// SideMenu
//
// Created by Pavel Selivanov on 03.07.17.
// Copyright © 2017 Pavel Selivanov. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SideMenuDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let sideMenu = SideMenu(menuWidth: 150, menuItemTitles: ["Home", "User", "Settings"], parentViewController: self)
sideMenu.menuDelegate = self
}
func didSelectMenuItem(withTitle title: String, index: Int) {
print("User has pressed row \"\(title)\"")
}
}
| mit |
ikait/KernLabel | KernLabelSample/KernLabelSample/Device.swift | 1 | 380 | //
// Device.swift
// KernLabelSample
//
// Created by Taishi Ikai on 2016/07/04.
// Copyright © 2016年 Taishi Ikai. All rights reserved.
//
import UIKit
final class Device {
static var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
static var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
}
| mit |
plumhead/OSXUtilityPanel | OSXUtilityPanel/OSXUtilityPanel/FlippedScrollView.swift | 1 | 290 | //
// FlippedScrollView.swift
// OSXUtilityPanel
//
// Created by Andrew Calderbank on 21/09/2015.
// Copyright © 2015 Andrew Calderbank. All rights reserved.
//
import Cocoa
class FlippedScrollView: NSScrollView {
override var flipped : Bool {
return true
}
}
| mit |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/Slack/View/MessageBubbleView.swift | 2 | 2184 | //
// MessageBubbleView.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 25.05.2016.
// Copyright © 2016 Macoscope. All rights reserved.
//
import UIKit
@IBDesignable
final class MessageBubbleView: UIView {
private let textToBubbleMargin = UIEdgeInsets(top: 25, left: 33, bottom: 25, right: 43)
private lazy var imageView: UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "message_bubble")!)
imageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(imageView)
return imageView
}()
private lazy var label: UILabel = { [unowned self] in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFontOfSize(40)
label.textColor = UIColor.whiteColor()
label.numberOfLines = 0
self.addSubview(label)
return label
}()
@IBInspectable var text: String = "" {
didSet {
label.text = text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setConstraints()
}
private func setConstraints() {
label.topAnchor.constraintGreaterThanOrEqualToAnchor(topAnchor, constant: textToBubbleMargin.top).active = true
label.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: textToBubbleMargin.left).active = true
label.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: -textToBubbleMargin.right).active = true
label.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -textToBubbleMargin.bottom).active = true
imageView.topAnchor.constraintEqualToAnchor(label.topAnchor, constant: -textToBubbleMargin.top).active = true
imageView.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: 0).active = true
imageView.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: 0).active = true
imageView.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: 0).active = true
}
}
| gpl-3.0 |
4taras4/totp-auth | TOTPTests/ViperModules/FolderDetails/Presenter/FolderDetailsPresenterTests.swift | 1 | 825 | //
// FolderDetailsFolderDetailsPresenterTests.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import XCTest
@testable import TOTP
class FolderDetailsPresenterTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
class MockInteractor: FolderDetailsInteractorInput {
}
class MockRouter: FolderDetailsRouterInput {
}
class MockViewController: FolderDetailsViewInput {
func setupInitialState() {
}
}
}
| mit |
sbaik/SwiftAnyPic | SwiftAnyPicTests/SwiftAnyPicTests.swift | 6 | 975 | //
// SwiftAnyPicTests.swift
// SwiftAnyPicTests
//
// Created by kw on 30/7/15.
// Copyright © 2015 parse. All rights reserved.
//
import XCTest
@testable import SwiftAnyPic
class SwiftAnyPicTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| cc0-1.0 |
kevinup7/S4HeaderExtensions | Tests/S4HeaderExtensions/ContentEncodingTests.swift | 1 | 418 | @testable import S4HeaderExtensions
import XCTest
import S4
class ContentEncodingTests: XCTestCase {
func testSingle() {
let headers = Headers(["Content-Encoding": "gzip"])
XCTAssert(headers.contentEncoding! == [.gzip])
}
func testMultiple() {
let headers = Headers(["Content-Encoding": "gzip, chunked"])
XCTAssert(headers.contentEncoding! == [.gzip, .chunked])
}
}
| mit |
gmarm/BetterSegmentedControl | Example/Tests/SnapshotHelpers.swift | 1 | 383 | //
// SnapshotHelpers.swift
// BetterSegmentedControl_Tests
//
// Created by George Marmaridis on 18.10.20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import Nimble
import Nimble_Snapshots
public func haveValidSnapshotWithAcceptableTolerance() -> Predicate<Snapshotable> {
haveValidSnapshot(named: nil, identifier: nil, usesDrawRect: false, tolerance: 0.01)
}
| mit |
pennlabs/penn-mobile-ios | PennMobile/About/Privacy/PrivacyPermissionDelegate.swift | 1 | 652 | //
// PrivacyPermissionDelegate.swift
// PennMobile
//
// Created by Dominic Holmes on 12/31/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
#if canImport(SwiftUI)
import SwiftUI
#endif
#if canImport(Combine)
import Combine
#endif
class PrivacyPermissionDelegate: ObservableObject {
var objectWillChange = PassthroughSubject<PrivacyPermissionDelegate, Never>()
var objectDidChange = PassthroughSubject<PrivacyPermissionDelegate, Never>()
var userDecision: PermissionView.Choice? {
willSet {
objectWillChange.send(self)
}
didSet {
objectDidChange.send(self)
}
}
}
| mit |
imclean/JLDishWashers | JLDishwasher/Images.swift | 1 | 1506 | //
// Images.swift
// JLDishwasher
//
// Created by Iain McLean on 21/12/2016.
// Copyright © 2016 Iain McLean. All rights reserved.
//
import Foundation
public class Images {
public var altText : String?
public var urls : [String]?
/**
Returns an array of models based on given dictionary.
Sample usage:
let images_list = Images.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
- parameter array: NSArray from JSON dictionary.
- returns: Array of Images Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [Images] {
var models:[Images] = []
for item in array {
models.append(Images(dictionary: item as! NSDictionary)!)
}
return models
}
/**
Constructs the object based on the given dictionary.
Sample usage:
let images = Images(someDictionaryFromJSON)
- parameter dictionary: NSDictionary from JSON.
- returns: Images Instance.
*/
required public init?(dictionary: NSDictionary) {
altText = dictionary["altText"] as? String
urls = dictionary["urls"] as? [String]
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.altText, forKey: "altText")
return dictionary
}
}
| gpl-3.0 |
VijayMay/WJLive | DouYuTV/DouYuTV/Code/Home/Controllers/FunnyViewController.swift | 1 | 317 | //
// FunnyViewController.swift
// DouYuTV
//
// Created by mwj on 17/4/14.
// Copyright © 2017年 MWJ. All rights reserved.
//
import UIKit
class FunnyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
}
| mit |
gowansg/firefox-ios | Providers/Profile.swift | 1 | 10105 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
public class NoAccountError: SyncError {
public var description: String {
return "No account configured."
}
}
class ProfileFileAccessor: FileAccessor {
init(profile: Profile) {
let profileDirName = "profile.\(profile.localName())"
let manager = NSFileManager.defaultManager()
// Bug 1147262: First option is for device, second is for simulator.
let url =
manager.containerURLForSecurityApplicationGroupIdentifier(ExtensionUtils.sharedContainerIdentifier()) ??
manager .URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL
let profilePath = url!.path!.stringByAppendingPathComponent(profileDirName)
super.init(rootPath: profilePath)
}
}
class CommandDiscardingSyncDelegate: SyncDelegate {
func displaySentTabForURL(URL: NSURL, title: String) {
// TODO: do something else.
log.info("Discarding sent URL \(URL.absoluteString)")
}
}
/**
* 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.
*/
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
log.info("Displaying notification for URL \(URL.absoluteString)")
app.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil))
app.registerForRemoteNotifications()
// TODO: localize.
let notification = UILocalNotification()
/* actions
notification.identifier = "tab-" + Bytes.generateGUID()
notification.activationMode = UIUserNotificationActivationMode.Foreground
notification.destructive = false
notification.authenticationRequired = true
*/
notification.alertTitle = "New tab: \(title)"
notification.alertBody = URL.absoluteString!
notification.alertAction = nil
// TODO: categories
// TODO: put the URL into the alert userInfo.
// TODO: application:didFinishLaunchingWithOptions:
// TODO:
// TODO: set additionalActions to bookmark or add to reading list.
self.app.presentLocalNotificationNow(notification)
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile {
var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: BrowserHistory { get } // TODO: protocol<BrowserHistory, SyncableHistory>.
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var passwords: Passwords { get }
var thumbnails: Thumbnails { get }
// 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
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
func getAccount() -> FirefoxAccount?
func setAccount(account: FirefoxAccount?)
func getClients() -> Deferred<Result<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>>
}
public class BrowserProfile: Profile {
private let name: String
weak private var app: UIApplication?
init(localName: String, app: UIApplication?) {
self.name = localName
self.app = app
let notificationCenter = NSNotificationCenter.defaultCenter()
let mainQueue = NSOperationQueue.mainQueue()
notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: "LocationChange", object: nil)
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
@objc
func onLocationChange(notification: NSNotification) {
if let url = notification.userInfo!["url"] as? NSURL {
var site: Site!
if let title = notification.userInfo!["title"] as? NSString {
site = Site(url: url.absoluteString!, title: title as String)
let visit = Visit(site: site, date: NSDate())
history.addVisit(visit, complete: { (success) -> Void in
// nothing to do
})
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func localName() -> String {
return name
}
var files: FileAccessor {
return ProfileFileAccessor(profile: self)
}
lazy var db: BrowserDB = {
return BrowserDB(files: self.files)
} ()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
return BookmarksSqliteFactory(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
} ()
func makePrefs() -> Prefs {
return NSUserDefaultsProfilePrefs(profile: self)
}
lazy var favicons: Favicons = {
return SQLiteFavicons(db: self.db)
}()
// lazy var ReadingList readingList
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var history: BrowserHistory = {
return SQLiteHistory(db: self.db)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
private class func syncClientsToStorage(storage: RemoteClientsAndTabs, delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> Deferred<Result<Ready>> {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
let success = clientSynchronizer.synchronizeLocalClients(storage, withServer: ready.client, info: ready.info)
return success >>== always(ready)
}
private class func syncTabsToStorage(storage: RemoteClientsAndTabs, delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> Deferred<Result<RemoteClientsAndTabs>> {
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
let success = tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
return success >>== always(storage)
}
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandDiscardingSyncDelegate()
}
public func getClients() -> Deferred<Result<[RemoteClient]>> {
if let account = self.account {
let authState = account.syncAuthState
let syncPrefs = self.prefs.branch("sync")
let storage = self.remoteClientsAndTabs
let ready = SyncStateMachine.toReady(authState, prefs: syncPrefs)
let delegate = self.getSyncDelegate()
let syncClients = curry(BrowserProfile.syncClientsToStorage)(storage, delegate, syncPrefs)
return ready
>>== syncClients
>>> { return storage.getClients() }
}
return deferResult(NoAccountError())
}
public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
log.info("Account is \(self.account), app is \(self.app)")
if let account = self.account {
log.debug("Fetching clients and tabs.")
let authState = account.syncAuthState
let syncPrefs = self.prefs.branch("sync")
let storage = self.remoteClientsAndTabs
let ready = SyncStateMachine.toReady(authState, prefs: syncPrefs)
let delegate = self.getSyncDelegate()
let syncClients = curry(BrowserProfile.syncClientsToStorage)(storage, delegate, syncPrefs)
let syncTabs = curry(BrowserProfile.syncTabsToStorage)(storage, delegate, syncPrefs)
return ready
>>== syncClients
>>== syncTabs
>>> { return storage.getClientsAndTabs() }
}
return deferResult(NoAccountError())
}
lazy var passwords: Passwords = {
return SQLitePasswords(db: self.db)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount?) {
if account == nil {
KeychainWrapper.removeObjectForKey(name + ".account")
} else {
KeychainWrapper.setObject(account!.asDictionary(), forKey: name + ".account")
}
self.account = account
}
}
| mpl-2.0 |
zmian/xcore.swift | Sources/Xcore/Swift/Components/Dates and Timers/Date/Calendar+Component+RawRepresentable.swift | 1 | 2577 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension Calendar.Component: RawRepresentable {
public init?(rawValue: String) {
switch rawValue {
case Self.era.rawValue:
self = .era
case Self.year.rawValue:
self = .year
case Self.month.rawValue:
self = .month
case Self.day.rawValue:
self = .day
case Self.hour.rawValue:
self = .hour
case Self.minute.rawValue:
self = .minute
case Self.second.rawValue:
self = .second
case Self.weekday.rawValue:
self = .weekday
case Self.weekdayOrdinal.rawValue:
self = .weekdayOrdinal
case Self.quarter.rawValue:
self = .quarter
case Self.weekOfMonth.rawValue:
self = .weekOfMonth
case Self.weekOfYear.rawValue:
self = .weekOfYear
case Self.yearForWeekOfYear.rawValue:
self = .yearForWeekOfYear
case Self.nanosecond.rawValue:
self = .nanosecond
case Self.calendar.rawValue:
self = .calendar
case Self.timeZone.rawValue:
self = .timeZone
default:
return nil
}
}
public var rawValue: String {
switch self {
case .era:
return "era"
case .year:
return "year"
case .month:
return "month"
case .day:
return "day"
case .hour:
return "hour"
case .minute:
return "minute"
case .second:
return "second"
case .weekday:
return "weekday"
case .weekdayOrdinal:
return "weekdayOrdinal"
case .quarter:
return "quarter"
case .weekOfMonth:
return "weekOfMonth"
case .weekOfYear:
return "weekOfYear"
case .yearForWeekOfYear:
return "yearForWeekOfYear"
case .nanosecond:
return "nanosecond"
case .calendar:
return "calendar"
case .timeZone:
return "timeZone"
@unknown default:
return "unknown"
}
}
}
| mit |
djschilling/SOPA-iOS | SOPA/model/game/PathState.swift | 1 | 237 | //
// PathState.swift
// SOPA
//
// Created by David Schilling on 21.10.17.
// Copyright © 2017 David Schilling. All rights reserved.
//
import Foundation
enum PathState {
case UNDEFINED
case POSIBLE
case IMPOSSIBLE
}
| apache-2.0 |
Miguel-Herrero/Swift | Rainy Shiny Cloudy/Rainy Shiny Cloudy/WeatherVC.swift | 1 | 4765 | //
// WeatherVC.swift
// Rainy Shiny Cloudy
//
// Created by Miguel Herrero on 13/12/16.
// Copyright © 2016 Miguel Herrero. All rights reserved.
//
import UIKit
import Alamofire
import CoreLocation
class WeatherVC: UIViewController {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var currentTempLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var currentTempImage: UIImageView!
@IBOutlet weak var currentTempTypeLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var currentWeather: CurrentWeather!
var forecast: Forecast!
var forecasts = [Forecast]()
let locationManager = CLLocationManager()
var currentLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation() //Step-1 Requesting location updates
currentWeather = CurrentWeather()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
func updateMainUI() {
dateLabel.text = currentWeather.date
currentTempLabel.text = "\(currentWeather.currentTemp) ºC"
currentTempTypeLabel.text = currentWeather.weatherType
locationLabel.text = currentWeather.cityName
currentTempImage.image = UIImage(named: currentWeather.weatherType)
tableView.reloadData()
}
func downloadForecastData(completed: @escaping DownloadComplete) {
// DOwnload forecast weather data for TableView
let forecastURL = URL(string: FORECAST_URL)!
Alamofire.request(forecastURL).responseJSON { (response) in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let list = dict["list"] as? [Dictionary<String, AnyObject>] {
for obj in list {
let forecast = Forecast(weatherDict: obj)
self.forecasts.append(forecast)
}
self.forecasts.remove(at: 0) //Remove today from forecast!
}
}
completed()
}
}
}
extension WeatherVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecasts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "weatherCell", for: indexPath) as? WeatherCell {
let forecast = forecasts[indexPath.row]
cell.configureCell(forecast: forecast)
return cell
} else {
return WeatherCell()
}
}
}
extension WeatherVC: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
locationAuthStatus()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
currentLocation = locationManager.location
if currentLocation != nil {
locationManager.stopUpdatingLocation()
}
Location.sharedInstance.latitude = currentLocation.coordinate.latitude
Location.sharedInstance.longitude = currentLocation.coordinate.longitude
print(Location.sharedInstance.latitude ?? "nada", Location.sharedInstance.longitude ?? "nada")
currentWeather.downloadWeatherDetails {
//Setup UI to load downloaded data
self.downloadForecastData {
self.updateMainUI()
}
}
} else {
locationManager.requestWhenInUseAuthorization()
}
}
/*
* If CLLocation is not authorized, we cannot show any weather info
*/
func locationAuthStatus() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
}
| gpl-3.0 |
devxoul/Drrrible | DrrribleTests/Sources/TestMain.swift | 1 | 176 | //
// TestMain.swift
// Drrrible
//
// Created by Suyeol Jeon on 18/04/2017.
// Copyright © 2017 Suyeol Jeon. All rights reserved.
//
import ReactorKit
import RxOptional
| mit |
vexy/Fridge | Tests/FridgeTests/FreezerTests.swift | 1 | 5672 | /*
//
// FreezerTests.swift
// FridgeTests
//
// Created by Veljko Tekelerovic on 21.1.20.
MIT License
Copyright (c) 2016 Veljko Tekelerović
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 XCTest
@testable import Fridge
fileprivate struct FridgeTestObject: Codable {
let string_field: String
let int_field: Int
let dict_field: InnerTestObject
let arr_field: [Int]
let data_field: Data
let url_field: URL
static let IDENTIFIER = "Test.OBJECT"
init() {
string_field = "Some f🧊ncy string"
int_field = Int.max
dict_field = InnerTestObject()
arr_field = [0xABCDEF, 0xCAB0CAB, 0xFADE, 0xEFCAD]
data_field = Data(repeating: 0xAE, count: 0xE1FE1)
url_field = URL(fileURLWithPath: "someFilePathOfAMockObject")
}
}
fileprivate struct InnerTestObject: Codable {
var field1: String? = nil
var field2: Float = 1_234_567.890_001
var field3: Double = Double.pi
var field4: Date = Date.init()
var field5: Bool = !false
var field6: Set = Set([1,2,3])
var field7: Array<Int64> = Array.init()
}
extension FridgeTestObject: Equatable {
static func ==(lhs: FridgeTestObject, rhs: FridgeTestObject) -> Bool {
let equality =
(lhs.string_field == rhs.string_field) &&
(lhs.int_field == rhs.int_field) &&
(lhs.arr_field == rhs.arr_field) &&
(lhs.data_field == rhs.data_field) &&
(lhs.url_field == rhs.url_field)
return equality
}
}
// !! LET THE HUNT BEGIN !! 🕵️♂️🥷
final class FreezerTests: XCTestCase {
// SHARED TESTING OBJECT
let freezer = Freezer()
/// Tests weather an object can be saved without throwing error
func testObjectFreezing(){
let testData = FridgeTestObject()
XCTAssertNoThrow(try freezer.freeze(object: testData, identifier: FridgeTestObject.IDENTIFIER))
}
/// Tests weather an object can be loaded without throwing error
func testObjectUnfreezing() {
//freeze an object first
let frozenObject = FridgeTestObject()
XCTAssertNoThrow(try freezer.freeze(object: frozenObject, identifier: FridgeTestObject.IDENTIFIER))
do {
//unfreeze it now
let unFrozenObject: FridgeTestObject = try freezer.unfreeze(identifier: FridgeTestObject.IDENTIFIER)
//make sure they are equal
XCTAssert(frozenObject == unFrozenObject)
} catch {
XCTFail("Unable to unfeeze frozen object")
}
}
func testPersistancyChecks() {
XCTAssert(freezer.isAlreadyFrozen(identifier: FridgeTestObject.IDENTIFIER))
XCTAssertFalse(freezer.isAlreadyFrozen(identifier: "non_existant_object"))
}
/// Tests if array can be stored
func testArrayFreezing() throws {
XCTAssertFalse(freezer.isAlreadyFrozen(identifier: "array.test"))
let foundationArray = [1,2,3,4,5,6,7,8]
let customStructArray: Array<FridgeTestObject> = [FridgeTestObject(), FridgeTestObject()]
XCTAssertNoThrow(try freezer.freeze(objects: foundationArray, identifier: "foundation.array"))
XCTAssertNoThrow(try freezer.freeze(objects: customStructArray, identifier: "array-object.test"))
// make sure it actually throws when passed incorrectly
XCTAssertThrowsError(try freezer.freeze(object: foundationArray, identifier: "wrong.method.array"))
XCTAssertThrowsError(try freezer.freeze(object: customStructArray, identifier: "wrong.method.custom.array"))
}
/// Tests if array can be read from the storage
func testArrayUnFreezing() throws {
let expectedFoundationArray = [1,2,3,4,5,6,7,8]
let expectedStructArray: Array<FridgeTestObject> = [FridgeTestObject(), FridgeTestObject()]
var failureMessage: String
do {
// check foundation
failureMessage = "Foundation array issue"
let unfrozenFoundation: Array<Int> = try freezer.unfreeze(identifier: "foundation.array")
XCTAssert(unfrozenFoundation == expectedFoundationArray)
failureMessage = "Array of custom struct issue"
let unfrozenCustomArray: Array<FridgeTestObject> = try freezer.unfreeze(identifier: "array-object.test")
XCTAssert(unfrozenCustomArray[0] == expectedStructArray[0])
// XCTAssert(unfrozenCustomArray[0].dict_field == expectedStructArray[0].dict_field)
} catch {
XCTFail(failureMessage)
}
}
}
| mit |
cameronpit/Unblocker | Unblocker/Program constants.swift | 1 | 2208 | //
// Program constants.swift
//
// Unblocker
// Swift 3.1
//
// Copyright © 2017 Cameron C. Pitcairn.
// See the file license.txt in the Unblocker project.
//
import UIKit
/*******************************************************************************
Const is a globally-available struct which defines various constants used
by the program.
******************************************************************************/
struct Const {
static let rows = 6, cols = 6 // Board is always 6 x 6
static let gapRatio = CGFloat(1.0/20) // Ratio of gap between blocks to tile size
static let imageTruncation = 10 // rows to ignore at top & bottom of original image
static let borderWidth: CGFloat = 15
// Colors for displaying board
static let prisonerBlockColor = UIColor.red
static let normalBlockColor = UIColor(red: 239/255, green: 195/255, blue: 132/255, alpha: 1)
static let rivetColor = UIColor.gray
static let boardBackgroundColor = UIColor(red: 106/255, green: 73/255, blue: 30/255, alpha: 1)
static let emptyBackgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
static let escapeColor = UIColor(red: 106/255, green: 73/255, blue: 30/255, alpha: 1)
static let normalMessageLabelColor = UIColor.black
static let urgentMessageLabelColor = UIColor.red
// Color thresholds for scanning image (determined empirically)
static let startEscapeRedHiThreshold:UInt8 = 120 // is > red component of escape chute
static let endEscapeRedLoThreshold:UInt8 = 130 // is < red component of frame
static let startBlackLineRedHiThreshold:UInt8 = 50 // is > red component of horizonal black line
static let endBlackLineRedLoThreshold:UInt8 = 70 // is < red component of not-a-black-line
static let edgeRedHiThreshold:UInt8 = 125 // is > red component of edge color
static let emptyRedHiThreshold:UInt8 = 125 // is > red component of empty color
static let redBlockGreenHiThreshold:UInt8 = 100 // is > green component of red block color
// Animation timings (in seconds)
static let blockViewAnimationDuration = 0.5
static let blockViewAnimationDelay = 0.5
static let boardViewResetAnimationDuration = 0.3
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.