repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
gtrdp/cs-rug-internship | BTWF/BTWF/HistoryTableViewCell.swift | 1 | 749 | //
// HistoryTableViewCell.swift
// BTWF
//
// Created by Guntur Dharma Putra on 25/05/16.
// Copyright © 2016 Guntur Dharma Putra. All rights reserved.
//
import UIKit
class HistoryTableViewCell: UITableViewCell {
@IBOutlet weak var methodLabel: UILabel!
@IBOutlet weak var sentPacketsLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var timeIntervalLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
uber/rides-ios-sdk | source/UberCoreTests/LoginButtonTests.swift | 1 | 4911 | //
// LoginButtonTests.swift
// UberRides
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import CoreLocation
@testable import UberCore
class LoginButtonTests : XCTestCase {
private var keychain: KeychainWrapper!
private var testToken: AccessToken!
override func setUp() {
super.setUp()
Configuration.plistName = "testInfo"
Configuration.restoreDefaults()
Configuration.shared.isSandbox = true
keychain = KeychainWrapper()
testToken = AccessToken(tokenString: "testTokenString")
}
override func tearDown() {
Configuration.restoreDefaults()
keychain = nil
super.tearDown()
}
func testButtonState_whenSignedOut() {
let identifier = "testIdentifier"
_ = keychain.deleteObjectForKey(identifier)
let token = TokenManager.fetchToken(identifier: identifier)
XCTAssertNil(token)
let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit)
let loginButton = LoginButton(frame: CGRect.zero, scopes: [], loginManager: loginManager)
XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedOut)
_ = keychain.deleteObjectForKey(identifier)
}
func testLabelText_whenSignedIn() {
let identifier = "testIdentifier"
let token: AccessToken = testToken
XCTAssertTrue(keychain.setObject(token, key: identifier))
let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit)
let loginButton = LoginButton(frame: CGRect.zero, scopes: [], loginManager: loginManager)
XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedIn)
XCTAssertTrue(keychain.deleteObjectForKey(identifier))
}
func testLoginCalled_whenSignedOut() {
let identifier = "testIdentifier"
_ = keychain.deleteObjectForKey(identifier)
let token = TokenManager.fetchToken(identifier: identifier)
XCTAssertNil(token)
let expectation = self.expectation(description: "Expected executeLogin() called")
let loginManager = LoginManagerPartialMock(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit)
loginManager.executeLoginClosure = { _ in
expectation.fulfill()
}
let loginButton = LoginButton(frame: CGRect.zero, scopes: [.profile], loginManager: loginManager)
loginButton.presentingViewController = UIViewController()
XCTAssertNotNil(loginButton)
XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedOut)
loginButton.uberButtonTapped(loginButton)
waitForExpectations(timeout: 0.2) { _ in
_ = self.keychain.deleteObjectForKey(identifier)
}
}
func testLogOut_whenSignedIn() {
let identifier = "testIdentifier"
_ = keychain.deleteObjectForKey(identifier)
let token: AccessToken = testToken
XCTAssertTrue(keychain.setObject(token, key: identifier))
let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit)
let loginButton = LoginButton(frame: CGRect.zero, scopes: [.profile], loginManager: loginManager)
loginButton.presentingViewController = UIViewController()
XCTAssertNotNil(loginButton)
XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedIn)
loginButton.uberButtonTapped(loginButton)
XCTAssertNil(TokenManager.fetchToken(identifier: identifier))
_ = keychain.deleteObjectForKey(identifier)
}
}
| mit |
nikita-leonov/tispr-card-stack | TisprCardStackExample/TisprCardStackExample/TisprCardStackDemoViewCell.swift | 2 | 1969 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// TisprCardStackDemoViewCell.swift
// TisprCardStackExample
//
// Created by Andrei Pitsko on 7/12/15.
// Copyright (c) 2015 BuddyHopp Inc. All rights reserved.
//
import UIKit
import TisprCardStack
class TisprCardStackDemoViewCell: TisprCardStackViewCell {
@IBOutlet weak var text: UILabel!
@IBOutlet weak var voteSmile: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 12
clipsToBounds = false
}
override var center: CGPoint {
didSet {
updateSmileVote()
}
}
override internal func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) {
super.applyLayoutAttributes(layoutAttributes)
updateSmileVote()
}
func updateSmileVote() {
let rotation = atan2(transform.b, transform.a)
if rotation == 0 {
voteSmile.hidden = true
} else {
voteSmile.hidden = false
let voteSmileImageName = (rotation > 0) ? "smile_face" : "rotten_face"
voteSmile.image = UIImage(named: voteSmileImageName)
}
}
} | apache-2.0 |
ZoranPandovski/al-go-rithms | sort/radix_sort/swift/radixSort.swift | 1 | 530 | extension Array where Element == Int {
public mutating func radixSort() {
let base = 10
var done = false
var digits = 1
while !done {
done = true
var buckets: [[Int]] = .init(repeating: [], count: base)
forEach {
number in
let remainingPart = number / digits
let digit = remainingPart % base
buckets[digit].append(number)
if remainingPart > 0 {
done = false
}
}
digits *= base
self = buckets.flatMap { $0 }
}
}
} | cc0-1.0 |
nethergrim/xpolo | XPolo/XPolo/TickerCell.swift | 1 | 966 | //
// TickerCell.swift
// XPolo
//
// Created by Андрей Дробязко on 26.06.17.
// Copyright © 2017 Андрей Дробязко. All rights reserved.
//
import UIKit
class TickerCell: UITableViewCell {
@IBOutlet weak var star: UIImageView!
@IBOutlet weak var coin: UILabel!
@IBOutlet weak var price: UILabel!
@IBOutlet weak var volume: UILabel!
@IBOutlet weak var change: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
public func bind(ticker: LocalTicker){
coin.addCharactersSpacing(spacing: 0.2, text: ticker.primalCoinName)
price.text = ticker.last
volume.text = ticker.baseVolume
change.text = ticker.percentChange
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if (selected){
setSelected(false, animated: true)
}
}
}
| gpl-3.0 |
diatrevolo/GameplaykitPDA | GameplaykitPDA/GameplaykitPDA_iosTests/GameplaykitPDA_iosTests.swift | 1 | 1339 | //
// GameplaykitPDATests.swift
// GameplaykitPDATests
//
// Created by Roberto Osorio Goenaga on 8/13/15.
// Copyright © 2015 Roberto Osorio Goenaga. All rights reserved.
//
import XCTest
class GameplaykitPDA_iosTests: XCTestCase {
var pushdownAutomaton: PushdownAutomaton?
override func setUp() {
super.setUp()
self.pushdownAutomaton = PushdownAutomaton(states: [OneState(), TwoState()], firstElement: StackElement())
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStack() {
let currentElement = self.pushdownAutomaton!.currentElement
self.pushdownAutomaton?.pushToStack(currentElement!)
self.pushdownAutomaton?.enterState(TwoState)
XCTAssertTrue(currentElement?.currentState != self.pushdownAutomaton?.currentElement?.currentState)
self.pushdownAutomaton?.popAndPush()
XCTAssertTrue(currentElement?.currentState == self.pushdownAutomaton?.currentElement?.currentState)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
pocketworks/Dollar.swift | Cent/Cent/Optional.swift | 1 | 191 | //
// Optional.swift
//
//
// Created by Harlan Haskins on 3/3/15.
//
//
import Foundation
//func ==<T: Equatable>(value: T?, other: T?) -> Bool {
// return $.equal(value, other)
//} | mit |
DataBreweryIncubator/StructuredQuery | Sources/Compiler/Dialect.swift | 1 | 539 | import Types
import Relation
/// Protocol that specifies a SQL dialect properties.
protocol Dialect {
func binaryOperator(_ name:String) -> Operator?
func unaryOperator(_ name:String) -> Operator?
}
/// Default SQL dialect that other dialects are recommended to inherit from.
class DefaultDialect: Dialect {
func binaryOperator(_ name:String) -> Operator? {
return BasicBinaryOperators[name] ?? nil
}
func unaryOperator(_ name:String) -> Operator? {
return BasicUnaryOperators[name] ?? nil
}
}
| mit |
Somnibyte/MLKit | Example/MLKit/AppDelegate.swift | 1 | 2168 | //
// AppDelegate.swift
// MLKit
//
// Created by Guled Ahmed on 02/20/2017.
// Copyright (c) 2017 Guled Ahmed. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/01750-swift-modulefile-gettype.swift | 11 | 470 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class C<f : Sequence, object2: d where I) {
func a<T {
class A {
}
class d: A
| apache-2.0 |
ledwards/ios-flicks | Flicks/AppDelegate.swift | 1 | 3450 | //
// AppDelegate.swift
// Flicks
//
// Created by Lee Edwards on 2/1/16.
// Copyright © 2016 Lee Edwards. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing")
let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
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 |
cocoascientist/Playgrounds | MultiThreading.playground/Contents.swift | 1 | 1927 | //: # Multithreading with GCD
import Cocoa
import XCPlayground
//: First we define a function do perform some simulated work. In the real world, this could be parsing a complex JSON file, compressing a file to disk, or some other long running task.
func countTo(limit: Int) -> Int {
var total = 0
for _ in 1...limit {
total += 1
}
return total
}
//: Next we grab a reference to a global dispatch queue for running tasks.
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//: A block is function that has no parmaters and returns nothing. In GCD terms, this is defined as the `dispatch_block_t` type. Blocks are typically declaring inline when a call to GCD is made.
let block: dispatch_block_t = { () -> Void in
countTo(100)
print("done with single block")
}
dispatch_async(queue, block)
//: Multiple tasks be arranged together in a group. This makes it possible to wait for the result of multiple asynchronous tasks.
let group = dispatch_group_create()
dispatch_group_enter(group)
dispatch_group_enter(group)
dispatch_async(queue, { () -> Void in
countTo(10)
print("finished first grouped task")
dispatch_group_leave(group)
})
dispatch_async(queue, { () -> Void in
countTo(20)
print("finished second grouped task")
dispatch_group_leave(group)
})
dispatch_group_notify(group, queue) { () -> Void in
print("finished ALL grouped tasks")
}
//: Queues can have differnt priority levels.
let high = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
let low = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
let background = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
//: The playground needs to continue to run indefinitely. It doesn't matter if we put this statement at the top or bottom of the playground. I prefer it at the bottom.
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
| mit |
SwiftKit/Reactant | Example/Application/Sources/Components/Table/TableViewController.swift | 2 | 954 | //
// TableViewController.swift
// Reactant
//
// Created by Matous Hybl on 3/24/17.
// Copyright © 2017 Brightify s.r.o. All rights reserved.
//
import Reactant
class TableViewController: ControllerBase<Void, TableViewRootView> {
struct Dependencies {
let nameService: NameService
}
struct Reactions {
let displayName: (String) -> Void
}
private let dependencies: Dependencies
private let reactions: Reactions
init(dependencies: Dependencies, reactions: Reactions) {
self.dependencies = dependencies
self.reactions = reactions
super.init()
}
override func update() {
rootView.componentState = .items(dependencies.nameService.names())
}
override func act(on action: TableViewRootView.ActionType) {
switch action {
case .selected(let name):
reactions.displayName(name)
default:
break
}
}
}
| mit |
cschlessinger/dbc-civichack-artistnonprofit | iOS/DevBootcampHackathon/DevBootcampHackathon/ViewController.swift | 1 | 2229 | //
// ViewController.swift
// DevBootcampHackathon
//
// Created by Lucas Farah on 1/23/16.
// Copyright © 2016 Lucas Farah. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ImagePickerDelegate {
var arrCat = ["Senior","Homeless","Children","Animals"]
var arrCatNum = ["109","230","59","90"]
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource
{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrCat.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCell!
if !(cell != nil)
{
cell = TableViewCell(style:.Default, reuseIdentifier: "cell")
}
let imgvName = arrCat[indexPath.row] + ".jpg"
// setup cell without force unwrapping it
cell.lblName.text = arrCat[indexPath.row]
cell.lblNumber.text = arrCatNum[indexPath.row]
cell.imgvCat.image = UIImage(named: imgvName)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
self.performSegueWithIdentifier("selected", sender: self)
}
func wrapperDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func doneButtonDidPress(images: [UIImage])
{
self.dismissViewControllerAnimated(true, completion: nil)
}
func cancelButtonDidPress()
{
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func butCamera(sender: AnyObject)
{
let imagePickerController = ImagePickerController()
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
}
| mit |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Home/Controller/HomeViewController.swift | 1 | 2620 | //
// HomeViewController.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/7/28.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
private let kPageTitleVH: CGFloat = 40
class HomeViewController: UIViewController,
PageTitleViewDelegate,
PageContentViewDelegate
{
// MARK: - 属性
private lazy var pageTitleV: PageTitleView = {
let v = PageTitleView(frame: CGRect(x: 0, y: kNavigationBarBottom, width: kScreenW, height: kPageTitleVH), titles: ["推荐", "游戏", "娱乐", "趣玩"])
v.delegate = self
return v
}()
private lazy var pageContentV: PageContentView = {
// 设置 frame
let frame = CGRect(x: 0, y: kNavigationBarBottom + kPageTitleVH, width: kScreenW, height: kScreenH - kNavigationBarBottom - kPageTitleVH - kTabBarH)
// 添加自控制器
var vcs = [UIViewController]()
vcs.append(RecommendViewController())
vcs.append(GameViewController())
vcs.append(AmuseViewController())
vcs.append(FunnyViewController())
let v = PageContentView(frame: frame, childVCs: vcs, parentVC: self)
v.delegate = self
return v
}()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
// MARK: - PageTitleViewDelegate
func pageTitleView(_ view: PageTitleView, didSelectedAt index: Int) {
pageContentV.setCurrentIndex(index)
}
// MARK: - PageContentViewDelegate
func pageContentVeiw(_ view: PageContentView, didScroll progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleV.scrollTitle(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
// MARK: - UI
private func setupUI() {
// 不自动调整 scrollView 的偏移量
automaticallyAdjustsScrollViewInsets = false
setupNavigationBar()
view.addSubview(pageTitleV)
view.addSubview(pageContentV)
}
private func setupNavigationBar() {
// 设置左侧 Item
navigationItem.leftBarButtonItem = UIBarButtonItem(normalImgName: "logo")
// 设置右侧 Items
navigationItem.rightBarButtonItems =
[UIBarButtonItem(normalImgName: "image_my_history", highlightImgName: "Image_my_history_click", width: 38),
UIBarButtonItem(normalImgName: "btn_search", highlightImgName: "btn_search_clicked", width: 38),
UIBarButtonItem(normalImgName: "Image_scan", highlightImgName: "Image_scan_click", width: 38)]
}
}
| mit |
bazelbuild/tulsi | src/TulsiGeneratorIntegrationTests/EndToEndIntegrationTestCase.swift | 1 | 12852 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import BazelIntegrationTestCase
@testable import TulsiGenerator
// Base class for end-to-end tests that generate xcodeproj bundles and validate them against golden
// versions.
class EndToEndIntegrationTestCase : BazelIntegrationTestCase {
enum Error: Swift.Error {
/// A subdirectory for the Xcode project could not be created.
case testSubdirectoryNotCreated
/// The Xcode project could not be generated.
case projectGenerationFailure(String)
/// Unable to execute user_build.py script.
case userBuildScriptInvocationFailure(String)
}
let extraDebugFlags = ["--define=TULSI_TEST=dbg"]
let extraReleaseFlags = ["--define=TULSI_TEST=rel"]
let fakeBazelURL = URL(fileURLWithPath: "/fake/tulsi_test_bazel", isDirectory: false)
let testTulsiVersion = "9.99.999.9999"
final func validateDiff(_ diffLines: [String], for resourceName: String, file: StaticString = #file, line: UInt = #line) {
guard !diffLines.isEmpty else { return }
let message = "\(resourceName) xcodeproj does not match its golden. Diff output:\n\(diffLines.joined(separator: "\n"))"
XCTFail(message, file: file, line: line)
}
final func diffProjectAt(_ projectURL: URL,
againstGoldenProject resourceName: String,
file: StaticString = #file,
line: UInt = #line) -> [String] {
guard let hashing = ProcessInfo.processInfo.environment["SWIFT_DETERMINISTIC_HASHING"],
hashing == "1" else {
XCTFail("Must define environment variable \"SWIFT_DETERMINISTIC_HASHING=1\", or golden tests will fail.")
return []
}
let goldenProjectURL = workspaceRootURL.appendingPathComponent(fakeBazelWorkspace
.resourcesPathBase,
isDirectory: true)
.appendingPathComponent("GoldenProjects/\(resourceName).xcodeproj", isDirectory: true)
guard FileManager.default.fileExists(atPath: goldenProjectURL.path) else {
assertionFailure("Missing required test resource file \(resourceName).xcodeproj")
XCTFail("Missing required test resource file \(resourceName).xcodeproj",
file: file,
line: line)
return []
}
var diffOutput = [String]()
let semaphore = DispatchSemaphore(value: 0)
let process = ProcessRunner.createProcess("/usr/bin/diff",
arguments: ["-r",
// For the sake of simplicity in
// maintaining the golden data, copied
// Tulsi artifacts are assumed to have
// been installed correctly.
"--exclude=.tulsi",
projectURL.path,
goldenProjectURL.path]) {
completionInfo in
defer {
semaphore.signal()
}
if let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) {
diffOutput = stdout.components(separatedBy: "\n").filter({ !$0.isEmpty })
} else {
XCTFail("No output received for diff command", file: file, line: line)
}
}
process.currentDirectoryPath = workspaceRootURL.path
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return diffOutput
}
final func copyOutput(source: URL, outputDir: String) throws {
if testUndeclaredOutputsDir != nil {
guard let testOutputURL = makeTestSubdirectory(outputDir,
rootDirectory: testUndeclaredOutputsDir,
cleanupOnTeardown: false) else {
throw Error.testSubdirectoryNotCreated
}
let testOutputProjURL = testOutputURL.appendingPathComponent(source.lastPathComponent)
if FileManager.default.fileExists(atPath: testOutputProjURL.path) {
try FileManager.default.removeItem(at: testOutputProjURL)
}
try FileManager.default.copyItem(at: source, to: testOutputProjURL)
}
}
final func validateBuildCommandForProject(_ projectURL: URL,
swift: Bool = false,
options: TulsiOptionSet = TulsiOptionSet(),
targets: [String]) throws {
let actualDebug = try userBuildCommandForProject(projectURL, release: false, targets: targets)
let actualRelease = try userBuildCommandForProject(projectURL, release: true, targets: targets)
let (debug, release) = expectedBuildCommands(swift: swift, options: options, targets: targets)
XCTAssertEqual(actualDebug, debug)
XCTAssertEqual(actualRelease, release)
}
final func expectedBuildCommands(swift: Bool,
options: TulsiOptionSet,
targets: [String]) -> (String, String) {
let provider = BazelSettingsProvider(universalFlags: bazelUniversalFlags)
let features = BazelBuildSettingsFeatures.enabledFeatures(options: options)
let dbg = provider.tulsiFlags(hasSwift: swift, options: options, features: features).debug
let rel = provider.tulsiFlags(hasSwift: swift, options: options, features: features).release
let config: PlatformConfiguration
if let identifier = options[.ProjectGenerationPlatformConfiguration].commonValue,
let parsedConfig = PlatformConfiguration(identifier: identifier) {
config = parsedConfig
} else {
config = PlatformConfiguration.defaultConfiguration
}
func buildCommand(extraBuildFlags: [String], tulsiFlags: BazelFlags) -> String {
var args = [fakeBazelURL.path]
args.append(contentsOf: bazelStartupOptions)
args.append(contentsOf: tulsiFlags.startup)
args.append("build")
args.append(contentsOf: extraBuildFlags)
args.append(contentsOf: bazelBuildOptions)
args.append(contentsOf: config.bazelFlags)
args.append(contentsOf: tulsiFlags.build)
args.append("--tool_tag=tulsi:user_build")
args.append(contentsOf: targets)
return args.map { $0.escapingForShell }.joined(separator: " ")
}
let debugCommand = buildCommand(extraBuildFlags: extraDebugFlags, tulsiFlags: dbg)
let releaseCommand = buildCommand(extraBuildFlags: extraReleaseFlags, tulsiFlags: rel)
return (debugCommand, releaseCommand)
}
final func userBuildCommandForProject(_ projectURL: URL,
release: Bool = false,
targets: [String],
file: StaticString = #file,
line: UInt = #line) throws -> String {
let expectedScriptURL = projectURL.appendingPathComponent(".tulsi/Scripts/user_build.py",
isDirectory: false)
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: expectedScriptURL.path) else {
throw Error.userBuildScriptInvocationFailure(
"user_build.py script not found: expected at path \(expectedScriptURL.path)")
}
var output = "<none>"
let semaphore = DispatchSemaphore(value: 0)
var args = [
"--norun",
]
if release {
args.append("--release")
}
args.append(contentsOf: targets)
let process = ProcessRunner.createProcess(
expectedScriptURL.path,
arguments: args,
messageLogger: localizedMessageLogger
) { completionInfo in
defer {
semaphore.signal()
}
let exitcode = completionInfo.terminationStatus
guard exitcode == 0 else {
let stderr =
String(data: completionInfo.stderr, encoding: .utf8) ?? "<no stderr>"
XCTFail("user_build.py returned \(exitcode). stderr: \(stderr)", file: file, line: line)
return
}
if let stdout = String(data: completionInfo.stdout, encoding: .utf8)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines),
!stdout.isEmpty {
output = stdout
} else {
let stderr =
String(data: completionInfo.stderr, encoding: .utf8) ?? "<no stderr>"
XCTFail("user_build.py had no stdout. stderr: \(stderr)", file: file, line: line)
}
}
process.currentDirectoryPath = workspaceRootURL.path
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return output
}
final func generateProjectNamed(_ projectName: String,
buildTargets: [RuleInfo],
pathFilters: [String],
additionalFilePaths: [String] = [],
outputDir: String,
options: TulsiOptionSet = TulsiOptionSet()) throws -> URL {
if !bazelStartupOptions.isEmpty {
let startupFlags = bazelStartupOptions.joined(separator: " ")
options[.BazelBuildStartupOptionsDebug].projectValue = startupFlags
options[.BazelBuildStartupOptionsRelease].projectValue = startupFlags
}
let debugBuildOptions = extraDebugFlags + bazelBuildOptions
let releaseBuildOptions = extraReleaseFlags + bazelBuildOptions
options[.BazelBuildOptionsDebug].projectValue = debugBuildOptions.joined(separator: " ")
options[.BazelBuildOptionsRelease].projectValue = releaseBuildOptions.joined(separator: " ")
let bazelURLParam = TulsiParameter(value: fakeBazelURL, source: .explicitlyProvided)
let config = TulsiGeneratorConfig(projectName: projectName,
buildTargets: buildTargets,
pathFilters: Set<String>(pathFilters),
additionalFilePaths: additionalFilePaths,
options: options,
bazelURL: bazelURLParam)
guard let outputFolderURL = makeXcodeProjPath(outputDir) else {
throw Error.testSubdirectoryNotCreated
}
let projectGenerator = TulsiXcodeProjectGenerator(workspaceRootURL: workspaceRootURL,
config: config,
extractorBazelURL: bazelURL,
tulsiVersion: testTulsiVersion)
// Bazel built-in preprocessor defines are suppressed in order to prevent any
// environment-dependent variables from mismatching the golden data.
projectGenerator.xcodeProjectGenerator.suppressCompilerDefines = true
// Don't update shell command utilities.
projectGenerator.xcodeProjectGenerator.suppressUpdatingShellCommands = true
// Don't install module cache pruner tool.
projectGenerator.xcodeProjectGenerator.suppressModuleCachePrunerInstallation = true
// The username is forced to a known value.
projectGenerator.xcodeProjectGenerator.usernameFetcher = { "_TEST_USER_" }
// Omit bazel output symlinks so they don't have unknown values.
projectGenerator.xcodeProjectGenerator.redactSymlinksToBazelOutput = true
let errorInfo: String
do {
let generatedProjURL = try projectGenerator.generateXcodeProjectInFolder(outputFolderURL)
try copyOutput(source: generatedProjURL, outputDir: outputDir)
return generatedProjURL
} catch TulsiXcodeProjectGenerator.GeneratorError.unsupportedTargetType(let targetType) {
errorInfo = "Unsupported target type: \(targetType)"
} catch TulsiXcodeProjectGenerator.GeneratorError.serializationFailed(let details) {
errorInfo = "General failure: \(details)"
} catch let error {
errorInfo = "Unexpected failure: \(error)"
}
throw Error.projectGenerationFailure(errorInfo)
}
}
| apache-2.0 |
S7Vyto/Mobile | iOS/SVCalendarView/SVCalendarView/Calendar/Extensions/SVColorExtension.swift | 1 | 517 | //
// SVColorExtension.swift
// SVCalendarView
//
// Created by Sam on 12/11/2016.
// Copyright © 2016 Semyon Vyatkin. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static func rgb(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> UIColor {
return UIColor.rgbа(r, g, b, 1.0)
}
static func rgbа(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat) -> UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
}
| apache-2.0 |
jtbandes/swift | test/decl/nested/protocol.swift | 2 | 2765 | // RUN: %target-typecheck-verify-swift -parse-as-library
// Protocols cannot be nested inside other types, and types cannot
// be nested inside protocols
struct OuterGeneric<D> {
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ t: D) // expected-error{{use of undeclared type 'D'}}
}
}
class OuterGenericClass<T> {
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ t: T) // expected-error{{use of undeclared type 'T'}}
}
}
protocol OuterProtocol {
associatedtype Hen
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
// expected-note@-1 {{did you mean 'InnerProtocol'?}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ h: Hen) // expected-error{{use of undeclared type 'Hen'}}
}
}
struct ConformsToOuterProtocol : OuterProtocol {
typealias Hen = Int
func f() { let _ = InnerProtocol.self }
// expected-error@-1 {{use of unresolved identifier 'InnerProtocol'}}
}
protocol Racoon {
associatedtype Stripes
class Claw<T> { // expected-error{{type 'Claw' cannot be nested in protocol 'Racoon'}}
func mangle(_ s: Stripes) {}
}
struct Fang<T> { // expected-error{{type 'Fang' cannot be nested in protocol 'Racoon'}}
func gnaw(_ s: Stripes) {}
}
enum Fur { // expected-error{{type 'Fur' cannot be nested in protocol 'Racoon'}}
case Stripes
}
}
enum SillyRawEnum : SillyProtocol.InnerClass {}
// expected-error@-1 {{reference to generic type 'SillyProtocol.InnerClass' requires arguments in <...>}}
// expected-error@-2 {{type 'SillyRawEnum' does not conform to protocol 'RawRepresentable'}}
protocol SillyProtocol {
class InnerClass<T> {} // expected-error {{type 'InnerClass' cannot be nested in protocol 'SillyProtocol'}}
// expected-note@-1 {{generic type 'InnerClass' declared here}}
}
enum OuterEnum {
protocol C {} // expected-error{{protocol 'C' cannot be nested inside another declaration}}
// expected-note@-1{{'C' previously declared here}}
case C(C) // expected-error{{invalid redeclaration of 'C'}}
}
class OuterClass {
protocol InnerProtocol : OuterClass { }
// expected-error@-1{{non-class type 'InnerProtocol' cannot inherit from class 'OuterClass'}}
// expected-error@-2{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
}
class OtherGenericClass<T> {
protocol InnerProtocol : OtherGenericClass { }
// expected-error@-1{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
}
| apache-2.0 |
thoughtworks/dancing-glyphs | GlyphWave/Configuration.swift | 1 | 1770 | /*
* Copyright 2016 Erik Doernenburg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use these files 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 ScreenSaver
class Configuration
{
enum WaveType: Int {
case linear, circular
}
static let sharedInstance = Configuration()
let numSprites = 600
let glyphSize = 0.1
let backgroundColor = NSColor.black
var defaults: UserDefaults
var waveType: WaveType = WaveType.linear
init()
{
let identifier = Bundle(for: Configuration.self).bundleIdentifier!
defaults = ScreenSaverDefaults(forModuleWithName: identifier)! as UserDefaults
defaults.register(defaults: [
String(describing: Wave.self): -1,
])
update()
}
var waveTypeCode: Int
{
set { defaults.set(newValue, forKey: String(describing: Wave.self)); update() }
get { return defaults.integer(forKey: String(describing: Wave.self)) }
}
private func update()
{
defaults.synchronize()
waveType = Util.enumForCode(waveTypeCode, defaultCase: WaveType.linear)
}
var wave: Wave
{
get
{
return (waveType == .linear) ? (LinearWave() as Wave) : (CircularWave() as Wave)
}
}
}
| apache-2.0 |
MukeshKumarS/Swift | test/expr/closure/basic.swift | 1 | 991 | // RUN: %target-parse-verify-swift
func takeIntToInt(f: (Int) -> Int) { }
func takeIntIntToInt(f: (Int, Int) -> Int) { }
// Simple closures
func simple() {
takeIntToInt({(x: Int) -> Int in
return x + 1
})
takeIntIntToInt({(x: Int, y: Int) -> Int in
return x + y
})
}
// Closures with variadic argument lists
func variadic() {
var f = {(start: Int, rest: Int...) -> Int in
var result = start
for x in rest {
result += x
}
return result
}
f(1)
f(1, 2)
f(1, 3)
let D = { (Ss ...) in 1 } // expected-error{{'...' cannot be applied to a subpattern which is not explicitly typed}}, expected-error{{unable to infer closure type in the current context}}
}
// Closures with attributes in the parameter list.
func attrs() {
_ = {(inout z: Int) -> Int in z }
}
// Closures with argument and parameter names.
func argAndParamNames() -> Int {
let f1: (x: Int, y: Int) -> Int = { (a x, b y) in x + y }
f1(x: 1, y: 2)
return f1(x: 1, y: 2)
}
| apache-2.0 |
GoogleCloudPlatform/google-cloud-iot-arduino | examples/complex/esp32/ios-gateway/extras/iOS_IoTCore_Client_Demo/SceneDelegate.swift | 1 | 2958 | //**************************************************************************
// Copyright 2020 Google
// 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 SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| apache-2.0 |
Eonil/EditorLegacy | Modules/EditorUIComponents/EditorUIComponents/MultipaneViewController.swift | 1 | 5475 | //
// MultipaneView.swift
// Editor
//
// Created by Hoon H. on 2015/02/04.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import AppKit.NSView
import AppKitExtras
//public protocol MultipaneViewControllerDelegate: class {
//// func multipaneViewController(MultipaneViewController, shouldSelectPaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, didSelectPaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, didHidePaneAtIndex:Int)
//// func multipaneViewController(MultipaneViewController, willShowPaneAtIndex:Int)
//}
public final class MultipaneViewController: NSViewController {
// public weak var delegate:MultipaneViewControllerDelegate?
public var pageSelectionIndex:Int? = nil {
didSet {
_currentPageViewController = pageSelectionIndex == nil ? nil : self.pages[pageSelectionIndex!].viewController
}
}
public var pages:[Page] = [] {
willSet {
assert(pageSelectionIndex == nil, "You must set `pageSelectionIndex` to `nil` before removing selected page.")
_selectorSegmentView.segmentCount = 0
_selectorSegmentView.sizeToFit()
if self.pages.count == 0 {
pageSelectionIndex = nil
}
for p in self.pages {
assert(p.viewController.view.superview === self)
}
}
didSet {
for p in self.pages {
assert(p.viewController.view.superview === nil)
assert(p.viewController.view.translatesAutoresizingMaskIntoConstraints == false, "Page view MUST have `translatesAutoresizingMaskIntoConstraints` property set to `false`.")
}
_selectorSegmentView.segmentCount = pages.count
for i in 0..<pages.count {
let p = pages[i]
_selectorSegmentView.setLabel(p.labelText, forSegment: i)
}
_selectorSegmentView.sizeToFit()
}
}
////
public override func loadView() {
super.view = NSView()
}
public override func viewDidLoad() {
super.viewDidLoad()
_selectorSegmentView.controlSize = NSControlSize.SmallControlSize
_selectorSegmentView.segmentStyle = NSSegmentStyle.Automatic
_selectorSegmentView.font = NSFont.systemFontOfSize(NSFont.smallSystemFontSize())
_selectorSegmentView.sizeToFit()
let h = _selectorSegmentView.frame.size.height
_selectorStackView.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
_selectorStackView.setViews([_selectorSegmentView], inGravity: NSStackViewGravity.Center)
_selectorSegmentView.translatesAutoresizingMaskIntoConstraints = false
_selectorStackView.translatesAutoresizingMaskIntoConstraints = false
_contentHostingView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(_contentHostingView)
self.view.addSubview(_selectorStackView)
self.view.needsLayout = true
self.view.addConstraintsWithLayoutAnchoring([
_selectorStackView.centerXAnchor == self.view.centerXAnchor,
_selectorStackView.topAnchor == self.view.topAnchor,
_contentHostingView.leftAnchor == self.view.leftAnchor,
_contentHostingView.rightAnchor == self.view.rightAnchor,
_contentHostingView.topAnchor == _selectorStackView.bottomAnchor,
_contentHostingView.bottomAnchor == self.view.bottomAnchor,
])
self.view.addConstraints([
NSLayoutConstraint(item: _selectorSegmentView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: h)
])
////
_selectorSegmentView.sizeToFit()
_subcomponentDelegate = SubcomponentDelegate(owner: self)
_selectorSegmentView.target = _subcomponentDelegate
_selectorSegmentView.action = "onPageSelectorValueChanged:"
}
////
private let _selectorSegmentView = NSSegmentedControl()
private let _selectorStackView = NSStackView()
private let _contentHostingView = NSView()
private var _subcomponentDelegate = nil as SubcomponentDelegate?
private var _selectionConstraints = nil as [NSLayoutConstraint]?
private var _currentPageViewController:NSViewController? {
willSet {
if let vc = _currentPageViewController {
_contentHostingView.removeConstraints(_selectionConstraints!)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
_selectionConstraints = nil
}
}
didSet {
if let vc = _currentPageViewController {
assert(vc.view.translatesAutoresizingMaskIntoConstraints == false, "Selected view MUST have `translatesAutoresizingMaskIntoConstraints` property set to `false`.")
self.addChildViewController(vc)
_contentHostingView.addSubview(vc.view)
_selectionConstraints = _contentHostingView.addConstraintsWithLayoutAnchoring([
vc.view.centerAnchor == _contentHostingView.centerAnchor,
vc.view.sizeAnchor == _contentHostingView.sizeAnchor,
])
}
}
}
}
public extension MultipaneViewController {
public struct Page {
// public var icon:NSImage
public var labelText:String
public var viewController:NSViewController
public init(labelText:String, viewController:NSViewController) {
self.labelText = labelText
self.viewController = viewController
}
}
}
@objc
private final class SubcomponentDelegate: NSObject {
unowned let owner:MultipaneViewController
init(owner:MultipaneViewController) {
self.owner = owner
}
@objc
func onPageSelectorValueChanged(AnyObject?) {
let i = owner._selectorSegmentView.selectedSegment
let p = owner.pages[i]
owner._currentPageViewController = p.viewController
}
}
| mit |
wjk930726/weibo | weiBo/weiBo/iPhone/Modules/View/OAuthViewController/WBOAuthViewController.swift | 1 | 4413 | //
// WBOAuthViewController.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/26.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import SnapKit
import UIKit
class WBOAuthViewController: UIViewController {
lazy var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
lazy var webView: UIWebView = {
// let webView = UIWebView(frame: self.view.bounds)
let webView = UIWebView()
webView.scrollView.bounces = false
webView.scrollView.backgroundColor = UIColor.colorWithHex(hex: 0xEBEDEF)
webView.delegate = self
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension WBOAuthViewController {
func setupUI() {
view.backgroundColor = UIColor.white
navigationItem.leftBarButtonItem = leftBarButtonItem
view.addSubview(webView)
webView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.view)
if #available(iOS 11, *) {
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.topMargin)
make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottomMargin)
} else {
make.top.bottom.equalTo(self.view)
}
}
let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
if let url = URL(string: urlStr) {
webView.loadRequest(URLRequest(url: url))
}
}
}
extension WBOAuthViewController {
@objc fileprivate func cancel() {
dismiss(animated: true, completion: nil)
}
}
extension WBOAuthViewController: UIWebViewDelegate {
func webView(_: UIWebView, shouldStartLoadWith request: URLRequest, navigationType _: UIWebViewNavigationType) -> Bool {
if let url = request.url?.absoluteString {
if url.hasPrefix(redirectURI) {
if let query = request.url?.query {
if query.hasPrefix("code=") {
let code = String(query["code=".endIndex...])
NetworkManager.shared.requestForAccessToken(code: code, networkCompletionHandler: { obj in
guard let dictionary = obj, let access_token = dictionary["access_token"], let uid = dictionary["uid"] else {
console.debug("没有获得正确的access_token信息")
self.cancel()
return
}
let parameters = ["access_token": access_token, "uid": uid]
NetworkManager.shared.requestForUserInfo(parameters: parameters, networkCompletionHandler: { obj in
guard var responseObject = obj else {
console.debug("没有获得正确的userAccount信息")
self.cancel()
return
}
for (key, value) in dictionary {
responseObject[key] = value
}
WBUserAccountModel.shared.saveAccount(dictionary: responseObject)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: loginSuccess), object: self)
self.cancel()
// TODO: 如果登陆失败的提示没做
})
})
} else {
cancel()
}
}
return false
}
}
return true
}
func webViewDidFinishLoad(_ webView: UIWebView) {
view.backgroundColor = UIColor.colorWithHex(hex: 0xEBEDEF)
webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '627515277@qq.com'")
}
}
| mit |
kishikawakatsumi/TextKitExamples | Math/Math/ViewController.swift | 1 | 7571 | //
// ViewController.swift
// Math
//
// Created by Kishikawa Katsumi on 9/1/16.
// Copyright © 2016 Kishikawa Katsumi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label = UILabel()
let font = UIFont(name: "LatinModernMath-Regular", size: 20)!
override func viewDidLoad() {
super.viewDidLoad()
label.frame = CGRectInset(view.bounds, 10, 10)
label.numberOfLines = 0
view.addSubview(label)
let attributedText = NSMutableAttributedString()
attributedText.appendAttributedString(NSAttributedString(string: "The Quadratic Formula\n\n", attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(20)]))
attributedText.appendAttributedString(formula1())
attributedText.appendAttributedString(NSAttributedString(string: "\n"))
attributedText.appendAttributedString(NSAttributedString(string: "Standard Deviation and Variance\n\n", attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(20)]))
attributedText.appendAttributedString(formula2())
label.attributedText = attributedText
label.sizeToFit()
}
func formula1() -> NSAttributedString {
let formula = expression("x = -b \\pm \\sqrtb2-4ac2a")
.stringByAppendingString("".stringByPaddingToLength(5, withString: Symbols.horizontalLine, startingAtIndex: 0)) // line of sqrt
.stringByAppendingString("".stringByPaddingToLength(10, withString: Symbols.horizontalLine, startingAtIndex: 0)) // line of fraction
let range = NSRange(location: 0, length: formula.utf16.count)
let attributedText = NSMutableAttributedString(string: formula)
attributedText.setAttributes([NSFontAttributeName: UIFont(name: "LatinModernMath-Regular", size: 20)!], range: range)
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -12, range: NSRange(location: 0, length: 5)) // x = -b
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: 1, range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 2, range: NSRange(location: 14, length: 1)) // superscript
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -26, range: NSRange(location: 21, length: 3)) // 2a
attributedText.addAttribute(NSKernAttributeName, value: -68, range: NSRange(location: 19, length: 2)) // 2a
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 18, range: NSRange(location: 11, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: -12, range: NSRange(location: 22, length: 2)) // line of sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 14, range: NSRange(location: 24, length: 5)) // line of sqrt
attributedText.addAttribute(NSKernAttributeName, value: -135, range: NSRange(location: 28, length: 1)) // line of fraction
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -12, range: NSRange(location: 29, length: 10)) // line of fraction
let paragraghStyle = NSMutableParagraphStyle()
paragraghStyle.alignment = .Center
paragraghStyle.paragraphSpacing = 40
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraghStyle, range: NSRange(location: 0, length: attributedText.string.utf16.count))
return attributedText
}
func formula2() -> NSAttributedString {
let formula = expression("\\sigma = \\sqrt1N\(Symbols.horizontalLine)\\sum_i=1N (xi - \\mu)2")
.stringByAppendingString("".stringByPaddingToLength(9, withString: Symbols.horizontalLine, startingAtIndex: 0))
let range = NSRange(location: 0, length: formula.utf16.count)
let attributedText = NSMutableAttributedString(string: formula)
attributedText.setAttributes([NSFontAttributeName: font], range: range)
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 0, length: 5)) // z =
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 1, y: 2.4), range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 20, range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: 2, range: NSRange(location: 5, length: 1)) // sqrt
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 6, length: 1)) // fraction of N
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -20, range: NSRange(location: 7, length: 2)) // fraction of N
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 7, length: 2)) // line of fraction
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 9, length: 1)) // line of fraction
attributedText.addAttribute(NSKernAttributeName, value: 4, range: NSRange(location: 9, length: 1)) // Sum
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 10, length: 1)) // Sum
attributedText.addAttribute(NSKernAttributeName, value: -20, range: NSRange(location: 10, length: 1)) // i=i
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 11, length: 4)) // i=i
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -24, range: NSRange(location: 11, length: 4)) // i=i
attributedText.addAttribute(NSKernAttributeName, value: -14, range: NSRange(location: 14, length: 1)) // N
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 15, length: 2)) // N
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 10, range: NSRange(location: 15, length: 2)) // N
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 21, length: 2)) // subscript i
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: -1, range: NSRange(location: 21, length: 2)) // subscript i
attributedText.addAttribute(NSFontAttributeName, value: font.scale(x: 0.6, y: 0.6), range: NSRange(location: 29, length: 1)) // superscript 2
attributedText.addAttribute(String(kCTSuperscriptAttributeName), value: 1, range: NSRange(location: 29, length: 1)) // superscript 2
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: -8, range: NSRange(location: 18, length: 12)) // (xi - u)2
attributedText.addAttribute(NSKernAttributeName, value: -118, range: NSRange(location: 29, length: 1)) // line of sqrt
attributedText.addAttribute(NSBaselineOffsetAttributeName, value: 16, range: NSRange(location: 30, length: 9)) // line of sqrt
let paragraghStyle = NSMutableParagraphStyle()
paragraghStyle.alignment = .Center
paragraghStyle.paragraphSpacing = 40
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraghStyle, range: NSRange(location: 0, length: attributedText.string.utf16.count))
return attributedText
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
hryk224/IPhotoBrowser | Sources/IPhotoWebImageCache.swift | 1 | 1235 | //
// IPhotoWebImageCache.swift
// IPhotoBrowser
//
// Created by yoshida hiroyuki on 2017/02/16.
// Copyright © 2017年 hryk224. All rights reserved.
//
import UIKit.UIImage
import Foundation.NSCache
open class IPhotoWebImageCache {
open static let `default` = IPhotoWebImageCache(name: "default")
init(name: String) {
let cacheName = "io.github.hryk224.IPhotoBrowserExample.ImageCache.\(name)"
memoryCache.name = cacheName
#if !os(macOS) && !os(watchOS)
NotificationCenter.default.addObserver(self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
let memoryCache = NSCache<NSString, UIImage>()
open func setImage(image: UIImage, for key: String) {
memoryCache.setObject(image, forKey: key as NSString)
}
open func removeImage(for key: String) {
memoryCache.removeObject(forKey: key as NSString)
}
open func image(for key: String) -> UIImage? {
return memoryCache.object(forKey: key as NSString)
}
@objc open func clearMemoryCache() {
memoryCache.removeAllObjects()
}
}
| mit |
lixiangzhou/ZZLib | Source/ZZExtension/ZZUIExtension/UIColor+ZZExtension.swift | 1 | 5956 | //
// UIColor+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 17/3/12.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public extension UIColor {
/// 快速创建颜色
///
/// - parameter red: 红
/// - parameter green: 绿
/// - parameter blue: 蓝
/// - parameter alpha: 透明度
convenience init(red: Int, green: Int, blue: Int, alphaValue: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alphaValue)
}
/// 16进制rgb颜色值生成对应UIColor
///
/// - parameter stringHexValue: 16进制颜色值, 可包含前缀0x,#,颜色值可以是 RGB RGBA RRGGBB RRGGBBAA
convenience init?(stringHexValue: String) {
var hexValue = stringHexValue.zz_trim.uppercased()
if hexValue.hasPrefix("#") {
hexValue = String(hexValue[hexValue.index(hexValue.startIndex, offsetBy: 1)...])
} else if hexValue.hasPrefix("0X") {
hexValue = String(hexValue[hexValue.index(hexValue.startIndex, offsetBy: 2)...])
}
let len = hexValue.count
// RGB RGBA RRGGBB RRGGBBAA
if len != 3 && len != 4 && len != 6 && len != 8 {
return nil
}
var resultHexValue: UInt32 = 0
guard Scanner(string: hexValue).scanHexInt32(&resultHexValue) else {
return nil
}
var divisor: CGFloat = 255
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if len == 3 {
divisor = 15
r = CGFloat((resultHexValue & 0xF00) >> 8) / divisor
g = CGFloat((resultHexValue & 0x0F0) >> 4) / divisor
b = CGFloat( resultHexValue & 0x00F) / divisor
a = 1
} else if len == 4 {
divisor = 15
r = CGFloat((resultHexValue & 0xF000) >> 12) / divisor
g = CGFloat((resultHexValue & 0x0F00) >> 8) / divisor
b = CGFloat((resultHexValue & 0x00F0) >> 4) / divisor
a = CGFloat(resultHexValue & 0x000F) / divisor
} else if len == 6 {
r = CGFloat((resultHexValue & 0xFF0000) >> 16) / divisor
g = CGFloat((resultHexValue & 0x00FF00) >> 8) / divisor
b = CGFloat(resultHexValue & 0x0000FF) / divisor
a = 1
} else if len == 8 {
r = CGFloat((resultHexValue & 0xFF000000) >> 24) / divisor
g = CGFloat((resultHexValue & 0x00FF0000) >> 16) / divisor
b = CGFloat((resultHexValue & 0x0000FF00) >> 8) / divisor
a = CGFloat(resultHexValue & 0x000000FF) / divisor
}
self.init(red: r, green: g, blue: b, alpha: a)
}
/// 16进制rgb颜色值生成对应UIColor
///
/// - parameter hexValue: 16进制颜色值, 前缀0x开头的颜色值
convenience init?(hexValue: Int) {
self.init(stringHexValue: String(hexValue, radix: 16))
}
/// 随机色
static var zz_random: UIColor {
let red = arc4random() % 256
let green = arc4random() % 256
let blue = arc4random() % 256
return UIColor(red: Int(red), green: Int(green), blue: Int(blue))
}
/// 返回颜色的rgba值
var rgbaValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 24) + (green << 16) + (blue << 8) + alpha
return String(value, radix: 16)
}
return nil
}
var rgbValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: nil) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 16) + (green << 8) + blue
return String(value, radix: 16)
}
return nil
}
/// 返回颜色的rgba值
var rgbaHexStringValue: (red: String, green: String, blue: String, alpha: String)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = String(Int(r * 255), radix: 16)
let green = String(Int(g * 255), radix: 16)
let blue = String(Int(b * 255), radix: 16)
let alpha = String(Int(a * 255), radix: 16)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
/// 返回颜色的rgba值,0-255
var rgbaIntValue: (red: Int, green: Int, blue: Int, alpha: Int)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
}
| mit |
ZackKingS/Tasks | task/Classes/Others/Lib/TakePhoto/PhotoAlbumsTableViewController.swift | 2 | 4968 | //
// PhotoAlbumsTableViewController.swift
// PhotoPicker
//
// Created by liangqi on 16/3/5.
// Copyright © 2016年 dailyios. All rights reserved.
//
import UIKit
import Photos
class PhotoAlbumsTableViewController: UITableViewController,PHPhotoLibraryChangeObserver{
// 自定义需要加载的相册
var customSmartCollections = [
PHAssetCollectionSubtype.smartAlbumUserLibrary, // All Photos
PHAssetCollectionSubtype.smartAlbumRecentlyAdded // Rencent Added
]
// tableCellIndetifier
let albumTableViewCellItentifier = "PhotoAlbumTableViewCell"
var albums = [ImageModel]()
let imageManager = PHImageManager.default()
override func viewDidLoad() {
super.viewDidLoad()
// 9.0以上添加截屏图片
if #available(iOS 9.0, *) {
customSmartCollections.append(.smartAlbumScreenshots)
}
PHPhotoLibrary.shared().register(self)
self.setupTableView()
self.configNavigationBar()
self.loadAlbums(replace: false)
}
deinit{
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
func photoLibraryDidChange(_ changeInstance: PHChange) {
self.loadAlbums(replace: true)
}
private func setupTableView(){
self.tableView.register(UINib.init(nibName: self.albumTableViewCellItentifier, bundle: nil), forCellReuseIdentifier: self.albumTableViewCellItentifier)
// 自定义 separatorLine样式
self.tableView.rowHeight = PhotoPickerConfig.AlbumTableViewCellHeight
self.tableView.separatorColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.15)
self.tableView.separatorInset = UIEdgeInsets.zero
// 去除tableView多余空格线
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
}
private func loadAlbums(replace: Bool){
if replace {
self.albums.removeAll()
}
// 加载Smart Albumns All Photos
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
for i in 0 ..< smartAlbums.count {
if customSmartCollections.contains(smartAlbums[i].assetCollectionSubtype){
self.filterFetchResult(collection: smartAlbums[i])
}
}
// 用户相册
let topUserLibarayList = PHCollectionList.fetchTopLevelUserCollections(with: nil)
for i in 0 ..< topUserLibarayList.count {
if let topUserAlbumItem = topUserLibarayList[i] as? PHAssetCollection {
self.filterFetchResult(collection: topUserAlbumItem)
}
}
self.tableView.reloadData()
}
private func filterFetchResult(collection: PHAssetCollection){
let fetchResult = PHAsset.fetchAssets(in: collection, options: PhotoFetchOptions.shareInstance)
if fetchResult.count > 0 {
let model = ImageModel(result: fetchResult as! PHFetchResult<AnyObject> as! PHFetchResult<PHObject>, label: collection.localizedTitle, assetType: collection.assetCollectionSubtype)
self.albums.append(model)
}
}
private func configNavigationBar(){
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(PhotoAlbumsTableViewController.eventViewControllerDismiss))
self.navigationItem.rightBarButtonItem = cancelButton
}
func eventViewControllerDismiss(){
PhotoImage.instance.selectedImage.removeAll()
self.navigationController?.dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albums.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.albumTableViewCellItentifier, for: indexPath) as! PhotoAlbumTableViewCell
let model = self.albums[indexPath.row]
cell.renderData(result: model.fetchResult as! PHFetchResult<AnyObject>, label: model.label)
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.showDetailPageModel(model: self.albums[indexPath.row])
}
private func showDetailPageModel(model: ImageModel){
let layout = PhotoCollectionViewController.configCustomCollectionLayout()
let controller = PhotoCollectionViewController(collectionViewLayout: layout)
controller.fetchResult = model.fetchResult
self.navigationController?.show(controller, sender: nil)
}
}
| apache-2.0 |
jgonfer/JGFLabRoom | JGFLabRoom/Controller/HomeViewController.swift | 1 | 5395 | //
// ViewController.swift
// JGFLabRoom
//
// Created by Josep Gonzalez Fernandez on 13/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController {
let kTagRemoveLabel = 101
let kHeightCell: CGFloat = 55.0
let headers = ["Information Access", "Performance", "Security", "Miscellaneous", ""]
let results = [["EventKit", "OAuth"], ["Grand Central Dispatch"], ["Common Crypto", "Keychain", "Touch ID"], ["My Apps"], ["Clear Cache"]]
var indexSelected: NSIndexPath?
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
setupController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupController() {
Utils.registerStandardXibForTableView(tableView, name: "cell")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let indexSelected = indexSelected else {
return
}
let title = results[indexSelected.section][indexSelected.row]
let vc = segue.destinationViewController
vc.title = title
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return results.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return kHeightCell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "cell"
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
let title = results[indexPath.section][indexPath.row]
if indexPath.section == 4 {
// First we search in the current cell for the label
if let view = cell!.viewWithTag(kTagRemoveLabel) {
// If the label exists, we remove it before add it again
view.removeFromSuperview()
}
// We customize our Delete Cache cell (It'll be different from the others
let removeLabel = UILabel(frame: cell!.frame)
removeLabel.frame.size = CGSizeMake(CGRectGetWidth(removeLabel.frame), kHeightCell)
removeLabel.text = title
removeLabel.textColor = UIColor.redColor()
removeLabel.textAlignment = .Center
removeLabel.tag = kTagRemoveLabel
// Finally we add it to the cell
cell!.addSubview(removeLabel)
cell!.accessoryType = .None
} else {
cell!.textLabel!.text = title
cell!.accessoryType = .DisclosureIndicator
}
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
indexSelected = indexPath
let row = indexPath.row
switch indexPath.section {
case 0:
sectionSelectedInformationAccess(row)
case 1:
sectionSelectedPerformance(row)
case 2:
sectionSelectedSecurity(row)
case 3:
sectionSelectedMiscellaneous(row)
case 4:
ImageHelper.sharedInstance.cleanCache()
default:
break
}
}
// MARK: Sections Selection
private func sectionSelectedInformationAccess(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdEventKit, sender: tableView)
case 1:
performSegueWithIdentifier(kSegueIdSocial, sender: tableView)
break
default:
break
}
}
private func sectionSelectedPerformance(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdGCD, sender: tableView)
default:
break
}
}
private func sectionSelectedSecurity(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdCommonCrypto, sender: tableView)
case 1:
performSegueWithIdentifier(kSegueIdKeychain, sender: tableView)
case 2:
performSegueWithIdentifier(kSegueIdTouchID, sender: tableView)
default:
break
}
}
private func sectionSelectedMiscellaneous(row: Int) {
switch row {
case 0:
performSegueWithIdentifier(kSegueIdListApps, sender: tableView)
default:
break
}
}
}
| mit |
johnlui/JSONNeverDie | Example/JSONNeverDieExample/ViewController.swift | 1 | 2675 | //
// ViewController.swift
// JSONNeverDieExample
//
// Created by 吕文翰 on 15/9/27.
// Copyright © 2015年 JohnLui. All rights reserved.
//
import UIKit
import JSONNeverDie
class People: JSONNDModel {
@objc var name = ""
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let json = JSONND(string: "{\"name\": \"JohnLui\"}")
let people = People(JSONNDObject: json)
print(people.name)
if let url = URL(string: "http://httpbin.org/get?hello=world"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let json1 = JSONND(string: string)
print(json1["args"]["hello"].stringValue)
print(json1.RAW)
}
if let url = URL(string: "http://httpbin.org/get?hello=world"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let json = JSONND(string: string)
print("json string: \(json.RAWValue)")
print("GOT string for key 'hello': ", json["args"]["hello"].stringValue)
}
// init from array
let array = ["hello", 123, false] as [Any]
let arrayJSON = JSONND(array: array as [AnyObject])
print(arrayJSON.array?.first?.string)
print(arrayJSON.array?[1].int)
print(arrayJSON.array?[2].bool)
print(arrayJSON.RAW)
// init from dictionary
let dic = ["hello": "NeverDie", "json": 200] as [String : Any]
let dicJSON = JSONND(dictionary: dic as [String : AnyObject])
print(dicJSON["hello"].string)
print(dicJSON["json"].int)
print(dicJSON.RAW)
if let url = Bundle.main.url(forResource: "Model", withExtension: "json"),
let string = try? String(contentsOf: url, encoding: String.Encoding.utf8) {
let jsonForModel = JSONND(string: string)
let model = Model(JSONNDObject: jsonForModel)
print(model.string)
print(model.double)
print(model.int)
print(model.array_values.first)
print(model.array.first?.key)
print(model.hey.man.hello)
}
self.testReflection()
}
func testReflection() {
let json = JSONND(dictionary: ["name": "JohnLui" as AnyObject])
let people = People(JSONNDObject: json)
print(people.name) // get "JohnLui"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
crescentflare/ViewletCreator | ViewletCreatorIOS/Example/ViewletCreator/Settings.swift | 1 | 1000 | //
// Settings.swift
// Viewlet creator example
//
// An easy way to handle settings for the viewlet example
//
import UIKit
class Settings {
// --
// MARK: Singleton instance
// --
static var shared: Settings = Settings()
private init() {
}
// --
// MARK: Settings access
// --
var serverEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: "serverEnabled") }
set {
UserDefaults.standard.set(newValue, forKey: "serverEnabled")
}
}
var autoRefresh: Bool {
get { return UserDefaults.standard.bool(forKey: "autoRefresh") }
set {
UserDefaults.standard.set(newValue, forKey: "autoRefresh")
}
}
var serverAddress: String {
get { return UserDefaults.standard.string(forKey: "serverAddress") ?? "http://127.0.0.1:2233" }
set {
UserDefaults.standard.set(newValue, forKey: "serverAddress")
}
}
}
| mit |
therealglazou/quaxe-for-swift | quaxe/protocols/css/pElementCSSInlineStyle.swift | 1 | 275 | /**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <daniel.glazman@disruptive-innovations.com>
*
* Contributors:
*
*/
public protocol pElementCSSInlineStyle {
var style: pCSSStyleDeclaration { get }
}
| mpl-2.0 |
ifobos/JTActivityIndicator | JTActivityIndicator/JTActivityIndicator/ViewController.swift | 1 | 2172 | //
// ViewController.swift
// JTActivityIndicator
//
// Created by Juan Garcia on 1/21/16.
// Copyright © 2016 jerti. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var exampleView: UIView!
@IBAction func show(sender: AnyObject)
{
let activityIndicator = JTActivityIndicator()
activityIndicator.show()
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()){ () -> Void in
activityIndicator.hide()
}
}
@IBAction func showNoAnimated(sender: AnyObject)
{
let activityIndicator = JTActivityIndicator()
activityIndicator.show(animated: false)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()){ () -> Void in
activityIndicator.hide()
}
}
@IBAction func showWithMessage(sender: AnyObject)
{
let activityIndicator = JTActivityIndicator()
activityIndicator.show(
animated : true,
message : "Custom"
)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()){ () -> Void in
activityIndicator.hide()
}
}
@IBAction func showInView(sender: AnyObject)
{
let activityIndicator = JTActivityIndicator()
activityIndicator.show(
animated : true,
message : "Custom",
network : false,
viewContainer : self.exampleView
)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(5 * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()){ () -> Void in
activityIndicator.hide()
}
}
}
| mit |
attheodo/ATHExtensions | ATHExtensions/ATHExtensions.swift | 1 | 4232 | //
// ATHExtensions.swift
// ATHExtensions
//
// Created by Athanasios Theodoridis on 25/05/16.
//
//
import Foundation
public struct App {
// MARK: - Private Properties
/// NSUserDefaults key for storing whether app has run before
private static let kATHExtensionsHasAppRunBeforeKey = "kATHExtensionsHasAppRunBefore"
// MARK: - Public Properties
/// Returns an optional string containing `CFBundleDisplayName`
public static var bundleDisplayName: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") as? String
}
/// Returns an optional string containing `CFBundleName`
public static var bundleName: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String
}
/// Returns the app's version number (`CFBundleShortVersionString`)
public static var version: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
}
/// Returns the app's build number (`kCFBundleVersionKey`)
public static var buildNumber: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as? String
}
/// Returns the app's version and build number
public static var versionWithBuildNumber: String? {
guard let version = self.version, buildNumber = self.buildNumber else {
return nil
}
if version == buildNumber {
return "v\(version)"
} else {
return "v\(version) (b\(buildNumber))"
}
}
/// Returns a boolean indicating whether "Debug" configuration is active
public static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
/// Returns a boolean indicating whether a production configuration is active
public static var isRelease: Bool {
return !isDebug
}
/// Returns a boolean indicating whether the app is currently being run in unit-testing mode
public static var isBeingTested: Bool {
return NSProcessInfo.processInfo().environment["XCInjectBundle"] != nil
}
/// returns a boolean indicating whether the apps is currently being run in UI testing mode
public static var isBeingUITested: Bool {
return NSProcessInfo.processInfo().arguments.contains("-ui_testing")
}
/// Returns a boolean indicating whether the app is running on the simulator
public static var isRunningOnSimulator: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return false
#endif
}
/// Returns a boolean indicating whether the app is running on a device
public static var isRunningOnDevice: Bool {
return !isRunningOnSimulator
}
/// A reference to the application delegate
public static var delegate: UIApplicationDelegate? {
return UIApplication.sharedApplication().delegate
}
/// Returns a boolean indicating whether this is the first time ever
/// the app is running
public static var isFirstLaunch: Bool {
let d = NSUserDefaults.standardUserDefaults()
if d.boolForKey(kATHExtensionsHasAppRunBeforeKey) {
return false
} else {
d.setBool(true, forKey: kATHExtensionsHasAppRunBeforeKey)
d.synchronize()
return true
}
}
/// Returns a boolean indicating whether this is the first time ever
/// the current version of the app is running
public static var isFirstLaunchForCurrentVersion: Bool {
guard let version = self.version else {
return true
}
let d = NSUserDefaults.standardUserDefaults()
let key = "\(kATHExtensionsHasAppRunBeforeKey)\(version)"
if d.boolForKey(key) {
return false
} else {
d.setBool(true, forKey: key)
d.synchronize()
return true
}
}
}
| mit |
devedbox/AXBadgeView-Swift | Sources/BadgeView.swift | 1 | 19194 | //
// BadgeView.swift
// Badge
//
// The MIT License (MIT)
//
// Copyright (c) 2016 devedbox.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
// MARK: - Types.
extension BadgeView {
// MARK: Style.
/// The style of the badge view.
public enum Style {
case normal // Shows a red dot only.
case number(value: Int) // Shows a number text.
case text(value: String) // Shows a custom text.
case new // Shows a 'new' text.
}
// MARK: Animator.
/// The animation type of the badge view.
public enum Animator: String {
case none // None animator, badge view stay still.
case scale // Sacle animator
case shaking // Shake animator.
case bounce // Bounce animator.
case breathing // Breathing animator.
}
// MARK: Offset.
/// The offset of a rectangle at any size.
public enum Offset {
case least
case exact(CGFloat)
case percent(CGFloat)
case greatest
}
/// The offsets of the badge view.
public struct Offsets {
public var x: Offset
public var y: Offset
public static func offsets(
x: Offset,
y: Offset) -> Offsets
{
return Offsets(x: x, y: y)
}
}
}
// MARK: - BadgeViewDelegate.
public protocol BadgeViewDelegate {
/// Badge view property.
var badge: BadgeView { get set }
/// Animated to show the badge view.
func showBadge(animated: Bool)
/// Animated to hide the badge view.
func clearBadge(animated: Bool)
}
extension BadgeViewDelegate {
public func showBadge(
animated: Bool,
configuration: (BadgeView) -> Void = { _ in })
{
configuration(badge)
showBadge(animated: animated)
}
}
// MARK: - UIView.
extension UIView: BadgeViewDelegate {
/// The associated keys.
private struct _AssociatedKeys {
/// Key for `badgeView`.
static var badge = "badgeKey"
}
/// Returns the badge view of the receiver.
public var badge: BadgeView {
get {
if self is BadgeView {
fatalError("The badge view of 'BadgeView' itself is not accessible.")
}
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
if self is BadgeView {
fatalError("The badge view of 'BadgeView' itself is not accessible.")
}
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
badge.show(
animated: animated,
inView: self
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - UIBarButtonItem.
extension UIBarButtonItem: BadgeViewDelegate {
private struct _AssociatedKeys {
static var badge = "badgeKey"
}
public var badge: BadgeView {
get {
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self, &_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
guard let view = value(forKey: "view") as? UIView else {
return
}
badge.show(
animated: animated,
inView: try! view.viewInEndpointsOfMinY()
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - UITabBarItem.
extension UITabBarItem: BadgeViewDelegate {
private struct _AssociatedKeys {
static var badge = "badgeKey"
}
public var badge: BadgeView {
get {
if let badge = objc_getAssociatedObject(self, &_AssociatedKeys.badge) as? BadgeView {
return badge
}
let badge = BadgeView()
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
badge,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return badge
}
set {
objc_setAssociatedObject(
self,
&_AssociatedKeys.badge,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func showBadge(
animated: Bool) -> Void
{
guard let view = value(forKey: "view") as? UIView else {
return
}
badge.show(
animated: animated,
inView: try! view.viewInEndpointsOfMinY()
)
}
public func clearBadge(
animated: Bool) -> Void
{
badge.hide(
animated: animated
)
}
}
// MARK: - AXBadgeView.
public class BadgeView: UILabel {
/// The mask of the badge view using shape layer.
public struct Mask {
/// The path content of the badge view's layer.
public private(set) var path: (CGRect) -> CGPath
public init(
path: @escaping (CGRect) -> CGPath)
{
self.path = path
}
fileprivate func _layer(
for frame: CGRect) -> CAShapeLayer
{
let layer = CAShapeLayer()
layer.fillColor = UIColor.black.cgColor
layer.path = path(frame)
return layer
}
// MARK: Presets.
public static let cornerRadius: Mask = Mask {
return UIBezierPath(
roundedRect: $0,
cornerRadius: $0.height * 0.5
).cgPath
}
public static func roundingCorner(
_ corner: UIRectCorner) -> Mask
{
return Mask {
return UIBezierPath(
roundedRect: $0,
byRoundingCorners: corner,
cornerRadii: CGSize(
width: $0.height * 0.5,
height: $0.height * 0.5
)
).cgPath
}
}
}
/// The attaching view of badge view.
public final weak var attachingView: UIView!
/// The alignment view of badge view.
public final weak var alignmentView: UIView!
/// Limited number to show text on .number style. Default is 99.
open var limitedNumber: Int = 99
/// Override text as unavailable, using style instead.
@available(*, unavailable)
public final override var text: String? {
get {
return super.text
}
set { }
}
/// The mask of the badge view.
public final var masking: Mask = .cornerRadius {
didSet {
setNeedsLayout()
}
}
/// The stroke color of the badge view.
open var strokeColor: UIColor? {
didSet {
setNeedsLayout()
}
}
/// The stroke appearance layer.
private lazy var _strokeLayer = CAShapeLayer()
/// Style of badge view. Defaults to AXBadgeViewNormal.
open var style = Style.normal {
didSet {
switch style {
case .normal:
super.text = ""
case .new:
super.text = "new"
case .number(value: let val):
if val > limitedNumber {
super.text = "\(limitedNumber)"+"+"
} else {
super.text = "\(val)"
}
case .text(value: let val):
super.text = val
}
sizeToFit()
if !constraints.contains(_widthLayout) {
addConstraint(_widthLayout)
}
if !constraints.contains(_heightLayout) {
addConstraint(_heightLayout)
}
_widthLayout.constant = bounds.width
_heightLayout.constant = bounds.height
setNeedsLayout()
if
visible,
scaleContent
{
show(animated: true)
}
if hideOnZero {
switch style {
case .number(value: let val) where val == 0:
isHidden = true
case .text(value: let val) where val.isEmpty:
isHidden = true
case .new: fallthrough
default: break
}
} else {
isHidden = false
}
}
}
/// Animation type of badge view. Defaults to None.
open var animator = Animator.none {
didSet {
layer.removeAllAnimations()
switch animator {
case .breathing:
layer.add(
createBreathingAnimation(duration: 1.2),
forKey: animator.rawValue
)
case .bounce:
layer.add(
createBounceAnimation(
repeatCount: .greatestFiniteMagnitude,
duration: 0.8,
fromLayer: layer
),
forKey: animator.rawValue
)
case .scale:
layer.add(
createScaleAnimation(
fromScale: 1.2,
toScale: 0.8,
duration: 0.8,
repeatCount: .greatestFiniteMagnitude
),
forKey: animator.rawValue
)
case .shaking:
layer.add(
createShakeAnimation(
repeatCount: .greatestFiniteMagnitude,
duration: 0.8,
fromLayer: layer
),
forKey: animator.rawValue
)
default: break
}
}
}
/// The offsets of the badge view laying on the attaching view.
/// Defaults to (x: .greatest, y: .least).
open var offsets = Offsets(x: .greatest, y: .least) {
didSet {
if
let suview = superview,
let align = alignmentView ?? superview
{
if
let _ = _horizontalLayout,
suview.constraints.contains(_horizontalLayout)
{
suview.removeConstraint(_horizontalLayout)
}
if
let _ = _verticalLayout,
suview.constraints.contains(_verticalLayout)
{
suview.removeConstraint(_verticalLayout)
}
switch offsets.x {
case .least, .exact(0.0), .percent(0.0):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .left,
multiplier: 1.0,
constant: 0.0
)
case .greatest, .exact(suview.bounds.width), .percent(1.0):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: 1.0,
constant: 0.0
)
case .exact(let val):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: val / suview.bounds.width,
constant: 0.0
)
case .percent(let val):
_horizontalLayout = NSLayoutConstraint(
item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: align,
attribute: .right,
multiplier: max(0.0, min(1.0, val)),
constant: 0.0
)
}
switch offsets.y {
case .least, .exact(0.0), .percent(0.0):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .top,
multiplier: 1.0,
constant: 0.0
)
case .greatest, .exact(suview.bounds.height), .percent(1.0):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0
)
case .exact(let val):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: val / suview.bounds.height,
constant: 0.0
)
case .percent(let val):
_verticalLayout = NSLayoutConstraint(
item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: align,
attribute: .bottom,
multiplier: max(0.0, min(1.0, val)),
constant: 0.0
)
}
suview.addConstraint(_horizontalLayout)
suview.addConstraint(_verticalLayout)
suview.setNeedsDisplay()
}
}
}
/// Hide on zero content. Defaults to YES.
open var hideOnZero = true
/// Min size. Defaults to {12.0, 12.0}.
open var minSize = CGSize(width: 12.0, height: 12.0) {
didSet {
sizeToFit()
style = {
style
}()
}
}
/// Scale content when set new content to badge label. Defaults to false.
open var scaleContent = false
/// Is badge visible.
open var visible: Bool {
return (superview != nil && !isHidden && alpha > 0) ? true : false
}
private var _horizontalLayout: NSLayoutConstraint!
private var _verticalLayout : NSLayoutConstraint!
private lazy var _widthLayout = NSLayoutConstraint(
item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0
)
private lazy var _heightLayout = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0
)
convenience init()
{
self.init(frame:CGRect.zero)
}
override init(
frame: CGRect)
{
super.init(frame: frame)
initializer()
}
required public init?(
coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initializer()
}
deinit {
// Do something to dealloc.
}
/// Initializer.
fileprivate func initializer() -> Void {
translatesAutoresizingMaskIntoConstraints = false
font = UIFont.systemFont(ofSize: 12)
backgroundColor = UIColor.red
textColor = UIColor.white
textAlignment = NSTextAlignment.center
style = .normal
}
/// - override: sizeThatFits
override open func sizeThatFits(
_ size: CGSize) -> CGSize
{
var susize = super.sizeThatFits(size)
susize.width = max(susize.width + susize.height / 2, minSize.width)
susize.height = max(susize.height, minSize.height)
return susize
}
/// - override: layoutSubviews
public override func layoutSubviews() {
super.layoutSubviews()
_maskBadgeViewIfNeeded(with: masking)
_strokeEdgesOfBadgeViewIfNeeded(with: strokeColor?.cgColor)
}
/// - override: willMoveToSuperview
override open func willMove(
toSuperview newSuperview: UIView?)
{
super.willMove(toSuperview: newSuperview)
newSuperview.map { _ in
offsets = {
offsets
}()
}
alpha = 1.0
}
/// - override: didMoveToSuperview
override open func didMoveToSuperview() {
super.didMoveToSuperview()
if let suview = superview {
self.offsets = { offsets }()
if !suview.constraints.contains(_verticalLayout) {
suview.addConstraint(_verticalLayout)
}
if !suview.constraints.contains(_horizontalLayout) {
suview.addConstraint(_horizontalLayout)
}
suview.bringSubviewToFront(self)
}
}
/// Show badge view in a target view with animation.
///
/// - parameter animated: animated to show badge view or not.
/// - parameter inView: the target view to add badge view.
///
/// - returns: Void.
open func show(
animated:Bool,
inView attachingView: UIView? = nil,
alignTo alignmentView: UIView? = nil) -> Void
{
self.attachingView = attachingView
self.alignmentView = alignmentView ?? attachingView
self.attachingView?.addSubview(self)
self.attachingView?.clipsToBounds = false
isHidden ? isHidden = false : ()
alpha < 1.0 ? alpha = 1.0 : ()
transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.6,
options: AnimationOptions(rawValue: 7),
animations: {
self.transform = CGAffineTransform.identity
},
completion: nil
)
} else {
transform = CGAffineTransform.identity
}
}
/// Hide the badge view with animation.
///
/// - parameter animated: animated to hide or not.
/// - parameter completion: completion block call back when the badge view finished hiding.
///
/// - returns: Void.
open func hide(
animated: Bool,
completion: @escaping (() -> Void) = { }) -> Void
{
if animated {
UIView.animate(
withDuration: 0.35,
animations: {
self.alpha = 0.0
},
completion: { [unowned self] finished -> Void in
if finished {
self.removeFromSuperview()
self.alpha = 1.0
completion()
}
}
)
} else {
self.removeFromSuperview()
completion()
}
}
/// Mask the bdage view if needed.
private func _maskBadgeViewIfNeeded(
with masking: Mask)
{
layer.mask = masking._layer(for: bounds)
}
/// Stroke the badge view's edges if needed.
///
/// - Parameter strokeColor: The color of the strokes. Nil to ignore stroke.
private func _strokeEdgesOfBadgeViewIfNeeded(
with strokeColor: CGColor?)
{
if
let strokeColor = strokeColor
{
_strokeLayer.frame = bounds
_strokeLayer.path = masking.path(bounds.insetBy(dx: 0.5, dy: 0.5))
_strokeLayer.strokeColor = strokeColor
_strokeLayer.fillColor = nil
_strokeLayer.strokeStart = 0.0
_strokeLayer.strokeEnd = 1.0
_strokeLayer.lineWidth = 1.0
layer.addSublayer(_strokeLayer)
} else {
_strokeLayer.removeFromSuperlayer()
}
}
}
| mit |
nguyenantinhbk77/practice-swift | Multitasking/Download an Image on a concurrent queue/Download an Image on a concurrent queue/AppDelegate.swift | 3 | 256 | //
// AppDelegate.swift
// Download an Image on a concurrent queue
//
// Created by Domenico Solazzo on 12/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
ryuichis/swift-ast | Sources/AST/Expression/PostfixOperatorExpression.swift | 2 | 1143 | /*
Copyright 2016-2017 Ryuichi Intellectual Property and the Yanagiba project contributors
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.
*/
public class PostfixOperatorExpression : ASTNode, PostfixExpression {
public let postfixOperator: Operator
public let postfixExpression: PostfixExpression
public init(postfixOperator: Operator, postfixExpression: PostfixExpression) {
self.postfixOperator = postfixOperator
self.postfixExpression = postfixExpression
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
return "\(postfixExpression.textDescription)\(postfixOperator)"
}
}
| apache-2.0 |
natecook1000/swift-compiler-crashes | crashes-duplicates/17664-no-stacktrace.swift | 11 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
{
extension NSData {
let a {
end = [ {
protocol c {
class
case ,
| mit |
rambler-ios/RamblerConferences | Carthage/Checkouts/rides-ios-sdk/source/UberRides/Request.swift | 1 | 7148 | //
// Request.swift
// UberRides
//
// Copyright © 2016 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/**
* Struct that packages the response from an executed NSURLRequest.
*/
@objc(UBSDKResponse) public class Response: NSObject {
/// String representing JSON response data.
public var data: NSData?
/// HTTP status code of response.
public var statusCode: Int
/// Response metadata.
public var response: NSHTTPURLResponse?
/// NSError representing an optional error.
public var error: RidesError?
/**
Initialize a Response object.
- parameter data: Data returned from server.
- parameter response: Provides response metadata, such as HTTP headers and status code.
- parameter error: Indicates why the request failed, or nil if the request was successful.
*/
init(data: NSData?, statusCode: Int, response: NSHTTPURLResponse?, error: RidesError?) {
self.data = data
self.response = response
self.statusCode = statusCode
self.error = error
}
/**
- returns: string representation of JSON data.
*/
func toJSONString() -> NSString {
guard let data = data else {
return ""
}
return NSString(data: data, encoding: NSUTF8StringEncoding)!
}
}
/// Class to create and execute NSURLRequests.
class Request: NSObject {
let session: NSURLSession?
let endpoint: UberAPI
let urlRequest: NSMutableURLRequest
let serverToken: NSString?
let bearerToken: NSString?
/**
Initialize a request object.
- parameter hostURL: Host URL string for API.
- parameter session: NSURLSession to execute request with.
- parameter endpoint: UberAPI conforming endpoint.
- parameter serverToken: Developer's server token.
*/
init(session: NSURLSession?, endpoint: UberAPI, serverToken: NSString? = nil, bearerToken: NSString? = nil) {
self.session = session
self.endpoint = endpoint
self.urlRequest = NSMutableURLRequest()
self.serverToken = serverToken
self.bearerToken = bearerToken
}
/**
Creates a URL based off the endpoint requested. Function asserts for valid URL.
- returns: constructed NSURL or nil if construction failed.
*/
func requestURL() -> NSURL? {
let components = NSURLComponents(string: endpoint.host)!
components.path = endpoint.path
components.queryItems = endpoint.query
return components.URL
}
/**
Adds HTTP Headers to the request.
*/
private func addHeaders() {
urlRequest.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
if let token = bearerToken {
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: Header.Authorization.rawValue)
} else if let token = serverToken {
urlRequest.setValue("Token \(token)", forHTTPHeaderField: Header.Authorization.rawValue)
}
if let headers = endpoint.headers {
for (header,value) in headers {
urlRequest.setValue(value, forHTTPHeaderField: header)
}
}
}
/**
Prepares the NSURLRequest by adding necessary fields.
*/
func prepare() {
urlRequest.URL = requestURL()
urlRequest.HTTPMethod = endpoint.method.rawValue
urlRequest.HTTPBody = endpoint.body
addHeaders()
}
/**
Performs all steps to execute request (construct URL, add headers, etc).
- parameter completion: completion handler for returned Response.
*/
func execute(completion: (response: Response) -> Void) {
guard let session = session else {
return
}
prepare()
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
let httpResponse: NSHTTPURLResponse? = response as? NSHTTPURLResponse
var statusCode: Int = 0
var ridesError: RidesError?
// Handle HTTP errors.
errorCheck: if httpResponse != nil {
statusCode = httpResponse!.statusCode
if statusCode <= 299 {
break errorCheck
}
let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
if statusCode >= 400 && statusCode <= 499 {
ridesError = ModelMapper<RidesClientError>().mapFromJSON(jsonString)
} else if (statusCode >= 500 && statusCode <= 599) {
ridesError = ModelMapper<RidesServerError>().mapFromJSON(jsonString)
} else {
ridesError = ModelMapper<RidesUnknownError>().mapFromJSON(jsonString)
}
ridesError?.status = statusCode
}
// Any other errors.
if response == nil || error != nil {
ridesError = RidesUnknownError()
if let error = error {
ridesError!.title = error.domain
ridesError!.status = error.code
} else {
ridesError!.title = "Request could not complete"
ridesError!.code = "request_error"
}
}
let ridesResponse = Response(data: data, statusCode: statusCode, response: httpResponse, error: ridesError)
completion(response: ridesResponse)
})
task.resume()
}
/**
* Cancel data tasks if needed.
*/
func cancelTasks() {
guard let session = session else {
return
}
session.getTasksWithCompletionHandler({ data, upload, download in
for task in data {
task.cancel()
}
})
}
}
| mit |
buyiyang/iosstar | iOSStar/Scenes/Deal/CustomView/DealTitleMenuCell.swift | 4 | 621 | //
// DealTitleMenuCell.swift
// iOSStar
//
// Created by J-bb on 17/5/23.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class DealTitleMenuCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setTitles(titles:[String]) {
for (index, title) in titles.enumerated() {
let label = viewWithTag(3000 + index) as? UILabel
label?.text = title
}
}
}
| gpl-3.0 |
acchou/RxGmail | Example/RxGmail/LabelViewController.swift | 1 | 1127 | import UIKit
import RxSwift
import RxCocoa
import RxGmail
class LabelViewController: UITableViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let inputs = LabelViewModelInputs ()
let outputs = global.labelViewModel(inputs)
tableView.dataSource = nil
outputs.labels.bindTo(tableView.rx.items(cellIdentifier: "Label")) { row, label, cell in
cell.textLabel?.text = label.name
}
.disposed(by: disposeBag)
tableView.rx
.modelSelected(Label.self)
.subscribe(onNext: {
self.performSegue(withIdentifier: "ShowLabelDetail", sender: $0)
})
.disposed(by: disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let labelDetailVC = segue.destination as! LabelDetailViewController
labelDetailVC.selectedLabel = sender as! Label
}
}
| mit |
Soryu/DummyCalendarEvents | DummyCalendarEvents/ViewController.swift | 1 | 10221 | //
// ViewController.swift
// DummyCalendarEvents
//
// Created by Stanley Rost on 14.08.15.
// Copyright © 2015 soryu2. All rights reserved.
//
import UIKit
import EventKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var calendarPickerView: UIPickerView!
@IBOutlet weak var startDatePickerView: UIDatePicker!
@IBOutlet weak var intervalSlider: UISlider!
@IBOutlet weak var intervalValueLabel: UILabel!
@IBOutlet weak var minStartTimeSlider: UISlider!
@IBOutlet weak var minStartTimeValueLabel: UILabel!
@IBOutlet weak var maxStartTimeSlider: UISlider!
@IBOutlet weak var maxStartTimeValueLabel: UILabel!
@IBOutlet weak var durationSlider: UISlider!
@IBOutlet weak var durationValueLabel: UILabel!
@IBOutlet weak var allDayProbabilitySlider: UISlider!
@IBOutlet weak var allDayProbabilityValueLabel: UILabel!
let eventStore = EKEventStore()
var calendars:Array<EKCalendar> = []
var isWorking = false {
didSet {
navigationItem.rightBarButtonItem?.enabled = !isWorking
}
}
// TODO: Other calendar types besides Gregorian
let timeCalendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian)!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem?.enabled = false
switch EKEventStore.authorizationStatusForEntityType(.Event) {
case .NotDetermined:
eventStore .requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.setupView()
})
})
case .Authorized:
setupView()
default:
break
}
intervalSlider.value = 60
minStartTimeSlider.value = 8 * 4
maxStartTimeSlider.value = 17 * 4
durationSlider.value = 3 * 4
allDayProbabilitySlider.value = 0.1
updateIntervalLabel()
updateMinStartTimeLabel()
updateMaxStartTimeLabel()
updateDurationLabel()
updateAllDayProbabilityLabel()
}
func setupView() {
calendars = eventStore.calendarsForEntityType(.Event)
.filter({ !$0.immutable })
.sort({ $0.title < $1.title })
navigationItem.rightBarButtonItem?.enabled = calendars.count > 0
calendarPickerView.reloadAllComponents()
}
// MARK: Work
func createDummyEventsInCalendar(eventCalendar:EKCalendar, fromDate:NSDate, interval:Int, minStartQuarterHour:Int, maxStartQuarterHour:Int, maxDuration:Int, allDayProbability:Float) throws -> Int {
var numberOfEventsCreated = 0
let titles = ["Meeting", "Party", "BBQ", "Pick up kids", "Cleaning", "Dinner", "Lunch", "Buy presents", "Dance", "Reminder", "Call X"]
// sanity, cannot have finish before start
let sanitizedMaxStartQuarterHour = max(maxStartQuarterHour, minStartQuarterHour)
var numberOfLoops = Int(Double(interval) * 1.5)
while numberOfLoops-- > 0 {
// TODO: clean up casting when using arc4random_uniform? how?
let title = titles[Int(arc4random_uniform(UInt32(titles.count)))]
let day = Int(arc4random_uniform(UInt32(interval)))
let startQuarterHour = minStartQuarterHour + Int(arc4random_uniform(UInt32(sanitizedMaxStartQuarterHour - minStartQuarterHour)))
let durationInQuarterHours = 1 + Int(arc4random_uniform(UInt32(maxDuration)))
let allDay = Float(arc4random_uniform(1000)) / 1000 < allDayProbability
var startDate = timeCalendar.dateBySettingHour(0, minute:0, second:0, ofDate:fromDate, options:[])!
startDate = timeCalendar.dateByAddingUnit(.Day, value:day, toDate:startDate, options:[])!
if !allDay {
startDate = timeCalendar.dateBySettingHour(startQuarterHour / 4, minute:(startQuarterHour % 4) * 15, second:0, ofDate:startDate, options:[])!
}
let components = NSDateComponents() // confusing to use let, I change it
components.hour = durationInQuarterHours / 4;
components.minute = (durationInQuarterHours % 4) * 15;
let endDate = timeCalendar.dateByAddingComponents(components, toDate:startDate, options:[])!
let event = EKEvent.init(eventStore: eventStore) // confusing to use let, I change it
event.calendar = eventCalendar;
event.title = title;
event.startDate = startDate;
event.endDate = endDate;
event.allDay = allDay;
do {
try eventStore.saveEvent(event, span: .ThisEvent)
numberOfEventsCreated++
}
catch let error as NSError {
NSLog("%@", error)
}
}
try eventStore.commit()
return numberOfEventsCreated;
}
// MARK: Actions
@IBAction func goButtonPressed(sender: AnyObject) {
isWorking = true
let calendarRow = calendarPickerView.selectedRowInComponent(0)
let calendar = calendars[calendarRow]
let startDate = startDatePickerView.date;
let interval = Int(floor(intervalSlider.value))
let minStartQuarterHour = Int(floor(minStartTimeSlider.value))
let maxStartQuarterHour = Int(floor(maxStartTimeSlider.value))
let duration = Int(floor(durationSlider.value))
let allDayProbability = floor(allDayProbabilitySlider.value * 1000) / 1000
// TODO: work on bg thread and show progress
let benchmarkStartDate = NSDate()
let message:String
do {
let numberOfEventsCreated:Int
try numberOfEventsCreated = createDummyEventsInCalendar(calendar, fromDate: startDate, interval:interval,
minStartQuarterHour: minStartQuarterHour, maxStartQuarterHour:maxStartQuarterHour, maxDuration:duration,
allDayProbability:allDayProbability)
message = NSString(format: "%zd events created in %.1f seconds", numberOfEventsCreated, NSDate().timeIntervalSinceDate(benchmarkStartDate)) as String
} catch let error as NSError {
message = error.localizedDescription
}
let alert = UIAlertController(title: "Done", message: message, preferredStyle: .Alert) // confusing to use let, I change it
alert.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
isWorking = false
}
@IBAction func intervalSliderChanged(sender: AnyObject) {
updateIntervalLabel()
}
@IBAction func minStartTimeSliderChanged(sender: AnyObject) {
updateMinStartTimeLabel()
}
@IBAction func maxStartTimeSliderChanged(sender: AnyObject) {
updateMaxStartTimeLabel()
}
@IBAction func durationSliderChanged(sender: AnyObject) {
updateDurationLabel()
}
@IBAction func allDayProbabilitySliderChanged(sender: AnyObject) {
updateAllDayProbabilityLabel()
}
// MARK: UIPickerViewDataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return max(calendars.count, 1)
}
// MARK: UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if calendars.count == 0 {
return "<No calendars>"
}
return calendars[row].title
}
// MARK: Helpers
func dateFromQuarterHours(numberOfQuarterHours:NSInteger) -> NSDate {
let date = NSDate.init(timeIntervalSinceReferenceDate: 0)
return timeCalendar.dateBySettingHour(numberOfQuarterHours / 4, minute: (numberOfQuarterHours % 4) * 15, second: 0, ofDate: date, options: [])!
}
// TODO: dateFormatter should be a property
func dateFormatter() -> NSDateFormatter {
let formatter = NSDateFormatter() // confusing to use let, I change it
formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("jjmm", options: 0, locale: timeCalendar.locale)
return formatter
}
// MARK: UI/ViewModel
func updateIntervalLabel() {
let interval = floor(intervalSlider.value)
intervalValueLabel.text = "\(interval)"
}
func updateMinStartTimeLabel() {
let numberOfQuarterHours = Int(floor(minStartTimeSlider.value))
let date = dateFromQuarterHours(numberOfQuarterHours)
minStartTimeValueLabel.text = dateFormatter().stringFromDate(date)
}
func updateMaxStartTimeLabel() {
let numberOfQuarterHours = Int(floor(maxStartTimeSlider.value))
let date = dateFromQuarterHours(numberOfQuarterHours)
maxStartTimeValueLabel.text = dateFormatter().stringFromDate(date)
}
func updateDurationLabel() {
let numberOfQuarterHours = Int(floor(durationSlider.value))
let components = NSDateComponents()
components.hour = numberOfQuarterHours / 4
components.minute = (numberOfQuarterHours % 4) * 15
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute]
formatter.unitsStyle = .Full
durationValueLabel.text = formatter.stringFromDateComponents(components)
}
func updateAllDayProbabilityLabel() {
let value = floor(self.allDayProbabilitySlider.value * 1000) / 1000
allDayProbabilityValueLabel.text = NSString(format:"%.1lf %%", value * 100) as String
}
}
| mit |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 22 - Intermediate Live Rendering/WatchControl-Starter/WatchControlSwift/TimezoneTableViewCell.swift | 1 | 1608 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class TimezoneTableViewCell: UITableViewCell {
@IBOutlet var timeZoneLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit |
lllyyy/LY | U17-master/U17/U17/Procedure/Book/ViewController/UDownloadListViewController.swift | 1 | 288 | //
// UDownloadListViewController.swift
// U17
//
// Created by charles on 2017/10/24.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
class UDownloadListViewController: UBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit |
PlutoMa/SwiftProjects | 024.Vertical Menu Transition/VerticalMenuTransition/VerticalMenuTransition/AppDelegate.swift | 1 | 2404 | //
// AppDelegate.swift
// VerticalMenuTransition
//
// Created by Dareway on 2017/11/6.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
let navigationC = UINavigationController(rootViewController: ViewController())
window?.rootViewController = navigationC
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
katalisha/ga-mobile | Resources/Lesson 10 - Function Review Challenge.playground/Contents.swift | 2 | 1182 | /////////////////////////////////////////////////
/// Lesson 10 - Function Review Challenge ///
/////////////////////////////////////////////////
import Foundation
// Complete these, in order, writing code under each TODO statement.
// Each statement calls for a function to be written, write each of them and then immediately
// call it after the function definition.
// 1) TODO: Define a function that prints "Hello World!"
// 2) TODO: Define a function that prints "Hello \(name)!" with name being passed in as a parameter.
// 3) TODO: Write a function that accepts a string optional. If the string optional exists, print "Hello {value of string}!". If it doesn't, print "Hello world!".
// 4) TODO: Write a function that is the same as 3), except that it RETURNS the string instead of printing it.
// 5) TODO: Create a function getTapPosition which returns a tuple with an x and y value (Int). Any valid Integer value is fine for the x and y values.
// 6) TODO: Create a joinStrings function that takes two strings and a third parameter that has a default value of ",". HINT: Look at the Apple Swift Tour guide on functions for an example if you get stuck.
| gpl-3.0 |
MainasuK/hitokoto | hitokoto/hitokoto/HitokotoData/HitokotoData.swift | 1 | 3063 | //
// HitokotoData.swift
//
//
// Created by Cirno MainasuK on 2015-5-8.
//
//
import Foundation
// Create an error type that you'll use later
enum HitokotoDataInitializationError: ErrorType {
case InvalidHitokotoData(identifier: String, data: AnyObject?)
}
struct HitokotoData { // You don't really need to use a class here since it's just a data structure. A struct would be much better on performance in Swift. Also as always, use as strict scope as possible.
let hitokoto: String
let source: String
let category: String
let author: String
let like: Int
let date: String
let catname: String
let id: Int
init(hitokotoDictionary: [String: NSObject]) throws { // Create a throwable initializer rather than using forced unwrapping
let jsonResult = hitokotoDictionary
print(jsonResult)
// Create constants that you'll use more than once
let hitokotoIdentifier = "hitokoto"
let sourceIdentifier = "source"
let categoryIdentifier = "cat"
let authorIdentifier = "author"
let likeIdentifier = "like"
let dateIdentifier = "date"
let catnameIdentifier = "catname"
let idIdentifier = "id"
// Make sure every thing you need in the dictionary is valid
guard let hitokoto = jsonResult[hitokotoIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: hitokotoIdentifier, data: jsonResult[hitokotoIdentifier])
}
guard let source = jsonResult[sourceIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: sourceIdentifier, data: jsonResult[sourceIdentifier])
}
guard let category = jsonResult[categoryIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: categoryIdentifier, data: jsonResult[categoryIdentifier])
}
guard let author = jsonResult[authorIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: authorIdentifier, data: jsonResult[authorIdentifier])
}
guard let like = jsonResult[likeIdentifier] as? Int else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: likeIdentifier, data: jsonResult[likeIdentifier])
}
guard let date = jsonResult[dateIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: dateIdentifier, data: jsonResult[dateIdentifier])
}
guard let catname = jsonResult[catnameIdentifier] as? String else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: catnameIdentifier, data: jsonResult[catnameIdentifier])
}
guard let id = jsonResult[idIdentifier] as? Int else {
throw HitokotoDataInitializationError.InvalidHitokotoData(identifier: idIdentifier, data: jsonResult[idIdentifier])
}
// Initialize
self.hitokoto = hitokoto
self.source = source
self.category = category
self.author = author
self.like = like
self.date = date
self.catname = catname
self.id = id
}
}
| mit |
bingoogolapple/SwiftNote-PartOne | 归档和恢复/归档和恢复/AppDelegate.swift | 1 | 2175 | //
// AppDelegate.swift
// 归档和恢复
//
// Created by bingoogol on 14/8/24.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
carlosgrossi/ExtensionKit | ExtensionKit/ExtensionKit/UIKit/UITextView.swift | 1 | 400 | //
// UITextView.swift
// Pods
//
// Created by Carlos Grossi on 19/06/17.
//
//
import Foundation
extension UITextView {
override open var contentSize: CGSize {
didSet {
var topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
topCorrection = max(0, topCorrection)
contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0)
}
}
}
| mit |
turekj/ReactiveTODO | ReactiveTODOTests/Classes/DataAccess/Impl/TODONoteDataAccessObjectSpec.swift | 1 | 7736 | @testable import ReactiveTODOFramework
import Nimble
import Quick
import RealmSwift
class TODONoteDataAccessObjectSpec: QuickSpec {
override func spec() {
describe("TODONoteDataAccessObject") {
let factory = TODONoteFactoryMock()
let sut = TODONoteDataAccessObject(factory: factory)
context("When creating a TODONote") {
it("Should save created note in database") {
let realm = try! Realm()
factory.guid = "FACTORY_GUID"
factory.completed = true
sut.createTODONote(NSDate(timeIntervalSince1970: 444),
note: "Creanote", priority: Priority.Urgent)
expect(realm.objects(TODONote.self).count).to(equal(1))
expect(realm.objects(TODONote.self).first).toNot(beNil())
expect(realm.objects(TODONote.self).first?.guid)
.to(equal("FACTORY_GUID"))
expect(realm.objects(TODONote.self).first?.date)
.to(equal(NSDate(timeIntervalSince1970: 444)))
expect(realm.objects(TODONote.self).first?.note)
.to(equal("Creanote"))
expect(realm.objects(TODONote.self).first?.priority)
.to(equal(Priority.Urgent))
expect(realm.objects(TODONote.self).first?.completed)
.to(beTrue())
}
it("Should return created note") {
factory.guid = "CREATED_GUID"
factory.completed = true
let result = sut.createTODONote(
NSDate(timeIntervalSince1970: 444),
note: "Creanote",
priority: Priority.Urgent)
expect(result.guid).to(equal("CREATED_GUID"))
expect(result.note).to(equal("Creanote"))
expect(result.date).to(
equal(NSDate(timeIntervalSince1970: 444)))
expect(result.priority).to(equal(Priority.Urgent))
expect(result.completed).to(beTrue())
}
}
context("When returning note by GUID") {
it("Should return correct note") {
let realm = try! Realm()
let firstNote = TODONote()
firstNote.guid = "note_1_guid"
firstNote.date = NSDate(timeIntervalSince1970: 222)
firstNote.note = "Note One"
firstNote.priority = .Urgent
firstNote.completed = false
let secondNote = TODONote()
secondNote.guid = "note_2_guid"
secondNote.date = NSDate(timeIntervalSince1970: 111)
secondNote.note = "Note Two"
secondNote.priority = .Urgent
secondNote.completed = false
try! realm.write {
realm.add(firstNote)
realm.add(secondNote)
}
let note = sut.getNote("note_2_guid")
expect(note).toNot(beNil())
expect(note?.guid).to(equal("note_2_guid"))
expect(note?.date).to(equal(NSDate(timeIntervalSince1970: 111)))
expect(note?.note).to(equal("Note Two"))
expect(note?.priority).to(equal(Priority.Urgent))
expect(note?.completed).to(beFalse())
}
}
context("When returning current TODONotes") {
it("Should return notes that are not complete") {
let realm = try! Realm()
let completedNote = TODONote()
completedNote.guid = "AWESOME_UNIQUE_GUID"
completedNote.date = NSDate(timeIntervalSince1970: 1970)
completedNote.note = "Awesome Note"
completedNote.priority = .Urgent
completedNote.completed = true
let notCompletedNote = TODONote()
notCompletedNote.guid = "AWESOME_UNIQUE_GUID_NOT_COMPLETED"
notCompletedNote.date = NSDate(timeIntervalSince1970: 111)
notCompletedNote.note = "Awesome Not Completed Note"
notCompletedNote.priority = .Low
notCompletedNote.completed = false
try! realm.write {
realm.add(completedNote)
realm.add(notCompletedNote)
}
let notes = sut.getCurrentTODONotes()
expect(notes.count).to(equal(1))
expect(notes.first?.guid)
.to(equal("AWESOME_UNIQUE_GUID_NOT_COMPLETED"))
expect(notes.first?.date)
.to(equal(NSDate(timeIntervalSince1970: 111)))
expect(notes.first?.note)
.to(equal("Awesome Not Completed Note"))
expect(notes.first?.priority).to(equal(Priority.Low))
expect(notes.first?.completed).to(beFalse())
}
it("Should order notes by ascending date") {
let realm = try! Realm()
let firstNote = TODONote()
firstNote.guid = "note_1_date"
firstNote.date = NSDate(timeIntervalSince1970: 222)
firstNote.note = "Note One"
firstNote.priority = .Urgent
firstNote.completed = false
let secondNote = TODONote()
secondNote.guid = "note_2_date"
secondNote.date = NSDate(timeIntervalSince1970: 111)
secondNote.note = "Note Two"
secondNote.priority = .Urgent
secondNote.completed = false
try! realm.write {
realm.add(firstNote)
realm.add(secondNote)
}
let notes = sut.getCurrentTODONotes()
expect(notes.count).to(equal(2))
expect(notes.first?.guid)
.to(equal("note_2_date"))
expect(notes.last?.guid)
.to(equal("note_1_date"))
}
}
context("When marking note as completed") {
it("Should set completed flag to true") {
let realm = try! Realm()
let note = TODONote()
note.guid = "completed_test_guid"
note.date = NSDate(timeIntervalSince1970: 222)
note.note = "Note to complete"
note.priority = .Urgent
note.completed = false
try! realm.write {
realm.add(note)
}
sut.completeTODONote("completed_test_guid")
let noteQuery = realm.objects(TODONote.self)
.filter("guid = 'completed_test_guid'")
expect(noteQuery.count).to(equal(1))
expect(noteQuery.first?.guid)
.to(equal("completed_test_guid"))
expect(noteQuery.first?.completed).to(beTrue())
}
}
}
}
}
| mit |
e78l/swift-corelibs-foundation | TestFoundation/FTPServer.swift | 1 | 11599 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if !os(Windows)
//This is a very rudimentary FTP server written plainly for testing URLSession FTP Implementation.
import Dispatch
#if canImport(Glibc)
import Glibc
#elseif canImport(Darwin)
import Darwin
#endif
class _FTPSocket {
private var listenSocket: Int32!
private var socketAddress = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1)
private var socketAddress1 = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1)
private var connectionSocket: Int32!
var dataSocket: Int32! // data socket for communication
var dataSocketPort: UInt16! // data socket port, should be sent as part of header
private func isNotMinusOne(r: CInt) -> Bool {
return r != -1
}
private func isZero(r: CInt) -> Bool {
return r == 0
}
private func attempt(_ name: String, file: String = #file, line: UInt = #line, valid: (CInt) -> Bool, _ b: @autoclosure () -> CInt) throws -> CInt {
let r = b()
guard valid(r) else { throw ServerError(operation: name, errno: r, file: file, line: line) }
return r
}
init(port: UInt16) throws {
#if os(Linux)
let SOCKSTREAM = Int32(SOCK_STREAM.rawValue)
#else
let SOCKSTREAM = SOCK_STREAM
#endif
listenSocket = try attempt("socket", valid: isNotMinusOne, socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP)))
var on: Int = 1
_ = try attempt("setsockopt", valid: isZero, setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<Int>.size)))
let sa = createSockaddr(port)
socketAddress.initialize(to: sa)
try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, {
let addr = UnsafePointer<sockaddr>($0)
_ = try attempt("bind", valid: isZero, bind(listenSocket, addr, socklen_t(MemoryLayout<sockaddr>.size)))
})
dataSocket = try attempt("socket", valid: isNotMinusOne,
socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP)))
var on1: Int = 1
_ = try attempt("setsockopt", valid: isZero,
setsockopt(dataSocket, SOL_SOCKET, SO_REUSEADDR, &on1, socklen_t(MemoryLayout<Int>.size)))
let sa1 = createSockaddr(port+1)
socketAddress1.initialize(to: sa1)
try socketAddress1.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, {
let addr = UnsafeMutablePointer<sockaddr>($0)
_ = try attempt("bind", valid: isZero, bind(dataSocket, addr, socklen_t(MemoryLayout<sockaddr>.size)))
var sockLen = socklen_t(MemoryLayout<sockaddr>.size)
_ = try attempt("listen", valid: isZero, listen(dataSocket, SOMAXCONN))
// Open the data port asynchronously. Port should be opened before ESPV header communication.
DispatchQueue(label: "delay").async {
do {
self.dataSocket = try self.attempt("accept", valid: self.isNotMinusOne, accept(self.dataSocket, addr, &sockLen))
self.dataSocketPort = sa1.sin_port
} catch {
NSLog("Could not open data port.")
}
}
})
}
private func createSockaddr(_ port: UInt16) -> sockaddr_in {
// Listen on the loopback address so that OSX doesnt pop up a dialog
// asking to accept incoming connections if the firewall is enabled.
let addr = UInt32(INADDR_LOOPBACK).bigEndian
let netPort = port.bigEndian
#if os(Linux)
return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0))
#elseif os(Android)
return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), __pad: (0,0,0,0,0,0,0,0))
#else
return sockaddr_in(sin_len: 0, sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0))
#endif
}
func acceptConnection(notify: ServerSemaphore) throws {
_ = try attempt("listen", valid: isZero, listen(listenSocket, SOMAXCONN))
try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, {
let addr = UnsafeMutablePointer<sockaddr>($0)
var sockLen = socklen_t(MemoryLayout<sockaddr>.size)
notify.signal()
connectionSocket = try attempt("accept", valid: isNotMinusOne, accept(listenSocket, addr, &sockLen))
})
}
func readData() throws -> String {
var buffer = [UInt8](repeating: 0, count: 4096)
_ = try attempt("read", valid: isNotMinusOne, CInt(read(connectionSocket, &buffer, 4096)))
return String(cString: &buffer)
}
func readDataOnDataSocket() throws -> String {
var buffer = [UInt8](repeating: 0, count: 4096)
_ = try attempt("read", valid: isNotMinusOne, CInt(read(dataSocket, &buffer, 4096)))
return String(cString: &buffer)
}
func writeRawData(_ data: Data) throws {
_ = try data.withUnsafeBytes { ptr in
try attempt("write", valid: isNotMinusOne, CInt(write(connectionSocket, ptr, data.count)))
}
}
func writeRawData(socket data: Data) throws -> Int32 {
var bytesWritten: Int32 = 0
_ = try data.withUnsafeBytes { ptr in
bytesWritten = try attempt("write", valid: isNotMinusOne, CInt(write(dataSocket, ptr, data.count)))
}
return bytesWritten
}
func shutdown() {
close(connectionSocket)
close(listenSocket)
close(dataSocket)
}
}
class _FTPServer {
let socket: _FTPSocket
let commandPort: UInt16
init(port: UInt16) throws {
commandPort = port
socket = try _FTPSocket(port: port)
}
public class func create(port: UInt16) throws -> _FTPServer {
return try _FTPServer(port: port)
}
public func listen(notify: ServerSemaphore) throws {
try socket.acceptConnection(notify: notify)
}
public func stop() {
socket.shutdown()
}
// parse header information and respond accordingly
public func parseHeaderData() throws {
let saveData = """
FTP implementation to test FTP
upload, download and data tasks. Instead of sending a file,
we are sending the hardcoded data.We are going to test FTP
data, download and upload tasks with delegates & completion handlers.
Creating the data here as we need to pass the count
as part of the header.\r\n
""".data(using: String.Encoding.utf8)
let dataCount = saveData?.count
let read = try socket.readData()
if read.contains("anonymous") {
try respondWithRawData(with: "331 Please specify the password.\r\n")
} else if read.contains("PASS") {
try respondWithRawData(with: "230 Login successful.\r\n")
} else if read.contains("PWD") {
try respondWithRawData(with: "257 \"/\"\r\n")
} else if read.contains("EPSV") {
try respondWithRawData(with: "229 Entering Extended Passive Mode (|||\(commandPort+1)|).\r\n")
} else if read.contains("TYPE I") {
try respondWithRawData(with: "200 Switching to Binary mode.\r\n")
} else if read.contains("SIZE") {
try respondWithRawData(with: "213 \(dataCount!)\r\n")
} else if read.contains("RETR") {
try respondWithRawData(with: "150 Opening BINARY mode data, connection for test.txt (\(dataCount!) bytes).\r\n")
// Send data here through data port
do {
let dataWritten = try respondWithData(with: saveData!)
if dataWritten != -1 {
// Send the end header on command port
try respondWithRawData(with: "226 Transfer complete.\r\n")
}
} catch {
NSLog("Transfer failed.")
}
} else if read.contains("STOR") {
// Request is for upload. As we are only dealing with data, just read the data and ignore
try respondWithRawData(with: "150 Ok to send data.\r\n")
// Read data from the data socket and respond with completion header after the transfer
do {
_ = try readDataOnDataSocket()
try respondWithRawData(with: "226 Transfer complete.\r\n")
} catch {
NSLog("Transfer failed.")
}
}
}
public func respondWithRawData(with string: String) throws {
try self.socket.writeRawData(string.data(using: String.Encoding.utf8)!)
}
public func respondWithData(with data: Data) throws -> Int32 {
return try self.socket.writeRawData(socket: data)
}
public func readDataOnDataSocket() throws -> String {
return try self.socket.readDataOnDataSocket()
}
}
public class TestFTPURLSessionServer {
let ftpServer: _FTPServer
public init (port: UInt16) throws {
ftpServer = try _FTPServer.create(port: port)
}
public func start(started: ServerSemaphore) throws {
started.signal()
try ftpServer.listen(notify: started)
}
public func parseHeaderAndRespond() throws {
try ftpServer.parseHeaderData()
}
func writeStartHeaderData() throws {
try ftpServer.respondWithRawData(with: "220 (vsFTPd 2.3.5)\r\n")
}
func stop() {
ftpServer.stop()
}
}
class LoopbackFTPServerTest: XCTestCase {
static var serverPort: Int = -1
override class func setUp() {
super.setUp()
func runServer(with condition: ServerSemaphore,
startDelay: TimeInterval? = nil,
sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
let start = 21961 // 21961
for port in start...(start+100) { //we must find at least one port to bind
do {
serverPort = port
let test = try TestFTPURLSessionServer(port: UInt16(port))
try test.start(started: condition)
try test.writeStartHeaderData() // Welcome message to start the transfer
for _ in 1...7 {
try test.parseHeaderAndRespond()
}
test.stop()
} catch let err as ServerError {
if err.operation == "bind" { continue }
throw err
}
}
}
let serverReady = ServerSemaphore()
globalDispatchQueue.async {
do {
try runServer(with: serverReady)
} catch {
XCTAssertTrue(true)
return
}
}
let timeout = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 2_000_000_000)
serverReady.wait(timeout: timeout)
}
}
#endif
| apache-2.0 |
creatubbles/ctb-api-swift | CreatubblesAPIClientIntegrationTests/Spec/Creation/NewCreationUploadResponseHandlerSpec.swift | 1 | 3010 | //
// NewCreationUploadResponseHandlerSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class NewCreationUploadResponseHandlerSpec: QuickSpec {
override func spec() {
describe("New Creation Upload response handler") {
it("Should return correct value after login") {
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(NewCreationUploadRequest(creationId: "hkwIetSk"), withResponseHandler:NewCreationUploadResponseHandler {
(creationUpload: CreationUpload?, error: Error?) -> Void in
expect(error).to(beNil())
expect(creationUpload).notTo(beNil())
done()
})
}
}
}
it("Should return error when not logged in") {
let sender = TestComponentsFactory.requestSender
sender.logout()
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.send(NewCreationUploadRequest(creationId: "TestCreation"), withResponseHandler:NewCreationUploadResponseHandler {
(creationUpload: CreationUpload?, error: Error?) -> Void in
expect(error).notTo(beNil())
expect(creationUpload).to(beNil())
done()
})
}
}
}
}
}
| mit |
ben-ng/swift | test/Constraints/function.swift | 1 | 2643 | // RUN: %target-typecheck-verify-swift
func f0(_ x: Float) -> Float {}
func f1(_ x: Float) -> Float {}
func f2(_ x: @autoclosure () -> Float) {}
var f : Float
_ = f0(f0(f))
_ = f0(1)
_ = f1(f1(f))
f2(f)
f2(1.0)
func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool {
return rhs()
}
// Function returns
func weirdCast<T, U>(_ x: T) -> U {}
func ff() -> (Int) -> (Float) { return weirdCast }
// Block <-> function conversions
var funct: (Int) -> Int = { $0 }
var block: @convention(block) (Int) -> Int = funct
funct = block
block = funct
// Application of implicitly unwrapped optional functions
var optFunc: ((String) -> String)! = { $0 }
var s: String = optFunc("hi")
// <rdar://problem/17652759> Default arguments cause crash with tuple permutation
func testArgumentShuffle(_ first: Int = 7, third: Int = 9) {
}
testArgumentShuffle(third: 1, 2) // expected-error {{unnamed argument #2 must precede argument 'third'}} {{21-29=2}} {{31-32=third: 1}}
func rejectsAssertStringLiteral() {
assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
}
// <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads
func process(_ line: UInt = #line, _ fn: () -> Void) {}
func process(_ line: UInt = #line) -> Int { return 0 }
func dangerous() throws {}
func test() {
process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}}
try dangerous()
test()
}
}
// <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic
class A {
func a(_ text:String) {
}
func a(_ text:String, something:Int?=nil) {
}
}
A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}}
// <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type
func r22451001() -> AnyObject {}
print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}}
// SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler
// SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any'
func sr590(_ x: Any) {} // expected-note {{'sr590' declared here}}
sr590(3,4) // expected-error {{extra argument in call}}
sr590() // expected-error {{missing argument for parameter #1 in call}}
// Make sure calling with structural tuples still works.
sr590(())
sr590((1, 2))
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/26971-swift-constraints-constraintsystem-solvesimplified.swift | 1 | 452 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{func a{return""}struct c<T where f:A{class n{let a={
| apache-2.0 |
Henryforce/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorView.swift | 1 | 16603 | //
// KRActivityIndicatorView.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
/**
Enum of animation types used for activity indicator view.
- Blank: Blank animation.
- BallPulse: BallPulse animation.
- BallGridPulse: BallGridPulse animation.
- BallClipRotate: BallClipRotate animation.
- SquareSpin: SquareSpin animation.
- BallClipRotatePulse: BallClipRotatePulse animation.
- BallClipRotateMultiple: BallClipRotateMultiple animation.
- BallPulseRise: BallPulseRise animation.
- BallRotate: BallRotate animation.
- CubeTransition: CubeTransition animation.
- BallZigZag: BallZigZag animation.
- BallZigZagDeflect: BallZigZagDeflect animation.
- BallTrianglePath: BallTrianglePath animation.
- BallScale: BallScale animation.
- LineScale: LineScale animation.
- LineScaleParty: LineScaleParty animation.
- BallScaleMultiple: BallScaleMultiple animation.
- BallPulseSync: BallPulseSync animation.
- BallBeat: BallBeat animation.
- LineScalePulseOut: LineScalePulseOut animation.
- LineScalePulseOutRapid: LineScalePulseOutRapid animation.
- BallScaleRipple: BallScaleRipple animation.
- BallScaleRippleMultiple: BallScaleRippleMultiple animation.
- BallSpinFadeLoader: BallSpinFadeLoader animation.
- LineSpinFadeLoader: LineSpinFadeLoader animation.
- TriangleSkewSpin: TriangleSkewSpin animation.
- Pacman: Pacman animation.
- BallGridBeat: BallGridBeat animation.
- SemiCircleSpin: SemiCircleSpin animation.
- BallRotateChase: BallRotateChase animation.
- Orbit: Orbit animation.
- AudioEqualizer: AudioEqualizer animation.
*/
public enum KRActivityIndicatorType: Int {
/**
Blank.
- returns: Instance of KRActivityIndicatorAnimationBlank.
*/
case blank
/**
BallPulse.
- returns: Instance of KRActivityIndicatorAnimationBallPulse.
*/
case ballPulse
/**
BallGridPulse.
- returns: Instance of KRActivityIndicatorAnimationBallGridPulse.
*/
case ballGridPulse
/**
BallClipRotate.
- returns: Instance of KRActivityIndicatorAnimationBallClipRotate.
*/
case ballClipRotate
/**
SquareSpin.
- returns: Instance of KRActivityIndicatorAnimationSquareSpin.
*/
case squareSpin
/**
BallClipRotatePulse.
- returns: Instance of KRActivityIndicatorAnimationBallClipRotatePulse.
*/
case ballClipRotatePulse
/**
BallClipRotateMultiple.
- returns: Instance of KRActivityIndicatorAnimationBallClipRotateMultiple.
*/
case ballClipRotateMultiple
/**
BallPulseRise.
- returns: Instance of KRActivityIndicatorAnimationBallPulseRise.
*/
case ballPulseRise
/**
BallRotate.
- returns: Instance of KRActivityIndicatorAnimationBallRotate.
*/
case ballRotate
/**
CubeTransition.
- returns: Instance of KRActivityIndicatorAnimationCubeTransition.
*/
case cubeTransition
/**
BallZigZag.
- returns: Instance of KRActivityIndicatorAnimationBallZigZag.
*/
case ballZigZag
/**
BallZigZagDeflect
- returns: Instance of KRActivityIndicatorAnimationBallZigZagDeflect
*/
case ballZigZagDeflect
/**
BallTrianglePath.
- returns: Instance of KRActivityIndicatorAnimationBallTrianglePath.
*/
case ballTrianglePath
/**
BallScale.
- returns: Instance of KRActivityIndicatorAnimationBallScale.
*/
case ballScale
/**
LineScale.
- returns: Instance of KRActivityIndicatorAnimationLineScale.
*/
case lineScale
/**
LineScaleParty.
- returns: Instance of KRActivityIndicatorAnimationLineScaleParty.
*/
case lineScaleParty
/**
BallScaleMultiple.
- returns: Instance of KRActivityIndicatorAnimationBallScaleMultiple.
*/
case ballScaleMultiple
/**
BallPulseSync.
- returns: Instance of KRActivityIndicatorAnimationBallPulseSync.
*/
case ballPulseSync
/**
BallBeat.
- returns: Instance of KRActivityIndicatorAnimationBallBeat.
*/
case ballBeat
/**
LineScalePulseOut.
- returns: Instance of KRActivityIndicatorAnimationLineScalePulseOut.
*/
case lineScalePulseOut
/**
LineScalePulseOutRapid.
- returns: Instance of KRActivityIndicatorAnimationLineScalePulseOutRapid.
*/
case lineScalePulseOutRapid
/**
BallScaleRipple.
- returns: Instance of KRActivityIndicatorAnimationBallScaleRipple.
*/
case ballScaleRipple
/**
BallScaleRippleMultiple.
- returns: Instance of KRActivityIndicatorAnimationBallScaleRippleMultiple.
*/
case ballScaleRippleMultiple
/**
BallSpinFadeLoader.
- returns: Instance of KRActivityIndicatorAnimationBallSpinFadeLoader.
*/
case ballSpinFadeLoader
/**
LineSpinFadeLoader.
- returns: Instance of KRActivityIndicatorAnimationLineSpinFadeLoader.
*/
case lineSpinFadeLoader
/**
TriangleSkewSpin.
- returns: Instance of KRActivityIndicatorAnimationTriangleSkewSpin.
*/
case triangleSkewSpin
/**
Pacman.
- returns: Instance of KRActivityIndicatorAnimationPacman.
*/
case pacman
/**
BallGridBeat.
- returns: Instance of KRActivityIndicatorAnimationBallGridBeat.
*/
case ballGridBeat
/**
SemiCircleSpin.
- returns: Instance of KRActivityIndicatorAnimationSemiCircleSpin.
*/
case semiCircleSpin
/**
BallRotateChase.
- returns: Instance of KRActivityIndicatorAnimationBallRotateChase.
*/
case ballRotateChase
/**
Orbit.
- returns: Instance of KRActivityIndicatorAnimationOrbit.
*/
case orbit
/**
AudioEqualizer.
- returns: Instance of KRActivityIndicatorAnimationAudioEqualizer.
*/
case audioEqualizer
static let allTypes = (blank.rawValue ... audioEqualizer.rawValue).map{ KRActivityIndicatorType(rawValue: $0)! }
func animation() -> KRActivityIndicatorAnimationDelegate {
switch self {
case .blank:
return KRActivityIndicatorAnimationBlank()
case .ballPulse:
return KRActivityIndicatorAnimationBallPulse()
case .ballGridPulse:
return KRActivityIndicatorAnimationBallGridPulse()
case .ballClipRotate:
return KRActivityIndicatorAnimationBallClipRotate()
case .squareSpin:
return KRActivityIndicatorAnimationSquareSpin()
case .ballClipRotatePulse:
return KRActivityIndicatorAnimationBallClipRotatePulse()
case .ballClipRotateMultiple:
return KRActivityIndicatorAnimationBallClipRotateMultiple()
case .ballPulseRise:
return KRActivityIndicatorAnimationBallPulseRise()
case .ballRotate:
return KRActivityIndicatorAnimationBallRotate()
case .cubeTransition:
return KRActivityIndicatorAnimationCubeTransition()
case .ballZigZag:
return KRActivityIndicatorAnimationBallZigZag()
case .ballZigZagDeflect:
return KRActivityIndicatorAnimationBallZigZagDeflect()
case .ballTrianglePath:
return KRActivityIndicatorAnimationBallTrianglePath()
case .ballScale:
return KRActivityIndicatorAnimationBallScale()
case .lineScale:
return KRActivityIndicatorAnimationLineScale()
case .lineScaleParty:
return KRActivityIndicatorAnimationLineScaleParty()
case .ballScaleMultiple:
return KRActivityIndicatorAnimationBallScaleMultiple()
case .ballPulseSync:
return KRActivityIndicatorAnimationBallPulseSync()
case .ballBeat:
return KRActivityIndicatorAnimationBallBeat()
case .lineScalePulseOut:
return KRActivityIndicatorAnimationLineScalePulseOut()
case .lineScalePulseOutRapid:
return KRActivityIndicatorAnimationLineScalePulseOutRapid()
case .ballScaleRipple:
return KRActivityIndicatorAnimationBallScaleRipple()
case .ballScaleRippleMultiple:
return KRActivityIndicatorAnimationBallScaleRippleMultiple()
case .ballSpinFadeLoader:
return KRActivityIndicatorAnimationBallSpinFadeLoader()
case .lineSpinFadeLoader:
return KRActivityIndicatorAnimationLineSpinFadeLoader()
case .triangleSkewSpin:
return KRActivityIndicatorAnimationTriangleSkewSpin()
case .pacman:
return KRActivityIndicatorAnimationPacman()
case .ballGridBeat:
return KRActivityIndicatorAnimationBallGridBeat()
case .semiCircleSpin:
return KRActivityIndicatorAnimationSemiCircleSpin()
case .ballRotateChase:
return KRActivityIndicatorAnimationBallRotateChase()
case .orbit:
return KRActivityIndicatorAnimationOrbit()
case .audioEqualizer:
return KRActivityIndicatorAnimationAudioEqualizer()
//default:
// return KRActivityIndicatorAnimationLineScalePulseOut()
}
}
}
/// Activity indicator view with nice animations
public final class KRActivityIndicatorView: NSView {
/// Default type. Default value is .BallSpinFadeLoader.
public static var DEFAULT_TYPE: KRActivityIndicatorType = .blank
/// Default color. Default value is NSColor.white.
public static var DEFAULT_COLOR = NSColor.white
/// Default padding. Default value is 0.0 - 0% padding
public static var DEFAULT_PADDING: CGFloat = 0.0
/// Default size of activity indicator view in UI blocker. Default value is 60x60.
public static var DEFAULT_BLOCKER_SIZE = CGSize(width: 60, height: 60)
/// Default display time threshold to actually display UI blocker. Default value is 0 ms.
public static var DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD = 0
/// Default minimum display time of UI blocker. Default value is 0 ms.
public static var DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME = 0
/// Default message displayed in UI blocker. Default value is nil.
public static var DEFAULT_BLOCKER_MESSAGE: String? = nil
/// Default font of message displayed in UI blocker. Default value is bold system font, size 20.
public static var DEFAULT_BLOCKER_MESSAGE_FONT = NSFont.boldSystemFont(ofSize: 20)
/// Default background color of UI blocker. Default value is UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
public static var DEFAULT_BLOCKER_BACKGROUND_COLOR = NSColor(red: 0, green: 0, blue: 0, alpha: 0.5)
/// Animation type.
public var type: KRActivityIndicatorType = KRActivityIndicatorView.DEFAULT_TYPE
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'type' instead.")
@IBInspectable var typeName: String {
get {
return getTypeName()
}
set {
_setTypeName(newValue)
}
}
/// Color of activity indicator view.
@IBInspectable public var color: NSColor = KRActivityIndicatorView.DEFAULT_COLOR
/// Padding of activity indicator view.
@IBInspectable public var padding: CGFloat = KRActivityIndicatorView.DEFAULT_PADDING
/// Current status of animation, read-only.
@available(*, deprecated)
public var animating: Bool { return isAnimating }
/// Current status of animation, read-only.
public private(set) var isAnimating: Bool = false
/**
Returns an object initialized from data in a given unarchiver.
self, initialized using the data in decoder.
- parameter decoder: an unarchiver object.
- returns: self, initialized using the data in decoder.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//backgroundColor = NSColor.clear
isHidden = true
}
/**
Create a activity indicator view.
Appropriate KRActivityIndicatorView.DEFAULT_* values are used for omitted params.
- parameter frame: view's frame.
- parameter type: animation type.
- parameter color: color of activity indicator view.
- parameter padding: padding of activity indicator view.
- returns: The activity indicator view.
*/
public init(frame: CGRect, type: KRActivityIndicatorType? = nil, color: NSColor? = nil, padding: CGFloat? = nil) {
self.type = type ?? KRActivityIndicatorView.DEFAULT_TYPE
self.color = color ?? KRActivityIndicatorView.DEFAULT_COLOR
self.padding = padding ?? KRActivityIndicatorView.DEFAULT_PADDING
super.init(frame: frame)
isHidden = true
}
/**
Returns the natural size for the receiving view, considering only properties of the view itself.
A size indicating the natural size for the receiving view based on its intrinsic properties.
- returns: A size indicating the natural size for the receiving view based on its intrinsic properties.
*/
public override var intrinsicContentSize : CGSize {
return CGSize(width: bounds.width, height: bounds.height)
}
/**
Start animating.
*/
public final func startAnimating() {
isHidden = false
isAnimating = true
layer?.speed = 1
//self.type = KRActivityIndicatorView.DEFAULT_TYPE
setUpAnimation()
}
/**
Stop animating.
*/
public final func stopAnimating() {
isHidden = true
isAnimating = false
layer?.sublayers?.removeAll()
}
// MARK: Internal
func _setTypeName(_ typeName: String) {
for item in KRActivityIndicatorType.allTypes {
if String(describing: item).caseInsensitiveCompare(typeName) == ComparisonResult.orderedSame {
type = item
break
}
}
}
func getTypeName() -> String {
return String(describing: type)
}
// MARK: Privates
private final func setUpAnimation() {
if(layer == nil){
layer = CALayer()
}
self.wantsLayer = true
let animation: KRActivityIndicatorAnimationDelegate = type.animation()
//var animationRect = UIEdgeInsetsInsetRect(frame, NSEdgeInsetsMake(padding, padding, padding, padding))
// TODO: CGRectInset alternative for padding...
var animationRect = CGRect(x: padding, y: padding, width: frame.size.width - padding, height: frame.size.height - padding)
let minEdge = min(animationRect.width, animationRect.height)
layer?.sublayers = nil
animationRect.size = CGSize(width: minEdge, height: minEdge)
animation.setUpAnimation(in: layer!, size: animationRect.size, color: color)
}
}
| mit |
ankurp/Dollar.swift | Package.swift | 3 | 65 | import PackageDescription
let package = Package(name: "Dollar")
| mit |
webim/webim-client-sdk-ios | Example/Tests/MessageImplTests.swift | 1 | 29283 | //
// MessageImplTests.swift
// WebimClientLibrary_Tests
//
// Created by Nikita Lazarev-Zubov on 20.02.18.
// Copyright © 2018 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
@testable import WebimClientLibrary
import XCTest
class MessageImplTests: XCTestCase {
// MARK: - Tests
func testToString() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let expectedString = """
MessageImpl {
serverURLString = http://demo.webim.ru,
ID = id,
operatorID = nil,
senderAvatarURLString = nil,
senderName = Name,
type = visitorMessage,
text = Text,
timeInMicrosecond = 0,
attachment = nil,
historyMessage = false,
currentChatID = nil,
historyID = nil,
rawText = nil,
read = false
}
"""
XCTAssertEqual(message.toString(),
expectedString)
}
func testGetSenderAvatarURL() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertNil(message.getSenderAvatarFullURL())
}
func testGetSendStatus() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertEqual(message.getSendStatus(),
MessageSendStatus.sent)
}
func testIsEqual() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message1 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id1",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message2 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name1",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message3 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text1",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message4 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .operatorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message5 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
let message6 = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: true,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertFalse(message.isEqual(to: message1))
XCTAssertFalse(message.isEqual(to: message2))
XCTAssertFalse(message.isEqual(to: message3))
XCTAssertFalse(message.isEqual(to: message4))
XCTAssertTrue(message.isEqual(to: message5))
XCTAssertFalse(message.isEqual(to: message6))
}
// MARK: MessageSource tests
func testAssertIsCurrentChat() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertNoThrow(try message.getSource().assertIsCurrentChat())
}
func testAssertIsHistory() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertThrowsError(try message.getSource().assertIsHistory())
}
func testGetHistoryID() {
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertNil(message.getHistoryID())
}
func testGetCurrentChatID() {
let currentChatID = "id"
let message = MessageImpl(serverURLString: "http://demo.webim.ru",
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: nil,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: currentChatID,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertEqual(currentChatID,
message.getCurrentChatID())
}
func testGetSenderAvatarFullURL() {
let baseURLString = "http://demo.webim.ru"
let avatarURLString = "/image.jpg"
let message = MessageImpl(serverURLString: baseURLString,
id: "id",
serverSideID: nil,
keyboard: nil,
keyboardRequest: nil,
operatorID: nil,
quote: nil,
senderAvatarURLString: avatarURLString,
senderName: "Name",
sendStatus: .sent,
sticker: nil,
type: .visitorMessage,
rawData: nil,
data: nil,
text: "Text",
timeInMicrosecond: 0,
historyMessage: false,
internalID: nil,
rawText: nil,
read: false,
messageCanBeEdited: false,
messageCanBeReplied: false,
messageIsEdited: false,
visitorReactionInfo: nil,
visitorCanReact: nil,
visitorChangeReaction: nil)
XCTAssertEqual(URL(string: (baseURLString + avatarURLString)),
message.getSenderAvatarFullURL())
}
}
// MARK: -
class MessageAttachmentTests: XCTestCase {
// MARK: - Tests
func testInit() {
let messageAttachment = FileInfoImpl(urlString: "/image.jpg",
size: 1,
filename: "image",
contentType: "image/jpeg",
guid: "image123",
fileUrlCreator: nil)
XCTAssertEqual(messageAttachment.getContentType(),
"image/jpeg")
XCTAssertEqual(messageAttachment.getFileName(),
"image")
XCTAssertEqual(messageAttachment.getSize(),
1)
XCTAssertEqual(messageAttachment.getURL(),
URL(string: "/image.jpg")!)
XCTAssertEqual(messageAttachment.getGuid(),
"image123")
}
}
// MARK: -
class ImageInfoImplTests: XCTestCase {
// MARK: - Tests
func testInit() {
let pageID = "page_id"
let authorizationToken = "auth_token"
let authorizationData = AuthorizationData(pageID: pageID,
authorizationToken: authorizationToken)
let SERVER_URL_STRING = "https://demo.webim.ru"
let userDefaultsKey = "userDefaultsKey"
let execIfNotDestroyedHandlerExecutor = ExecIfNotDestroyedHandlerExecutor(sessionDestroyer: SessionDestroyer(userDefaultsKey: userDefaultsKey),
queue: DispatchQueue.main)
let internalErrorListener = InternalErrorListenerForTests()
let actionRequestLoop = ActionRequestLoopForTests(completionHandlerExecutor: execIfNotDestroyedHandlerExecutor,
internalErrorListener: internalErrorListener)
let deltaRequestLoop = DeltaRequestLoop(deltaCallback: DeltaCallback(currentChatMessageMapper: CurrentChatMessageMapper(withServerURLString: SERVER_URL_STRING),
historyMessageMapper: HistoryMessageMapper(withServerURLString: SERVER_URL_STRING),
userDefaultsKey: userDefaultsKey),
completionHandlerExecutor: execIfNotDestroyedHandlerExecutor,
sessionParametersListener: nil,
internalErrorListener: internalErrorListener,
baseURL: SERVER_URL_STRING,
title: "title",
location: "location",
appVersion: nil,
visitorFieldsJSONString: nil,
providedAuthenticationTokenStateListener: nil,
providedAuthenticationToken: nil,
deviceID: "id",
deviceToken: nil,
remoteNotificationSystem: nil,
visitorJSONString: nil,
sessionID: nil,
prechat: nil,
authorizationData: authorizationData)
let webimClient = WebimClient(withActionRequestLoop: actionRequestLoop,
deltaRequestLoop: deltaRequestLoop,
webimActions: WebimActionsImpl(baseURL: SERVER_URL_STRING,
actionRequestLoop: actionRequestLoop))
let fileUrlCreator = FileUrlCreator(webimClient: webimClient, serverURL: SERVER_URL_STRING)
let imageInfo = ImageInfoImpl(withThumbURLString: "https://demo.webim.ru/thumb.jpg",
fileUrlCreator: fileUrlCreator,
filename: "thumb.jpg",
guid: "123",
width: 100,
height: 200)
XCTAssertEqual(imageInfo.getWidth(),
100)
XCTAssertEqual(imageInfo.getHeight(),
200)
}
}
| mit |
julienbodet/wikipedia-ios | WMF Framework/Theme.swift | 1 | 19288 | import Foundation
public extension UIColor {
@objc public convenience init(_ hex: Int, alpha: CGFloat) {
let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let g = CGFloat((hex & 0xFF00) >> 8) / 255.0
let b = CGFloat(hex & 0xFF) / 255.0
self.init(red: r, green: g, blue: b, alpha: alpha)
}
@objc(initWithHexInteger:)
public convenience init(_ hex: Int) {
self.init(hex, alpha: 1)
}
@objc public class func wmf_colorWithHex(_ hex: Int) -> UIColor {
return UIColor(hex)
}
fileprivate static let defaultShadow = UIColor(white: 0, alpha: 0.25)
fileprivate static let pitchBlack = UIColor(0x101418)
fileprivate static let base10 = UIColor(0x222222)
fileprivate static let base20 = UIColor(0x54595D)
fileprivate static let base30 = UIColor(0x72777D)
fileprivate static let base50 = UIColor(0xA2A9B1)
fileprivate static let base70 = UIColor(0xC8CCD1)
fileprivate static let base80 = UIColor(0xEAECF0)
fileprivate static let base90 = UIColor(0xF8F9FA)
fileprivate static let base100 = UIColor(0xFFFFFF)
fileprivate static let red30 = UIColor(0xB32424)
fileprivate static let red50 = UIColor(0xCC3333)
fileprivate static let red75 = UIColor(0xFF6E6E)
fileprivate static let yellow50 = UIColor(0xFFCC33)
fileprivate static let green50 = UIColor(0x00AF89)
fileprivate static let blue10 = UIColor(0x2A4B8D)
fileprivate static let blue50 = UIColor(0x3366CC)
fileprivate static let lightBlue = UIColor(0xEAF3FF)
fileprivate static let mesosphere = UIColor(0x43464A)
fileprivate static let thermosphere = UIColor(0x2E3136)
fileprivate static let stratosphere = UIColor(0x6699FF)
fileprivate static let exosphere = UIColor(0x27292D)
fileprivate static let accent = UIColor(0x00AF89)
fileprivate static let accent10 = UIColor(0x2A4B8D)
fileprivate static let amate = UIColor(0xE1DAD1)
fileprivate static let parchment = UIColor(0xF8F1E3)
fileprivate static let masi = UIColor(0x646059)
fileprivate static let papyrus = UIColor(0xF0E6D6)
fileprivate static let kraft = UIColor(0xCBC8C1)
fileprivate static let osage = UIColor(0xFF9500)
fileprivate static let darkSearchFieldBackground = UIColor(0x8E8E93, alpha: 0.12)
fileprivate static let lightSearchFieldBackground = UIColor(0xFFFFFF, alpha: 0.15)
fileprivate static let masi60PercentAlpha = UIColor(0x646059, alpha:0.6)
fileprivate static let black50PercentAlpha = UIColor(0x000000, alpha:0.5)
fileprivate static let black75PercentAlpha = UIColor(0x000000, alpha:0.75)
fileprivate static let white20PercentAlpha = UIColor(white: 1, alpha:0.2)
fileprivate static let base70At55PercentAlpha = base70.withAlphaComponent(0.55)
@objc public static let wmf_darkGray = UIColor(0x4D4D4B)
@objc public static let wmf_lightGray = UIColor(0x9AA0A7)
@objc public static let wmf_gray = UIColor.base70
@objc public static let wmf_lighterGray = UIColor.base80
@objc public static let wmf_lightestGray = UIColor(0xF5F5F5) // also known as refresh gray
@objc public static let wmf_darkBlue = UIColor.blue10
@objc public static let wmf_blue = UIColor.blue50
@objc public static let wmf_lightBlue = UIColor.lightBlue
@objc public static let wmf_green = UIColor.green50
@objc public static let wmf_lightGreen = UIColor(0xD5FDF4)
@objc public static let wmf_red = UIColor.red50
@objc public static let wmf_lightRed = UIColor(0xFFE7E6)
@objc public static let wmf_yellow = UIColor.yellow50
@objc public static let wmf_lightYellow = UIColor(0xFEF6E7)
@objc public static let wmf_orange = UIColor(0xFF5B00)
@objc public static let wmf_purple = UIColor(0x7F4AB3)
@objc public static let wmf_lightPurple = UIColor(0xF3E6FF)
@objc public func wmf_hexStringIncludingAlpha(_ includeAlpha: Bool) -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
var hexString = String(format: "%02X%02X%02X", Int(255.0 * r), Int(255.0 * g), Int(255.0 * b))
if (includeAlpha) {
hexString = hexString.appendingFormat("%02X", Int(255.0 * a))
}
return hexString
}
@objc public var wmf_hexString: String {
return wmf_hexStringIncludingAlpha(false)
}
}
@objc(WMFColors)
public class Colors: NSObject {
fileprivate static let light = Colors(baseBackground: .base80, midBackground: .base90, paperBackground: .base100, chromeBackground: .base100, popoverBackground: .base100, subCellBackground: .base100, overlayBackground: .black50PercentAlpha, batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .lightBlue, overlayText: .base20, searchFieldBackground: .darkSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .base30, tertiaryText: .base70, disabledText: .base80, disabledLink: .lightBlue, chromeText: .base20, link: .blue50, accent: .green50, border: .base70, shadow: .base80, chromeShadow: .defaultShadow, cardShadow: .base10, secondaryAction: .blue10, icon: nil, iconBackground: nil, destructive: .red50, error: .red50, warning: .osage, unselected: .base50, blurEffectStyle: .extraLight, blurEffectBackground: .clear)
fileprivate static let sepia = Colors(baseBackground: .amate, midBackground: .papyrus, paperBackground: .parchment, chromeBackground: .parchment, popoverBackground: .base100, subCellBackground: .papyrus, overlayBackground: .masi60PercentAlpha, batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .lightBlue, overlayText: .base20, searchFieldBackground: .darkSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .masi, tertiaryText: .masi, disabledText: .base80, disabledLink: .lightBlue, chromeText: .base20, link: .blue50, accent: .green50, border: .kraft, shadow: .kraft, chromeShadow: .base20, cardShadow: .kraft, secondaryAction: .accent10, icon: .masi, iconBackground: .amate, destructive: .red30, error: .red30, warning: .osage, unselected: .masi, blurEffectStyle: .extraLight, blurEffectBackground: .clear)
fileprivate static let dark = Colors(baseBackground: .base10, midBackground: .exosphere, paperBackground: .thermosphere, chromeBackground: .mesosphere, popoverBackground: .base10, subCellBackground: .exosphere, overlayBackground: .black75PercentAlpha, batchSelectionBackground: .accent10, referenceHighlightBackground: .clear, hintBackground: .pitchBlack, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .thermosphere, primaryText: .base90, secondaryText: .base70, tertiaryText: .base70, disabledText: .base70, disabledLink: .lightBlue, chromeText: .base90, link: .stratosphere, accent: .green50, border: .mesosphere, shadow: .base10, chromeShadow: .base10, cardShadow: .base10, secondaryAction: .accent10, icon: .base70, iconBackground: .exosphere, destructive: .red75, error: .red75, warning: .yellow50, unselected: .base70, blurEffectStyle: .dark, blurEffectBackground: .base70At55PercentAlpha)
fileprivate static let black = Colors(baseBackground: .pitchBlack, midBackground: .base10, paperBackground: .black, chromeBackground: .base10, popoverBackground: .base10, subCellBackground: .base10, overlayBackground: .black75PercentAlpha, batchSelectionBackground: .accent10, referenceHighlightBackground: .white20PercentAlpha, hintBackground: .thermosphere, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .thermosphere, primaryText: .base90, secondaryText: .base70, tertiaryText: .base70, disabledText: .base70, disabledLink: .lightBlue, chromeText: .base90, link: .stratosphere, accent: .green50, border: .mesosphere, shadow: .base10, chromeShadow: .base10, cardShadow: .base30, secondaryAction: .accent10, icon: .base70, iconBackground: .exosphere, destructive: .red75, error: .red75, warning: .yellow50, unselected: .base70, blurEffectStyle: .dark, blurEffectBackground: .base70At55PercentAlpha)
fileprivate static let widget = Colors(baseBackground: .clear, midBackground: .clear, paperBackground: .clear, chromeBackground: .clear, popoverBackground: .clear, subCellBackground: .clear, overlayBackground: UIColor(white: 1.0, alpha: 0.4), batchSelectionBackground: .lightBlue, referenceHighlightBackground: .clear, hintBackground: .clear, overlayText: .base20, searchFieldBackground: .lightSearchFieldBackground, keyboardBarSearchFieldBackground: .base80, primaryText: .base10, secondaryText: .base10, tertiaryText: .base20, disabledText: .base30, disabledLink: .lightBlue, chromeText: .base20, link: .accent10, accent: .green50, border: UIColor(white: 0, alpha: 0.15) , shadow: .base80, chromeShadow: .base80, cardShadow: .black, secondaryAction: .blue10, icon: nil, iconBackground: nil, destructive: .red50, error: .red50, warning: .yellow50, unselected: .base50, blurEffectStyle: .extraLight, blurEffectBackground: .clear)
@objc public let baseBackground: UIColor
@objc public let midBackground: UIColor
@objc public let subCellBackground: UIColor
@objc public let paperBackground: UIColor
@objc public let popoverBackground: UIColor
@objc public let chromeBackground: UIColor
@objc public let chromeShadow: UIColor
@objc public let overlayBackground: UIColor
@objc public let batchSelectionBackground: UIColor
@objc public let referenceHighlightBackground: UIColor
@objc public let hintBackground: UIColor
@objc public let overlayText: UIColor
@objc public let primaryText: UIColor
@objc public let secondaryText: UIColor
@objc public let tertiaryText: UIColor
@objc public let disabledText: UIColor
@objc public let disabledLink: UIColor
@objc public let chromeText: UIColor
@objc public let link: UIColor
@objc public let accent: UIColor
@objc public let secondaryAction: UIColor
@objc public let destructive: UIColor
@objc public let warning: UIColor
@objc public let error: UIColor
@objc public let unselected: UIColor
@objc public let border: UIColor
@objc public let shadow: UIColor
@objc public let cardShadow: UIColor
@objc public let icon: UIColor?
@objc public let iconBackground: UIColor?
@objc public let searchFieldBackground: UIColor
@objc public let keyboardBarSearchFieldBackground: UIColor
@objc public let linkToAccent: Gradient
@objc public let blurEffectStyle: UIBlurEffectStyle
@objc public let blurEffectBackground: UIColor
//Someday, when the app is all swift, make this class a struct.
init(baseBackground: UIColor, midBackground: UIColor, paperBackground: UIColor, chromeBackground: UIColor, popoverBackground: UIColor, subCellBackground: UIColor, overlayBackground: UIColor, batchSelectionBackground: UIColor, referenceHighlightBackground: UIColor, hintBackground: UIColor, overlayText: UIColor, searchFieldBackground: UIColor, keyboardBarSearchFieldBackground: UIColor, primaryText: UIColor, secondaryText: UIColor, tertiaryText: UIColor, disabledText: UIColor, disabledLink: UIColor, chromeText: UIColor, link: UIColor, accent: UIColor, border: UIColor, shadow: UIColor, chromeShadow: UIColor, cardShadow: UIColor, secondaryAction: UIColor, icon: UIColor?, iconBackground: UIColor?, destructive: UIColor, error: UIColor, warning: UIColor, unselected: UIColor, blurEffectStyle: UIBlurEffectStyle, blurEffectBackground: UIColor) {
self.baseBackground = baseBackground
self.midBackground = midBackground
self.subCellBackground = subCellBackground
self.paperBackground = paperBackground
self.popoverBackground = popoverBackground
self.chromeBackground = chromeBackground
self.chromeShadow = chromeShadow
self.cardShadow = cardShadow
self.overlayBackground = overlayBackground
self.batchSelectionBackground = batchSelectionBackground
self.hintBackground = hintBackground
self.referenceHighlightBackground = referenceHighlightBackground
self.overlayText = overlayText
self.searchFieldBackground = searchFieldBackground
self.keyboardBarSearchFieldBackground = keyboardBarSearchFieldBackground
self.primaryText = primaryText
self.secondaryText = secondaryText
self.tertiaryText = tertiaryText
self.disabledText = disabledText
self.disabledLink = disabledLink
self.chromeText = chromeText
self.link = link
self.accent = accent
self.border = border
self.shadow = shadow
self.icon = icon
self.iconBackground = iconBackground
self.linkToAccent = Gradient(startColor: link, endColor: accent)
self.error = error
self.warning = warning
self.destructive = destructive
self.secondaryAction = secondaryAction
self.unselected = unselected
self.blurEffectStyle = blurEffectStyle
self.blurEffectBackground = blurEffectBackground
}
}
@objc(WMFTheme)
public class Theme: NSObject {
@objc public static let standard = Theme.light
@objc public let colors: Colors
@objc public let isDark: Bool
@objc public var preferredStatusBarStyle: UIStatusBarStyle {
return isDark ? .lightContent : .default
}
@objc public var scrollIndicatorStyle: UIScrollViewIndicatorStyle {
return isDark ? .white : .black
}
@objc public var blurEffectStyle: UIBlurEffectStyle {
return isDark ? .dark : .light
}
@objc public var keyboardAppearance: UIKeyboardAppearance {
return isDark ? .dark : .light
}
@objc public lazy var navigationBarBackgroundImage: UIImage = {
return UIImage.wmf_image(from: colors.paperBackground)
}()
@objc public lazy var navigationBarShadowImage: UIImage = {
return #imageLiteral(resourceName: "transparent-pixel")
}()
static func roundedRectImage(with color: UIColor, cornerRadius: CGFloat, width: CGFloat? = nil, height: CGFloat? = nil) -> UIImage? {
let minDimension = 2 * cornerRadius + 1
let rect = CGRect(x: 0, y: 0, width: width ?? minDimension, height: height ?? minDimension)
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setFillColor(color.cgColor)
let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
path.fill()
let capInsets = UIEdgeInsetsMake(cornerRadius, cornerRadius, cornerRadius, cornerRadius)
let image = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: capInsets)
UIGraphicsEndImageContext()
return image
}
@objc public lazy var searchFieldBackgroundImage: UIImage? = {
return Theme.roundedRectImage(with: colors.searchFieldBackground, cornerRadius: 10, height: 36)
}()
@objc public lazy var navigationBarTitleTextAttributes: [NSAttributedStringKey: Any] = {
return [NSAttributedStringKey.foregroundColor: colors.chromeText]
}()
@objc public let imageOpacity: CGFloat
@objc public let name: String
@objc public let displayName: String
@objc public let multiSelectIndicatorImage: UIImage?
fileprivate static let lightMultiSelectIndicator = UIImage(named: "selected", in: Bundle.main, compatibleWith:nil)
fileprivate static let darkMultiSelectIndicator = UIImage(named: "selected-dark", in: Bundle.main, compatibleWith:nil)
@objc public static let light = Theme(colors: .light, imageOpacity: 1, multiSelectIndicatorImage: Theme.lightMultiSelectIndicator, isDark: false, name: "standard", displayName: WMFLocalizedString("theme-default-display-name", value: "Default", comment: "Default theme name presented to the user"))
@objc public static let sepia = Theme(colors: .sepia, imageOpacity: 1, multiSelectIndicatorImage: Theme.lightMultiSelectIndicator, isDark: false, name: "sepia", displayName: WMFLocalizedString("theme-sepia-display-name", value: "Sepia", comment: "Sepia theme name presented to the user"))
@objc public static let dark = Theme(colors: .dark, imageOpacity: 1, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "dark", displayName: WMFLocalizedString("theme-dark-display-name", value: "Dark", comment: "Dark theme name presented to the user"))
@objc public static let darkDimmed = Theme(colors: .dark, imageOpacity: 0.65, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "dark-dimmed", displayName: Theme.dark.displayName)
@objc public static let black = Theme(colors: .black, imageOpacity: 1, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "black", displayName: WMFLocalizedString("theme-black-display-name", value: "Black", comment: "Black theme name presented to the user"))
@objc public static let blackDimmed = Theme(colors: .black, imageOpacity: 0.65, multiSelectIndicatorImage: Theme.darkMultiSelectIndicator, isDark: true, name: "black-dimmed", displayName: Theme.black.displayName)
@objc public static let widget = Theme(colors: .widget, imageOpacity: 1, multiSelectIndicatorImage: nil, isDark: false, name: "", displayName: "")
init(colors: Colors, imageOpacity: CGFloat, multiSelectIndicatorImage: UIImage?, isDark: Bool, name: String, displayName: String) {
self.colors = colors
self.imageOpacity = imageOpacity
self.name = name
self.displayName = displayName
self.multiSelectIndicatorImage = multiSelectIndicatorImage
self.isDark = isDark
}
fileprivate static let themesByName = [Theme.light.name: Theme.light, Theme.dark.name: Theme.dark, Theme.sepia.name: Theme.sepia, Theme.darkDimmed.name: Theme.darkDimmed, Theme.black.name: Theme.black, Theme.blackDimmed.name: Theme.blackDimmed]
@objc(withName:)
public class func withName(_ name: String?) -> Theme? {
guard let name = name else {
return nil
}
return themesByName[name]
}
@objc public func withDimmingEnabled(_ isDimmingEnabled: Bool) -> Theme {
guard let baseName = name.components(separatedBy: "-").first else {
return self
}
let adjustedName = isDimmingEnabled ? "\(baseName)-dimmed" : baseName
return Theme.withName(adjustedName) ?? self
}
}
@objc(WMFThemeable)
public protocol Themeable : NSObjectProtocol {
@objc(applyTheme:)
func apply(theme: Theme) //this might be better as a var theme: Theme { get set } - common VC superclasses could check for viewIfLoaded and call an update method in the setter. This would elminate the need for the viewIfLoaded logic in every applyTheme:
}
| mit |
brokenhandsio/AWSwift | Sources/AWSwift/DynamoDb/DynamoDbTable.swift | 1 | 4091 | public struct DynamoDbTable {
// MARK: - Properties
// TOOD sort out access
let tableName: String
let partitionKey: String
let sortKey: String?
let connectionManager: ConnectionManager
// MARK: - Initialiser
/**
Initialiser for a table in DynamoDb. You can use the table object to perform all the actions you need
that involve tables, such as creation and deletion of tables, putting items, deleting items etc
- Parameters:
- tableName: The name of the table
- partitionKey: The name of the partition key
- sortKey: The name of the optional sort key
- connectionManager: The connectionManager to connect to DynamoDb
*/
public init(tableName: String, partitionKey: String, sortKey: String?, connectionManager: ConnectionManager) {
self.tableName = tableName
self.partitionKey = partitionKey
self.sortKey = sortKey
self.connectionManager = connectionManager
}
}
// MARK = DynamoDbAction
// TODO documentation
extension DynamoDbTable: DynamoDbItemAction {
public func putItem(item: [String : Any], condition: String, conditionAttributes: [String : [String : String]], completion: @escaping ((String?, AwsRequestErorr?) -> Void)) {
let request = [
"TableName": tableName,
"Item": item,
"ConditionExpression": condition,
"ExpressionAttributeValues": conditionAttributes
] as [String: Any]
connectionManager.request(request, method: .post, service: DynamoDbService.putItem) { (response, error) in
completion(response, error)
}
}
public func getItem(keyValues: DynamoDbTableKeyValues, completion: @escaping ((String?, AwsRequestErorr?) -> Void)) {
var key = [
partitionKey: [
"S": keyValues.partitionKeyValue
]
]
if let sortKey = sortKey {
guard let sortKeyValue = keyValues.sortKeyValue else {
fatalError("Table has sort key but no sort key specified")
}
key[sortKey] = ["S" :sortKeyValue]
}
let request = [
"TableName": tableName,
"Key": key
] as [String: Any]
connectionManager.request(request, method: .post, service: DynamoDbService.getItem) { (response, error) in
completion(response, error)
}
}
public func deleteItem(keyValue: DynamoDbTableKeyValues, conditionExpression: String?, returnValues: DynamoDbReturnValue?, completion: @escaping ((String?, AwsRequestErorr?) -> Void)) {
// Check valid return value
if let returnValues = returnValues {
switch returnValues {
case .none, .allOld: break
default:
// Invalid return type
completion(nil, AwsRequestErorr.failed(message: "Invalid return value for delete"))
}
}
var key = [
partitionKey: [
"S": keyValue.partitionKeyValue
]
]
if let sortKey = sortKey {
guard let sortKeyValue = keyValue.sortKeyValue else {
fatalError("Table has sort key but no sort key specified")
}
key[sortKey] = ["S" :sortKeyValue]
}
var request = [
"TableName": tableName,
"Key": key
] as [String: Any]
if let conditionExpression = conditionExpression {
request["ConditionExpression"] = conditionExpression
}
if let returnValues = returnValues {
request["ReturnValues"] = returnValues.rawValue
}
connectionManager.request(request, method: .post, service: DynamoDbService.deleteItem) { (resposne, error) in
completion(resposne, error)
}
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/01263-no-stacktrace.swift | 2 | 580 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class l: j{ k() -> ())
func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(p: (Any, Any) -> Any) -> Any in
func n<n : l,) {
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
func f BooleanType>(b: T) {
}
f( func b(b: X.Type) {
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
}
protocol e {
}
protocol i : d
| apache-2.0 |
VadimPavlov/Swifty | Sources/Swifty/ios/UIKit/UITextField.swift | 1 | 282 | //
// String.swift
// Created by Vadim Pavlov on 26.07.16.
import UIKit
public extension UITextField {
func setPlaceholderColor(color: UIColor) {
if let placeholder = self.placeholder {
self.attributedPlaceholder = placeholder.foregroundColorString(color: color)
}
}
}
| mit |
werner-freytag/DockTime | DockTime/DockTimeAppDelegate.swift | 1 | 6504 | // The MIT License
//
// Copyright 2012-2021 Werner Freytag
//
// 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 AppKit
@NSApplicationMain
class DockTimeAppDelegate: NSObject, NSApplicationDelegate {
private let defaultBundleIdentifier = "io.pecora.DockTime-ClockBundle-BigSur"
private let clockBundles = Bundle.paths(forResourcesOfType: "clockbundle", inDirectory: Bundle.main.builtInPlugInsPath!)
.compactMap { Bundle(path: $0) }
.sorted(by: { $0.bundleName! < $1.bundleName! })
.filter {
guard let principalClass = $0.principalClass else {
assertionFailure("Missing principalClass for bundle \(String(describing: $0.bundleIdentifier)).")
return false
}
guard let clockViewClass = principalClass as? NSView.Type else {
assertionFailure("\(String(describing: principalClass)) is not an NSView.")
return false
}
return true
}
private var updateInterval = UpdateInterval.second {
didSet {
lastRefreshDate = nil
}
}
private lazy var clockMenuItems: [NSMenuItem] = {
clockBundles.enumerated()
.map { index, bundle in
let keyEquivalent: String = {
switch index {
case 0 ..< 9: return String(index + 1)
case 9: return "0"
default: return ""
}
}()
let item = NSMenuItem(title: bundle.bundleName!, action: #selector(didSelectClockMenuItem(_:)), keyEquivalent: keyEquivalent)
item.target = self
item.state = bundle.bundleIdentifier == currentClockBundle?.bundleIdentifier ? .on : .off
return item
}
}()
private lazy var showSecondsMenuItem: NSMenuItem = {
let item = NSMenuItem(title: NSLocalizedString("Show seconds", comment: "Show seconds menu item title"), action: #selector(didSelectShowSecondsMenuItem(_:)), keyEquivalent: ",")
item.target = self
item.state = UserDefaults.shared.showSeconds ? .on : .off
return item
}()
private lazy var menu: NSMenu = {
let menu = NSMenu(title: NSLocalizedString("Model", comment: ""))
for item in clockMenuItems {
menu.addItem(item)
}
menu.addItem(.separator())
menu.addItem(showSecondsMenuItem)
return menu
}()
private var currentClockBundle: Bundle? {
didSet {
guard let clockBundle = currentClockBundle, let clockViewClass = clockBundle.principalClass as? NSView.Type else {
return assertionFailure()
}
NSLog("Loading \(clockViewClass) of bundle \(clockBundle.bundleIdentifier!)")
let updateIntervalString = clockBundle.object(forInfoDictionaryKey: "DTUpdateInterval") as? String ?? ""
updateInterval = UpdateInterval(updateIntervalString) ?? .second
dockTile.contentView = clockViewClass.init(frame: .zero)
}
}
private var refreshTimer: Timer!
private var lastRefreshDate: Date?
private let dockTile = NSApp.dockTile
func applicationWillFinishLaunching(_: Notification) {
currentClockBundle = clockBundles.first(where: { $0.bundleIdentifier == UserDefaults.standard.selectedClockBundle }) ??
clockBundles.first(where: { $0.bundleIdentifier == defaultBundleIdentifier }) ??
clockBundles.first!
refreshTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(refreshDockTile), userInfo: nil, repeats: true)
let menuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
menuItem.submenu = menu
NSApp.mainMenu?.addItem(menuItem)
}
func applicationDockMenu(_: NSApplication) -> NSMenu? {
return menu
}
@objc func didSelectClockMenuItem(_ menuItem: NSMenuItem!) {
guard let index = clockMenuItems.firstIndex(of: menuItem) else { return }
UserDefaults.standard.selectedClockBundle = clockBundles[index].bundleIdentifier
for item in clockMenuItems {
item.state = item == menuItem ? .on : .off
}
currentClockBundle = clockBundles[index]
dockTile.display()
}
@objc func didSelectShowSecondsMenuItem(_ menuItem: NSMenuItem!) {
let showSeconds = menuItem.state == .off
UserDefaults.shared.showSeconds = showSeconds
NSLog("Toggle Show Seconds: \(showSeconds)")
menuItem.state = showSeconds ? .on : .off
lastRefreshDate = nil
}
var requiresRefresh: Bool {
let date = Date()
defer {
lastRefreshDate = date
}
guard let lastRefreshDate = lastRefreshDate else { return true }
let calendar = Calendar.current
switch updateInterval {
case .minute:
return calendar.dateComponents([.hour, .minute], from: date) != calendar.dateComponents([.hour, .minute], from: lastRefreshDate)
case .second:
return calendar.dateComponents([.hour, .minute, .second], from: date) != calendar.dateComponents([.hour, .minute, .second], from: lastRefreshDate)
case .continual:
return true
}
}
@objc func refreshDockTile() {
guard requiresRefresh else { return }
dockTile.display()
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/27068-swift-conformancelookuptable-conformancelookuptable.swift | 4 | 263 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{
protocol A{
let:A
struct A
func d<T:T.e
| apache-2.0 |
sabensm/playgrounds | optionals.playground/Contents.swift | 1 | 1403 | //: Playground - noun: a place where people can play
import UIKit
//The Question Mark defines the variable as an optional -- it may or may not have a value
var lotteryWinnings: Int?
if lotteryWinnings != nil {
print(lotteryWinnings!)
}
lotteryWinnings = 1000
//This is the prefered method of handling the optionals. Anytime a variable has a quesion mark, we should use if let
if let winnings = lotteryWinnings {
print(winnings)
}
class Car {
var model: String?
}
//Multiple if/let statement
var vehicle: Car?
vehicle = Car ()
vehicle?.model = "Bronco"
if let v = vehicle, let m = v.model {
print(m)
}
//Another Example with an if/let along with a conditional
var cars: [Car]?
cars = [Car] ()
if let carArray = cars where carArray.count > 0 {
// Only execute if not nil and more than 0 elements
} else {
cars?.append(Car())
print(cars?.count)
}
//Implicitly Unwrapped Optional
class Person {
private var _age: Int!
var age: Int {
if _age == nil {
_age = 15
}
return _age
}
func setAge(newAge: Int) {
self._age = newAge
}
}
var jack = Person()
print(jack.age)
//Initializing properties without ? !
class Dog {
var species: String
init(someSpecies: String) {
self.species = someSpecies
}
}
var lab = Dog(someSpecies: "Black Lab")
print(lab.species)
| mit |
17AustinZ/Poker-Chip | ViewControllers/BOContainerViewController.swift | 1 | 1645 | //
// BOContainerViewController.swift
// ChipManager
//
// Created by Austin Zhang on 7/28/15.
// Copyright (c) 2015 Austin Zhang. All rights reserved.
//
import Foundation
import Bohr
class BOContainerViewController : UIViewController{
var betStructure : bettingStructure = .Default
var config : BOConfigureViewController?
enum bettingStructure {
case Default
case NoLimit
case FixedLimit
case PotLimit
case SpreadLimit
}
var startingChips : Int? = 0
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toGame" {
super.prepareForSegue(segue, sender: sender)
navigationController?.setNavigationBarHidden(false, animated: true)
var bettingVC : BettingViewController = segue.destinationViewController as! BettingViewController
bettingVC.players = [
Player(name: "P01", startChips: startingChips!),
Player(name: "P02", startChips: startingChips!),
Player(name: "P03", startChips: startingChips!),
Player(name: "P04", startChips: startingChips!),
Player(name: "P05", startChips: startingChips!),
Player(name: "P06", startChips: startingChips!),
Player(name: "P07", startChips: startingChips!),
Player(name: "P08", startChips: startingChips!)]
} else if segue.identifier == "configureEmbed"{
config = segue.destinationViewController as? BOConfigureViewController
}
}
} | mit |
mentrena/SyncKit | SyncKit/Classes/CoreData/CoreDataStack.swift | 1 | 3889 | //
// CoreDataStack.swift
// SyncKit
//
// Created by Manuel Entrena on 02/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import Foundation
import CoreData
/// Encapsulates a Core Data stack. This predates `NSPersistentContainer` and it's basically the same.
@objc public class CoreDataStack: NSObject {
@objc public private(set) var managedObjectContext: NSManagedObjectContext!
@objc public private(set) var persistentStoreCoordinator: NSPersistentStoreCoordinator!
@objc public private(set) var store: NSPersistentStore!
@objc public let storeType: String
@objc public let storeURL: URL?
@objc public let useDispatchImmediately: Bool
@objc public let model: NSManagedObjectModel
@objc public let concurrencyType: NSManagedObjectContextConcurrencyType
/// Create a new Core Data stack.
/// - Parameters:
/// - storeType: Store type, such as NSSQLiteStoreType.
/// - model: model to be used for the stack.
/// - storeURL: `URL` for the store location. Optional.
/// - concurrencyType: Default is `privateQueueConcurrencyType`
/// - dispatchImmediately: Used for testing.
@objc public init(storeType: String,
model: NSManagedObjectModel,
storeURL: URL?,
concurrencyType: NSManagedObjectContextConcurrencyType = .privateQueueConcurrencyType,
dispatchImmediately: Bool = false) {
self.storeType = storeType
self.storeURL = storeURL
self.useDispatchImmediately = dispatchImmediately
self.model = model
self.concurrencyType = concurrencyType
super.init()
initializeStack()
loadStore()
}
/// Winds down the stack and deletes the store.
@objc public func deleteStore() {
managedObjectContext.performAndWait {
self.managedObjectContext.reset()
}
if let storeURL = storeURL {
try? persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: storeType, options: nil)
}
managedObjectContext = nil
store = nil
}
private func ensureStoreDirectoryExists() {
guard let storeURL = storeURL else { return }
let storeDirectory = storeURL.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: storeDirectory.path) == false {
try! FileManager.default.createDirectory(at: storeDirectory,
withIntermediateDirectories: true,
attributes: nil)
}
}
private func initializeStack() {
ensureStoreDirectoryExists()
persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
if useDispatchImmediately {
managedObjectContext = QSManagedObjectContext(concurrencyType: concurrencyType)
} else {
managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType)
}
managedObjectContext.performAndWait {
self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
self.managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
}
}
private func loadStore() {
guard store == nil else { return }
let options = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
store = try! persistentStoreCoordinator.addPersistentStore(ofType: storeType,
configurationName: nil,
at: storeURL,
options: options)
}
}
| mit |
nanthi1990/SwiftCharts | Examples/Examples/TrackerExample.swift | 2 | 3054 | //
// TrackerExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class TrackerExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints = [(2, 2), (4, 4), (7, 1), (8, 11), (12, 3)].map{ChartPoint(x: ChartAxisValueDouble($0.0, labelSettings: labelSettings), y: ChartAxisValueDouble($0.1))}
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 1, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let trackerLayerSettings = ChartPointsLineTrackerLayerSettings(thumbSize: Env.iPad ? 30 : 20, thumbCornerRadius: Env.iPad ? 16 : 10, thumbBorderWidth: Env.iPad ? 4 : 2, infoViewFont: ExamplesDefaults.fontWithSize(Env.iPad ? 26 : 16), infoViewSize: CGSizeMake(Env.iPad ? 400 : 160, Env.iPad ? 70 : 40), infoViewCornerRadius: Env.iPad ? 30 : 15)
let chartPointsTrackerLayer = ChartPointsLineTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, lineColor: UIColor.blackColor(), animDuration: 1, animDelay: 2, settings: trackerLayerSettings)
var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer,
chartPointsTrackerLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 |
tensorflow/swift-models | Support/FileManagement.swift | 1 | 6295 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// Creates a directory at a path, if missing. If the directory exists, this does nothing.
///
/// - Parameters:
/// - path: The path of the desired directory.
public func createDirectoryIfMissing(at path: String) throws {
guard !FileManager.default.fileExists(atPath: path) else { return }
try FileManager.default.createDirectory(
atPath: path,
withIntermediateDirectories: true,
attributes: nil)
}
/// Downloads a remote file and places it either within a target directory or at a target file name.
/// If `destination` has been explicitly specified as a directory (setting `isDirectory` to true
/// when appending the last path component), the file retains its original name and is placed within
/// this directory. If `destination` isn't marked in this fashion, the file is saved as a file named
/// after `destination` and its last path component. If the encompassing directory is missing in
/// either case, it is created.
///
/// - Parameters:
/// - source: The remote URL of the file to download.
/// - destination: Either the local directory to place the file in, or the local filename.
public func download(from source: URL, to destination: URL) throws {
let destinationFile: String
if destination.hasDirectoryPath {
try createDirectoryIfMissing(at: destination.path)
let fileName = source.lastPathComponent
destinationFile = destination.appendingPathComponent(fileName).path
} else {
try createDirectoryIfMissing(at: destination.deletingLastPathComponent().path)
destinationFile = destination.path
}
let downloadedFile = try Data(contentsOf: source)
try downloadedFile.write(to: URL(fileURLWithPath: destinationFile))
}
/// Collect all file URLs under a folder `url`, potentially recursing through all subfolders.
/// Optionally filters some extension (only jpeg or txt files for instance).
///
/// - Parameters:
/// - url: The folder to explore.
/// - recurse: Will explore all subfolders if set to `true`.
/// - extensions: Only keeps URLs with extensions in that array if it's provided
public func collectURLs(
under directory: URL, recurse: Bool = false, filtering extensions: [String]? = nil
) -> [URL] {
var files: [URL] = []
do {
let dirContents = try FileManager.default.contentsOfDirectory(
at: directory, includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles])
for content in dirContents {
if content.hasDirectoryPath && recurse {
files += collectURLs(under: content, recurse: recurse, filtering: extensions)
} else if content.isFileURL
&& (extensions == nil
|| extensions!.contains(content.pathExtension.lowercased()))
{
files.append(content)
}
}
} catch {
fatalError("Could not explore this folder: \(error)")
}
return files
}
/// Extracts a compressed file to a specified directory. This keys off of either the explicit
/// file extension or one determined from the archive to determine which unarchiving method to use.
/// This optionally deletes the original archive when done.
///
/// - Parameters:
/// - archive: The source archive file, assumed to be on the local filesystem.
/// - localStorageDirectory: A directory that the archive will be unpacked into.
/// - fileExtension: An optional explicitly-specified file extension for the archive, determining
/// how it is unpacked.
/// - deleteArchiveWhenDone: Whether or not the original archive is deleted when the extraction
/// process has been completed. This defaults to false.
public func extractArchive(
at archive: URL, to localStorageDirectory: URL, fileExtension: String? = nil,
deleteArchiveWhenDone: Bool = false
) {
let archivePath = archive.path
#if os(macOS)
var binaryLocation = "/usr/bin/"
#else
var binaryLocation = "/bin/"
#endif
let toolName: String
let arguments: [String]
let adjustedPathExtension: String
if archive.path.hasSuffix(".tar.gz") {
adjustedPathExtension = "tar.gz"
} else {
adjustedPathExtension = archive.pathExtension
}
switch fileExtension ?? adjustedPathExtension {
case "gz":
toolName = "gunzip"
arguments = [archivePath]
case "tar":
toolName = "tar"
arguments = ["xf", archivePath, "-C", localStorageDirectory.path]
case "tar.gz", "tgz":
toolName = "tar"
arguments = ["xzf", archivePath, "-C", localStorageDirectory.path]
case "zip":
binaryLocation = "/usr/bin/"
toolName = "unzip"
arguments = ["-qq", archivePath, "-d", localStorageDirectory.path]
default:
printError(
"Unable to find archiver for extension \(fileExtension ?? adjustedPathExtension).")
exit(-1)
}
let toolLocation = "\(binaryLocation)\(toolName)"
let task = Process()
task.executableURL = URL(fileURLWithPath: toolLocation)
task.arguments = arguments
do {
try task.run()
task.waitUntilExit()
} catch {
printError("Failed to extract \(archivePath) with error: \(error)")
exit(-1)
}
if FileManager.default.fileExists(atPath: archivePath) && deleteArchiveWhenDone {
do {
try FileManager.default.removeItem(atPath: archivePath)
} catch {
printError("Could not remove archive, error: \(error)")
exit(-1)
}
}
}
| apache-2.0 |
charmaex/poke-deck | PokeDeck/NextEvoImgView.swift | 1 | 393 | //
// NextEvoImgView.swift
// PokeDeck
//
// Created by Jan Dammshäuser on 01.03.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import Foundation
import UIKit
class NextEvoImgView: TappableImage {
override func tapped() {
guard let delegate = delegate as? DetailVC else {
return
}
delegate.evoPokemon()
}
}
| gpl-3.0 |
broccolii/Demos | DEMO02-LoginAnimation/LoginAnimation/SwiftClass/LoginAnimationButton.swift | 1 | 9553 | //
// LoginAnimationButton.swift
// LoginAnimation
//
// Created by Broccoli on 16/6/28.
// Copyright © 2016年 youzan. All rights reserved.
//
import UIKit
class LoginAnimationButton: UIButton {
typealias AnimationCompletion = Void -> Void
var failedBackgroundColor = UIColor.redColor()
private var shrinkDuration: CFTimeInterval = 0.1
private var expandDuration: CFTimeInterval = 0.3
private var shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
private var expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05)
private var spinerLayer: SpinerLayer!
private var defaultBackgroundColor = UIColor(red: 4/255.0, green: 186/255.0, blue: 215/255.0, alpha: 1)
private var animationCompletion: AnimationCompletion?
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
setupTargetAction()
}
func failedAnimation(WithCompletion completion: AnimationCompletion) {
animationCompletion = completion
let shrinkAnimation = CABasicAnimation(keyPath: "bounds.size.width")
shrinkAnimation.fromValue = CGRectGetHeight(bounds)
shrinkAnimation.toValue = CGRectGetWidth(bounds)
shrinkAnimation.duration = shrinkDuration
shrinkAnimation.timingFunction = shrinkCurve
shrinkAnimation.fillMode = kCAFillModeForwards
shrinkAnimation.removedOnCompletion = false
defaultBackgroundColor = backgroundColor!
let backgroundColorAniamtion = CABasicAnimation(keyPath: "backgroundColor")
backgroundColorAniamtion.toValue = failedBackgroundColor.CGColor
backgroundColorAniamtion.duration = shrinkDuration
backgroundColorAniamtion.timingFunction = shrinkCurve
backgroundColorAniamtion.fillMode = kCAFillModeForwards
backgroundColorAniamtion.removedOnCompletion = false
let keyframeAnimation = CAKeyframeAnimation(keyPath: "position")
let originPoint = layer.position
keyframeAnimation.values = [NSValue(CGPoint: CGPoint(x: originPoint.x, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x - 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x + 10, y: originPoint.y)),
NSValue(CGPoint: CGPoint(x: originPoint.x, y: originPoint.y))]
keyframeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
keyframeAnimation.duration = 0.5
keyframeAnimation.delegate = self
layer.position = originPoint
layer.addAnimation(shrinkAnimation, forKey: shrinkAnimation.keyPath)
layer.addAnimation(backgroundColorAniamtion, forKey: backgroundColorAniamtion.keyPath)
layer.addAnimation(keyframeAnimation, forKey: keyframeAnimation.keyPath)
spinerLayer.stopAnimation()
userInteractionEnabled = true
}
func succeedAnimation(WithCompletion completion: AnimationCompletion) {
animationCompletion = completion
let expandAnimation = CABasicAnimation(keyPath: "transform.scale")
expandAnimation.fromValue = 1.0
expandAnimation.toValue = 33.0
expandAnimation.timingFunction = expandCurve
expandAnimation.duration = expandDuration
expandAnimation.delegate = self
expandAnimation.fillMode = kCAFillModeForwards
expandAnimation.removedOnCompletion = false
layer.addAnimation(expandAnimation, forKey: expandAnimation.keyPath)
spinerLayer.stopAnimation()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - animation delegate
extension LoginAnimationButton {
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let basicAnimation = anim as? CABasicAnimation where
basicAnimation.keyPath == "transform.scale" {
userInteractionEnabled = true
if animationCompletion != nil {
animationCompletion!()
}
// NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(didStopAnimation), userInfo: nil, repeats: true)
}
}
}
private extension LoginAnimationButton {
func setupLayer() {
spinerLayer = SpinerLayer(frame: frame)
layer.addSublayer(spinerLayer)
layer.cornerRadius = CGRectGetHeight(bounds) / 2
clipsToBounds = true
}
func setupTargetAction() {
addTarget(self, action: #selector(scaleToSmall), forControlEvents: [.TouchDown, .TouchDragEnter])
addTarget(self, action: #selector(scaleAnimation), forControlEvents: .TouchUpInside)
addTarget(self, action: #selector(scaleToDefault), forControlEvents: .TouchDragExit)
}
@objc func scaleToSmall() {
transform = CGAffineTransformMakeScale(1, 1)
layer.backgroundColor = self.backgroundColor?.CGColor
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .LayoutSubviews, animations: {
self.transform = CGAffineTransformMakeScale(0.9, 0.9)
}, completion: nil)
}
@objc func scaleAnimation() {
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .LayoutSubviews, animations: {
self.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
beginAniamtion()
}
@objc func scaleToDefault() {
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.4,
options: .LayoutSubviews,
animations: {
self.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
}
@objc func didStopAnimation() {
layer.removeAllAnimations()
}
func beginAniamtion() {
// if CGColorEqualToColor(layer.backgroundColor, failedBackgroundColor.CGColor) {
revertBackgroundColor()
// }
layer.addSublayer(spinerLayer)
let shrinkAnimation = CABasicAnimation(keyPath: "bounds.size.width")
shrinkAnimation.fromValue = CGRectGetWidth(bounds)
shrinkAnimation.toValue = CGRectGetHeight(bounds)
shrinkAnimation.duration = shrinkDuration
shrinkAnimation.timingFunction = shrinkCurve
shrinkAnimation.fillMode = kCAFillModeForwards
shrinkAnimation.removedOnCompletion = false
layer.addAnimation(shrinkAnimation, forKey: shrinkAnimation.keyPath)
spinerLayer.beginAnimation()
userInteractionEnabled = false
}
func revertBackgroundColor() {
let backgroundColorAniamtion = CABasicAnimation(keyPath: "backgroundColor")
backgroundColorAniamtion.toValue = defaultBackgroundColor.CGColor
backgroundColorAniamtion.duration = shrinkDuration
backgroundColorAniamtion.timingFunction = shrinkCurve
backgroundColorAniamtion.fillMode = kCAFillModeForwards
backgroundColorAniamtion.removedOnCompletion = false
layer.addAnimation(backgroundColorAniamtion, forKey: "revertBackgroundColor")
}
}
class SpinerLayer: CAShapeLayer {
required init(frame: CGRect) {
super.init()
let radius = CGRectGetHeight(frame) / 4
self.frame = CGRect(x: 0, y: 0, width: CGRectGetHeight(frame), height: CGRectGetHeight(frame))
let center = CGPoint(x: CGRectGetHeight(frame) / 2, y: CGRectGetMidY(bounds))
let startAngle = CGFloat(-M_PI_2)
let endAngle = CGFloat(M_PI * 2 - M_PI_2)
let clockwise = true
path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise).CGPath
fillColor = nil
strokeColor = UIColor.whiteColor().CGColor
lineWidth = 1
strokeEnd = 0.4
hidden = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func beginAnimation() {
hidden = false
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.fromValue = 0
rotateAnimation.toValue = M_PI * 2
rotateAnimation.duration = 0.4
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotateAnimation.repeatCount = HUGE
rotateAnimation.fillMode = kCAFillModeForwards
rotateAnimation.removedOnCompletion = false
addAnimation(rotateAnimation, forKey: rotateAnimation.keyPath)
}
func stopAnimation() {
hidden = true
removeAllAnimations()
}
}
| mit |
thinkaboutiter/Transitions | SideTransitions/SideTransitions/source/Extensions/UIColor+Extensions.swift | 1 | 609 | //
// UIColor+Extensions.swift
// SideTransitions
//
// Created by Boyan Yankov on 2020-W15-11-Apr-Sat.
// Copyright © 2020 boyankov@yahoo.com. All rights reserved.
//
import UIKit
extension UIColor {
enum AppColor {
static var dimmingViewBackgroundColor: UIColor {
var result: UIColor = UIColor.black.withAlphaComponent(0.5)
if #available(iOS 13.0, *),
(UITraitCollection.current.userInterfaceStyle == .dark)
{
result = UIColor.white.withAlphaComponent(0.5)
}
return result
}
}
}
| mit |
StanDimitroff/SDDropdown | Example/Tests/Tests.swift | 1 | 1160 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SDDropdown
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit |
Dibel/androidtool-mac | AndroidTool/Util.swift | 1 | 4378 | //
// Util.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/22/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Foundation
import AppKit
class Util {
var deviceWidth:CGFloat = 373
var deviceHeight:CGFloat = 127
// view is self.view
func changeWindowSize(window:NSWindow, view:NSView, addHeight:CGFloat=0, addWidth:CGFloat=0) {
var frame = window.frame
frame.size = CGSizeMake(frame.size.width+addWidth, frame.size.height+addHeight)
frame.origin.y -= addHeight
window.setFrame(frame, display: true, animate: true)
view.frame.size.height += addHeight
view.frame.origin.y -= addHeight
}
// func changeWindowHeight(window:NSWindow, view:NSView, newHeight:CGFloat=0) {
// var frame = window.frame
// frame.size = CGSizeMake(frame.size.width, newHeight)
//// frame.origin.y -= newHeight
// window.setFrame(frame, display: true, animate: true)
// view.frame.size.height += newHeight
// view.frame.origin.y -= newHeight
// }
func changeWindowHeight(window:NSWindow, view:NSView, newHeight:CGFloat=0) {
var frame = window.frame
frame.origin.y += frame.size.height; // origin.y is top Y coordinate now
frame.origin.y -= newHeight // new Y coordinate for the origin
frame.size.height = newHeight
frame.size = CGSizeMake(frame.size.width, newHeight)
window.setFrame(frame, display: true, animate: true)
}
func showNotification(title:String, moreInfo:String, sound:Bool=true) -> Void {
let unc = NSUserNotificationCenter.defaultUserNotificationCenter()
let notification = NSUserNotification()
notification.title = title
notification.informativeText = moreInfo
if sound == true {
notification.soundName = NSUserNotificationDefaultSoundName
}
unc.deliverNotification(notification)
}
func getSupportFolderScriptPath() -> String {
let fileM = NSFileManager.defaultManager()
let supportFolder:String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let folder = "\(supportFolder)/AndroidTool"
let scriptFolder = "\(folder)/UserScripts"
if !fileM.fileExistsAtPath(folder) {
do {
try fileM.createDirectoryAtPath(folder, withIntermediateDirectories: false, attributes: nil)
} catch _ {
}
do {
try fileM.createDirectoryAtPath(scriptFolder, withIntermediateDirectories: false, attributes: nil)
} catch _ {
}
// copy files from UserScriptsInception to this new folder - TODO: Take all, not just bugreport
let inceptionScript = NSBundle.mainBundle().pathForResource("Take Bugreport", ofType: "sh")
do {
try fileM.copyItemAtPath(inceptionScript!, toPath: "\(scriptFolder)/Take Bugreport.sh")
} catch _ {
}
}
return scriptFolder
}
func revealScriptsFolder(){
let folder = getSupportFolderScriptPath()
NSWorkspace.sharedWorkspace().openFile(folder)
}
func getFilesInScriptFolder(folder:String) -> [String]? {
let fileM = NSFileManager.defaultManager()
var files = [String]()
let someFiles = fileM.enumeratorAtPath(folder)
while let file = someFiles?.nextObject() as? String {
if file != ".DS_Store" {
files.append(file)
}
}
return files
}
func isMavericks() -> Bool {
if #available(OSX 10.10, *) {
return NSProcessInfo.processInfo().operatingSystemVersion.minorVersion != 10 ? true : false
} else {
// Fallback on earlier versions
return false
}
}
func restartRefreshingDeviceList(){
NSNotificationCenter.defaultCenter().postNotificationName("unSuspendAdb", object: self, userInfo:nil)
}
func stopRefreshingDeviceList(){
NSNotificationCenter.defaultCenter().postNotificationName("suspendAdb", object: self, userInfo:nil)
}
}
| apache-2.0 |
karavakis/simply_counted | File.swift | 1 | 10016 | ////
//// ClientViewController.swift
//// simply_counted
////
//// Created by Jennifer Karavakis on 8/19/16.
//// Copyright © 2017 Jennifer Karavakis. All rights reserved.
////
//
//import UIKit
//import LocalAuthentication
//
//class ClientViewController: UIViewController, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,
//UIPickerViewDataSource, UIPickerViewDelegate {
// @IBOutlet weak var clientNameLabel: UILabel!
// @IBOutlet weak var passesLabel: UILabel!
// @IBOutlet weak var checkInDatePicker: UIDatePicker!
// @IBOutlet weak var checkInButton: UIButton!
// @IBOutlet weak var imageView: UIImageView!
// @IBOutlet weak var passTextField: UITextField!
//
// // Hideable
// @IBOutlet weak var unlockMoreOptionsLabel: UIButton!
// @IBOutlet weak var addClassPassButton: UIButton!
// @IBOutlet weak var removeClassPathButton: UIButton!
// @IBOutlet weak var addClassPassesButtons: UISegmentedControl!
// @IBOutlet weak var deleteUserButton: UIButton!
//
// var client : Client? = nil
// var allowNegative = false
// var ifAddClicked = true
//
// override func viewDidLoad() {
// super.viewDidLoad()
// // Do any additional setup after loading the view, typically from a nib.
// toggleMoreOptions()
// populateClientInfo()
// setupDatePicker()
// setupPickerView()
// }
//
// override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// self.view.endEditing(true)
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// /*********************/
// /* Setup Date Picker */
// /*********************/
// func setupDatePicker() {
// let today = NSDate()
// checkInDatePicker.setDate(today, animated: true)
// checkInDatePicker.maximumDate = today
// }
//
// /************************/
// /* Populate Client Info */
// /************************/
// func populateClientInfo() {
// if let client : Client = client {
// clientNameLabel.text = client.name
// passesLabel.text = "Passes Remaining: " + String(client.passes)
// }
// }
//
// /*********************/
// /* Update Class Pass */
// /*********************/
// func setupPickerView() {
// let pickerView = UIPickerView()
// pickerView.delegate = self
// passTextField.inputView = pickerView
//
// let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
// let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(ClientViewController.donePressed))
// let pickerToolbar = UIToolbar(frame: CGRectMake(0, self.view.frame.size.height/6, self.view.frame.size.width, 40.0))
// pickerToolbar.setItems([flexSpace, doneButton], animated: true)
// passTextField.inputAccessoryView = pickerToolbar
//
// passTextField.text = "1"
// }
//
// func donePressed() {
// passTextField.resignFirstResponder()
// if let passes = passTextField.text {
// if let passNumber = Int(passes) {
// addPassActivity(passNumber)
// }
// }
// }
//
// func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
// return 1
// }
//
// func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// return 99
// }
//
// func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
// return String(row + 1)
// }
//
// func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// passTextField.text = String(row + 1)
// }
//
// func addPassActivity(passes : Int) {
// if let client = self.client {
// let changedPasses = ifAddClicked ? passes : passes * -1
// client.addPasses(changedPasses)
// populateClientInfo()
//
// let addString = "The " + String(changedPasses) + " class pass was added successfully."
// let wasWere = changedPasses == -1 ? " was" : "es were"
// let removeString = String(changedPasses * -1) + " class pass" + wasWere + " removed successfully."
// let message = ifAddClicked ? addString : removeString
//
//
// let passAddedAlert = UIAlertController(title: "Pass Added", message: message, preferredStyle: UIAlertControllerStyle.Alert)
// passAddedAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
// }))
//
// presentViewController(passAddedAlert, animated: true, completion: nil)
// }
// }
//
// func updateClassPath() {
// var changedPasses = 0
// switch addClassPassesButtons.selectedSegmentIndex {
// case 0:
// changedPasses = 1
// case 1:
// changedPasses = 12
// case 2:
// changedPasses = 20
// case 3:
// changedPasses = 30
// default:
// changedPasses = 0
// break;
// }
// if(changedPasses == 0) {
// passTextField.becomeFirstResponder()
// }
// else {
// addPassActivity(changedPasses)
// }
// }
//
// @IBAction func addClassPass(sender: AnyObject) {
// ifAddClicked = true
// updateClassPath()
// }
//
// @IBAction func removeClassPath(sender: AnyObject) {
// ifAddClicked = false
// updateClassPath()
// }
//
//
// /*********************/
// /* Authenticate User */
// /*********************/
//
// @IBAction func unlockOptions(sender: AnyObject) {
// let context = LAContext()
//
// context.evaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason: "Please authenticate to proceed.") { [weak self] (success, error) in
//
// guard success else {
// dispatch_async(dispatch_get_main_queue()) {
// // show something here to block the user from continuing
// }
//
// return
// }
//
// dispatch_async(dispatch_get_main_queue()) {
// // do something here to continue loading your app, e.g. call a delegate method
// self!.toggleMoreOptions()
// }
// }
// }
//
// func toggleMoreOptions() {
// addClassPassButton.hidden = !addClassPassButton.hidden
// removeClassPathButton.hidden = !removeClassPathButton.hidden
// addClassPassesButtons.hidden = !addClassPassesButtons.hidden
// unlockMoreOptionsLabel.hidden = !addClassPassesButtons.hidden
// deleteUserButton.hidden = !unlockMoreOptionsLabel.hidden
// allowNegative = !addClassPassesButtons.hidden
// }
//
//
// /*******************/
// /* Load Table View */
// /*******************/
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return 1
// }
//
// func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// if let client : Client = client {
// return client.activities.count
// }
// return 0
// }
//
// func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> SimpleLabelTableViewCell {
// var cell : SimpleLabelTableViewCell
// cell = tableView.dequeueReusableCellWithIdentifier("CheckInCell") as! SimpleLabelTableViewCell
//
// if let client : Client = client {
// let dateFormatter = NSDateFormatter()
// dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
// dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
// cell.label.text = dateFormatter.stringFromDate(client.activities[indexPath.row].date)
// }
//
// return cell
// }
//
// func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// return true
// }
//
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if (segue.identifier == "CheckInClicked") {
// if let client = client {
// if (client.passes <= 0 && !allowNegative) {
// let noPassesAlert = UIAlertController(title: "Error", message: "Please load passes before checking in.", preferredStyle: UIAlertControllerStyle.Alert)
// noPassesAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
// }))
//
// presentViewController(noPassesAlert, animated: true, completion: nil)
// }
// else {
// client.checkIn(checkInDatePicker.date)
// }
// }
// }
// if (segue.identifier == "DeleteClicked") {
// if let client = client {
// let deleteAlert = UIAlertController(title: "Warning", message: "You are about to delete this user. This action cannot be undone.", preferredStyle: UIAlertControllerStyle.Alert)
// deleteAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
// func deleteSuccess() {
// segue.perform()
// }
// client.deleteClient(deleteSuccess)
// }))
// deleteAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
// //Do nothing
// }))
//
// presentViewController(deleteAlert, animated: true, completion: nil)
// }
// }
// }
//}
//
| apache-2.0 |
ohwutup/ReactiveCocoa | ReactiveCocoaTests/UIKit/UIButtonSpec.swift | 1 | 1617 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import UIKit
import enum Result.NoError
class UIButtonSpec: QuickSpec {
override func spec() {
var button: UIButton!
weak var _button: UIButton?
beforeEach {
button = UIButton(frame: .zero)
_button = button
}
afterEach {
button = nil
expect(_button).to(beNil())
}
it("should accept changes from bindings to its titles under different states") {
let firstTitle = "First title"
let secondTitle = "Second title"
let (pipeSignal, observer) = Signal<String, NoError>.pipe()
button.reactive.title <~ SignalProducer(pipeSignal)
button.setTitle("", for: .selected)
button.setTitle("", for: .highlighted)
observer.send(value: firstTitle)
expect(button.title(for: UIControlState())) == firstTitle
expect(button.title(for: .highlighted)) == ""
expect(button.title(for: .selected)) == ""
observer.send(value: secondTitle)
expect(button.title(for: UIControlState())) == secondTitle
expect(button.title(for: .highlighted)) == ""
expect(button.title(for: .selected)) == ""
}
it("should execute the `pressed` action upon receiving a `touchUpInside` action message.") {
button.isEnabled = true
button.isUserInteractionEnabled = true
let pressed = MutableProperty(false)
let action = Action<(), Bool, NoError> { _ in
SignalProducer(value: true)
}
pressed <~ SignalProducer(action.values)
button.reactive.pressed = CocoaAction(action)
expect(pressed.value) == false
button.sendActions(for: .touchUpInside)
expect(pressed.value) == true
}
}
}
| mit |
scottrhoyt/Cider | Tests/CiderTests/AlbumTests.swift | 1 | 5230 | //
// AlbumTests.swift
// CiderTests
//
// Created by Scott Hoyt on 8/1/17.
// Copyright © 2017 Scott Hoyt. All rights reserved.
//
import XCTest
@testable import Cider
class AlbumTests: XCTestCase {
func testAlbumFromSearch() throws {
let search = try fixture(ResponseRoot<SearchResults>.self, name: "search")
let album = search.results!.albums!.data![0]
XCTAssertEqual(album.id, "900721190")
XCTAssertEqual(album.type, .albums)
XCTAssertEqual(album.href, "/v1/catalog/us/albums/900721190")
XCTAssertNil(album.relationships)
let attributes = album.attributes!
XCTAssertEqual(attributes.artistName, "James Brown")
XCTAssertEqual(attributes.name, "20 All-Time Greatest Hits!")
XCTAssertEqual(attributes.copyright, "℗ 1991 Universal Records, a Division of UMG Recordings, Inc.")
XCTAssertEqual(attributes.genreNames, ["Soul", "Music", "R&B/Soul", "Funk"])
XCTAssertEqual(attributes.isComplete, true)
XCTAssertEqual(attributes.isSingle, false)
XCTAssertEqual(attributes.releaseDate, "1991-10-22")
XCTAssertEqual(attributes.trackCount, 20)
XCTAssertEqual(attributes.url, URL(string: "https://itunes.apple.com/us/album/20-all-time-greatest-hits/id900721190")!)
XCTAssertEqual(attributes.artwork.bgColor, "ffffff")
XCTAssertEqual(attributes.artwork.height, 1400)
XCTAssertEqual(attributes.artwork.textColor1, "0a0a09")
XCTAssertEqual(attributes.artwork.textColor2, "2a240f")
XCTAssertEqual(attributes.artwork.textColor3, "3b3b3a")
XCTAssertEqual(attributes.artwork.textColor4, "544f3f")
XCTAssertEqual(attributes.artwork.url, "https://example.mzstatic.com/image/thumb/Music4/v4/76/85/e5/7685e5c8-9346-88db-95ff-af87bf84151b/source/{w}x{h}bb.jpg")
XCTAssertEqual(attributes.artwork.width, 1400)
XCTAssertEqual(attributes.playParams?.id, "900721190")
XCTAssertEqual(attributes.playParams?.kind, "album")
XCTAssertNil(attributes.editorialNotes)
}
func testAlbumFromFetch() throws {
let fetch = try fixture(ResponseRoot<Album>.self, name: "album")
let album = fetch.data![0]
XCTAssertEqual(album.id, "310730204")
XCTAssertEqual(album.type, .albums)
XCTAssertEqual(album.href, "/v1/catalog/us/albums/310730204")
let attributes = album.attributes!
XCTAssertEqual(attributes.artistName, "Bruce Springsteen")
XCTAssertEqual(attributes.name, "Born to Run")
XCTAssertEqual(attributes.copyright, "℗ 1975 Bruce Springsteen")
XCTAssertEqual(attributes.genreNames, [
"Rock",
"Music",
"Arena Rock",
"Rock & Roll",
"Pop",
"Pop/Rock"
])
XCTAssertEqual(attributes.isComplete, true)
XCTAssertEqual(attributes.isSingle, false)
XCTAssertEqual(attributes.releaseDate, "1975-08-25")
XCTAssertEqual(attributes.trackCount, 8)
XCTAssertEqual(attributes.url, URL(string: "https://itunes.apple.com/us/album/born-to-run/id310730204")!)
XCTAssertEqual(attributes.artwork.bgColor, "ffffff")
XCTAssertEqual(attributes.artwork.height, 1500)
XCTAssertEqual(attributes.artwork.textColor1, "0c0b09")
XCTAssertEqual(attributes.artwork.textColor2, "2a2724")
XCTAssertEqual(attributes.artwork.textColor3, "3d3c3a")
XCTAssertEqual(attributes.artwork.textColor4, "555250")
XCTAssertEqual(attributes.artwork.url, "https://example.mzstatic.com/image/thumb/Music3/v4/2d/02/4a/2d024aaa-4547-ca71-7ba1-b8f5e1d98256/source/{w}x{h}bb.jpg")
XCTAssertEqual(attributes.artwork.width, 1500)
XCTAssertEqual(attributes.playParams?.id, "310730204")
XCTAssertEqual(attributes.playParams?.kind, "album")
XCTAssertEqual(attributes.editorialNotes?.standard, "Springsteen's third album was the one that broke it all open for him, planting his tales of Jersey girls, cars, and nights spent sleeping on the beach firmly in the Top Five. He shot for an unholy hybrid of Orbison, Dylan and Spector — and actually reached it. \"Come take my hand,\" he invited in the opening lines. \"We're ridin' out tonight to case the Promised Land.\" Soon after this album, he'd discover the limits of such dreams, but here, it's a wide-open road: Even the tales of petty crime (\"Meeting Across the River\") and teen-gang violence (\"Jungleland\") are invested with all the wit and charm you can handle. Bruce's catalog is filled with one-of-a-kind albums from <i>The Wild, The Innocent and the E Street Shuffle</i> to <i>The Ghost of Tom Joad</i>. Forty years on, <i>Born to Run</i> still sits near the very top of that stack.")
XCTAssertEqual(attributes.editorialNotes?.short, "Springsteen's third album was the one that broke it all open for him.")
}
}
#if os(Linux)
extension AlbumTests {
static var allTests: [(String, (AlbumTests) -> () throws -> Void)] {
return [
("testAlbumFromSearch", testAlbumFromSearch),
("testAlbumFromFetch", testAlbumFromFetch),
]
}
}
#endif
| mit |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/session/UserDataChangeInfo.swift | 3 | 172 | //
// UserDataChangeInfo.swift
// EmbyApiClient
//
import Foundation
public struct UserDataChangeInfo {
let userId: String
let userDataList: [UserItemDataDto]
} | mit |
Finb/V2ex-Swift | Model/Moya/Observable+Extension.swift | 1 | 7297 | //
// Observable+Extension.swift
// V2ex-Swift
//
// Created by huangfeng on 2018/6/11.
// Copyright © 2018 Fin. All rights reserved.
//
import UIKit
import RxSwift
import ObjectMapper
import SwiftyJSON
import Moya
import Ji
public enum ApiError : Swift.Error {
case Error(info: String)
case AccountBanned(info: String)
case LoginPermissionRequired(info: String)
case needs2FA(info: String) //需要两步验证
case needsCloudflareChecking(info: String) //需要 Cloudflare 检查
}
extension Swift.Error {
func rawString() -> String {
guard let err = self as? ApiError else {
return self.localizedDescription
}
switch err {
case let .Error(info):
return info
case let .AccountBanned(info):
return info
case let .LoginPermissionRequired(info):
return info
case .needs2FA(let info):
return info
case .needsCloudflareChecking(let info):
return info
}
}
}
//MARK: - JSON解析相关
extension Observable where Element: Moya.Response {
/// 过滤 HTTP 错误,例如超时,请求失败等
func filterHttpError() -> Observable<Element> {
return filter{ response in
if (200...209) ~= response.statusCode {
return true
}
if 503 == response.statusCode {
if let jiHtml = Ji(htmlData: response.data) {
if let titleNode = jiHtml.xPath("/html/head/title")?.first , let content = titleNode.content, content.hasPrefix("Just a moment") {
throw ApiError.needsCloudflareChecking(info: "需要Cloudflare检查")
}
}
}
throw ApiError.Error(info: "网络错误")
}
}
/// 过滤逻辑错误,例如协议里返回 错误CODE
func filterResponseError() -> Observable<JSON> {
return filterHttpError().map({ (response) -> JSON in
var json: JSON
do {
json = try JSON(data: response.data)
} catch {
json = JSON(NSNull())
}
var code = 200
var msg = ""
if let codeStr = json["code"].rawString(), let c = Int(codeStr) {
code = c
}
if json["msg"].exists() {
msg = json["msg"].rawString()!
}
else if json["message"].exists() {
msg = json["message"].rawString()!
}
else if json["info"].exists() {
msg = json["info"].rawString()!
}
else if json["description"].exists() {
msg = json["description"].rawString()!
}
if (code == 200 || code == 99999 || code == 80001 || code == 1){
return json
}
switch code {
default: throw ApiError.Error(info: msg)
}
})
}
/// 将Response 转换成 JSON Model
///
/// - Parameters:
/// - typeName: 要转换的Model Class
/// - dataPath: 从哪个节点开始转换,例如 ["data","links"]
func mapResponseToObj<T: Mappable>(_ typeName: T.Type , dataPath:[String] = [] ) -> Observable<T> {
return filterResponseError().map{ json in
var rootJson = json
if dataPath.count > 0{
rootJson = rootJson[dataPath]
}
if let model: T = self.resultFromJSON(json: rootJson) {
return model
}
else{
throw ApiError.Error(info: "json 转换失败")
}
}
}
/// 将Response 转换成 JSON Model Array
func mapResponseToObjArray<T: Mappable>(_ type: T.Type, dataPath:[String] = [] ) -> Observable<[T]> {
return filterResponseError().map{ json in
var rootJson = json;
if dataPath.count > 0{
rootJson = rootJson[dataPath]
}
var result = [T]()
guard let jsonArray = rootJson.array else{
return result
}
for json in jsonArray{
if let jsonModel: T = self.resultFromJSON(json: json) {
result.append(jsonModel)
}
else{
throw ApiError.Error(info: "json 转换失败")
}
}
return result
}
}
private func resultFromJSON<T: Mappable>(jsonString:String) -> T? {
return T(JSONString: jsonString)
}
private func resultFromJSON<T: Mappable>(json:JSON) -> T? {
if let str = json.rawString(){
return resultFromJSON(jsonString: str)
}
return nil
}
}
//MARK: - Ji 解析相关
extension Observable where Element: Moya.Response {
/// 过滤业务逻辑错误
func filterJiResponseError() -> Observable<Ji> {
return filterHttpError().map({ (response: Element) -> Ji in
if response.response?.url?.path == "/signin" && response.request?.url?.path != "/signin" {
throw ApiError.LoginPermissionRequired(info: "查看的内容需要登录!")
}
if response.response?.url?.path == "/2fa" {
//需要两步验证
throw ApiError.needs2FA(info: "需要两步验证")
}
if let jiHtml = Ji(htmlData: response.data) {
return jiHtml
}
else {
throw ApiError.Error(info: "Failed to serialize response.")
}
})
}
/// 将Response 转成成 Ji Model Array
func mapResponseToJiArray<T: HtmlModelArrayProtocol>(_ type: T.Type) -> Observable<[T]> {
return filterJiResponseError().map{ ji in
return type.createModelArray(ji: ji) as! [T]
}
}
/// 将Response 转成成 Ji Model
func mapResponseToJiModel<T: HtmlModelProtocol>(_ type: T.Type) -> Observable<T> {
return filterJiResponseError().map{ ji in
return type.createModel(ji: ji) as! T
}
}
/// 在将 Ji 对象转换成 Model 之前,可能需要先获取 Ji 对象的数据
/// 例如获取我的收藏帖子列表时,除了需要将 Ji 数据 转换成 TopicListModel
/// 还需要额外获取最大页码,这个最大页面就从这个方法中获得
func getJiDataFirst(hander:@escaping ((_ ji: Ji) -> Void)) -> Observable<Ji> {
return filterJiResponseError().map({ (response: Ji) -> Ji in
hander(response)
return response
})
}
}
//调用 getJiDataFirst() 方法后可调用的方法
extension Observable where Element: Ji {
func mapResponseToJiArray<T: HtmlModelArrayProtocol>(_ type: T.Type) -> Observable<[T]> {
return map{ ji in
return type.createModelArray(ji: ji) as! [T]
}
}
/// 将Response 转成成 Ji Model
func mapResponseToJiModel<T: HtmlModelProtocol>(_ type: T.Type) -> Observable<T> {
return map{ ji in
return type.createModel(ji: ji) as! T
}
}
}
| mit |
Jean-Daniel/PhoneNumberKit | PhoneNumberKit/NSRegularExpression+Swift.swift | 2 | 3211 | //
// NSRegularExpression+Swift.swift
// PhoneNumberKit
//
// Created by David Beck on 8/15/16.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = range.lowerBound.samePosition(in: utf16view) ?? self.startIndex
let to = range.upperBound.samePosition(in: utf16view) ?? self.endIndex
return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from),
utf16view.distance(from: from, to: to))
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}
extension NSRegularExpression {
func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
self.enumerateMatches(in: string, options: options, range: nsRange, using: block)
}
func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> [NSTextCheckingResult] {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
return self.matches(in: string, options: options, range: nsRange)
}
func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Int {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
return self.numberOfMatches(in: string, options: options, range: nsRange)
}
func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> NSTextCheckingResult? {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
return self.firstMatch(in: string, options: options, range: nsRange)
}
func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Range<String.Index>? {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
let match = self.rangeOfFirstMatch(in: string, options: options, range: nsRange)
return string.range(from: match)
}
func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, withTemplate templ: String) -> String {
let range = range ?? string.startIndex..<string.endIndex
let nsRange = string.nsRange(from: range)
return self.stringByReplacingMatches(in: string, options: options, range: nsRange, withTemplate: templ)
}
}
| mit |
AtharvaVaidya/Expression | Expression/Classes/OperatorToken.swift | 1 | 1096 | //
// OperatorToken.swift
// Expression
//
// Created by Atharva Vaidya on 6/29/19.
//
import Foundation
public struct OperatorToken: CustomStringConvertible {
let operatorType: OperatorType
init(operatorType: OperatorType) {
self.operatorType = operatorType
}
var precedence: Int {
switch operatorType {
case .add, .subtract:
return 0
case .divide, .multiply, .percent:
return 5
case .exponent:
return 10
}
}
var associativity: OperatorAssociativity {
switch operatorType {
case .add, .subtract, .divide, .multiply, .percent:
return .LeftAssociative
case .exponent:
return .RightAssociative
}
}
public var description: String {
return operatorType.description
}
}
func <= (left: OperatorToken, right: OperatorToken) -> Bool {
return left.precedence <= right.precedence
}
func < (left: OperatorToken, right: OperatorToken) -> Bool {
return left.precedence < right.precedence
}
| mit |
jongwonwoo/CodeSamples | Performance/signposts/LivePhotoPlayground/LivePhotoPlayground/ExUICollectionView.swift | 2 | 529 | //
// ExUICollectionView.swift
// LivePhotoPlayground
//
// Created by jongwon woo on 2016. 11. 18..
// Copyright © 2016년 jongwonwoo. All rights reserved.
//
import UIKit
extension UICollectionView {
func indexPathForVisibleCenter() -> IndexPath? {
var visibleRect = CGRect()
visibleRect.origin = self.contentOffset
visibleRect.size = self.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
return self.indexPathForItem(at: visiblePoint)
}
}
| mit |
XRedcolor/noahhotel | noahhotel/Pods/CocoaLumberjack/Classes/CocoaLumberjack.swift | 78 | 4944 | // Software License Agreement (BSD License)
//
// Copyright (c) 2014-2015, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
import Foundation
import CocoaLumberjack
extension DDLogFlag {
public static func fromLogLevel(logLevel: DDLogLevel) -> DDLogFlag {
return DDLogFlag(logLevel.rawValue)
}
///returns the log level, or the lowest equivalant.
public func toLogLevel() -> DDLogLevel {
if let ourValid = DDLogLevel(rawValue: self.rawValue) {
return ourValid
} else {
let logFlag = self
if logFlag & .Verbose == .Verbose {
return .Verbose
} else if logFlag & .Debug == .Debug {
return .Debug
} else if logFlag & .Info == .Info {
return .Info
} else if logFlag & .Warning == .Warning {
return .Warning
} else if logFlag & .Error == .Error {
return .Error
} else {
return .Off
}
}
}
}
extension DDMultiFormatter {
public var formatterArray: [DDLogFormatter] {
return self.formatters as! [DDLogFormatter]
}
}
public var defaultDebugLevel = DDLogLevel.Verbose
public func resetDefaultDebugLevel() {
defaultDebugLevel = DDLogLevel.Verbose
}
public func SwiftLogMacro(isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, tag: AnyObject? = nil, @autoclosure #string: () -> String) {
if level.rawValue & flg.rawValue != 0 {
// Tell the DDLogMessage constructor to copy the C strings that get passed to it. Using string interpolation to prevent integer overflow warning when using StaticString.stringValue
let logMessage = DDLogMessage(message: string(), level: level, flag: flg, context: context, file: "\(file)", function: "\(function)", line: line, tag: tag, options: .CopyFile | .CopyFunction, timestamp: nil)
DDLog.log(isAsynchronous, message: logMessage)
}
}
public func DDLogDebug(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Debug, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func DDLogInfo(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Info, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func DDLogWarn(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Warning, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func DDLogVerbose(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Verbose, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func DDLogError(@autoclosure logText: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Error, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
/// Analogous to the C preprocessor macro THIS_FILE
public func CurrentFileName(fileName: StaticString = __FILE__) -> String {
// Using string interpolation to prevent integer overflow warning when using StaticString.stringValue
return "\(fileName)".lastPathComponent.stringByDeletingPathExtension
}
| mit |
bastiangardel/EasyPayClientSeller | TB_Client_Seller/TB_Client_Seller/ViewControllerReceiptToPay.swift | 1 | 4862 | //
// ReceiptToPayViewController.swift
// TB_Client_Seller
//
// Created by Bastian Gardel on 27.06.16.
//
// Copyright © 2016 Bastian Gardel
//
// 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 SwiftQRCode
import BButton
import MBProgressHUD
import SCLAlertView
// ** Class ViewControllerReceiptToPay **
//
// View Receipt to pay Controller
//
// Author: Bastian Gardel
// Version: 1.0
class ViewControllerReceiptToPay: UIViewController {
var toPass: CheckoutDTO?
@IBOutlet weak var ReceiptIDLabel: UILabel!
@IBOutlet weak var qrcode: UIImageView!
@IBOutlet weak var returnButton: BButton!
@IBOutlet weak var amountLabel: UILabel!
var httpsSession = HTTPSSession.sharedInstance
var receipt: ReceiptPayDTO?
var hud: MBProgressHUD?
//View initialisation
override func viewDidLoad() {
super.viewDidLoad()
returnButton.color = UIColor.bb_dangerColorV2()
returnButton.setStyle(BButtonStyle.BootstrapV2)
returnButton.setType(BButtonType.Danger)
returnButton.addAwesomeIcon(FAIcon.FAAngleDoubleLeft, beforeTitle: true)
qrcode.image = QRCode.generateImage((toPass?.uuid)!, avatarImage: UIImage(named: "avatar"), avatarScale: 0.3)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewControllerReceiptToPay.quitView(_:)), name: "quitView", object: nil)
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud?.labelText = "Receipt Loading in progress"
hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)!
httpsSession.getReceiptToPay((toPass?.uuid)!){
(success: Bool, errorDescription:String, receiptPayDTO : ReceiptPayDTO?) in
self.hud!.hide(true)
if(success)
{
self.receipt = receiptPayDTO
self.amountLabel.text = "CHF " + String(format: "%.02f", (self.receipt?.amount)!)
self.ReceiptIDLabel.text = "Receipt ID: " + (self.receipt?.id?.description)!
}
else
{
let appearance = SCLAlertView.SCLAppearance(
kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!,
kTextFont: UIFont(name: "HelveticaNeue", size: 30)!,
kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!,
kWindowWidth: 500.0,
kWindowHeight: 500.0,
kTitleHeight: 50,
showCloseButton: false
)
let alertView = SCLAlertView(appearance: appearance)
alertView.addButton("Return to menu"){
self.performSegueWithIdentifier("returnMenuSegue", sender: self)
}
alertView.showError("Receipt Loading Error", subTitle: errorDescription)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Quit view action
func quitView(notification: NSNotification) {
print(notification.userInfo!["aps"]!["uuid"])
if(notification.userInfo!["uuid"]! as? String == toPass?.uuid){
self.performSegueWithIdentifier("returnMenuSegue", sender: self)
}
}
//Click on Return button handler
@IBAction func returnMenuAction(sender: AnyObject) {
self.performSegueWithIdentifier("returnMenuSegue", sender: self)
}
//Prepare transfer value for next view
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "returnMenuSegue") {
let svc = segue.destinationViewController as! ViewControllerCheckoutMenu;
svc.toPass = toPass
}
}
}
| mit |
chenyunguiMilook/VisualDebugger | Sources/VisualDebugger/extensions/CGPoint+Behavior.swift | 1 | 2519 | //
// CGPoint+Behavior.swift
// VisualDebugger
//
// Created by chenyungui on 2018/3/19.
//
import Foundation
import CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#else
import Cocoa
#endif
let kPointRadius: CGFloat = 3
extension CGPoint {
func getBezierPath(radius: CGFloat) -> AppBezierPath {
let x = (self.x - radius/2.0)
let y = (self.y - radius/2.0)
let rect = CGRect(x: x, y: y, width: radius, height: radius)
return AppBezierPath(ovalIn: rect)
}
var length:CGFloat {
return sqrt(self.x * self.x + self.y * self.y)
}
func normalized(to length:CGFloat = 1) -> CGPoint {
let len = length/self.length
return CGPoint(x: self.x * len, y: self.y * len)
}
}
func +(p1: CGPoint, p2: CGPoint) -> CGPoint {
return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y)
}
func -(p1: CGPoint, p2: CGPoint) -> CGPoint {
return CGPoint(x: p1.x - p2.x, y: p1.y - p2.y)
}
func calculateAngle(_ point1:CGPoint, _ point2:CGPoint) -> CGFloat {
return atan2(point2.y - point1.y, point2.x - point1.x)
}
func calculateDistance(_ point1:CGPoint, _ point2:CGPoint) -> CGFloat {
let x = point2.x - point1.x
let y = point2.y - point1.y
return sqrt(x*x + y*y)
}
func calculateCenter(_ point1:CGPoint, _ point2:CGPoint) -> CGPoint {
return CGPoint(x: point1.x+(point2.x-point1.x)/2.0, y: point1.y+(point2.y-point1.y)/2.0)
}
extension Array where Element == CGPoint {
public var bounds:CGRect {
guard let pnt = self.first else { return CGRect.zero }
var (minX, maxX, minY, maxY) = (pnt.x, pnt.x, pnt.y, pnt.y)
for point in self {
minX = point.x < minX ? point.x : minX
minY = point.y < minY ? point.y : minY
maxX = point.x > maxX ? point.x : maxX
maxY = point.y > maxY ? point.y : maxY
}
return CGRect(x: minX, y: minY, width: (maxX-minX), height: (maxY-minY))
}
}
// MARK: - Point
extension CGPoint : Debuggable {
public var bounds: CGRect {
return CGRect(origin: self, size: .zero)
}
public func debug(in coordinate: CoordinateSystem, color: AppColor?) {
let newPoint = self * coordinate.matrix
let path = newPoint.getBezierPath(radius: kPointRadius)
let color = color ?? coordinate.getNextColor()
let shapeLayer = CAShapeLayer(path: path.cgPath, strokeColor: nil, fillColor: color, lineWidth: 0)
coordinate.addSublayer(shapeLayer)
}
}
| mit |
zybug/firefox-ios | Client/Frontend/Home/ReaderPanel.swift | 12 | 22123 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
import XCGLogger
private let log = Logger.browserLogger
private struct ReadingListTableViewCellUX {
static let RowHeight: CGFloat = 86
static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44)
static let ReadIndicatorWidth: CGFloat = 12 // image width
static let ReadIndicatorHeight: CGFloat = 12 // image height
static let ReadIndicatorTopOffset: CGFloat = 36.75 // half of the cell - half of the height of the asset
static let ReadIndicatorLeftOffset: CGFloat = 18
static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest
static let TitleLabelFont = UIFont.systemFontOfSize(UIConstants.DeviceFontSize, weight: UIFontWeightMedium)
static let TitleLabelTopOffset: CGFloat = 14 - 4
static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16
static let TitleLabelRightOffset: CGFloat = -40
static let HostnameLabelFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight)
static let HostnameLabelBottomOffset: CGFloat = 11
static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035)
static let DeleteButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight)
static let DeleteButtonTitleColor = UIColor.whiteColor()
static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1)
static let MarkAsReadButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight)
static let MarkAsReadButtonTitleColor = UIColor.whiteColor()
static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
// Localizable strings
static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item")
static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read")
static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread")
}
private struct ReadingListPanelUX {
// Welcome Screen
static let WelcomeScreenTopPadding: CGFloat = 16
static let WelcomeScreenPadding: CGFloat = 15
static let WelcomeScreenHeaderFont = UIFont.boldSystemFontOfSize(UIConstants.DeviceFontSize - 1)
static let WelcomeScreenHeaderTextColor = UIColor.darkGrayColor()
static let WelcomeScreenItemFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight)
static let WelcomeScreenItemTextColor = UIColor.grayColor()
static let WelcomeScreenItemWidth = 220
static let WelcomeScreenItemOffset = -20
static let WelcomeScreenCircleWidth = 40
static let WelcomeScreenCircleOffset = 20
static let WelcomeScreenCircleSpacer = 10
}
class ReadingListTableViewCell: SWTableViewCell {
var title: String = "Example" {
didSet {
titleLabel.text = title
updateAccessibilityLabel()
}
}
var url: NSURL = NSURL(string: "http://www.example.com")! {
didSet {
hostnameLabel.text = simplifiedHostnameFromURL(url)
updateAccessibilityLabel()
}
}
var unread: Bool = true {
didSet {
readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")
titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal)
if let text = markAsReadButton.titleLabel?.text {
markAsReadAction.name = text
}
updateAccessibilityLabel()
}
}
private var deleteAction: UIAccessibilityCustomAction!
private var markAsReadAction: UIAccessibilityCustomAction!
let readStatusImageView: UIImageView!
let titleLabel: UILabel!
let hostnameLabel: UILabel!
let deleteButton: UIButton!
let markAsReadButton: UIButton!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
readStatusImageView = UIImageView()
titleLabel = UILabel()
hostnameLabel = UILabel()
deleteButton = UIButton()
markAsReadButton = UIButton()
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clearColor()
separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0)
layoutMargins = UIEdgeInsetsZero
preservesSuperviewLayoutMargins = false
contentView.addSubview(readStatusImageView)
readStatusImageView.contentMode = UIViewContentMode.ScaleAspectFit
readStatusImageView.snp_makeConstraints { (make) -> () in
make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth)
make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight)
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset)
}
contentView.addSubview(titleLabel)
titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
titleLabel.numberOfLines = 2
titleLabel.font = ReadingListTableViewCellUX.TitleLabelFont
titleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset)
make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec
}
contentView.addSubview(hostnameLabel)
hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
hostnameLabel.numberOfLines = 1
hostnameLabel.font = ReadingListTableViewCellUX.HostnameLabelFont
hostnameLabel.snp_makeConstraints { (make) -> () in
make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)
make.left.right.equalTo(self.titleLabel)
}
deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor
deleteButton.titleLabel?.font = ReadingListTableViewCellUX.DeleteButtonTitleFont
deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor
deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center
deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal)
deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets
deleteAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.DeleteButtonTitleText, target: self, selector: "deleteActionActivated")
rightUtilityButtons = [deleteButton]
markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor
markAsReadButton.titleLabel?.font = ReadingListTableViewCellUX.MarkAsReadButtonTitleFont
markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor
markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center
markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal)
markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets
markAsReadAction = UIAccessibilityCustomAction(name: ReadingListTableViewCellUX.MarkAsReadButtonTitleText, target: self, selector: "markAsReadActionActivated")
leftUtilityButtons = [markAsReadButton]
accessibilityCustomActions = [deleteAction, markAsReadAction]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
private func simplifiedHostnameFromURL(url: NSURL) -> String {
let hostname = url.host ?? ""
for prefix in prefixesToSimplify {
if hostname.hasPrefix(prefix) {
return hostname.substringFromIndex(hostname.startIndex.advancedBy(prefix.characters.count))
}
}
return hostname
}
@objc private func markAsReadActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0)
return true
}
@objc private func deleteActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0)
return true
}
private func updateAccessibilityLabel() {
if let hostname = hostnameLabel.text,
title = titleLabel.text {
let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.")
let string = "\(title), \(unreadStatus), \(hostname)"
var label: AnyObject
if !unread {
// mimic light gray visual dimming by "dimming" the speech by reducing pitch
let lowerPitchString = NSMutableAttributedString(string: string as String)
lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length))
label = NSAttributedString(attributedString: lowerPitchString)
} else {
label = string
}
// need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this
// see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple
// also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly...
setValue(label, forKey: "accessibilityLabel")
}
}
}
class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview()
private var records: [ReadingListClientRecord]?
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = ReadingListTableViewCellUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.separatorColor = UIConstants.SeparatorColor
tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell")
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
view.backgroundColor = UIConstants.PanelBackgroundColor
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
// If no records have been added yet, we display the empty state
if records?.count == 0 {
tableView.scrollEnabled = false
view.addSubview(emptyStateOverlayView)
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
refreshReadingList()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
func refreshReadingList() {
let prevNumberOfRecords = records?.count
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
if records?.count == 0 {
tableView.scrollEnabled = false
if emptyStateOverlayView.superview == nil {
view.addSubview(emptyStateOverlayView)
}
} else {
if prevNumberOfRecords == 0 {
tableView.scrollEnabled = true
emptyStateOverlayView.removeFromSuperview()
}
}
self.tableView.reloadData()
}
}
private func createEmptyStateOverview() -> UIView {
let overlayView = UIView(frame: tableView.bounds)
overlayView.backgroundColor = UIColor.whiteColor()
// Unknown why this does not work with autolayout
overlayView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
let containerView = UIView()
overlayView.addSubview(containerView)
let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel"))
containerView.addSubview(logoImageView)
logoImageView.snp_makeConstraints { make in
make.centerX.equalTo(containerView)
make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).priorityHigh()
// Sets proper top constraint for iPhone 6 in portait and iPads.
make.centerY.equalTo(overlayView.snp_centerY).offset(-180).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView.snp_top).offset(50).priorityHigh()
}
let welcomeLabel = UILabel()
containerView.addSubview(welcomeLabel)
welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL")
welcomeLabel.textAlignment = NSTextAlignment.Center
welcomeLabel.font = ReadingListPanelUX.WelcomeScreenHeaderFont
welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp_makeConstraints { make in
make.centerX.equalTo(containerView)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth)
make.top.equalTo(logoImageView.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
// Sets proper center constraint for iPhones in landscape.
make.centerY.lessThanOrEqualTo(overlayView.snp_centerY).offset(-40).priorityHigh()
}
let readerModeLabel = UILabel()
containerView.addSubview(readerModeLabel)
readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL")
readerModeLabel.font = ReadingListPanelUX.WelcomeScreenItemFont
readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readerModeLabel.numberOfLines = 0
readerModeLabel.snp_makeConstraints { make in
make.top.equalTo(welcomeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
}
let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle"))
containerView.addSubview(readerModeImageView)
readerModeImageView.snp_makeConstraints { make in
make.centerY.equalTo(readerModeLabel)
make.right.equalTo(welcomeLabel.snp_right)
}
let readingListLabel = UILabel()
containerView.addSubview(readingListLabel)
readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL")
readingListLabel.font = ReadingListPanelUX.WelcomeScreenItemFont
readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readingListLabel.numberOfLines = 0
readingListLabel.snp_makeConstraints { make in
make.top.equalTo(readerModeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
}
let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle"))
containerView.addSubview(readingListImageView)
readingListImageView.snp_makeConstraints { make in
make.centerY.equalTo(readingListLabel)
make.right.equalTo(welcomeLabel.snp_right)
}
containerView.snp_makeConstraints { make in
// Let the container wrap around the content
make.top.equalTo(logoImageView.snp_top)
make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset)
make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset)
// And then center it in the overlay view that sits on top of the UITableView
make.centerX.equalTo(overlayView)
}
return overlayView
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell
cell.delegate = self
if let record = records?[indexPath.row] {
cell.title = record.title
cell.url = NSURL(string: record.url)!
cell.unread = record.unread
}
return cell
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell {
cell.hideUtilityButtonsAnimated(true)
if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess {
// TODO This is a bit odd because the success value of the update is an optional optional Record
if let successValue = result.successValue, updatedRecord = successValue {
records?[indexPath.row] = updatedRecord
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
}
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.deleteRecord(record) where result.isSuccess {
records?.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
// reshow empty state if no records left
if records?.count == 0 {
view.addSubview(emptyStateOverlayView)
}
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) {
// Mark the item as read
profile.readingList?.updateRecord(record, unread: false)
// Reading list items are closest in concept to bookmarks.
let visitType = VisitType.Bookmark
homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType)
}
}
}
| mpl-2.0 |
wireapp/wire-ios-data-model | Source/Model/AccountStore.swift | 1 | 5463 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
private let log = ZMSLog(tag: "Accounts")
/// Persistence layer for `Account` objects.
/// Objects are stored in files named after their identifier like this:
///
/// ```
/// - Root url passed to init
/// - Accounts
/// - 47B3C313-E3FA-4DE4-8DBE-5BBDB6A0A14B
/// - 0F5771BB-2103-4E45-9ED2-E7E6B9D46C0F
/// ```
public final class AccountStore: NSObject {
private static let directoryName = "Accounts"
private let fileManager = FileManager.default
private let directory: URL // The url to the directory in which accounts are stored in
/// Creates a new `AccountStore`.
/// `Account` objects will be stored in a subdirectory of the passed in url.
/// - parameter root: The root url in which the storage will use to store its data
public required init(root: URL) {
directory = root.appendingPathComponent(AccountStore.directoryName)
super.init()
FileManager.default.createAndProtectDirectory(at: directory)
}
// MARK: - Storing and Retrieving
/// Loads all stored accounts.
/// - returns: All accounts stored in this `AccountStore`.
func load() -> Set<Account> {
return Set<Account>(loadURLs().compactMap(Account.load))
}
/// Tries to load a stored account with the given `UUID`.
/// - parameter uuid: The `UUID` of the user the account belongs to.
/// - returns: The `Account` stored for the passed in `UUID`, or `nil` otherwise.
func load(_ uuid: UUID) -> Account? {
return Account.load(from: url(for: uuid))
}
/// Stores an `Account` in the account store.
/// - parameter account: The account which should be saved (or updated).
/// - returns: Whether or not the operation was successful.
@discardableResult func add(_ account: Account) -> Bool {
do {
try account.write(to: url(for: account))
return true
} catch {
log.error("Unable to store account \(account), error: \(error)")
return false
}
}
/// Deletes an `Account` from the account store.
/// - parameter account: The account which should be deleted.
/// - returns: Whether or not the operation was successful.
@discardableResult func remove(_ account: Account) -> Bool {
do {
guard contains(account) else { return false }
try fileManager.removeItem(at: url(for: account))
return true
} catch {
log.error("Unable to delete account \(account), error: \(error)")
return false
}
}
/// Deletes the persistence layer of an `AccountStore` from the file system.
/// Mostly useful for cleaning up after tests or for complete account resets.
/// - parameter root: The root url of the store that should be deleted.
@discardableResult static func delete(at root: URL) -> Bool {
do {
try FileManager.default.removeItem(at: root.appendingPathComponent(directoryName))
return true
} catch {
log.error("Unable to remove all accounts at \(root): \(error)")
return false
}
}
/// Check if an `Account` is already stored in this `AccountStore`.
/// - parameter account: The account which should be deleted.
/// - returns: Whether or not the account is stored in this `AccountStore`.
func contains(_ account: Account) -> Bool {
return fileManager.fileExists(atPath: url(for: account).path)
}
// MARK: - Private Helper
/// Loads the urls to all stored accounts.
/// - returns: The urls to all accounts stored in this `AccountStore`.
private func loadURLs() -> Set<URL> {
do {
let uuidName: (String) -> Bool = { UUID(uuidString: $0) != nil }
let paths = try fileManager.contentsOfDirectory(atPath: directory.path)
return Set<URL>(paths.filter(uuidName).map(directory.appendingPathComponent))
} catch {
log.error("Unable to load accounts from \(directory), error: \(error)")
return []
}
}
/// Create a local url for an `Account` inside this `AccountStore`.
/// - parameter account: The account for which the url should be generated.
/// - returns: The `URL` for the given account.
private func url(for account: Account) -> URL {
return url(for: account.userIdentifier)
}
/// Create a local url for an `Account` with the given `UUID` inside this `AccountStore`.
/// - parameter uuid: The uuid of the user for which the url should be generated.
/// - returns: The `URL` for the given uuid.
private func url(for uuid: UUID) -> URL {
return directory.appendingPathComponent(uuid.uuidString)
}
}
| gpl-3.0 |
cotkjaer/Silverback | Silverback/Picker.swift | 1 | 389 | //
// Picker.swift
// Silverback
//
// Created by Christian Otkjær on 27/01/16.
// Copyright © 2016 Christian Otkjær. All rights reserved.
//
import Foundation
public protocol PickerDelegate
{
func picker(picker: Picker, didPick item: Any?)
}
public protocol Picker: class
{
var pickedObject: Any? { get set }
var pickerDelegate : PickerDelegate? { get set }
}
| mit |
hi-hu/Hu-Tumbler | Hu-Tumbler/MainContainerViewController.swift | 1 | 5183 | //
// MainContainerViewController.swift
// Hu-Tumbler
//
// Created by Hi_Hu on 3/6/15.
// Copyright (c) 2015 hi_hu. All rights reserved.
//
import UIKit
class MainContainerViewController: UIViewController {
@IBOutlet weak var mainContainerVC: UIView!
@IBOutlet weak var exploreImage: UIImageView!
@IBOutlet weak var loginBtn: UIButton!
// array of tab controller buttons
@IBOutlet var tabControlButtons: [UIButton]!
// array holding the views
var vcArray = [UIViewController]()
var homeVC: HomeViewController!
var searchVC: TrendingViewController!
var composeVC: ComposeViewController!
var accountVC: AccountViewController!
var activityVC: SearchViewController!
// index defaulted to home
var selectedIndex: Int! = 0
// custom transitions
var composeTransition: FadeTransition!
var loginTransition: LoginTransition!
override func viewDidLoad() {
super.viewDidLoad()
// set the status bar style to light
UIApplication.sharedApplication().statusBarStyle = .LightContent
// view controller instantiation
var storyboard = UIStoryboard(name: "Main", bundle: nil)
homeVC = storyboard.instantiateViewControllerWithIdentifier("homeSBID") as HomeViewController
searchVC = storyboard.instantiateViewControllerWithIdentifier("trendingSBID") as TrendingViewController
composeVC = storyboard.instantiateViewControllerWithIdentifier("composeSBID") as ComposeViewController
accountVC = storyboard.instantiateViewControllerWithIdentifier("accountSBID") as AccountViewController
activityVC = storyboard.instantiateViewControllerWithIdentifier("searchSBID") as SearchViewController
// add the instantiated views into the array
vcArray = [homeVC, searchVC, accountVC, activityVC]
// default to homepage
displayContentController(mainContainerVC, content: homeVC)
tabControlButtons[0].selected = true
// animate the explore bubble to bob up and down
UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { () -> Void in
self.exploreImage.center.y = self.exploreImage.center.y - 6
}) { (Bool) -> Void in
// code
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tabBtnDidPress(sender: AnyObject) {
var oldIndex = selectedIndex
selectedIndex = sender.tag
if selectedIndex != 0 {
loginBtn.hidden = true
} else {
loginBtn.hidden = false
}
if selectedIndex == 1 {
exploreImage.hidden = true
}
// deactivate button and remove current view
tabControlButtons[oldIndex].selected = false
hideContentController(mainContainerVC, content: vcArray[oldIndex])
// activate button add new selected view
tabControlButtons[selectedIndex].selected = true
displayContentController(mainContainerVC, content: vcArray[selectedIndex])
}
// perform custom segue
@IBAction func composeDidPress(sender: AnyObject) {
performSegueWithIdentifier("composeSegue", sender: self)
}
@IBAction func loginDidPress(sender: AnyObject) {
performSegueWithIdentifier("loginSegue", sender: self)
}
// add a subbview to the specified container
func displayContentController(container: UIView, content: UIViewController) {
addChildViewController(content)
mainContainerVC.addSubview(content.view)
content.didMoveToParentViewController(self)
}
// remove a subview from the specified container
func hideContentController(container: UIView, content: UIViewController) {
content.willMoveToParentViewController(nil)
content.view.removeFromSuperview()
content.removeFromParentViewController()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destinationViewController = segue.destinationViewController as UIViewController
if segue.identifier == "composeSegue" {
// instantiate the transition
composeTransition = FadeTransition()
composeTransition.duration = 0.3
destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
destinationViewController.transitioningDelegate = composeTransition
} else if segue.identifier == "loginSegue" {
// instantiate the transition
loginTransition = LoginTransition()
loginTransition.duration = 0.3
destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
destinationViewController.transitioningDelegate = loginTransition
}
}
}
| mit |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Other/SPFooterButtonsView.swift | 1 | 4355 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by)
//
// 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
class SPFooterActionsView: SPView {
var sectionLabels = SPSectionLabelsView()
private var buttons: [SPFooterActionButton] = []
private var separators: [SPSeparatorView] = []
override func commonInit() {
super.commonInit()
self.backgroundColor = UIColor.clear
self.sectionLabels.titleLabel.text = "Actions"
self.addSubview(self.sectionLabels)
}
func addButton(title: String, titleColor: UIColor, target: @escaping ()->()) {
let button = SPFooterActionButton()
button.setTitle(title, color: titleColor)
button.target { target() }
self.buttons.append(button)
self.addSubview(button)
let separator = SPSeparatorView()
self.separators.append(separator)
self.addSubview(separator)
}
func button(for id: Int) -> SPFooterActionButton? {
if (self.buttons.count - 1) < id {
return nil
}
return self.buttons[id]
}
func layout(origin: CGPoint, width: CGFloat) {
self.frame.origin = origin
self.frame.set(width: width)
self.layoutSubviews()
}
func layout(y: CGFloat, width: CGFloat) {
self.layout(origin: CGPoint.init(x: 19, y: y), width: width)
}
override func layoutSubviews() {
super.layoutSubviews()
self.sectionLabels.layout(origin: CGPoint.zero, width: self.frame.width)
let buttonHeight: CGFloat = 50
var yPositionButton: CGFloat = self.sectionLabels.frame.bottomY + 12
if !self.buttons.isEmpty {
for i in 0...(buttons.count - 1) {
let button = self.buttons[i]
let separator = self.separators[i]
separator.frame.origin.x = 0
separator.frame.origin.y = yPositionButton
separator.frame.set(width: self.frame.width)
button.frame = CGRect.init(x: 0, y: yPositionButton, width: self.frame.width, height: buttonHeight)
yPositionButton += buttonHeight
}
self.frame.set(height: yPositionButton)
}
}
}
class SPFooterActionButton: SPButton {
var rightIconView: UIView? {
willSet {
self.rightIconView?.removeFromSuperview()
}
didSet {
if let view = self.rightIconView {
self.addSubview(view)
self.layoutSubviews()
}
}
}
override func commonInit() {
super.commonInit()
self.setTitleColor(SPNativeColors.blue)
self.titleLabel?.font = UIFont.system(weight: .regular, size: 21)
self.contentHorizontalAlignment = .left
}
override func layoutSubviews() {
super.layoutSubviews()
let sideSize: CGFloat = self.frame.height * 0.36
self.rightIconView?.frame = CGRect.init(x: 0, y: 0, width: sideSize, height: sideSize)
self.rightIconView?.center.y = self.frame.height / 2
self.rightIconView?.frame.bottomX = self.frame.width - sideSize / 3
}
}
| mit |
NghiaTranUIT/PullToMakeSoup | PullToMakeSoup/Demo/AppDelegate.swift | 1 | 2153 | //
// AppDelegate.swift
// PullToMakeSoup
//
// Created by Anastasiya Gorban on 5/19/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Mobelux/MONK | MONKTests/Tests/UploadTaskTests.swift | 1 | 26326 | //
// UploadTaskTests.swift
// MONK
//
// MIT License
//
// Copyright (c) 2017 Mobelux
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import MONK
class UploadTaskTests: XCTestCase {
private let networkController = NetworkController(serverTrustSettings: nil)
override func tearDown() {
super.tearDown()
networkController.cancelAllTasks()
}
func testUploadJSONTask() {
let expectation = self.expectation(description: "Network request")
let url = URL(string: "http://httpbin.org/post")!
let json = try! DataHelper.data(for: .posts1).json()
let dataToUpload = UploadableData.json(json: json)
XCTAssertFalse(dataToUpload.isMultiPart, "Multipart data was not expected")
let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
let responseWhatWePosted = responseJSON["json"]
XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing")
XCTAssert((responseWhatWePosted as! JSON) == json, "The JSON we posted is not what we got back")
XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
func testPUTUploadJSONTask() {
let expectation = self.expectation(description: "Network request")
let url = URL(string: "http://httpbin.org/put")!
let json = try! DataHelper.data(for: .posts1).json()
let dataToUpload = UploadableData.json(json: json)
XCTAssertFalse(dataToUpload.isMultiPart, "Multipart data was not expected")
let request = DataRequest(url: url, httpMethod: .put(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
let responseWhatWePosted = responseJSON["json"]
XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing")
XCTAssert((responseWhatWePosted as! JSON) == json, "The JSON we posted is not what we got back")
XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
func testUploadImageFromURLTask() {
let expectation = self.expectation(description: "Network request")
let imageURL = DataHelper.imageURL(for: .compiling)
let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .file(url: imageURL))
let dataToUpload = UploadableData.files(files: [file])
let url = URL(string: "http://httpbin.org/post")!
let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files")
XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
func testUploadJSONAndImageFromURLTask() {
let expectation = self.expectation(description: "Network request")
let json = try! DataHelper.data(for: .posts1).json()
let imageURL = DataHelper.imageURL(for: .compiling)
let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .file(url: imageURL))
let dataToUpload = UploadableData.jsonAndFiles(json: json, files: [file])
let url = URL(string: "http://httpbin.org/post")!
let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
let responseWhatWePosted = responseJSON["form"] as? JSON
XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing")
XCTAssert(responseWhatWePosted!.keys.elementsEqual(json.keys), "The JSON we posted is not what we got back")
XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files")
XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
func testUploadJSONAndImageFromDataTask() {
let expectation = self.expectation(description: "Network request")
let json = try! DataHelper.data(for: .posts1).json()
let imageData = DataHelper.imageData(for: .compiling)
let file = UploadableData.FileData.init(name: "imageFile", fileName: "compiling.png", mimeType: ContentType.png, data: .data(data: imageData))
let dataToUpload = UploadableData.jsonAndFiles(json: json, files: [file])
XCTAssert(dataToUpload.isMultiPart, "Multipart data expected")
let url = URL(string: "http://httpbin.org/post")!
let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
let responseWhatWePosted = responseJSON["form"] as? JSON
XCTAssertNotNil(responseWhatWePosted, "The JSON we posted is missing")
XCTAssert(responseWhatWePosted!.keys.elementsEqual(json.keys), "The JSON we posted is not what we got back")
XCTAssert(FileValidator.validate(files: [file], response: responseJSON), "Uploaded files don't match recieved files")
XCTAssert(self.networkController.activeTasksCount == 0, "Tasks still active")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
func testUploadImageFromRawData() {
let expectation = self.expectation(description: "Network request")
let imageData = DataHelper.imageData(for: .compiling)
let dataToUpload = UploadableData.data(data: imageData, contentType: ContentType.png)
let url = URL(string: "http://httpbin.org/post")!
let request = DataRequest(url: url, httpMethod: .post(bodyData: dataToUpload))
let task = networkController.data(with: request)
var downloadProgressCalled = false
var uploadProgressCalled = false
task.addCompletion { (result) in
switch result {
case .failure(let error):
XCTAssert(false, "Error found: \(String(describing: error))")
expectation.fulfill()
case .success(let statusCode, let responseData, let cached):
XCTAssert(statusCode == 200, "Invalid status code found")
XCTAssertNotNil(responseData, "Data was nil")
switch cached {
case .notCached:
break
case .fromCache, .updatedCache:
XCTAssert(false, "We should not have used the cache")
}
guard let responseJSON = try? responseData!.json() else { expectation.fulfill(); return }
XCTAssert(FileValidator.validate(uploadedData: dataToUpload, response: responseJSON), "Uploaded data don't match recieved data")
XCTAssert(downloadProgressCalled, "Download progress was never called")
XCTAssert(uploadProgressCalled, "Upload progress was never called")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
let mutableTask = task as! MutableDataTask
XCTAssert(mutableTask.completionHandlers.count == 0, "Completion handlers aren't dealocated")
XCTAssert(mutableTask.progressHandlers.count == 0, "Progress handlers aren't dealocated")
XCTAssert(mutableTask.uploadProgressHandlers.count == 0, "Progress handlers aren't dealocated")
expectation.fulfill()
})
}
}
task.addProgress { (progress) in
XCTAssertNotNil(task.downloadProgress, "Download progress wasn't set")
XCTAssert(progress.totalBytes == task.downloadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.downloadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.downloadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
downloadProgressCalled = true
}
task.addUploadProgress { (progress) in
XCTAssertNotNil(task.uploadProgress, "Upload progress wasn't set")
XCTAssert(progress.totalBytes == task.uploadProgress!.totalBytes, "Total bytes don't match")
XCTAssert(progress.completeBytes == task.uploadProgress!.completeBytes, "Complete bytes don't match")
XCTAssert(progress.progress == task.uploadProgress!.progress, "Progresses don't match")
XCTAssertNotNil(progress.progress, "Progress was nil")
XCTAssert(progress.totalBytes >= progress.completeBytes, "Total bytes should always be more then complete bytes")
uploadProgressCalled = true
}
task.resume()
waitForExpectations(timeout: TestConstants.testTimeout, handler: nil)
}
}
| mit |
skedgo/tripkit-ios | Sources/TripKit/server/TKDeparturesProvider.swift | 1 | 4001 | //
// TKDeparturesProvider.swift
// TripKit
//
// Created by Adrian Schönig on 01.11.20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
#if canImport(CoreData)
import Foundation
import CoreData
@objc
public class TKDeparturesProvider: NSObject {
private override init() {
super.init()
}
}
// MARK: - API to Core Data
extension TKDeparturesProvider {
public static func addDepartures(_ departures: TKAPI.Departures, to stops: [StopLocation]) -> Bool {
guard let context = stops.first?.managedObjectContext else {
return false
}
var addedStops = false
// First, we process optional parent information
let lookup = Dictionary(grouping: stops) { $0.stopCode }
for parent in departures.parentStops ?? [] {
if let existing = lookup[parent.code]?.first {
addedStops = existing.update(from: parent) || addedStops
} else {
assertionFailure("Got a parent that we didn't ask for: \(parent)")
}
}
// Next, we collect the existing stops to add content to
let flattened = stops.flatMap {
return [$0] + ($0.children ?? [])
}
let candidates = Dictionary(grouping: flattened) { $0.stopCode }
// Now, we can add all the stops
var addedCount = 0
for embarkation in departures.embarkationStops {
guard let stop = candidates[embarkation.stopCode]?.first else {
assertionFailure("Got an embarkation but no stop to add it to: \(embarkation). Stops: \(candidates)")
continue
}
for serviceModel in embarkation.services {
addedCount += 1
let service = Service(from: serviceModel, into: context)
service.addVisits(StopVisits.self, from: serviceModel, at: stop)
}
}
assert(addedCount > 0, "No embarkations in \(departures)")
// Insert all the alerts, and make sure that the stops point
// to them, too
TKAPIToCoreDataConverter.updateOrAddAlerts(departures.alerts, in: context)
departures.stops?.forEach {
let hashCodes = $0.alertHashCodes
guard !hashCodes.isEmpty else { return }
lookup[$0.code]?.forEach { $0.alertHashCodes = hashCodes.map(NSNumber.init) }
}
return addedStops
}
public static func addDepartures(_ departures: TKAPI.Departures, into context: NSManagedObjectContext) -> Set<String> {
// First, we make sure we have all the stops
let stops = (departures.stops ?? [])
.map { TKAPIToCoreDataConverter.insertNewStopLocation(from: $0, into: context) }
// Next, we collect the existing stops to add content to
let flattened = stops.flatMap {
return [$0] + ($0.children ?? [])
}
let candidates = Dictionary(grouping: flattened) { $0.stopCode }
// Now, we can add all the stops
var pairIdentifieres = Set<String>()
for embarkation in departures.embarkationStops {
guard let startStop = candidates[embarkation.stopCode]?.first else {
TKLog.info("Got an embarkation but no stop to add it to: \(embarkation). Stops: \(candidates)")
continue
}
for serviceModel in embarkation.services {
guard
let endStopCode = serviceModel.endStopCode,
let endStop = candidates[endStopCode]?.first else {
TKLog.info("Got an disembarkation but no stop to add it to: \(embarkation). Stops: \(candidates)")
continue
}
let service = Service(from: serviceModel, into: context)
if let entry = service.addVisits(DLSEntry.self, from: serviceModel, at: startStop) {
entry.pairIdentifier = "\(embarkation.stopCode)-\(endStopCode)"
entry.endStop = endStop
pairIdentifieres.insert(entry.pairIdentifier)
}
}
}
// assert(!pairIdentifieres.isEmpty, "No embarkations in \(departures)")
TKAPIToCoreDataConverter.updateOrAddAlerts(departures.alerts, in: context)
return pairIdentifieres
}
}
#endif
| apache-2.0 |
apple/swift-argument-parser | Sources/ArgumentParserTestHelpers/TestHelpers.swift | 1 | 13844 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import ArgumentParserToolInfo
import XCTest
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension CollectionDifference.Change {
var offset: Int {
switch self {
case .insert(let offset, _, _):
return offset
case .remove(let offset, _, _):
return offset
}
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension CollectionDifference.Change: Comparable where ChangeElement: Equatable {
public static func < (lhs: Self, rhs: Self) -> Bool {
guard lhs.offset == rhs.offset else {
return lhs.offset < rhs.offset
}
switch (lhs, rhs) {
case (.remove, .insert):
return true
case (.insert, .remove):
return false
default:
return true
}
}
}
// extensions to the ParsableArguments protocol to facilitate XCTestExpectation support
public protocol TestableParsableArguments: ParsableArguments {
var didValidateExpectation: XCTestExpectation { get }
}
public extension TestableParsableArguments {
mutating func validate() throws {
didValidateExpectation.fulfill()
}
}
// extensions to the ParsableCommand protocol to facilitate XCTestExpectation support
public protocol TestableParsableCommand: ParsableCommand, TestableParsableArguments {
var didRunExpectation: XCTestExpectation { get }
}
public extension TestableParsableCommand {
mutating func run() throws {
didRunExpectation.fulfill()
}
}
extension XCTestExpectation {
public convenience init(singleExpectation description: String) {
self.init(description: description)
expectedFulfillmentCount = 1
assertForOverFulfill = true
}
}
public func AssertResultFailure<T, U: Error>(
_ expression: @autoclosure () -> Result<T, U>,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line)
{
switch expression() {
case .success:
let msg = message()
XCTFail(msg.isEmpty ? "Incorrectly succeeded" : msg, file: file, line: line)
case .failure:
break
}
}
public func AssertErrorMessage<A>(_ type: A.Type, _ arguments: [String], _ errorMessage: String, file: StaticString = #file, line: UInt = #line) where A: ParsableArguments {
do {
_ = try A.parse(arguments)
XCTFail("Parsing should have failed.", file: file, line: line)
} catch {
// We expect to hit this path, i.e. getting an error:
XCTAssertEqual(A.message(for: error), errorMessage, file: file, line: line)
}
}
public func AssertFullErrorMessage<A>(_ type: A.Type, _ arguments: [String], _ errorMessage: String, file: StaticString = #file, line: UInt = #line) where A: ParsableArguments {
do {
_ = try A.parse(arguments)
XCTFail("Parsing should have failed.", file: (file), line: line)
} catch {
// We expect to hit this path, i.e. getting an error:
XCTAssertEqual(A.fullMessage(for: error), errorMessage, file: (file), line: line)
}
}
public func AssertParse<A>(_ type: A.Type, _ arguments: [String], file: StaticString = #file, line: UInt = #line, closure: (A) throws -> Void) where A: ParsableArguments {
do {
let parsed = try type.parse(arguments)
try closure(parsed)
} catch {
let message = type.message(for: error)
XCTFail("\"\(message)\" — \(error)", file: (file), line: line)
}
}
public func AssertParseCommand<A: ParsableCommand>(_ rootCommand: ParsableCommand.Type, _ type: A.Type, _ arguments: [String], file: StaticString = #file, line: UInt = #line, closure: (A) throws -> Void) {
do {
let command = try rootCommand.parseAsRoot(arguments)
guard let aCommand = command as? A else {
XCTFail("Command is of unexpected type: \(command)", file: (file), line: line)
return
}
try closure(aCommand)
} catch {
let message = rootCommand.message(for: error)
XCTFail("\"\(message)\" — \(error)", file: file, line: line)
}
}
public func AssertEqualStrings(actual: String, expected: String, file: StaticString = #file, line: UInt = #line) {
// If the input strings are not equal, create a simple diff for debugging...
guard actual != expected else {
// Otherwise they are equal, early exit.
return
}
// Split in the inputs into lines.
let actualLines = actual.split(separator: "\n", omittingEmptySubsequences: false)
let expectedLines = expected.split(separator: "\n", omittingEmptySubsequences: false)
// If collectionDifference is available, use it to make a nicer error message.
if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
// Compute the changes between the two strings.
let changes = actualLines.difference(from: expectedLines).sorted()
// Render the changes into a diff style string.
var diff = ""
var expectedLines = expectedLines[...]
for change in changes {
if expectedLines.startIndex < change.offset {
for line in expectedLines[..<change.offset] {
diff += " \(line)\n"
}
expectedLines = expectedLines[change.offset...].dropFirst()
}
switch change {
case .insert(_, let line, _):
diff += "- \(line)\n"
case .remove(_, let line, _):
diff += "+ \(line)\n"
}
}
for line in expectedLines {
diff += " \(line)\n"
}
XCTFail("Strings are not equal.\n\(diff)", file: file, line: line)
} else {
XCTAssertEqual(
actualLines.count,
expectedLines.count,
"Strings have different numbers of lines.",
file: file,
line: line)
for (actualLine, expectedLine) in zip(actualLines, expectedLines) {
XCTAssertEqual(actualLine, expectedLine, file: file, line: line)
}
}
}
public func AssertHelp<T: ParsableArguments>(
_ visibility: ArgumentVisibility,
for _: T.Type,
equals expected: String,
file: StaticString = #file,
line: UInt = #line
) {
let flag: String
let includeHidden: Bool
switch visibility {
case .default:
flag = "--help"
includeHidden = false
case .hidden:
flag = "--help-hidden"
includeHidden = true
case .private:
XCTFail("Should not be called.", file: file, line: line)
return
default:
XCTFail("Unrecognized visibility.", file: file, line: line)
return
}
do {
_ = try T.parse([flag])
XCTFail(file: file, line: line)
} catch {
let helpString = T.fullMessage(for: error)
AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line)
}
let helpString = T.helpMessage(includeHidden: includeHidden, columns: nil)
AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line)
}
public func AssertHelp<T: ParsableCommand, U: ParsableCommand>(
_ visibility: ArgumentVisibility,
for _: T.Type,
root _: U.Type,
equals expected: String,
file: StaticString = #file,
line: UInt = #line
) {
let includeHidden: Bool
switch visibility {
case .default:
includeHidden = false
case .hidden:
includeHidden = true
case .private:
XCTFail("Should not be called.", file: file, line: line)
return
default:
XCTFail("Unrecognized visibility.", file: file, line: line)
return
}
let helpString = U.helpMessage(
for: T.self, includeHidden: includeHidden, columns: nil)
AssertEqualStrings(actual: helpString, expected: expected, file: file, line: line)
}
public func AssertDump<T: ParsableArguments>(
for _: T.Type, equals expected: String,
file: StaticString = #file, line: UInt = #line
) throws {
do {
_ = try T.parse(["--experimental-dump-help"])
XCTFail(file: file, line: line)
} catch {
let dumpString = T.fullMessage(for: error)
try AssertJSONEqualFromString(actual: dumpString, expected: expected, for: ToolInfoV0.self)
}
try AssertJSONEqualFromString(actual: T._dumpHelp(), expected: expected, for: ToolInfoV0.self)
}
public func AssertJSONEqualFromString<T: Codable & Equatable>(actual: String, expected: String, for type: T.Type) throws {
let actualJSONData = try XCTUnwrap(actual.data(using: .utf8))
let actualDumpJSON = try XCTUnwrap(JSONDecoder().decode(type, from: actualJSONData))
let expectedJSONData = try XCTUnwrap(expected.data(using: .utf8))
let expectedDumpJSON = try XCTUnwrap(JSONDecoder().decode(type, from: expectedJSONData))
XCTAssertEqual(actualDumpJSON, expectedDumpJSON)
}
extension XCTest {
public var debugURL: URL {
let bundleURL = Bundle(for: type(of: self)).bundleURL
return bundleURL.lastPathComponent.hasSuffix("xctest")
? bundleURL.deletingLastPathComponent()
: bundleURL
}
public func AssertExecuteCommand(
command: String,
expected: String? = nil,
exitCode: ExitCode = .success,
file: StaticString = #file, line: UInt = #line) throws
{
try AssertExecuteCommand(
command: command.split(separator: " ").map(String.init),
expected: expected,
exitCode: exitCode,
file: file,
line: line)
}
public func AssertExecuteCommand(
command: [String],
expected: String? = nil,
exitCode: ExitCode = .success,
file: StaticString = #file, line: UInt = #line) throws
{
#if os(Windows)
throw XCTSkip("Unsupported on this platform")
#endif
let arguments = Array(command.dropFirst())
let commandName = String(command.first!)
let commandURL = debugURL.appendingPathComponent(commandName)
guard (try? commandURL.checkResourceIsReachable()) ?? false else {
XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.",
file: file, line: line)
return
}
#if !canImport(Darwin) || os(macOS)
let process = Process()
if #available(macOS 10.13, *) {
process.executableURL = commandURL
} else {
process.launchPath = commandURL.path
}
process.arguments = arguments
let output = Pipe()
process.standardOutput = output
let error = Pipe()
process.standardError = error
if #available(macOS 10.13, *) {
guard (try? process.run()) != nil else {
XCTFail("Couldn't run command process.", file: file, line: line)
return
}
} else {
process.launch()
}
process.waitUntilExit()
let outputData = output.fileHandleForReading.readDataToEndOfFile()
let outputActual = String(data: outputData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
let errorData = error.fileHandleForReading.readDataToEndOfFile()
let errorActual = String(data: errorData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
if let expected = expected {
AssertEqualStrings(
actual: errorActual + outputActual,
expected: expected,
file: file,
line: line)
}
XCTAssertEqual(process.terminationStatus, exitCode.rawValue, file: file, line: line)
#else
throw XCTSkip("Not supported on this platform")
#endif
}
public func AssertJSONOutputEqual(
command: String,
expected: String,
file: StaticString = #file, line: UInt = #line
) throws {
#if os(Windows)
throw XCTSkip("Unsupported on this platform")
#endif
let splitCommand = command.split(separator: " ")
let arguments = splitCommand.dropFirst().map(String.init)
let commandName = String(splitCommand.first!)
let commandURL = debugURL.appendingPathComponent(commandName)
guard (try? commandURL.checkResourceIsReachable()) ?? false else {
XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.",
file: file, line: line)
return
}
#if !canImport(Darwin) || os(macOS)
let process = Process()
if #available(macOS 10.13, *) {
process.executableURL = commandURL
} else {
process.launchPath = commandURL.path
}
process.arguments = arguments
let output = Pipe()
process.standardOutput = output
let error = Pipe()
process.standardError = error
if #available(macOS 10.13, *) {
guard (try? process.run()) != nil else {
XCTFail("Couldn't run command process.", file: file, line: line)
return
}
} else {
process.launch()
}
process.waitUntilExit()
let outputString = try XCTUnwrap(String(data: output.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8))
XCTAssertTrue(error.fileHandleForReading.readDataToEndOfFile().isEmpty, "Error occurred with `--experimental-dump-help`")
try AssertJSONEqualFromString(actual: outputString, expected: expected, for: ToolInfoV0.self)
#else
throw XCTSkip("Not supported on this platform")
#endif
}
public func AssertGenerateManual(
multiPage: Bool,
command: String,
expected: String,
file: StaticString = #file,
line: UInt = #line
) throws {
#if os(Windows)
throw XCTSkip("Unsupported on this platform")
#endif
let commandURL = debugURL.appendingPathComponent(command)
var command = [
"generate-manual", commandURL.path,
"--date", "1996-05-12",
"--section", "9",
"--authors", "Jane Appleseed",
"--authors", "<johnappleseed@apple.com>",
"--authors", "The Appleseeds<appleseeds@apple.com>",
"--output-directory", "-",
]
if multiPage {
command.append("--multi-page")
}
try AssertExecuteCommand(
command: command,
expected: expected,
exitCode: .success,
file: file,
line: line)
}
}
| apache-2.0 |
wtanuw/WTLibrary-iOS | WTLibrary-iOS/Swift/ButtonExtender.swift | 1 | 1777 | //
// ButtonExtender.swift
// IBButtonExtender
//
// Created by Ashish on 08/08/15.
// Copyright (c) 2015 Ashish. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
open class ButtonExtender: UIButton {
//MARK: PROPERTIES
@IBInspectable open var borderColor: UIColor = UIColor.white {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable open var borderWidth: CGFloat = 1.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var cornurRadius: CGFloat = 1.0 {
didSet {
layer.cornerRadius = cornurRadius
clipsToBounds = true
}
}
//MARK: Initializers
override public init(frame : CGRect) {
super.init(frame : frame)
setup()
configure()
}
convenience public init() {
self.init(frame:CGRect.zero)
setup()
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
configure()
}
override open func awakeFromNib() {
super.awakeFromNib()
setup()
configure()
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
configure()
}
func setup() {
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 1.0
layer.cornerRadius = 1.0
}
func configure() {
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornurRadius
}
override open func layoutSubviews() {
super.layoutSubviews()
}
}
| mit |
SwiftyVK/SwiftyVK | Example/AppDelegate.swift | 2 | 1461 | import SwiftyVK
var vkDelegateReference : SwiftyVKDelegate?
#if os(iOS)
import UIKit
@UIApplicationMain
final class AppDelegate : UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
vkDelegateReference = VKDelegateExample()
return true
}
@available(iOS 9.0, *)
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
let app = options[.sourceApplication] as? String
VK.handle(url: url, sourceApplication: app)
return true
}
func application(
_ application: UIApplication,
open url: URL,
sourceApplication: String?,
annotation: Any
) -> Bool {
VK.handle(url: url, sourceApplication: sourceApplication)
return true
}
}
#elseif os(macOS)
import Cocoa
@NSApplicationMain
final class AppDelegate : NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
vkDelegateReference = VKDelegateExample()
}
}
#endif
| mit |
karloscarweber/SwiftFoundations-Examples | Chapter1/TickTackToe/TickTackToe/ViewController.swift | 1 | 3547 | //
// ViewController.swift
// TickTackToe
//
// Created by Karl Oscar Weber on 6/20/15.
// Copyright (c) 2015 Swift Foundations. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/*
remember, you must initialize all of your instance variables before
calling super.init
If you don't do it here you can do it in the init() method.
*/
var button1 = UIButton()
var button2 = UIButton()
var button3 = UIButton()
var button4 = UIButton()
var button5 = UIButton()
var button6 = UIButton()
var button7 = UIButton()
var button8 = UIButton()
var button9 = UIButton()
var buttons: Array<UIButton> = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
init() {
// add all of the buttons to the array
buttons.append(button1)
buttons.append(button2)
buttons.append(button3)
buttons.append(button4)
buttons.append(button5)
buttons.append(button6)
buttons.append(button7)
buttons.append(button8)
buttons.append(button9)
// always call the designated initialiser of the super class
super.init(nibName: nil, bundle: nil)
// now we can layout buttons and stuff.
self.layoutButtons()
}
/*
I like to create a sub method to layout user interface elements.
Doing so keeps the init method nice and clean.
*/
func layoutButtons() {
print("layoutButtons called.\n")
print("Say hello to my little friend.")
let screen = UIScreen.mainScreen().bounds
let screenThirdHeight = screen.height / 3
let screenThirdWidth = screen.width / 3
/*
We should really use AutoLayout, but because this is a beginners book
We'll just use Calculated rectangles.
*/
self.button1.frame = CGRectMake(0, 0, screenThirdWidth, screenThirdWidth)
self.button2.frame = CGRectMake(screenThirdWidth, 0, screenThirdWidth, screenThirdWidth)
self.button3.frame = CGRectMake(screenThirdWidth*2, 0, screenThirdWidth, screenThirdWidth)
self.button4.frame = CGRectMake(0, screenThirdWidth, screenThirdWidth, screenThirdWidth)
self.button5.frame = CGRectMake(screenThirdWidth, screenThirdWidth, screenThirdWidth, screenThirdWidth)
self.button6.frame = CGRectMake(screenThirdWidth*2, screenThirdWidth, screenThirdWidth, screenThirdWidth)
self.button7.frame = CGRectMake(0, screenThirdWidth*2, screenThirdWidth, screenThirdWidth)
self.button8.frame = CGRectMake(screenThirdWidth, screenThirdWidth*2, screenThirdWidth, screenThirdWidth)
self.button9.frame = CGRectMake(screenThirdWidth*2, screenThirdWidth*2, screenThirdWidth, screenThirdWidth)
// button5.backgroundColor = UIColor.blueColor()
for button in buttons {
button.layer.borderWidth = 2.0
button.layer.borderColor = UIColor.blackColor().CGColor
self.view.addSubview(button)
}
}
/* Not often used methods down here */
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
Sephiroth87/scroll-phat-swift | Sources/ScrollpHAT.swift | 1 | 4566 | //
// ScrollpHAT.swift
// sroll-phat-swift
//
// Created by Fabio Ritrovato on 14/01/2016.
// Copyright (c) 2016 orange in a day. All rights reserved.
//
public class ScrollpHAT {
static private let i2cAddress: Int32 = 0x60
static private let cmdSetMode: UInt8 = 0x00
static private let cmdSetState: UInt8 = 0x01
static private let cmdSetBrightness: UInt8 = 0x19
static private let mode5x11: UInt8 = 0x03
static private let font: [Int: [UInt8]] = [33: [23], 34: [3, 0, 3], 35: [10, 31, 10, 31, 10], 36: [2, 21, 31, 21, 8], 37: [9, 4, 18], 38: [10, 21, 10, 16], 39: [3], 40: [14, 17], 41: [17, 14], 42: [20, 14, 20], 43: [4, 14, 4], 44: [16, 8], 45: [4, 4], 46: [16], 47: [24, 6], 48: [14, 21, 14], 49: [18, 31, 16], 50: [25, 21, 18], 51: [17, 21, 10], 52: [14, 9, 28], 53: [23, 21, 9], 54: [14, 21, 8], 55: [25, 5, 3], 56: [10, 21, 10], 57: [2, 21, 14], 58: [10], 59: [16, 10], 60: [4, 10], 61: [10, 10, 10], 62: [10, 4], 63: [1, 21, 2], 64: [14, 29, 21, 14], 65: [30, 5, 30], 66: [31, 21, 10], 67: [14, 17, 17], 68: [31, 17, 14], 69: [31, 21, 17], 70: [31, 5, 1], 71: [14, 17, 29], 72: [31, 4, 31], 73: [17, 31, 17], 74: [9, 17, 15], 75: [31, 4, 27], 76: [31, 16, 16], 77: [31, 2, 4, 2, 31], 78: [31, 2, 12, 31], 79: [14, 17, 14], 80: [31, 9, 6], 81: [14, 17, 9, 22], 82: [31, 9, 22], 83: [18, 21, 9], 84: [1, 31, 1], 85: [15, 16, 16, 15], 86: [15, 16, 15], 87: [15, 16, 8, 16, 15], 88: [27, 4, 27], 89: [3, 28, 3], 90: [25, 21, 19], 91: [31, 17], 92: [6, 24], 93: [17, 31], 94: [2, 1, 2], 95: [16, 16, 16], 96: [1, 2], 97: [8, 20, 28], 98: [31, 20, 8], 99: [8, 20], 100: [8, 20, 31], 101: [14, 21, 2], 102: [30, 5], 103: [2, 21, 15], 104: [31, 4, 24], 105: [29], 106: [16, 13], 107: [31, 4, 26], 108: [31], 109: [28, 4, 24, 4, 24], 110: [28, 4, 24], 111: [8, 20, 8], 112: [30, 10, 4], 113: [4, 10, 30], 114: [28, 2], 115: [20, 10], 116: [15, 18], 117: [12, 16, 28], 118: [12, 16, 12], 119: [12, 16, 8, 16, 12], 120: [20, 8, 20], 121: [2, 20, 14], 122: [18, 26, 22], 123: [4, 14, 17], 124: [31], 125: [17, 14, 4], 126: [8, 4, 8, 4], 127: []]
private let bus: SMBus
private var buffer = [UInt8](repeating: UInt8(0x00), count: 11)
private var offset = 0
public init() throws {
try bus = SMBus(busNumber: 1)
try bus.writeI2CBlockData(address: ScrollpHAT.i2cAddress, command: ScrollpHAT.cmdSetMode, values: [ScrollpHAT.mode5x11])
}
public func update() throws {
var window: [UInt8]
if offset + 11 <= buffer.count {
window = Array(buffer[offset..<offset + 11])
} else {
window = Array(buffer[offset..<buffer.count])
window += Array(buffer.prefix(11 - window.count))
}
window.append(0xFF)
try bus.writeI2CBlockData(address: ScrollpHAT.i2cAddress, command: ScrollpHAT.cmdSetState, values: window)
}
public func clear() throws {
buffer = [UInt8](repeating: UInt8(0x00), count: 11)
offset = 0
try update()
}
public func setBrightness(_ brightness: Int) throws {
try bus.writeI2CBlockData(address: ScrollpHAT.i2cAddress, command: ScrollpHAT.cmdSetBrightness, values: [UInt8(brightness)])
}
public func setColumn(x: Int, value: UInt8) {
if buffer.count <= x {
buffer += [UInt8](repeating: UInt8(0x00), count: x - buffer.count + 1)
}
buffer[x] = value
}
public func write(string: String, x: Int = 0) throws {
var x = x
for char in string.utf8 {
if let fontChar = ScrollpHAT.font[Int(char)] {
for c in fontChar {
setColumn(x: x, value: c)
x += 1
}
} else {
setColumn(x: x, value: 0)
x += 1
setColumn(x: x, value: 0)
x += 1
}
setColumn(x: x, value: 0)
x += 1
}
try update()
}
public func setPixel(x: Int, y: Int, value: Bool) {
guard x >= 0 && x < 11 && y >= 0 && y < 5 else { return }
if value {
buffer[x] |= UInt8(1 << y)
} else {
buffer[x] &= ~UInt8(1 << y)
}
}
public func scroll() throws {
try scroll(by: 1)
}
public func scroll(by: Int) throws {
offset += by
offset %= buffer.count
try update()
}
public func scroll(to: Int = 0) throws {
offset = to % buffer.count
try update()
}
}
| gpl-2.0 |
wangyuxianglove/TestKitchen1607 | Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/recommend(推荐)/view/IngreLikeCell.swift | 1 | 2819 | //
// IngreLikeCell.swift
// Testkitchen1607
//
// Created by qianfeng on 16/10/25.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
class IngreLikeCell: UITableViewCell {
var jumpClosure:IngreJumpClourse?
//数据
var listModel:IngreRecommendWidgetList?
{
didSet{
showData()
}
}
//显示数据
private func showData(){
if listModel?.widget_data?.count>1{
//循坏显示文字图片
for var i in 0..<((listModel?.widget_data?.count)!-1){
//图片
let imageData=listModel?.widget_data![i]
if imageData?.type=="image"{
let imageTag=200+i/2
let imageView=contentView
.viewWithTag(imageTag)
if imageView?.isKindOfClass(UIImageView)==true{
let tmpImageView=imageView as! UIImageView
//数据
let url=NSURL(string:(imageData?.content)!)
tmpImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named:"sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
//文字
let textData=listModel?.widget_data![i+1]
if textData?.type=="text" {
let label=contentView.viewWithTag(300+i/2)
if label?.isKindOfClass(UILabel)==true{
let tmplabel=label as! UILabel
tmplabel.text=textData?.content
}
}
i+=1
}
}
}
@IBAction func clickBtn(sender: UIButton) {
let index=sender.tag-100
if index*2<listModel?.widget_data?.count{
let data=listModel?.widget_data![index*2]
if data?.link != nil && jumpClosure != nil{
jumpClosure!((data?.link)!)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//创建cell的方法
class func creatLikeCellFor(tableView:UITableView,atIndexPath indexPatn:NSIndexPath,listModel:IngreRecommendWidgetList?)->IngreLikeCell{
let cellId="IngreLikeCellId"
var cell=tableView.dequeueReusableCellWithIdentifier(cellId)as? IngreLikeCell
if nil==cell{
cell=NSBundle.mainBundle().loadNibNamed("IngreLikeCell", owner: nil, options: nil).last as?IngreLikeCell
}
cell?.listModel=listModel
return cell!
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
liyang1217/- | 斗鱼/斗鱼/Casses/Main/Controller/MainViewController.swift | 1 | 767 | //
// MainViewController.swift
// 斗鱼
//
// Created by BARCELONA on 16/9/20.
// Copyright © 2016年 LY. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVC(storyName: "Home")
addChildVC(storyName: "Live")
addChildVC(storyName: "Follow")
addChildVC(storyName: "Profile")
}
fileprivate func addChildVC(storyName: String){
//1. 通过storyBoard获取控制器
let childVC = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()!
//2. 将childVC作为子控制器
addChildViewController(childVC)
}
}
| mit |
RevenueCat/purchases-ios | Tests/UnitTests/Networking/Backend/BackendGetIntroEligibilityTests.swift | 1 | 6743 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// BackendGetIntroEligibilityTests.swift
//
// Created by Nacho Soto on 3/7/22.
import Foundation
import Nimble
import XCTest
@testable import RevenueCat
class BackendGetIntroEligibilityTests: BaseBackendTests {
override func createClient() -> MockHTTPClient {
super.createClient(#file)
}
func testEmptyEligibilityCheckDoesNothing() {
var error: NSError??
self.backend.offerings.getIntroEligibility(appUserID: Self.userID,
receiptData: Data(),
productIdentifiers: []) {
error = $1 as NSError?
}
expect(error).toEventually(equal(.some(nil)))
expect(self.httpClient.calls.count) == 0
}
func testPostsProductIdentifiers() throws {
self.httpClient.mock(
requestPath: .getIntroEligibility(appUserID: Self.userID),
response: .init(statusCode: .success,
response: ["producta": true, "productb": false, "productd": NSNull()])
)
var eligibility: [String: IntroEligibility]?
let products = ["producta", "productb", "productc", "productd"]
self.offerings.getIntroEligibility(appUserID: Self.userID,
receiptData: Data(1...3),
productIdentifiers: products,
completion: {(productEligibility, error) in
expect(error).to(beNil())
eligibility = productEligibility
})
expect(self.httpClient.calls).toEventually(haveCount(1))
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?.keys).to(contain(products))
expect(eligibility?["producta"]?.status) == .eligible
expect(eligibility?["productb"]?.status) == .ineligible
expect(eligibility?["productc"]?.status) == .unknown
expect(eligibility?["productd"]?.status) == .unknown
}
func testEligibilityUnknownIfError() {
self.httpClient.mock(
requestPath: .getIntroEligibility(appUserID: Self.userID),
response: .init(statusCode: .invalidRequest, response: Self.serverErrorResponse)
)
var eligibility: [String: IntroEligibility]?
let products = ["producta", "productb", "productc"]
self.offerings.getIntroEligibility(appUserID: Self.userID,
receiptData: Data.init(1...2),
productIdentifiers: products,
completion: {(productEligibility, error) in
expect(error).to(beNil())
eligibility = productEligibility
})
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?["producta"]?.status) == .unknown
expect(eligibility?["productb"]?.status) == .unknown
expect(eligibility?["productc"]?.status) == .unknown
}
func testEligibilityUnknownIfMissingAppUserID() {
self.httpClient.mock(
requestPath: .getIntroEligibility(appUserID: ""),
response: .init(error: .unexpectedResponse(nil))
)
var eligibility: [String: IntroEligibility]?
let products = ["producta"]
var eventualError: BackendError?
self.backend.offerings.getIntroEligibility(appUserID: "",
receiptData: Data.init(1...2),
productIdentifiers: products,
completion: {(productEligibility, error) in
eventualError = error
eligibility = productEligibility
})
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?["producta"]?.status) == IntroEligibilityStatus.unknown
expect(eventualError) == .missingAppUserID()
eligibility = nil
eventualError = nil
self.offerings.getIntroEligibility(appUserID: " ",
receiptData: Data.init(1...2),
productIdentifiers: products,
completion: {(productEligibility, error) in
eventualError = error
eligibility = productEligibility
})
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?["producta"]?.status) == IntroEligibilityStatus.unknown
expect(eventualError) == .missingAppUserID()
}
func testEligibilityUnknownIfUnknownError() {
let error: NetworkError = .networkError(NSError(domain: "myhouse", code: 12, userInfo: nil))
self.httpClient.mock(
requestPath: .getIntroEligibility(appUserID: Self.userID),
response: .init(error: error)
)
var eligibility: [String: IntroEligibility]?
let products = ["producta", "productb", "productc"]
self.offerings.getIntroEligibility(appUserID: Self.userID,
receiptData: Data.init(1...2),
productIdentifiers: products,
completion: {(productEligbility, error) in
expect(error).to(beNil())
eligibility = productEligbility
})
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?["producta"]?.status) == .unknown
expect(eligibility?["productb"]?.status) == .unknown
expect(eligibility?["productc"]?.status) == .unknown
}
func testEligibilityUnknownIfNoReceipt() {
var eligibility: [String: IntroEligibility]?
let products = ["producta", "productb", "productc"]
self.offerings.getIntroEligibility(appUserID: Self.userID,
receiptData: Data(),
productIdentifiers: products,
completion: {(productEligibility, error) in
expect(error).to(beNil())
eligibility = productEligibility
})
expect(eligibility).toEventuallyNot(beNil())
expect(eligibility?["producta"]?.status) == .unknown
expect(eligibility?["productb"]?.status) == .unknown
expect(eligibility?["productc"]?.status) == .unknown
}
}
| mit |
zeeshankhan/WeatherApp | WeatherAppTests/WeatherAppTests.swift | 1 | 1232 | //
// WeatherAppTests.swift
// WeatherAppTests
//
// Created by Zeeshan Khan on 10/14/16.
// Copyright © 2016 Zeeshan. All rights reserved.
//
import XCTest
@testable import WeatherApp
class WeatherAppTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testAddToStore() {
// let store = Store()
// XCTAssert(store.add("one"))
// let total = store.all.count
// XCTAssert(total == 1)
// XCTAssertEqual(total, 1)
// XCTAssert(store.all.contains("one"))
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.