repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
simonnarang/Fandom-IOS | Fandomm/RedisClient.swift | 2 | 15357 | //
// RedisClient.swift
// Redis-Framework
//
// Copyright (c) 2015, Eric Orion Anderson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
public let RedisErrorDomain = "com.rareairconsulting.redis"
public enum RedisLogSeverity:String
{
case Info = "Info"
case Debug = "Debug"
case Error = "Error"
case Critical = "Critical"
}
public typealias RedisLoggingBlock = ((redisClient:AnyObject, message:String, severity:RedisLogSeverity) -> Void)?
public typealias RedisCommandStringBlock = ((string:String!, error:NSError!)->Void)
public typealias RedisCommandIntegerBlock = ((int:Int!, error:NSError!)->Void)
public typealias RedisCommandArrayBlock = ((array:[AnyObject]!, error:NSError!)->Void)
public typealias RedisCommandDataBlock = ((data:NSData!, error:NSError!)->Void)
/// RedisClient
///
/// A simple redis client that can be extended for supported Redis commands.
/// This client expects a response for each request and acts as a serial queue.
/// See: RedisPubSubClient for publish/subscribe functionality.
public class RedisClient
{
private let _loggingBlock:RedisLoggingBlock
private let _delegateQueue:NSOperationQueue!
private let _serverHost:String!
private let _serverPort:Int!
lazy private var _commander:RESPCommander = RESPCommander(redisClient: self)
internal var closeExpected:Bool = false {
didSet {
self._commander._closeExpected = self.closeExpected
}
}
public var host:String {
return self._serverHost
}
public var port:Int {
return self._serverPort
}
internal func performBlockOnDelegateQueue(block:dispatch_block_t) -> Void {
self._delegateQueue.addOperationWithBlock(block)
}
public init(host:String, port:Int, loggingBlock:RedisLoggingBlock? = nil, delegateQueue:NSOperationQueue? = nil)
{
self._serverHost = host
self._serverPort = port
if loggingBlock == nil
{
self._loggingBlock = {(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
switch(severity)
{
case .Critical, .Error:
print(message)
default: break
}
}
}
else {
self._loggingBlock = loggingBlock!
}
if delegateQueue == nil {
self._delegateQueue = NSOperationQueue.mainQueue()
}
else {
self._delegateQueue = delegateQueue
}
}
public func sendCommandWithArrayResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandArrayBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(array: nil, error: error)
}
else {
let parsingResults:(array:[AnyObject]!, error:NSError!) = RESPUtilities.respArrayFromData(data)
completionHandler(array: parsingResults.array, error: parsingResults.error)
}
})
})
}
public func sendCommandWithIntegerResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandIntegerBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(int: nil, error: error)
}
else {
let parsingResults:(int:Int!, error:NSError!) = RESPUtilities.respIntegerFromData(data)
completionHandler(int: parsingResults.int, error: parsingResults.error)
}
})
})
}
public func sendCommandWithStringResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandStringBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), data:data, completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(string: nil, error: error)
}
else {
let parsingResults = RESPUtilities.respStringFromData(data)
completionHandler(string: parsingResults.string, error: parsingResults.error)
}
})
})
}
public func sendCommandWithDataResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandDataBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
completionHandler(data: data, error: error)
})
})
}
private func log(message:String, severity:RedisLogSeverity)
{
if NSThread.isMainThread() {
self._loggingBlock!(redisClient: self, message: message, severity: severity)
}
else {
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self._loggingBlock!(redisClient: self, message: message, severity: severity)
})
}
}
}
private class RESPCommander:NSObject, NSStreamDelegate
{
private let _redisClient:RedisClient!
private var _inputStream:NSInputStream!
private var _outputStream:NSOutputStream!
private let _operationQueue:NSOperationQueue!
private let _commandLock:dispatch_semaphore_t!
private let _queueLock:dispatch_semaphore_t!
private var _incomingData:NSMutableData!
private let operationLock:String = "RedisOperationLock"
private var _queuedCommand:String! = nil
private var _queuedData:NSData! = nil
private var _error:NSError?
private var _closeExpected:Bool = false
private func _closeStreams()
{
if self._inputStream != nil
{
self._inputStream.close()
self._inputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream = nil
}
if self._outputStream != nil
{
self._outputStream.close()
self._outputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream = nil
}
}
private func _openStreams()
{
self._closeStreams()
var readStream:NSInputStream? = nil
var writeStream:NSOutputStream? = nil
NSStream.getStreamsToHostWithName(self._redisClient._serverHost, port: self._redisClient._serverPort, inputStream: &readStream, outputStream: &writeStream)
self._inputStream = readStream
self._outputStream = writeStream
self._inputStream.delegate = self
self._outputStream.delegate = self
self._inputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream.open()
self._outputStream.open()
}
init(redisClient: RedisClient)
{
self._commandLock = dispatch_semaphore_create(0);
self._queueLock = dispatch_semaphore_create(1)
self._operationQueue = NSOperationQueue()
self._redisClient = redisClient
super.init()
self._openStreams()
}
@objc func stream(theStream: NSStream, handleEvent streamEvent: NSStreamEvent)
{
switch(streamEvent)
{
case NSStreamEvent.HasBytesAvailable:
if self._inputStream === theStream //reading
{
self._redisClient.log("\tHasBytesAvailable", severity: .Debug)
self._redisClient.log("\t--READING COMMAND RESPONSE---", severity: .Debug)
let bufferSize:Int = 1024
var buffer = [UInt8](count: bufferSize, repeatedValue: 0)
let bytesRead:Int = self._inputStream.read(&buffer, maxLength: bufferSize)
self._redisClient.log("\tbytes read:\(bytesRead)", severity: .Debug)
let data = NSData(bytes: buffer, length: bytesRead)
if bytesRead == bufferSize && self._inputStream.hasBytesAvailable //reached the end of the buffer, more to come
{
if self._incomingData != nil { //there was existing data
self._incomingData.appendData(data)
}
else {
self._incomingData = NSMutableData(data: data)
}
}
else if bytesRead > 0 //finished
{
if self._incomingData != nil //there was existing data
{
self._incomingData.appendData(data)
}
else { //got it all in one shot
self._incomingData = NSMutableData(data: data)
}
self._redisClient.log("\tfinished reading", severity: .Debug)
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
else
{
if !self._closeExpected
{
self._error = NSError(domain: "com.rareairconsulting.resp", code: 0, userInfo: [NSLocalizedDescriptionKey:"Error occured while reading."])
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
}
}
case NSStreamEvent.HasSpaceAvailable:
self._redisClient.log("\tHasSpaceAvailable", severity: .Debug)
if theStream === self._outputStream && self._queuedCommand != nil { //writing
self._sendQueuedCommand()
}
case NSStreamEvent.OpenCompleted:
self._redisClient.log("\tOpenCompleted", severity: .Debug)
case NSStreamEvent.ErrorOccurred:
self._redisClient.log("\tErrorOccurred", severity: .Debug)
self._error = theStream.streamError
dispatch_semaphore_signal(self._commandLock) //signal we are done
case NSStreamEvent.EndEncountered: //cleanup
self._redisClient.log("\tEndEncountered", severity: .Debug)
self._closeStreams()
default:
break
}
}
private func _sendQueuedCommand()
{
let queuedCommand = self._queuedCommand
self._queuedCommand = nil
if queuedCommand != nil && !queuedCommand.isEmpty
{
self._redisClient.log("\t--SENDING COMMAND (\(queuedCommand))---", severity: .Debug)
let commandStringData:NSMutableData = NSMutableData(data: queuedCommand.dataUsingEncoding(NSUTF8StringEncoding)!)
if self._queuedData != nil
{
commandStringData.appendData("$\(self._queuedData.length)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
commandStringData.appendData(self._queuedData)
commandStringData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
self._queuedData = nil
}
self._incomingData = nil
let bytesWritten = self._outputStream.write(UnsafePointer<UInt8>(commandStringData.bytes), maxLength: commandStringData.length)
self._redisClient.log("\tbytes sent: \(bytesWritten)", severity: .Debug)
}
}
private func sendCommand(command:NSString, data:NSData? = nil, completionHandler:RedisCommandDataBlock)
{
//could probably use gcd barriers for this but this seems good for now
self._operationQueue.addOperationWithBlock { [unowned self] () -> Void in
self._redisClient.log("***Adding to the command queue***", severity: .Debug)
dispatch_semaphore_wait(self._queueLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***New command starting off queue***", severity: .Debug)
self._queuedCommand = command as String
self._queuedData = data
if self._inputStream != nil
{
switch(self._inputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
default: break
}
}
else {
self._openStreams()
}
switch(self._outputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
case NSStreamStatus.Open:
self._sendQueuedCommand()
default: break
}
dispatch_semaphore_wait(self._commandLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***Releasing command queue lock***", severity: .Debug)
completionHandler(data: self._incomingData, error: self._error)
dispatch_semaphore_signal(self._queueLock)
}
}
}
| unlicense | e90c115f434ea2e988a8cfa001aada9d | 42.381356 | 166 | 0.598359 | 5.156817 | false | false | false | false |
CodeEagle/SSPhotoKit | Example/Classes/ExPhoto.swift | 1 | 4455 | //
// ExPhoto.swift
// SSPhotoKit
//
// Created by LawLincoln on 15/7/24.
// Copyright (c) 2015年 CocoaPods. All rights reserved.
//
import UIKit
import Photos
extension PHAsset {
var image: UIImage! {
let cache = NSURLCache.sharedURLCache()
let key = "https://\(identifier)"
let url = NSURL(string: key)!
let request = NSURLRequest(URL: url)
if let data = cache.cachedResponseForRequest(request)?.data, img = UIImage(data: data) {
return img
}
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
var thumbnail: UIImage! = UIImage()
let scale = UIScreen.mainScreen().scale
var asize = Config.kGroupSize
asize.width *= scale
asize.height *= scale
option.synchronous = true
option.normalizedCropRect = CGRect(origin: CGPointZero, size: asize)
option.resizeMode = .Exact
manager.requestImageForAsset(self, targetSize: asize, contentMode: .AspectFill, options: option, resultHandler: { (result, info) -> Void in
if let img = result {
thumbnail = img
if let data = UIImageJPEGRepresentation(img, 1) {
let resp = NSURLResponse(URL: url, MIMEType: nil, expectedContentLength: 0, textEncodingName: nil)
cache.storeCachedResponse(NSCachedURLResponse(response: resp, data: data), forRequest: request)
}
}
})
return thumbnail
}
var identifier: String {
return self.localIdentifier// .pathComponents[0]
}
func imageWithSize(size: CGSize, done: (UIImage) -> ()) {
let cache = NSURLCache.sharedURLCache()
let key = "https://" + identifier + "-original"
let url = NSURL(string: key)!
let request = NSURLRequest(URL: url)
if let data = cache.cachedResponseForRequest(request)?.data, img = UIImage(data: data) {
done(img)
}
let manager = PHImageManager.defaultManager()
let option = PHImageRequestOptions()
option.synchronous = false
option.networkAccessAllowed = true
option.normalizedCropRect = CGRect(origin: CGPointZero, size: size)
option.resizeMode = .Exact
option.progressHandler = {
(progress, error, stop, info) -> Void in
print(progress, terminator: "")
print(info, terminator: "")
}
manager.requestImageForAsset(self, targetSize: size, contentMode: .AspectFill, options: option, resultHandler: { (result, info) -> Void in
if let img = result {
if let data = UIImageJPEGRepresentation(img, 1) {
let resp = NSURLResponse(URL: url, MIMEType: nil, expectedContentLength: 0, textEncodingName: nil)
cache.storeCachedResponse(NSCachedURLResponse(response: resp, data: data), forRequest: request)
}
done(img)
}
})
}
}
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
// let radiansToDegrees: (CGFloat) -> CGFloat = {
// return $0 * (180.0 / CGFloat(M_PI))
// }
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if (flip) {
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public func toTintColor(color: UIColor) -> UIImage! {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
color.setFill()
let bounds = CGRectMake(0, 0, self.size.width, self.size.height)
UIRectFill(bounds)
self.drawInRect(bounds, blendMode: CGBlendMode.DestinationIn, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return tintedImage
}
} | mit | eab5a2c794bc0922c77a3e07151b20bc | 30.588652 | 141 | 0.71435 | 3.835487 | false | false | false | false |
thebnich/firefox-ios | SyncTests/HistorySynchronizerTests.swift | 1 | 9168 | /* 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 Shared
import Storage
import XCGLogger
import XCTest
private let log = Logger.syncLogger
class MockSyncDelegate: SyncDelegate {
func displaySentTabForURL(URL: NSURL, title: String) {
}
}
class DBPlace: Place {
var isDeleted = false
var shouldUpload = false
var serverModified: Timestamp? = nil
var localModified: Timestamp? = nil
}
class MockSyncableHistory {
var wasReset: Bool = false
var places = [GUID: DBPlace]()
var remoteVisits = [GUID: Set<Visit>]()
var localVisits = [GUID: Set<Visit>]()
init() {
}
private func placeForURL(url: String) -> DBPlace? {
return findOneValue(places) { $0.url == url }
}
}
extension MockSyncableHistory: ResettableSyncStorage {
func resetClient() -> Success {
self.wasReset = true
return succeed()
}
}
extension MockSyncableHistory: SyncableHistory {
// TODO: consider comparing the timestamp to local visits, perhaps opting to
// not delete the local place (and instead to give it a new GUID) if the visits
// are newer than the deletion.
// Obviously this'll behave badly during reconciling on other devices:
// they might apply our new record first, renaming their local copy of
// the old record with that URL, and thus bring all the old visits back to life.
// Desktop just finds by GUID then deletes by URL.
func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> {
self.remoteVisits.removeValueForKey(guid)
self.localVisits.removeValueForKey(guid)
self.places.removeValueForKey(guid)
return succeed()
}
/**
* This assumes that the provided GUID doesn't already map to a different URL!
*/
func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success {
// Find by URL.
if let existing = self.placeForURL(url) {
let p = DBPlace(guid: guid, url: url, title: existing.title)
p.isDeleted = existing.isDeleted
p.serverModified = existing.serverModified
p.localModified = existing.localModified
self.places.removeValueForKey(existing.guid)
self.places[guid] = p
}
return succeed()
}
func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success {
// Strip out existing local visits.
// We trust that an identical timestamp and type implies an identical visit.
var remote = Set<Visit>(visits)
if let local = self.localVisits[guid] {
remote.subtractInPlace(local)
}
// Visits are only ever added.
if var r = self.remoteVisits[guid] {
r.unionInPlace(remote)
} else {
self.remoteVisits[guid] = remote
}
return succeed()
}
func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// See if we've already applied this one.
if let existingModified = self.places[place.guid]?.serverModified {
if existingModified == modified {
log.debug("Already seen unchanged record \(place.guid).")
return deferMaybe(place.guid)
}
}
// Make sure that we collide with any matching URLs -- whether locally
// modified or not. Then overwrite the upstream and merge any local changes.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> {
if let existingLocal = self.places[place.guid] {
if existingLocal.shouldUpload {
log.debug("Record \(existingLocal.guid) modified locally and remotely.")
log.debug("Local modified: \(existingLocal.localModified); remote: \(modified).")
// Should always be a value if marked as changed.
if existingLocal.localModified! > modified {
// Nothing to do: it's marked as changed.
log.debug("Discarding remote non-visit changes!")
self.places[place.guid]?.serverModified = modified
return deferMaybe(place.guid)
} else {
log.debug("Discarding local non-visit changes!")
self.places[place.guid]?.shouldUpload = false
}
} else {
log.debug("Remote record exists, but has no local changes.")
}
} else {
log.debug("Remote record doesn't exist locally.")
}
// Apply the new remote record.
let p = DBPlace(guid: place.guid, url: place.url, title: place.title)
p.localModified = NSDate.now()
p.serverModified = modified
p.isDeleted = false
self.places[place.guid] = p
return deferMaybe(place.guid)
}
}
func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// TODO.
return deferMaybe([])
}
func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO.
return deferMaybe([])
}
func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO
return deferMaybe(0)
}
func markAsDeleted(_: [GUID]) -> Success {
// TODO
return succeed()
}
func onRemovedAccount() -> Success {
// TODO
return succeed()
}
func doneApplyingRecordsAfterDownload() -> Success {
return succeed()
}
func doneUpdatingMetadataAfterUpload() -> Success {
return succeed()
}
}
class HistorySynchronizerTests: XCTestCase {
private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: protocol<SyncableHistory, ResettableSyncStorage>) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) {
let delegate = MockSyncDelegate()
// We can use these useless values because we're directly injecting decrypted
// payloads; no need for real keys etc.
let prefs = MockProfilePrefs()
let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs)
let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs)
let ts = NSDate.now()
let expectation = expectationWithDescription("Waiting for application.")
var succeeded = false
synchronizer.applyIncomingToStorage(storage, records: records, fetched: ts)
.upon({ result in
succeeded = result.isSuccess
expectation.fulfill()
})
waitForExpectationsWithTimeout(10, handler: nil)
XCTAssertTrue(succeeded, "Application succeeded.")
return (synchronizer, prefs, scratchpad)
}
func testApplyRecords() {
let earliest = NSDate.now()
func assertTimestampIsReasonable(synchronizer: HistorySynchronizer) {
XCTAssertTrue(earliest <= synchronizer.lastFetched, "Timestamp is reasonable (lower).")
XCTAssertTrue(NSDate.now() >= synchronizer.lastFetched, "Timestamp is reasonable (upper).")
}
let empty = MockSyncableHistory()
let noRecords = [Record<HistoryPayload>]()
// Apply no records.
assertTimestampIsReasonable(self.applyRecords(noRecords, toStorage: empty).synchronizer)
// Hey look! Nothing changed.
XCTAssertTrue(empty.places.isEmpty)
XCTAssertTrue(empty.remoteVisits.isEmpty)
XCTAssertTrue(empty.localVisits.isEmpty)
// Apply one remote record.
let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}"
let pA = HistoryPayload.fromJSON(JSON.parse(jA))!
let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000)
let (synchronizer, prefs, _) = self.applyRecords([rA], toStorage: empty)
assertTimestampIsReasonable(synchronizer)
// The record was stored. This is checking our mock implementation, but real storage should work, too!
XCTAssertEqual(1, empty.places.count)
XCTAssertEqual(1, empty.remoteVisits.count)
XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count)
XCTAssertTrue(empty.localVisits.isEmpty)
// Test resetting now that we have a timestamp.
XCTAssertFalse(empty.wasReset)
XCTAssertTrue(0 < synchronizer.lastFetched)
XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess)
XCTAssertTrue(empty.wasReset)
XCTAssertFalse(0 < synchronizer.lastFetched)
}
} | mpl-2.0 | 4cda6ec3fcbbd7520dee8b078180d41d | 37.041494 | 212 | 0.619396 | 5.003821 | false | false | false | false |
suifengqjn/swiftDemo | Swift基本语法-黑马笔记/继承/main.swift | 1 | 6779 | //
// main.swift
// 继承
//
// Created by 李南江 on 15/4/4.
// Copyright (c) 2015年 itcast. All rights reserved.
//
import Foundation
/*
继承语法
继承是面向对象最显著的一个特性, 继承是从已经有的类中派生出新的类
新的类能够继承已有类的属性和方法, 并能扩展新的能力
术语: 基类(父类, 超类), 派生类(子类, 继承类)
语法:
class 子类: 父类{
}
继承有点: 代码重用
继承缺点: 增加程序耦合度, 父类改变会影响子类
注意:Swift和OC一样没有多继承
*/
class Man {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan: Man {
var power:Int = 100
func fly(){
// 子类可以继承父类的属性
print("飞 \(name) \(age)")
}
}
var m = Man()
m.sleep()
//m.fly() // 父类不可以使用子类的方法
var sm = SuperMan()
sm.sleep()// 子类可以继承父类的方法
sm.fly()
/*
super关键字:
派生类中可以通过super关键字来引用父类的属性和方法
*/
class Man2 {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan2: Man2 {
var power:Int = 100
func eat()
{
print("吃饭")
}
func fly(){
// 子类可以继承父类的属性
print("飞 \(super.name) \(super.age)")
}
func eatAndSleep()
{
eat()
super.sleep()
// 如果没有写super, 那么会现在当前类中查找, 如果找不到再去父类中查找
// 如果写了super, 会直接去父类中查找
}
}
var sm2 = SuperMan2()
sm2.eatAndSleep()
/*
方法重写: override
重写父类方法, 必须加上override关键字
*/
class Man3 {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan3: Man3 {
var power:Int = 100
// override关键字主要是为了明确表示重写父类方法,
// 所以如果要重写父类方法, 必须加上override关键字
override func sleep() {
// sleep() // 不能这样写, 会导致递归
super.sleep()
print("子类睡觉")
}
func eat()
{
print("吃饭")
}
func fly(){
// 子类可以继承父类的属性
print("飞 \(super.name) \(super.age)")
}
func eatAndSleep()
{
eat()
sleep()
}
}
var sm3 = SuperMan3()
// 通过子类调用, 优先调用子类重写的方法
//sm3.sleep()
sm3.eatAndSleep()
/*
重写属性
无论是存储属性还是计算属性, 都只能重写为计算属性
*/
class Man4 {
var name:String = "lnj" // 存储属性
var age: Int { // 计算属性
get{
return 30
}
set{
print("man new age \(newValue)")
}
}
func sleep(){
print("睡觉")
}
}
class SuperMan4: Man4 {
var power:Int = 100
// 可以将父类的存储属性重写为计算属性
// 但不可以将父类的存储属性又重写为存储属性, 因为这样没有意义
// override var name:String = "zs"
override var name:String{
get{
return "zs"
}
set{
print("SuperMan new name \(newValue)")
}
}
// 可以将父类的计算属性重写为计算属性, 同样不能重写为存储属性
override var age: Int { // 计算属性
get{
return 30
}
set{
print("superMan new age \(newValue)")
}
}
}
let sm4 = SuperMan4()
// 通过子类对象来调用重写的属性或者方法, 肯定会调用子类中重写的版本
sm4.name = "xxx"
sm4.age = 50
/*
重写属性的限制
1.读写计算属性/存储属性, 是否可以重写为只读计算属性? (权限变小)不可以
2.只读计算属性, 是否可以在重写时变成读写计算属性? (权限变大)可以
3.只需
*/
class Man5 {
var name:String = "lnj" // 存储属性
var age: Int { // 计算属性
get{
return 30
}
set{
print("man new age \(newValue)")
}
}
func sleep(){
print("睡觉")
}
}
class SuperMan5: Man5 {
var power:Int = 100
override var name:String{
get{
return "zs"
}
set{
print("SuperMan new name \(newValue)")
}
}
override var age: Int { // 计算属性
get{
return 30
}
set{
print("superMan new age \(newValue)")
}
}
}
/*
重写属性观察器
只能给非lazy属性的变量存储属性设定属性观察器,
不能给计算属性设置属性观察器,给计算属性设置属性观察器没有意义
属性观察器限制:
1.不能在子类中重写父类只读的存储属性
2.不能给lazy的属性设置属性观察器
*/
class Man6 {
var name: String = "lnj"
var age: Int = 0 { // 存储属性
willSet{
print("super new \(newValue)")
}
didSet{
print("super new \(oldValue)")
}
}
var height:Double{
get{
print("super get")
return 10.0
}
set{
print("super set")
}
}
}
class SuperMan6: Man6 {
// 可以在子类中重写父类的存储属性为属性观察器
override var name: String {
willSet{
print("new \(newValue)")
}
didSet{
print("old \(oldValue)")
}
}
// 可以在子类中重写父类的属性观察器
override var age: Int{
willSet{
print("child new \(newValue)")
}
didSet{
print("child old \(oldValue)")
}
}
// 可以在子类重写父类的计算属性为属性观察器
override var height:Double{
willSet{
print("child height")
}
didSet{
print("child height")
}
}
}
var m6 = SuperMan6()
//m6.age = 55
//print(m.age)
m6.height = 20.0
/*
利用final关键字防止重写
final关键字既可以修饰属性, 也可以修饰方法, 并且还可以修饰类
被final关键字修饰的属性和方法不能被重写
被final关键字修饰的类不能被继承
*/
final class Man7 {
final var name: String = "lnj"
final var age: Int = 0 { // 存储属性
willSet{
print("super new \(newValue)")
}
didSet{
print("super new \(oldValue)")
}
}
final var height:Double{
get{
print("super get")
return 10.0
}
set{
print("super set")
}
}
final func eat(){
print("吃饭")
}
}
| apache-2.0 | 080d0c49b778cd081fbec7e29b8bf2d4 | 15.578275 | 52 | 0.50742 | 3.039836 | false | false | false | false |
xxxAIRINxxx/ARNSpaceStretchFlowLayout | Lib/ARNSpaceStretchFlowLayout.swift | 1 | 3600 | //
// ARNSpaceStretchFlowLayout.swift
// ARNSpaceStretchFlowLayout
//
// Created by xxxAIRINxxx on 2015/02/08.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
public class ARNSpaceStretchFlowLayout : UICollectionViewFlowLayout {
public var scrollResistanceDenominator : CGFloat = 0.0
public var overflowPadding : UIEdgeInsets {
get {
return self.contentOverflowPadding
}
set (overflowPadding) {
self.contentOverflowPadding = overflowPadding
self.bufferedContentInsets = overflowPadding
self.bufferedContentInsets.top *= -1
self.bufferedContentInsets.bottom *= -1
}
}
public override func collectionViewContentSize() -> CGSize {
var contentSize = super.collectionViewContentSize()
contentSize.height += self.contentOverflowPadding.top + self.contentOverflowPadding.bottom
return contentSize
}
private var contentOverflowPadding : UIEdgeInsets = UIEdgeInsetsZero
private var bufferedContentInsets : UIEdgeInsets = UIEdgeInsetsZero
private var transformsNeedReset : Bool = false
public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let newRect = UIEdgeInsetsInsetRect(rect, self.bufferedContentInsets)
let att = super.layoutAttributesForElementsInRect(newRect)
var attributes:[UICollectionViewLayoutAttributes] = []
att?.forEach() { attributes.append($0.copy() as! UICollectionViewLayoutAttributes) }
attributes.forEach(){ [unowned self] in
var center = $0.center
center.y += self.contentOverflowPadding.top
$0.center = center
}
let collectionViewHeight = super.collectionViewContentSize().height
let topOffset = self.contentOverflowPadding.top
let bottomOffset = collectionViewHeight - self.collectionView!.frame.size.height + self.contentOverflowPadding.top
let yPosition = self.collectionView!.contentOffset.y
if yPosition < topOffset {
let stretchDelta = topOffset - yPosition
attributes.forEach(){ [unowned self] in
let distanceFromTop = $0.center.y - self.contentOverflowPadding.top
let scrollResistance = distanceFromTop / self.scrollResistanceDenominator
$0.transform = CGAffineTransformMakeTranslation(0, -stretchDelta + (stretchDelta * scrollResistance))
}
self.transformsNeedReset = true
} else if yPosition > bottomOffset {
let stretchDelta = yPosition - bottomOffset
attributes.forEach(){ [unowned self] in
let distanceFromBottom = collectionViewHeight + self.contentOverflowPadding.top - $0.center.y
let scrollResistance = distanceFromBottom / self.scrollResistanceDenominator
$0.transform = CGAffineTransformMakeTranslation(0, stretchDelta + (-stretchDelta * scrollResistance))
}
self.transformsNeedReset = true
} else if self.transformsNeedReset == true {
self.transformsNeedReset = false
attributes.forEach(){
$0.transform = CGAffineTransformIdentity
}
}
return attributes
}
public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
} | mit | d18406a762bd304473a26938fc23283d | 39.011111 | 122 | 0.651667 | 5.872757 | false | false | false | false |
Amosel/CollectionView | CollectionView/SchematicDataController.swift | 1 | 1356 | import UIKit
class SchematicDataController : NSObject, LayoutDataControllerProtocol {
typealias SectionMap = IndexPathMap<Node>
var sectionsMap = SectionMap {
return [:]
}
var sections = [[Node]]()
var tree: Node? {
didSet {
sectionsMap = IndexPathMap {
tree?.byIndexPaths ?? [:]
}
sections = tree?.array ?? []
}
}
var maxNodesInSection = 0
func performFetch() {
tree = Node(name:"Root", type:.normal)
{[
Node(name:"Child 1", type:.normal)
{[
Node(name:"Child 1-1", type:.important),
Node(name:"Child 1-2", type:.critical)
]},
Node(name:"Child 2", type:.normal),
Node(name:"Child 3", type:.normal)
{[
Node(name:"Child 3-1", type:.normal)
{[
Node(name:"Child 3-1-1", type:.critical),
Node(name:"Child 3-1-2", type:.normal)
]},
Node(name:"Child 3-2", type:.important)
]}
]}
}
func element(at indexPath: IndexPath) -> Node? {
return self.sectionsMap.element(at: indexPath)
}
func indexPath(for element: Node) -> IndexPath? {
return self.sectionsMap.indexPath(for: element)
}
func indexPathForParent(for element:Node) -> IndexPath? {
if let parent = element.parent {
return self.indexPath(for: parent)
}
return nil
}
}
| mit | 383a04bb07d7cd28788bc46a13b84b38 | 23.214286 | 72 | 0.575959 | 3.625668 | false | false | false | false |
AcuityInfoMgt/MobileFAQ | MobileFAQ/RootViewController.swift | 1 | 5070 | //
// RootViewController.swift
// MobileFAQ
//
// Created by Kevin Ferrell on 11/28/14.
// Copyright (c) 2014 Acuity Inc. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers: NSArray = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers as [AnyObject], direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
_modelController?.rootViewController = self
}
return _modelController!
}
var _modelController: ModelController? = nil
func moveToViewControllerAtIndex(index: Int) {
let viewController = modelController.viewControllerAtIndex(index, storyboard: storyboard!)!
pageViewController?.setViewControllers([viewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
}
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
let currentViewController = self.pageViewController!.viewControllers[0] as! UIViewController
let viewControllers: [AnyObject] = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
// In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
let currentViewController = self.pageViewController!.viewControllers[0] as! DataViewController
var viewControllers: [AnyObject]
let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
return .Mid
}
}
| mit | d2cb43eec6c2e1bc9ed59ef4a9069349 | 52.93617 | 329 | 0.719132 | 6.198044 | false | false | false | false |
openHPI/xikolo-ios | Common/Data/Model/LastVisit.swift | 1 | 1420 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import CoreData
import Stockpile
public final class LastVisit: NSManagedObject {
@NSManaged public var id: String
@NSManaged public var visitDate: Date?
@NSManaged public var item: CourseItem?
@nonobjc public class func fetchRequest() -> NSFetchRequest<LastVisit> {
return NSFetchRequest<LastVisit>(entityName: "LastVisit")
}
}
extension LastVisit: JSONAPIPullable {
public static var type: String {
return "last-visits"
}
public func update(from object: ResourceData, with context: SynchronizationContext) throws {
let attributes = try object.value(for: "attributes") as JSON
guard let newVisitDate = try? attributes.value(for: "visit_date") as Date else { return }
let isNewObject = self.objectID.isTemporaryID
let isNewVisitNewer = newVisitDate > (self.visitDate ?? Date.distantPast)
guard isNewObject || isNewVisitNewer else { return }
self.visitDate = newVisitDate
if let relationships = try? object.value(for: "relationships") as JSON {
try self.updateRelationship(forKeyPath: \Self.item,
forKey: "item",
fromObject: relationships,
with: context)
}
}
}
| gpl-3.0 | b35fcab1d9038d49625a79aad8b7b701 | 29.191489 | 97 | 0.630726 | 4.777778 | false | false | false | false |
awesome-labs/LFLoginController | LFLoginControllerExample/ViewController.swift | 1 | 1719 | //
// ViewController.swift
// LFLoginController
//
// Created by Lucas Farah on 6/10/16.
// Copyright © 2016 Lucas Farah. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable trailing_whitespace
import UIKit
import LFLoginController
class ViewController: UIViewController {
let controller = LFLoginController()
override func viewDidLoad() {
super.viewDidLoad()
controller.delegate = self
// Customizations
controller.logo = UIImage(named: "AwesomeLabsLogoWhite")
controller.isSignupSupported = false
controller.backgroundColor = UIColor(red: 224 / 255, green: 68 / 255, blue: 98 / 255, alpha: 1)
controller.videoURL = Bundle.main.url(forResource: "PolarBear", withExtension: "mov")!
controller.loginButtonColor = UIColor.purple
// controller.setupOnePassword("YourAppName", appUrl: "YourAppURL")
}
@IBAction func butLoginTapped(sender: AnyObject) {
self.navigationController?.pushViewController(controller, animated: true)
}
}
extension ViewController: LFLoginControllerDelegate {
func loginDidFinish(email: String, password: String, type: LFLoginController.SendType) {
// Implement your server call here
print(email)
print(password)
print(type)
// Example
if type == .Login && password != "1234" {
controller.wrongInfoShake()
} else {
_ = navigationController?.popViewController(animated: true)
}
}
func forgotPasswordTapped(email: String) {
print("forgot password: \(email)")
}
}
| mit | aab5e393fd58d5a11b906543d10157f4 | 27.163934 | 103 | 0.633877 | 4.785515 | false | false | false | false |
taewan0530/RxBindNext | Sources/RxBindNext.swift | 1 | 2339 | // The MIT License (MIT)
//
// Copyright (c) 2017 taewan kim
//
// 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.
//http://blog.xebia.com/function-references-in-swift-and-retain-cycles/
//https://medium.com/@gnod94/improvements-of-flatmap-function-in-rxswift-5d70add0fc88#.mjmtg1sp3
import Foundation
import RxSwift
import RxCocoa
public extension ObservableType {
public func bindNext<A: AnyObject>(weak obj: A,
_ onNext: @escaping (A) -> ((Self.E) -> Swift.Void)) -> Disposable {
return self.bind(onNext: { [weak obj] (value: Self.E) in
guard let `self` = obj else { return }
onNext(self)(value)
})
}
}
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
public func drive<A: AnyObject>(weak obj: A,
_ onNext: @escaping (A) -> ((Self.E) -> Swift.Void),
onCompleted: (() -> Void)? = nil,
onDisposed: (() -> Void)? = nil) -> Disposable {
return self.drive(
onNext: { [weak obj] (value: Self.E) in
guard let `self` = obj else { return }
onNext(self)(value)
},
onCompleted: onCompleted,
onDisposed: onDisposed)
}
}
| mit | 0d54bef879343f5f8bddbcb944b944fd | 37.344262 | 96 | 0.655408 | 4.315498 | false | false | false | false |
nerdishbynature/TrashCanKit | TrashCanKitTests/TestHelper.swift | 1 | 1071 | import Foundation
class TestHelper {
static func loadJSON(_ name: String) -> [String: AnyObject] {
let bundle = Bundle(for: self)
let path = bundle.path(forResource: name, ofType: "json")
if let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let json: AnyObject? = try! JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject?
if let json = json as! [String: AnyObject]? {
return json
}
}
return Dictionary()
}
static func loadJSONString(_ name: String) -> String {
let bundle = Bundle(for: self)
let path = bundle.path(forResource: name, ofType: "json")
if let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let jsonString = String(data: data, encoding: String.Encoding.utf8)
if let json = jsonString {
return json
}
}
return ""
}
}
| mit | fb9abe9823e2684dd41e630a221df01d | 34.7 | 90 | 0.582633 | 4.596567 | false | false | false | false |
kildevaeld/location | Pod/Classes/NSPredicate.swift | 1 | 3501 | //
// NSPredicate+Location.swift
// Pods
//
// Created by Rasmus Kildevæld on 23/06/15.
//
//
import Foundation
import MapKit
enum Unit : Double {
case Kilometres = 6378.137, Miles = 3963.19
}
func deg2rad(deg: Double) -> Double{
return deg*(M_PI / 180)
}
func rad2deg(rad: Double) -> Double {
return rad*(180 / M_PI)
}
struct BoundingBox {
let latitude: (Double, Double)
let longitide: (Double, Double)
}
func locationFromDistance(latitude: Double, longitude: Double, bearing: Double, distanceInMeters: Double, unit: Unit) -> CLLocationCoordinate2D {
let radius = unit.rawValue
let distance = distanceInMeters / 1000.0;
let rLatitude = deg2rad(latitude);
let rLongitude = deg2rad(longitude);
let rBearing = deg2rad(bearing);
let rAngDist = distance / radius;
let rLatB = asin(sin(rLatitude) * cos(rAngDist) +
cos(rLatitude) * sin(rAngDist) * cos(rBearing))
let rLonB = rLongitude + atan2(sin(rBearing) * sin(rAngDist) * cos(rLatitude),
cos(rAngDist) - sin(rLatitude) * sin(rLatB))
return CLLocationCoordinate2DMake(rad2deg(rLatB), rad2deg(rLonB))
}
func _boundingBox (location: CLLocationCoordinate2D, distance: Double, unit: Unit) -> BoundingBox {
let minLat = locationFromDistance(location.latitude, longitude: location.longitude, bearing: 0, distanceInMeters: distance, unit: .Kilometres).latitude
let maxLat = locationFromDistance(location.latitude, longitude: location.longitude, bearing: 180, distanceInMeters: distance, unit: .Kilometres).latitude
let minLng = locationFromDistance(location.latitude, longitude: location.longitude, bearing: 90, distanceInMeters: distance, unit: .Kilometres).longitude
let maxLng = locationFromDistance(location.latitude, longitude: location.longitude, bearing: 270, distanceInMeters: distance, unit: .Kilometres).longitude
return BoundingBox(latitude: (minLat,maxLat), longitide: (minLng,maxLng))
}
extension NSPredicate {
static public func boundingBox(location:CLLocationCoordinate2D, distance: CLLocationDistance) -> NSPredicate {
return self.boundingBox(location, distance: distance, latitudeKeyPath: "latitude", longitudeKeyPath: "longitude")
}
static public func boundingBox(location:CLLocationCoordinate2D, distance: CLLocationDistance, latitudeKeyPath:String, longitudeKeyPath: String) -> NSPredicate {
let box = _boundingBox(location, distance: distance, unit: .Kilometres)
let (minLat, maxLat) = box.latitude
let (minLng, maxLng) = box.longitide
let latPredicate : NSPredicate
let lngPredicate : NSPredicate
let las = "\(latitudeKeyPath) <= %@ AND \(latitudeKeyPath) >= %@"
let los = "\(longitudeKeyPath) <= %@ AND \(longitudeKeyPath) >= %@"
if maxLat > minLat {
latPredicate = NSPredicate(format:las, NSNumber(double: maxLat), minLat as NSNumber)
} else {
latPredicate = NSPredicate(format:las, NSNumber(double:minLat), maxLat as NSNumber)
}
if maxLng > minLng {
lngPredicate = NSPredicate(format:los, maxLng as NSNumber, minLng as NSNumber)
} else {
lngPredicate = NSPredicate(format:los, minLng as NSNumber, maxLng as NSNumber)
}
return NSCompoundPredicate(andPredicateWithSubpredicates:[lngPredicate, latPredicate])
}
} | mit | 0bdf6397fbaac74609c2028fd11a1221 | 35.46875 | 164 | 0.678571 | 4.088785 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/ZeroMeasurementRequest.swift | 1 | 6120 | //
// ZeroMeasurementRequest.swift
// RMBTClient
//
// Created by Sergey Glushchenko on 10/4/17.
//
import ObjectMapper
class ZeroMeasurementRequest: BasicRequest {
///
var clientUuid: String?
///
var geoLocations = [GeoLocation]()
var cellLocations = [FakeCellLocation]()
///
var networkType: Int?
///
var time: Date?
#if os(iOS)
///
var signals = [Signal]()
/// Telephony Info properties
var telephonyInfo: TelephonyInfo? {
didSet {
self.telephonyDataState = telephonyInfo?.dataState
self.telephonyNetworkCountry = telephonyInfo?.networkCountry
self.telephonyNetworkIsRoaming = telephonyInfo?.networkIsRoaming
self.telephonyNetworkOperator = telephonyInfo?.networkOperator
self.telephonyNetworkOperatorName = telephonyInfo?.networkOperatorName
self.telephonyNetworkSimCountry = telephonyInfo?.networkSimCountry
self.telephonyNetworkSimOperator = telephonyInfo?.networkSimOperator
self.telephonyNetworkSimOperatorName = telephonyInfo?.networkSimOperatorName
self.telephonyPhoneType = telephonyInfo?.phoneType
}
}
var telephonyDataState: Int?
var telephonyNetworkCountry: String?
var telephonyNetworkIsRoaming: Bool?
var telephonyNetworkOperator: String?
var telephonyNetworkOperatorName: String?
var telephonyNetworkSimCountry: String?
var telephonyNetworkSimOperator: String?
var telephonyNetworkSimOperatorName: String?
var telephonyPhoneType: Int?
///WiFi Info Properties
var wifiInfo: WifiInfo? {
didSet {
self.wifiSsid = wifiInfo?.ssid
self.wifiBssid = wifiInfo?.bssid
self.wifiNetworkId = wifiInfo?.networkId
self.wifiSupplicantState = wifiInfo?.supplicantState
self.wifiSupplicantStateDetail = wifiInfo?.supplicantStateDetail
}
}
var wifiSsid: String?
var wifiBssid: String?
var wifiNetworkId: String?
var wifiSupplicantState: String?
var wifiSupplicantStateDetail: String?
#endif
init(measurement: StoredZeroMeasurement) {
super.init()
if let speedMeasurement = measurement.speedMeasurementResult() {
self.clientUuid = speedMeasurement.clientUuid
self.geoLocations = speedMeasurement.geoLocations
self.networkType = speedMeasurement.networkType
self.time = speedMeasurement.time
#if os(iOS)
self.signals = speedMeasurement.signals
for signal in self.signals {
if signal.time == nil {
signal.time = Int(Date().timeIntervalSince1970)
}
}
self.telephonyInfo = speedMeasurement.telephonyInfo
self.wifiInfo = speedMeasurement.wifiInfo
#endif
self.uuid = speedMeasurement.uuid
self.apiLevel = speedMeasurement.apiLevel
self.clientName = speedMeasurement.clientName
self.device = speedMeasurement.device
self.model = speedMeasurement.model
self.osVersion = speedMeasurement.osVersion
self.platform = speedMeasurement.platform
self.plattform = speedMeasurement.plattform
self.product = speedMeasurement.product
self.previousTestStatus = speedMeasurement.previousTestStatus
self.softwareRevision = speedMeasurement.softwareRevision
self.softwareVersion = speedMeasurement.softwareVersion
self.clientVersion = speedMeasurement.clientVersion
self.softwareVersionCode = speedMeasurement.softwareVersionCode
self.softwareVersionName = speedMeasurement.softwareVersionName
self.timezone = speedMeasurement.timezone
self.clientType = speedMeasurement.clientType
self.cellLocations = [FakeCellLocation()]
}
}
required public init?(map: Map) {
fatalError("init(map:) has not been implemented")
}
///
override func mapping(map: Map) {
super.mapping(map: map)
clientUuid <- map["client_uuid"]
geoLocations <- map["geoLocations"]
networkType <- map["network_type"]
time <- map["time"]
#if os(iOS)
signals <- map["signals"]
// telephonyInfo <- map["telephony_info"]
// wifiInfo <- map["wifi_info"]
//Telephony Info Properties
telephonyDataState <- map["telephony_data_state"]
telephonyNetworkCountry <- map["telephony_network_country"]
telephonyNetworkIsRoaming <- map["telephony_network_is_roaming"]
telephonyNetworkOperator <- map["telephony_network_operator"]
telephonyNetworkOperatorName <- map["telephony_network_operator_name"]
telephonyNetworkSimCountry <- map["telephony_network_sim_country"]
telephonyNetworkSimOperator <- map["telephony_network_sim_operator"]
telephonyNetworkSimOperatorName <- map["telephony_network_sim_operator_name"]
telephonyPhoneType <- map["telephony_phone_type"]
//WiFi Info Properties
wifiSsid <- map["wifi_ssid"]
wifiBssid <- map["wifi_bssid"]
wifiNetworkId <- map["wifi_network_id"]
wifiSupplicantState <- map["wifi_supplicant_state"]
wifiSupplicantStateDetail <- map["wifi_supplicant_state_detail"]
cellLocations <- map["cellLocations"]
#endif
}
class func submit(zeroMeasurements: [ZeroMeasurementRequest], success: @escaping (_ response: SpeedMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) {
let controlServer = ControlServer.sharedControlServer
controlServer.submitZeroMeasurementRequests(zeroMeasurements, success: success, error: failure)
}
}
| apache-2.0 | 700676ef64269418f73beacdc1133cde | 37.980892 | 178 | 0.638725 | 4.686064 | false | false | false | false |
mohamede1945/quran-ios | Quran/AsyncLabel.swift | 2 | 2485 | //
// AsyncLabel.swift
// Quran
//
// Created by Mohamed Afifi on 3/28/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
class AsyncLabel: UIView {
static var sharedRenderer: AnyCacheableService<TranslationTextLayout, UIImage> = {
let cache = Cache<TranslationTextLayout, UIImage>()
cache.countLimit = 20
let creator = AnyCreator { TextRenderPreloadingOperation(layout: $0).asPreloadingOperationRepresentable() }
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let renderer = OperationCacheableService(queue: queue, cache: cache, operationCreator: creator).asCacheableService()
return renderer
}()
var onImageChanged: ((UIImage?) -> Void)?
var textLayout: TranslationTextLayout? {
didSet {
if oldValue != textLayout {
renderTextInBackground()
}
}
}
private(set) var image: UIImage? {
set {
imageView.image = newValue
onImageChanged?(image)
}
get {
return imageView.image
}
}
let imageView: UIImageView = UIImageView()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
private func setUp() {
addAutoLayoutSubview(imageView)
pinParentHorizontal(imageView)
addParentTopConstraint(imageView)
}
private func renderTextInBackground() {
guard let textLayout = textLayout else {
return
}
let renderer = type(of: self).sharedRenderer
renderer.getOnMainThread(textLayout) { [weak self] image in
self?.image = image
}
}
override var intrinsicContentSize: CGSize {
return imageView.intrinsicContentSize
}
}
| gpl-3.0 | 35280668890d1f3e4881d0099139688b | 27.238636 | 124 | 0.643058 | 4.71537 | false | false | false | false |
djflsdl08/BasicIOS | LoginSystem/LoginSystem/SignUpViewController.swift | 1 | 4572 | //
// SignUpViewController.swift
// LoginSystem
//
// Created by 김예진 on 2017. 10. 21..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var Id: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var checkPassword: UITextField!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
Id.delegate = self
password.delegate = self
checkPassword.delegate = self
textView.delegate = self
}
// MARK: - Navigation
@IBAction func cancel(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
@IBAction func signUp(_ sender: UIButton) {
if let id = Id.text, let password = password.text,
let checkPassword = checkPassword.text {
if(id.isEmpty || password.isEmpty || checkPassword.isEmpty) {
var artMsg = "Input the "
if(id.isEmpty) {
artMsg += "ID"
} else if(password.isEmpty) {
artMsg += "Password"
} else if(checkPassword.isEmpty) {
artMsg += "check Password"
}
let alert = UIAlertController(title: "Fail to signup", message: artMsg, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
if password == checkPassword {
dismiss(animated: true, completion: nil)
} else {
let checkPasswordAlert = UIAlertController(title: "Password do not match", message : "Check your password", preferredStyle : UIAlertControllerStyle.alert)
checkPasswordAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(checkPasswordAlert, animated: true, completion : nil)
return
}
}
}
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
//MARK: UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return true
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//MARK : Actions
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
hideTheKeyboard()
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.allowsEditing = true
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
//MARK : UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker : UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.view.endEditing(true)
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
imageView.image = selectedImage
dismiss(animated: true, completion: nil)
}
//MARK: When user clicks the background, keyboard will be disappear.
@IBAction func background(_ sender: UITapGestureRecognizer) {
hideTheKeyboard()
}
func hideTheKeyboard() {
Id.resignFirstResponder()
password.resignFirstResponder()
checkPassword.resignFirstResponder()
textView.resignFirstResponder()
}
}
| mit | e00df1a89e5f9988be2c5ea59252f1a0 | 36.710744 | 170 | 0.636862 | 5.633333 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Browser/Tab.swift | 1 | 25829 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Storage
import Shared
import SwiftyJSON
import XCGLogger
fileprivate var debugTabCount = 0
func mostRecentTab(inTabs tabs: [Tab]) -> Tab? {
var recent = tabs.first
tabs.forEach { tab in
if let time = tab.lastExecutedTime, time > (recent?.lastExecutedTime ?? 0) {
recent = tab
}
}
return recent
}
protocol TabContentScript {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol TabDelegate {
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar)
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar)
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String)
func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String)
@objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView)
@objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView)
}
@objc
protocol URLChangeDelegate {
func tab(_ tab: Tab, urlDidChangeTo url: URL)
}
struct TabState {
var isPrivate: Bool = false
var url: URL?
var title: String?
var favicon: Favicon?
}
class Tab: NSObject {
fileprivate var _isPrivate: Bool = false
internal fileprivate(set) var isPrivate: Bool {
get {
return _isPrivate
}
set {
if _isPrivate != newValue {
_isPrivate = newValue
}
}
}
var tabState: TabState {
return TabState(isPrivate: _isPrivate, url: url, title: displayTitle, favicon: displayFavicon)
}
// PageMetadata is derived from the page content itself, and as such lags behind the
// rest of the tab.
var pageMetadata: PageMetadata?
var consecutiveCrashes: UInt = 0
var canonicalURL: URL? {
if let string = pageMetadata?.siteURL,
let siteURL = URL(string: string) {
// If the canonical URL from the page metadata doesn't contain the
// "#" fragment, check if the tab's URL has a fragment and if so,
// append it to the canonical URL.
if siteURL.fragment == nil,
let fragment = self.url?.fragment,
let siteURLWithFragment = URL(string: "\(string)#\(fragment)") {
return siteURLWithFragment
}
return siteURL
}
return self.url
}
var userActivity: NSUserActivity?
var webView: WKWebView?
var tabDelegate: TabDelegate?
weak var urlDidChangeDelegate: URLChangeDelegate? // TODO: generalize this.
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
fileprivate var lastRequest: URLRequest?
var restoring: Bool = false
var pendingScreenshot = false
var url: URL? {
didSet {
if let _url = url, let internalUrl = InternalURL(_url), internalUrl.isAuthorized {
url = URL(string: internalUrl.stripAuthorization)
}
}
}
var mimeType: String?
var isEditing: Bool = false
// When viewing a non-HTML content type in the webview (like a PDF document), this URL will
// point to a tempfile containing the content so it can be shared to external applications.
var temporaryDocument: TemporaryDocument?
/// Returns true if this tab's URL is known, and it's longer than we want to store.
var urlIsTooLong: Bool {
guard let url = self.url else {
return false
}
return url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX
}
// Use computed property so @available can be used to guard `noImageMode`.
var noImageMode: Bool {
didSet {
guard noImageMode != oldValue else {
return
}
contentBlocker?.noImageMode(enabled: noImageMode)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var nightMode: Bool {
didSet {
guard nightMode != oldValue else {
return
}
webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(nightMode))")
// For WKWebView background color to take effect, isOpaque must be false,
// which is counter-intuitive. Default is true. The color is previously
// set to black in the WKWebView init.
webView?.isOpaque = !nightMode
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var contentBlocker: FirefoxTabContentBlocker?
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation.
var changedUserAgent: Bool = false {
didSet {
webView?.customUserAgent = changedUserAgent ? UserAgent.oppositeUserAgent() : nil
if changedUserAgent != oldValue {
TabEvent.post(.didToggleDesktopMode, for: self)
}
}
}
var readerModeAvailableOrActive: Bool {
if let readerMode = self.getContentScript(name: "ReaderMode") as? ReaderMode {
return readerMode.state != .unavailable
}
return false
}
fileprivate(set) var screenshot: UIImage?
var screenshotUUID: UUID?
// If this tab has been opened from another, its parent will point to the tab from which it was opened
weak var parent: Tab?
fileprivate var contentScriptManager = TabContentScriptManager()
fileprivate let configuration: WKWebViewConfiguration
/// Any time a tab tries to make requests to display a Javascript Alert and we are not the active
/// tab instance, queue it for later until we become foregrounded.
fileprivate var alertQueue = [JSAlertInfo]()
weak var browserViewController:BrowserViewController?
init(bvc: BrowserViewController, configuration: WKWebViewConfiguration, isPrivate: Bool = false) {
self.configuration = configuration
self.nightMode = false
self.noImageMode = false
self.browserViewController = bvc
super.init()
self.isPrivate = isPrivate
debugTabCount += 1
}
class func toRemoteTab(_ tab: Tab) -> RemoteTab? {
if tab.isPrivate {
return nil
}
if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) {
let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: Date.now(),
icon: nil)
} else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed())
if let displayURL = history.first {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
configuration.userContentController = WKUserContentController()
configuration.allowsInlineMediaPlayback = true
let webView = TabWebView(frame: .zero, configuration: configuration)
webView.delegate = self
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
if #available(iOS 13, *) {
webView.allowsLinkPreview = true
} else {
webView.allowsLinkPreview = false
}
// Night mode enables this by toggling WKWebView.isOpaque, otherwise this has no effect.
webView.backgroundColor = .black
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
restore(webView)
self.webView = webView
self.webView?.addObserver(self, forKeyPath: KVOConstants.URL.rawValue, options: .new, context: nil)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
tabDelegate?.tab?(self, didCreateWebView: webView)
}
}
func restore(_ webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var urls = [String]()
for url in sessionData.urls {
urls.append(url.absoluteString)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = urls as AnyObject?
jsonDict["currentPage"] = currentPage as AnyObject?
guard let json = JSON(jsonDict).stringify()?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return
}
if let restoreURL = URL(string: "\(InternalURL.baseUrl)/\(SessionRestoreHandler.path)?history=\(json)") {
let request = PrivilegedRequest(url: restoreURL) as URLRequest
webView.load(request)
lastRequest = request
}
} else if let request = lastRequest {
webView.load(request)
} else {
print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")")
}
}
deinit {
debugTabCount -= 1
#if DEBUG
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
func checkTabCount(failures: Int) {
// Need delay for pool to drain.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if appDelegate.tabManager.tabs.count == debugTabCount {
return
}
// If this assert has false positives, remove it and just log an error.
assert(failures < 3, "Tab init/deinit imbalance, possible memory leak.")
checkTabCount(failures: failures + 1)
}
}
checkTabCount(failures: 0)
#endif
}
func closeAndRemovePrivateBrowsingData() {
contentScriptManager.uninstall(tab: self)
webView?.removeObserver(self, forKeyPath: KVOConstants.URL.rawValue)
if let webView = webView {
tabDelegate?.tab?(self, willDeleteWebView: webView)
}
if isPrivate {
removeAllBrowsingData()
}
webView?.navigationDelegate = nil
webView?.removeFromSuperview()
webView = nil
}
func removeAllBrowsingData(completionHandler: @escaping () -> Void = {}) {
let dataTypes = Set([WKWebsiteDataTypeCookies,
WKWebsiteDataTypeLocalStorage,
WKWebsiteDataTypeSessionStorage,
WKWebsiteDataTypeWebSQLDatabases,
WKWebsiteDataTypeIndexedDBDatabases])
webView?.configuration.websiteDataStore.removeData(ofTypes: dataTypes,
modifiedSince: Date.distantPast,
completionHandler: completionHandler)
}
var loading: Bool {
return webView?.isLoading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [URL] {
func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url }
var tabs = self.backList?.map(listToUrl) ?? [URL]()
if let url = url {
tabs.append(url)
}
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title, !title.isEmpty {
return title
}
// When picking a display title. Tabs with sessionData are pending a restore so show their old title.
// To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle.
if let url = self.url, InternalURL(url)?.isAboutHomeURL ?? false, sessionData == nil, !restoring {
return Strings.AppMenuOpenHomePageTitleString
}
//lets double check the sessionData in case this is a non-restored new tab
if let firstURL = sessionData?.urls.first, sessionData?.urls.count == 1, InternalURL(firstURL)?.isAboutHomeURL ?? false {
return Strings.AppMenuOpenHomePageTitleString
}
if let url = self.url, !InternalURL.isValid(url: url), let shownUrl = url.displayURL?.absoluteString {
return shownUrl
}
guard let lastTitle = lastTitle, !lastTitle.isEmpty else {
return self.url?.displayURL?.absoluteString ?? ""
}
return lastTitle
}
var displayFavicon: Favicon? {
return favicons.max { $0.width! < $1.width! }
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
_ = webView?.goBack()
}
func goForward() {
_ = webView?.goForward()
}
func goToBackForwardListItem(_ item: WKBackForwardListItem) {
_ = webView?.go(to: item)
}
@discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? {
if let webView = webView {
// Convert about:reader?url=http://example.com URLs to local ReaderMode URLs
if let url = request.url, let syncedReaderModeURL = url.decodeReaderModeURL, let localReaderModeURL = syncedReaderModeURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) {
let readerModeRequest = PrivilegedRequest(url: localReaderModeURL) as URLRequest
lastRequest = readerModeRequest
return webView.load(readerModeRequest)
}
lastRequest = request
if let url = request.url, url.isFileURL, request.isPrivileged {
return webView.loadFileURL(url, allowingReadAccessTo: url)
}
return webView.load(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
if let _ = webView?.reloadFromOrigin() {
print("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
print("restoring webView from scratch")
restore(webView)
}
}
func addContentScript(_ helper: TabContentScript, name: String) {
contentScriptManager.addContentScript(helper, name: name, forTab: self)
}
func getContentScript(name: String) -> TabContentScript? {
return contentScriptManager.getContentScript(name)
}
func hideContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(_ bar: SnackBar) {
bars.append(bar)
tabDelegate?.tab(self, didAddSnackbar: bar)
}
func removeSnackbar(_ bar: SnackBar) {
if let index = bars.firstIndex(of: bar) {
bars.remove(at: index)
tabDelegate?.tab(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
bars.reversed().forEach { removeSnackbar($0) }
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
bars.reversed().filter({ !$0.shouldPersist(self) }).forEach({ removeSnackbar($0) })
}
func expireSnackbars(withClass snackbarClass: String) {
bars.reversed().filter({ $0.snackbarClassIdentifier == snackbarClass }).forEach({ removeSnackbar($0) })
}
func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = UUID()
}
}
func toggleChangeUserAgent() {
changedUserAgent = !changedUserAgent
reload()
TabEvent.post(.didToggleDesktopMode, for: self)
}
func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView, webView == self.webView,
let path = keyPath, path == KVOConstants.URL.rawValue else {
return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
guard let url = self.webView?.url else {
return
}
self.urlDidChangeDelegate?.tab(self, urlDidChangeTo: url)
}
func isDescendentOf(_ ancestor: Tab) -> Bool {
return sequence(first: parent) { $0?.parent }.contains { $0 == ancestor }
}
func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) {
guard let webView = self.webView else {
return
}
if let path = Bundle.main.path(forResource: fileName, ofType: type),
let source = try? String(contentsOfFile: path) {
let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly)
webView.configuration.userContentController.addUserScript(userScript)
}
}
func observeURLChanges(delegate: URLChangeDelegate) {
self.urlDidChangeDelegate = delegate
}
func removeURLChangeObserver(delegate: URLChangeDelegate) {
if let existing = self.urlDidChangeDelegate, existing === delegate {
self.urlDidChangeDelegate = nil
}
}
}
extension Tab: TabWebViewDelegate {
fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) {
tabDelegate?.tab(self, didSelectFindInPageForSelection: selection)
}
fileprivate func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String) {
tabDelegate?.tab(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
extension Tab: ContentBlockerTab {
func currentURL() -> URL? {
return url
}
func currentWebView() -> WKWebView? {
return webView
}
func imageContentBlockingEnabled() -> Bool {
return noImageMode
}
}
private class TabContentScriptManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: TabContentScript]()
// Without calling this, the TabContentScriptManager will leak.
func uninstall(tab: Tab) {
helpers.forEach { helper in
if let name = helper.value.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.removeScriptMessageHandler(forName: name)
}
}
}
@objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName(), scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
func addContentScript(_ helper: TabContentScript, name: String, forTab tab: Tab) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right TabHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName)
}
}
func getContentScript(_ name: String) -> TabContentScript? {
return helpers[name]
}
}
private protocol TabWebViewDelegate: AnyObject {
func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String)
func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String)
}
class TabWebView: WKWebView, MenuHelperInterface {
fileprivate weak var delegate: TabWebViewDelegate?
// Updates the `background-color` of the webview to match
// the theme if the webview is showing "about:blank" (nil).
func applyTheme() {
if url == nil {
let backgroundColor = ThemeManager.instance.current.browser.background.hexString
evaluateJavaScript("document.documentElement.style.backgroundColor = '\(backgroundColor)';")
}
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection)
}
}
@objc func menuHelperSearchWithFirefox() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebViewSearchWithFirefox(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
internal override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, with: event)
}
}
///
// Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector
//
// This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never
// instantiated. It only serves as a placeholder for the method. When the method is called, self is
// actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know
// that it is a UIView subclass to access its superview.
//
class TabWebViewMenuHelper: UIView {
@objc func swizzledMenuHelperFindInPage() {
if let tabWebView = superview?.superview as? TabWebView {
tabWebView.evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection)
}
}
}
}
| mpl-2.0 | ea0c3180115843cae52009bdc4108ede | 34.774238 | 201 | 0.63359 | 5.337673 | false | false | false | false |
SwiftGen/SwiftGen | SwiftGen.playground/Pages/Plist-Demo.xcplaygroundpage/Sources/Implementation Details.swift | 2 | 867 | import Foundation
// Extra for playgrounds
public var bundle: Bundle!
// MARK: - Implementation Details
public func arrayFromPlist<T>(at path: String) -> [T] {
guard let url = bundle.url(forResource: path, withExtension: nil),
let data = NSArray(contentsOf: url) as? [T] else {
fatalError("Unable to load PLIST at path: \(path)")
}
return data
}
public struct PlistDocument {
let data: [String: Any]
public init(path: String) {
guard let url = bundle.url(forResource: path, withExtension: nil),
let data = NSDictionary(contentsOf: url) as? [String: Any] else {
fatalError("Unable to load PLIST at path: \(path)")
}
self.data = data
}
public subscript<T>(key: String) -> T {
guard let result = data[key] as? T else {
fatalError("Property '\(key)' is not of type \(T.self)")
}
return result
}
}
| mit | f881c1f458c30b3c67af0e902aca8d0f | 25.272727 | 71 | 0.648212 | 3.72103 | false | false | false | false |
carolight/sample-code | swift/04-DrawingIn3D/DrawingIn3D/MBERenderer.swift | 1 | 5768 | //
// MBERenderer.swift
// DrawingIn3D
//
// Created by Caroline Begbie on 3/11/2015.
// Copyright © 2015 Caroline Begbie. All rights reserved.
//
import Foundation
import MetalKit
import simd
class MBERenderer {
var device: MTLDevice?
var vertexBuffer: MTLBuffer?
var indexBuffer: MTLBuffer?
var uniformBuffer: MTLBuffer?
var pipeline: MTLRenderPipelineState?
var depthStencilState: MTLDepthStencilState?
var bufferIndex:Int = 0
var commandQueue: MTLCommandQueue?
var time: TimeInterval = 0
var rotationX: Float = 0
var rotationY: Float = 0
init() {
makeDevice()
makeBuffers()
makePipeline()
}
private func makeDevice() {
device = MTLCreateSystemDefaultDevice()
}
private func makeBuffers() {
vertexBuffer = device?.newBuffer(withBytes: vertices, length: sizeof(MBEVertex.self) * vertices.count, options: [])
vertexBuffer?.label = "Vertices"
indexBuffer = device?.newBuffer(withBytes: indices, length: sizeof(MBEIndex.self) * indices.count, options: [])
indexBuffer?.label = "Indices"
uniformBuffer = device?.newBuffer(withLength: sizeof(MBEUniforms.self), options: [])
uniformBuffer?.label = "Uniforms"
}
private func makePipeline() {
let library = device?.newDefaultLibrary()
let vertexFunc = library?.newFunction(withName: "vertex_project")
let fragmentFunc = library?.newFunction(withName: "fragment_flatColor")
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunc
pipelineDescriptor.fragmentFunction = fragmentFunc
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.depthAttachmentPixelFormat = .depth32Float
let depthStencilDescriptor = MTLDepthStencilDescriptor()
depthStencilDescriptor.depthCompareFunction = .less
depthStencilDescriptor.isDepthWriteEnabled = true
depthStencilState = device?.newDepthStencilState(with: depthStencilDescriptor)
do {
pipeline = try device?.newRenderPipelineState(with: pipelineDescriptor)
} catch let error as NSError {
print("Error occurred when creating render pipeline state: \(error)")
}
commandQueue = device?.newCommandQueue()
}
private func updateUniformsForView(view: MBEMetalView, duration: TimeInterval) {
time += duration
rotationX += Float(duration) * (π / 2)
rotationY += Float(duration) * (π / 3)
let scaleFactor = sinf(5.0 * Float(time)) * 0.25 + 1
let xAxis = float3(1, 0, 0)
let yAxis = float3(0, 1, 0)
let xRotation = matrix_float4x4_rotation(axis: xAxis, angle: rotationX)
let yRotation = matrix_float4x4_rotation(axis: yAxis, angle: rotationY)
let scale = matrix_float4x4_uniform_scale(scale: scaleFactor)
let modelMatrix = matrix_multiply(matrix_multiply(xRotation, yRotation), scale)
let cameraTranslation = vector_float3(0, 0, -5)
let viewMatrix = matrix_float4x4_translation(t: cameraTranslation)
let drawableSize = view.metalLayer.drawableSize
let aspect: Float = Float(drawableSize.width / drawableSize.height)
let fov: Float = Float((2 * π) / 5)
let near: Float = 1
let far: Float = 100
let projectionMatrix = matrix_float4x4_perspective(aspect: aspect, fovy: fov, near: near, far: far)
let modelViewProjectionMatrix = matrix_multiply(projectionMatrix, matrix_multiply(viewMatrix, modelMatrix))
var uniforms: MBEUniforms = MBEUniforms(modelViewProjectionMatrix: modelViewProjectionMatrix)
let uniformBufferOffset = sizeof(MBEUniforms.self) * bufferIndex
memcpy(uniformBuffer!.contents() + uniformBufferOffset, &uniforms, sizeof(MBEUniforms.self))
}
}
extension MBERenderer: MBEMetalViewDelegate {
func drawInView(view: MBEMetalView) {
// Setup drawable
guard let drawable = view.currentDrawable else {
print("drawable not set")
return
}
guard let frameDuration = view.frameDuration else {
print("frameDuration not set")
return
}
guard let pipeline = pipeline else {
print("pipeline not set")
return
}
// Setup command buffer
guard let commandBuffer = commandQueue?.commandBuffer() else {
print("command buffer not set")
return
}
view.clearColor = MTLClearColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
updateUniformsForView(view: view, duration: frameDuration)
// Setup texture
let framebufferTexture = drawable.texture
// Setup render passes
let passDescriptor = view.currentRenderPassDescriptor
let colorAttachment = passDescriptor.colorAttachments[0]
colorAttachment?.texture = framebufferTexture
colorAttachment?.loadAction = .clear
colorAttachment?.storeAction = .store
colorAttachment?.clearColor = MTLClearColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
// Start render pass
let commandEncoder = commandBuffer.renderCommandEncoder(with: passDescriptor)
commandEncoder.setRenderPipelineState(pipeline)
commandEncoder.setDepthStencilState(depthStencilState)
commandEncoder.setFrontFacing(.counterClockwise)
commandEncoder.setCullMode(.back)
// Set up buffers
let uniformBufferOffset = sizeof(MBEUniforms.self) * bufferIndex
commandEncoder.setVertexBuffer(vertexBuffer, offset: 0, at: 0)
commandEncoder.setVertexBuffer(uniformBuffer, offset: uniformBufferOffset, at: 1)
commandEncoder.drawIndexedPrimitives(.triangle, indexCount: indexBuffer!.length / sizeof(MBEIndex.self), indexType: MBEIndexType, indexBuffer: indexBuffer!, indexBufferOffset: 0)
commandEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
| mit | 78de0dbee125f32ea32ccf83bcf02959 | 32.707602 | 182 | 0.719813 | 4.648387 | false | false | false | false |
MiMo42/XLForm | Examples/Swift/SwiftExample/PredicateExamples/BlogExampleViewController.swift | 4 | 3673 | //
// BlogExampleViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.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.
class BlogExampleViewController : XLFormViewController {
fileprivate struct Tags {
static let Hobbies = "hobbies"
static let Sport = "sport"
static let Film = "films1"
static let Film2 = "films2"
static let Music = "music"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Blog Example: Hobbies")
section = XLFormSectionDescriptor()
section.title = "Hobbies"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Hobbies, rowType: XLFormRowDescriptorTypeMultipleSelector, title:"Select Hobbies")
row.selectorOptions = ["Sport", "Music", "Films"]
row.value = []
section.addFormRow(row)
section = XLFormSectionDescriptor()
section.title = "Some more questions"
section.hidden = NSPredicate(format: "$\(row.description).value.@count == 0")
section.footerTitle = "BlogExampleViewController.swift"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Sport, rowType: XLFormRowDescriptorTypeTextView, title:"Your favourite sportsman?")
row.hidden = "NOT $\(Tags.Hobbies).value contains 'Sport'"
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Film, rowType:XLFormRowDescriptorTypeTextView, title: "Your favourite film?")
row.hidden = "NOT $\(Tags.Hobbies) contains 'Films'"
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Film2, rowType:XLFormRowDescriptorTypeTextView, title:"Your favourite actor?")
row.hidden = "NOT $\(Tags.Hobbies) contains 'Films'"
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Music, rowType:XLFormRowDescriptorTypeTextView, title:"Your favourite singer?")
row.hidden = "NOT $\(Tags.Hobbies) contains 'Music'"
section.addFormRow(row)
self.form = form
}
}
| mit | e4d89dcce349fe5dc5cfee20dece1318 | 40.269663 | 127 | 0.676831 | 4.776333 | false | false | false | false |
synchromation/Buildasaur | Buildasaur/ManualBotManagementViewController.swift | 2 | 4780 | //
// ManualBotManagementViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 15/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaGitServer
import BuildaUtils
import XcodeServerSDK
import BuildaKit
class ManualBotManagementViewController: NSViewController {
var syncer: HDGitHubXCBotSyncer!
var storageManager: StorageManager!
@IBOutlet weak var nameTextField: NSTextField!
@IBOutlet weak var branchComboBox: NSComboBox!
@IBOutlet weak var branchActivityIndicator: NSProgressIndicator!
@IBOutlet weak var templateComboBox: NSComboBox!
@IBOutlet weak var creatingActivityIndicator: NSProgressIndicator!
private var buildTemplates: [BuildTemplate] {
return Array(self.storageManager.buildTemplates.value.values)
.sort {$0.id < $1.id }
}
override func viewDidLoad() {
super.viewDidLoad()
assert(self.syncer != nil, "We need a syncer here")
let names = self.buildTemplates.map({ $0.name })
self.templateComboBox.addItemsWithObjectValues(names)
}
override func viewWillAppear() {
super.viewWillAppear()
self.fetchBranches { (branches, error) -> () in
if let error = error {
UIUtils.showAlertWithError(error)
}
}
}
func fetchBranches(completion: ([Branch]?, NSError?) -> ()) {
self.branchActivityIndicator.startAnimation(nil)
let repoName = self.syncer.project.githubRepoName()!
self.syncer.github.getBranchesOfRepo(repoName, completion: { (branches, error) -> () in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.branchComboBox.removeAllItems()
if let branches = branches {
let names = branches.map { $0.name }
self.branchComboBox.addItemsWithObjectValues(names)
}
completion(branches, error)
self.branchActivityIndicator.stopAnimation(nil)
})
})
}
func pullBotName() -> String? {
let name = self.nameTextField.stringValue
if name.isEmpty {
UIUtils.showAlertWithText("Please specify the bot's name")
return nil
}
return name
}
func pullBranchName() -> String? {
if let branch = self.branchComboBox.objectValueOfSelectedItem as? String where !branch.isEmpty {
return branch
}
UIUtils.showAlertWithText("Please specify a valid branch")
return nil
}
func pullTemplate() -> BuildTemplate? {
let index = self.templateComboBox.indexOfSelectedItem
if index > -1 {
let template = self.buildTemplates[index]
return template
}
UIUtils.showAlertWithText("Please specify a valid build template")
return nil
}
func createBot() {
if
let name = self.pullBotName(),
let branch = self.pullBranchName(),
let template = self.pullTemplate()
{
let project = self.syncer.project
let xcodeServer = self.syncer.xcodeServer
self.creatingActivityIndicator.startAnimation(nil)
XcodeServerSyncerUtils.createBotFromBuildTemplate(name, syncer: syncer,template: template, project: project, branch: branch, scheduleOverride: nil, xcodeServer: xcodeServer, completion: { (bot, error) -> () in
self.creatingActivityIndicator.stopAnimation(nil)
if let error = error {
UIUtils.showAlertWithError(error)
} else if let bot = bot {
let text = "Successfully created bot \(bot.name) for branch \(bot.configuration.sourceControlBlueprint.branch)"
UIUtils.showAlertWithText(text, style: nil, completion: { (resp) -> () in
self.dismissController(nil)
})
} else {
//should never get here
UIUtils.showAlertWithText("Unexpected error, please report this!")
}
})
} else {
Log.error("Failed to satisfy some bot dependencies, ignoring...")
}
}
@IBAction func cancelTapped(sender: AnyObject) {
self.dismissController(nil)
}
@IBAction func createTapped(sender: AnyObject) {
self.createBot()
}
}
| mit | 8af6345da09941de94217e5864ed062b | 31.517007 | 221 | 0.580544 | 5.51963 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/SwiftyVK/Source/API/Video.swift | 2 | 8263 | extension _VKAPI {
///Methods for working with video. More - https://vk.com/dev/video
public struct Video {
///Returns detailed information about videos. More - https://vk.com/dev/video.get
public static func get(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.get", parameters: parameters)
}
///Edits information about a video on a user or community page. More - https://vk.com/dev/video.edit
public static func edit(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.edit", parameters: parameters)
}
///Adds a video to a user or community page. More - https://vk.com/dev/video.add
public static func add(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.add", parameters: parameters)
}
///Returns a server address (required for upload) and video data. More - https://vk.com/dev/video.save
public static func save(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.save", parameters: parameters)
}
///Deletes a video from a user or community page. More - https://vk.com/dev/video.delete
public static func delete(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.delete", parameters: parameters)
}
///Restores a previously deleted video. More - https://vk.com/dev/video.restore
public static func restore(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.restore", parameters: parameters)
}
///Returns a list of videos under the set search criterion. More - https://vk.com/dev/video.search
public static func search(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.search", parameters: parameters)
}
///Returns list of videos in which the user is tagged. More - https://vk.com/dev/video.getUserVideos
public static func getUserVideos(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getUserVideos", parameters: parameters)
}
///Returns a list of video albums owned by a user or community. More - https://vk.com/dev/video.getAlbums
public static func getAlbums(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getAlbums", parameters: parameters)
}
///Returns a video album by ID. More - https://vk.com/dev/video.getAlbumById
public static func getAlbumById(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getAlbumById", parameters: parameters)
}
///Creates an empty album for videos. More - https://vk.com/dev/video.addAlbum
public static func addAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.addAlbum", parameters: parameters)
}
///Edits the title of a video album. More - https://vk.com/dev/video.editAlbum
public static func editAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.editAlbum", parameters: parameters)
}
///Deletes a video album. More - https://vk.com/dev/video.deleteAlbum
public static func deleteAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.deleteAlbum", parameters: parameters)
}
///Reorders the album in the list of user video albums. More - https://vk.com/dev/video.moveToAlbum
public static func moveToAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.moveToAlbum", parameters: parameters)
}
///Add video to album. More - https://vk.com/dev/video.addToAlbum
public static func addToAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.addToAlbum", parameters: parameters)
}
///Remove video from album. More - https://vk.com/dev/video.removeFromAlbum
public static func removeFromAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.removeFromAlbum", parameters: parameters)
}
///Get list of video albums by video. More - https://vk.com/dev/video.getAlbumsByVideo
public static func getAlbumsByVideo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getAlbumsByVideo", parameters: parameters)
}
///Returns a list of comments on a video. More - https://vk.com/dev/video.getComments
public static func getComments(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getComments", parameters: parameters)
}
///Adds a new comment on a video. More - https://vk.com/dev/video.createComment
public static func createComment(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.createComment", parameters: parameters)
}
///Deletes a comment on a video. More - https://vk.com/dev/video.deleteComment
public static func deleteComment(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.deleteComment", parameters: parameters)
}
///Restores a previously deleted comment on a video. More - https://vk.com/dev/video.restoreComment
public static func restoreComment(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.restoreComment", parameters: parameters)
}
///Edits the text of a comment on a video. More - https://vk.com/dev/video.editComment
public static func editComment(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.editComment", parameters: parameters)
}
///Returns a list of tags on a video. More - https://vk.com/dev/video.getTags
public static func getTags(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getTags", parameters: parameters)
}
///Adds a tag on a video. More - https://vk.com/dev/video.putTag
public static func putTag(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.putTag", parameters: parameters)
}
///Removes a tag from a video. More - https://vk.com/dev/video.removeTag
public static func removeTag(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.removeTag", parameters: parameters)
}
///Returns a list of videos with tags that have not been viewed. More - https://vk.com/dev/video.getNewTags
public static func getNewTags(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getNewTags", parameters: parameters)
}
///Reports (submits a complaint about) a video. More - https://vk.com/dev/video.report
public static func report(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.report", parameters: parameters)
}
///Reports (submits a complaint about) a comment on a video. More - https://vk.com/dev/video.reportComment
public static func reportComment(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.reportComment", parameters: parameters)
}
///Returns video catalog
public static func getCatalog(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getCatalog", parameters: parameters)
}
///Returns video catalog block
public static func getCatalogSection(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.getCatalogSection", parameters: parameters)
}
///Hide video catalog section
public static func hideCatalogSection(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "video.hideCatalogSection", parameters: parameters)
}
}
}
| apache-2.0 | 58e8a903c20015f9d9beb0d13478af9c | 36.053812 | 111 | 0.63742 | 4.250514 | false | false | false | false |
Jnosh/swift | test/Constraints/overload.swift | 2 | 5832 | // RUN: %target-typecheck-verify-swift
func markUsed<T>(_ t: T) {}
func f0(_: Float) -> Float {}
func f0(_: Int) -> Int {}
func f1(_: Int) {}
func identity<T>(_: T) -> T {}
func f2<T>(_: T) -> T {}
// FIXME: Fun things happen when we make this T, U!
func f2<T>(_: T, _: T) -> (T, T) { }
struct X {}
var x : X
var i : Int
var f : Float
_ = f0(i)
_ = f0(1.0)
_ = f0(1)
f1(f0(1))
f1(identity(1))
f0(x) // expected-error{{cannot invoke 'f0' with an argument list of type '(X)'}}
// expected-note @-1 {{overloads for 'f0' exist with these partially matching parameter lists: (Float), (Int)}}
_ = f + 1
_ = f2(i)
_ = f2((i, f))
class A {
init() {}
}
class B : A {
override init() { super.init() }
}
class C : B {
override init() { super.init() }
}
func bar(_ b: B) -> Int {} // #1
func bar(_ a: A) -> Float {} // #2
var barResult = bar(C()) // selects #1, which is more specialized
i = barResult // make sure we got #1
f = bar(C()) // selects #2 because of context
// Overload resolution for constructors
protocol P1 { }
struct X1a : P1 { }
struct X1b {
init(x : X1a) { }
init<T : P1>(x : T) { }
}
X1b(x: X1a()) // expected-warning{{unused}}
// Overload resolution for subscript operators.
class X2a { }
class X2b : X2a { }
class X2c : X2b { }
struct X2d {
subscript (index : X2a) -> Int {
return 5
}
subscript (index : X2b) -> Int {
return 7
}
func foo(_ x : X2c) -> Int {
return self[x]
}
}
// Invalid declarations
// FIXME: Suppress the diagnostic for the call below, because the invalid
// declaration would have matched.
func f3(_ x: Intthingy) -> Int { } // expected-error{{use of undeclared type 'Intthingy'}}
func f3(_ x: Float) -> Float { }
f3(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
func f4(_ i: Wonka) { } // expected-error{{use of undeclared type 'Wonka'}}
func f4(_ j: Wibble) { } // expected-error{{use of undeclared type 'Wibble'}}
f4(5)
func f1() {
var c : Class // expected-error{{use of undeclared type 'Class'}}
markUsed(c.x) // make sure error does not cascade here
}
// We don't provide return-type sensitivity unless there is context.
func f5(_ i: Int) -> A { return A() } // expected-note{{candidate}}
func f5(_ i: Int) -> B { return B() } // expected-note{{candidate}}
f5(5) // expected-error{{ambiguous use of 'f5'}}
struct HasX1aProperty {
func write(_: X1a) {}
func write(_: P1) {}
var prop = X1a()
func test() {
write(prop) // no error, not ambiguous
}
}
// rdar://problem/16554496
@available(*, unavailable)
func availTest(_ x: Int) {}
func availTest(_ x: Any) { markUsed("this one") }
func doAvailTest(_ x: Int) {
availTest(x)
}
// rdar://problem/20886179
func test20886179(_ handlers: [(Int) -> Void], buttonIndex: Int) {
handlers[buttonIndex](buttonIndex)
}
// The problem here is that the call has a contextual result type incompatible
// with *all* overload set candidates. This is not an ambiguity.
func overloaded_identity(_ a : Int) -> Int {}
func overloaded_identity(_ b : Float) -> Float {}
func test_contextual_result_1() {
return overloaded_identity() // expected-error {{cannot invoke 'overloaded_identity' with no arguments}}
// expected-note @-1 {{overloads for 'overloaded_identity' exist with these partially matching parameter lists: (Int), (Float)}}
}
func test_contextual_result_2() {
return overloaded_identity(1) // expected-error {{unexpected non-void return value in void function}}
}
// rdar://problem/24128153
struct X0 {
init(_ i: Any.Type) { }
init?(_ i: Any.Type, _ names: String...) { }
}
let x0 = X0(Int.self)
let x0check: X0 = x0 // okay: chooses first initializer
struct X1 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, _ names: String...) { }
}
let x1 = X1(Int.self)
let x1check: X1 = x1 // expected-error{{value of optional type 'X1?' not unwrapped; did you mean to use '!' or '?'?}}
struct X2 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, a: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, b: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, c: Int = 0) { }
}
let x2 = X2(Int.self)
let x2check: X2 = x2 // expected-error{{value of optional type 'X2?' not unwrapped; did you mean to use '!' or '?'?}}
// rdar://problem/28051973
struct R_28051973 {
mutating func f(_ i: Int) {}
@available(*, deprecated, message: "deprecated")
func f(_ f: Float) {}
}
let r28051973: Int = 42
R_28051973().f(r28051973) // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}}
// Fix for CSDiag vs CSSolver disagreement on what constitutes a
// valid overload.
func overloadedMethod(n: Int) {} // expected-note {{'overloadedMethod(n:)' declared here}}
func overloadedMethod<T>() {}
// expected-error@-1 {{generic parameter 'T' is not used in function signature}}
overloadedMethod()
// expected-error@-1 {{missing argument for parameter 'n' in call}}
// Ensure we select the overload of '??' returning T? rather than T.
func SR3817(_ d: [String : Any], _ s: String, _ t: String) -> Any {
if let r = d[s] ?? d[t] {
return r
} else {
return 0
}
}
// Overloading with mismatched labels.
func f6<T>(foo: T) { }
func f6<T: P1>(bar: T) { }
struct X6 {
init<T>(foo: T) { }
init<T: P1>(bar: T) { }
}
func test_f6() {
let _: (X1a) -> Void = f6
let _: (X1a) -> X6 = X6.init
}
func curry<LHS, RHS, R>(_ f: @escaping (LHS, RHS) -> R) -> (LHS) -> (RHS) -> R {
return { lhs in { rhs in f(lhs, rhs) } }
}
// We need to have an alternative version of this to ensure that there's an overload disjunction created.
func curry<F, S, T, R>(_ f: @escaping (F, S, T) -> R) -> (F) -> (S) -> (T) -> R {
return { fst in { snd in { thd in f(fst, snd, thd) } } }
}
// Ensure that we consider these unambiguous
let _ = curry(+)(1)
let _ = [0].reduce(0, +)
| apache-2.0 | f021b1703513fb591d13fcfab1b9c45b | 25.035714 | 132 | 0.61917 | 2.954407 | false | false | false | false |
sberrevoets/SDCAlertView | Source/Presentation/PresentationController.swift | 1 | 1493 | import UIKit
class PresentationController: UIPresentationController {
private let dimmingView = UIView()
init(presentedViewController: UIViewController,
presenting presentingViewController: UIViewController?,
dimmingViewColor: UIColor)
{
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
self.dimmingView.backgroundColor = dimmingViewColor
}
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
self.presentingViewController.view.tintAdjustmentMode = .dimmed
self.dimmingView.alpha = 0
self.containerView?.addSubview(self.dimmingView)
let coordinator = self.presentedViewController.transitionCoordinator
coordinator?.animate(alongsideTransition: { _ in self.dimmingView.alpha = 1 }, completion: nil)
}
override func dismissalTransitionWillBegin() {
super.dismissalTransitionWillBegin()
self.presentingViewController.view.tintAdjustmentMode = .automatic
let coordinator = self.presentedViewController.transitionCoordinator
coordinator?.animate(alongsideTransition: { _ in self.dimmingView.alpha = 0 }, completion: nil)
}
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
if let containerView = self.containerView {
self.dimmingView.frame = containerView.frame
}
}
}
| mit | b0a7faef6bbdf2624d8ff163eba72801 | 33.72093 | 106 | 0.731413 | 6.407725 | false | false | false | false |
Jnosh/swift | validation-test/compiler_crashers_fixed/00232-swift-lookupresult-filter.swift | 65 | 1245 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: a {
}
class b<h, i> {
}
protocol c {
typealias g
}
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
| apache-2.0 | 430d765c80ed7ea289414235363ad8a9 | 17.863636 | 79 | 0.496386 | 2.855505 | false | false | false | false |
Raizlabs/BonMot | Sources/Composable.swift | 1 | 12827 | //
// Composable.swift
// BonMot
//
// Created by Brian King on 9/28/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// Describes types which know how to append themselves to an attributed string.
/// Used to provide a flexible, extensible chaning API for BonMot.
public protocol Composable {
/// Append the receiver to a given attributed string. It is up to the
/// receiver's type to define what it means to be appended to an attributed
/// string. Typically, the receiver will pick up the attributes of the last
/// character of the passed attributed string, but the `baseStyle` parameter
/// can be used to provide additional attributes for the appended string.
///
/// - Parameters:
/// - attributedString: The attributed string to which to append the
/// receiver.
/// - baseStyle: Additional attributes to apply to the receiver before
/// appending it to the passed attributed string.
func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle)
/// Append the receiver to a given attributed string. It is up to the
/// receiver's type to define what it means to be appended to an attributed
/// string. Typically, the receiver will pick up the attributes of the last
/// character of the passed attributed string, but the `baseStyle` parameter
/// can be used to provide additional attributes for the appended string.
///
/// - Parameters:
/// - attributedString: The attributed string to which to append the
/// receiver.
/// - baseStyle: Additional attributes to apply to the receiver before
/// appending it to the passed attributed string.
/// - isLastElement: Whether the receiver is the final element that is
/// being appended to an attributed string. Used in cases
/// where the receiver wants to customize how it is
/// appended if it knows it is the last element, chiefly
/// regarding NSAttributedStringKey.kern.
func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool)
}
extension Composable {
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle) {
append(to: attributedString, baseStyle: baseStyle, isLastElement: false)
}
/// Create an attributed string with only this composable content, and no
/// base style.
///
/// - returns: a new `NSAttributedString`
public func attributedString() -> NSAttributedString {
return .composed(of: [self])
}
/// Create a new `NSAttributedString` with the style specified.
///
/// - parameter style: The style to use.
/// - parameter overrideParts: The style parts to override on the base style.
/// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern
/// from the last character of the result.
/// - returns: A new `NSAttributedString`.
public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString {
let string = NSMutableAttributedString()
let newStyle = style.byAdding(stringStyle: StringStyle(overrideParts))
append(to: string, baseStyle: newStyle, isLastElement: stripTrailingKerning)
return string
}
/// Create a new `NSAttributedString` with the style parts specified.
///
/// - parameter parts: The style parts to use.
/// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern
/// from the last character of the result.
/// - returns: A new `NSAttributedString`.
public func styled(with parts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString {
var style = StringStyle()
for part in parts {
style.update(part: part)
}
return styled(with: style, stripTrailingKerning: stripTrailingKerning)
}
}
extension NSAttributedString {
/// Compose an `NSAttributedString` by concatenating every item in
/// `composables` with `baseStyle` applied. The `separator` is inserted
/// between every item. `baseStyle` acts as the default style, and apply to
/// the `Composable` item only if the `Composable` does not have a style
/// value configured.
///
/// - parameter composables: An array of `Composable` to join into an
/// `NSAttributedString`.
/// - parameter baseStyle: The base style to apply to every `Composable`.
/// If no `baseStyle` is supplied, no additional
/// styling will be added.
/// - parameter separator: The separator to insert between every pair of
/// elements in `composables`.
/// - returns: A new `NSAttributedString`.
@nonobjc public static func composed(of composables: [Composable], baseStyle: StringStyle = StringStyle(), separator: Composable? = nil) -> NSAttributedString {
let string = NSMutableAttributedString()
string.beginEditing()
let lastComposableIndex = composables.endIndex
for (index, composable) in composables.enumerated() {
composable.append(to: string, baseStyle: baseStyle, isLastElement: index == lastComposableIndex - 1)
if let separator = separator {
if index != composables.indices.last {
separator.append(to: string, baseStyle: baseStyle)
}
}
}
string.endEditing()
return string
}
public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part...) -> NSAttributedString {
let newStyle = style.byAdding(overrideParts)
let newAttributes = newStyle.attributes
let mutableSelf = mutableStringCopy()
let fullRange = NSRange(location: 0, length: mutableSelf.string.utf16.count)
for (key, value) in newAttributes {
mutableSelf.addAttribute(key, value: value, range: fullRange)
}
return mutableSelf.immutableCopy()
}
}
extension NSAttributedString: Composable {
/// Append this `NSAttributedString` to `attributedString`, with `baseStyle`
/// applied as default values. This method enumerates all attribute ranges
/// in the receiver and use `baseStyle` to supply defaults for the attributes.
/// This effectively merges `baseStyle` and the embedded attributes, with a
/// tie going to the embedded attributes.
///
/// See `StringStyle.supplyDefaults(for:)` for more details.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The `StringStyle` that is overridden by the
/// receiver's attributes
@nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
let range = NSRange(location: 0, length: length)
enumerateAttributes(in: range, options: []) { (attributes, range, _) in
let substring = self.attributedSubstring(from: range)
// Add the string with the defaults supplied by the style
let newString = baseStyle.attributedString(from: substring.string, existingAttributes: attributes)
attributedString.append(newString)
}
if isLastElement {
attributedString.removeKerningFromLastCharacter()
}
else {
attributedString.restoreKerningOnLastCharacter()
}
}
}
extension String: Composable {
/// Append the receiver to `attributedString`, with `baseStyle` applied as
/// default values. Since `String` has no style, `baseStyle` is the only
/// style that is used.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use for this string.
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
attributedString.append(baseStyle.attributedString(from: self))
if isLastElement {
attributedString.removeKerningFromLastCharacter()
}
else {
attributedString.restoreKerningOnLastCharacter()
}
}
}
#if os(iOS) || os(tvOS) || os(OSX)
extension BONImage: Composable {
/// Append the receiver to `attributedString`, with `baseStyle` applied as
/// default values. Only a few properties in `baseStyle` are relevant when
/// styling images. These include `baselineOffset`, as well as `color` for
/// template images. All attributes are stored in the range of the image for
/// consistency inside the attributed string.
///
/// - note: the `NSBaselineOffsetAttributeName` value is used as the
/// `bounds.origin.y` value for the text attachment, and is removed from the
/// attributes dictionary to fix an issue with UIKit.
///
/// - note: `NSTextAttachment` is not available on watchOS.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use.
@nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
let baselinesOffsetForAttachment = baseStyle.baselineOffset ?? 0
let attachment = NSTextAttachment()
#if os(OSX)
let imageIsTemplate = isTemplate
#else
let imageIsTemplate = (renderingMode != .alwaysOriginal)
#endif
var imageToUse = self
if let color = baseStyle.color {
if imageIsTemplate {
imageToUse = tintedImage(color: color)
}
}
attachment.image = imageToUse
attachment.bounds = CGRect(origin: CGPoint(x: 0, y: baselinesOffsetForAttachment), size: size)
let attachmentString = NSAttributedString(attachment: attachment).mutableStringCopy()
// Remove the baseline offset from the attributes so it isn't applied twice
var attributes = baseStyle.attributes
attributes[.baselineOffset] = nil
attachmentString.addAttributes(attributes, range: NSRange(location: 0, length: attachmentString.length))
attributedString.append(attachmentString)
}
}
#endif
extension Special: Composable {
/// Append the receiver's string value to `attributedString`, with `baseStyle`
/// applied as default values.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use.
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
description.append(to: attributedString, baseStyle: baseStyle)
}
}
public extension Sequence where Element: Composable {
func joined(separator: Composable = "") -> NSAttributedString {
return NSAttributedString.composed(of: Array(self), separator: separator)
}
}
extension NSAttributedString.Key {
public static let bonMotRemovedKernAttribute = NSAttributedString.Key("com.raizlabs.bonmot.removedKernAttributeRemoved")
}
extension NSMutableAttributedString {
func removeKerningFromLastCharacter() {
guard length != 0 else {
return
}
let lastCharacterLength = string.suffix(1).utf16.count
let lastCharacterRange = NSRange(location: length - lastCharacterLength, length: lastCharacterLength)
guard let currentKernValue = attribute(.kern, at: lastCharacterRange.location, effectiveRange: nil) else {
return
}
removeAttribute(.kern, range: lastCharacterRange)
addAttribute(.bonMotRemovedKernAttribute, value: currentKernValue, range: lastCharacterRange)
}
func restoreKerningOnLastCharacter() {
guard length != 0 else {
return
}
let lastCharacterLength = string.suffix(1).utf16.count
let lastCharacterRange = NSRange(location: length - lastCharacterLength, length: lastCharacterLength)
guard let currentKernValue = attribute(.bonMotRemovedKernAttribute, at: lastCharacterRange.location, effectiveRange: nil) else {
return
}
removeAttribute(.bonMotRemovedKernAttribute, range: lastCharacterRange)
addAttribute(.kern, value: currentKernValue, range: lastCharacterRange)
}
}
| mit | 465a211dea2fb7bae8301803c89c1aeb | 41.052459 | 164 | 0.665523 | 5.073576 | false | false | false | false |
AugustRush/EasyLayout-Swift | Sources/UIView(EasyLayout).swift | 1 | 5252 |
//
// UIView(EasyLayout).swift
// EasyLayout
//
// Created by AugustRush on 4/28/16.
// Copyright © 2016 August. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
public typealias ELMakerClosure = (_ make : ELLayoutConstraintMaker) -> Void
extension View : ELLayoutAttributeProtocol {
//MARK: Make Constraints Methods
public func makeConstraints(closure : ELMakerClosure) {
self.translatesAutoresizingMaskIntoConstraints = false
closure(maker)
maker.install()
}
public func remakeConstraints(closure : ELMakerClosure) {
self.translatesAutoresizingMaskIntoConstraints = false
maker.removeAll()
closure(maker)
maker.install()
}
func updateConstraints(closure : ELMakerClosure) {
self.translatesAutoresizingMaskIntoConstraints = false
closure(maker)
maker.updateExsit()
}
//MARK: ELLayoutAttributeProtocol
public var ELLeft : ELLayoutConstraintModel {
return constraintModel(.left)
}
public var ELRight : ELLayoutConstraintModel {
return constraintModel(.right)
}
public var ELTop : ELLayoutConstraintModel {
return constraintModel(.top)
}
public var ELBottom : ELLayoutConstraintModel {
return constraintModel(.bottom)
}
public var ELWidth : ELLayoutConstraintModel {
return constraintModel(.width)
}
public var ELHeight : ELLayoutConstraintModel {
return constraintModel(.height)
}
public var ELNone : ELLayoutConstraintModel {
return constraintModel(.notAnAttribute)
}
public var ELCenterX : ELLayoutConstraintModel {
return constraintModel(.centerX)
}
public var ELCenterY : ELLayoutConstraintModel {
return constraintModel(.centerY)
}
public var ELLeading : ELLayoutConstraintModel {
return constraintModel(.leading)
}
public var ELTrailing : ELLayoutConstraintModel {
return constraintModel(.trailing)
}
public var ELLastBaseline : ELLayoutConstraintModel {
return constraintModel(.lastBaseline)
}
public var ELSize: ELLayoutCombinationConstraintModel {
let width = constraintModel(.width)
let height = constraintModel(.height)
return ELLayoutCombinationConstraintModel(ms: width,height)
}
public var ELCenter: ELLayoutCombinationConstraintModel {
let centerX = constraintModel(.centerX)
let centerY = constraintModel(.centerY)
return ELLayoutCombinationConstraintModel(ms: centerX,centerY)
}
public var ELAllEdges: ELLayoutCombinationConstraintModel {
let top = constraintModel(.top)
let left = constraintModel(.left)
let bottom = constraintModel(.bottom)
let right = constraintModel(.right)
return ELLayoutCombinationConstraintModel(ms: top,left,bottom,right)
}
public func ELCombination(attrs: NSLayoutAttribute...) -> ELLayoutCombinationConstraintModel {
var models : [ELLayoutConstraintModel] = Array()
for attr in attrs {
let m = constraintModel(attr)
models.append(m)
}
return ELLayoutCombinationConstraintModel(ms: models)
}
@available(iOS 8.0, *)
public var ELFirstBaseline : ELLayoutConstraintModel {
return constraintModel(.firstBaseline)
}
@available(iOS 8.0, *)
public var ELLeftMargin : ELLayoutConstraintModel {
return constraintModel(.leftMargin)
}
@available(iOS 8.0, *)
public var ELRightMargin : ELLayoutConstraintModel {
return constraintModel(.rightMargin)
}
@available(iOS 8.0, *)
public var ELBottomMargin : ELLayoutConstraintModel {
return constraintModel(.bottomMargin)
}
@available(iOS 8.0, *)
public var ELLeadingMargin : ELLayoutConstraintModel {
return constraintModel(.leadingMargin)
}
@available(iOS 8.0, *)
public var ELTrailingMargin : ELLayoutConstraintModel {
return constraintModel(.trailingMargin)
}
@available(iOS 8.0, *)
public var ELCenterXWithMargins : ELLayoutConstraintModel {
return constraintModel(.centerXWithinMargins)
}
@available(iOS 8.0, *)
public var ELCenterYWithMargins : ELLayoutConstraintModel {
return constraintModel(.centerYWithinMargins)
}
private func constraintModel(_ attribute : NSLayoutAttribute) -> ELLayoutConstraintModel {
let model = ELLayoutConstraintModel(view: self,attribute: attribute)
return model
}
private var maker : ELLayoutConstraintMaker {
get {
var make = objc_getAssociatedObject(self, &ELLayoutConstraintMakerIdentifier) as? ELLayoutConstraintMaker
if make == nil {
make = ELLayoutConstraintMaker(view : self)
objc_setAssociatedObject(self, &ELLayoutConstraintMakerIdentifier, make, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return make!
}
}
}
private var ELLayoutConstraintMakerIdentifier = "_EasyLayoutMaker_"
| mit | 18600e0601138db443da2f946abb174e | 30.824242 | 124 | 0.677395 | 5.00572 | false | false | false | false |
chrisjmendez/swift-exercises | Walkthroughs/MyPresentation/Carthage/Checkouts/Cartography/CartographyTests/MemoryLeakSpec.swift | 23 | 1232 | import Cartography
import Nimble
import Quick
class MemoryLeakSpec: QuickSpec {
override func spec() {
describe("constrain") {
it("should not leak memory") {
weak var weak_superview: View? = .None
weak var weak_viewA: View? = .None
weak var weak_viewB: View? = .None
autoreleasepool {
let superview = View(frame: CGRectMake(0, 0, 400, 400))
let viewA: TestView = TestView(frame: CGRectMake(0, 0, 200, 200))
superview.addSubview(viewA)
let viewB: TestView = TestView(frame: CGRectMake(0, 0, 200, 200))
superview.addSubview(viewB)
weak_superview = superview
weak_viewA = viewA
weak_viewB = viewB
constrain(viewA, viewB) { viewA, viewB in
viewA.top == viewB.top
viewB.bottom == viewA.bottom
}
}
expect(weak_superview).to(beNil())
expect(weak_viewA).to(beNil())
expect(weak_viewB).to(beNil())
}
}
}
}
| mit | 7eb06960bd40ac53cdae36d144ee28ce | 30.589744 | 85 | 0.473214 | 4.684411 | false | true | false | false |
coach-plus/ios | Pods/Hero/Sources/HeroContext.swift | 1 | 13496 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 UIKit
public class HeroContext {
internal var heroIDToSourceView = [String: UIView]()
internal var heroIDToDestinationView = [String: UIView]()
internal var snapshotViews = [UIView: UIView]()
internal var viewAlphas = [UIView: CGFloat]()
internal var targetStates = [UIView: HeroTargetState]()
internal var superviewToNoSnapshotSubviewMap: [UIView: [(Int, UIView)]] = [:]
internal var insertToViewFirst = false
internal var defaultCoordinateSpace: HeroCoordinateSpace = .local
internal init(container: UIView) {
self.container = container
}
internal func set(fromViews: [UIView], toViews: [UIView]) {
self.fromViews = fromViews
self.toViews = toViews
process(views: fromViews, idMap: &heroIDToSourceView)
process(views: toViews, idMap: &heroIDToDestinationView)
}
internal func process(views: [UIView], idMap: inout [String: UIView]) {
for view in views {
view.layer.removeAllHeroAnimations()
let targetState: HeroTargetState?
if let modifiers = view.hero.modifiers {
targetState = HeroTargetState(modifiers: modifiers)
} else {
targetState = nil
}
if targetState?.forceAnimate == true || container.convert(view.bounds, from: view).intersects(container.bounds) {
if let heroID = view.hero.id {
idMap[heroID] = view
}
targetStates[view] = targetState
}
}
}
/**
The container holding all of the animating views
*/
public let container: UIView
/**
A flattened list of all views from source ViewController
*/
public var fromViews: [UIView] = []
/**
A flattened list of all views from destination ViewController
*/
public var toViews: [UIView] = []
}
// public
extension HeroContext {
/**
- Returns: a source view matching the heroID, nil if not found
*/
public func sourceView(for heroID: String) -> UIView? {
return heroIDToSourceView[heroID]
}
/**
- Returns: a destination view matching the heroID, nil if not found
*/
public func destinationView(for heroID: String) -> UIView? {
return heroIDToDestinationView[heroID]
}
/**
- Returns: a view with the same heroID, but on different view controller, nil if not found
*/
public func pairedView(for view: UIView) -> UIView? {
if let id = view.hero.id {
if sourceView(for: id) == view {
return destinationView(for: id)
} else if destinationView(for: id) == view {
return sourceView(for: id)
}
}
return nil
}
/**
- Returns: a snapshot view for animation
*/
public func snapshotView(for view: UIView) -> UIView {
if let snapshot = snapshotViews[view] {
return snapshot
}
var containerView = container
let coordinateSpace = targetStates[view]?.coordinateSpace ?? defaultCoordinateSpace
switch coordinateSpace {
case .local:
containerView = view
while containerView != container, snapshotViews[containerView] == nil, let superview = containerView.superview {
containerView = superview
}
if let snapshot = snapshotViews[containerView] {
containerView = snapshot
}
if let visualEffectView = containerView as? UIVisualEffectView {
containerView = visualEffectView.contentView
}
case .global:
break
}
unhide(view: view)
// capture a snapshot without alpha, cornerRadius, or shadows
let oldCornerRadius = view.layer.cornerRadius
let oldAlpha = view.alpha
let oldShadowRadius = view.layer.shadowRadius
let oldShadowOffset = view.layer.shadowOffset
let oldShadowPath = view.layer.shadowPath
let oldShadowOpacity = view.layer.shadowOpacity
view.layer.cornerRadius = 0
view.alpha = 1
view.layer.shadowRadius = 0.0
view.layer.shadowOffset = .zero
view.layer.shadowPath = nil
view.layer.shadowOpacity = 0.0
let snapshot: UIView
let snapshotType: HeroSnapshotType = self[view]?.snapshotType ?? .optimized
switch snapshotType {
case .normal:
snapshot = view.snapshotView() ?? UIView()
case .layerRender:
snapshot = view.slowSnapshotView()
case .noSnapshot:
if view.superview != container {
if superviewToNoSnapshotSubviewMap[view.superview!] == nil {
superviewToNoSnapshotSubviewMap[view.superview!] = []
}
superviewToNoSnapshotSubviewMap[view.superview!]!.append((view.superview!.subviews.index(of: view)!, view))
}
snapshot = view
case .optimized:
#if os(tvOS)
snapshot = view.snapshotView(afterScreenUpdates: true)!
#else
if let customSnapshotView = view as? HeroCustomSnapshotView, let snapshotView = customSnapshotView.heroSnapshot {
snapshot = snapshotView
} else if #available(iOS 9.0, *), let stackView = view as? UIStackView {
snapshot = stackView.slowSnapshotView()
} else if let imageView = view as? UIImageView, view.subviews.filter({!$0.isHidden}).isEmpty {
let contentView = UIImageView(image: imageView.image)
contentView.frame = imageView.bounds
contentView.contentMode = imageView.contentMode
contentView.tintColor = imageView.tintColor
contentView.backgroundColor = imageView.backgroundColor
contentView.layer.magnificationFilter = imageView.layer.magnificationFilter
contentView.layer.minificationFilter = imageView.layer.minificationFilter
contentView.layer.minificationFilterBias = imageView.layer.minificationFilterBias
let snapShotView = UIView()
snapShotView.addSubview(contentView)
snapshot = snapShotView
} else if let barView = view as? UINavigationBar, barView.isTranslucent {
let newBarView = UINavigationBar(frame: barView.frame)
newBarView.barStyle = barView.barStyle
newBarView.tintColor = barView.tintColor
newBarView.barTintColor = barView.barTintColor
newBarView.clipsToBounds = false
// take a snapshot without the background
barView.layer.sublayers![0].opacity = 0
let realSnapshot = barView.snapshotView(afterScreenUpdates: true)!
barView.layer.sublayers![0].opacity = 1
newBarView.addSubview(realSnapshot)
snapshot = newBarView
} else if let effectView = view as? UIVisualEffectView {
snapshot = UIVisualEffectView(effect: effectView.effect)
snapshot.frame = effectView.bounds
} else {
snapshot = view.snapshotView() ?? UIView()
}
#endif
}
#if os(tvOS)
if let imageView = view as? UIImageView, imageView.adjustsImageWhenAncestorFocused {
snapshot.frame = imageView.focusedFrameGuide.layoutFrame
}
#endif
view.layer.cornerRadius = oldCornerRadius
view.alpha = oldAlpha
view.layer.shadowRadius = oldShadowRadius
view.layer.shadowOffset = oldShadowOffset
view.layer.shadowPath = oldShadowPath
view.layer.shadowOpacity = oldShadowOpacity
snapshot.layer.anchorPoint = view.layer.anchorPoint
snapshot.layer.position = containerView.convert(view.layer.position, from: view.superview!)
snapshot.layer.transform = containerView.layer.flatTransformTo(layer: view.layer)
snapshot.layer.bounds = view.layer.bounds
snapshot.hero.id = view.hero.id
if snapshotType != .noSnapshot {
if !(view is UINavigationBar), let contentView = snapshot.subviews.get(0) {
// the Snapshot's contentView must have hold the cornerRadius value,
// since the snapshot might not have maskToBounds set
contentView.layer.cornerRadius = view.layer.cornerRadius
contentView.layer.masksToBounds = true
}
snapshot.layer.allowsGroupOpacity = false
snapshot.layer.cornerRadius = view.layer.cornerRadius
snapshot.layer.zPosition = view.layer.zPosition
snapshot.layer.opacity = view.layer.opacity
snapshot.layer.isOpaque = view.layer.isOpaque
snapshot.layer.anchorPoint = view.layer.anchorPoint
snapshot.layer.masksToBounds = view.layer.masksToBounds
snapshot.layer.borderColor = view.layer.borderColor
snapshot.layer.borderWidth = view.layer.borderWidth
snapshot.layer.contentsRect = view.layer.contentsRect
snapshot.layer.contentsScale = view.layer.contentsScale
if self[view]?.displayShadow ?? true {
snapshot.layer.shadowRadius = view.layer.shadowRadius
snapshot.layer.shadowOpacity = view.layer.shadowOpacity
snapshot.layer.shadowColor = view.layer.shadowColor
snapshot.layer.shadowOffset = view.layer.shadowOffset
snapshot.layer.shadowPath = view.layer.shadowPath
}
hide(view: view)
}
if let pairedView = pairedView(for: view), let pairedSnapshot = snapshotViews[pairedView] {
let siblingViews = pairedView.superview!.subviews
let nextSiblings = siblingViews[siblingViews.index(of: pairedView)!+1..<siblingViews.count]
containerView.addSubview(pairedSnapshot)
containerView.addSubview(snapshot)
for subview in pairedView.subviews {
insertGlobalViewTree(view: subview)
}
for sibling in nextSiblings {
insertGlobalViewTree(view: sibling)
}
} else {
containerView.addSubview(snapshot)
}
containerView.addSubview(snapshot)
snapshotViews[view] = snapshot
return snapshot
}
func insertGlobalViewTree(view: UIView) {
if targetStates[view]?.coordinateSpace == .global, let snapshot = snapshotViews[view] {
container.addSubview(snapshot)
}
for subview in view.subviews {
insertGlobalViewTree(view: subview)
}
}
public subscript(view: UIView) -> HeroTargetState? {
get {
return targetStates[view]
}
set {
targetStates[view] = newValue
}
}
public func clean() {
for (superview, subviews) in superviewToNoSnapshotSubviewMap {
for (index, view) in subviews.reversed() {
superview.insertSubview(view, at: index)
}
}
}
}
// internal
extension HeroContext {
public func hide(view: UIView) {
if viewAlphas[view] == nil {
if view is UIVisualEffectView {
view.isHidden = true
viewAlphas[view] = 1
} else {
viewAlphas[view] = view.alpha
view.alpha = 0
}
}
}
public func unhide(view: UIView) {
if let oldAlpha = viewAlphas[view] {
if view is UIVisualEffectView {
view.isHidden = false
} else {
view.alpha = oldAlpha
}
viewAlphas[view] = nil
}
}
internal func unhideAll() {
for view in viewAlphas.keys {
unhide(view: view)
}
viewAlphas.removeAll()
}
internal func unhide(rootView: UIView) {
unhide(view: rootView)
for subview in rootView.subviews {
unhide(rootView: subview)
}
}
internal func removeAllSnapshots() {
for (view, snapshot) in snapshotViews {
if view != snapshot {
snapshot.removeFromSuperview()
} else {
view.layer.removeAllHeroAnimations()
}
}
}
internal func removeSnapshots(rootView: UIView) {
if let snapshot = snapshotViews[rootView] {
if rootView != snapshot {
snapshot.removeFromSuperview()
} else {
rootView.layer.removeAllHeroAnimations()
}
}
for subview in rootView.subviews {
removeSnapshots(rootView: subview)
}
}
internal func snapshots(rootView: UIView) -> [UIView] {
var snapshots = [UIView]()
for v in rootView.flattenedViewHierarchy {
if let snapshot = snapshotViews[v] {
snapshots.append(snapshot)
}
}
return snapshots
}
internal func loadViewAlpha(rootView: UIView) {
if let storedAlpha = rootView.hero.storedAlpha {
rootView.alpha = storedAlpha
rootView.hero.storedAlpha = nil
}
for subview in rootView.subviews {
loadViewAlpha(rootView: subview)
}
}
internal func storeViewAlpha(rootView: UIView) {
rootView.hero.storedAlpha = viewAlphas[rootView]
for subview in rootView.subviews {
storeViewAlpha(rootView: subview)
}
}
}
/// Allows a view to create their own custom snapshot when using **Optimized** snapshot
public protocol HeroCustomSnapshotView {
var heroSnapshot: UIView? { get }
}
| mit | 086a775c0b6c07d1254c908f1155b5b4 | 32.994962 | 121 | 0.684573 | 4.592038 | false | false | false | false |
davepagurek/raytracer | Sources/RaytracerLib/Camera.swift | 1 | 1287 | import VectorMath
import Foundation
public struct Camera {
let origin, swCorner, h, v: Vector4
let aperture, focalDistance: Scalar
public init(from: Vector4, to: Vector4, up: Vector4, vfov: Scalar, aspect: Scalar, aperture: Scalar, focalDistance: Scalar) {
let theta = Double(vfov) * M_PI/180
let halfHeight:Scalar = Scalar(tan(theta/2))
let halfWidth:Scalar = aspect*halfHeight
let direction = (from - to).normalized()
let x3 = up.xyz.cross(direction.xyz).normalized()
let y3 = direction.xyz.cross(x3).normalized()
let x = Vector(x: x3.x, y: x3.y, z: x3.z)
let y = Vector(x: y3.x, y: y3.y, z: y3.z)
swCorner = from - (x*halfWidth*focalDistance) - (y*halfHeight*focalDistance) - (direction*focalDistance)
h = x * halfWidth * focalDistance * 2
v = y * halfHeight * focalDistance * 2
origin = from
self.aperture = aperture
self.focalDistance = focalDistance
}
func rayAt(x: Scalar, y: Scalar, time: TimeRange) -> Ray {
let randomInLens = randomVectorInDisc()*aperture*0.5
let offset = h*randomInLens.x + v*randomInLens.y
return Ray(
point: origin + offset,
direction: (swCorner + (h*x) + (v*(1-y))) - origin - offset,
color: Color(0xFFFFFF),
time: time
)
}
}
| mit | 53a263756a2ec37f5a1a63fe00b8a196 | 32.868421 | 127 | 0.646465 | 3.233668 | false | false | false | false |
Onix-Systems/RainyRefreshControl | Sources/ONXRefreshControl.swift | 2 | 4785 | //
// BaseRefreshControl.swift
// BaseRefreshControl
//
import UIKit
public class ONXRefreshControl: UIControl {
private var forbidsOffsetChanges = false
private var forbidsInsetChanges = false
private var changingInset = false
private var refreshing = false
private var contentInset: UIEdgeInsets?
public var animationDuration = TimeInterval(0.33)
public var animationDamping = CGFloat(0.4)
public var animationVelocity = CGFloat(0.8)
//delay for finishing custom animation
public var delayBeforeEnd = 0.0
private var expandedHeight: CGFloat {
return UIScreen.main.bounds.height / 6
}
// MARK: Initialization
public convenience init() {
self.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
deinit {
if let superview = superview as? UIScrollView {
superview.removeObserver(self, forKeyPath: "contentOffset")
}
}
// MARK: Superview handling
public override func willMove(toSuperview newSuperview: UIView?) {
if let superview = superview as? UIScrollView {
superview.removeObserver(self, forKeyPath: "contentOffset")
}
super.willMove(toSuperview: newSuperview)
}
public override func didMoveToSuperview() {
if let superview = superview as? UIScrollView {
superview.addObserver(self, forKeyPath: "contentOffset", options: [.new, .old], context: nil)
}
super.didMoveToSuperview()
}
// MARK: Refresh methods
public func beginRefreshing() {
guard let superview = superview as? UIScrollView, !refreshing else { return }
refreshing = true
//Saving inset
contentInset = superview.contentInset
let currentOffset = superview.contentOffset
//Setting new inset
changingInset = true
var inset = superview.contentInset
inset.top = inset.top + expandedHeight
superview.contentInset = inset
changingInset = false
//Aaaaand scrolling
superview.setContentOffset(currentOffset, animated: false)
superview.setContentOffset(CGPoint(x: 0, y: -inset.top), animated: true)
forbidsOffsetChanges = true
didBeginRefresh()
}
public func endRefreshing() {
guard let superview = superview as? UIScrollView, refreshing else { return }
forbidsOffsetChanges = false
refreshing = false
self.willEndRefresh()
DispatchQueue.main.asyncAfter(deadline: .now() + delayBeforeEnd) {
UIView.animate(withDuration: self.animationDuration,
delay: 0,
usingSpringWithDamping: self.animationDamping,
initialSpringVelocity: self.animationVelocity,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
if let contentInset = self.contentInset {
superview.contentInset = contentInset
self.contentInset = nil
}
}) { (finished) -> Void in
self.didEndRefresh()
}
}
}
// MARK: KVO
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let superview = superview as? UIScrollView, !changingInset else { return }
//Updating frame
let topInset = (contentInset ?? superview.contentInset).top
let originY = superview.contentOffset.y + topInset
let height = originY
frame = CGRect(origin: CGPoint(x: 0, y: originY),
size: CGSize(width: superview.frame.width, height: -height))
layout()
//Detecting refresh gesture
if superview.contentOffset.y + topInset <= -expandedHeight {
forbidsInsetChanges = true
} else if !refreshing {
forbidsInsetChanges = false
}
if !superview.isDragging && superview.isDecelerating && !forbidsOffsetChanges && forbidsInsetChanges {
sendActions(for: .valueChanged)
beginRefreshing()
}
}
open func setup() { }
open func layout() { }
open func willBeginRefresh() { }
open func didBeginRefresh() { }
open func willEndRefresh() { }
open func didEndRefresh() { }
}
| mit | 10cd93c18a91c1aff9709145b17977a8 | 32.93617 | 158 | 0.6 | 5.419026 | false | false | false | false |
ObjSer/objser-swift | ObjSer/Primitive.swift | 1 | 11918 | //
// Primitive.swift
// ObjSer
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Greg Omelaenko
//
// 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.
//
/// Defines the ObjSer primitive types.
enum Primitive {
/// A promised value with an attached function that will be called to resolve the primitive for use.
case Promised(() -> Primitive)
case Reference(UInt32)
case Integer(AnyInteger)
case Nil
case Boolean(Bool)
case Float(AnyFloat)
case String(Swift.String)
case Data(ByteArray)
indirect case TypeIdentified(name: Primitive, value: Primitive)
indirect case Array(ContiguousArray<Primitive>)
/// A map, represented by an array of alternating keys and values.
indirect case Map(ContiguousArray<Primitive>)
}
// MARK: Encoding
extension OutputStream {
/// Convenience method for writing `Primitive` data
func write(byte: Byte, _ array: ByteArray) {
write(byte)
write(array)
}
}
extension Primitive {
func writeTo(stream: OutputStream) {
switch self {
case .Promised(let resolve):
resolve().writeTo(stream)
case .Reference(let v):
switch v {
case 0...0b0011_1111:
stream.write(Format.Ref6.byte | Byte(v))
case 0...0xff:
stream.write(Format.Ref8.byte, Byte(v))
case 0...0xffff:
stream.write(Format.Ref16.byte, UInt16(v).bytes)
case 0...0xffff_ffff:
stream.write(Format.Ref32.byte, UInt32(v).bytes)
default:
preconditionFailure("Could not format reference value \(v) greater than 2³² - 1.")
}
case .Integer(let v):
if let v = Int8(convert: v) {
switch v {
case 0...0b0011_1111:
stream.write(Format.PosInt6.byte | Byte(v))
case -32..<0:
stream.write(Byte(bitPattern: v))
default:
stream.write(Format.Int8.byte, Byte(bitPattern: v))
}
}
else if let v = UInt8(convert: v) { stream.write(Format.UInt8.byte, v) }
else if let v = Int16(convert: v) { stream.write(Format.Int16.byte, v.bytes) }
else if let v = UInt16(convert: v) { stream.write(Format.UInt16.byte, v.bytes) }
else if let v = Int32(convert: v) { stream.write(Format.Int32.byte, v.bytes) }
else if let v = UInt32(convert: v) { stream.write(Format.UInt32.byte, v.bytes) }
else if let v = Int64(convert: v) { stream.write(Format.Int64.byte, v.bytes) }
else if let v = UInt64(convert: v) { stream.write(Format.UInt64.byte, v.bytes) }
case .Nil:
stream.write(Format.Nil.byte)
case .Boolean(let v):
stream.write(v ? Format.True.byte : Format.False.byte)
case .Float(let v):
if let v = v.exactFloat32Value { stream.write(Format.Float32.byte, v.bytes) }
else { stream.write(Format.Float64.byte, Float64(v).bytes) }
case .String(let v):
switch v.utf8.count {
case 0:
stream.write(Format.EString.byte)
case 1...0b0000_1111:
var b = v.nulTerminatedUTF8
b.removeLast()
stream.write(Format.FString.byte | Byte(b.count), b)
default:
stream.write(Format.VString.byte, v.nulTerminatedUTF8)
}
case .Data(let v):
let c = v.count
switch c {
case 0:
stream.write(Format.EData.byte)
case 1...0b0000_1111:
stream.write(Format.FData.byte | Byte(c), v)
case 0...0xff:
stream.write(Format.VData8.byte, Byte(c))
stream.write(v)
case 0...0xffff:
stream.write(Format.VData16.byte, UInt16(c).bytes)
stream.write(v)
default:
stream.write(Format.VData32.byte, UInt32(c).bytes)
stream.write(v)
}
case .Array(let v):
let c = v.count
switch c {
case 0:
stream.write(Format.EArray.byte)
case 1...0b001_1111:
stream.write(Format.FArray.byte | Byte(c))
v.forEach { $0.writeTo(stream) }
default:
stream.write(Format.VArray.byte)
v.forEach { $0.writeTo(stream) }
stream.write(Format.Sentinel.byte)
}
case .Map(let a):
if a.count == 0 {
stream.write(Format.EMap.byte)
}
else {
stream.write(Format.Map.byte)
Primitive.Array(a).writeTo(stream)
}
case .TypeIdentified(let name, let v):
stream.write(Format.TypeID.byte)
name.writeTo(stream)
v.writeTo(stream)
}
}
}
// MARK: Decoding
extension InputStream {
func readByteArray(length length: Int) -> ByteArray {
return ByteArray(readBytes(length: length))
}
}
extension String {
init?(UTF8Bytes bytes: ByteArray) {
guard let str = bytes.withUnsafeBufferPointer({
String(UTF8String: UnsafePointer<CChar>($0.baseAddress))
}) else {
return nil
}
self = str
}
}
extension Primitive {
enum FormatError: ErrorType {
case SentinelReached
case ReservedCode(Byte)
case InvalidMapArray(Primitive)
case InvalidString(ByteArray)
}
init(readFrom stream: InputStream) throws {
let v = stream.readByte()
switch v {
case Format.Ref6.range:
self = .Reference(UInt32(v))
case Format.Ref8.byte:
self = .Reference(UInt32(stream.readByte()))
case Format.Ref16.byte:
self = .Reference(UInt32(UInt16(bytes: stream.readByteArray(length: 2))))
case Format.Ref32.byte:
self = .Reference(UInt32(bytes: stream.readByteArray(length: 4)))
case Format.PosInt6.range:
self = .Integer(AnyInteger(v & 0b0011_1111))
case Format.NegInt5.range:
self = .Integer(AnyInteger(Int8(bitPattern: v)))
case Format.False.byte:
self = .Boolean(false)
case Format.True.byte:
self = .Boolean(true)
case Format.Nil.byte:
self = .Nil
case Format.Int8.byte:
self = .Integer(AnyInteger(Int8(bitPattern: stream.readByte())))
case Format.Int16.byte:
self = .Integer(AnyInteger(Int16(bytes: stream.readByteArray(length: 2))))
case Format.Int32.byte:
self = .Integer(AnyInteger(Int32(bytes: stream.readByteArray(length: 4))))
case Format.Int64.byte:
self = .Integer(AnyInteger(Int64(bytes: stream.readByteArray(length: 8))))
case Format.UInt8.byte:
self = .Integer(AnyInteger(UInt8(stream.readByte())))
case Format.UInt16.byte:
self = .Integer(AnyInteger(UInt16(bytes: stream.readByteArray(length: 2))))
case Format.UInt32.byte:
self = .Integer(AnyInteger(UInt32(bytes: stream.readByteArray(length: 4))))
case Format.UInt64.byte:
self = .Integer(AnyInteger(UInt64(bytes: stream.readByteArray(length: 8))))
case Format.Float32.byte:
self = .Float(AnyFloat(Float32(bytes: stream.readByteArray(length: 4))))
case Format.Float64.byte:
self = .Float(AnyFloat(Float64(bytes: stream.readByteArray(length: 8))))
case Format.FString.range:
var b = stream.readByteArray(length: Int(v) & 0b1111)
b.append(0)
guard let str = Swift.String(UTF8Bytes: b) else {
throw FormatError.InvalidString(b)
}
self = .String(str)
case Format.VString.byte:
var b = ByteArray()
while b.last != 0 {
b.append(stream.readByte())
}
guard let str = Swift.String(UTF8Bytes: b) else {
throw FormatError.InvalidString(b)
}
self = .String(str)
case Format.EString.byte:
self = .String("")
case Format.FData.range:
self = .Data(stream.readByteArray(length: Int(v) & 0b1111))
case Format.VData8.byte:
self = .Data(stream.readByteArray(length: Int(stream.readByte())))
case Format.VData16.byte:
let len = Swift.UInt16(bytes: stream.readByteArray(length: 2))
self = .Data(stream.readByteArray(length: Int(len)))
case Format.VData32.byte:
let len = Swift.UInt32(bytes: stream.readByteArray(length: 4))
self = .Data(stream.readByteArray(length: Int(len)))
case Format.EData.byte:
self = .Data([])
case Format.FArray.range:
let len = Int(v & 0b1_1111)
var array = ContiguousArray<Primitive>()
array.reserveCapacity(len)
for _ in 0..<len {
array.append(try Primitive(readFrom: stream))
}
self = .Array(array)
case Format.VArray.byte:
var array = ContiguousArray<Primitive>()
while true {
do { array.append(try Primitive(readFrom: stream)) }
catch FormatError.SentinelReached { break }
}
self = .Array(array)
case Format.EArray.byte:
self = .Array([])
case Format.Map.byte:
let a = try Primitive(readFrom: stream)
guard case .Array(let v) = a else {
throw FormatError.InvalidMapArray(a)
}
self = .Map(v)
case Format.EMap.byte:
self = .Map([])
case Format.TypeID.byte:
self = .TypeIdentified(name: try Primitive(readFrom: stream), value: try Primitive(readFrom: stream))
case Format.Sentinel.byte:
throw FormatError.SentinelReached
case Format.Reserved.range:
throw FormatError.ReservedCode(v)
default:
preconditionFailure("Unrecognised format value \(v). THIS SHOULD NEVER HAPPEN — the format reader should cover all possible byte values. Please report this issue, including the library version, and the unrecognised value \(v).")
}
}
}
| mit | 6287c27f69259d556c3136c5e392e923 | 35.434251 | 240 | 0.559678 | 4.174492 | false | false | false | false |
ccwuzhou/WWZSwift | Source/Models/WWZLanguage.swift | 1 | 2409 | //
// WWZLanguage.swift
// WWZSwift
//
// Created by wwz on 2017/4/6.
// Copyright © 2017年 tijio. All rights reserved.
//
import UIKit
private let WWZ_EN_VALUE = "en"
private let WWZ_ZH_HANS_VALUE = "zh-Hans"
private let WWZ_ZH_HANT_VALUE = "zh-Hant"
public enum WWZLanguageType {
case english
case simpleChinese
case hantChinese
case other
}
public class WWZLanguage: NSObject {
public static let shared = WWZLanguage()
/// 当前语言
public lazy var currentLanguageValue : String = {
guard let languageValues = UserDefaults.standard.object(forKey: "AppleLanguages") as? [String] else { return WWZ_EN_VALUE }
let languageValue = languageValues[0]
if languageValue.hasPrefix(WWZ_ZH_HANS_VALUE) {
return WWZ_ZH_HANS_VALUE
}
if languageValue.hasPrefix(WWZ_ZH_HANT_VALUE) {
return WWZ_ZH_HANT_VALUE
}
return languageValue
}()
/// 当前语言类型
public var languageType : WWZLanguageType {
if currentLanguageValue == WWZ_EN_VALUE {
return .english
}else if currentLanguageValue == WWZ_ZH_HANS_VALUE {
return .simpleChinese
}else if currentLanguageValue == WWZ_ZH_HANT_VALUE {
return .hantChinese
}else {
return .other
}
}
private lazy var languageBundle : Bundle? = {
if let path = Bundle.main.path(forResource: self.currentLanguageValue, ofType: "lproj") {
return Bundle(path: path)
}else {
guard let en_path = Bundle.main.path(forResource: WWZ_EN_VALUE, ofType: "lproj") else {
return nil
}
return Bundle(path: en_path)
}
}()
public func localizedString(key: String) -> String {
return self.localizedString(key: key, inTable: "Localizable")
}
public func localizedString(key: String, inTable: String) -> String {
guard let bundle = self.languageBundle else {
return Bundle.main.localizedString(forKey: key, value: "", table: inTable)
}
return bundle.localizedString(forKey: key, value: "", table: inTable)
}
}
| mit | 511f83224eba125c5e2313860a33e91b | 24.115789 | 131 | 0.563705 | 4.451493 | false | false | false | false |
maximedegreve/Walllpaper | Sources/App/Controllers/ShotController.swift | 1 | 2332 | import Vapor
import HTTP
import FluentMySQL
import Fluent
final class PublicShotController: ResourceRepresentable{
func index(_ request: Request) throws -> ResponseRepresentable {
let shotQuery = try Shot.query()
shotQuery.limit = Limit(count: 8, offset: 0)
return try shotQuery.union(User.self).filter(User.self, "consented", 1).all().makeJSON()
}
func makeResource() -> Resource<Shot> {
return Resource(
index: index
)
}
}
final class ShotController: ResourceRepresentable {
func index(request: Request) throws -> ResponseRepresentable {
guard let categoryString = request.data["category"]?.string else {
throw Abort.custom(status: .badRequest, message: "No category was defined")
}
if categoryString == "liked"{
return try liked(request: request)
}
if categoryString == "latest"{
return try all(request: request)
}
guard let category = try Category.query().filter("name", categoryString).first() else {
throw Abort.custom(status: .badRequest, message: "Category not found")
}
let user = try request.user()
return try category.shots().union(User.self).filter(User.self, "consented", 1).all().makeJSON(user: user)
}
func all(request: Request) throws -> ResponseRepresentable {
let user = try request.user()
return try Shot.query().union(User.self).filter(User.self, "consented", 1).all().makeJSON(user: user)
}
func liked(request: Request) throws -> ResponseRepresentable {
let user = try request.user()
guard let userId = user.id else {
throw Abort.custom(status: .badRequest, message: "Could not get user id")
}
return try Like.query().filter("user_id", userId).all().makeJSON(request: request)
}
func makeResource() -> Resource<Shot> {
return Resource(
index: index
)
}
}
extension Request {
func shot() throws -> Shot {
guard let json = json else { throw Abort.badRequest }
return try Shot(node: json)
}
}
| mit | b9aca3f0172d807943d0c523392cd41e | 26.761905 | 113 | 0.578045 | 4.759184 | false | false | false | false |
bananafish911/SmartReceiptsiOS | SmartReceipts/Modules/Trips/TripsRouter.swift | 1 | 2091 | //
// TripsRouter.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 11/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
class TripsRouter: Router {
private let moduleStoryboard = UIStoryboard(name: "Trips", bundle: nil)
func openSettings() {
let settingsVC = MainStoryboard().instantiateViewController(withIdentifier: "SettingsOverflow")
settingsVC.modalTransitionStyle = .coverVertical
settingsVC.modalPresentationStyle = .formSheet
_view.present(settingsVC, animated: true, completion: nil)
}
func openEdit(trip: WBTrip) {
openEditTrip(trip)
}
func openAddTrip() {
openEditTrip(nil)
}
func openDetails(trip: WBTrip) {
let vc = MainStoryboard().instantiateViewController(withIdentifier: "Receipts")
let receiptsVC = vc as! WBReceiptsViewController
receiptsVC.trip = trip
executeFor(iPhone: {
_view.navigationController?.pushViewController(receiptsVC, animated: true)
}, iPad: {
let nav = UINavigationController(rootViewController: receiptsVC)
nav.isToolbarHidden = false
_view.splitViewController?.show(nav, sender: nil)
})
}
func openNoTrips() {
let vc = moduleStoryboard.instantiateViewController(withIdentifier: "NoTrips")
_view.splitViewController?.show(vc, sender: nil)
}
private func openEditTrip(_ trip: WBTrip?) {
executeFor(iPhone: {
Module.build(AppModules.editTrip).router.show(from: _view,
embedInNavController: true, setupData: trip)
}, iPad: {
Module.build(AppModules.editTrip).router.showIPadForm(from: _view, setupData: trip, needNavigationController: true)
})
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension TripsRouter {
var presenter: TripsPresenter {
return _presenter as! TripsPresenter
}
}
| agpl-3.0 | 80882cff34bd87066d7e192d5faf6e69 | 30.666667 | 127 | 0.637799 | 4.634146 | false | false | false | false |
kotoole1/Paranormal | Paranormal/Paranormal/AppDelegate.swift | 1 | 1436 | import Cocoa
import XCGLogger
let log = XCGLogger.defaultInstance()
@NSApplicationMain
public class AppDelegate: NSObject, NSApplicationDelegate {
public var documentController : DocumentController
public override init() {
documentController = DocumentController()
super.init()
}
func removeLastItemFromEdit(selectorName : String) {
var edit = NSApplication.sharedApplication().mainMenu?.itemWithTitle("Edit")
if let count = edit?.submenu?.numberOfItems {
let lastItem = edit?.submenu?.itemAtIndex(count - 1)
if lastItem?.action == NSSelectorFromString(selectorName) {
edit?.submenu?.removeItemAtIndex(count - 1)
}
}
}
public func applicationDidFinishLaunching(aNotification: NSNotification) {
// At this point, the main menu is automatically loaded
self.removeLastItemFromEdit("orderFrontCharacterPalette:")
self.removeLastItemFromEdit("startDictation:")
documentController.createDocumentFromUrl(nil)
}
public func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
public func applicationShouldOpenUntitledFile(sender: NSApplication) -> Bool {
return true
}
public func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
}
| mit | e2fa21686f05576510ca7e2ae2a4e986 | 32.395349 | 96 | 0.697772 | 5.675889 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/Resources.swift | 1 | 1322 | //
// Resources.swift
// RsyncOSX
//
// Created by Thomas Evensen on 20/12/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length
import CoreVideo
import Foundation
// Enumtype type of resource
enum ResourceType {
case changelog
case documents
case urlPLIST
case urlJSON
case firsttimeuse
}
struct Resources {
// Resource strings
private var changelog: String = "https://rsyncosx.netlify.app/post/changelog/"
private var documents: String = "https://rsyncosx.netlify.app/post/rsyncosxdocs/"
private var urlPlist: String = "https://raw.githubusercontent.com/rsyncOSX/RsyncOSX/master/versionRsyncOSX/versionRsyncOSX.plist"
private var urlJSON: String = "https://raw.githubusercontent.com/rsyncOSX/RsyncUI/master/versionRsyncUI/versionRsyncUI.json"
private var firsttimeuse: String = "https://rsyncosx.netlify.app/post/important/"
// Get the resource.
func getResource(resource: ResourceType) -> String {
switch resource {
case .changelog:
return changelog
case .documents:
return documents
case .urlPLIST:
return urlPlist
case .urlJSON:
return urlJSON
case .firsttimeuse:
return firsttimeuse
}
}
}
| mit | 7d5f4dadae97a7f3b1cc7c18a9d601b4 | 28.355556 | 133 | 0.679788 | 3.931548 | false | false | false | false |
apple/swift | test/SILGen/opaque_result_type.swift | 2 | 4434 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -disable-availability-checking -emit-silgen %s | %FileCheck %s
import resilient_struct
protocol P {}
protocol Q: AnyObject {}
extension String: P {}
struct AddrOnly: P { var field: P }
class C: Q {}
// CHECK-LABEL: sil hidden {{.*}}11valueToAddr1xQr
func valueToAddr(x: String) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*String, [[ARG1:%.*]] : @guaranteed $String):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: store [[VALUE_COPY]] to [init] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}10addrToAddr1xQr
func addrToAddr(x: AddrOnly) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*AddrOnly, [[ARG1:%.*]] : $*AddrOnly):
// CHECK: copy_addr [[ARG1]] to [init] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}13genericAddrToE01xQr
func genericAddrToAddr<T: P>(x: T) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*T, [[ARG1:%.*]] : $*T):
// CHECK: copy_addr [[ARG1]] to [init] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}12valueToValue1xQr
func valueToValue(x: C) -> some Q {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG]]
// CHECK: return [[VALUE_COPY]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}13reabstraction1xQr
func reabstraction(x: @escaping () -> ()) -> some Any {
// CHECK: bb0([[ARG0:%[0-9]+]] :
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sIeg_ytIegr_TR
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[VALUE_COPY]])
// CHECK: [[THUNK_CONV:%.*]] = convert_function [[THUNK]]
// CHECK: store [[THUNK_CONV]] to [init] [[ARG0]]
return x
}
protocol X {
associatedtype A
func foo() -> A
}
extension Int : P {}
extension ResilientInt : P {}
class K : P {}
func useClosure2(_ cl: () -> ()) {}
func useClosure(_ cl: @escaping () -> ()) {
cl()
}
struct S : X {
func foo() -> some P {
return returnTrivial()
}
func returnTrivial() -> some P {
return 1
}
func returnClass() -> some P {
return K()
}
func returnResilient() -> some P {
return ResilientInt(i: 1)
}
func testCapture() {
var someP = returnTrivial()
var someK = returnClass()
var someR = returnResilient()
useClosure {
someP = self.returnTrivial()
someK = self.returnClass()
someR = self.returnResilient()
}
print(someP)
print(someK)
print(someR)
}
func testCapture2() {
var someP = returnTrivial()
var someK = returnClass()
var someR = returnResilient()
useClosure2 {
someP = self.returnTrivial()
someK = self.returnClass()
someR = self.returnResilient()
}
print(someP)
print(someK)
print(someR)
}
func testCapture3() {
let someP = returnTrivial()
let someK = returnClass()
let someR = returnResilient()
useClosure {
print(someP)
print(someK)
print(someR)
}
}
func testCapture4() {
let someP = returnTrivial()
let someK = returnClass()
let someR = returnResilient()
useClosure {
print(someP)
print(someK)
print(someR)
}
}
}
extension Optional : P { }
struct S2 : X {
func foo() -> some P {
let x : Optional = 1
return x
}
func returnFunctionType() -> () -> A {
return foo
}
}
class Base {}
class Sub1 : Base {}
class Sub2 : Base {}
public class D {
var cond = true
// CHECK-LABEL: sil private [lazy_getter] [noinline] [ossa] @$s18opaque_result_type1DC1c33_C2C55A4BAF30C3244D4A165D48A91142LLQrvg
// CHECK: bb3([[RET:%[0-9]+]] : @owned $Base):
// CHECH: return [[RET]]
// CHECK: } // end sil function '$s18opaque_result_type1DC1c33_C2C55A4BAF30C3244D4A165D48A91142LLQrvg'
private lazy var c: some Base = {
let d = cond ? Sub1() : Sub2()
return d
}()
}
// CHECK-LABEL: sil [ossa] @$s18opaque_result_type10tupleAsAnyQryF : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <@_opaqueReturnTypeOf("$s18opaque_result_type10tupleAsAnyQryF", 0) __> {
public func tupleAsAny() -> some Any {
// CHECK: bb0(%0 : $*()):
// CHECK-NEXT: %1 = tuple ()
// CHECK-NEXT: return %1 : $()
return ()
}
| apache-2.0 | 41acb69abbcd72c992af9d49d8ccee9f | 24.181818 | 202 | 0.599955 | 3.202312 | false | false | false | false |
hgl888/firefox-ios | Client/Frontend/Browser/BrowserToolbar.swift | 7 | 11132 | /* 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 UIKit
import SnapKit
@objc
protocol BrowserToolbarProtocol {
weak var browserToolbarDelegate: BrowserToolbarDelegate? { get set }
var shareButton: UIButton { get }
var bookmarkButton: UIButton { get }
var forwardButton: UIButton { get }
var backButton: UIButton { get }
var stopReloadButton: UIButton { get }
var actionButtons: [UIButton] { get }
func updateBackStatus(canGoBack: Bool)
func updateForwardStatus(canGoForward: Bool)
func updateBookmarkStatus(isBookmarked: Bool)
func updateReloadStatus(isLoading: Bool)
func updatePageStatus(isWebPage isWebPage: Bool)
}
@objc
protocol BrowserToolbarDelegate: class {
func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton)
func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton)
}
@objc
public class BrowserToolbarHelper: NSObject {
let toolbar: BrowserToolbarProtocol
let ImageReload = UIImage(named: "reload")
let ImageReloadPressed = UIImage(named: "reloadPressed")
let ImageStop = UIImage(named: "stop")
let ImageStopPressed = UIImage(named: "stopPressed")
var buttonTintColor = UIColor.darkGrayColor() {
didSet {
setTintColor(buttonTintColor, forButtons: toolbar.actionButtons)
}
}
var loading: Bool = false {
didSet {
if loading {
toolbar.stopReloadButton.setImage(ImageStop, forState: .Normal)
toolbar.stopReloadButton.setImage(ImageStopPressed, forState: .Highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the browser toolbar Stop button")
} else {
toolbar.stopReloadButton.setImage(ImageReload, forState: .Normal)
toolbar.stopReloadButton.setImage(ImageReloadPressed, forState: .Highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button")
}
}
}
private func setTintColor(color: UIColor, forButtons buttons: [UIButton]) {
buttons.forEach { $0.tintColor = color }
}
init(toolbar: BrowserToolbarProtocol) {
self.toolbar = toolbar
super.init()
toolbar.backButton.setImage(UIImage(named: "back"), forState: .Normal)
toolbar.backButton.setImage(UIImage(named: "backPressed"), forState: .Highlighted)
toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility Label for the browser toolbar Back button")
//toolbar.backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
let longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack:")
toolbar.backButton.addGestureRecognizer(longPressGestureBackButton)
toolbar.backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside)
toolbar.forwardButton.setImage(UIImage(named: "forward"), forState: .Normal)
toolbar.forwardButton.setImage(UIImage(named: "forwardPressed"), forState: .Highlighted)
toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the browser toolbar Forward button")
//toolbar.forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
let longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward:")
toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton)
toolbar.forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside)
toolbar.stopReloadButton.setImage(UIImage(named: "reload"), forState: .Normal)
toolbar.stopReloadButton.setImage(UIImage(named: "reloadPressed"), forState: .Highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button")
toolbar.stopReloadButton.addTarget(self, action: "SELdidClickStopReload", forControlEvents: UIControlEvents.TouchUpInside)
toolbar.shareButton.setImage(UIImage(named: "send"), forState: .Normal)
toolbar.shareButton.setImage(UIImage(named: "sendPressed"), forState: .Highlighted)
toolbar.shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Accessibility Label for the browser toolbar Share button")
toolbar.shareButton.addTarget(self, action: "SELdidClickShare", forControlEvents: UIControlEvents.TouchUpInside)
toolbar.bookmarkButton.contentMode = UIViewContentMode.Center
toolbar.bookmarkButton.setImage(UIImage(named: "bookmark"), forState: .Normal)
toolbar.bookmarkButton.setImage(UIImage(named: "bookmarked"), forState: UIControlState.Selected)
toolbar.bookmarkButton.accessibilityLabel = NSLocalizedString("Bookmark", comment: "Accessibility Label for the browser toolbar Bookmark button")
let longPressGestureBookmarkButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBookmark:")
toolbar.bookmarkButton.addGestureRecognizer(longPressGestureBookmarkButton)
toolbar.bookmarkButton.addTarget(self, action: "SELdidClickBookmark", forControlEvents: UIControlEvents.TouchUpInside)
setTintColor(buttonTintColor, forButtons: toolbar.actionButtons)
}
func SELdidClickBack() {
toolbar.browserToolbarDelegate?.browserToolbarDidPressBack(toolbar, button: toolbar.backButton)
}
func SELdidLongPressBack(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBack(toolbar, button: toolbar.backButton)
}
}
func SELdidClickShare() {
toolbar.browserToolbarDelegate?.browserToolbarDidPressShare(toolbar, button: toolbar.shareButton)
}
func SELdidClickForward() {
toolbar.browserToolbarDelegate?.browserToolbarDidPressForward(toolbar, button: toolbar.forwardButton)
}
func SELdidLongPressForward(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
toolbar.browserToolbarDelegate?.browserToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton)
}
}
func SELdidClickBookmark() {
toolbar.browserToolbarDelegate?.browserToolbarDidPressBookmark(toolbar, button: toolbar.bookmarkButton)
}
func SELdidLongPressBookmark(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBookmark(toolbar, button: toolbar.bookmarkButton)
}
}
func SELdidClickStopReload() {
if loading {
toolbar.browserToolbarDelegate?.browserToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton)
} else {
toolbar.browserToolbarDelegate?.browserToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton)
}
}
func updateReloadStatus(isLoading: Bool) {
loading = isLoading
}
}
class BrowserToolbar: Toolbar, BrowserToolbarProtocol {
weak var browserToolbarDelegate: BrowserToolbarDelegate?
let shareButton: UIButton
let bookmarkButton: UIButton
let forwardButton: UIButton
let backButton: UIButton
let stopReloadButton: UIButton
let actionButtons: [UIButton]
var helper: BrowserToolbarHelper?
// This has to be here since init() calls it
private override init(frame: CGRect) {
// And these have to be initialized in here or the compiler will get angry
backButton = UIButton()
forwardButton = UIButton()
stopReloadButton = UIButton()
shareButton = UIButton()
bookmarkButton = UIButton()
actionButtons = [backButton, forwardButton, stopReloadButton, shareButton, bookmarkButton]
super.init(frame: frame)
self.helper = BrowserToolbarHelper(toolbar: self)
addButtons(backButton, forwardButton, stopReloadButton, shareButton, bookmarkButton)
accessibilityNavigationStyle = .Combined
accessibilityLabel = NSLocalizedString("Navigation Toolbar", comment: "Accessibility label for the navigation toolbar displayed at the bottom of the screen.")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
helper?.updateReloadStatus(isLoading)
}
func updatePageStatus(isWebPage isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override func drawRect(rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0))
}
}
private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) {
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().colorWithAlphaComponent(0.05).CGColor)
CGContextSetLineWidth(context, 2)
CGContextMoveToPoint(context, start.x, start.y)
CGContextAddLineToPoint(context, end.x, end.y)
CGContextStrokePath(context)
}
}
// MARK: UIAppearance
extension BrowserToolbar {
dynamic var actionButtonTintColor: UIColor? {
get { return helper?.buttonTintColor }
set {
guard let value = newValue else { return }
helper?.buttonTintColor = value
}
}
}
| mpl-2.0 | e979a37ba686f2b5703810efff7ccea6 | 44.8107 | 166 | 0.735088 | 5.694118 | false | false | false | false |
1170197998/Swift-DEMO | FMDB_DEMO/FMDB_DEMO/TableViewController.swift | 1 | 3052 | //
// ViewController.swift
// FMDB_DEMO
//
// Created by ShaoFeng on 2017/4/3.
// Copyright © 2017年 ShaoFeng. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var dataArray = Array<ListModel>()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
DBManager.shareManager.openDB()
}
private func makeData() {
for i in 0..<10 {
let model = ListModel()
model.personId = i
model.name = "名称\(i)"
model.isTop = false
ListDAO.shareDAO.insertData(model: model)
}
dataArray = ListDAO.shareDAO.getDataList()
self.tableView.reloadData()
}
@IBAction func creatTable(_ sender: Any) {
ListDAO.shareDAO.creatTable()
makeData()
}
@IBAction func dropTable(_ sender: Any) {
ListDAO.shareDAO.dropTable()
dataArray = ListDAO.shareDAO.getDataList()
tableView.reloadData()
}
}
extension TableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = dataArray[indexPath.row]
var cell = tableView.dequeueReusableCell(withIdentifier: "ID");
if (nil == cell) {
cell = UITableViewCell(style: .default, reuseIdentifier: "ID")
}
cell?.textLabel?.text = "\(model.name) + isTop: \(model.isTop)"
if model.isTop {
cell?.backgroundColor = UIColor.lightGray
} else {
cell?.backgroundColor = UIColor.white
}
return cell!
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = DetailViewController()
navigationController?.pushViewController(vc, animated: true)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let model = dataArray[indexPath.row]
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
guard ListDAO.shareDAO.deleteDataOfDataList(personId: model.personId) else {
return
}
self.dataArray = ListDAO.shareDAO.getDataList()
self.tableView.reloadData()
print("Delete")
}
let topAction = UITableViewRowAction(style: .normal, title: model.isTop ? "Cancel Top" : "Top") { (action, indexPath) in
guard ListDAO.shareDAO.setTopWithPersonId(personId: model.personId, isTop: !model.isTop) else {
return
}
self.dataArray = ListDAO.shareDAO.getDataList()
self.tableView.reloadData()
print("Top")
}
return [deleteAction,topAction]
}
}
| apache-2.0 | 308a7484b8f3019841c23b3fae2e74ee | 32.833333 | 128 | 0.61445 | 4.765258 | false | false | false | false |
abelsanchezali/ViewBuilder | Source/Model/UIKit/CGGeometry+Models.swift | 1 | 3146 | //
// CGGeometryModel.swift
// ViewBuilder
//
// Created by Abel Sanchez on 6/15/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import CoreGraphics
import Foundation
// MARK: - CGRect
extension CGRect: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSValue(cgRect: self)
}
}
open class Rect: Object, TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text, value.count > 0 else {
return NSValue(cgRect: CGRect.zero)
}
guard let array = service.parseValidDoubleArray(from: value), array.count == 4 else {
return nil
}
return CGRect(x: CGFloat(array[0]), y: CGFloat(array[1]), width: CGFloat(array[2]), height: CGFloat(array[3]))
}
}
extension CGRect: TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
return Rect.deserialize(text: text, service: service)
}
}
// MARK: - CGPoint
extension CGPoint: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSValue(cgPoint: self)
}
}
open class Point: Object, TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text, value.count > 0 else {
return NSValue(cgRect: CGRect.zero)
}
guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else {
return nil
}
return CGPoint(x: CGFloat(array[0]), y: CGFloat(array[1]))
}
}
extension CGPoint: TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
return Point.deserialize(text: text, service: service)
}
}
// MARK: - CGSize
extension CGSize: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSValue(cgSize: self)
}
}
open class Size: Object, TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text, value.count > 0 else {
return NSValue(cgRect: CGRect.zero)
}
guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else {
return nil
}
return CGSize(width: CGFloat(array[0]), height: CGFloat(array[1]))
}
}
// MARK: - CGVector
extension CGVector: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSValue(cgVector: self)
}
}
open class Vector: Object, TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text, value.count > 0 else {
return NSValue(cgRect: CGRect.zero)
}
guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else {
return nil
}
return CGVector(dx: CGFloat(array[0]), dy: CGFloat(array[1]))
}
}
| mit | 8b81ce07ebf7b7123c59e2acc47da0b0 | 29.240385 | 118 | 0.651828 | 4.221477 | false | false | false | false |
brentdax/swift | test/IDE/print_synthesized_extensions.swift | 3 | 12709 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_synthesized_extensions.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_synthesized_extensions.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -annotate-print -synthesize-extension -print-interface -no-empty-line-between-members -module-to-print=print_synthesized_extensions -I %t -source-filename=%s > %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK3 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK4 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK5 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK6 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK7 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK8 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK9 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK10 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK11 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK12 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK13 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK14 < %t.syn.txt
public protocol P1 {
associatedtype T1
associatedtype T2
func f1(t : T1) -> T1
func f2(t : T2) -> T2
}
public extension P1 where T1 == Int {
func p1IntFunc(i : Int) -> Int {return 0}
}
public extension P1 where T1 : P3 {
func p3Func(i : Int) -> Int {return 0}
}
public protocol P2 {
associatedtype P2T1
}
public extension P2 where P2T1 : P2{
public func p2member() {}
}
public protocol P3 {}
public extension P1 where T1 : P2 {
public func ef1(t : T1) {}
public func ef2(t : T2) {}
}
public extension P1 where T1 == P2, T2 : P3 {
public func ef3(t : T1) {}
public func ef4(t : T1) {}
}
public extension P1 where T2 : P3 {
public func ef5(t : T2) {}
}
public struct S2 {}
public struct S1<T> : P1, P2 {
public typealias T1 = T
public typealias T2 = S2
public typealias P2T1 = T
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S3<T> : P1 {
public typealias T1 = (T, T)
public typealias T2 = (T, T)
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S4<T> : P1 {
public typealias T1 = Int
public typealias T2 = Int
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S5 : P3 {}
public struct S6<T> : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public extension S6 {
public func f3() {}
}
public struct S7 {
public struct S8 : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
}
public extension P1 where T1 == S9<Int> {
public func S9IntFunc() {}
}
public struct S9<T> : P3 {}
public struct S10 : P1 {
public typealias T1 = S9<Int>
public typealias T2 = S9<Int>
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public protocol P4 {}
/// Extension on P4Func1
public extension P4 {
func P4Func1() {}
}
/// Extension on P4Func2
public extension P4 {
func P4Func2() {}
}
public struct S11 : P4 {}
public extension S6 {
public func fromActualExtension() {}
}
public protocol P5 {
associatedtype T1
/// This is picked
func foo1()
}
public extension P5 {
/// This is not picked
public func foo1() {}
}
public extension P5 where T1 == Int {
/// This is picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo3() {}
}
public extension P5 where T1 : Comparable{
/// This is picked
public func foo3() {}
}
public extension P5 where T1 : Comparable {
/// This is picked
public func foo4() {}
}
public extension P5 where T1 : AnyObject {
/// This should not crash
public func foo5() {}
}
public extension P5 {
/// This is not picked
public func foo4() {}
}
public struct S12 : P5{
public typealias T1 = Int
public func foo1() {}
}
public protocol P6 {
func foo1()
func foo2()
}
public extension P6 {
public func foo1() {}
}
public protocol P7 {
associatedtype T1
func f1(t: T1)
}
public extension P7 {
public func nomergeFunc(t: T1) -> T1 { return t }
public func f1(t: T1) -> T1 { return t }
}
public struct S13 {}
extension S13 : P5 {
public typealias T1 = Int
public func foo1() {}
}
// CHECK1: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P2</ref> {
// CHECK1-NEXT: <decl:Func>public func <loc>p2member()</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef1(<decl:Param>t: T</decl>)</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef2(<decl:Param>t: <ref:Struct>S2</ref></decl>)</loc></decl>
// CHECK1-NEXT: }</synthesized>
// CHECK2: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P3</ref> {
// CHECK2-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK2-NEXT: }</synthesized>
// CHECK3: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>Int</ref> {
// CHECK3-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK3-NEXT: }</synthesized>
// CHECK4: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>S9</ref><<ref:Struct>Int</ref>> {
// CHECK4-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK4-NEXT: }</synthesized>
// CHECK5: <decl:Struct>public struct <loc>S10</loc> : <ref:Protocol>P1</ref> {
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>)</loc></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK5-NEXT: }</synthesized>
// CHECK6: <synthesized>/// Extension on P4Func1
// CHECK6-NEXT: extension <ref:Struct>S11</ref> {
// CHECK6-NEXT: <decl:Func>public func <loc>P4Func1()</loc></decl>
// CHECK6-NEXT: }</synthesized>
// CHECK7: <synthesized>/// Extension on P4Func2
// CHECK7-NEXT: extension <ref:Struct>S11</ref> {
// CHECK7-NEXT: <decl:Func>public func <loc>P4Func2()</loc></decl>
// CHECK7-NEXT: }</synthesized>
// CHECK8: <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T1</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref><T>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: }</synthesized>
// CHECK9: <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T1</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref><T>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>f3()</loc></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>fromActualExtension()</loc></decl></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK9-NEXT: }</synthesized>
// CHECK10: <synthesized>extension <ref:Struct>S7</ref>.<ref:Struct>S8</ref> {
// CHECK10-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK10-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK10-NEXT: }</synthesized>
// CHECK11: <decl:Struct>public struct <loc>S12</loc> : <ref:Protocol>P5</ref> {
// CHECK11-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo1()</loc></decl></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo2()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo3()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo4()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This should not crash
// CHECK11-NEXT: public func <loc>foo5()</loc></decl>
// CHECK11-NEXT: }</synthesized>
// CHECK12: <decl:Protocol>public protocol <loc>P6</loc> {
// CHECK12-NEXT: <decl:Func(HasDefault)>func <loc>foo1()</loc></decl>
// CHECK12-NEXT: <decl:Func>func <loc>foo2()</loc></decl>
// CHECK12-NEXT: }</decl>
// CHECK13: <decl:Protocol>public protocol <loc>P7</loc> {
// CHECK13-NEXT: <decl:AssociatedType>associatedtype <loc>T1</loc></decl>
// CHECK13-NEXT: <decl:Func(HasDefault)>func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc></decl>
// CHECK13-NEXT: }</decl>
// CHECK13: <decl:Extension>extension <loc><ref:Protocol>P7</ref></loc> {
// CHECK13-NEXT: <decl:Func>public func <loc>nomergeFunc(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: }</decl>
// CHECK14: <decl:Struct>public struct <loc>S13</loc> {</decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo2()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo3()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo4()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This should not crash
// CHECK14-NEXT: public func <loc>foo5()</loc></decl>
// CHECK14-NEXT: }</synthesized>
| apache-2.0 | e8cfa17ad5c78d5954c9b97fc35e82a4 | 36.269795 | 285 | 0.653867 | 2.801808 | false | false | false | false |
ar9jun/Time-for-Cookies | Time for Cookies/Cookies/NSDate+Cookies.swift | 1 | 3366 | //
// NSDate+Cookies.swift
// Time for Cookies
//
// Created by Arjun Srivastava on 6/11/15.
// Copyright (c) 2015 Arjun Srivastava. All rights reserved.
//
import Foundation
import UIKit
//MARK: - Ask User for Permission to Send Notifications
public func getPermissionForNotifications(){
//Register notifications
var localNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
var localNotificationSettings = UIUserNotificationSettings(forTypes: localNotificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(localNotificationSettings)
}
//MARK: -
public extension NSDate{
//MARK: - Local Notifications
//MARK: -Repeat Yearly
func createYearlyLocalNotification(alertBody: String, alertAction: String) -> Bool{
//Create a notification, repeated every year
return createLocalNotification(alertBody: alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitYear)
}
//MARK: -Repeat Monthly
func createMonthlyLocalNotification(alertBody: String, alertAction: String) -> Bool{
//Create a notification, repeated every month
return createLocalNotification(alertBody: alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitMonth)
}
//MARK: -Repeat Weekly
func createWeeklyLocalNotification(alertBody: String, alertAction: String) -> Bool{
//Create a notification, repeated every week
return createLocalNotification(alertBody: alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitWeekday)
}
//MARK: -Repeat Daily
func createDailyLocalNotifcation(alertBody: String, alertAction: String) -> Bool{
//Create a notification, repeated every day
return createLocalNotification(alertBody: alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitDay)
}
//MARK: -One Time
func createLocalNotifcation(alertBody: String, alertAction: String) -> Bool{
//Create a single local notification, called only once
return createLocalNotification(alertBody: alertBody, alertAction: alertAction)
}
//MARK: - Private
//MARK: -Create Local Notification
private func createLocalNotification(#alertBody: String, alertAction: String, repeatInterval: NSCalendarUnit? = nil) -> Bool{
//Check that user allowed notifications
let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
let required:UIUserNotificationType = UIUserNotificationType.Alert
if (currentSettings.types & required) == nil {
println("User did not allow notifications")
return false
}
//Create notification
var localNotification = UILocalNotification()
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.alertBody = alertBody
localNotification.alertAction = alertAction
localNotification.fireDate = self
if let interval = repeatInterval{
localNotification.repeatInterval = interval
}
//Send notification
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
println("Created notification!")
return true
}
} | mit | 1d2460ce0e1831f32d5d9de5d186dd4e | 38.611765 | 129 | 0.714498 | 5.783505 | false | false | false | false |
Foild/SwiftForms | SwiftForms/cells/FormTextFieldCell.swift | 4 | 5869 | //
// FormTextFieldCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormTextFieldCell: FormBaseCell {
/// MARK: Cell views
public let titleLabel = UILabel()
public let textField = UITextField()
/// MARK: Properties
private var customConstraints: [AnyObject]!
/// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
titleLabel.translatesAutoresizingMaskIntoConstraints = false
textField.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
contentView.addSubview(titleLabel)
contentView.addSubview(textField)
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
titleLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
textField.addTarget(self, action: "editingChanged:", forControlEvents: .EditingChanged)
}
public override func update() {
super.update()
if let showsInputToolbar = rowDescriptor.configuration[FormRowDescriptor.Configuration.ShowsInputToolbar] as? Bool {
if showsInputToolbar && textField.inputAccessoryView == nil {
textField.inputAccessoryView = inputAccesoryView()
}
}
titleLabel.text = rowDescriptor.title
textField.text = rowDescriptor.value as? String
textField.placeholder = rowDescriptor.configuration[FormRowDescriptor.Configuration.Placeholder] as? String
textField.secureTextEntry = false
textField.clearButtonMode = .WhileEditing
switch rowDescriptor.rowType {
case .Text:
textField.autocorrectionType = .Default
textField.autocapitalizationType = .Sentences
textField.keyboardType = .Default
case .Number:
textField.keyboardType = .NumberPad
case .NumbersAndPunctuation:
textField.keyboardType = .NumbersAndPunctuation
case .Decimal:
textField.keyboardType = .DecimalPad
case .Name:
textField.autocorrectionType = .No
textField.autocapitalizationType = .Words
textField.keyboardType = .Default
case .Phone:
textField.keyboardType = .PhonePad
case .NamePhone:
textField.autocorrectionType = .No
textField.autocapitalizationType = .Words
textField.keyboardType = .NamePhonePad
case .URL:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .URL
case .Twitter:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .Twitter
case .Email:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .EmailAddress
case .ASCIICapable:
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .ASCIICapable
case .Password:
textField.secureTextEntry = true
textField.clearsOnBeginEditing = false
default:
break
}
}
public override func constraintsViews() -> [String : UIView] {
var views = ["titleLabel" : titleLabel, "textField" : textField]
if self.imageView!.image != nil {
views["imageView"] = imageView
}
return views
}
public override func defaultVisualConstraints() -> [String] {
if self.imageView!.image != nil {
if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 {
return ["H:[imageView]-[titleLabel]-[textField]-16-|"]
}
else {
return ["H:[imageView]-[textField]-16-|"]
}
}
else {
if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 {
return ["H:|-16-[titleLabel]-[textField]-16-|"]
}
else {
return ["H:|-16-[textField]-16-|"]
}
}
}
public override func firstResponderElement() -> UIResponder? {
return textField
}
public override class func formRowCanBecomeFirstResponder() -> Bool {
return true
}
/// MARK: Actions
internal func editingChanged(sender: UITextField) {
let trimmedText = sender.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
rowDescriptor.value = trimmedText.characters.count > 0 ? trimmedText : nil
}
}
| mit | 3423a22990907244454f2d3929db0807 | 37.333333 | 185 | 0.631884 | 5.688652 | false | false | false | false |
OscarSwanros/swift | test/Parse/operator_decl.swift | 28 | 3322 | // RUN: %target-typecheck-verify-swift
prefix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{20-23=}}
postfix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{21-24=}}
infix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{19-22=}}
infix operator +++* { // expected-warning {{operator should no longer be declared with body; use a precedence group instead}} {{none}}
associativity right
}
infix operator +++*+ : A { } // expected-warning {{operator should no longer be declared with body}} {{25-29=}}
prefix operator +++** : A { }
// expected-error@-1 {{only infix operators may declare a precedence}} {{23-27=}}
// expected-warning@-2 {{operator should no longer be declared with body}} {{26-30=}}
prefix operator ++*++ : A
// expected-error@-1 {{only infix operators may declare a precedence}} {{23-26=}}
postfix operator ++*+* : A { }
// expected-error@-1 {{only infix operators may declare a precedence}} {{24-28=}}
// expected-warning@-2 {{operator should no longer be declared with body}} {{27-31=}}
postfix operator ++**+ : A
// expected-error@-1 {{only infix operators may declare a precedence}} {{24-27=}}
operator ++*** : A
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
operator +*+++ { }
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
// expected-warning@-2 {{operator should no longer be declared with body}} {{15-19=}}
operator +*++* : A { }
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
// expected-warning@-2 {{operator should no longer be declared with body}} {{19-23=}}
prefix operator // expected-error {{expected operator name in operator declaration}}
;
prefix operator %%+
prefix operator ??
postfix operator ?? // expected-error {{expected operator name in operator declaration}}
prefix operator !!
postfix operator !! // expected-error {{expected operator name in operator declaration}}
infix operator +++=
infix operator *** : A
infix operator --- : ;
precedencegroup { // expected-error {{expected identifier after 'precedencegroup'}}
associativity: right
}
precedencegroup A {
associativity right // expected-error {{expected colon after attribute name in precedence group}}
}
precedencegroup B {
precedence 123 // expected-error {{'precedence' is not a valid precedence group attribute}}
}
precedencegroup C {
associativity: sinister // expected-error {{expected 'none', 'left', or 'right' after 'associativity'}}
}
precedencegroup D {
assignment: no // expected-error {{expected 'true' or 'false' after 'assignment'}}
}
precedencegroup E {
higherThan:
} // expected-error {{expected name of related precedence group after 'higherThan'}}
precedencegroup F {
higherThan: A, B, C
}
precedencegroup BangBangBang {
associativity: none
associativity: left // expected-error{{'associativity' attribute for precedence group declared multiple times}}
}
precedencegroup CaretCaretCaret {
assignment: true
assignment: false // expected-error{{'assignment' attribute for precedence group declared multiple times}}
}
class Foo {
infix operator ||| // expected-error{{'operator' may only be declared at file scope}}
}
| apache-2.0 | ab26b6ac84b3c944e2bdb9259035bb21 | 37.183908 | 134 | 0.704696 | 4.221093 | false | false | false | false |
amnuaym/TiAppBuilder | Day6/MyShoppingListDB/MyShoppingListDB/ShoppingListViewController.swift | 1 | 10041 | //
// ShoppingListViewController.swift
// MyShoppingListDB
//
// Created by DrKeng on 9/16/2560 BE.
// Copyright © 2560 ANT. All rights reserved.
//
import UIKit
import CoreData
class ShoppingListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//ตัวแปรสำหรับเก็บข้อมูล List ของ ShoppingItems
var myShoppingItemsList : [AnyObject]? = []
//Add Variables for Item Category store
var myItemCategoriesList : [AnyObject]? = []
@IBOutlet weak var mySegmentedControl: UISegmentedControl!
@IBOutlet weak var myTableView: UITableView!
//MARK: Customized SegmentedControl Methods
func customizedSegmentedControlTab(){
//Delete All Segments
mySegmentedControl.removeAllSegments()
//Add first segment and some more
mySegmentedControl.insertSegment(withTitle: "All", at: 0, animated: false)
for myIndex in 0..<myItemCategoriesList!.count{
let myItemCategory = myItemCategoriesList![myIndex]
let myItemName = myItemCategory.value(forKey: "CategoryName") as! String
mySegmentedControl.insertSegment(withTitle: myItemName, at: myIndex + 1, animated: false)
}
}
func displayShoppingItemsByItemCategory (categoryNumber : Int){
// Create AppDelegate Object to enable PersistentContainer(Core Data) Access
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
let myContext = myAppDelegate.persistentContainer.viewContext
let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem")
if categoryNumber != 0 {
let myItemCategory = myItemCategoriesList![categoryNumber - 1] as! NSManagedObject
//Specifiy Data Query
let myPredicate = NSPredicate(format: "itemCategory = %@", myItemCategory)
myFetchRequest.predicate = myPredicate
}
do{
myShoppingItemsList = try myContext.fetch(myFetchRequest)
}catch let error as NSError{
print(error.description)
}
self.myTableView.reloadData()
}
@IBAction func selectSegmentMethod() {
let mySelection = mySegmentedControl.selectedSegmentIndex
self.displayShoppingItemsByItemCategory(categoryNumber: mySelection)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "My Shopping List"
myTableView.delegate = self
myTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
//สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
let myContext = myAppDelegate.persistentContainer.viewContext
let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem")
//Add Fetch data by Category
let myCategodyFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCategory")
do{
myShoppingItemsList = try myContext.fetch(myFetchRequest)
//Read Iteam Category from Database
myItemCategoriesList = try myContext.fetch(myCategodyFetchRequest)
}catch let error as NSError{
print(error.description)
}
self.myTableView.reloadData()
self.customizedSegmentedControlTab()
mySegmentedControl.selectedSegmentIndex = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myShoppingItemsList!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
let myShoppingItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject
let myItemName = myShoppingItem.value(forKey: "itemName") as! String
let myItemNumber = myShoppingItem.value(forKey: "itemNumber") as! Int
let myItemPrice = myShoppingItem.value(forKey: "itemPrice") as! Float
let myItemStatus = myShoppingItem.value(forKey: "itemStatus") as! Int
//เช็ค Status เพื่อเปลี่ยนสีของ Font
if myItemStatus == 0 {
cell.textLabel?.textColor = UIColor.orange
cell.detailTextLabel?.textColor = UIColor.orange
}
else{
cell.textLabel?.textColor = UIColor.black
cell.detailTextLabel?.textColor = UIColor.black
}
cell.textLabel?.text = myItemName
cell.detailTextLabel?.text = "จำนวน \(myItemNumber) | ราคาต่อหน่วย \(myItemPrice) บาท"
return cell
}
//สร้างปุ่ม (Action) ในแต่ละ Row และกำหนดฟังก์ชันการทำงาน
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .default, title: "Delete") { (action:UITableViewRowAction, indexPath:IndexPath) in
print("delete at:\(indexPath)") //Log ดูที่ Console
self.deleteRowFromTableView(tableView, indexPath: indexPath)
}
delete.backgroundColor = UIColor.red
let done = UITableViewRowAction(style: .default, title: "Done") { (action:UITableViewRowAction, indexPath:IndexPath) in
print("done at:\(indexPath)")
self.updateItemInTableView(tableView, indexPath: indexPath)
}
done.backgroundColor = UIColor.orange
// let button1 = UITableViewRowAction(style: .default, title: "button1") { (action:UITableViewRowAction, indexPath:IndexPath) in
// }
//
// let button2 = UITableViewRowAction(style: .default, title: "button2") { (action:UITableViewRowAction, indexPath:IndexPath) in
// }
// let button3 = UITableViewRowAction(style: .default, title: "button3") { (action:UITableViewRowAction, indexPath:IndexPath) in
// }
//
// let button4 = UITableViewRowAction(style: .default, title: "button4") { (action:UITableViewRowAction, indexPath:IndexPath) in
// }
// return [delete, done, button1, button2, button3, button4]
return [delete, done]
}
//ฟังก์ชันที่ถูกเรียกเมื่อกดปุ่ม Delete
func deleteRowFromTableView (_ tableView: UITableView, indexPath: IndexPath){
//สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
let myContext = myAppDelegate.persistentContainer.viewContext
//ลบข้อมูลออกจาก NSManagedObject
myContext.delete(myShoppingItemsList![indexPath.row] as! NSManagedObject)
//ลบข้อมูลออกจาก Datasource Array
myShoppingItemsList!.remove(at: indexPath.row)
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
//บันทึกการลบข้อมูล
do{
try myContext.save()
print("ลบข้อมูลแล้ว!")
}catch let error as NSError{
print(error.description + " : ไม่สามารถบันทึกการลบข้อมูลได้")
}
}
func updateItemInTableView(_ tableView: UITableView, indexPath: IndexPath){
let selectedItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject
//สร้าง Object ของ AppDelegate เพื่อเรียกใช้ persistentContainer
let myAppDelegate = UIApplication.shared.delegate as! AppDelegate
let myContext = myAppDelegate.persistentContainer.viewContext
selectedItem.setValue(0, forKey: "itemStatus")
//บันทึกลงฐานข้อมูล
do{
try myContext.save()
print("บันทึกข้อมูลแล้ว!")
}catch let error as NSError{
print(error.description + " : ไม่สามารถบันทึกข้อมูลได้")
}
//Refresh ข้อมูลใน TableView
let myFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShoppingItem")
do{
myShoppingItemsList = try myContext.fetch(myFetchRequest)
}catch let error as NSError{
print(error.description)
}
tableView.reloadData()
}
// 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 == "UpdateSegue"{
let indexPath = self.myTableView.indexPathForSelectedRow!
let selectedItem : NSManagedObject = myShoppingItemsList![indexPath.row] as! NSManagedObject
let myAddItemViewController = segue.destination as! AddItemViewController
myAddItemViewController.myShoppingItem = selectedItem
}
}
}
| gpl-3.0 | f7cadc4019225a1e2d634b154401c275 | 37.713693 | 135 | 0.648017 | 4.681385 | false | false | false | false |
mauryat/firefox-ios | XCUITests/PrivateBrowsingTest.swift | 1 | 7043 | /* 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 url1 = "www.mozilla.org"
let url2 = "www.facebook.com"
let url1Label = "Internet for people, not profit — Mozilla"
let url2Label = "Facebook - Log In or Sign Up"
class PrivateBrowsingTest: BaseTestCase {
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
super.tearDown()
}
func testPrivateTabDoesNotTrackHistory() {
navigator.openURL(urlString: url1)
navigator.goto(BrowserTabMenu)
// Go to History screen
waitforExistence(app.toolbars.buttons["HistoryMenuToolbarItem"])
app.toolbars.buttons["HistoryMenuToolbarItem"].tap()
navigator.nowAt(NewTabScreen)
waitforExistence(app.tables["History List"])
XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists)
// History without counting Recently Closed and Synced devices
let history = app.tables["History List"].cells.count - 2
XCTAssertEqual(history, 1, "History entries in regular browsing do not match")
// Go to Private browsing to open a website and check if it appears on History
navigator.goto(NewPrivateTabScreen)
navigator.goto(PrivateTabTray)
navigator.openURL(urlString: url2)
navigator.nowAt(PrivateBrowserTab)
waitForValueContains(app.textFields["url"], value: "facebook")
navigator.goto(BrowserTabMenu)
waitforExistence(app.toolbars.buttons["HistoryMenuToolbarItem"])
app.toolbars.buttons["HistoryMenuToolbarItem"].tap()
waitforExistence(app.tables["History List"])
XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists)
XCTAssertFalse(app.tables["History List"].staticTexts[url2Label].exists)
// Open one tab in private browsing and check the total number of tabs
let privateHistory = app.tables["History List"].cells.count - 2
XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match")
}
func testTabCountShowsOnlyNormalOrPrivateTabCount() {
// Open two tabs in normal browsing and check the number of tabs open
navigator.openNewURL(urlString: url1)
navigator.goto(TabTray)
navigator.goto(NewTabScreen)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[url1Label])
let numTabs = app.collectionViews.cells.count
XCTAssertEqual(numTabs, 2, "The number of regular tabs is not correct")
// Open one tab in private browsing and check the total number of tabs
navigator.goto(NewPrivateTabScreen)
navigator.openURL(urlString: url2)
navigator.nowAt(PrivateBrowserTab)
waitForValueContains(app.textFields["url"], value: "facebook")
navigator.goto(PrivateTabTray)
waitforExistence(app.collectionViews.cells[url2Label])
let numPrivTabs = app.collectionViews.cells.count
XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct")
// Go back to regular mode and check the total number of tabs
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[url1Label])
waitforNoExistence(app.collectionViews.cells[url2Label])
let numRegularTabs = app.collectionViews.cells.count
XCTAssertEqual(numRegularTabs, 2, "The number of regular tabs is not correct")
}
func testClosePrivateTabsOptionClosesPrivateTabs() {
// Check that Close Private Tabs when closing the Private Browsing Button is off by default
navigator.goto(SettingsScreen)
let appsettingstableviewcontrollerTableviewTable = app.tables["AppSettingsTableViewController.tableView"]
while appsettingstableviewcontrollerTableviewTable.staticTexts["Close Private Tabs"].exists == false {
appsettingstableviewcontrollerTableviewTable.swipeUp()
}
let closePrivateTabsSwitch = appsettingstableviewcontrollerTableviewTable.switches["Close Private Tabs, When Leaving Private Browsing"]
XCTAssertFalse(closePrivateTabsSwitch.isSelected)
// Open a Private tab
navigator.goto(PrivateTabTray)
navigator.openURL(urlString: url1)
navigator.nowAt(PrivateBrowserTab)
navigator.goto(PrivateTabTray)
// Go back to regular browser
navigator.goto(TabTray)
// Go back to private browsing and check that the tab has not been closed
navigator.goto(PrivateTabTray)
waitforExistence(app.collectionViews.cells[url1Label])
let numPrivTabs = app.collectionViews.cells.count
XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed")
// Now the enable the Close Private Tabs when closing the Private Browsing Button
navigator.goto(SettingsScreen)
closePrivateTabsSwitch.tap()
// Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing
navigator.goto(PrivateTabTray)
navigator.goto(TabTray)
navigator.goto(PrivateTabTray)
waitforNoExistence(app.collectionViews.cells[url1Label])
let numPrivTabsAfterClosing = app.collectionViews.cells.count
XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed")
XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown")
}
func testPrivateBrowserPanelView() {
// If no private tabs are open, there should be a initial screen with label Private Browsing
navigator.goto(PrivateTabTray)
XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown")
let numPrivTabsFirstTime = app.collectionViews.cells.count
XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet")
// If a private tab is open Private Browsing screen is not shown anymore
navigator.goto(NewPrivateTabScreen)
// Go to regular browsing
navigator.goto(TabTray)
// Go back to private brosing
navigator.goto(PrivateTabTray)
waitforNoExistence(app.staticTexts["Private Browsing"])
XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is shown")
let numPrivTabsOpen = app.collectionViews.cells.count
XCTAssertEqual(numPrivTabsOpen, 1, "The number of tabs is not correct, there should be one private tab")
}
}
| mpl-2.0 | 117e0114789e8c087b8a21577fcc715d | 44.134615 | 175 | 0.710837 | 5.050933 | false | false | false | false |
DanielAsher/SwiftCheck | SwiftCheck/Modifiers.swift | 3 | 13266 | //
// Modifiers.swift
// SwiftCheck
//
// Created by Robert Widmann on 1/29/15.
// Copyright (c) 2015 CodaFi. All rights reserved.
//
// MARK: - Modifier Types
/// A Modifier Type is a type that wraps another to provide special semantics or simply to generate
/// values of an underlying type that would be unusually difficult to express given the limitations
/// of Swift's type system.
///
/// For an example of the former, take the `Blind` modifier. Because SwiftCheck's counterexamples
/// come from a description a particular object provides for itself, there are many cases where
/// console output can become unbearably long, or just simply isn't useful to your test suite. By
/// wrapping that type in `Blind` SwiftCheck ignores whatever description the property provides and
/// just print "(*)".
///
/// property("All blind variables print '(*)'") <- forAll { (x : Blind<Int>) in
/// return x.description == "(*)"
/// }
///
/// For an example of the latter see the `ArrowOf` modifier. Because Swift's type system treats
/// arrows (`->`) as an opaque entity that you can't interact with or extend, SwiftCheck provides
/// `ArrowOf` to enable the generation of functions between 2 types. That's right, we can generate
/// arbitrary functions!
///
/// property("map accepts SwiftCheck arrows") <- forAll { (xs : [Int]) in
/// return forAll { (f : ArrowOf<Int, Int>) in
/// /// Just to prove it really is a function (that is, every input always maps to the
/// /// same output), and not just a trick, we map twice and should get equal arrays.
/// return xs.map(f.getArrow) == xs.map(f.getArrow)
/// }
/// }
///
/// Finally, modifiers nest to allow the generation of intricate structures that would not otherwise
/// be possible due to the limitations above. For example, to generate an Array of Arrays of
/// Dictionaries of Integers and Strings (a type that normally looks like
/// `Array<Array<Dictionary<String, Int>>>`), would look like this:
///
/// property("Generating monstrous data types is possible") <- forAll { (xs : ArrayOf<ArrayOf<DictionaryOf<String, Int>>>) in
/// /// We're gonna need a bigger boat.
/// }
/// For types that either do not have a `CustomStringConvertible` instance or that wish to have no
/// description to print, Blind will create a default description for them.
public struct Blind<A : Arbitrary> : Arbitrary, CustomStringConvertible {
public let getBlind : A
public init(_ blind : A) {
self.getBlind = blind
}
public var description : String {
return "(*)"
}
public static var arbitrary : Gen<Blind<A>> {
return Blind.init <^> A.arbitrary
}
public static func shrink(bl : Blind<A>) -> [Blind<A>] {
return A.shrink(bl.getBlind).map(Blind.init)
}
}
extension Blind : CoArbitrary {
// Take the lazy way out.
public static func coarbitrary<C>(x : Blind) -> (Gen<C> -> Gen<C>) {
return coarbitraryPrintable(x)
}
}
/// Guarantees test cases for its underlying type will not be shrunk.
public struct Static<A : Arbitrary> : Arbitrary, CustomStringConvertible {
public let getStatic : A
public init(_ fixed : A) {
self.getStatic = fixed
}
public var description : String {
return "Static( \(self.getStatic) )"
}
public static var arbitrary : Gen<Static<A>> {
return Static.init <^> A.arbitrary
}
}
extension Static : CoArbitrary {
// Take the lazy way out.
public static func coarbitrary<C>(x : Static) -> (Gen<C> -> Gen<C>) {
return coarbitraryPrintable(x)
}
}
/// Generates an array of arbitrary values of type A.
public struct ArrayOf<A : Arbitrary> : Arbitrary, CustomStringConvertible {
public let getArray : [A]
public var getContiguousArray : ContiguousArray<A> {
return ContiguousArray(self.getArray)
}
public init(_ array : [A]) {
self.getArray = array
}
public var description : String {
return "\(self.getArray)"
}
public static var arbitrary : Gen<ArrayOf<A>> {
return ArrayOf.init <^> Array<A>.arbitrary
}
public static func shrink(bl : ArrayOf<A>) -> [ArrayOf<A>] {
return Array<A>.shrink(bl.getArray).map(ArrayOf.init)
}
}
extension ArrayOf : CoArbitrary {
public static func coarbitrary<C>(x : ArrayOf) -> (Gen<C> -> Gen<C>) {
let a = x.getArray
if a.isEmpty {
return { $0.variant(0) }
}
return { $0.variant(1) } • ArrayOf.coarbitrary(ArrayOf([A](a[1..<a.endIndex])))
}
}
/// Generates an dictionary of arbitrary keys and values.
public struct DictionaryOf<K : protocol<Hashable, Arbitrary>, V : Arbitrary> : Arbitrary, CustomStringConvertible {
public let getDictionary : Dictionary<K, V>
public init(_ dict : Dictionary<K, V>) {
self.getDictionary = dict
}
public var description : String {
return "\(self.getDictionary)"
}
public static var arbitrary : Gen<DictionaryOf<K, V>> {
return DictionaryOf.init <^> Dictionary<K, V>.arbitrary
}
public static func shrink(d : DictionaryOf<K, V>) -> [DictionaryOf<K, V>] {
return Dictionary.shrink(d.getDictionary).map(DictionaryOf.init)
}
}
extension DictionaryOf : CoArbitrary {
public static func coarbitrary<C>(x : DictionaryOf) -> (Gen<C> -> Gen<C>) {
return Dictionary.coarbitrary(x.getDictionary)
}
}
/// Generates an Optional of arbitrary values of type A.
public struct OptionalOf<A : Arbitrary> : Arbitrary, CustomStringConvertible {
public let getOptional : A?
public init(_ opt : A?) {
self.getOptional = opt
}
public var description : String {
return "\(self.getOptional)"
}
public static var arbitrary : Gen<OptionalOf<A>> {
return OptionalOf.init <^> Optional<A>.arbitrary
}
public static func shrink(bl : OptionalOf<A>) -> [OptionalOf<A>] {
return Optional<A>.shrink(bl.getOptional).map(OptionalOf.init)
}
}
extension OptionalOf : CoArbitrary {
public static func coarbitrary<C>(x : OptionalOf) -> (Gen<C> -> Gen<C>) {
if let _ = x.getOptional {
return { $0.variant(0) }
}
return { $0.variant(1) }
}
}
/// Generates a set of arbitrary values of type A.
public struct SetOf<A : protocol<Hashable, Arbitrary>> : Arbitrary, CustomStringConvertible {
public let getSet : Set<A>
public init(_ set : Set<A>) {
self.getSet = set
}
public var description : String {
return "\(self.getSet)"
}
public static var arbitrary : Gen<SetOf<A>> {
return Gen.sized { n in
return Gen<Int>.choose((0, n)).bind { k in
if k == 0 {
return Gen.pure(SetOf(Set([])))
}
return (SetOf.init • Set.init) <^> sequence(Array((0...k)).map { _ in A.arbitrary })
}
}
}
public static func shrink(s : SetOf<A>) -> [SetOf<A>] {
return ArrayOf.shrink(ArrayOf([A](s.getSet))).map({ SetOf(Set($0.getArray)) })
}
}
extension SetOf : CoArbitrary {
public static func coarbitrary<C>(x : SetOf) -> (Gen<C> -> Gen<C>) {
if x.getSet.isEmpty {
return { $0.variant(0) }
}
return { $0.variant(1) }
}
}
/// Generates a Swift function from T to U.
public struct ArrowOf<T : protocol<Hashable, CoArbitrary>, U : Arbitrary> : Arbitrary, CustomStringConvertible {
private var table : Dictionary<T, U>
private var arr : T -> U
public var getArrow : T -> U {
return self.arr
}
private init (_ table : Dictionary<T, U>, _ arr : (T -> U)) {
self.table = table
self.arr = arr
}
public init(_ arr : (T -> U)) {
self.init(Dictionary(), { (_ : T) -> U in return undefined() })
self.arr = { x in
if let v = self.table[x] {
return v
}
let y = arr(x)
self.table[x] = y
return y
}
}
public var description : String {
return "\(T.self) -> \(U.self)"
}
public static var arbitrary : Gen<ArrowOf<T, U>> {
return ArrowOf.init <^> promote({ a in
return T.coarbitrary(a)(U.arbitrary)
})
}
public static func shrink(f : ArrowOf<T, U>) -> [ArrowOf<T, U>] {
return f.table.flatMap { (x, y) in
return U.shrink(y).map({ (y2 : U) -> ArrowOf<T, U> in
return ArrowOf<T, U>({ (z : T) -> U in
if x == z {
return y2
}
return f.arr(z)
})
})
}
}
}
extension ArrowOf : CustomReflectable {
public func customMirror() -> Mirror {
return Mirror(self, children: [
"types": "\(T.self) -> \(U.self)",
"currentMap": self.table,
])
}
}
/// Generates two isomorphic Swift function from T to U and back again.
public struct IsoOf<T : protocol<Hashable, CoArbitrary, Arbitrary>, U : protocol<Equatable, CoArbitrary, Arbitrary>> : Arbitrary, CustomStringConvertible {
private var table : Dictionary<T, U>
private var embed : T -> U
private var project : U -> T
public var getTo : T -> U {
return embed
}
public var getFrom : U -> T {
return project
}
private init (_ table : Dictionary<T, U>, _ embed : (T -> U), _ project : (U -> T)) {
self.table = table
self.embed = embed
self.project = project
}
public init(_ embed : (T -> U), _ project : (U -> T)) {
self.init(Dictionary(), { (_ : T) -> U in return undefined() }, { (_ : U) -> T in return undefined() })
self.embed = { t in
if let v = self.table[t] {
return v
}
let y = embed(t)
self.table[t] = y
return y
}
self.project = { u in
let ts = self.table.filter { $1 == u }.map { $0.0 }
if let k = ts.first, _ = self.table[k] {
return k
}
let y = project(u)
self.table[y] = u
return y
}
}
public var description : String {
return "IsoOf<\(T.self) -> \(U.self), \(U.self) -> \(T.self)>"
}
public static var arbitrary : Gen<IsoOf<T, U>> {
return Gen<(T -> U, U -> T)>.zip(promote({ a in
return T.coarbitrary(a)(U.arbitrary)
}), promote({ a in
return U.coarbitrary(a)(T.arbitrary)
})).fmap { IsoOf($0, $1) }
}
public static func shrink(f : IsoOf<T, U>) -> [IsoOf<T, U>] {
return f.table.flatMap { (x, y) in
return Zip2Sequence(T.shrink(x), U.shrink(y)).map({ (y1 , y2) -> IsoOf<T, U> in
return IsoOf<T, U>({ (z : T) -> U in
if x == z {
return y2
}
return f.embed(z)
}, { (z : U) -> T in
if y == z {
return y1
}
return f.project(z)
})
})
}
}
}
extension IsoOf : CustomReflectable {
public func customMirror() -> Mirror {
return Mirror(self, children: [
"embed": "\(T.self) -> \(U.self)",
"project": "\(U.self) -> \(T.self)",
"currentMap": self.table,
])
}
}
private func undefined<A>() -> A {
fatalError("")
}
public struct Large<A : protocol<RandomType, LatticeType, IntegerType>> : Arbitrary {
public let getLarge : A
public init(_ lrg : A) {
self.getLarge = lrg
}
public var description : String {
return "Large( \(self.getLarge) )"
}
public static var arbitrary : Gen<Large<A>> {
return Gen<A>.choose((A.min, A.max)).fmap(Large.init)
}
public static func shrink(bl : Large<A>) -> [Large<A>] {
return bl.getLarge.shrinkIntegral.map(Large.init)
}
}
/// Guarantees that every generated integer is greater than 0.
public struct Positive<A : protocol<Arbitrary, SignedNumberType>> : Arbitrary, CustomStringConvertible {
public let getPositive : A
public init(_ pos : A) {
self.getPositive = pos
}
public var description : String {
return "Positive( \(self.getPositive) )"
}
public static var arbitrary : Gen<Positive<A>> {
return A.arbitrary.fmap(Positive.init • abs).suchThat { $0.getPositive > 0 }
}
public static func shrink(bl : Positive<A>) -> [Positive<A>] {
return A.shrink(bl.getPositive).filter({ $0 > 0 }).map(Positive.init)
}
}
extension Positive : CoArbitrary {
// Take the lazy way out.
public static func coarbitrary<C>(x : Positive) -> (Gen<C> -> Gen<C>) {
return coarbitraryPrintable(x)
}
}
/// Guarantees that every generated integer is never 0.
public struct NonZero<A : protocol<Arbitrary, IntegerType>> : Arbitrary, CustomStringConvertible {
public let getNonZero : A
public init(_ non : A) {
self.getNonZero = non
}
public var description : String {
return "NonZero( \(self.getNonZero) )"
}
public static var arbitrary : Gen<NonZero<A>> {
return NonZero.init <^> A.arbitrary.suchThat { $0 != 0 }
}
public static func shrink(bl : NonZero<A>) -> [NonZero<A>] {
return A.shrink(bl.getNonZero).filter({ $0 != 0 }).map(NonZero.init)
}
}
extension NonZero : CoArbitrary {
public static func coarbitrary<C>(x : NonZero) -> (Gen<C> -> Gen<C>) {
return x.getNonZero.coarbitraryIntegral()
}
}
/// Guarantees that every generated integer is greater than or equal to 0.
public struct NonNegative<A : protocol<Arbitrary, IntegerType>> : Arbitrary, CustomStringConvertible {
public let getNonNegative : A
public init(_ non : A) {
self.getNonNegative = non
}
public var description : String {
return "NonNegative( \(self.getNonNegative) )"
}
public static var arbitrary : Gen<NonNegative<A>> {
return NonNegative.init <^> A.arbitrary.suchThat { $0 >= 0 }
}
public static func shrink(bl : NonNegative<A>) -> [NonNegative<A>] {
return A.shrink(bl.getNonNegative).filter({ $0 >= 0 }).map(NonNegative.init)
}
}
extension NonNegative : CoArbitrary {
public static func coarbitrary<C>(x : NonNegative) -> (Gen<C> -> Gen<C>) {
return x.getNonNegative.coarbitraryIntegral()
}
}
private func inBounds<A : IntegerType where A.IntegerLiteralType == Int>(fi : (Int -> A)) -> Gen<Int> -> Gen<A> {
return { g in
return fi <^> g.suchThat { x in
return (fi(x) as! Int) == x
}
}
}
| mit | 75078c5057b83c6c469ef400c6a1a62b | 26.396694 | 155 | 0.648793 | 3.200579 | false | false | false | false |
cqix/icf | app/icf/icf/SecondViewController.swift | 1 | 2467 | //
// SecondViewController.swift
// icf
//
// Created by Patrick Gröller, Christian Koller, Helmut Kopf on 20.10.15.
// Copyright © 2015 FH. All rights reserved.
//
// Settings view
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var coursePicker: UIPickerView!
@IBOutlet weak var yearPicker: UIPickerView!
@IBOutlet weak var groupPicker: UIPickerView!
@IBOutlet weak var lecturerNameText: UITextField!
@IBOutlet weak var TypeSelection: UISegmentedControl!
@IBOutlet weak var StudentView: UIView!
@IBOutlet weak var LecturerView: UIView!
let typeDataSource = TypeDataSource()
let groupDataSource = GroupDataSource()
let yearDataSource = YearDataSource()
let courseDataSource = CourseDataSource()
let lecturerNameDataSource = LecturerNameDataSource()
override func viewDidLoad() {
super.viewDidLoad()
TypeSelection.selectedSegmentIndex = typeDataSource.getSavedIndex()
setTypeView()
TypeSelection.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: .ValueChanged)
coursePicker.dataSource = courseDataSource
coursePicker.delegate = courseDataSource
coursePicker.selectRow(courseDataSource.getSavedIndex(), inComponent: 0, animated: true)
yearPicker.dataSource = yearDataSource
yearPicker.delegate = yearDataSource
yearPicker.selectRow(yearDataSource.getSavedIndex(), inComponent: 0, animated: true)
groupPicker.dataSource = groupDataSource
groupPicker.delegate = groupDataSource
groupPicker.selectRow(groupDataSource.getSavedIndex(), inComponent: 0, animated: true)
lecturerNameText.text = lecturerNameDataSource.getSavedText()
lecturerNameText.delegate = lecturerNameDataSource
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func segmentedControlValueChanged(segment: UISegmentedControl) {
typeDataSource.saveIndex(segment.selectedSegmentIndex)
setTypeView()
}
func setTypeView() {
if (typeDataSource.getSavedIndex()==1) {
StudentView.hidden = true
LecturerView.hidden = false
} else {
StudentView.hidden = false
LecturerView.hidden = true
}
}
}
| gpl-2.0 | 212b1c7b59f7910dc27f9f4c50737a68 | 32.767123 | 111 | 0.691684 | 5.12474 | false | false | false | false |
xingerdayu/dayu | dayu/UserDao.swift | 1 | 2045 | //
// UserDao.swift
// dayu
//
// Created by Xinger on 15/9/16.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import Foundation
class UserDao {
//CREATE TABLE IF NOT EXISTS USERINFO (TEL TEXT, USER_ID TEXT, USERNAME TEXT, TOKEN TEXT, AUTHORITY TEXT, INTRO TEXT, REG_TIME TEXT)
class func save(id:Int, tel:String, token:String, username:String?, intro:String?, regTime:Int64) {
delete()
let sql = "INSERT INTO USERINFO (TEL, USER_ID, USERNAME, TOKEN, AUTHORITY, INTRO, REG_TIME) VALUES (?,?,?,?,?,?,?)"
let un = username == nil ? "" : username!
let ito = intro == nil ? "" : intro!
Db.executeSql(sql, arguments: [tel, id, un, token, 1, ito, "\(regTime)"])
}
class func save(id:Int, token:String) {
let sql = "INSERT INTO USERINFO (USER_ID, TOKEN, AUTHORITY) VALUES (?,?,?)"
Db.executeSql(sql, arguments: [id, token, 0])
}
class func modifyNick(nick:String, id:Int) {
let sql = "UPDATE USERINFO SET USERNAME=? WHERE USER_ID=?"
Db.executeSql(sql, arguments: [nick, id])
}
class func modifyIntro(intro:String, id:Int) {
let sql = "UPDATE USERINFO SET INTRO=? WHERE USER_ID=?"
Db.executeSql(sql, arguments: [intro, id])
}
class func get() -> User? {
var user:User?
let sql = "SELECT * FROM USERINFO"
let db = Db.getDb()
db.open()
let rs = db.executeQuery(sql, withArgumentsInArray: [])
while rs.next() {
user = User()
user?.id = Int(rs.longForColumn("USER_ID"))
user?.tel = rs.stringForColumn("TEL")
user?.token = rs.stringForColumn("TOKEN")
user?.username = rs.stringForColumn("USERNAME")
user?.authority = Int(rs.intForColumn("AUTHORITY"))
}
db.close()
return user
}
class func delete() {
let sql = "DELETE FROM USERINFO WHERE AUTHORITY=?"
Db.executeSql(sql, arguments: [1])
}
} | bsd-3-clause | 77a82cad5e7650dfcf76b45e332bad7d | 31.967742 | 136 | 0.568282 | 3.667864 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/FacebookCore/Sources/Core/Permissions/Permission.swift | 13 | 2767 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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
/**
Represents a Graph API permission.
Each permission has its own set of requirements and suggested use cases.
See a full list at https://developers.facebook.com/docs/facebook-login/permissions
*/
public struct Permission {
internal let name: String
/**
Create a permission with a string value.
- parameter name: Name of the permission.
*/
public init(name: String) {
self.name = name
}
}
extension Permission: ExpressibleByStringLiteral {
/**
Create a permission with a string value.
- parameter value: String literal representation of the permission.
*/
public init(stringLiteral value: StringLiteralType) {
self.init(name: value)
}
/**
Create a permission with a string value.
- parameter value: String literal representation of the permission.
*/
public init(unicodeScalarLiteral value: String) {
self.init(name: value)
}
/**
Create a permission with a string value.
- parameter value: String literal representation of the permission.
*/
public init(extendedGraphemeClusterLiteral value: String) {
self.init(name: value)
}
}
extension Permission: Hashable {
/// The hash value.
public var hashValue: Int {
return name.hashValue
}
/**
Compare two `Permission`s for equality.
- parameter lhs: The first permission to compare.
- parameter rhs: The second permission to compare.
- returns: Whether or not the permissions are equal.
*/
public static func == (lhs: Permission, rhs: Permission) -> Bool {
return lhs.name == rhs.name
}
}
internal protocol PermissionRepresentable {
var permissionValue: Permission { get }
}
| mit | a3f899779c279d8cc12d9a95fd219c6b | 29.744444 | 83 | 0.730755 | 4.536066 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/Sugar/Reachability.swift | 2 | 2207 | import SystemConfiguration
internal enum Reachability {
case wifi
#if os(iOS)
case wwan
#endif
case none
internal static var current: Reachability {
return reachabilityProperty.value
}
internal static let signalProducer = reachabilityProperty.producer
}
private let reachabilityProperty: MutableProperty<Reachability> = {
guard
let networkReachability = networkReachability(),
let reachabilityFlags = reachabilityFlags(forNetworkReachability: networkReachability)
else { return MutableProperty(.none) }
guard SCNetworkReachabilitySetCallback(networkReachability, callback, nil)
&& SCNetworkReachabilitySetDispatchQueue(networkReachability, queue)
else { return MutableProperty(.none) }
return MutableProperty(reachability(forFlags: reachabilityFlags))
}()
private let queue = DispatchQueue(label: "com.keith.pi.tsui.reachability", attributes: [])
private func networkReachability() -> SCNetworkReachability? {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
return withUnsafePointer(to: &zeroAddress, { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
})
}
private func reachabilityFlags(forNetworkReachability networkReachability: SCNetworkReachability)
-> SCNetworkReachabilityFlags? {
var reachabilityFlags = SCNetworkReachabilityFlags()
guard withUnsafeMutablePointer(to: &reachabilityFlags, {
SCNetworkReachabilityGetFlags(networkReachability, UnsafeMutablePointer($0))
}) else { return nil }
return reachabilityFlags
}
private func reachability(forFlags flags: SCNetworkReachabilityFlags) -> Reachability {
#if os(iOS)
if flags.contains(.isWWAN) {
return .wwan
}
#endif
if flags.contains(.reachable) {
return .wifi
}
return .none
}
private func callback(networkReachability: SCNetworkReachability,
flags: SCNetworkReachabilityFlags,
info: UnsafeMutableRawPointer?) {
reachabilityProperty.value = reachability(forFlags: flags)
}
| mit | bcc6fef888afd730a0c327c6e71ce430 | 28.824324 | 97 | 0.757136 | 5.305288 | false | false | false | false |
jxxcarlson/exploring_swift | circles.playground/Contents.swift | 1 | 3547 | /*
*/
import UIKit
class Shape: CustomStringConvertible {
var x: Double
var y: Double
var width: Double
var height: Double
var color: UIColor
init() {
self.x = 0
self.y = 0
self.width = 1
self.height = 1
self.color = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)
}
init (x: Double, y: Double, width: Double, height: Double) {
self.x = x; self.y = y
self.width = width; self.height = height
self.color = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)
}
var description: String {
return "\(width)x\(height) shape at (\(x),\(y))"
}
func moveto(x x: Double, y: Double) {
self.x = x; self.y = y
}
func setBox(width width: Double, height: Double) {
self.width = width; self.height = height
}
func translate(dx dx: Double, dy: Double) {
self.x = self.x + dx
self.y = self.y + dy
}
func dilate(k: Double) {
self.width = k*self.width
self.height = k*self.height
}
func draw(frame: CGRect) {
let r = CGRect(x: self.x, y: self.y, width: self.width, height: self.height)
let context = UIGraphicsGetCurrentContext()
self.color.set()
CGContextFillRect(context, r)
}
}
class Circle: Shape {
var radius: Double {
return min(width,height)/2.0
}
override func draw(frame: CGRect) {
let context = UIGraphicsGetCurrentContext()
self.color.set()
CGContextAddArc(context,
CGFloat(self.x),
CGFloat(self.y),
CGFloat(self.radius),
0.0, CGFloat(M_PI * 2.0), 1)
CGContextFillPath(context) }
}
func drawFigure1(frame:CGRect) {
let d = Double(frame.width)
let bg = Shape(x: 0.0, y: 0.0, width: d, height: d)
bg.color = UIColor.blackColor()
let S = Circle(x: 0, y: 0, width: d, height: d)
S.color = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)
bg.draw(frame)
S.draw(frame)
S.translate(dx: d, dy: d)
S.draw(frame)
/*
S.translate(dx: -d/2.0, dy: -d/2.0)
S.draw(frame)
S.dilate(0.4)
S.draw(frame)
*/
/*
S.moveto(x: d, y: 0)
S.setBox(width: d, height: d)
S.draw(frame)
S.translate(dx: -d, dy: d)
S.draw(frame)
*/
}
func drawFigure2(frame:CGRect) {
let d = Double(frame.width)
let k = 1.2
let k2 = 0.8
let d2 = 2*k*d
let a = CGFloat(0.11)
let n = 20
let bg = Shape(x: 0.0, y: 0.0, width: d, height: d)
bg.color = UIColor(red: 0, green: 0, blue: 1, alpha: 0.7)
let S1 = Circle(x: 0, y: 0, width: d2, height: d2)
S1.color = UIColor(red: 1, green: 0, blue: 0, alpha: a)
let S2 = Circle(x: d, y: d, width: -d2, height: -d2)
S2.color = UIColor(red: 1, green: 0, blue: 0, alpha: a)
bg.draw(frame)
for(var i = 0; i < n; i++) {
S1.draw(frame)
S1.dilate(k2)
}
for(var i = 0; i < n; i++) {
S2.draw(frame)
S2.dilate(k2)
}
}
class GraphicsView: UIView {
override func drawRect(rect: CGRect) {
drawFigure1(frame)
}
}
let view = GraphicsView(frame:CGRect(x: 0, y: 0, width: 300, height: 300))
| mit | c6906dbdadc9d668eceb34871efa26de | 17.967914 | 85 | 0.491965 | 3.269124 | false | false | false | false |
SerenadeX/SwiftNotesAndSnippets | SafariSavedPasswords.swift | 1 | 991 |
func getPassword() -> (username: String, password: String) {
var tuple = (username: "", password: "")
SecRequestSharedWebCredential(.None, .None) { (credentials, error) -> Void in
guard error == nil else {
NSLog("error loading safari credentials: \(error)")
return
}
guard let unwrappedCredentials = credentials else {
print("Error unwrapping credentials array", credentials)
return
}
let arrayCredentials = unwrappedCredentials as [AnyObject]
guard let typedCredentials = arrayCredentials as? [[String: AnyObject]] else {
print("error typecasting credentials")
return
}
let credential = typedCredentials[0]
if let username = credential[kSecAttrAccount as String], password = credential[kSecSharedPassword as String] {
tuple.username = username
tuple.password = password
}
}
return tuple
}
| gpl-2.0 | eb70b0ff987a78320dd27b94e8ef046a | 33.172414 | 118 | 0.611504 | 5.415301 | false | false | false | false |
WenchaoD/FSPagerView | Sources/FSPagerView.swift | 2 | 26170 | //
// FSPagerView.swift
// FSPagerView
//
// Created by Wenchao Ding on 17/12/2016.
// Copyright © 2016 Wenchao Ding. All rights reserved.
//
// https://github.com/WenchaoD
//
// FSPagerView is an elegant Screen Slide Library implemented primarily with UICollectionView. It is extremely helpful for making Banner、Product Show、Welcome/Guide Pages、Screen/ViewController Sliders.
//
import UIKit
@objc
public protocol FSPagerViewDataSource: NSObjectProtocol {
/// Asks your data source object for the number of items in the pager view.
@objc(numberOfItemsInPagerView:)
func numberOfItems(in pagerView: FSPagerView) -> Int
/// Asks your data source object for the cell that corresponds to the specified item in the pager view.
@objc(pagerView:cellForItemAtIndex:)
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell
}
@objc
public protocol FSPagerViewDelegate: NSObjectProtocol {
/// Asks the delegate if the item should be highlighted during tracking.
@objc(pagerView:shouldHighlightItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, shouldHighlightItemAt index: Int) -> Bool
/// Tells the delegate that the item at the specified index was highlighted.
@objc(pagerView:didHighlightItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didHighlightItemAt index: Int)
/// Asks the delegate if the specified item should be selected.
@objc(pagerView:shouldSelectItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, shouldSelectItemAt index: Int) -> Bool
/// Tells the delegate that the item at the specified index was selected.
@objc(pagerView:didSelectItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int)
/// Tells the delegate that the specified cell is about to be displayed in the pager view.
@objc(pagerView:willDisplayCell:forItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int)
/// Tells the delegate that the specified cell was removed from the pager view.
@objc(pagerView:didEndDisplayingCell:forItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didEndDisplaying cell: FSPagerViewCell, forItemAt index: Int)
/// Tells the delegate when the pager view is about to start scrolling the content.
@objc(pagerViewWillBeginDragging:)
optional func pagerViewWillBeginDragging(_ pagerView: FSPagerView)
/// Tells the delegate when the user finishes scrolling the content.
@objc(pagerViewWillEndDragging:targetIndex:)
optional func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int)
/// Tells the delegate when the user scrolls the content view within the receiver.
@objc(pagerViewDidScroll:)
optional func pagerViewDidScroll(_ pagerView: FSPagerView)
/// Tells the delegate when a scrolling animation in the pager view concludes.
@objc(pagerViewDidEndScrollAnimation:)
optional func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView)
/// Tells the delegate that the pager view has ended decelerating the scrolling movement.
@objc(pagerViewDidEndDecelerating:)
optional func pagerViewDidEndDecelerating(_ pagerView: FSPagerView)
}
@IBDesignable
open class FSPagerView: UIView,UICollectionViewDataSource,UICollectionViewDelegate {
// MARK: - Public properties
/// The object that acts as the data source of the pager view.
@IBOutlet open weak var dataSource: FSPagerViewDataSource?
/// The object that acts as the delegate of the pager view.
@IBOutlet open weak var delegate: FSPagerViewDelegate?
/// The scroll direction of the pager view. Default is horizontal.
@objc
open var scrollDirection: FSPagerView.ScrollDirection = .horizontal {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// The time interval of automatic sliding. 0 means disabling automatic sliding. Default is 0.
@IBInspectable
open var automaticSlidingInterval: CGFloat = 0.0 {
didSet {
self.cancelTimer()
if self.automaticSlidingInterval > 0 {
self.startTimer()
}
}
}
/// The spacing to use between items in the pager view. Default is 0.
@IBInspectable
open var interitemSpacing: CGFloat = 0 {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// The item size of the pager view. When the value of this property is FSPagerView.automaticSize, the items fill the entire visible area of the pager view. Default is FSPagerView.automaticSize.
@IBInspectable
open var itemSize: CGSize = automaticSize {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// A Boolean value indicates that whether the pager view has infinite items. Default is false.
@IBInspectable
open var isInfinite: Bool = false {
didSet {
self.collectionViewLayout.needsReprepare = true
self.collectionView.reloadData()
}
}
/// An unsigned integer value that determines the deceleration distance of the pager view, which indicates the number of passing items during the deceleration. When the value of this property is FSPagerView.automaticDistance, the actual 'distance' is automatically calculated according to the scrolling speed of the pager view. Default is 1.
@IBInspectable
open var decelerationDistance: UInt = 1
/// A Boolean value that determines whether scrolling is enabled.
@IBInspectable
open var isScrollEnabled: Bool {
set { self.collectionView.isScrollEnabled = newValue }
get { return self.collectionView.isScrollEnabled }
}
/// A Boolean value that controls whether the pager view bounces past the edge of content and back again.
@IBInspectable
open var bounces: Bool {
set { self.collectionView.bounces = newValue }
get { return self.collectionView.bounces }
}
/// A Boolean value that determines whether bouncing always occurs when horizontal scrolling reaches the end of the content view.
@IBInspectable
open var alwaysBounceHorizontal: Bool {
set { self.collectionView.alwaysBounceHorizontal = newValue }
get { return self.collectionView.alwaysBounceHorizontal }
}
/// A Boolean value that determines whether bouncing always occurs when vertical scrolling reaches the end of the content view.
@IBInspectable
open var alwaysBounceVertical: Bool {
set { self.collectionView.alwaysBounceVertical = newValue }
get { return self.collectionView.alwaysBounceVertical }
}
/// A Boolean value that controls whether the infinite loop is removed if there is only one item. Default is false.
@IBInspectable
open var removesInfiniteLoopForSingleItem: Bool = false {
didSet {
self.reloadData()
}
}
/// The background view of the pager view.
@IBInspectable
open var backgroundView: UIView? {
didSet {
if let backgroundView = self.backgroundView {
if backgroundView.superview != nil {
backgroundView.removeFromSuperview()
}
self.insertSubview(backgroundView, at: 0)
self.setNeedsLayout()
}
}
}
/// The transformer of the pager view.
@objc
open var transformer: FSPagerViewTransformer? {
didSet {
self.transformer?.pagerView = self
self.collectionViewLayout.forceInvalidate()
}
}
// MARK: - Public readonly-properties
/// Returns whether the user has touched the content to initiate scrolling.
@objc
open var isTracking: Bool {
return self.collectionView.isTracking
}
/// The percentage of x position at which the origin of the content view is offset from the origin of the pagerView view.
@objc
open var scrollOffset: CGFloat {
let contentOffset = max(self.collectionView.contentOffset.x, self.collectionView.contentOffset.y)
let scrollOffset = Double(contentOffset/self.collectionViewLayout.itemSpacing)
return fmod(CGFloat(scrollOffset), CGFloat(self.numberOfItems))
}
/// The underlying gesture recognizer for pan gestures.
@objc
open var panGestureRecognizer: UIPanGestureRecognizer {
return self.collectionView.panGestureRecognizer
}
@objc open fileprivate(set) dynamic var currentIndex: Int = 0
// MARK: - Private properties
internal weak var collectionViewLayout: FSPagerViewLayout!
internal weak var collectionView: FSPagerCollectionView!
internal weak var contentView: UIView!
internal var timer: Timer?
internal var numberOfItems: Int = 0
internal var numberOfSections: Int = 0
fileprivate var dequeingSection = 0
fileprivate var centermostIndexPath: IndexPath {
guard self.numberOfItems > 0, self.collectionView.contentSize != .zero else {
return IndexPath(item: 0, section: 0)
}
let sortedIndexPaths = self.collectionView.indexPathsForVisibleItems.sorted { (l, r) -> Bool in
let leftFrame = self.collectionViewLayout.frame(for: l)
let rightFrame = self.collectionViewLayout.frame(for: r)
var leftCenter: CGFloat,rightCenter: CGFloat,ruler: CGFloat
switch self.scrollDirection {
case .horizontal:
leftCenter = leftFrame.midX
rightCenter = rightFrame.midX
ruler = self.collectionView.bounds.midX
case .vertical:
leftCenter = leftFrame.midY
rightCenter = rightFrame.midY
ruler = self.collectionView.bounds.midY
}
return abs(ruler-leftCenter) < abs(ruler-rightCenter)
}
let indexPath = sortedIndexPaths.first
if let indexPath = indexPath {
return indexPath
}
return IndexPath(item: 0, section: 0)
}
fileprivate var isPossiblyRotating: Bool {
guard let animationKeys = self.contentView.layer.animationKeys() else {
return false
}
let rotationAnimationKeys = ["position", "bounds.origin", "bounds.size"]
return animationKeys.contains(where: { rotationAnimationKeys.contains($0) })
}
fileprivate var possibleTargetingIndexPath: IndexPath?
// MARK: - Overriden functions
public override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
open override func layoutSubviews() {
super.layoutSubviews()
self.backgroundView?.frame = self.bounds
self.contentView.frame = self.bounds
self.collectionView.frame = self.contentView.bounds
}
open override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if newWindow != nil {
self.startTimer()
} else {
self.cancelTimer()
}
}
#if TARGET_INTERFACE_BUILDER
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.contentView.layer.borderWidth = 1
self.contentView.layer.cornerRadius = 5
self.contentView.layer.masksToBounds = true
self.contentView.frame = self.bounds
let label = UILabel(frame: self.contentView.bounds)
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 25)
label.text = "FSPagerView"
self.contentView.addSubview(label)
}
#endif
deinit {
self.collectionView.dataSource = nil
self.collectionView.delegate = nil
}
// MARK: - UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let dataSource = self.dataSource else {
return 1
}
self.numberOfItems = dataSource.numberOfItems(in: self)
guard self.numberOfItems > 0 else {
return 0;
}
self.numberOfSections = self.isInfinite && (self.numberOfItems > 1 || !self.removesInfiniteLoopForSingleItem) ? Int(Int16.max)/self.numberOfItems : 1
return self.numberOfSections
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.numberOfItems
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let index = indexPath.item
self.dequeingSection = indexPath.section
let cell = self.dataSource!.pagerView(self, cellForItemAt: index)
return cell
}
// MARK: - UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
guard let function = self.delegate?.pagerView(_:shouldHighlightItemAt:) else {
return true
}
let index = indexPath.item % self.numberOfItems
return function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didHighlightItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let function = self.delegate?.pagerView(_:shouldSelectItemAt:) else {
return true
}
let index = indexPath.item % self.numberOfItems
return function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didSelectItemAt:) else {
return
}
self.possibleTargetingIndexPath = indexPath
defer {
self.possibleTargetingIndexPath = nil
}
let index = indexPath.item % self.numberOfItems
function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:willDisplay:forItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,cell as! FSPagerViewCell,index)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didEndDisplaying:forItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,cell as! FSPagerViewCell,index)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !self.isPossiblyRotating && self.numberOfItems > 0 {
// In case someone is using KVO
let currentIndex = lround(Double(self.scrollOffset)) % self.numberOfItems
if (currentIndex != self.currentIndex) {
self.currentIndex = currentIndex
}
}
guard let function = self.delegate?.pagerViewDidScroll else {
return
}
function(self)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewWillBeginDragging(_:) {
function(self)
}
if self.automaticSlidingInterval > 0 {
self.cancelTimer()
}
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if let function = self.delegate?.pagerViewWillEndDragging(_:targetIndex:) {
let contentOffset = self.scrollDirection == .horizontal ? targetContentOffset.pointee.x : targetContentOffset.pointee.y
let targetItem = lround(Double(contentOffset/self.collectionViewLayout.itemSpacing))
function(self, targetItem % self.numberOfItems)
}
if self.automaticSlidingInterval > 0 {
self.startTimer()
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewDidEndDecelerating {
function(self)
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewDidEndScrollAnimation {
function(self)
}
}
// MARK: - Public functions
/// Register a class for use in creating new pager view cells.
///
/// - Parameters:
/// - cellClass: The class of a cell that you want to use in the pager view.
/// - identifier: The reuse identifier to associate with the specified class. This parameter must not be nil and must not be an empty string.
@objc(registerClass:forCellWithReuseIdentifier:)
open func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) {
self.collectionView.register(cellClass, forCellWithReuseIdentifier: identifier)
}
/// Register a nib file for use in creating new pager view cells.
///
/// - Parameters:
/// - nib: The nib object containing the cell object. The nib file must contain only one top-level object and that object must be of the type FSPagerViewCell.
/// - identifier: The reuse identifier to associate with the specified nib file. This parameter must not be nil and must not be an empty string.
@objc(registerNib:forCellWithReuseIdentifier:)
open func register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
self.collectionView.register(nib, forCellWithReuseIdentifier: identifier)
}
/// Returns a reusable cell object located by its identifier
///
/// - Parameters:
/// - identifier: The reuse identifier for the specified cell. This parameter must not be nil.
/// - index: The index specifying the location of the cell.
/// - Returns: A valid FSPagerViewCell object.
@objc(dequeueReusableCellWithReuseIdentifier:atIndex:)
open func dequeueReusableCell(withReuseIdentifier identifier: String, at index: Int) -> FSPagerViewCell {
let indexPath = IndexPath(item: index, section: self.dequeingSection)
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
guard cell.isKind(of: FSPagerViewCell.self) else {
fatalError("Cell class must be subclass of FSPagerViewCell")
}
return cell as! FSPagerViewCell
}
/// Reloads all of the data for the collection view.
@objc(reloadData)
open func reloadData() {
self.collectionViewLayout.needsReprepare = true;
self.collectionView.reloadData()
}
/// Selects the item at the specified index and optionally scrolls it into view.
///
/// - Parameters:
/// - index: The index path of the item to select.
/// - animated: Specify true to animate the change in the selection or false to make the change without animating it.
@objc(selectItemAtIndex:animated:)
open func selectItem(at index: Int, animated: Bool) {
let indexPath = self.nearbyIndexPath(for: index)
let scrollPosition: UICollectionView.ScrollPosition = self.scrollDirection == .horizontal ? .centeredHorizontally : .centeredVertically
self.collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
/// Deselects the item at the specified index.
///
/// - Parameters:
/// - index: The index of the item to deselect.
/// - animated: Specify true to animate the change in the selection or false to make the change without animating it.
@objc(deselectItemAtIndex:animated:)
open func deselectItem(at index: Int, animated: Bool) {
let indexPath = self.nearbyIndexPath(for: index)
self.collectionView.deselectItem(at: indexPath, animated: animated)
}
/// Scrolls the pager view contents until the specified item is visible.
///
/// - Parameters:
/// - index: The index of the item to scroll into view.
/// - animated: Specify true to animate the scrolling behavior or false to adjust the pager view’s visible content immediately.
@objc(scrollToItemAtIndex:animated:)
open func scrollToItem(at index: Int, animated: Bool) {
guard index < self.numberOfItems else {
fatalError("index \(index) is out of range [0...\(self.numberOfItems-1)]")
}
let indexPath = { () -> IndexPath in
if let indexPath = self.possibleTargetingIndexPath, indexPath.item == index {
defer {
self.possibleTargetingIndexPath = nil
}
return indexPath
}
return self.numberOfSections > 1 ? self.nearbyIndexPath(for: index) : IndexPath(item: index, section: 0)
}()
let contentOffset = self.collectionViewLayout.contentOffset(for: indexPath)
self.collectionView.setContentOffset(contentOffset, animated: animated)
}
/// Returns the index of the specified cell.
///
/// - Parameter cell: The cell object whose index you want.
/// - Returns: The index of the cell or NSNotFound if the specified cell is not in the pager view.
@objc(indexForCell:)
open func index(for cell: FSPagerViewCell) -> Int {
guard let indexPath = self.collectionView.indexPath(for: cell) else {
return NSNotFound
}
return indexPath.item
}
/// Returns the visible cell at the specified index.
///
/// - Parameter index: The index that specifies the position of the cell.
/// - Returns: The cell object at the corresponding position or nil if the cell is not visible or index is out of range.
@objc(cellForItemAtIndex:)
open func cellForItem(at index: Int) -> FSPagerViewCell? {
let indexPath = self.nearbyIndexPath(for: index)
return self.collectionView.cellForItem(at: indexPath) as? FSPagerViewCell
}
// MARK: - Private functions
fileprivate func commonInit() {
// Content View
let contentView = UIView(frame:CGRect.zero)
contentView.backgroundColor = UIColor.clear
self.addSubview(contentView)
self.contentView = contentView
// UICollectionView
let collectionViewLayout = FSPagerViewLayout()
let collectionView = FSPagerCollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clear
self.contentView.addSubview(collectionView)
self.collectionView = collectionView
self.collectionViewLayout = collectionViewLayout
}
fileprivate func startTimer() {
guard self.automaticSlidingInterval > 0 && self.timer == nil else {
return
}
self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.automaticSlidingInterval), target: self, selector: #selector(self.flipNext(sender:)), userInfo: nil, repeats: true)
RunLoop.current.add(self.timer!, forMode: .common)
}
@objc
fileprivate func flipNext(sender: Timer?) {
guard let _ = self.superview, let _ = self.window, self.numberOfItems > 0, !self.isTracking else {
return
}
let contentOffset: CGPoint = {
let indexPath = self.centermostIndexPath
let section = self.numberOfSections > 1 ? (indexPath.section+(indexPath.item+1)/self.numberOfItems) : 0
let item = (indexPath.item+1) % self.numberOfItems
return self.collectionViewLayout.contentOffset(for: IndexPath(item: item, section: section))
}()
self.collectionView.setContentOffset(contentOffset, animated: true)
}
fileprivate func cancelTimer() {
guard self.timer != nil else {
return
}
self.timer!.invalidate()
self.timer = nil
}
fileprivate func nearbyIndexPath(for index: Int) -> IndexPath {
// Is there a better algorithm?
let currentIndex = self.currentIndex
let currentSection = self.centermostIndexPath.section
if abs(currentIndex-index) <= self.numberOfItems/2 {
return IndexPath(item: index, section: currentSection)
} else if (index-currentIndex >= 0) {
return IndexPath(item: index, section: currentSection-1)
} else {
return IndexPath(item: index, section: currentSection+1)
}
}
}
extension FSPagerView {
/// Constants indicating the direction of scrolling for the pager view.
@objc
public enum ScrollDirection: Int {
/// The pager view scrolls content horizontally
case horizontal
/// The pager view scrolls content vertically
case vertical
}
/// Requests that FSPagerView use the default value for a given distance.
public static let automaticDistance: UInt = 0
/// Requests that FSPagerView use the default value for a given size.
public static let automaticSize: CGSize = .zero
}
| mit | 2326fb69cb046dc38eb4fe9f6385f1f8 | 40.133648 | 345 | 0.670731 | 5.312957 | false | false | false | false |
dymx101/Gamers | Gamers/Views/YoutubeLiveController.swift | 1 | 1351 | //
// YoutubeLiveController.swift
// Gamers
//
// Created by 虚空之翼 on 15/9/4.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import UIKit
import youtube_ios_player_helper
class YoutubeLiveController: UIViewController {
@IBOutlet weak var playerView: YTPlayerView!
@IBOutlet weak var chatView: UIWebView!
var liveData: Live!
var isLoadRequest = false
override func viewDidLoad() {
super.viewDidLoad()
//去掉webview加载顶部空白,禁止滚屏滑动
chatView.allowsInlineMediaPlayback = true
chatView.scrollView.scrollEnabled = false
// 设置顶部导航条样式,透明
//self.navigationItem.title = videoData.videoTitle
self.navigationController?.navigationBar.setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true
// 加载视频播放
var playerVars = ["playsinline": 1, "showinfo": 1]
playerView.loadWithVideoId(liveData.stream.id, playerVars: playerVars)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | d2b9685946198393267811b0afcaeb5e | 26.170213 | 114 | 0.678152 | 4.694853 | false | false | false | false |
jxxcarlson/exploring_swift | mandala.playground/Sources/Circle.swift | 1 | 1845 |
import UIKit
public enum drawMode {
case Fill
case Stroke
case Both
}
public class Circle{
public var center = Point()
public var radius = 0.0
public var strokeColor = UIColor.blueColor()
public var lineWidth = 2.0
public init() { }
public init( center: Point, radius: Double) {
self.center = center
self.radius = radius
}
public func includes_point(P: Point) -> Bool {
if self.center.distance_to(P) <= self.radius {
return true
} else {
return false
}
}
public func overlaps(C: Circle) -> Bool {
let sum_of_radii = self.radius + C.radius
if self.center.distance_to(C.center) < sum_of_radii {
return true
} else {
return false
}
}
public func rotate(center: Point, angle: Double) {
let dx = (cos(angle) - 1)*self.center.x + sin(angle)*self.center.y
let dy = -sin(angle)*self.center.x + (cos(angle) - 1)*self.center.y
self.center.x += dx
self.center.y += dy
}
public func translate(dx: Double, dy: Double) {
self.center.x += dx
self.center.y += dy
}
public func draw(frame: CGRect) {
let ox = frame.size.width/2
let oy = frame.size.height/2
let context = UIGraphicsGetCurrentContext()
self.strokeColor.set()
CGContextSetLineWidth(context, CGFloat(self.lineWidth))
CGContextAddArc(context,
CGFloat(self.center.x) + ox,
CGFloat(self.center.y) + oy,
CGFloat(self.radius),
0.0, CGFloat(M_PI * 2.0), 1)
CGContextStrokePath(context)
}
}
| mit | e324485e833dda97f9be8e488618d963 | 20.964286 | 75 | 0.518157 | 4.127517 | false | false | false | false |
neonichu/emoji-search-keyboard | Keyboard/DefaultSettings.swift | 1 | 14459 | //
// DefaultSettings.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 11/2/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView?
@IBOutlet var effectsView: UIVisualEffectView?
@IBOutlet var backButton: UIButton?
@IBOutlet var settingsLabel: UILabel?
@IBOutlet var pixelLine: UIView?
override var darkMode: Bool {
didSet {
self.updateAppearance(darkMode)
}
}
let cellBackgroundColorDark = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.25))
let cellBackgroundColorLight = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(1))
let cellLabelColorDark = UIColor.whiteColor()
let cellLabelColorLight = UIColor.blackColor()
let cellLongLabelColorDark = UIColor.lightGrayColor()
let cellLongLabelColorLight = UIColor.grayColor()
// TODO: these probably don't belong here, and also need to be localized
var settingsList: [(String, [String])] {
get {
return [
("General Settings", [kAutoCapitalization, kPeriodShortcut, kKeyboardClicks]),
("Extra Settings", [kAutoCompleteEmoji, kSmallLowercase])
]
}
}
var settingsNames: [String:String] {
get {
return [
kAutoCapitalization: "Auto-Capitalization",
kPeriodShortcut: "“.” Shortcut",
kKeyboardClicks: "Keyboard Clicks",
kAutoCompleteEmoji: "Auto-Complete Emoji",
kSmallLowercase: "Allow Lowercase Key Caps"
]
}
}
var settingsNotes: [String: String] {
get {
return [
kKeyboardClicks: "Please note that keyboard clicks will work only if “Allow Full Access” is enabled in the keyboard settings. Unfortunately, this is a limitation of the operating system.",
kSmallLowercase: "Changes your key caps to lowercase when Shift is off, making it easier to tell what mode you are in."
]
}
}
required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) {
super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode)
self.loadNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadNib() {
let assets = NSBundle(forClass: self.dynamicType).loadNibNamed("DefaultSettings", owner: self, options: nil)
if assets.count > 0 {
if let rootView = assets.first as? UIView {
rootView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(rootView)
let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
}
}
self.tableView?.registerClass(DefaultSettingsTableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView?.estimatedRowHeight = 44;
self.tableView?.rowHeight = UITableViewAutomaticDimension;
// XXX: this is here b/c a totally transparent background does not support scrolling in blank areas
self.tableView?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.01)
self.updateAppearance(self.darkMode)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.settingsList.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.settingsList[section].1.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == self.settingsList.count - 1 {
return 50
}
else {
return 0
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.settingsList[section].0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("cell") as? DefaultSettingsTableViewCell {
let key = self.settingsList[indexPath.section].1[indexPath.row]
if cell.sw.allTargets().count == 0 {
cell.sw.addTarget(self, action: Selector("toggleSetting:"), forControlEvents: UIControlEvents.ValueChanged)
}
cell.sw.on = NSUserDefaults.standardUserDefaults().boolForKey(key)
cell.label.text = self.settingsNames[key]
cell.longLabel.text = self.settingsNotes[key]
cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight)
cell.label.textColor = (self.darkMode ? cellLabelColorDark : cellLabelColorLight)
cell.longLabel.textColor = (self.darkMode ? cellLongLabelColorDark : cellLongLabelColorLight)
cell.changeConstraints()
return cell
}
else {
assert(false, "this is a bad thing that just happened")
return UITableViewCell()
}
}
func updateAppearance(dark: Bool) {
if dark {
self.effectsView?.effect
let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.whiteColor()
if let visibleCells = self.tableView?.visibleCells {
for cell in visibleCells {
cell.backgroundColor = cellBackgroundColorDark
let label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorDark
let longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorDark
}
}
}
else {
let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.grayColor()
if let visibleCells = self.tableView?.visibleCells {
for cell in visibleCells {
cell.backgroundColor = cellBackgroundColorLight
let label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorLight
let longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorLight
}
}
}
}
func toggleSetting(sender: UISwitch) {
if let cell = sender.superview as? UITableViewCell {
if let indexPath = self.tableView?.indexPathForCell(cell) {
let key = self.settingsList[indexPath.section].1[indexPath.row]
NSUserDefaults.standardUserDefaults().setBool(sender.on, forKey: key)
}
}
}
}
class DefaultSettingsTableViewCell: UITableViewCell {
var sw: UISwitch
var label: UILabel
var longLabel: UITextView
var constraintsSetForLongLabel: Bool
var cellConstraints: [NSLayoutConstraint]
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
self.sw = UISwitch()
self.label = UILabel()
self.longLabel = UITextView()
self.cellConstraints = []
self.constraintsSetForLongLabel = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sw.translatesAutoresizingMaskIntoConstraints = false
self.label.translatesAutoresizingMaskIntoConstraints = false
self.longLabel.translatesAutoresizingMaskIntoConstraints = false
self.longLabel.text = nil
self.longLabel.scrollEnabled = false
self.longLabel.selectable = false
self.longLabel.backgroundColor = UIColor.clearColor()
self.sw.tag = 1
self.label.tag = 2
self.longLabel.tag = 3
self.addSubview(self.sw)
self.addSubview(self.label)
self.addSubview(self.longLabel)
self.addConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addConstraints() {
let margin: CGFloat = 8
let sideMargin = margin * 2
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
let left = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let right = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let top = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: margin)
let bottom = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
self.cellConstraints += [switchSide, switchTop, labelSide, labelCenter, left, right, top, bottom]
self.constraintsSetForLongLabel = true
}
else {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let switchBottom = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(switchBottom)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
self.cellConstraints += [switchSide, switchTop, switchBottom, labelSide, labelCenter]
self.constraintsSetForLongLabel = false
}
}
// XXX: not in updateConstraints because it doesn't play nice with UITableViewAutomaticDimension for some reason
func changeConstraints() {
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText != self.constraintsSetForLongLabel {
self.removeConstraints(self.cellConstraints)
self.cellConstraints.removeAll()
self.addConstraints()
}
}
}
| bsd-3-clause | ec8eab6153a182a5f872cd59c0ced3e3 | 47.656566 | 218 | 0.656771 | 5.320692 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/ContentLengthVerifier.swift | 1 | 2558 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOHPACK
/// An object that verifies that a content-length field on a HTTP request or
/// response is respected.
struct ContentLengthVerifier {
internal var expectedContentLength: Int?
}
extension ContentLengthVerifier {
/// A chunk of data has been received from the network.
mutating func receivedDataChunk(length: Int) throws {
assert(length >= 0, "received data chunks must be positive")
// If there was no content-length, don't keep track.
guard let expectedContentLength = self.expectedContentLength else {
return
}
let newContentLength = expectedContentLength - length
if newContentLength < 0 {
throw NIOHTTP2Errors.contentLengthViolated()
}
self.expectedContentLength = newContentLength
}
/// Called when end of stream has been received. Validates that the complete body was received.
func endOfStream() throws {
switch self.expectedContentLength {
case .none, .some(0):
break
default:
throw NIOHTTP2Errors.contentLengthViolated()
}
}
}
extension ContentLengthVerifier {
internal init(_ headers: HPACKHeaders) throws {
let contentLengths = headers[canonicalForm: "content-length"]
guard let first = contentLengths.first else {
return
}
// multiple content-length headers are permitted as long as they agree
guard contentLengths.dropFirst().allSatisfy({ $0 == first }) else {
throw NIOHTTP2Errors.contentLengthHeadersMismatch()
}
self.expectedContentLength = Int(first, radix: 10)
}
/// The verifier for use when content length verification is disabled.
internal static var disabled: ContentLengthVerifier {
return ContentLengthVerifier(expectedContentLength: nil)
}
}
extension ContentLengthVerifier: CustomStringConvertible {
var description: String {
return "ContentLengthVerifier(length: \(String(describing: self.expectedContentLength)))"
}
}
| apache-2.0 | 18443195b49c329b6ae7bfe0c5f8d5ba | 34.041096 | 99 | 0.644644 | 5.285124 | false | false | false | false |
eternityz/RWScrollChart | RWScrollChartDemo/ViewController.swift | 1 | 2459 | //
// ViewController.swift
// RWScrollChartDemo
//
// Created by Zhang Bin on 2015-08-06.
// Copyright (c) 2015年 Zhang Bin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var chart: RWScrollChart!
func makeDataSetRatios() -> [[CGFloat]] {
return map(self.sections) { itemCount in
map(Array(0..<itemCount)) { _ in
CGFloat(Int(arc4random()) % 1000) / 1000.0
}
}
}
lazy var sections: [Int] = map(Array(0..<10)) { _ in Int(arc4random()) % 30 + 1 }
// lazy var sections: [Int] = [0, 4]
var barData: [[CGFloat]] = []
var lineData: [[CGFloat]] = []
override func viewDidLoad() {
super.viewDidLoad()
barData = makeDataSetRatios()
lineData = map(makeDataSetRatios()) { section in
map(section) {
0.5 * $0 + 0.2
}
}
var appearance = RWScrollChart.Appearance()
appearance.backgroundColor = UIColor.darkGrayColor()
// appearance.itemWidth = 50.0
var dataSource = RWScrollChart.DataSource()
dataSource.numberOfSections = { self.sections.count }
dataSource.numberOfItemsInSection = { self.sections[$0] }
dataSource.titleForSection = { "Section \($0)" }
dataSource.textForItemAtIndexPath = { "\($0.section) - \($0.item)" }
var lineDataSet = RWScrollChart.LineDataSet(
pointAtIndexPath: { indexPath in
if indexPath.section % 2 == 1 {
return nil
}
return self.lineData[indexPath.section][indexPath.item]
}
)
lineDataSet.showFocus = true
lineDataSet.smoothed = true
var barDataSet = RWScrollChart.BarDataSet(
barAtIndexPath: { indexPath in
return [(self.barData[indexPath.section][indexPath.item], UIColor.grayColor())]
}
)
barDataSet.showFocus = false
dataSource.axis = RWScrollChart.Axis(items: map(Array(0...4)) { i in
let ratio = CGFloat(1.0 / 4.0) * CGFloat(i)
return (ratio, toString(ratio))
}
)
dataSource.dataSets = [barDataSet, lineDataSet]
chart.appearance = appearance
chart.dataSource = dataSource
chart.reloadData()
}
}
| mit | 1977698c6adcf5aea28dc8f7845ff666 | 29.333333 | 95 | 0.550265 | 4.516544 | false | false | false | false |
btanner/Eureka | Example/Example/Controllers/ValidationsController.swift | 4 | 11224 | //
// ValidationsController.swift
// Example
//
// Created by Mathias Claassen on 3/15/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Eureka
class ValidationsController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
LabelRow.defaultCellUpdate = { cell, row in
cell.contentView.backgroundColor = .red
cell.textLabel?.textColor = .white
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
cell.textLabel?.textAlignment = .right
}
TextRow.defaultCellUpdate = { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
form
+++ Section(header: "Required Rule", footer: "Options: Validates on change")
<<< TextRow() {
$0.title = "Required Rule"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
+++ Section(header: "Email Rule, Required Rule", footer: "Options: Validates on change after blurred")
<<< TextRow() {
$0.title = "Email Rule"
$0.add(rule: RuleRequired())
var ruleSet = RuleSet<String>()
ruleSet.add(rule: RuleRequired())
ruleSet.add(rule: RuleEmail())
$0.add(ruleSet: ruleSet)
$0.validationOptions = .validatesOnChangeAfterBlurred
}
+++ Section(header: "URL Rule", footer: "Options: Validates on change")
<<< URLRow() {
$0.title = "URL Rule"
$0.add(rule: RuleURL())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "MinLength 8 Rule, MaxLength 13 Rule", footer: "Options: Validates on blurred")
<<< PasswordRow() {
$0.title = "Password"
$0.add(rule: RuleMinLength(minLength: 8))
$0.add(rule: RuleMaxLength(maxLength: 13))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "Should be GreaterThan 2 and SmallerThan 999", footer: "Options: Validates on blurred")
<<< IntRow() {
$0.title = "Range Rule"
$0.add(rule: RuleGreaterThan(min: 2))
$0.add(rule: RuleSmallerThan(max: 999))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "Match field values", footer: "Options: Validates on blurred")
<<< PasswordRow("password") {
$0.title = "Password"
}
<<< PasswordRow() {
$0.title = "Confirm Password"
$0.add(rule: RuleEqualsToRow(form: form, tag: "password"))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
+++ Section(header: "More sophisticated validations UX using callbacks", footer: "")
<<< TextRow() {
$0.title = "Required Rule"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
<<< EmailRow() {
$0.title = "Email Rule"
$0.add(rule: RuleRequired())
$0.add(rule: RuleEmail())
$0.validationOptions = .validatesOnChangeAfterBlurred
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
<<< URLRow() {
$0.title = "URL Rule"
$0.add(rule: RuleURL())
$0.validationOptions = .validatesOnChange
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
<<< PasswordRow("password2") {
$0.title = "Password"
$0.add(rule: RuleMinLength(minLength: 8))
$0.add(rule: RuleMaxLength(maxLength: 13))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
<<< PasswordRow() {
$0.title = "Confirm Password"
$0.add(rule: RuleEqualsToRow(form: form, tag: "password2"))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
<<< IntRow() {
$0.title = "Range Rule"
$0.add(rule: RuleGreaterThan(min: 2))
$0.add(rule: RuleSmallerThan(max: 999))
}
.cellUpdate { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
}
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = validationMsg
$0.cell.height = { 30 }
}
let indexPath = row.indexPath!.row + index + 1
row.section?.insert(labelRow, at: indexPath)
}
}
}
+++ Section()
<<< ButtonRow() {
$0.title = "Tap to force form validation"
}
.onCellSelection { cell, row in
row.section?.form?.validate()
}
}
}
| mit | 4e6fde802b902dd7b8cd12ab0adb9893 | 39.663043 | 119 | 0.415219 | 5.344286 | false | false | false | false |
VFUC/StackGrid | StackGrid/ViewController.swift | 1 | 1651 | //
// ViewController.swift
// StackGrid
//
// Created by Jonas on 12/09/15.
// Copyright © 2015 VFUC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var grid: StackGrid!
var viewCount = 5
let purple = UIColor(red:0.35, green:0.24, blue:0.76, alpha:1)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ViewController.addButton))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "-", style: .plain, target: self, action: #selector(ViewController.removeButton))
grid.setGridViews(createGradientViews(numOfViews: viewCount, color: purple))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createGradientViews(numOfViews num: Int, color: UIColor) -> [UIView]{
var views = [UIView]()
let interval : Float = Float(1) / Float(num)
for i in 0..<num{
let view = UIView()
view.backgroundColor = color.withAlphaComponent(CGFloat(Float(i+1) * interval))
views.append(view)
}
return views
}
@objc func addButton(){
viewCount = viewCount + 1
grid.setGridViews(createGradientViews(numOfViews: viewCount, color: purple))
}
@objc func removeButton(){
viewCount = max(0, viewCount - 1)
grid.setGridViews(createGradientViews(numOfViews: viewCount, color: purple))
}
}
| mit | fd0cbfb4eefd4ba4efc3cd962b77ca45 | 29 | 141 | 0.644242 | 4.330709 | false | false | false | false |
dvxiaofan/Pro-Swift-Learning | Part-02/15-Tuples.playground/Contents.swift | 1 | 450 | //: Playground - noun: a place where people can play
import UIKit
//func doNothing() { }
//
//let result = doNothing()
//
//let int1: (Int) = 1
//let int2: Int = (1)
//
//var singelTuple = (value: 42)
//singelTuple = 87
//
//
//var single = (first: "xiaoming", last: "fanfan")
//print(single.last)
//
var singer = (first: "xiaofan", last: "swift", sing: {
(lyris: String) in
print("lalala \(lyris)")
})
singer.sing("haters gonna hate")
| mit | 328bfc00b01b341535b3316307c82443 | 16.307692 | 54 | 0.602222 | 2.727273 | false | false | false | false |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Parsers/InterfaceBuilder/Storyboard.swift | 1 | 2528 | //
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import Foundation
import Kanna
extension InterfaceBuilder {
struct Storyboard {
let name: String
let platform: Platform
let initialScene: Scene?
let scenes: Set<Scene>
let segues: Set<Segue>
var modules: Set<String> {
var result: [String] = [platform.module] +
scenes.filter { !$0.moduleIsPlaceholder }.compactMap { $0.module } +
segues.filter { !$0.moduleIsPlaceholder }.compactMap { $0.module }
if let scene = initialScene, let module = scene.module, !scene.moduleIsPlaceholder {
result += [module]
}
return Set(result)
}
}
}
// MARK: - XML
private enum XML {
static let initialVCXPath = "/*/@initialViewController"
static let targetRuntimeXPath = "/*/@targetRuntime"
static func initialSceneXPath(identifier: String) -> String {
"/document/scenes/scene/objects/*[@sceneMemberID=\"viewController\" and @id=\"\(identifier)\"]"
}
static let sceneXPath = """
/document/scenes/scene/objects/*[@sceneMemberID=\"viewController\" and \
string-length(@storyboardIdentifier) > 0]
"""
static let segueXPath = "/document/scenes/scene//connections/segue[string(@identifier)]"
static let placeholderTags = ["controllerPlaceholder", "viewControllerPlaceholder"]
}
extension InterfaceBuilder.Storyboard {
init(with document: Kanna.XMLDocument, name: String) throws {
self.name = name
// TargetRuntime
let targetRuntime = document.at_xpath(XML.targetRuntimeXPath)?.text ?? ""
guard let platform = InterfaceBuilder.Platform(runtime: targetRuntime) else {
throw InterfaceBuilder.ParserError.unsupportedTargetRuntime(target: targetRuntime)
}
self.platform = platform
// Initial VC
let initialSceneID = document.at_xpath(XML.initialVCXPath)?.text ?? ""
if let object = document.at_xpath(XML.initialSceneXPath(identifier: initialSceneID)) {
initialScene = InterfaceBuilder.Scene(with: object, platform: platform)
} else {
initialScene = nil
}
// Scenes
scenes = Set<InterfaceBuilder.Scene>(
document.xpath(XML.sceneXPath).compactMap {
guard !XML.placeholderTags.contains($0.tagName ?? "") else { return nil }
return InterfaceBuilder.Scene(with: $0, platform: platform)
}
)
// Segues
segues = Set<InterfaceBuilder.Segue>(
document.xpath(XML.segueXPath).map {
InterfaceBuilder.Segue(with: $0, platform: platform)
}
)
}
}
| mit | 6ec53deea550843c6b4437efd321b442 | 29.083333 | 99 | 0.679462 | 4.218698 | false | false | false | false |
wosheesh/uchatclient | uchat/Data Sources and Providers/FetchedResultsDataProvider.swift | 1 | 2726 | //
// FetchedResultsDataProvider.swift
// uchat
//
// Created by Wojtek Materka on 01/03/2016.
// Copyright © 2016 Wojtek Materka. All rights reserved.
//
import CoreData
class FetchedResultsDataProvider<Delegate: DataProviderDelegate>: NSObject, NSFetchedResultsControllerDelegate, DataProvider {
typealias Object = Delegate.Object
init(fetchedResultsController: NSFetchedResultsController, delegate: Delegate) {
self.fetchedResultsController = fetchedResultsController
self.delegate = delegate
super.init()
fetchedResultsController.delegate = self
try! fetchedResultsController.performFetch()
}
func objectAtIndexPath(indexPath: NSIndexPath) -> Object {
guard let result = fetchedResultsController.objectAtIndexPath(indexPath) as? Object else { fatalError("Unexpected object at \(indexPath)") }
return result
}
func numberOfItemsInSection(section: Int) -> Int {
guard let sec = fetchedResultsController.sections?[section] else { return 0 }
return sec.numberOfObjects
}
// MARK: - Private
private let fetchedResultsController: NSFetchedResultsController
private weak var delegate: Delegate!
private var updates: [DataProviderUpdate<Object>] = []
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
updates = []
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
guard let indexPath = newIndexPath else { fatalError("Index path should be not nil") }
updates.append(.Insert(indexPath))
case .Update:
guard let indexPath = indexPath else { fatalError("Index path should be not nil") }
let object = objectAtIndexPath(indexPath)
updates.append(.Update(indexPath, object))
case .Move:
guard let indexPath = indexPath else { fatalError("Index path should be not nil") }
guard let newIndexPath = newIndexPath else { fatalError(" new index path shoul be not nil") }
updates.append(.Move(indexPath, newIndexPath))
case .Delete:
guard let indexPath = indexPath else { fatalError("Index path should be not nil") }
updates.append(.Delete(indexPath))
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
delegate.dataProviderDidUpdate(updates)
}
}
| mit | 49d6171d34461073d9df2f0bd360ad94 | 36.847222 | 211 | 0.682936 | 5.872845 | false | false | false | false |
Kawoou/FlexibleImage | Sources/Filter/LinearLightFilter.swift | 1 | 3109 | //
// LinearLightFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(watchOS)
import Metal
#endif
internal class LinearLightFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "LinearLightFilter"
}
}
internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0)
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [color.r, color.g, color.b, color.a]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
let memoryPool = device.memoryPool!
let width = Int(device.drawRect!.width)
let height = Int(device.drawRect!.height)
func linearLight(_ a: UInt16, _ b: UInt16) -> UInt8 {
if b < 128 {
if a + 2 * b < 255 {
return 0
} else {
return UInt8(a + 2 * b - 255)
}
} else {
return UInt8(min(255, 2 * (Int32(b) - 128) + Int32(a)))
}
}
var index = 0
for _ in 0..<height {
for _ in 0..<width {
let r = UInt16(memoryPool[index + 0])
let g = UInt16(memoryPool[index + 1])
let b = UInt16(memoryPool[index + 2])
let a = UInt16(memoryPool[index + 3])
memoryPool[index + 0] = linearLight(r, UInt16(color.r * 255))
memoryPool[index + 1] = linearLight(g, UInt16(color.g * 255))
memoryPool[index + 2] = linearLight(b, UInt16(color.b * 255))
memoryPool[index + 3] = linearLight(a, UInt16(color.a * 255))
index += 4
}
}
return super.processNone(device)
}
}
| mit | ec632dd9d77e9a54c6f05026ed2e580a | 31.020619 | 160 | 0.474565 | 4.430813 | false | false | false | false |
mlburggr/OverRustleiOS | OverRustleiOS/ViewController.swift | 1 | 12080 | //
// ViewController.swift
// OverRustleiOS
//
// Created by Maxwell Burggraf on 8/8/15.
// Copyright (c) 2015 Maxwell Burggraf. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
import SocketIO
class ViewController: UIViewController, UIWebViewDelegate, UIGestureRecognizerDelegate {
func gestureRecognizer(_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
return true
}
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var webView: UIWebView!
var player = MPMoviePlayerController()
var customStreamTextField: UITextField!
var currentStream : String = ""
@IBOutlet weak var backButton: UIButton!
var socket = SocketIOClient(socketURL: "http://api.overrustle.com", options: ["nsp": "/streams"])
var api_data:NSDictionary = NSDictionary()
var isFullWidthPlayer: Bool = true
func webViewDidFinishLoad(webView: UIWebView) {
if(webView.request?.URL != NSURL(string: "http://www.destiny.gg/embed/chat")){
print("showing button", terminator: "")
backButton.bringSubviewToFront(self.view)
backButton.hidden = false
} else {
backButton.hidden = true
}
}
@IBAction func stopVideoPressed(sender: AnyObject) {
player.stop()
currentStream = ""
}
@IBAction func backPressed(sender: AnyObject) {
webView.goBack()
}
@IBAction func strimsPressed(sender: AnyObject) {
var title = "Select Strim"
if let viewers = api_data["viewercount"] as? Int {
print("Rustlers:", viewers, terminator: "")
title = "\(viewers) Rustlers Watching"
}
var list = NSArray()
if let stream_list = api_data["stream_list"] as? NSArray {
list = stream_list
print("Stream List", stream_list, terminator: "")
}
let rustleActionSheet = UIAlertController(title: title, message: nil, preferredStyle:UIAlertControllerStyle.ActionSheet)
rustleActionSheet.popoverPresentationController?.sourceView = self.view
rustleActionSheet.popoverPresentationController?.sourceRect = CGRectMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0, 1.0, 1.0)
// var button_customStream_title = "Enter custom stream..."
// let action = UIAlertAction(title:button_customStream_title, style:UIAlertActionStyle.Default, handler:{ action in
// println("Enter custom strim button loaded")
//
// var alert = UIAlertController(title: "Enter custom stream", message: "", preferredStyle: UIAlertControllerStyle.Alert)
// //alert.addAction(UIAlertAction(title: "Enter", style: UIAlertActionStyle.Default, handler: nil))
// alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
// alert.addAction(UIAlertAction(title: "UStream", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("ustream", channel: self.customStreamTextField.text)
// }))
// alert.addAction(UIAlertAction(title: "Twitch", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("twitch", channel: self.customStreamTextField.text)
// }))
// alert.addAction(UIAlertAction(title: "YouTube", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("youtube", channel: self.customStreamTextField.text)
// }))
// alert.addAction(UIAlertAction(title: "Hitbox", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("hitbox", channel: self.customStreamTextField.text)
// }))
// alert.addAction(UIAlertAction(title: "Azubu", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("azubu", channel: self.customStreamTextField.text)
// }))
// alert.addAction(UIAlertAction(title: "MLG", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
// self.openStream("mlg", channel: self.customStreamTextField.text)
// }))
// alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
// self.customStreamTextField = textField;
// textField.placeholder = "Enter stream title"
// })
// self.presentViewController(alert, animated: true, completion: nil)
// })
// rustleActionSheet.addAction(action)
var i : Int
for i = 0; i<list.count; i++ {
let stream = list[i] as! NSDictionary
if let channel = stream["channel"] as? String, let platform = stream["platform"] as? String, let imageURLString = stream["image_url"] as? String {
var button_title = "\(channel) on \(platform)"
if let name = stream["name"] as? String {
button_title = "\(name) via \(button_title)"
}
let action = UIAlertAction(title:button_title, style:UIAlertActionStyle.Default, handler:{ action in
print("loading", channel, "from", platform)
self.openStream(platform, channel: channel)
})
if let imageURL = NSURL(string: imageURLString) {
if let imageData = NSData(contentsOfURL: imageURL) {
let image = UIImage(data: imageData, scale: 10)
let originalImage = image?.imageWithRenderingMode(.AlwaysOriginal)
action.setValue(originalImage, forKey: "image")
}
}
rustleActionSheet.addAction(action)
}
}
rustleActionSheet.addAction(UIAlertAction(title:"Cancel", style:UIAlertActionStyle.Cancel, handler:nil))
presentViewController(rustleActionSheet, animated:true, completion:nil)
}
func openStream(platform:String, channel:String) {
currentStream = channel
var s = RustleStream()
switch platform {
case "ustream":
s = UStream()
case "twitch":
s = Twitch()
case "youtube":
s = YouTubeLive()
case "hitbox":
s = Hitbox()
case "azubu":
s = Azubu()
case "mlg":
s = MLG()
default:
print(platform, "is not supported right now")
}
s.channel = channel
player.contentURL = s.getStreamURL()
player.play()
}
func closeSocket() {
self.socket.disconnect()
}
func openSocket() {
self.socket.connect()
}
func addHandlers() {
self.socket.onAny {
print("Got event: \($0.event)")
}
self.socket.on("strims") { data, ack in
print("in strims")
if let new_api_data = data[0] as? NSDictionary {
self.api_data = new_api_data
if let viewers = self.api_data["viewercount"] as? Int {
print("Rustlers:", viewers)
}
if let stream_list = self.api_data["stream_list"] as? NSArray {
print("Good Stream List")
}
}
}
}
func handleTap(sender: UITapGestureRecognizer) {
print("tapped video")
if sender.state == .Ended {
// handling code
fullscreenButtonClick()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.addHandlers()
self.socket.connect()
backButton.hidden = true
let chatURL = NSURL(string: "http://www.destiny.gg/embed/chat")
let chatURLRequestObj = NSURLRequest(URL: chatURL!)
webView.loadRequest(chatURLRequestObj)
var testStream = Twitch()
testStream.channel = "vgbootcamp"
let videoStreamURL = testStream.getStreamURL()
player = MPMoviePlayerController(contentURL: videoStreamURL)
player.controlStyle = MPMovieControlStyle.None
let anyTap = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
anyTap.delegate = self
player.view.addGestureRecognizer(anyTap)
//The player takes up 40% of the screen
//(this can (and probably should be) changed later
player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40)
self.view.addSubview(player.view)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "fullscreenButtonClick", name: MPMoviePlayerDidEnterFullscreenNotification, object: nil)
self.isFullWidthPlayer = true
player.play()
}
func fullscreenButtonClick(){
print("fullscreen button clicked")
if(isFullWidthPlayer){
//make the player a mini player
//self.player.setFullscreen(false, animated: true)
//self.player.controlStyle = MPMovieControlStyle.Fullscreen
player.view.frame = CGRectMake(self.view.frame.size.width * 0.50, 0, self.view.frame.size.width * 0.50, self.view.frame.size.height * 0.20)
isFullWidthPlayer = false
} else {
//make the mini player a full width player again
//self.player.setFullscreen(false, animated: true)
player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40)
//self.player.controlStyle = MPMovieControlStyle.Fullscreen
isFullWidthPlayer = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
let deviceOrientation = UIDevice.currentDevice().orientation
if(UIDeviceOrientationIsLandscape(deviceOrientation)){
if(currentStream == ""){
self.player.view.frame = CGRectMake(0, 0, 0, 0);
} else {
if(isFullWidthPlayer){
self.player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
} else {
self.player.view.frame = CGRectMake( 2 * self.view.frame.size.width / 3, 0, self.view.frame.size.width / 3, self.view.frame.size.width / 3 * 0.5625)
}
}
} else {
if(currentStream == ""){
self.player.view.frame = CGRectMake(0, 0, 0, 0);
} else {
if(isFullWidthPlayer){
self.player.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.40)
webView.frame.size.width = self.view.frame.size.width
webView.frame.origin.x = 0
webView.frame.origin.y = self.view.frame.size.height * 0.40
print("viewDidLayoutSubviews")
//The webview frame is the other 60% of the screen, minus the space that the toolbar takes up
webView.frame.size.height = self.view.frame.size.height * 0.60 - toolbar.frame.size.height
} else {
player.view.frame = CGRectMake(self.view.frame.size.width * 0.50, 0, self.view.frame.size.width * 0.50, self.view.frame.size.height * 0.20)
webView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height - self.toolbar.frame.size.height)
}
}
}
}
}
| mit | 9f61ac338150aca59386dd495ff6340d | 40.655172 | 164 | 0.592964 | 4.58444 | false | false | false | false |
Esri/tips-and-tricks-ios | DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/CustomDynamicLayer/USGSQuakeHeatMapLayer.swift | 1 | 4593 | // Copyright 2015 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
class USGSQuakeHeatMapLayer: AGSDynamicLayer {
var currentJsonOp: AGSJSONRequestOperation!
var points: NSMutableArray!
var bgQueue: NSOperationQueue!
var completion: (() -> Void)!
override init() {
super.init()
// queue to process our operation
self.bgQueue = NSOperationQueue()
// holds on to our earthquake data
self.points = NSMutableArray();
}
func loadWithCompletion(completion:() -> Void) {
self.completion = completion
// go grab JSON from usgs.gov
let url = NSURL(string:"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson")
// create our JSON request operation
self.currentJsonOp = AGSJSONRequestOperation(URL: url)
self.currentJsonOp.target = self
self.currentJsonOp.action = "operation:didSucceedWithResponse:"
self.currentJsonOp.errorAction = "operation:didFailWithError:"
self.bgQueue.addOperation(self.currentJsonOp)
}
// MARK: operation actions
// this will be called when the JSON has been downloaded and parsed
func operation(op:NSOperation, didSucceedWithResponse json:[NSObject:AnyObject]) {
// simple json parsing to create an array of AGSPoints
let features = json["features"] as [NSDictionary]
for featureJSON in features {
let geometry = featureJSON["geometry"] as NSDictionary
let coordinates = geometry["coordinates"] as NSArray
let latitude = coordinates[1].doubleValue
let longitude = coordinates[0].doubleValue
// note use of AGSSpatialReference class methods... these are shared instances so we don't created potentially several hundred (or thousand)
// instances when we have loops like this
let wgs84Pt = AGSPoint(x: longitude, y: latitude, spatialReference: AGSSpatialReference.wgs84SpatialReference())
// project to mercator since we know we will be using a mercator map in this sample
let mercPt = AGSGeometryEngine.defaultGeometryEngine().projectGeometry(wgs84Pt, toSpatialReference: AGSSpatialReference.webMercatorSpatialReference())
self.points.addObject(mercPt)
}
self.layerDidLoad()
if let comp = self.completion {
comp()
}
}
func operation(op: NSOperation, didFailWithError error:NSError) {
self.layerDidFailToLoad(error)
if let comp = self.completion {
comp()
}
}
// MARK: Dynamic layer overrides
override var fullEnvelope: AGSEnvelope! {
return self.mapView.maxEnvelope
}
override var initialEnvelope: AGSEnvelope! {
get {
return self.mapView.maxEnvelope
}
set {
super.initialEnvelope = initialEnvelope
}
}
override var spatialReference: AGSSpatialReference! {
return self.mapView.spatialReference;
}
func requestImage(width w:NSInteger, height h:NSInteger, envelope env:AGSEnvelope, timeExtent te:AGSTimeExtent) {
// if we are currently processing a current draw request we want to make sure we cancel it
// because the user may have move away from that extent...
self.bgQueue.cancelAllOperations()
// kickoff an operation to draw our layer so we don't block the main thread.
// This operation is responsible for creating a UIImage for the given envelope
// and setting it on the layer
var drawOp = USGSQuakeHeatMapDrawingOperation()
drawOp.envelope = env;
drawOp.rect = CGRectMake(0, 0, CGFloat(w), CGFloat(h));
drawOp.layer = self;
drawOp.points = self.points;
// // add our drawing operation to the queue
self.bgQueue.addOperation(drawOp)
}
}
| apache-2.0 | 5b2c45b0f11b892a19cac469922587dd | 35.744 | 162 | 0.652079 | 4.880978 | false | false | false | false |
bryzinski/skype-ios-app-sdk-samples | BankingAppSwift/BankingAppSwift/AccountTableViewController.swift | 1 | 1354 | //+----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Module name: AccountTableViewController.swift
//----------------------------------------------------------------
import UIKit
class AccountTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "MMMM dd, yyyy"
self.navigationItem.prompt = dateFormatter.string(from: Date())
}
@IBAction func logOff(_ sender: AnyObject) {
self.parent?.navigationController?.setNavigationBarHidden(false, animated: false)
self.parent?.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 287fcc7dec8ba20525ea7e24256459fb | 35.594595 | 113 | 0.643279 | 6.327103 | false | false | false | false |
ArtSabintsev/Siren | Sources/Managers/APIManager.swift | 1 | 5673 | //
// APIManager.swift
// Siren
//
// Created by Arthur Sabintsev on 11/24/18.
// Copyright © 2018 Sabintsev iOS Projects. All rights reserved.
//
import Foundation
/// APIManager for Siren
public struct APIManager {
/// Constants used in the `APIManager`.
private struct Constants {
/// Constant for the `bundleId` parameter in the iTunes Lookup API request.
static let bundleID = "bundleId"
/// Constant for the `country` parameter in the iTunes Lookup API request.
static let country = "country"
/// Constant for the `lang` parameter in the iTunes Lookup API request.
static let language = "lang"
/// Constant for the `entity` parameter in the iTunes Lookup API reqeust.
static let entity = "entity"
/// Constant for the `entity` parameter value when performing a tvOS iTunes Lookup API reqeust.
static let tvSoftware = "tvSoftware"
}
/// Return results or errors obtained from performing a version check with Siren.
typealias CompletionHandler = (Result<APIModel, KnownError>) -> Void
/// The Bundle ID for the your application. Defaults to "Bundle.main.bundleIdentifier".
let bundleID: String?
/// The region or country of an App Store in which the app is available.
let country: AppStoreCountry
/// The language for the localization of App Store responses.
let language: String?
/// Initializes `APIManager` to the region or country of an App Store in which the app is available.
/// By default, all version check requests are performed against the US App Store and the language of the copy/text is returned in English.
/// - Parameters:
/// - country: The country for the App Store in which the app is available.
/// - language: The locale to use for the App Store notes. The default result the API returns is equivalent to passing "en_us", so passing `nil` is equivalent to passing "en_us".
/// - bundleID: The bundleID for your app. Defaults to `Bundle.main.bundleIdentifier`. Passing `nil` will throw a `missingBundleID` error.
public init(country: AppStoreCountry = .unitedStates, language: String? = nil, bundleID: String? = Bundle.main.bundleIdentifier) {
self.country = country
self.language = language
self.bundleID = bundleID
}
/// The default `APIManager`.
///
/// The version check is performed against the US App Store.
public static let `default` = APIManager()
}
extension APIManager {
/// Convenience initializer that initializes `APIManager` to the region or country of an App Store in which the app is available.
/// If nil, version check requests are performed against the US App Store.
///
/// - Parameter countryCode: The raw country code for the App Store in which the app is available.
public init(countryCode: String?) {
self.init(country: .init(code: countryCode))
}
/// Creates and performs a URLRequest against the iTunes Lookup API.
///
/// - returns APIModel: The decoded JSON as an instance of APIModel.
func performVersionCheckRequest() async throws -> APIModel {
guard bundleID != nil else {
throw KnownError.missingBundleID
}
do {
let url = try makeITunesURL()
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30)
let (data, response) = try await URLSession.shared.data(for: request)
return try processVersionCheckResults(withData: data, response: response)
} catch {
throw error
}
}
/// Parses and maps the the results from the iTunes Lookup API request.
///
/// - Parameters:
/// - data: The JSON data returned from the request.
/// - response: The response metadata returned from the request.
private func processVersionCheckResults(withData data: Data?, response: URLResponse?) throws -> APIModel {
guard let data = data else {
throw KnownError.appStoreDataRetrievalFailure(underlyingError: nil)
}
do {
let apiModel = try JSONDecoder().decode(APIModel.self, from: data)
guard !apiModel.results.isEmpty else {
throw KnownError.appStoreDataRetrievalEmptyResults
}
return apiModel
} catch {
throw KnownError.appStoreJSONParsingFailure(underlyingError: error)
}
}
/// Creates the URL that points to the iTunes Lookup API.
///
/// - Returns: The iTunes Lookup API URL.
/// - Throws: An error if the URL cannot be created.
private func makeITunesURL() throws -> URL {
var components = URLComponents()
components.scheme = "https"
components.host = "itunes.apple.com"
components.path = "/lookup"
var items: [URLQueryItem] = [URLQueryItem(name: Constants.bundleID, value: bundleID)]
#if os(tvOS)
let tvOSQueryItem = URLQueryItem(name: Constants.entity, value: Constants.tvSoftware)
items.append(tvOSQueryItem)
#endif
if let countryCode = country.code {
let item = URLQueryItem(name: Constants.country, value: countryCode)
items.append(item)
}
if let language = language {
let item = URLQueryItem(name: Constants.language, value: language)
items.append(item)
}
components.queryItems = items
guard let url = components.url, !url.absoluteString.isEmpty else {
throw KnownError.malformedURL
}
return url
}
}
| mit | 5a223eb38c851ff4a8a00d838e736d40 | 39.22695 | 183 | 0.656559 | 4.83959 | false | false | false | false |
thyagostall/ios-playground | StopWatch/StopWatch/CountdownTimerViewController.swift | 1 | 3556 | //
// CountdownTimerViewController.swift
// StopWatch
//
// Created by Thyago on 1/7/16.
// Copyright © 2016 Thyago. All rights reserved.
//
import UIKit
class CountdownTimerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var timePicker: UIPickerView!
private let HOUR_COLUMN = 0;
private let MINUTE_COLUMN = 1;
private let SECOND_COLUMN = 2;
private var hour = 0;
private var minute = 0;
private var second = 0;
private var initialHour = 0;
private var initialMinute = 0;
private var initialSecond = 0;
private var timer: NSTimer?
@IBOutlet var startButton: UIBarButtonItem!
@IBOutlet var stopButton: UIBarButtonItem!
@IBOutlet var resetButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
startButton.enabled = true
stopButton.enabled = false
resetButton.enabled = false
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return 100
} else {
return 60
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let formatter = NSNumberFormatter()
formatter.minimumIntegerDigits = 2
return formatter.stringFromNumber(row)
}
func update() {
second--
if second < 0 {
second = 59
minute--
}
if minute < 0 {
minute = 59
hour--
}
if hour < 0 {
hour = 0
minute = 0
second = 0
stop(nil)
}
timePicker.selectRow(hour, inComponent: HOUR_COLUMN, animated: true)
timePicker.selectRow(minute, inComponent: MINUTE_COLUMN, animated: true)
timePicker.selectRow(second, inComponent: SECOND_COLUMN, animated: true)
}
@IBAction func start(sender: UIBarButtonItem?) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
timePicker.userInteractionEnabled = false
hour = timePicker.selectedRowInComponent(HOUR_COLUMN)
minute = timePicker.selectedRowInComponent(MINUTE_COLUMN)
second = timePicker.selectedRowInComponent(SECOND_COLUMN)
initialHour = hour
initialMinute = minute
initialSecond = second
startButton.enabled = false
stopButton.enabled = true
resetButton.enabled = true
}
@IBAction func stop(sender: UIBarButtonItem?) {
timer?.invalidate()
timePicker.userInteractionEnabled = true
startButton.enabled = true
stopButton.enabled = false
resetButton.enabled = false
}
@IBAction func reset(sender: UIBarButtonItem?) {
timePicker.selectRow(initialHour, inComponent: HOUR_COLUMN, animated: true)
timePicker.selectRow(initialMinute, inComponent: MINUTE_COLUMN, animated: true)
timePicker.selectRow(initialSecond, inComponent: SECOND_COLUMN, animated: true)
timer?.invalidate()
timePicker.userInteractionEnabled = true
startButton.enabled = true
stopButton.enabled = false
resetButton.enabled = false
}
}
| gpl-2.0 | ab3036d9363351a97b45b6466ca9d320 | 28.139344 | 121 | 0.622504 | 5.258876 | false | false | false | false |
fgengine/quickly | Quickly/ViewControllers/Push/Animation/QPushViewControllerAnimation.swift | 1 | 2228 | //
// Quickly
//
public final class QPushViewControllerPresentAnimation : IQPushViewControllerFixedAnimation {
public var duration: TimeInterval
public init(duration: TimeInterval = 0.2) {
self.duration = duration
}
public func animate(
viewController: IQPushViewController,
animated: Bool,
complete: @escaping () -> Void
) {
viewController.layoutIfNeeded()
if animated == true {
viewController.willPresent(animated: animated)
UIView.animate(withDuration: self.duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
viewController.state = .show
viewController.layoutIfNeeded()
}, completion: { (completed: Bool) in
viewController.didPresent(animated: animated)
complete()
})
} else {
viewController.state = .show
viewController.willPresent(animated: animated)
viewController.didPresent(animated: animated)
complete()
}
}
}
public final class QPushViewControllerDismissAnimation : IQPushViewControllerFixedAnimation {
public var duration: TimeInterval
public init(duration: TimeInterval = 0.2) {
self.duration = duration
}
public func animate(
viewController: IQPushViewController,
animated: Bool,
complete: @escaping () -> Void
) {
viewController.layoutIfNeeded()
if animated == true {
viewController.willDismiss(animated: animated)
UIView.animate(withDuration: self.duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
viewController.state = .hide
viewController.layoutIfNeeded()
}, completion: { (completed: Bool) in
viewController.didDismiss(animated: animated)
complete()
})
} else {
viewController.state = .hide
viewController.willDismiss(animated: animated)
viewController.didDismiss(animated: animated)
complete()
}
}
}
| mit | 88ddabcba65a612750225cf4e6299bcf | 30.380282 | 133 | 0.601885 | 5.683673 | false | false | false | false |
xixi197/XXColorTheme | Classes/Style/RCButtonStyle.swift | 1 | 1221 | //
// RCButtonStyle.swift
// XXColorTheme
//
// Created by xixi197 on 16/1/21.
// Copyright © 2016年 xixi197. All rights reserved.
//
import UIKit
public enum RCButtonStyle {
case MiddleNormal
case MiddleTint
case LargeNormal
case LargeTint
}
public extension RCButton {
convenience init(style: RCButtonStyle) {
self.init(frame: CGRectZero)
styled(style)
}
func styled(style: RCButtonStyle) {
switch style {
case .MiddleNormal:
xx_borderWidth = 1
xx_cornerRadius = 1
xx_normalTintColorStyle = .Light
xx_highlightedTintColorStyle = .Back
case .MiddleTint:
xx_borderWidth = 1
xx_cornerRadius = 1
xx_normalTintColorStyle = .Tint
xx_highlightedTintColorStyle = .Back
case .LargeNormal:
xx_borderWidth = 1
xx_cornerRadius = 2
xx_normalTintColorStyle = .Light
xx_highlightedTintColorStyle = .Back
case .LargeTint:
xx_borderWidth = 1
xx_cornerRadius = 2
xx_normalTintColorStyle = .Tint
xx_highlightedTintColorStyle = .Back
}
}
}
| mit | 3f27acbddfe885680c7525bb3f68cff8 | 23.857143 | 51 | 0.587849 | 4.429091 | false | false | false | false |
gregomni/swift | test/SILOptimizer/Inputs/cross-module/cross-module.swift | 3 | 5496 | import Submodule
@_implementationOnly import PrivateSubmodule
@_implementationOnly import PrivateCModule
private enum PE<T> {
case A
case B(T)
}
public struct Container {
private final class Base {
}
@inline(never)
public func testclass<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testclass_gen<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
public func testenum<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testenum_gen<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
public init() { }
}
private class PrivateBase<T> {
var t: T
func foo() -> Int { return 27 }
init(_ t: T) { self.t = t }
}
private class PrivateDerived<T> : PrivateBase<T> {
override func foo() -> Int { return 28 }
}
@inline(never)
private func getClass<T>(_ t : T) -> PrivateBase<T> {
return PrivateDerived<T>(t)
}
@inline(never)
public func createClass<T>(_ t: T) -> Int {
return getClass(t).foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func createClass_gen<T>(_ t: T) -> Int {
return getClass(t).foo()
}
private struct PrivateError: Error { }
public func returnPrivateError<V>(_ v: V) -> Error {
return PrivateError()
}
struct InternalError: Error { }
public func returnInternalError<V>(_ v: V) -> Error {
return InternalError()
}
private protocol PrivateProtocol {
func foo() -> Int
}
open class OpenClass<T> {
public init() { }
@inline(never)
fileprivate func bar(_ t: T) {
print(t)
}
}
extension OpenClass {
@inline(never)
public func testit() -> Bool {
return self is PrivateProtocol
}
}
@inline(never)
public func checkIfClassConforms<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func checkIfClassConforms_gen<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
public func callClassMethod<T>(_ t: T) {
let k = OpenClass<T>()
k.bar(t)
}
extension Int : PrivateProtocol {
func foo() -> Int { return self }
}
@inline(never)
@_semantics("optimize.no.crossmodule")
private func printFooExistential(_ p: PrivateProtocol) {
print(p.foo())
}
@inline(never)
private func printFooGeneric<T: PrivateProtocol>(_ p: T) {
print(p.foo())
}
@inline(never)
public func callFoo<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFoo_gen<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
fileprivate protocol PrivateProto {
func foo()
}
public class FooClass: PrivateProto {
func foo() {
print(321)
}
}
final class Internalclass {
public var publicint: Int = 27
}
final public class Outercl {
var ic: Internalclass = Internalclass()
}
@inline(never)
public func classWithPublicProperty<T>(_ t: T) -> Int {
return createInternal().ic.publicint
}
@inline(never)
func createInternal() -> Outercl {
return Outercl()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
fileprivate func callProtocolFoo<T: PrivateProto>(_ t: T) {
t.foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFooViaConformance<T>(_ t: T) {
let c = FooClass()
callProtocolFoo(c)
}
@inline(never)
public func callGenericSubmoduleFunc<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callGenericSubmoduleFunc_gen<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
public func genericClosure<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func genericClosure_gen<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
struct Abc {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Myclass {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Derived : Myclass {
override var x: Int { return 29 }
override var y: Int { return 30 }
}
@inline(never)
func getStructKeypath<T>(_ t: T) -> KeyPath<Abc, Int> {
return \Abc.x
}
@inline(never)
public func useStructKeypath<T>(_ t: T) -> Int {
let abc = Abc()
return abc[keyPath: getStructKeypath(t)]
}
@inline(never)
func getClassKeypath<T>(_ t: T) -> KeyPath<Myclass, Int> {
return \Myclass.x
}
@inline(never)
public func useClassKeypath<T>(_ t: T) -> Int {
let c = Derived()
return c[keyPath: getClassKeypath(t)]
}
@inline(never)
func unrelated<U>(_ u: U) {
print(u)
}
@inline(never)
public func callUnrelated<T>(_ t: T) -> T {
unrelated(43)
return t
}
public func callImplementationOnlyType<T>(_ t: T) -> T {
let p = PrivateStr(i: 27)
print(p.test())
return t
}
public func callImplementationOnlyFunc<T>(_ t: T) -> Int {
return privateFunc()
}
public func callCImplementationOnly<T>(_ t: T) -> Int {
return Int(privateCFunc())
}
public let globalLet = 529387
public struct StructWithClosure {
public static let c = { (x: Int) -> Int in return x }
}
public func getEmptySet() -> Set<Int> {
return Set()
}
| apache-2.0 | 752990e7810816f8317ce1cb1433540f | 17.567568 | 59 | 0.656114 | 3.112118 | false | false | false | false |
jianghongbing/APIReferenceDemo | Swift/Syntax/String.playground/Contents.swift | 1 | 7973 | //: Playground - noun: a place where people can play
import UIKit
//String: 由一个或者多个字符组成的有序集合
//1.字符串的构造
let wuhan = "wuhan" //字面量构造
// 通过构造方法来构造字符串
let charArray:[Character] = ["w", "u", "h", "a", "n"]
let cityName = String(charArray)
//构造多个重复的字符串组成新的字符串
let repeatString = String(repeating: "wuhan", count: 5)
//通过格式化来构建字符串
let formatString = String(format:"name is %@, age is %ld", "xiaoming", 12)
//2.多行字符串的构造,使用""""""或者在字符串中间插入换行符来构造
let multiLineString = """
first line
second line
third line
"""
let secondMultiLineString = "first line\nsecond line\nthird line"
print(multiLineString, secondMultiLineString)
//3.通过+,+=来拼接字符串
let firstName = "John"
let secondName = "Smith"
let fullName = firstName + secondName
var name = firstName
name += secondName
//4.字符串的插值法
let age = 10;
name = "xiaoming"
let xiaomingInfo = "name is \(name), age is \(age)"
//5.字符串常用的属性
let isEmpty = xiaomingInfo.isEmpty //判断字符串是否为空
let count = firstName.count //判断字符的个数
let upperString = wuhan.uppercased() //转换成大写
let lowerString = upperString.lowercased() //转换成小写
let appleURL = "https://www.apple.com"
appleURL.hasPrefix("https") //是否包含某个前缀
appleURL.hasSuffix("com") //是否包含某个后缀
//6.字符串中的字符的遍历和枚举器
//let charactView = wuhan.
for char in wuhan {
print(char)
}
wuhan.forEach { char in
print(char)
}
let greeting = "你好, Swift"
let enumeratedSequence = greeting.enumerated() //字符的位置和字符组成一对
enumeratedSequence.forEach { (index, char) in
print("index:\(index), char: \(char)")
}
//var iterator = greeting.makeIterator() //迭代器
//while iterator.next() != nil {
// print(iterator.next() ?? "迭代完成")
//}
let underestimatedCount = greeting.underestimatedCount
//7.字符串中的Unicode的呈现形式
let utf8 = greeting.utf8 //字符串以UTF8编码的形式所呈现的码点的集合,即每一个码点的范围为0~127
let utf16 = greeting.utf16 //字符串以UTF16编码的形式所呈现的码点的集合 0~2^16-1
let unicodeScalarView = greeting.unicodeScalars //字符串以Unicode标量编码的形式所呈现的码点的集合 0~2^21-1
for utf8CodePoint in utf8 {
print(utf8CodePoint)
}
for utf16CodePoint in utf16 {
print(utf16CodePoint)
}
for unicodeScalar in unicodeScalarView {
print(unicodeScalar, unicodeScalar.value)
}
//6.字符串的拼接
var string = "test"
string.append("A")
string.append("abc")
var appendString = string.appending("hehehe")
appendString = string.appendingFormat("append age is %ld", 15)
print(string, appendString)
//appendString.reserveCapacity(10) //使用指定的储存空间来储存字符串,如果大小小于字符串需要的最小空间,则使用该字符串需要的最少的空间
//7.字符串的index, 字符在字符串中的位置
string = "test"
let startIndex = string.startIndex
let endIndex = string.endIndex;
let beforeIndex = string.index(before: endIndex)
let afterIndex = string.index(after: startIndex)
let distanceIndex = string.index(startIndex, offsetBy: 1)
let indexDistance = string.distance(from: startIndex, to: endIndex)
//7.字符串的插入
string.insert("好", at: startIndex)
string.insert(contentsOf: "haha", at: endIndex)
//7.字符串的移除, 如果移除的index,超过了字符串的最后一个字符的index,会产生运行时错误
string.remove(at: startIndex) //移除指定位置的字符
string.removeLast() //移除第一个字符
string.removeFirst() //移除最后一个字符
string.removeSubrange(string.startIndex ..< string.index(string.startIndex, offsetBy: 2)) //移除指定范围的字符
string.removeLast(2) //移除后两个字符
string.removeFirst(2) //移除前两个字符
string.removeAll() //移除所有的字符
string = "testtestAAAbbbscd"
var subString = string.dropFirst() //移除第一个字符,并返回移除第一个字符后的字符串
subString = string.dropFirst(2) //移除前几个字符,并且返回移除后的字符串
subString = string.dropLast()
subString = string.dropLast(3)
//通过闭包的形式来移除某个字符
subString = string.drop(while: { (char) -> Bool in
return char == "t"
})
print(subString)
//字符串过滤,过滤所有某个出现的字符
let filterString = string.filter({ (char) -> Bool in
return char != "b"
})
print(filterString)
//8.SubString:Swift为了优化字符串的性能,使用一个SubString的类型,表示某一个字符串的子字符串,其指向的内存和父字符串共享相同字符的内存,来减小内存的分配,可以通过String的构造方法将subString转换成字符串,subString和字符串有着一样的接口
//通过range来获取subString
subString = string[string.startIndex ... string.index(string.startIndex, offsetBy: 5)]
subString = string.prefix(8) //获取字符的前8个字符的字符串
subString = string.prefix(through: string.index(string.startIndex, offsetBy: 3)) //获取字符串开始到自定位置的字符(包含最后位置)所组成的字符串
subString = string.prefix(upTo: string.index(string.startIndex, offsetBy: 3)) //获取字符串开始到自定位置的字符(不包含最后位置)所组成的字符串
//返回在某个字符之前的字符串
subString = string.prefix(while: { (char) -> Bool in
return char == "c"
})
print(subString)
subString = string.suffix(10) //返回后10字符组成字符串
//subString = string.suffix(from: <#T##String.Index#>)
//subString转换成字符串
let convertString = String(subString)
//9.字符串的比较
let isEqual = "aA" == "Aa"
let isLessThan = "aA" < "Aa"
let isLessThanOrEqual = "abc" <= "aBC"
let isGreaterThan = "abc" > "aBC"
let isGreaterThanOrEqual = "abc" >= "ABC"
//10.字符相关方法
var isContains = "abc".contains("a") //是否包含某个字符
isContains = "abc".contains(where: { (char) -> Bool in
return char == "A"
})
print(isContains)
//根据提供的条件找出第一个匹配的字符
if let firstCharacter = "abc".first(where: { (char) -> Bool in
return char == "b" || char == "B"
}) {
print(firstCharacter)
}
//获取某个字符的index
let charIndex = "abcd".index(of: "d")
if charIndex == nil {
print("not found")
} else {
print(charIndex!)
}
//min max字符
string = "dfefwaw"
if let min = string.min(), let max = string.max() {
print("min:\(min), max:\(max)")
}
let firstChar = string.first
let lastChar = string.last
let indexChar = string[string.index(string.startIndex, offsetBy: 2)] //通过下标获取某个位置的char
//11.sort
var characters = string.sorted() //升序排列
characters = string.sorted(by: { (charOne, charTwo) -> Bool in
return charOne >= charTwo //按照指定的顺序排列
})
print(characters)
characters = string.reversed() //翻转
//12.高阶函数
//12.1 map函数,将string中的char,转换成其他的值,将对应的值的集合并将其返回
let hashValueArray = string.map({ (char) -> Int in
return char.hashValue
})
print(hashValueArray)
//13.通过reduce函数翻转字符串
let reversedString = string.reduce("") { (x, y) -> String in
// return x.appending(String(y))
var string = x
string.insert(y, at: string.endIndex)
return string
}
print(reversedString)
//14.分片splite
let splitString = "wuhan, beijing, shanghai, shenzhen, chengdu, hanzhou"
var stringArray = splitString.split(separator: ",")
stringArray = splitString.split(separator: ",", maxSplits: 2) //最大分几片
stringArray = splitString.split(whereSeparator: { (char) -> Bool in
return char == ","
})
print(stringArray)
//15. String和NSString之间的互换
var nsString:NSString = "hello, swift"
var swiftString = nsString as String
nsString = swiftString as NSString
| mit | 548f1f6269a93929efb3942712c338af | 28.67757 | 143 | 0.732326 | 3.080019 | false | false | false | false |
petester42/ReactiveDataSource | Example/CollectionView/CollectionViewController.swift | 1 | 1407 | import UIKit
import ReactiveDataSource
import ReactiveCocoa
class CollectionViewController: UICollectionViewController {
/// Make sure that the dataSource is a strong reference
/// UICollectionView's dataSource property is marked weak
/// so it will be deallocated if not retained properly
var model: CollectionViewModel?
override func viewDidLoad() {
super.viewDidLoad()
guard let collectionView = collectionView else {
return
}
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 10
layout.itemSize = CGSizeMake(CGRectGetWidth(collectionView.frame)/2 - layout.sectionInset.left - layout.minimumInteritemSpacing/2, CGRectGetWidth(collectionView.frame)/2 - layout.sectionInset.top - layout.minimumLineSpacing/2)
model = CollectionViewModel()
collectionView.rac_dataSource = model?.dataSource
collectionView.rac_delegate = model?.delegate
collectionView.collectionViewLayout = layout
model?.dataSource.pushbackSignal.observeNext(pushbackAction())
model?.delegate.selectionSignal.observeNext(selectionAction())
}
deinit {
print("controller deinit")
}
}
| mit | f33fb99225bd36cf00a4b6f80a3d1b1b | 36.026316 | 234 | 0.68941 | 5.8625 | false | false | false | false |
einsteinx2/iSub | Classes/UI/Reusable/ItemViewModel.swift | 1 | 21900 | //
// ItemViewModel.swift
// iSub
//
// Created by Benjamin Baron on 2/1/16.
// Copyright © 2016 Ben Baron. All rights reserved.
//
import Foundation
protocol ItemViewModelDelegate {
func itemsChanged(viewModel: ItemViewModel)
func loadingFinished(viewModel: ItemViewModel)
func loadingError(_ error: String, viewModel: ItemViewModel)
func presentActionSheet(_ actionSheet: UIAlertController, viewModel: ItemViewModel)
func pushViewController(_ viewController: UIViewController, viewModel: ItemViewModel)
}
typealias LoadModelsCompletion = (_ success: Bool, _ error: Error?) -> Void
class ItemViewModel {
// MARK: - Properties -
fileprivate var loader: PersistedItemLoader
var serverId: Int64 {
return loader.serverId
}
var isDownloadQueue: Bool {
if let loader = loader as? CachedPlaylistLoader, loader.playlistId == Playlist.downloadQueuePlaylistId {
return true
}
return false
}
var isRootItemLoader: Bool {
return loader is RootItemLoader
}
var isBrowsingCache: Bool {
return loader is CachedDatabaseLoader
}
var isBrowsingFolder: Bool {
return loader is FolderLoader
}
var isBrowsingAlbum: Bool {
return loader is AlbumLoader
}
var isTopLevelController: Bool {
return false
}
fileprivate(set) var artistSortOrder = ArtistSortOrder.name
fileprivate(set) var albumSortOrder = AlbumSortOrder.year
fileprivate(set) var songSortOrder = SongSortOrder.track
var isShowTrackNumbers = true
var delegate: ItemViewModelDelegate?
var navigationTitle: String?
var mediaFolderId: Int64? {
didSet {
if var rootItemLoader = loader as? RootItemLoader {
rootItemLoader.mediaFolderId = mediaFolderId
}
}
}
var shouldSetupRefreshControl: Bool {
return !isBrowsingCache
}
fileprivate(set) var rootItem: Item?
fileprivate(set) var items = [Item]()
fileprivate(set) var folders = [Folder]()
fileprivate(set) var artists = [Artist]()
fileprivate(set) var albums = [Album]()
fileprivate(set) var songs = [Song]()
fileprivate(set) var playlists = [Playlist]()
fileprivate(set) var isFiltered = false
fileprivate(set) var filteredItems = [Item]()
fileprivate(set) var filteredFolders = [Folder]()
fileprivate(set) var filteredArtists = [Artist]()
fileprivate(set) var filteredAlbums = [Album]()
fileprivate(set) var filteredSongs = [Song]()
fileprivate(set) var filteredPlaylists = [Playlist]()
fileprivate(set) var songsDuration = 0
fileprivate(set) var sectionIndexes = [SectionIndex]()
fileprivate(set) var sectionIndexesSection = -1
// MARK - Lifecycle -
init(loader: PersistedItemLoader, title: String? = nil) {
self.loader = loader
self.rootItem = loader.associatedItem
self.navigationTitle = title //?? loader.associatedItem?.itemName
if let folder = loader.associatedItem as? Folder {
self.songSortOrder = folder.songSortOrder
} else if let artist = loader.associatedItem as? Artist {
self.albumSortOrder = artist.albumSortOrder
} else if let album = loader.associatedItem as? Album {
self.songSortOrder = album.songSortOrder
} else if loader is RootItemLoader {
self.artistSortOrder = SavedSettings.si.rootArtistSortOrder
self.albumSortOrder = SavedSettings.si.rootAlbumSortOrder
}
}
// MARK - Loading -
@discardableResult func loadModelsFromDatabase(notify: Bool = true) -> Bool {
let success = loader.loadModelsFromDatabase()
if (success) {
self.processModels(notify: notify)
}
return success
}
func loadModelsFromWeb(completion: LoadModelsCompletion? = nil) {
if loader.state != .loading {
loader.completionHandler = { success, error, loader in
completion?(success, error)
if success {
// May have some false positives, but prevents UI pauses
if self.items.count != self.loader.items.count {
self.processModels(notify: false)
}
self.delegate?.loadingFinished(viewModel: self)
} else {
let errorString = error == nil ? "Unknown error" : error!.localizedDescription
self.delegate?.loadingError(errorString, viewModel: self)
}
}
loader.start()
}
}
func cancelLoad() {
loader.cancel()
}
func processModels(notify: Bool = true) {
// Reset models
folders = []
artists = []
albums = []
songs = []
playlists = []
items = loader.items
for item in items {
switch item {
case let item as Folder: folders.append(item)
case let item as Artist: artists.append(item)
case let item as Album: albums.append(item)
case let item as Song: songs.append(item)
case let item as Playlist: playlists.append(item)
default: assertionFailure("WHY YOU NO ITEM?")
}
}
var duration = 0
for song in songs {
if let songDuration = song.duration {
duration = duration + Int(songDuration)
}
}
songsDuration = duration
sortAll(notify: notify)
}
func filterModels(filterString: String, notify: Bool = true) {
guard filterString.count > 0 else {
clearFilter()
return
}
clearFilter(notify: false)
isFiltered = true
let lowercaseFilteredString = filterString.lowercased()
filteredItems = items.filter({$0.itemName.lowercased().contains(lowercaseFilteredString)})
for item in filteredItems {
switch item {
case let item as Folder: filteredFolders.append(item)
case let item as Artist: filteredArtists.append(item)
case let item as Album: filteredAlbums.append(item)
case let item as Song: filteredSongs.append(item)
case let item as Playlist: filteredPlaylists.append(item)
default: assertionFailure("WHY YOU NO ITEM?")
}
}
if notify {
delegate?.itemsChanged(viewModel: self)
}
}
func clearFilter(notify: Bool = true) {
filteredItems = []
filteredFolders = []
filteredArtists = []
filteredAlbums = []
filteredSongs = []
filteredPlaylists = []
isFiltered = false
if notify {
delegate?.itemsChanged(viewModel: self)
}
}
fileprivate func createSectionIndexes() {
let minAmountForIndexes = 50
if folders.count >= minAmountForIndexes {
sectionIndexes = SectionIndex.sectionIndexes(forItems: folders)
sectionIndexesSection = 0
} else if artists.count >= minAmountForIndexes {
if artistSortOrder == .name {
sectionIndexes = SectionIndex.sectionIndexes(forItems: artists)
} else {
sectionIndexes = SectionIndex.sectionIndexes(forCount: artists.count)
}
sectionIndexesSection = 1
} else if albums.count >= minAmountForIndexes {
if albumSortOrder == .name {
sectionIndexes = SectionIndex.sectionIndexes(forItems: albums)
} else {
sectionIndexes = SectionIndex.sectionIndexes(forCount: albums.count)
}
sectionIndexesSection = 2
} else if songSortOrder != .track && songs.count >= minAmountForIndexes {
switch songSortOrder {
case .title:
sectionIndexes = SectionIndex.sectionIndexes(forItems: songs)
case .artist:
sectionIndexes = SectionIndex.sectionIndexes(forNames: songs.map({$0.artistDisplayName ?? ""}))
case .album:
sectionIndexes = SectionIndex.sectionIndexes(forNames: songs.map({$0.albumDisplayName ?? ""}))
default:
sectionIndexes = SectionIndex.sectionIndexes(forCount: songs.count)
}
sectionIndexesSection = 3
} else {
sectionIndexes = []
sectionIndexesSection = -1
}
}
// MARK - Actions -
func playSong(atIndex index: Int) {
PlayQueue.si.playSongs(songs, playIndex: index)
}
func sortAll(notify: Bool = true) {
var sorted = false
sorted = sorted || sortFolders(createIndexes: false, notify: false)
sorted = sorted || sortArtists(by: artistSortOrder, createIndexes: false, notify: false)
sorted = sorted || sortAlbums(by: albumSortOrder, createIndexes: false, notify: false)
sorted = sorted || sortSongs(by: songSortOrder, createIndexes: false, notify: false)
// TODO: Find a better solution than this folder count hack to decide when to create section indexes
if sorted || folders.count > 0 {
createSectionIndexes()
if notify {
delegate?.itemsChanged(viewModel: self)
}
}
}
@discardableResult func sortFolders(createIndexes: Bool = true, notify: Bool = true) -> Bool {
guard folders.count > 0 else {
return false
}
folders.sort { lhs, rhs -> Bool in
return lhs.name.lowercased() < rhs.name.lowercased()
}
if createIndexes {
createSectionIndexes()
}
if notify {
delegate?.itemsChanged(viewModel: self)
}
return true
}
@discardableResult func sortArtists(by sortOrder: ArtistSortOrder, createIndexes: Bool = true, notify: Bool = true) -> Bool {
artistSortOrder = sortOrder
if isRootItemLoader {
SavedSettings.si.rootArtistSortOrder = sortOrder
}
guard artists.count > 0 else {
return false
}
artists.sort { lhs, rhs -> Bool in
switch sortOrder {
case .name: return lhs.name.lowercased() < rhs.name.lowercased()
case .albumCount: return lhs.albumCount ?? 0 > rhs.albumCount ?? 0
}
}
if createIndexes {
createSectionIndexes()
}
if notify {
delegate?.itemsChanged(viewModel: self)
}
return true
}
@discardableResult func sortAlbums(by sortOrder: AlbumSortOrder, createIndexes: Bool = true, notify: Bool = true) -> Bool {
self.albumSortOrder = sortOrder
if isRootItemLoader {
SavedSettings.si.rootAlbumSortOrder = sortOrder
} else if let artist = loader.associatedItem as? Artist {
artist.albumSortOrder = sortOrder
artist.replace()
}
guard albums.count > 0 else {
return false
}
albums.sort { lhs, rhs -> Bool in
switch sortOrder {
case .year: return lhs.year ?? 0 < rhs.year ?? 0
case .name: return lhs.name.lowercased() < rhs.name.lowercased()
case .artist: return lhs.artist?.name ?? "" < rhs.artist?.name ?? ""
case .genre: return lhs.genre?.name ?? "" < rhs.genre?.name ?? ""
case .songCount: return lhs.songCount ?? 0 < rhs.songCount ?? 0
case .duration: return lhs.duration ?? 0 < rhs.duration ?? 0
}
}
if createIndexes {
createSectionIndexes()
}
if notify {
delegate?.itemsChanged(viewModel: self)
}
return true
}
@discardableResult func sortSongs(by sortOrder: SongSortOrder, createIndexes: Bool = true, notify: Bool = true) -> Bool {
self.songSortOrder = sortOrder
if let folder = loader.associatedItem as? Folder {
folder.songSortOrder = sortOrder
folder.replace()
} else if let album = loader.associatedItem as? Album {
album.songSortOrder = sortOrder
album.replace()
}
guard songs.count > 0 else {
return false
}
songs.sort { lhs, rhs -> Bool in
switch sortOrder {
case .track: return lhs.trackNumber ?? 0 < rhs.trackNumber ?? 0
case .title: return lhs.title.lowercased() < rhs.title.lowercased()
case .artist: return lhs.artistDisplayName?.lowercased() ?? "" < rhs.artistDisplayName?.lowercased() ?? ""
case .album: return lhs.albumDisplayName?.lowercased() ?? "" < rhs.albumDisplayName?.lowercased() ?? ""
}
}
if createIndexes {
createSectionIndexes()
}
if notify {
delegate?.itemsChanged(viewModel: self)
}
return true
}
// MARK: - Action Sheets -
func addCancelAction(toActionSheet actionSheet: UIAlertController) {
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
}
// MARK: Cell
func cellActionSheet(forItem item: Item, indexPath: IndexPath) -> UIAlertController {
let alertController = UIAlertController(title: item.itemName, message: nil, preferredStyle: .actionSheet)
return alertController
}
func addPlayQueueActions(toActionSheet actionSheet: UIAlertController, forItem item: Item, indexPath: IndexPath) {
actionSheet.addAction(UIAlertAction(title: "Play All", style: .default) { action in
if item is Song {
self.playSong(atIndex: indexPath.row)
} else {
let loader = RecursiveSongLoader(item: item)
loader.completionHandler = { success, _, _ in
if success {
PlayQueue.si.playSongs(loader.songs, playIndex: 0)
}
}
loader.start()
}
})
actionSheet.addAction(UIAlertAction(title: "Queue Next", style: .default) { action in
if let song = item as? Song {
PlayQueue.si.insertSongNext(song: song, notify: true)
} else {
let loader = RecursiveSongLoader(item: item)
loader.completionHandler = { success, _, _ in
if success {
for song in loader.songs.reversed() {
PlayQueue.si.insertSongNext(song: song, notify: false)
}
PlayQueue.si.notifyPlayQueueIndexChanged()
}
}
loader.start()
}
})
actionSheet.addAction(UIAlertAction(title: "Queue Last", style: .default) { action in
if let song = item as? Song {
PlayQueue.si.insertSong(song: song, index: PlayQueue.si.songCount, notify: true)
} else {
let loader = RecursiveSongLoader(item: item)
loader.completionHandler = { success, _, _ in
if success {
for song in loader.songs {
PlayQueue.si.insertSong(song: song, index: PlayQueue.si.songCount, notify: false)
}
PlayQueue.si.notifyPlayQueueIndexChanged()
}
}
loader.start()
}
})
}
func addGoToRelatedActions(toActionSheet actionSheet: UIAlertController, forItem item: Item, indexPath: IndexPath) {
if !isBrowsingCache, let song = item as? Song {
if !isBrowsingFolder, let folderId = song.folderId, let mediaFolderId = song.mediaFolderId {
actionSheet.addAction(UIAlertAction(title: "Go to Folder", style: .default) { action in
let loader = FolderLoader(folderId: folderId, serverId: self.serverId, mediaFolderId: mediaFolderId)
if let controller = itemViewController(forLoader: loader) {
self.delegate?.pushViewController(controller, viewModel: self)
}
})
}
if let artistId = song.artistId {
actionSheet.addAction(UIAlertAction(title: "Go to Artist", style: .default) { action in
let loader = ArtistLoader(artistId: artistId, serverId: self.serverId)
if let controller = itemViewController(forLoader: loader) {
self.delegate?.pushViewController(controller, viewModel: self)
}
})
}
if !isBrowsingAlbum, let albumId = song.albumId {
actionSheet.addAction(UIAlertAction(title: "Go to Album", style: .default) { action in
let loader = AlbumLoader(albumId: albumId, serverId: self.serverId)
if let controller = itemViewController(forLoader: loader) {
self.delegate?.pushViewController(controller, viewModel: self)
}
})
}
}
}
// MARK: View Options
func viewOptionsActionSheet() -> UIAlertController {
return UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
}
func addSortOptions(toActionSheet actionSheet: UIAlertController) {
if artists.count > 1 {
actionSheet.addAction(UIAlertAction(title: "Sort Artists", style: .default) { action in
self.delegate?.presentActionSheet(self.sortArtistsActionsSheet(), viewModel: self)
})
}
if albums.count > 1 {
actionSheet.addAction(UIAlertAction(title: "Sort Albums", style: .default) { action in
self.delegate?.presentActionSheet(self.sortAlbumsActionsSheet(), viewModel: self)
})
}
if songs.count > 1 {
actionSheet.addAction(UIAlertAction(title: "Sort Songs", style: .default) { action in
self.delegate?.presentActionSheet(self.sortSongsActionsSheet(), viewModel: self)
})
}
}
func sortArtistsActionsSheet() -> UIAlertController {
let actionSheet = UIAlertController(title: "Sort Artists By:", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Name", style: .default) { action in
self.sortArtists(by: .name)
})
actionSheet.addAction(UIAlertAction(title: "Album Count", style: .default) { action in
self.sortArtists(by: .albumCount)
})
addCancelAction(toActionSheet: actionSheet)
return actionSheet
}
func sortAlbumsActionsSheet() -> UIAlertController {
let actionSheet = UIAlertController(title: "Sort Albums By:", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Year", style: .default) { action in
self.sortAlbums(by: .year)
})
actionSheet.addAction(UIAlertAction(title: "Name", style: .default) { action in
self.sortAlbums(by: .name)
})
actionSheet.addAction(UIAlertAction(title: "Artist", style: .default) { action in
self.sortAlbums(by: .artist)
})
actionSheet.addAction(UIAlertAction(title: "Genre", style: .default) { action in
self.sortAlbums(by: .genre)
})
actionSheet.addAction(UIAlertAction(title: "Song Count", style: .default) { action in
self.sortAlbums(by: .songCount)
})
actionSheet.addAction(UIAlertAction(title: "Duration", style: .default) { action in
self.sortAlbums(by: .duration)
})
addCancelAction(toActionSheet: actionSheet)
return actionSheet
}
func sortSongsActionsSheet() -> UIAlertController {
let actionSheet = UIAlertController(title: "Sort Songs By:", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Track Number", style: .default) { action in
self.sortSongs(by: .track)
})
actionSheet.addAction(UIAlertAction(title: "Title", style: .default) { action in
self.sortSongs(by: .title)
})
actionSheet.addAction(UIAlertAction(title: "Artist", style: .default) { action in
self.sortSongs(by: .artist)
})
actionSheet.addAction(UIAlertAction(title: "Album", style: .default) { action in
self.sortSongs(by: .album)
})
addCancelAction(toActionSheet: actionSheet)
return actionSheet
}
func addDisplayOptions(toActionSheet actionSheet: UIAlertController) {
if songs.count > 0 {
let trackNumbersTitle = self.isShowTrackNumbers ? "Hide Track Numbers" : "Show Track Numbers"
actionSheet.addAction(UIAlertAction(title: trackNumbersTitle, style: .default) { action in
self.isShowTrackNumbers = !self.isShowTrackNumbers
self.delegate?.itemsChanged(viewModel: self)
})
}
}
}
| gpl-3.0 | 4a039e53fe0e84fe4691783a49bfe6eb | 36.116949 | 129 | 0.576784 | 5.080974 | false | false | false | false |
loudnate/LoopKit | LoopKitTests/TemporaryScheduleOverrideTests.swift | 1 | 12283 | //
// TemporaryScheduleOverrideTests.swift
// LoopKitTests
//
// Created by Michael Pangburn on 1/2/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import XCTest
@testable import LoopKit
class TemporaryScheduleOverrideTests: XCTestCase {
let dateFormatter = ISO8601DateFormatter.localTimeDate()
let epsilon = 1e-6
let basalRateSchedule = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.2),
RepeatingScheduleValue(startTime: .hours(6), value: 1.4),
RepeatingScheduleValue(startTime: .hours(20), value: 1.0)
])!
private func date(at time: String) -> Date {
return dateFormatter.date(from: "2019-01-01T\(time):00")!
}
private func basalUpOverride(start: String, end: String) -> TemporaryScheduleOverride {
return TemporaryScheduleOverride(
context: .custom,
settings: TemporaryScheduleOverrideSettings(
unit: .milligramsPerDeciliter,
targetRange: nil,
insulinNeedsScaleFactor: 1.5
),
startDate: date(at: start),
duration: .finite(date(at: end).timeIntervalSince(date(at: start))),
enactTrigger: .local,
syncIdentifier: UUID()
)
}
private func applyingActiveBasalOverride(from start: String, to end: String, on schedule: BasalRateSchedule, referenceDate: Date? = nil) -> BasalRateSchedule {
let override = basalUpOverride(start: start, end: end)
let referenceDate = referenceDate ?? override.startDate
return schedule.applyingBasalRateMultiplier(from: override, relativeTo: referenceDate)
}
// Override start aligns with schedule item start
func testBasalRateScheduleOverrideStartTimeMatch() {
let overrideBasalSchedule = applyingActiveBasalOverride(from: "00:00", to: "01:00", on: basalRateSchedule)
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.8),
RepeatingScheduleValue(startTime: .hours(1), value: 1.2),
RepeatingScheduleValue(startTime: .hours(6), value: 1.4),
RepeatingScheduleValue(startTime: .hours(20), value: 1.0)
])!
XCTAssert(overrideBasalSchedule.equals(expected, accuracy: epsilon))
}
// Override contained fully within a schedule item
func testBasalRateScheduleOverrideContained() {
let overridden = applyingActiveBasalOverride(from: "02:00", to: "04:00", on: basalRateSchedule)
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.2),
RepeatingScheduleValue(startTime: .hours(2), value: 1.8),
RepeatingScheduleValue(startTime: .hours(4), value: 1.2),
RepeatingScheduleValue(startTime: .hours(6), value: 1.4),
RepeatingScheduleValue(startTime: .hours(20), value: 1.0)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
// Override end aligns with schedule item start
func testBasalRateScheduleOverrideEndTimeMatch() {
let overridden = applyingActiveBasalOverride(from: "02:00", to: "06:00", on: basalRateSchedule)
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.2),
RepeatingScheduleValue(startTime: .hours(2), value: 1.8),
RepeatingScheduleValue(startTime: .hours(6), value: 1.4),
RepeatingScheduleValue(startTime: .hours(20), value: 1.0)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
// Override completely encapsulates schedule item
func testBasalRateScheduleOverrideEncapsulate() {
let overridden = applyingActiveBasalOverride(from: "02:00", to: "22:00", on: basalRateSchedule)
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.2),
RepeatingScheduleValue(startTime: .hours(2), value: 1.8),
RepeatingScheduleValue(startTime: .hours(6), value: 2.1),
RepeatingScheduleValue(startTime: .hours(20), value: 1.5),
RepeatingScheduleValue(startTime: .hours(22), value: 1.0),
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testSingleBasalRateSchedule() {
let basalRateSchedule = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.0)
])!
let overridden = applyingActiveBasalOverride(from: "08:00", to: "12:00", on: basalRateSchedule)
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.0),
RepeatingScheduleValue(startTime: .hours(8), value: 1.5),
RepeatingScheduleValue(startTime: .hours(12), value: 1.0)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testOverrideCrossingMidnight() {
var override = basalUpOverride(start: "22:00", end: "23:00")
override.duration += .hours(5) // override goes from 10pm to 4am of the next day
let overridden = basalRateSchedule.applyingBasalRateMultiplier(from: override, relativeTo: date(at: "22:00"))
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.8),
RepeatingScheduleValue(startTime: .hours(4), value: 1.2),
RepeatingScheduleValue(startTime: .hours(6), value: 1.4),
RepeatingScheduleValue(startTime: .hours(20), value: 1.0),
RepeatingScheduleValue(startTime: .hours(22), value: 1.5)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testMultiDayOverride() {
var override = basalUpOverride(start: "02:00", end: "22:00")
override.duration += .hours(48) // override goes from 2am until 10pm two days later
let overridden = basalRateSchedule.applyingBasalRateMultiplier(
from: override,
relativeTo: date(at: "02:00") + .hours(24)
)
// expect full schedule override; start/end dates are too distant to have an effect
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.8),
RepeatingScheduleValue(startTime: .hours(6), value: 2.1),
RepeatingScheduleValue(startTime: .hours(20), value: 1.5)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testOutdatedOverride() {
let overridden = applyingActiveBasalOverride(from: "02:00", to: "04:00", on: basalRateSchedule,
referenceDate: date(at: "12:00").addingTimeInterval(.hours(24)))
let expected = basalRateSchedule
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testFarFutureOverride() {
let overridden = applyingActiveBasalOverride(from: "10:00", to: "12:00", on: basalRateSchedule,
referenceDate: date(at: "02:00").addingTimeInterval(-.hours(24)))
let expected = basalRateSchedule
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testIndefiniteOverride() {
var override = basalUpOverride(start: "02:00", end: "22:00")
override.duration = .indefinite
let overridden = basalRateSchedule.applyingBasalRateMultiplier(from: override, relativeTo: date(at: "02:00"))
// expect full schedule overridden
let expected = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: .hours(0), value: 1.8),
RepeatingScheduleValue(startTime: .hours(6), value: 2.1),
RepeatingScheduleValue(startTime: .hours(20), value: 1.5)
])!
XCTAssert(overridden.equals(expected, accuracy: epsilon))
}
func testOverrideScheduleAnnotatingReservoirSplitsDose() {
let schedule = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: 0, value: 0.225),
RepeatingScheduleValue(startTime: 3600.0, value: 0.18000000000000002),
RepeatingScheduleValue(startTime: 10800.0, value: 0.135),
RepeatingScheduleValue(startTime: 12689.855275034904, value: 0.15),
RepeatingScheduleValue(startTime: 21600.0, value: 0.2),
RepeatingScheduleValue(startTime: 32400.0, value: 0.2),
RepeatingScheduleValue(startTime: 50400.0, value: 0.2),
RepeatingScheduleValue(startTime: 52403.79680299759, value: 0.16000000000000003),
RepeatingScheduleValue(startTime: 63743.58014559746, value: 0.2),
RepeatingScheduleValue(startTime: 63743.58014583588, value: 0.16000000000000003),
RepeatingScheduleValue(startTime: 69968.05249071121, value: 0.2),
RepeatingScheduleValue(startTime: 69968.05249094963, value: 0.18000000000000002),
RepeatingScheduleValue(startTime: 79200.0, value: 0.225),
])!
let dose = DoseEntry(
type: .tempBasal,
startDate: date(at: "19:25"),
endDate: date(at: "19:30"),
value: 0.8,
unit: .units
)
let annotated = [dose].annotated(with: schedule)
XCTAssertEqual(3, annotated.count)
XCTAssertEqual(dose.programmedUnits, annotated.map { $0.unitsInDeliverableIncrements }.reduce(0, +))
}
// MARK: - Target range tests
func testActiveTargetRangeOverride() {
let overrideRange = DoubleRange(minValue: 120, maxValue: 140)
let overrideStart = Date()
let overrideDuration = TimeInterval(hours: 4)
let settings = TemporaryScheduleOverrideSettings(unit: .milligramsPerDeciliter, targetRange: overrideRange)
let override = TemporaryScheduleOverride(context: .custom, settings: settings, startDate: overrideStart, duration: .finite(overrideDuration), enactTrigger: .local, syncIdentifier: UUID())
let normalRange = DoubleRange(minValue: 95, maxValue: 105)
let rangeSchedule = GlucoseRangeSchedule(unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: 0, value: normalRange)])!.applyingOverride(override)
XCTAssertEqual(rangeSchedule.value(at: overrideStart), overrideRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + overrideDuration / 2), overrideRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + overrideDuration), overrideRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + overrideDuration + .hours(2)), overrideRange)
}
func testFutureTargetRangeOverride() {
let overrideRange = DoubleRange(minValue: 120, maxValue: 140)
let overrideStart = Date() + .hours(2)
let overrideDuration = TimeInterval(hours: 4)
let settings = TemporaryScheduleOverrideSettings(unit: .milligramsPerDeciliter, targetRange: overrideRange)
let futureOverride = TemporaryScheduleOverride(context: .custom, settings: settings, startDate: overrideStart, duration: .finite(overrideDuration), enactTrigger: .local, syncIdentifier: UUID())
let normalRange = DoubleRange(minValue: 95, maxValue: 105)
let rangeSchedule = GlucoseRangeSchedule(unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue(startTime: 0, value: normalRange)])!.applyingOverride(futureOverride)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + .minutes(-5)), normalRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart), overrideRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + overrideDuration), overrideRange)
XCTAssertEqual(rangeSchedule.value(at: overrideStart + overrideDuration + .hours(2)), overrideRange)
}
}
private extension TemporaryScheduleOverride.Duration {
static func += (lhs: inout TemporaryScheduleOverride.Duration, rhs: TimeInterval) {
switch lhs {
case .finite(let interval):
lhs = .finite(interval + rhs)
case .indefinite:
return
}
}
}
| mit | 2754b3d75a513de2abac56a4237e4d50 | 46.976563 | 201 | 0.669516 | 4.634717 | false | true | false | false |
Dewire/SwiftCommon | SwiftCommon/UIColor.swift | 1 | 1467 | //
// UIColor.swift
// SwiftCommon
//
// Created by Kalle Lindström on 2017-09-26.
// Copyright © 2017 Dewire. All rights reserved.
//
import UIKit
extension UIColor {
/**
Creates a color given a RGB(A) number. If the number given is less than or equal to 0xFFFFFF
it is interpreted as a RGB value. If it is greater than 0xFFFFFF it is interpreted as an RGBA value.
If the number is a RGB value, an optional alpha value can be given from 0 to 1. The default is 1.
If the number is a RGBA value the optional alpha value is ignored.
Example:
```
UIColor(rgb: 0xFF0000) # -> same as UIColor.red
UIColor(rgb: 0xFF0000, alpha: 0.5) # -> red color with 50% opacity
UIColor(rgb: 0xFF000080) # -> rec color with =~ 50% opacity
```
*/
public convenience init(rgb: Int64, alpha: CGFloat = 1) {
let r, g, b: Int64
let a: CGFloat
if rgb > 0xFFFFFF { // we have a RGBA color
r = (rgb & 0xFF000000) >> 24
g = (rgb & 0x00FF0000) >> 16
b = (rgb & 0x0000FF00) >> 8
a = CGFloat((rgb & 0x000000FF)) / 255
} else { // we have a RGB color
r = (rgb & 0xFF0000) >> 16
g = (rgb & 0x00FF00) >> 8
b = rgb & 0x0000FF
a = alpha
}
self.init(red: CGFloat(r) / 255,
green: CGFloat(g) / 255,
blue: CGFloat(b) / 255,
alpha: a)
}
}
| mit | 85988a29b6efdbeb27ad9a188bb6cadc | 30.170213 | 103 | 0.553584 | 3.564477 | false | false | false | false |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/Pods/Nimble/Nimble/Matchers/BeAnInstanceOf.swift | 44 | 1574 | import Foundation
// A Nimble matcher that catches attempts to use beAnInstanceOf with non Objective-C types
public func beAnInstanceOf(expectedClass: Any) -> NonNilMatcherFunc<Any> {
return NonNilMatcherFunc {actualExpression, failureMessage in
failureMessage.stringValue = "beAnInstanceOf only works on Objective-C types since"
+ " the Swift compiler will automatically type check Swift-only types."
+ " This expectation is redundant."
return false
}
}
/// A Nimble matcher that succeeds when the actual value is an instance of the given class.
/// @see beAKindOf if you want to match against subclasses
public func beAnInstanceOf(expectedClass: AnyClass) -> NonNilMatcherFunc<NSObject> {
return NonNilMatcherFunc { actualExpression, failureMessage in
let instance = actualExpression.evaluate()
if let validInstance = instance {
failureMessage.actualValue = "<\(NSStringFromClass(validInstance.dynamicType)) instance>"
} else {
failureMessage.actualValue = "<nil>"
}
failureMessage.postfixMessage = "be an instance of \(NSStringFromClass(expectedClass))"
return instance != nil && instance!.isMemberOfClass(expectedClass)
}
}
extension NMBObjCMatcher {
public class func beAnInstanceOfMatcher(expected: AnyClass) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
return beAnInstanceOf(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
| mit | 5c604fbcf457a352bd2f10a59a7124dc | 45.294118 | 101 | 0.719822 | 5.503497 | false | false | false | false |
therealglazou/quaxe-for-swift | quaxe/css/CSSRule.swift | 1 | 1303 | /**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <[email protected]>
*
* Contributors:
*
*/
/*
* https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule
*/
public class CSSRule: pCSSRule {
static let UNKNOWN_RULE: ushort = 0;
static let STYLE_RULE: ushort = 1;
static let CHARSET_RULE: ushort = 2;
static let IMPORT_RULE: ushort = 3;
static let MEDIA_RULE: ushort = 4;
static let FONT_FACE_RULE: ushort = 5;
static let PAGE_RULE: ushort = 6;
internal var mType: ushort = UNKNOWN_RULE;
internal var mParentStyleSheet: pCSSStyleSheet
internal var mParentStyleRule: pCSSRule? = nil
public var type: ushort { return mType }
// XXXXXX
public var cssText: DOMString {
get {
return ""
}
set {
}
}
public var parentStyleSheet: pCSSStyleSheet { return mParentStyleSheet }
public var parentRule: pCSSRule? { return mParentStyleRule }
init(_ parentStyleSheet: pCSSStyleSheet, _ parentRule: pCSSRule?) {
mParentStyleSheet = parentStyleSheet;
mParentStyleRule = parentRule;
}
}
| mpl-2.0 | fe99ef95e8fcf1650c3bbb8d5c731ad1 | 25.06 | 74 | 0.605526 | 3.701705 | false | false | false | false |
OscarSwanros/swift | test/IRGen/sil_witness_tables.swift | 12 | 3855 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@_T039sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP]] = external global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1QAAWP]] = hidden constant [2 x i8*] [
// CHECK: i8* bitcast ([4 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1PAAWP]] to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.type* ()* @_T018sil_witness_tables14AssocConformerVMa to i8*),
// CHECK: i8* bitcast (i8** ()* @_T018sil_witness_tables14AssocConformerVAA1AAAWa to i8*)
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@_T018sil_witness_tables10Conformer2VAA1PAAWP]] = hidden constant [4 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables7erasureAA2QQ_pAA9ConformerV1c_tF(%T18sil_witness_tables2QQP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_T0.*WP]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables15externalErasure0a1_b1_c1_D12_conformance9ExternalP_pAC0G9ConformerV1c_tF(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden %swift.type* @_T018sil_witness_tables14AssocConformerVMa()
// CHECK: ret %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @_T018sil_witness_tables14AssocConformerVMf, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define hidden i8** @_T018sil_witness_tables9ConformerVAA1PAAWa()
// CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @_T018sil_witness_tables9ConformerVAA1PAAWP, i32 0, i32 0)
| apache-2.0 | 1742ea366f30117f56f8ecc16c1b7cdb | 47.1875 | 221 | 0.718547 | 3.2125 | false | false | false | false |
JanNash/Djaft | Djaft/Sources/Classes/DJQuerySetCreator.swift | 2 | 2736 | //
// DJQuerySetCreator.swift
// Djaft
//
// Created by Jan Nash on 16/11/15.
// Copyright © 2015 Jan Nash. All rights reserved.
//
import Foundation
import CoreData
// MARK: // Internal
// MARK: Interface
extension DJQuerySetCreator {
// Basic QuerySet Generation
func createRefinableQuerySet_(newFilters newFilters: [String] = [], newExcludes: [String] = [], newOrderBys: [String] = []) -> DJRefinableQuerySet<T> {
return self._createRefinableQuerySet(
newFilters: newFilters,
newExcludes: newExcludes,
newOrderBys: newOrderBys
)
}
// Refined QuerySet Generation
func filter_(params: [String]) -> DJRefinableQuerySet<T> {
return self._filter(params)
}
func exclude_(params: [String]) -> DJRefinableQuerySet<T> {
return self._exclude(params)
}
func orderBy_(params: [String]) -> DJRefinableQuerySet<T> {
return self._orderBy(params)
}
}
// MARK: Class Declaration
class DJQuerySetCreator<T: NSManagedObject>: DJQuerySetEvaluator<T> {
override init(withClass klass: NSManagedObject.Type,
objectContext: NSManagedObjectContext? = nil,
filters: [String] = [],
excludes: [String] = [],
orderBys: [String]? = nil,
fetchedObjects: [T]? = nil) {
super.init(
withClass: klass,
objectContext: objectContext,
filters: filters,
excludes: excludes,
orderBys: orderBys,
fetchedObjects: fetchedObjects
)
}
}
// MARK: // Private
// MARK: Basic QuerySet Generation
private extension DJQuerySetCreator {
private func _createRefinableQuerySet(newFilters newFilters: [String] = [], newExcludes: [String] = [], newOrderBys: [String] = []) -> DJRefinableQuerySet<T> {
return DJRefinableQuerySet(
withClass: self.klass_,
objectContext: self.objectContext,
filters: self.filters + newFilters,
excludes: self.excludes + newExcludes,
orderBys: self.orderBys + newOrderBys
)
}
}
// MARK: Refined QuerySet Generation
private extension DJQuerySetCreator {
private func _filter(params: [String]) -> DJRefinableQuerySet<T> {
return self._createRefinableQuerySet(newFilters: params)
}
private func _exclude(params: [String]) -> DJRefinableQuerySet<T> {
return self._createRefinableQuerySet(newExcludes: params)
}
private func _orderBy(params: [String]) -> DJRefinableQuerySet<T> {
return self._createRefinableQuerySet(newOrderBys: params)
}
}
| mit | c91b012f40e172c7bf8c4b6ecda438ed | 30.079545 | 163 | 0.610969 | 4.169207 | false | false | false | false |
JxbSir/JxbRefresh | JxbRefresh/AppDelegate.swift | 1 | 2478 | //
// AppDelegate.swift
// JxbRefresh
//
// Created by Peter on 16/6/12.
// Copyright © 2016年 https://github.com/JxbSir. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc: ViewController = ViewController()
let nav: UINavigationController = UINavigationController.init(rootViewController: vc)
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.makeKey()
window?.becomeKey()
window?.rootViewController = nav
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 | 20a3bb19edca3ded9c6e862477f1f23d | 44.833333 | 285 | 0.736162 | 5.512249 | false | false | false | false |
mikeckennedy/DevWeek2015 | swift/ttt/ttt/ViewController.swift | 1 | 2772 | //
// ViewController.swift
// ttt
//
// Created by Michael Kennedy on 3/25/15.
// Copyright (c) 2015 DevelopMentor. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button11: UIButton!
@IBOutlet weak var button12: UIButton!
@IBOutlet weak var button13: UIButton!
@IBOutlet weak var button21: UIButton!
@IBOutlet weak var button22: UIButton!
@IBOutlet weak var button23: UIButton!
@IBOutlet weak var button31: UIButton!
@IBOutlet weak var button32: UIButton!
@IBOutlet weak var button33: UIButton!
@IBOutlet weak var labelOutcome: UILabel!
var buttons : [[UIButton!]] = []
var game = Game()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
labelOutcome.text = ""
// button11.removeConstraints(button11.constraints())
// button11.setTranslatesAutoresizingMaskIntoConstraints(true)
//
// button11.frame = CGRect(x: 0, y: 0, width: 200, height: 200
//)
var row1 = [button11, button12, button13]
var row2 = [button21, button22, button23]
var row3 = [button31, button32, button33]
buttons.append(row1)
buttons.append(row2)
buttons.append(row3)
syncGameToButtons()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPlayClicked(sender: UIButton) {
if game.hasWinner {
return
}
let (r, c) = getIndexForButton(sender)
var currentPlayer = game.currentPlayerName
if game.play(r, col: c) {
game.swapPlayers()
}
syncGameToButtons()
if game.hasWinner {
labelOutcome.text = "We have a winner! " + currentPlayer
}
}
func getIndexForButton(btn : UIButton!) -> (Int, Int) {
for (idx_r, row) in enumerate(buttons) {
for (idx_c, b) in enumerate(row) {
if b == btn {
return (idx_r, idx_c)
}
}
}
return (-1, -1)
}
func syncGameToButtons() {
for row in buttons {
for b in row {
let (r, c) = getIndexForButton(b)
if let text = game.getCellText(r,c: c) {
b.setTitle(text, forState: .Normal)
} else {
b.setTitle("___", forState: .Normal)
}
}
}
}
}
| cc0-1.0 | ec4a7ec5d9f3cbe5d61b8069c8318c46 | 24.906542 | 80 | 0.539683 | 4.351648 | false | false | false | false |
DianQK/rx-sample-code | PDFExpertContents/ExpandedTableViewCell.swift | 1 | 2045 | //
// ExpandedTableViewCell.swift
// PDF-Expert-Contents
//
// Created by DianQK on 17/09/2016.
// Copyright © 2016 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxExtensions
class ExpandedTableViewCell: ReactiveTableViewCell {
@IBOutlet private weak var expandMarkImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
var attributedText: NSAttributedString? {
get {
return titleLabel?.attributedText
}
set(attributedText) {
titleLabel.attributedText = attributedText
}
}
var level: Int = 0 {
didSet {
let left = CGFloat(level * 15) + 15 + 15 + 10
separatorInset = UIEdgeInsets(top: 0, left: left, bottom: 0, right: 0)
}
}
var isExpanded: Bool = false {
didSet {
guard canExpanded, isExpanded != oldValue else { return }
var from = CATransform3DIdentity
var to = CATransform3DRotate(from, CGFloat(M_PI_2), 0, 0, 1)
if !isExpanded {
(from, to) = (to, from)
}
expandMarkImageView.layer.transform = to
let affineTransformAnimation = CABasicAnimation(keyPath: "transform")
affineTransformAnimation.fromValue = NSValue(caTransform3D: from)
affineTransformAnimation.toValue = NSValue(caTransform3D: to)
affineTransformAnimation.duration = 0.3
expandMarkImageView.layer.add(affineTransformAnimation, forKey: nil)
}
}
var canExpanded: Bool = false {
didSet {
expandMarkImageView.isHidden = !canExpanded
}
}
}
extension Reactive where Base: ExpandedTableViewCell {
var isExpanded: AnyObserver<Bool> {
return UIBindingObserver(UIElement: self.base as ExpandedTableViewCell, binding: { (cell, isExpanded) in
if cell.isExpanded != isExpanded {
cell.isExpanded = isExpanded
}
}).asObserver()
}
}
| mit | 9d6b8b61161d7568a606d29776b6261a | 28.2 | 112 | 0.620352 | 4.742459 | false | false | false | false |
segura2010/exodobb-for-iOS | exodoapp/SecondViewController.swift | 1 | 5704 | //
// SecondViewController.swift
// exodoapp
//
// Created by Alberto on 18/9/15.
// Copyright © 2015 Alberto. All rights reserved.
//
import UIKit
import CoreData
class SecondViewController: UIViewController {
let LOGIN_URL = "https://exo.do/login"
@IBOutlet var usernameTxt: UITextField!
@IBOutlet var passwordTxt: UITextField!
var users = [NSManagedObject]()
var csrf: String!
override func viewDidLoad() {
super.viewDidLoad()
var cookie = SecondViewController.getCookie()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SecondViewController.DismissKeyboard))
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view, typically from a nib.
}
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getCSRF()
{
var request = URLRequest(url: URL(string: LOGIN_URL)!)
let session = URLSession.shared
request.httpMethod = "GET"
var csrf = ""
do {
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
do{
//print("Response: \(response)")
//let res = response as! NSHTTPURLResponse
//print(data)
let nsString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
var text = nsString as! String
var matchs = self.matches(for:"\"csrf_token\":\"([^\"]+)", in: text)
var csrf_str = "\"csrf_token\":\""
//print(matchs[0])
self.csrf = matchs[0].replacingOccurrences(of: csrf_str, with: "") //substring(from: 14 as Int)
//print(csrf)
self.login()
}catch{
print("Error:\n \(error)")
return
}
})
task.resume()
}catch{
print("Error:\n")
}
}
@IBAction func logInBtnClick(_ sender: AnyObject) {
getCSRF()
//saveCookie(usernameTxt.text!)
}
func login()
{
var request = URLRequest(url: URL(string: LOGIN_URL)!)
let session = URLSession.shared
request.httpMethod = "POST"
let params = "username=\(usernameTxt.text!)&password=\(passwordTxt.text!)&returnTo=https://exo.do/recent"
print(self.csrf)
do {
request.httpBody = params.data(using: String.Encoding.utf8)
request.addValue(self.csrf, forHTTPHeaderField: "x-csrf-token")
request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
request.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With")
request.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
do{
//print("Response: \(response)")
let res = response as! HTTPURLResponse
print(res)
if res.statusCode == 200{
if let cookie = res.allHeaderFields["Set-Cookie"]{
print(cookie)
self.saveCookie(cookie: cookie as! String)
exit(0)
}
}else{
//self.usernameTxt.text = "Invalid username/password"
//self.passwordTxt.text = ""
}
}catch{
print("Error:\n \(error)")
return
}
})
task.resume()
}catch{
print("Error:\n \(error)")
return
}
}
class func getCookie() -> String
{
let defaults = UserDefaults(suiteName: "group.exodobb")
if let cookie = defaults?.string(forKey: "cookie") {
print("getCookie() -> \(cookie)")
return cookie
}
else{
return ""
}
}
func saveCookie(cookie:String)
{
/*
let defaults = UserDefaults.standard
defaults.setValue(cookie, forKey: "cookie")
defaults.synchronize()
*/
let defaults = UserDefaults(suiteName: "group.exodobb")
defaults?.setValue(cookie, forKey: "cookie")
defaults?.synchronize()
}
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
| gpl-2.0 | 3d5696f82e9c26010c6cfa1b4dbfb3e5 | 29.994565 | 135 | 0.505874 | 5.198724 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Subreddits/View/ThumbnailLinkCell.swift | 1 | 5100 | //
// ThumbnailLinkCell.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import DrapierLayout
class ThumbnailLinkCell : LinkCell {
let thumbnailImageView = UIImageView()
var isThumbnailSet: Bool {
return thumbnailImage != nil
}
var thumbnailImage: UIImage? {
get {
return thumbnailImageView.image
}
set {
thumbnailImageView.image = newValue
}
}
override func prepareForReuse() {
super.prepareForReuse()
thumbnailImageView.image = nil
}
override func configure() {
super.configure()
contentView.addSubview(thumbnailImageView)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = generateLayout(contentView.bounds)
thumbnailImageView.frame = layout.thumbnailFrame
titleLabel.frame = layout.titleFrame
ageLabel.frame = layout.ageFrame
authorLabel.frame = layout.authorFrame
separatorView.frame = layout.separatorFrame
}
override func sizeThatFits(size: CGSize) -> CGSize {
let layout = generateLayout(size.rect())
let maxBottom = layout.authorFrame.baseline(font: authorLabel.font)
return CGSize(width: size.width, height: maxBottom + insets.bottom)
}
struct CellLayout {
let thumbnailFrame: CGRect
let titleFrame: CGRect
let ageFrame: CGRect
let authorFrame: CGRect
let separatorFrame: CGRect
}
func generateLayout(bounds: CGRect) -> CellLayout {
var thumbnailFrame = thumbnailImageView.layout(
Trailing(equalTo: bounds.trailing(insets)),
Top(equalTo: bounds.top(insets)),
Width(equalTo: measurements.thumbnailSize.width),
Height(equalTo: measurements.thumbnailSize.height)
)
let titleFrame = titleLabel.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: thumbnailFrame.leading, constant: -measurements.horizontalSpacing),
Capline(equalTo: bounds.top(insets))
)
if titleFrame.height > thumbnailFrame.height {
thumbnailFrame = thumbnailImageView.layout(
Trailing(equalTo: bounds.trailing(insets)),
CenterY(equalTo: titleFrame.centerY),
Width(equalTo: measurements.thumbnailSize.width),
Height(equalTo: measurements.thumbnailSize.height)
)
}
let ageFrame = ageLabel.layout(
Leading(equalTo: bounds.leading(insets)),
Capline(equalTo: titleFrame.baseline(font: titleLabel.font), constant: measurements.verticalSpacing)
)
var authorFrame = authorLabel.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: bounds.trailing(insets)),
Capline(equalTo: ageFrame.baseline(font: ageLabel.font), constant: measurements.verticalSpacing)
)
if authorFrame.top < thumbnailFrame.bottom + measurements.verticalSpacing {
authorFrame = authorLabel.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: bounds.trailing(insets)),
Capline(equalTo: thumbnailFrame.bottom, constant: measurements.verticalSpacing)
)
}
let separatorFrame = separatorView.layout(
Leading(equalTo: bounds.leading(insets)),
Trailing(equalTo: bounds.trailing),
Bottom(equalTo: authorFrame.baseline(font: authorLabel.font) + insets.bottom),
Height(equalTo: separatorHeight)
)
return CellLayout(
thumbnailFrame: thumbnailFrame,
titleFrame: titleFrame,
ageFrame: ageFrame,
authorFrame: authorFrame,
separatorFrame: separatorFrame
)
}
}
| mit | abe5736ccc8a8a44bf342cbbb63dcfb0 | 35.690647 | 112 | 0.651961 | 5.130785 | false | false | false | false |
youngsoft/TangramKit | TangramKitDemo/IntegratedDemo/AllTest8ViewController.swift | 1 | 12384 | //
// AllTest8ViewController.swift
// TangramKit
//
// Created by apple on 16/10/17.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
/**
* ❁2.Screen perfect fit - Demo2
*/
class AllTest8ViewController: UIViewController {
func createDemoButton(_ title: String, action: Selector) -> UIButton
{
let btn = UIButton(type: .system)
btn.layer.borderWidth = 0.5
btn.layer.cornerRadius = 5
btn.layer.borderColor = UIColor.lightGray.cgColor
btn.setTitle(title, for: .normal)
btn.titleLabel!.font = CFTool.font(15)
btn.sizeToFit()
btn.addTarget(self, action: action, for: .touchUpInside)
return btn
}
override func viewDidLoad() {
if #available(iOS 11.0, *)
{
}
else
{
self.edgesForExtendedLayout = UIRectEdge(rawValue:0) //设置视图控制器中的视图尺寸不延伸到导航条或者工具条下面。您可以注释这句代码看看效果。
}
super.viewDidLoad()
self.view.backgroundColor = .white
// Do any additional setup after loading the view.
/*
本例子演示当把一个布局视图加入到非布局视图时的各种场景。当把一个布局视图加入到非布局父视图时,因为无法完全对非布局父视图进行控制。所以一些布局视图的属性将不再起作用了,但是基本的视图扩展属性: tg_leading,tg_trailing,tg_top,tg_bottom,tg_centerX,tg_centerY,tg_width,tg_height这几个属性仍然有意义,只不过这些属性的equal方法能设置的类型有限,而且这些设置都只是基于父视图的。
*/
let scrollView = UIScrollView(frame: self.view.bounds)
scrollView.contentSize = self.view.bounds.size
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(scrollView)
//按钮用AutoLayout来实现,本例子说明AutoLayout是可以和TangramKit混合使用的。
let button = self.createDemoButton(NSLocalizedString("Pop layoutview at center", comment: ""), action: #selector(handleDemo1))
button.translatesAutoresizingMaskIntoConstraints = false //button使用AutoLayout设置约束
scrollView.addSubview(button)
//下面的代码是iOS6以来自带的约束布局写法,可以看出代码量较大。
scrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: scrollView, attribute: .centerX, multiplier: 1, constant: 0))
scrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 10))
scrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40))
scrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: scrollView, attribute: .width, multiplier: 1, constant: -20))
//下面的代码是iOS9以后提供的一种简便的约束设置方法。可以看出其中各种属性设置方式和MyLayout是相似的。
//在iOS9提供的NSLayoutXAxisAnchor,NSLayoutYAxisAnchor,NSLayoutDimension这三个类提供了和TangramKit中的TGLayoutPos,TGLayoutSize类等价的功能。
if #available(iOS 9.0, *) {
button.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
button.topAnchor.constraint(equalTo: scrollView.topAnchor, constant:10).isActive = true
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
button.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier:1, constant:-20).isActive = true
} else {
// Fallback on earlier versions
}
//如果您用TangramKit布局。并且button在一个垂直线性布局下那么可以写成如下:
/*
button.tg_top.equal(10)
button.tg_height.equal(40)
button.tg_leading.equal(10)
button.tg_trailing.equal(10)
*/
/*
下面例子用来建立一个不规则的功能区块。
*/
//建立一个浮动布局,这个浮动布局不会控制父视图UIScrollView的contentSize。
let floatLayout = TGFloatLayout(.horz)
floatLayout.backgroundColor = CFTool.color(0)
floatLayout.tg_space = 10
floatLayout.tg_leading.equal(10)
floatLayout.tg_trailing.equal(10) //同时设定了左边和右边边距,布局视图的宽度就决定了。
floatLayout.tg_padding = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10); //设置内边距。
floatLayout.tg_top.equal(60)
floatLayout.tg_bottom.equal(10) //底部边距为10,这样同样设置了顶部和底部边距后布局的高度就决定了。
floatLayout.tg_adjustScrollViewContentSizeMode = .no //布局视图不控制滚动视图的contentSize。
/*这里面把布局视图加入到滚动视图时不会自动调整滚动视图的contentSize,如果不设置这个属性则当布局视图加入滚动视图时会自动调整滚动视图的contentSize。您可以把tg_adjustScrollViewContentSizeMode属性设置这句话注释掉,可以看到当使用默认设置时,UIScrollView的contentSize的值会完全受到布局视图的尺寸和边距控制,这时候:
contentSize.height = 布局视图的高度+布局视图的tg_top设置的上边距值 + 布局视图的tg_bottom设置的下边距值。
contentSize.width = 布局视图的宽度+布局视图的tg_leading设置的左距值 + 布局视图的tg_trailing设置的右边距值。
*/
scrollView.addSubview(floatLayout)
//这里定义高度占父视图的比例,每列分为5份,下面数组定义每个子视图的高度占比。
let heightscale:[CGFloat] = [0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.4]
//因为分为左右2列,而要求每个视图之间的垂直间距为10,左边列的总间距是30,一共有4个,因此前4个都要减去-30/4的间距高度;右边列总间距为20,一共有3个,因此后3个都要减去-20/3的间距高度。
let heightinc:[CGFloat] = [-30.0/4, -30.0/4, -30.0/4, -30.0/4, -20.0/3, -20.0/3, -20.0/3]
for i in 0 ..< 7
{
let buttonTag = self.createDemoButton("不规则功能块", action:#selector(handleDemo1))
buttonTag.contentVerticalAlignment = .top
buttonTag.contentHorizontalAlignment = .left //按钮内容左上角对齐。
buttonTag.backgroundColor = CFTool.color(i + 5)
buttonTag.tg_width.equal(floatLayout.tg_width, increment:-5, multiple: 0.5) //因为宽度都是父视图的一半,并且水平间距是10,所以这里比例是0.5,分别减去5个间距宽度。
buttonTag.tg_height.equal(floatLayout.tg_height, increment:heightinc[i], multiple:heightscale[i]) //高度占比和所减的间距在上面数组里面定义。
floatLayout.addSubview(buttonTag)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func handleDemo1AddTest(sender:UIButton!)
{
if let label = sender.superview?.superview?.subviews[1] as? UILabel
{
label.text = label.text?.appending("添加文字。")
}
}
@objc func handleDemo1RemoveLayout(sender:UIButton!)
{
UIView.perform(.delete, on: [sender.superview!.superview!], options: .curveLinear, animations: nil, completion: nil)
}
@objc func handleDemo1(sener:UIButton!)
{
//布局视图用来实现弹框,这里把一个布局视图放入一个非布局视图里面。
let layout = TGLinearLayout(.vert)
layout.backgroundColor = CFTool.color(14)
layout.layer.cornerRadius = 5
layout.tg_height.equal(.wrap)
layout.tg_padding = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
//设置布局视图的内边距。
layout.tg_vspace = 5
//设置视图之间的间距,这样子视图就不再需要单独设置间距了。
layout.tg_gravity = TGGravity.horz.fill
//里面的子视图宽度和自己一样,这样就不再需要设置子视图的宽度了。
layout.tg_leading.equal(20%)
layout.tg_trailing.equal(20%)
//左右边距0.2表示相对边距,也就是左右边距都是父视图总宽度的20%,这样布局视图的宽度就默认为父视图的60%了。
layout.tg_centerY.equal(0)
//布局视图在父视图中垂直居中出现。
//layout.tg_bottom.equal(0) //布局视图在父视图中底部出现。您可以注释上面居中的代码并解开这句看看效果。
self.view.addSubview(layout)
//标题
let titleLabel = UILabel()
titleLabel.text = NSLocalizedString("Title", comment: "")
titleLabel.textAlignment = .center
titleLabel.textColor = CFTool.color(4)
titleLabel.font = CFTool.font(17)
titleLabel.sizeToFit()
layout.addSubview(titleLabel)
//文本
let label = UILabel()
label.font = CFTool.font(14)
label.text = "这是一段具有动态高度的文本,同时他也会影响着布局视图的高度。您可以单击下面的按钮来添加文本来查看效果:"
label.tg_height.equal(.wrap)
layout.addSubview(label)
//按钮容器。如果您想让两个按钮水平排列则只需在btnContainer初始化中把方向改为:.horz 。您可以尝试看看效果。
let btnContainer = TGLinearLayout(.vert)
btnContainer.tg_height.equal(.wrap)
//高度由子视图确定。
btnContainer.tg_space = 5
//视图之间的间距设置为5
btnContainer.tg_gravity = TGGravity.horz.fill
//里面的子视图的宽度水平填充,如果是垂直线性布局则里面的所有子视图的宽度都和父视图相等。如果是水平线性布局则会均分所有子视图的宽度。
layout.addSubview(btnContainer)
/*
TangramKit和SizeClass有着紧密的结合。如果你想在横屏时两个按钮水平排列而竖屏时垂直排列则设置如下 :
因为所有设置的布局属于默认都是基于wAny,hAny这种Size Classes的。所以我们要对按钮容器视图指定一个单独横屏的Size Classes: Landscape
这里的copyFrom表示系统会拷贝默认的Size Classes,最终方法返回横屏的Size Classes。 这样你只需要设置一下排列的方向就可以了。
您可以将下面两句代码注释掉看看横竖屏切换的结果。
*/
let btnContainerSC = btnContainer.tg_fetchSizeClass(with: .landscape, from: .default) as! TGLinearLayoutViewSizeClass
btnContainerSC.tg_orientation = .horz
//您可以看到下面的两个按钮没有出现任何的需要进行布局的属性设置,直接添加到父视图就能达到想要的效果,这样就简化了程序的开发。
btnContainer.addSubview(self.createDemoButton("Add Text", action:#selector(handleDemo1AddTest)))
btnContainer.addSubview(self.createDemoButton("Remove Layout",action:#selector(handleDemo1RemoveLayout)))
//这里把一个布局视图加入到非布局父视图。
self.view.addSubview(layout)
//如果您要移动出现的动画效果则解开如下注释。
layout.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height/2)
layout.alpha = 0.5
UIView.animate(withDuration: 0.3, animations: {
layout.transform = .identity
layout.alpha = 1
})
}
}
| mit | d73acf12aeb6e0070ef200cd0f8f8017 | 39.268085 | 237 | 0.655078 | 3.494461 | false | false | false | false |
huangboju/AsyncDisplay_Study | AsyncDisplay/Weibo/Model/PictureMetaModel.swift | 1 | 928 | //
// PictureMetaModel.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/5/17.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import SwiftyJSON
struct PictureMetaModel {
let cutType: Int
let type: String // "WEBP" "JPEG" "GIF"
let url: URL
let width: Double
let height: Double
let croped: Bool
var badgeName: String?
init(dict: [String: JSON]?) {
cutType = dict?["cut_type"]?.intValue ?? 0
type = dict?["type"]?.stringValue ?? ""
url = dict?["url"]?.url ?? URL(string: "https://www.baidu.com/")!
width = dict?["width"]?.doubleValue ?? 0
height = dict?["height"]?.doubleValue ?? 0
croped = dict?["croped"]?.boolValue ?? false
if type == "GIF" {
badgeName = "timeline_image_gif"
} else if width > 0 && height / width > 3 {
badgeName = "timeline_image_longimage"
}
}
}
| mit | 6eb8c44bccf10af255bd7aea8706a81d | 25.852941 | 73 | 0.559693 | 3.681452 | false | false | false | false |
DTLivingstone/HypoTrack | HypoTrack/HistoryViewController.swift | 1 | 2395 | //
// HistoryViewController.swift
// HypoTrack
//
// Created by David Livingstone on 7/8/16.
// Copyright © 2016 David Livingstone. All rights reserved.
//
//import UIKit
//
//class HistoryViewController: UIViewController {
//
// @IBOutlet weak var table: UITableView!
//
// func table(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return injections.count
// }
//
// func table(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("HistoryCell", forIndexPath: indexPath)
// let med = injections[indexPath.row].med
// let dose = injections[indexPath.row].dose
// let location = injections[indexPath.row].location
// let date = injections[indexPath.row].date
//
// let formatter = NSDateFormatter()
// formatter.dateStyle = .MediumStyle
// formatter.timeStyle = .NoStyle
// formatter.locale = NSLocale(localeIdentifier: "en_US")
//
// let formattedDate = formatter.stringFromDate(date!)
//
// cell.textLabel!.text = "\(med): \(dose), \(location)"
// cell.detailTextLabel!.text = formattedDate
//
//
// return cell
// }
//}
//extension HistoryViewController: UITableViewDataSource {
// func table(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return injections.count
// }
//
// func table(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("HistoryCell", forIndexPath: indexPath)
// let med = injections[indexPath.row].med
// let dose = injections[indexPath.row].dose
// let location = injections[indexPath.row].location
// let date = injections[indexPath.row].date
//
// let formatter = NSDateFormatter()
// formatter.dateStyle = .MediumStyle
// formatter.timeStyle = .NoStyle
// formatter.locale = NSLocale(localeIdentifier: "en_US")
//
// let formattedDate = formatter.stringFromDate(date!)
//
// cell.textLabel!.text = "\(med): \(dose), \(location)"
// cell.detailTextLabel!.text = formattedDate
//
//
// return cell
// }
| unlicense | a6b19c9703d5ea337ce7783f05e70d16 | 35.830769 | 107 | 0.631997 | 4.360656 | false | false | false | false |
cenfoiOS/ImpesaiOSCourse | CustomTableViewExample/CustomTableViewExample/DogsTableViewController.swift | 1 | 3964 | //
// DogsTableViewController.swift
// CustomTableViewExample
//
// Created by Cesar Brenes on 5/16/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import UIKit
class DogsTableViewController: UITableViewController {
let keyName = "keyName"
let keyColor = "keyColor"
let keyAge = "keyAge"
var dataSource: [[String: Any]]?
override func viewDidLoad() {
super.viewDidLoad()
registerCustomCell()
initializeDataSourceWithDictionary()
}
func registerCustomCell(){
let nib = UINib(nibName: "DogTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "DogTableViewCell")
}
func initializeDataSourceWithDictionary(){
let dog1 = [keyName: "Bruno", keyColor:"Negro", keyAge:"2 años"]
let dog2 = [keyName: "Dandy", keyColor:"Blanco", keyAge:"1 año"]
let dog3 = [keyName: "Perla", keyColor:"Blanco", keyAge:"3 año"]
let dog4 = [keyName: "Scoth", keyColor:"Negro", keyAge:"4 años"]
dataSource = [dog1,dog2,dog3,dog4]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let count = dataSource?.count else {
return 0
}
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DogTableViewCell", for: indexPath) as! DogTableViewCell
let dictionary = dataSource![indexPath.row]
cell.nameLabel.text = (dictionary[keyName] as! String)
cell.colorLabel.text = (dictionary[keyColor] as! String)
cell.ageLabel.text = (dictionary[keyAge] as! String)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return 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?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 92aeab5af0735427ef289a7c475caff3 | 30.664 | 137 | 0.644012 | 4.868389 | false | false | false | false |
Pursuit92/antlr4 | runtime/Swift/Antlr4/org/antlr/v4/runtime/tree/pattern/ParseTreePattern.swift | 5 | 5059 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/**
* A pattern like {@code <ID> = <expr>;} converted to a {@link org.antlr.v4.runtime.tree.ParseTree} by
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)}.
*/
public class ParseTreePattern {
/**
* This is the backing field for {@link #getPatternRuleIndex()}.
*/
private let patternRuleIndex: Int
/**
* This is the backing field for {@link #getPattern()}.
*/
private let pattern: String
/**
* This is the backing field for {@link #getPatternTree()}.
*/
private let patternTree: ParseTree
/**
* This is the backing field for {@link #getMatcher()}.
*/
private let matcher: ParseTreePatternMatcher
/**
* Construct a new instance of the {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern} class.
*
* @param matcher The {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher} which created this
* tree pattern.
* @param pattern The tree pattern in concrete syntax form.
* @param patternRuleIndex The parser rule which serves as the root of the
* tree pattern.
* @param patternTree The tree pattern in {@link org.antlr.v4.runtime.tree.ParseTree} form.
*/
public init(_ matcher: ParseTreePatternMatcher,
_ pattern: String, _ patternRuleIndex: Int, _ patternTree: ParseTree) {
self.matcher = matcher
self.patternRuleIndex = patternRuleIndex
self.pattern = pattern
self.patternTree = patternTree
}
/**
* Match a specific parse tree against this tree pattern.
*
* @param tree The parse tree to match against this tree pattern.
* @return A {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} object describing the result of the
* match operation. The {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#succeeded()} method can be
* used to determine whether or not the match was successful.
*/
public func match(_ tree: ParseTree) throws -> ParseTreeMatch {
return try matcher.match(tree, self)
}
/**
* Determine whether or not a parse tree matches this tree pattern.
*
* @param tree The parse tree to match against this tree pattern.
* @return {@code true} if {@code tree} is a match for the current tree
* pattern; otherwise, {@code false}.
*/
public func matches(_ tree: ParseTree) throws -> Bool {
return try matcher.match(tree, self).succeeded()
}
/**
* Find all nodes using XPath and then try to match those subtrees against
* this tree pattern.
*
* @param tree The {@link org.antlr.v4.runtime.tree.ParseTree} to match against this pattern.
* @param xpath An expression matching the nodes
*
* @return A collection of {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} objects describing the
* successful matches. Unsuccessful matches are omitted from the result,
* regardless of the reason for the failure.
*/
/*public func findAll(tree : ParseTree, _ xpath : String) -> Array<ParseTreeMatch> {
var subtrees : Array<ParseTree> = XPath.findAll(tree, xpath, matcher.getParser());
var matches : Array<ParseTreeMatch> = Array<ParseTreeMatch>();
for t : ParseTree in subtrees {
var match : ParseTreeMatch = match(t);
if ( match.succeeded() ) {
matches.add(match);
}
}
return matches;
}*/
/**
* Get the {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher} which created this tree pattern.
*
* @return The {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher} which created this tree
* pattern.
*/
public func getMatcher() -> ParseTreePatternMatcher {
return matcher
}
/**
* Get the tree pattern in concrete syntax form.
*
* @return The tree pattern in concrete syntax form.
*/
public func getPattern() -> String {
return pattern
}
/**
* Get the parser rule which serves as the outermost rule for the tree
* pattern.
*
* @return The parser rule which serves as the outermost rule for the tree
* pattern.
*/
public func getPatternRuleIndex() -> Int {
return patternRuleIndex
}
/**
* Get the tree pattern as a {@link org.antlr.v4.runtime.tree.ParseTree}. The rule and token tags from
* the pattern are present in the parse tree as terminal nodes with a symbol
* of type {@link org.antlr.v4.runtime.tree.pattern.RuleTagToken} or {@link org.antlr.v4.runtime.tree.pattern.TokenTagToken}.
*
* @return The tree pattern as a {@link org.antlr.v4.runtime.tree.ParseTree}.
*/
public func getPatternTree() -> ParseTree {
return patternTree
}
}
| bsd-3-clause | 762d46b3bbc794405fefc0eaae7eecb7 | 33.889655 | 129 | 0.650524 | 4.294567 | false | false | false | false |
piv199/LocalisysChat | LocalisysChat/Sources/Modules/Common/Chat/Extra/UITextViewExtensions+LocalisysChat.swift | 1 | 2132 | //
// UITextViewExtensions+LocalisysChat.swift
// LocalisysChat
//
// Created by Olexii Pyvovarov on 7/5/17.
// Copyright © 2017 Olexii Pyvovarov. All rights reserved.
//
import UIKit
import CoreText
extension UITextView {
func hasMultilineText(with size: CGSize) -> Bool {
let estimatedTextHeight: CGFloat
if (!text.isEmpty) {
estimatedTextHeight = (text as NSString)
.boundingRect(with: size, options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font!], context: nil)
.height
} else {
estimatedTextHeight = attributedText
.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil)
.height
}
let numberOfLines = estimatedTextHeight / font!.lineHeight
return numberOfLines > 1.0
}
func lines(allowedWidth width: CGFloat) -> [String] {
guard !text.isEmpty else { return [] }
guard let font = self.font else { return [] }
let ctFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attrText = NSMutableAttributedString(string: text)
attrText.addAttribute(kCTFontAttributeName as String, value: ctFont, range: NSRange(location: 0, length: attrText.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attrText)
let path = CGMutablePath()
path.addRect(.init(x: 0, y: 0, width: width - 1.5 * textContainerInset.horizontal, height: .greatestFiniteMagnitude))
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame) as! [CTLine]
var resultLines = [String]()
for line in lines {
let lineRange = CTLineGetStringRange(line)
let range = NSRange.init(location: lineRange.location, length: lineRange.length)
let lineString = (text as NSString).substring(with: range)
CFAttributedStringSetAttribute(attrText, lineRange, kCTKernAttributeName, NSNumber(value: 0))
CFAttributedStringSetAttribute(attrText, lineRange, kCTKernAttributeName, NSNumber(value: 0))
resultLines.append(lineString)
}
return resultLines
}
}
| unlicense | 12c66760856297fccecb5b679d58738a | 35.741379 | 126 | 0.710934 | 4.486316 | false | false | false | false |
1aurabrown/eidolon | Kiosk/App/AppDelegate+GlobalActions.swift | 1 | 5342 | import UIKit
import QuartzCore
public extension AppDelegate {
// Registration
func showRegistration() {
hideHelp {
// Need to give it a second to ensure view heirarchy is good.
dispatch_async(dispatch_get_main_queue()) {
let listingsVCNav = self.window.rootViewController?.childViewControllers.first! as UINavigationController
let listingVC = listingsVCNav.topViewController as ListingsViewController
if let fulfillment = listingVC.presentedViewController as? FulfillmentContainerViewController {
fulfillment.closeFulfillmentModal() {
listingVC.registerTapped(self)
}
} else {
listingVC.registerTapped(self)
}
}
}
}
// Condtions of Sale and Privacy Policy
func showConditionsOfSale() {
self.showWebControllerWithAddress("https://artsy.net/conditions-of-sale")
}
func showPrivacyPolicy() {
self.showWebControllerWithAddress("https://artsy.net/privacy")
}
func showWebControllerWithAddress(address: String) {
let block = { () -> Void in
let webController = ModalWebViewController(url: NSURL(string: address)!)
let nav = UINavigationController(rootViewController: webController)
nav!.modalPresentationStyle = .FormSheet
self.window.rootViewController?.presentViewController(nav!, animated: true, completion: nil)
self.webViewController = nav
}
if helpIsVisisble {
hideHelp {
// Need to give it a second to ensure view heirarchy is good.
dispatch_async(dispatch_get_main_queue()) {
block()
}
}
} else {
block()
}
}
// Help button and menu
typealias HelpCompletion = () -> ()
var helpIsVisisble: Bool {
return helpViewController != nil
}
var webViewControllerIsVisible: Bool {
return webViewController != nil
}
func helpButtonPressed() {
if helpIsVisisble {
hideHelp()
} else {
showHelp()
}
}
func hidewebViewController(completion: (() -> ())? = nil) {
webViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: completion)
}
func setupHelpButton() {
helpButton = MenuButton()
helpButton.setTitle("Help", forState: .Normal)
helpButton.addTarget(self, action: "helpButtonPressed", forControlEvents: .TouchUpInside)
window.addSubview(helpButton)
helpButton.alignTop(nil, leading: nil, bottom: "-24", trailing: "-24", toView: window)
window.layoutIfNeeded()
}
enum HelpButtonState {
case Help
case Close
}
func setHelpButtonState(state: HelpButtonState) {
var image: UIImage? = nil
var text: String? = nil
switch state {
case .Help:
text = "HELP"
case .Close:
image = UIImage(named: "xbtn_white")?.imageWithRenderingMode(.AlwaysOriginal)
}
helpButton.setTitle(text, forState: .Normal)
helpButton.setImage(image, forState: .Normal)
let transition = CATransition()
transition.duration = AnimationDuration.Normal
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
helpButton.layer.addAnimation(transition, forKey: "fade")
}
func showHelp(completion: HelpCompletion? = nil) {
let block = { () -> Void in
self.setHelpButtonState(.Close)
let helpViewController = HelpViewController()
helpViewController.modalPresentationStyle = .Custom
helpViewController.transitioningDelegate = self
self.window.rootViewController?.presentViewController(helpViewController, animated: true, completion: {
self.helpViewController = helpViewController
completion?()
})
}
if webViewControllerIsVisible {
hidewebViewController {
// Need to give it a second to ensure view heirarchy is good.
dispatch_async(dispatch_get_main_queue()) {
block()
}
}
} else {
block()
}
}
func hideHelp(completion: HelpCompletion? = nil) {
setHelpButtonState(.Help)
helpViewController?.presentingViewController?.dismissViewControllerAnimated(true) {
completion?()
return
}
}
}
// Help transtion animation
extension AppDelegate: UIViewControllerTransitioningDelegate {
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return HelpAnimator(presenting: true)
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return HelpAnimator()
}
}
| mit | 6c70bfddf8a4d1e39fb6e624ab0618d3 | 31.573171 | 224 | 0.619057 | 5.701174 | false | false | false | false |
LYM-mg/MGOFO | MGOFO/MGOFO/Class/Home/View/ScanBottomView.swift | 1 | 2619 | //
// ScanBottomView.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/11.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
enum MGButtonType: Int {
case photo, flash, myqrcode,intput
}
class ScanBottomView: UIView {
fileprivate lazy var myButtons: [UIButton] = [UIButton]()
var btnClickBlcok: ((_ view: ScanBottomView,_ btn: UIButton, _ type: MGButtonType)->())?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.darkGray
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置UI
extension ScanBottomView {
func setUpUI() {
// 设置UI
let btn1 = setUpBtn(image: UIImage(named: "inputBlikeNo_90x91_")!, highlightedImage: #imageLiteral(resourceName: "inputBlikeNo_90x91_"), title: "手动输入车牌号",type: .intput)
let flashBtn = setUpBtn(image: UIImage(named: "btn_unenableTorch_45x45_")!, highlightedImage: UIImage(named: "btn_enableTorch_45x45_")!, title: "手电筒",type: .flash)
// 布局UI
let margin: CGFloat = 35
let count: CGFloat = CGFloat(myButtons.count)
let width = (self.frame.width - margin*CGFloat(count+1))/count
let height = self.frame.height - margin*1
let y: CGFloat = 15
let x = margin
btn1.frame = CGRect(x: x, y: y, width: width, height: height)
flashBtn.frame = CGRect(x: MGScreenW - width - margin, y: y, width: width, height: height)
/*
for (i,btn) in myButtons.enumerated() {
let x = CGFloat(i)*width + margin
btn.frame = CGRect(x: x, y: y, width: width, height: height)
}
*/
}
func setUpBtn(image: UIImage,highlightedImage: UIImage,title: String,type: MGButtonType) -> UIButton{
let btn = MoreButton(image: image, highlightedImage: highlightedImage,title: title, target: self, action: #selector(self.btnClick(btn:)))
btn.tag = type.rawValue
self.addSubview(btn)
myButtons.append(btn)
return btn
}
@objc func btnClick(btn: UIButton) {
switch btn.tag {
case 0:
btn.isSelected = !btn.isSelected
case 1:
btn.isSelected = !btn.isSelected
case 2:
btn.isSelected = !btn.isSelected
default: break
}
if self.btnClickBlcok != nil {
btnClickBlcok!(self,btn,MGButtonType(rawValue: btn.tag)!)
}
}
}
| mit | 119e0e78b9bfcf4cf74e1815fc3b32eb | 31.708861 | 176 | 0.596362 | 3.862481 | false | false | false | false |
srn214/Floral | Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/views/CLImageAmplifyView.swift | 2 | 24135 | //
// CLImageAmplifyView.swift
// relex_swift
//
// Created by darren on 17/1/5.
// Copyright © 2017年 darren. All rights reserved.
//
import UIKit
import Photos
import PhotosUI
import ImageIO
import QuartzCore
typealias singlePictureClickSureBtnClouse = ()->()
typealias singlePictureClickEditorBtnClouse = ()->()
class CLImageAmplifyView: UIView {
private var imageArr: Array<CGImage> = [] // 图片数组(存放每一帧的图片)
private var timeArr: Array<NSNumber> = [] // 时间数组 (存放每一帧的图片的时间)
private var totalTime: Float = 0 // gif 动画时间
var originalFrame:CGRect!
@objc let manager = PHImageManager.default()
var imageRequestID: PHImageRequestID?
// 单选模式下图片是否可以编辑
@objc var singleModelImageCanEditor: Bool = false
@objc var singlePictureClickSureBtn: singlePictureClickSureBtnClouse?
@objc var singlePictureClickEditorBtn: singlePictureClickEditorBtnClouse?
var originImageAsset: PHAsset?
lazy var scrollView: UIScrollView = {
let scroll = UIScrollView()
return scroll
}()
lazy var circleBtn: CLCircleView = {
let btn = CLCircleView.init()
return btn
}()
lazy var lastImageView: UIImageView = {
let img = UIImageView()
return img
}()
lazy var selectBtn: UIButton = {
let btn = UIButton()
btn.addTarget(self, action: #selector(clickBtn), for: .touchUpInside)
return btn
}()
lazy var singleSureBtn: UIButton = {
let btn = UIButton.init()
btn.setTitle(sureStr, for: .normal)
btn.setTitleColor(mainColor, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
btn.addTarget(self, action: #selector(clickSureBtn), for: .touchUpInside)
return btn
}()
lazy var btnEditor: UIButton = {
let btnEditor = UIButton.init()
btnEditor.setTitle(editorStr, for: .normal)
btnEditor.setTitleColor(mainColor, for: .normal)
btnEditor.titleLabel?.font = UIFont.systemFont(ofSize: 16)
btnEditor.addTarget(self, action: #selector(clickEditorBtn), for: .touchUpInside)
return btnEditor
}()
@objc lazy var bottomView: UIView = {
let bottom = UIView.init()
bottom.backgroundColor = UIColor(white: 0, alpha: 0.8)
return bottom
}()
@objc static func setupAmplifyViewWithUITapGestureRecognizer(tap:UITapGestureRecognizer,superView:UIView,originImageAsset:PHAsset,isSingleChoose:Bool,singleModelImageCanEditor:Bool,isSelect: Bool) -> CLImageAmplifyView{
let amplifyView = CLImageAmplifyView.init(frame: (UIApplication.shared.keyWindow?.bounds)!)
UIApplication.shared.keyWindow?.addSubview(amplifyView)
amplifyView.setupUIWithUITapGestureRecognizer(tap: tap, superView: superView,originImageAsset:originImageAsset,isSingleChoose:isSingleChoose,singleModelImageCanEditor:singleModelImageCanEditor,isSelect: isSelect)
return amplifyView
}
func initLayout() {
let win = UIApplication.shared.keyWindow
self.bottomView.translatesAutoresizingMaskIntoConstraints = false
self.translatesAutoresizingMaskIntoConstraints = false
self.singleSureBtn.translatesAutoresizingMaskIntoConstraints = false
self.btnEditor.translatesAutoresizingMaskIntoConstraints = false
self.selectBtn.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.circleBtn.translatesAutoresizingMaskIntoConstraints = false
win?.addConstraints([
NSLayoutConstraint.init(item: self, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: win, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: win, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: win, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: win, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0)
])
self.addConstraints([
NSLayoutConstraint.init(item: self.scrollView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.scrollView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.scrollView, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.scrollView, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0)
])
if self.selectBtn.superview == self {
self.selectBtn.addConstraint(NSLayoutConstraint.init(item: self.selectBtn, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 25))
self.selectBtn.addConstraint(NSLayoutConstraint.init(item: self.selectBtn, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 25))
self.addConstraints([
NSLayoutConstraint.init(item: self.selectBtn, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 28),
NSLayoutConstraint.init(item: self.selectBtn, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -20)
])
}
if self.bottomView.superview == self {
let viewH: CGFloat = UIDevice.current.isX() == true ? 44+34:44
self.bottomView.addConstraint(NSLayoutConstraint.init(item: self.bottomView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: viewH))
self.addConstraints([
NSLayoutConstraint.init(item: self.bottomView, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.bottomView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.bottomView, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0)
])
}
if self.singleSureBtn.superview == self.bottomView {
self.singleSureBtn.addConstraint(NSLayoutConstraint.init(item: self.singleSureBtn, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 44))
self.singleSureBtn.addConstraint(NSLayoutConstraint.init(item: self.singleSureBtn, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 80))
self.bottomView.addConstraints([
NSLayoutConstraint.init(item: self.singleSureBtn, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.bottomView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.singleSureBtn, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.bottomView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
])
}
if self.btnEditor.superview == self.bottomView {
self.btnEditor.addConstraint(NSLayoutConstraint.init(item: self.btnEditor, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 44))
self.btnEditor.addConstraint(NSLayoutConstraint.init(item: self.btnEditor, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 80))
self.bottomView.addConstraints([
NSLayoutConstraint.init(item: self.btnEditor, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.bottomView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.btnEditor, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.bottomView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
])
}
if self.circleBtn.superview == self {
self.circleBtn.addConstraint(NSLayoutConstraint.init(item: self.circleBtn, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 30))
self.circleBtn.addConstraint(NSLayoutConstraint.init(item: self.circleBtn, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 30))
self.addConstraints([
NSLayoutConstraint.init(item: self.circleBtn, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -10),
NSLayoutConstraint.init(item: self.circleBtn, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: -80)
])
}
}
private func setupUIWithUITapGestureRecognizer(tap:UITapGestureRecognizer,superView:UIView,originImageAsset: PHAsset,isSingleChoose:Bool,singleModelImageCanEditor:Bool,isSelect: Bool) {
self.singleModelImageCanEditor = singleModelImageCanEditor
self.originImageAsset = originImageAsset
//scrollView作为背景
self.scrollView.frame = (UIApplication.shared.keyWindow?.bounds)!
self.scrollView.backgroundColor = UIColor.black
self.scrollView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.clickBgView(tapBgView:))))
// 点击的图片
let picView = tap.view
self.lastImageView.image = (tap.view as! UIImageView).image
self.lastImageView.frame = (self.scrollView.convert((picView?.frame)!, from: superView))
self.scrollView.addSubview((self.lastImageView))
self.addSubview(self.scrollView)
CLPickersTools.instence.getAssetOrigin(asset: originImageAsset) { (img, info) in
if img != nil {
// 等界面加载出来再复制,放置卡顿效果
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
self.lastImageView.image = img!
self.dealGif(info: info,originImageAsset:originImageAsset)
}
} else { // 说明本地没有需要到iCloud下载
self.addSubview(self.circleBtn)
let option = PHImageRequestOptions()
option.isNetworkAccessAllowed = true
option.progressHandler = {
(progress, error, stop, info) in
DispatchQueue.main.async(execute: {
print(progress, info ?? "0000",error ?? "error")
if progress*100 < 10 {
self.circleBtn.value = 10
} else {
self.circleBtn.value = CGFloat(progress*100)
}
})
}
self.imageRequestID = self.manager.requestImageData(for: originImageAsset, options: option, resultHandler: { (imageData, string, imageOrientation, info) in
if imageData != nil {
self.lastImageView.image = UIImage.init(data: imageData!)
self.circleBtn.removeFromSuperview()
self.dealGif(info: info,originImageAsset:originImageAsset)
}
})
}
}
self.originalFrame = self.lastImageView.frame
//最大放大比例
self.scrollView.maximumZoomScale = 1.5
self.scrollView.delegate = self
if isSingleChoose { // 单选
self.setupBottomView()
} else { // 多选
self.addSubview(self.selectBtn)
if isSelect {
self.setselectimg()
selectBtn.isSelected = true
} else {
self.selectBtn.setBackgroundImage(UIImage(named: "", in: BundleUtil.getCurrentBundle(), compatibleWith: nil), for: .normal)
selectBtn.isSelected = false
}
CLViewsBorder(self.selectBtn, borderWidth: 1.5, borderColor: UIColor.white, cornerRadius: 25*0.5)
}
self.initLayout()
self.show()
}
func show() {
var frameImg = self.lastImageView.frame
frameImg.size.width = (self.scrollView.cl_width)
let bili = (self.lastImageView.image?.size.height)! / (self.lastImageView.image?.size.width)!
let h = (frameImg.size.width) * bili
frameImg.size.height = h
frameImg.origin.x = 0
frameImg.origin.y = ((self.scrollView.frame.size.height) - (h)) * 0.5
if (frameImg.size.height) > UIScreen.main.bounds.height {
frameImg.origin.y = 0
self.scrollView.contentSize = CGSize(width: 0, height: (frameImg.size.height))
}
UIView.animate(withDuration: 0.5) {
self.lastImageView.frame = frameImg
}
}
@objc func clickBtn() {
self.selectBtn.isSelected = !self.selectBtn.isSelected
let model = PreviewModel()
model.phAsset = self.originImageAsset ?? PHAsset()
if self.selectBtn.isSelected {
// 判断是否超过限制
let maxCount = UserDefaults.standard.integer(forKey: CLImagePickerMaxImagesCount)
if CLPickersTools.instence.getSavePictureCount() >= maxCount {
PopViewUtil.alert(message:String(format: maxPhotoCountStr, maxCount), leftTitle: "", rightTitle: knowStr, leftHandler: {
}, rightHandler: {
})
return
}
self.setselectimg()
model.isCheck = true
CLPickersTools.instence.savePicture(asset: (model.phAsset)!, isAdd: true)
} else {
self.selectBtn.setBackgroundImage(UIImage(named: "", in: BundleUtil.getCurrentBundle(), compatibleWith: nil), for: .normal)
model.isCheck = false
CLPickersTools.instence.savePicture(asset: (model.phAsset)!, isAdd: false)
}
// 通知列表刷新状态
CLNotificationCenter.post(name: NSNotification.Name(rawValue:PreviewForSelectOrNotSelectedNotic), object: model)
// 动画
let shakeAnimation = CABasicAnimation.init(keyPath: "transform.scale")
shakeAnimation.duration = 0.1
shakeAnimation.fromValue = 0.8
shakeAnimation.toValue = 1
shakeAnimation.autoreverses = true
self.selectBtn.layer.add(shakeAnimation, forKey: nil)
}
@objc func clickBgView(tapBgView:UITapGestureRecognizer){
self.bottomView.removeFromSuperview()
self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
UIView.animate(withDuration: 0.5, animations: {
self.lastImageView.frame = self.originalFrame
self.lastImageView.contentMode = .scaleAspectFill
self.lastImageView.layer.masksToBounds = true
tapBgView.view?.backgroundColor = UIColor.clear
self.circleBtn.removeFromSuperview()
self.selectBtn.alpha = 0
if self.imageRequestID != nil {
self.manager.cancelImageRequest(self.imageRequestID!)
}
}) { (true:Bool) in
tapBgView.view?.removeFromSuperview()
self.imageRequestID = nil
self.lastImageView.removeFromSuperview()
self.selectBtn.removeFromSuperview()
self.scrollView.removeFromSuperview()
self.removeFromSuperview()
}
}
@objc func setupBottomView() {
// 编辑按钮
if self.singleModelImageCanEditor == true {
self.bottomView.addSubview(self.btnEditor)
}
self.bottomView.addSubview(self.singleSureBtn)
self.addSubview(self.bottomView)
}
@objc func clickSureBtn() {
if self.singlePictureClickSureBtn != nil {
self.singlePictureClickSureBtn!()
}
self.lastImageView.removeFromSuperview()
self.scrollView.removeFromSuperview()
self.removeFromSuperview()
if self.imageRequestID != nil {
self.manager.cancelImageRequest(self.imageRequestID!)
self.imageRequestID = nil
}
}
// 编辑图片
@objc func clickEditorBtn() {
if self.singlePictureClickEditorBtn != nil {
self.singlePictureClickEditorBtn!()
}
self.lastImageView.removeFromSuperview()
self.scrollView.removeFromSuperview()
self.removeFromSuperview()
if self.imageRequestID != nil {
self.manager.cancelImageRequest(self.imageRequestID!)
self.imageRequestID = nil
}
}
}
//返回可缩放的视图
extension CLImageAmplifyView:UIScrollViewDelegate{
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.lastImageView
}
}
extension CLImageAmplifyView: CAAnimationDelegate {
func dealGif(info: [AnyHashable:Any]?,originImageAsset: PHAsset) {
if info != nil {
let url = (info!["PHImageFileURLKey"] ?? "") as? NSURL
let urlstr = url?.path ?? ""
if urlstr.contains(".gif") || urlstr.contains(".GIF") {
let option = PHImageRequestOptions()
option.isSynchronous = true
self.manager.requestImageData(for: originImageAsset, options: option, resultHandler: { (gifImgData, str, imageOrientation, info) in
if gifImgData != nil {
self.createKeyFram(imgData: gifImgData!)
}
})
}
}
}
// 获取GIF 图片的每一帧有关的东西 比如:每一帧的图片、每一帧图片执行的时间
func createKeyFram(imgData: Data) {
let gifSource = CGImageSourceCreateWithData(imgData as CFData, nil)
if gifSource == nil {
return
}
let imageCount = CGImageSourceGetCount(gifSource!) // 总共图片张数
for i in 0..<imageCount {
let imageRef = CGImageSourceCreateImageAtIndex(gifSource!, i, nil) // 取得每一帧的图
self.imageArr.append(imageRef!)
let sourceDict = CGImageSourceCopyPropertiesAtIndex(gifSource!, i, nil) as NSDictionary?
let gifDict = sourceDict![String(kCGImagePropertyGIFDictionary)] as! NSDictionary?
let time = gifDict![String(kCGImagePropertyGIFUnclampedDelayTime)] as! NSNumber // 每一帧的动画时间
self.timeArr.append(time)
self.totalTime += time.floatValue
// 获取图片的尺寸 (适应)
let imageWidth = sourceDict![String(kCGImagePropertyPixelWidth)] as! NSNumber
let imageHeight = sourceDict![String(kCGImagePropertyPixelHeight)] as! NSNumber
if (imageWidth.floatValue / imageHeight.floatValue) != Float(self.frame.size.width/self.frame.size.height) {
self.fitScale(imageWidth: CGFloat(imageWidth.floatValue), imageHeight: CGFloat(imageHeight.floatValue))
}
}
self.showAnimation()
}
/**
* 适应
*/
private func fitScale(imageWidth: CGFloat, imageHeight: CGFloat) {
var newWidth: CGFloat
var newHeight: CGFloat
if imageWidth/imageHeight > self.bounds.width/self.bounds.height {
newWidth = self.bounds.width
newHeight = self.frame.size.width/(imageWidth/imageHeight)
} else {
newHeight = self.frame.size.height
newWidth = self.frame.size.height/(imageHeight/imageWidth)
}
let point = self.center;
self.lastImageView.frame.size = CGSize(width: newWidth, height: newHeight)
self.lastImageView.center = point
}
/**
* 展示动画
*/
private func showAnimation() {
let animation = CAKeyframeAnimation(keyPath: "contents")
var current: Float = 0
var timeKeys: Array<NSNumber> = []
for time in timeArr {
timeKeys.append(NSNumber(value: current/self.totalTime))
current += time.floatValue
}
animation.keyTimes = timeKeys
animation.delegate = self
animation.values = self.imageArr
animation.repeatCount = MAXFLOAT
animation.duration = TimeInterval(totalTime)
animation.isRemovedOnCompletion = false
self.lastImageView.layer.add(animation, forKey: "GifView")
}
// Delegate 动画结束
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
}
func setselectimg() {
let img = UIImage(named: "photo_sel_photoPicker2", in: BundleUtil.getCurrentBundle(), compatibleWith: nil)?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
self.selectBtn.setBackgroundImage(img, for: .normal)
self.selectBtn.tintColor = CLPickersTools.instence.tineColor
}
}
| mit | 7066f97552e8c540b600a05703d0ebe8 | 49.927039 | 287 | 0.6664 | 5.003584 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/PresentationLayer/Wallet/Balance/Module/BalanceModule.swift | 1 | 898 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
class BalanceModule {
class func create(app: Application) -> BalanceModuleInput {
let router = BalanceRouter()
let presenter = BalancePresenter()
let interactor = BalanceInteractor()
let viewController = R.storyboard.balance.balanceViewController()!
interactor.output = presenter
viewController.output = presenter
presenter.view = viewController
presenter.router = router
presenter.interactor = interactor
router.app = app
// MARK: - Injection
interactor.walletRepository = app.walletRepository
interactor.balanceUpdater = app.balanceUpdater
interactor.ratesUpdater = app.ratesUpdater
interactor.balanceIndexer = app.balanceIndexer
interactor.tokenIndexer = app.tokenIndexer
return presenter
}
}
| gpl-3.0 | bf431658658cc1e2ae7b03488403f922 | 23.916667 | 70 | 0.721293 | 5.096591 | false | false | false | false |
jkolb/Shkadov | Sources/Logger/LogRecord.swift | 1 | 1759 | /*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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.
*/
public struct LogRecord {
public let formattedTimestamp: String
public let level: LogLevel
public let name: String
public let threadID: UInt64
public let fileName: String
public let lineNumber: Int
public let message: String
public init(formattedTimestamp: String, level: LogLevel, name: String, threadID: UInt64, fileName: String, lineNumber: Int, message: String) {
self.formattedTimestamp = formattedTimestamp
self.level = level
self.name = name
self.threadID = threadID
self.fileName = fileName
self.lineNumber = lineNumber
self.message = message
}
}
| mit | 1d7499cc1ede3a787efb33c71f8d2143 | 39.906977 | 146 | 0.744741 | 4.886111 | false | false | false | false |
JuanjoArreola/AsyncRequest | Sources/GroupRequestHandlers.swift | 1 | 1401 | //
// GroupRequestHandlers.swift
// AsyncRequest
//
// Created by Juan Jose Arreola on 11/11/17.
//
import Foundation
class GroupRequestHandlers {
private var successHandlers: [() -> Void] = []
private var everyErrorHandlers: [(Error) -> Void] = []
private var errorsHandlers: [([Error]) -> Void] = []
private var finishHandlers: [() -> Void] = []
func add(successHandler: @escaping () -> Void) {
successHandlers.append(successHandler)
}
func add(everyErrorHandler: @escaping (Error) -> Void) {
everyErrorHandlers.append(everyErrorHandler)
}
func add(errorsHandler: @escaping ([Error]) -> Void) {
errorsHandlers.append(errorsHandler)
}
func add(finishHandler: @escaping () -> Void) {
finishHandlers.append(finishHandler)
}
// MARK: -
func completeSuccessfully() {
successHandlers.forEach({ $0() })
finishHandlers.forEach({ $0() })
clear()
}
func sendError(_ error: Error) {
everyErrorHandlers.forEach({ $0(error) })
}
func complete(with errors: [Error]) {
errorsHandlers.forEach({ $0(errors) })
finishHandlers.forEach({ $0() })
clear()
}
func clear() {
successHandlers = []
everyErrorHandlers = []
errorsHandlers = []
finishHandlers = []
}
}
| mit | 9959252eefc66efae66cf68085f2b10a | 23.578947 | 60 | 0.575303 | 4.232628 | false | false | false | false |
devpunk/velvet_room | Source/View/Connecting/VConnectingPinListCell.swift | 1 | 1434 | import UIKit
class VConnectingPinListCell:UICollectionViewCell
{
private weak var labelNumber:UILabel!
private let kCornerRadius:CGFloat = 4
override init(frame:CGRect)
{
super.init(frame:frame)
isUserInteractionEnabled = false
let background:UIView = UIView()
background.isUserInteractionEnabled = false
background.backgroundColor = UIColor(white:1, alpha:0.8)
background.translatesAutoresizingMaskIntoConstraints = false
background.layer.cornerRadius = kCornerRadius
let labelNumber:UILabel = UILabel()
labelNumber.isUserInteractionEnabled = false
labelNumber.translatesAutoresizingMaskIntoConstraints = false
labelNumber.backgroundColor = UIColor.clear
labelNumber.font = UIFont.regular(size:30)
labelNumber.textColor = UIColor.black
labelNumber.textAlignment = NSTextAlignment.center
self.labelNumber = labelNumber
addSubview(background)
addSubview(labelNumber)
NSLayoutConstraint.equals(
view:background,
toView:self)
NSLayoutConstraint.equals(
view:labelNumber,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: internal
func config(number:String)
{
labelNumber.text = number
}
}
| mit | 47b191f0addd582a9851159f91deb9cf | 27.117647 | 69 | 0.643654 | 5.829268 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.