repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kortnee1021/Kortnee
03-Single View App/Swift 2/BMI-Step10/BMI/ViewController.swift
2
4098
// // ViewController.swift // BMI // // Created by Nicholas Outram on 30/12/2014. // Copyright (c) 2014 Plymouth University. All rights reserved. // // 04-11-2015 Updated for Swift 2 import UIKit class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource { class func doDiv100(u : Int) -> Double { return Double(u) * 0.01 } class func doDiv2(u : Int) -> Double { return Double(u) * 0.5 } var weight : Double? var height : Double? var bmi : Double? { get { if (weight != nil) && (height != nil) { return weight! / (height! * height!) } else { return nil } } } let listOfHeightsInM = Array(140...220).map(ViewController.doDiv100) let listOfWeightsInKg = Array(80...240).map(ViewController.doDiv2) @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! @IBOutlet weak var heightPickerView: UIPickerView! @IBOutlet weak var weightPickerView: UIPickerView! 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. } //This function dismissed the keyboard func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func updateUI() { if let b = self.bmi { self.bmiLabel.text = String(format: "%4.1f", b) } } //Called when ever the textField looses focus func textFieldDidEndEditing(textField: UITextField) { //First we check if textField.text actually contains a (wrapped) String guard let txt : String = textField.text else { //Simply return if not return } //At this point, txt is of type String. Here is a nested function that will be used //to parse this string, and convert it to a wrapped Double if possible. func conv(numString : String) -> Double? { let result : Double? = NSNumberFormatter().numberFromString(numString)?.doubleValue return result } //Which textField is being edit? switch (textField) { case heightTextField: self.height = conv(txt) case weightTextField: self.weight = conv(txt) //default must be here to give complete coverage. A safety precaution. default: print("Something bad happened!") } //end of switch //Last of all, update the user interface. updateUI() } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch (pickerView) { case heightPickerView: return self.listOfHeightsInM.count case weightPickerView: return self.listOfWeightsInKg.count default: return 1 } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch (pickerView) { case heightPickerView: return String(format: "%4.2f", self.listOfHeightsInM[row]) case weightPickerView: return String(format: "%4.1f", self.listOfWeightsInKg[row]) default: return "" } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch (pickerView) { case heightPickerView: self.height = self.listOfHeightsInM[row] case weightPickerView: self.weight = self.listOfWeightsInKg[row] default: break } updateUI() } }
mit
796941a1d7a6290e4aa2bd80d28918e3
25.784314
108
0.612006
4.678082
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 2/5-Closures.playground/Contents.swift
2
1294
// Playground - noun: a place where people can play import UIKit // Closures func duasVezes(num: Int) -> Int { return 2 * num } var dobro = duasVezes(2) count("Fabio") let megaSena = [02, 33, 35, 12, 46, 13] // sorted : ordenado // (Int, Int) -> Bool func decrescente(n1: Int, n2: Int) -> Bool { return n1 > n2 } //Usando função como parâmetro var megaOrdenadaDecrescente = sorted(megaSena, decrescente) //Usando inline closure como parâmetro e simplificando ela a cada linha megaOrdenadaDecrescente = sorted(megaSena, {(n1: Int, n2: Int) -> Bool in return n1 > n2}) megaOrdenadaDecrescente = sorted(megaSena, {(n1, n2) in return n1 > n2}) megaOrdenadaDecrescente = sorted(megaSena, {$0 > $1}) megaOrdenadaDecrescente = sorted(megaSena) {$0 > $1} // trailing closure. // numero curto de argumentos megaOrdenadaDecrescente func criarDoador(paraValor valor: Int) -> () -> Int { var doaçãoTotal = 0 func doador() -> Int { doaçãoTotal += valor return doaçãoTotal } return doador } let doarDez = criarDoador(paraValor: 10) doarDez() doarDez() doarDez() let doarVinte = criarDoador(paraValor: 20) doarVinte() doarDez() let tambemDoarDez = doarDez tambemDoarDez()
mit
bb2056691de95891be43ad262d2c7249
14.46988
90
0.654206
2.680585
false
false
false
false
semiroot/SwiftyConstraints
Source/SC+Height.swift
1
3662
// // SwiftyConstraints+Height.swift // SwiftyConstraints // // Created by Hansmartin Geiser on 15/04/17. // Copyright © 2017 Hansmartin Geiser. All rights reserved. // // MARK: Height constraint management extension SwiftyConstraints { /// Creates a height constraint for the subview /// /// - Parameter equals: Float width (dpi) /// - Returns: SwiftyConstraints for method chaining @discardableResult open func height(_ equals: Float) -> SwiftyConstraints { do { try createConstraint(.height, .equal, nil, .height, 0, equals) } catch let error { reportError(error, "Height") } return self } /// Creates a height constraint for the subview equal to the height of the referenced view /// /// Make sure the view you reference is already attached via SwiftyConstraints /// otherwise no constraint will be created. /// /// - Parameters: /// - view: SCView referencing view /// - multipliedBy: Float multiplier (1 is default) /// - modiefiedBy: Float modifier (0 is default) /// - Returns: SwiftyConstraints for method chaining @discardableResult open func heightOf(_ view: SCView, _ multipliedBy: Float = 1, _ modiefiedBy: Float = 0) -> SwiftyConstraints { do { let referenceContainer = try getExistingContainer(view) return heightOf(referenceContainer, multipliedBy, modiefiedBy) } catch let error { reportError(error, "HeightOf") } return self } /// Internal heightOf for use with SCContainer instead of SCView /// /// - Parameters: /// - reference: SCContainer containing the referencing view /// - multipliedBy: Float multiplier (1 is default) /// - modiefiedBy: Float modifier (0 is default) /// - Returns: SwiftyConstraints for method chaining internal func heightOf(_ reference: SCContainer, _ multipliedBy: Float = 1, _ modiefiedBy: Float = 0) -> SwiftyConstraints { do { try createConstraint(.height, .equal, reference.view, .height, multipliedBy, modiefiedBy) } catch let error { reportError(error, "HeightOf") } return self } /// Creates a height constraint for the subview equal to the height of the superview /// /// - Parameters: /// - multipliedBy: Float multiplier (1 is default) /// - modiefiedBy: Float modifier (0 is default) /// - Returns: SwiftyConstraints for method chaining @discardableResult open func heightOfSuperview(_ multipliedBy: Float = 1, _ modiefiedBy: Float = 0) -> SwiftyConstraints { do { try createConstraint(.height, .equal, superview, .height, multipliedBy, modiefiedBy) } catch let error { reportError(error, "HeightOfSuperview") } return self } /// Creates a height constraint that is equal to the subview's width /// /// - Parameters: /// - multipliedBy: Float multiplier (1 is default) /// - modiefiedBy: Float modifier (0 is default) /// - Returns: SwiftyConstraints for method chaining @discardableResult open func heightFromWidth(_ multipliedBy: Float = 1, _ modiefiedBy: Float = 0) -> SwiftyConstraints { do { let container = try getCurrentContainer() try createConstraint(.height, .equal, container.view, .width, multipliedBy, modiefiedBy) } catch let error { reportError(error, "HeightFromWidth") } return self } /// Removes the height constraint for this subview /// /// Only the constraint will be removed. /// /// - Returns: SwiftyConstraints for method chaining @discardableResult open func removeHeight() -> SwiftyConstraints { do { try deleteConstraint(.height) } catch let error { reportError(error, "RemoveHeight") } return self } }
mit
a10f7e7b81a56ca97e29d333a47b74ab
36.357143
126
0.687517
4.384431
false
false
false
false
wangguangfeng/STUIComponent
STUIComponent/STUIComponent/Components/LoopPage.swift
2
7364
// // LoopPage.swift // STUIComponent // // Created by XuAzen on 16/2/25. // Copyright © 2016年 st company. All rights reserved. // public typealias LoopPageCountClosure = () -> Int public typealias LoopPageCurrentViewClosure = (pageIndex : Int) -> UIView public typealias LoopPageTapActionClosure = (pageIndex : Int) -> Void public class LoopPage: UIView { public var timeInterval : NSTimeInterval! // default is 0 -> 不自动轮播 private var collectionView : UICollectionView? private var pageCountClosure : LoopPageCountClosure? private var pageCurrentClosure : LoopPageCurrentViewClosure? private var pageTapActionClosure : LoopPageTapActionClosure? private var timer : NSTimer? private var pageCount : Int { get { var pageC = 1 if pageCountClosure != nil { if pageCountClosure!() != 0 { pageC = pageCountClosure!() } } return pageC } } private var privateTimeInterval : NSTimeInterval { get { if timeInterval == 0 { return Double(CGFloat.max) } else { return timeInterval } } } private var realPageCount : Int { get { return 5000 * pageCount } } //MARK: - init override private init(frame: CGRect) { pageCountClosure = {() -> Int in return 1 } pageCurrentClosure = {(pageIndex : Int) -> UIView in let view = UIView() view.backgroundColor = UIColor.whiteColor() return view } timeInterval = 0 super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 快速生成LoopPage - parameter frame: frame - parameter timeInter: 自动轮播时长,为0时表示不自动轮播 - parameter countClosur: 返回page数 - parameter pageClosure: 当前page - parameter actionClosure: page点击事件 - returns: LoopPage */ convenience public init(frame: CGRect, timeInter: NSTimeInterval, countClosur: LoopPageCountClosure, pageClosure: LoopPageCurrentViewClosure, actionClosure: LoopPageTapActionClosure) { self.init(frame: frame) timeInterval = timeInter pageCountClosure = countClosur pageCurrentClosure = pageClosure pageTapActionClosure = actionClosure } //MARK: - LifeCircle override public func didMoveToSuperview() { super.didMoveToSuperview() setupBasic() } // MARK: - Private private func setupBasic() { // 设定layout let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: frame.width, height: frame.height) layout.scrollDirection = UICollectionViewScrollDirection.Horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 // 设定collectionView collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) collectionView!.backgroundColor = UIColor.whiteColor() collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "loopCell") collectionView!.dataSource = self collectionView!.delegate = self collectionView!.showsVerticalScrollIndicator = false collectionView!.showsHorizontalScrollIndicator = false collectionView!.pagingEnabled = true collectionView!.bounces = false addSubview(collectionView!) // 设定pageCtl pageCtl.frame = CGRect(x: 0, y: 0, width: 100, height: 20) pageCtl.center.x = center.x pageCtl.frame.origin.y = frame.height - pageCtl.frame.height if pageCountClosure != nil { pageCtl.numberOfPages = pageCountClosure!() pageCtl.hidden = false } else { pageCtl.hidden = true } addSubview(pageCtl) // 处理时间 removeTimer() if pageCount > 1 { addTimer() } } //MARK: - Timer private func addTimer() -> Void { timer = NSTimer.scheduledTimerWithTimeInterval(privateTimeInterval, target: self, selector: Selector("timerStart"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } private func removeTimer() -> Void { timer?.invalidate() timer = nil } //MARK: - Target private var realIndex = 0 private var index : Int { get { return realIndex++ } } @objc private func timerStart() { let num = index collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: num, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true) } //KARK: - Lazy private lazy var pageCtl : UIPageControl = { let pageCtl = UIPageControl() return pageCtl }() } extension LoopPage : UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return realPageCount } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let page = collectionView.dequeueReusableCellWithReuseIdentifier("loopCell", forIndexPath: indexPath) let realIndex = indexPath.item % pageCount let currentView = pageCurrentClosure!(pageIndex: realIndex) currentView.frame = page.bounds for subView in page.subviews { subView.removeFromSuperview() } page.addSubview(currentView) return page } public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let currentPageIndex = collectionView.indexPathsForVisibleItems().first if let currentPageNum = currentPageIndex?.item { realIndex = currentPageIndex!.item pageCtl.currentPage = currentPageNum % pageCount } } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if pageTapActionClosure != nil { pageTapActionClosure!(pageIndex: indexPath.item % pageCount) } } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if pageCount == 1 { collectionView?.contentSize = CGSizeZero } else { if let visIndexPath = collectionView?.indexPathsForVisibleItems().first { if visIndexPath.item == 0 { collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: realPageCount / 2, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false) } } removeTimer() } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { addTimer() } }
mit
7303a4b28a44ebf39af4824b58a1911e
32.675926
188
0.630964
5.493202
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/RandomProjection.swift
1
2334
// Copyright 2020 The SwiftFusion 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 TensorFlow import PenguinStructures /// A class performing common activities in the RandomProjection framework. /// Input shape for training: [N, H, W, C] /// W matrix: [feature, H*W*C] /// Output: [feature] public struct RandomProjection { public typealias Patch = Tensor<Double> /// Random Basis Matrix /// When input image is of shape [N, H, W, C] /// B is of shape [d, H * W * C] public let B: Tensor<Double> /// Initialize the random projector with a normalized projection matrix public init(fromShape shape: TensorShape, toFeatureSize d: Int) { let (H, W, C) = (shape[0], shape[1], shape[2]) B = Tensor<Double>( stacking: (0..<d).map { _ in let t = Tensor<Double>(randomNormal: [H * W * C]) return t/sqrt(t.squared().sum()) } ) } /// Initialize given an image batch public typealias HyperParameters = Int public init(from imageBatch: Tensor<Double>, given d: HyperParameters? = nil) { self.init(fromShape: imageBatch.shape.suffix(3), toFeatureSize: d ?? 5) } /// Generate an feature from image or image batch /// Input: [H, W, C] or [N,H,W,C] /// Output: [d] or [N, d] @differentiable public func encode(_ image: Patch) -> Tensor<Double> { precondition(image.rank == 3 || (image.rank == 4), "wrong feature dimension \(image.shape)") let HWC = B.shape[1] let d = B.shape[0] if image.rank == 4 { let N = image.shape[0] let v_T = (image).reshaped(to: [HWC, N]).transposed() return matmul(v_T, B.transposed()).reshaped(to: [N, d]) } else { return matmul(B, (image).reshaped(to: [HWC, 1])).reshaped(to: [d]) } } } extension RandomProjection: AppearanceModelEncoder {}
apache-2.0
8beba949788f7612be5816bab53d6a72
34.907692
96
0.662811
3.613003
false
false
false
false
Desgard/Calendouer-iOS
Calendouer/Calendouer/App/View/detail/DegreeLifeTableViewCell.swift
1
4957
// // DegreeLifeTableViewCell.swift // Calendouer // // Created by Seahub on 2017/4/25. // Copyright © 2017年 Seahub. All rights reserved. // import UIKit class DegreeLifeTableViewCell: UITableViewCell { let badColor = DouRed let normalColor = UIColor.orange let goodColor = DouGreen var lifeScoreData: LifeScoreObject? { didSet { if let lifeScore = lifeScoreData { self.airQuantityBriefLabel.text = lifeScore.air_brf self.airQuantityDetailedLabel.text = lifeScore.air_txt self.comfortQuantityBriefLabel.text = lifeScore.comf_brf self.comfortQuantityDetailedLabel.text = lifeScore.comf_txt self.carWashingBriefLabel.text = lifeScore.cw_brf self.carWashingDetailedLabel.text = lifeScore.cw_txt self.clothesDressingBriefLabel.text = lifeScore.drsg_brf self.clothesDressingDetailedLabel.text = lifeScore.drsg_txt self.coldCatchingBriefLabel.text = lifeScore.flu_brf self.coldCatchingDetailedLabel.text = lifeScore.flu_txt self.sportsDoingBriefLabel.text = lifeScore.sport_brf self.sportsDoingDetailedLabel.text = lifeScore.sport_txt self.travellingBriefLabel.text = lifeScore.trav_brf self.travellingDetailedLabel.text = lifeScore.trav_txt self.ultravioletBriefLabel.text = lifeScore.uv_brf self.ultravioletDetailedLabel.text = lifeScore.uv_txt } } } @IBOutlet weak var airQuantityDetailedLabel: UILabel! @IBOutlet weak var comfortQuantityDetailedLabel: UILabel! @IBOutlet weak var carWashingDetailedLabel: UILabel! @IBOutlet weak var clothesDressingDetailedLabel: UILabel! @IBOutlet weak var coldCatchingDetailedLabel: UILabel! @IBOutlet weak var sportsDoingDetailedLabel: UILabel! @IBOutlet weak var travellingDetailedLabel: UILabel! @IBOutlet weak var ultravioletDetailedLabel: UILabel! @IBOutlet weak var airQuantityBriefLabel: UILabel! @IBOutlet weak var comfortQuantityBriefLabel: UILabel! @IBOutlet weak var carWashingBriefLabel: UILabel! @IBOutlet weak var clothesDressingBriefLabel: UILabel! @IBOutlet weak var coldCatchingBriefLabel: UILabel! @IBOutlet weak var sportsDoingBriefLabel: UILabel! @IBOutlet weak var travellingBriefLabel: UILabel! @IBOutlet weak var ultravioletBriefLabel: UILabel! // Maybe there are better solutions??? private func updateTextColor() { self.airQuantityBriefLabel.textColor = self.chooseColorByContent(self.airQuantityBriefLabel.text!, badStrs: ["较差,很差"], goodStrs: ["优"]) self.comfortQuantityBriefLabel.textColor = self.chooseColorByContent(self.comfortQuantityBriefLabel.text!, badStrs: ["不舒适", "不宜"], goodStrs: ["舒适", "较舒适"]) self.carWashingBriefLabel.textColor = self.chooseColorByContent(self.carWashingBriefLabel.text!, badStrs: ["不宜"], goodStrs: ["较适宜"]) self.clothesDressingBriefLabel.textColor = self.chooseColorByContent(self.clothesDressingBriefLabel.text!, badStrs: ["不舒适", "不宜"], goodStrs: ["较舒适", "舒适"]) self.coldCatchingBriefLabel.textColor = self.chooseColorByContent(self.coldCatchingBriefLabel.text!, badStrs: ["易发"], goodStrs: ["少发"]) self.sportsDoingBriefLabel.textColor = self.chooseColorByContent(self.sportsDoingBriefLabel.text!, badStrs: ["不宜"], goodStrs: ["较适宜", "适宜"]) self.travellingBriefLabel.textColor = self.chooseColorByContent(self.travellingBriefLabel.text!, badStrs: ["不宜"], goodStrs: ["较适宜", "适宜"]) self.ultravioletBriefLabel.textColor = self.chooseColorByContent(self.ultravioletBriefLabel.text!, badStrs: ["强", "最强"], goodStrs: ["最弱", "弱"]) } // Maybe there are better algorithm??? private func chooseColorByContent(_ contentStr: String, badStrs: [String], goodStrs: [String]) -> UIColor { for str in badStrs { if contentStr.contains(str) { return self.badColor; } } for str in goodStrs { if contentStr.contains(str) { return self.goodColor } } return self.normalColor } public func configure(lifeScore data: LifeScoreObject?) { if let data = data { self.lifeScoreData = data self.updateTextColor() } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
mit
534c1a99d895e03cf1606682d55416fa
46.45098
164
0.653926
3.903226
false
false
false
false
Quaggie/Quaggify
Quaggify/AppDelegate.swift
1
1733
// // AppDelegate.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. 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?.makeKeyAndVisible() if SpotifyService.shared.isLoggedIn { window?.rootViewController = TabBarController() } else { window?.rootViewController = LoginViewController() } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if let code = url.queryItemValueFor(key: "code") { API.requestToken(code: code) { [weak self] (error) in if let error = error { print(error) Alert.shared.show(title: "Error", message: error.localizedDescription) } else { API.fetchCurrentUser { (user, err) in if let err = err { Alert.shared.show(title: "Error", message: err.localizedDescription) } else if let user = user { User.current = user User.current.saveToDefaults() let tabBarVC = TabBarController() tabBarVC.didLogin = true self?.window?.rootViewController = tabBarVC } } } } } else if let error = url.queryItemValueFor(key: "error") { print(error) Alert.shared.show(title: "Error", message: error) } return true } }
mit
a3e8bdf7d3630e3111f4fc1c33c466ae
28.862069
142
0.616628
4.719346
false
false
false
false
wess/Cargo
Sources/resource/properties/relationship.swift
2
704
import Foundation public enum RelationshipType { case hasMany case belongsTo } public class Relationship<T: Resource> : ResourceProperty{ private let type:RelationshipType public var list:[Resource] = [] public init(_ type:RelationshipType) { self.type = type } public func all() -> [T]? { return nil } public func filter(handler:((T) -> Bool)) -> [T]? { return (all() ?? []).filter(handler) } public func get(_ where:[String:Any]) -> [T]? { return nil } func get(_ id:Int) -> T? { return nil } func add(_ resource:Resource) { var current = list.filter { $0 != resource } current.append(resource) list = current } }
mit
81b1fdb7614d9f2aefbc30de392ba6c8
16.170732
58
0.602273
3.744681
false
false
false
false
SlackKit/SlackKit
SKCore/Sources/Reply.swift
2
2032
// // Reaction.swift // // Copyright © 2017 Peter Zignego. 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. public struct Reply { fileprivate enum CodingKeys: String { case user case ts } public let user: String? public let ts: String? public init(reply: [String: Any]?) { user = reply?[CodingKeys.user] as? String ts = reply?[CodingKeys.ts] as? String } } extension Reply: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) user = try values.decodeIfPresent(String.self, forKey: .user) ts = try values.decodeIfPresent(String.self, forKey: .ts) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(user, forKey: .user) try container.encode(ts, forKey: .ts) } } extension Reply.CodingKeys: CodingKey { }
mit
fcd594208947f31ed665309ed269ded2
37.320755
80
0.707533
4.415217
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/OpenSearch.swift
3
10670
/* 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 Shared import Fuzi private let TypeSearch = "text/html" private let TypeSuggest = "application/x-suggestions+json" class OpenSearchEngine: NSObject, NSCoding { static let PreferredIconSize = 30 let shortName: String let engineID: String? let image: UIImage let isCustomEngine: Bool let searchTemplate: String fileprivate let suggestTemplate: String? fileprivate let SearchTermComponent = "{searchTerms}" fileprivate let LocaleTermComponent = "{moz:locale}" fileprivate lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate() init(engineID: String?, shortName: String, image: UIImage, searchTemplate: String, suggestTemplate: String?, isCustomEngine: Bool) { self.shortName = shortName self.image = image self.searchTemplate = searchTemplate self.suggestTemplate = suggestTemplate self.isCustomEngine = isCustomEngine self.engineID = engineID } required init?(coder aDecoder: NSCoder) { // this catches the cases where bool encoded in Swift 2 needs to be decoded with decodeObject, but a Bool encoded in swift 3 needs // to be decoded using decodeBool. This catches the upgrade case to ensure that we are always able to fetch a keyed valye for isCustomEngine // http://stackoverflow.com/a/40034694 let isCustomEngine = aDecoder.decodeAsBool(forKey: "isCustomEngine") guard let searchTemplate = aDecoder.decodeObject(forKey: "searchTemplate") as? String, let shortName = aDecoder.decodeObject(forKey: "shortName") as? String, let image = aDecoder.decodeObject(forKey: "image") as? UIImage else { assertionFailure() return nil } self.searchTemplate = searchTemplate self.shortName = shortName self.isCustomEngine = isCustomEngine self.image = image self.engineID = aDecoder.decodeObject(forKey: "engineID") as? String self.suggestTemplate = nil } func encode(with aCoder: NSCoder) { aCoder.encode(searchTemplate, forKey: "searchTemplate") aCoder.encode(shortName, forKey: "shortName") aCoder.encode(isCustomEngine, forKey: "isCustomEngine") aCoder.encode(image, forKey: "image") aCoder.encode(engineID, forKey: "engineID") } /** * Returns the search URL for the given query. */ func searchURLForQuery(_ query: String) -> URL? { return getURLFromTemplate(searchTemplate, query: query) } /** * Return the arg that we use for searching for this engine * Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this? **/ fileprivate func getQueryArgFromTemplate() -> String? { // we have the replace the templates SearchTermComponent in order to make the template // a valid URL, otherwise we cannot do the conversion to NSURLComponents // and have to do flaky pattern matching instead. let placeholder = "PLACEHOLDER" let template = searchTemplate.replacingOccurrences(of: SearchTermComponent, with: placeholder) let components = URLComponents(string: template) let searchTerm = components?.queryItems?.filter { item in return item.value == placeholder } guard let term = searchTerm, !term.isEmpty else { return nil } return term[0].name } /** * check that the URL host contains the name of the search engine somewhere inside it **/ fileprivate func isSearchURLForEngine(_ url: URL?) -> Bool { guard let urlHost = url?.shortDisplayString, let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound, let templateURL = URL(string: String(searchTemplate[..<queryEndIndex])) else { return false } return urlHost == templateURL.shortDisplayString } /** * Returns the query that was used to construct a given search URL **/ func queryForSearchURL(_ url: URL?) -> String? { if isSearchURLForEngine(url) { if let key = searchQueryComponentKey, let value = url?.getQuery()[key] { return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding } } return nil } /** * Returns the search suggestion URL for the given query. */ func suggestURLForQuery(_ query: String) -> URL? { if let suggestTemplate = suggestTemplate { return getURLFromTemplate(suggestTemplate, query: query) } return nil } fileprivate func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? { if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: .SearchTermsAllowed) { // Escape the search template as well in case it contains not-safe characters like symbols let templateAllowedSet = NSMutableCharacterSet() templateAllowedSet.formUnion(with: .URLAllowed) // Allow brackets since we use them in our template as our insertion point templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}")) if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) { let localeString = Locale.current.identifier let urlString = encodedSearchTemplate .replacingOccurrences(of: SearchTermComponent, with: escapedQuery, options: .literal, range: nil) .replacingOccurrences(of: LocaleTermComponent, with: localeString, options: .literal, range: nil) return URL(string: urlString) } } return nil } } /** * OpenSearch XML parser. * * This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to * the Firefox-specific search plugin format. * * OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1 */ class OpenSearchParser { fileprivate let pluginMode: Bool init(pluginMode: Bool) { self.pluginMode = pluginMode } func parse(_ file: String, engineID: String) -> OpenSearchEngine? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else { print("Invalid search file") return nil } guard let indexer = try? XMLDocument(data: data), let docIndexer = indexer.root else { print("Invalid XML document") return nil } let shortNameIndexer = docIndexer.children(tag: "ShortName") if shortNameIndexer.count != 1 { print("ShortName must appear exactly once") return nil } let shortName = shortNameIndexer[0].stringValue if shortName == "" { print("ShortName must contain text") return nil } let urlIndexers = docIndexer.children(tag: "Url") if urlIndexers.isEmpty { print("Url must appear at least once") return nil } var searchTemplate: String! var suggestTemplate: String? for urlIndexer in urlIndexers { let type = urlIndexer.attributes["type"] if type == nil { print("Url element requires a type attribute", terminator: "\n") return nil } if type != TypeSearch && type != TypeSuggest { // Not a supported search type. continue } var template = urlIndexer.attributes["template"] if template == nil { print("Url element requires a template attribute", terminator: "\n") return nil } if pluginMode { let paramIndexers = urlIndexer.children(tag: "Param") if !paramIndexers.isEmpty { template! += "?" var firstAdded = false for paramIndexer in paramIndexers { if firstAdded { template! += "&" } else { firstAdded = true } let name = paramIndexer.attributes["name"] let value = paramIndexer.attributes["value"] if name == nil || value == nil { print("Param element must have name and value attributes", terminator: "\n") return nil } template! += name! + "=" + value! } } } if type == TypeSearch { searchTemplate = template } else { suggestTemplate = template } } if searchTemplate == nil { print("Search engine must have a text/html type") return nil } let imageIndexers = docIndexer.children(tag: "Image") var largestImage = 0 var largestImageElement: XMLElement? // TODO: For now, just use the largest icon. for imageIndexer in imageIndexers { let imageWidth = Int(imageIndexer.attributes["width"] ?? "") let imageHeight = Int(imageIndexer.attributes["height"] ?? "") // Only accept square images. if imageWidth != imageHeight { continue } if let imageWidth = imageWidth { if imageWidth > largestImage { largestImage = imageWidth largestImageElement = imageIndexer } } } let uiImage: UIImage if let imageElement = largestImageElement, let imageURL = URL(string: imageElement.stringValue), let imageData = try? Data(contentsOf: imageURL), let image = UIImage.imageFromDataThreadSafe(imageData) { uiImage = image } else { print("Error: Invalid search image data") return nil } return OpenSearchEngine(engineID: engineID, shortName: shortName, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate, isCustomEngine: false) } }
mpl-2.0
3f46664161a2f552f91c8b0970be7aad
37.107143
178
0.603187
5.388889
false
false
false
false
rsmoz/swift-package-manager
Sources/dep/Manifest.swift
1
7129
/* This source file is part of the Swift.org open source project Copyright 2015 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 Swift project authors ------------------------------------------------------------------------- This file defines the support for loading the Swift-based manifest files. */ import PackageDescription import POSIX import sys import func sys.popen extension PackageDescription.Package { public static func fromTOML(item: TOMLItem, baseURL: String? = nil) -> PackageDescription.Package { // This is a private API, currently, so we do not currently try and // validate the input. guard case .Table(let topLevelTable) = item else { fatalError("unexpected item") } guard case .Some(.Table(let table)) = topLevelTable.items["package"] else { fatalError("missing package") } var name: String? = nil if case .Some(.String(let value)) = table.items["name"] { name = value } // Parse the targets. var targets: [PackageDescription.Target] = [] if case .Some(.Array(let array)) = table.items["targets"] { for item in array.items { targets.append(PackageDescription.Target.fromTOML(item)) } } // Parse the dependencies. var dependencies: [PackageDescription.Package.Dependency] = [] if case .Some(.Array(let array)) = table.items["dependencies"] { for item in array.items { dependencies.append(PackageDescription.Package.Dependency.fromTOML(item, baseURL: baseURL)) } } // Parse the test dependencies. var testDependencies: [PackageDescription.Package.Dependency] = [] if case .Some(.Array(let array)) = table.items["testDependencies"] { for item in array.items { testDependencies.append(PackageDescription.Package.Dependency.fromTOML(item, baseURL: baseURL)) } } //Parse the exclude folders. var exclude: [String] = [] if case .Some(.Array(let array)) = table.items["exclude"] { for item in array.items { guard case .String(let excludeItem) = item else { fatalError("exclude contains non string element") } exclude.append(excludeItem) } } return PackageDescription.Package(name: name, targets: targets, dependencies: dependencies, testDependencies: testDependencies, exclude: exclude) } } extension PackageDescription.Package.Dependency { public static func fromTOML(item: TOMLItem, baseURL: String?) -> PackageDescription.Package.Dependency { guard case .Array(let array) = item where array.items.count == 3 else { fatalError("Unexpected TOMLItem") } guard case .String(let url) = array.items[0], case .String(let vv1) = array.items[1], case .String(let vv2) = array.items[2], let v1 = Version(vv1), v2 = Version(vv2) else { fatalError("Unexpected TOMLItem") } func fixURL() -> String { if let baseURL = baseURL where URL.scheme(url) == nil { return Path.join(baseURL, url).normpath } else { return url } } return PackageDescription.Package.Dependency.Package(url: fixURL(), versions: v1..<v2) } } extension PackageDescription.Target { private static func fromTOML(item: TOMLItem) -> PackageDescription.Target { // This is a private API, currently, so we do not currently try and // validate the input. guard case .Table(let table) = item else { fatalError("unexpected item") } guard case .Some(.String(let name)) = table.items["name"] else { fatalError("missing name") } // Parse the dependencies. var dependencies: [PackageDescription.Target.Dependency] = [] if case .Some(.Array(let array)) = table.items["dependencies"] { for item in array.items { dependencies.append(PackageDescription.Target.Dependency.fromTOML(item)) } } return PackageDescription.Target(name: name, dependencies: dependencies) } } extension PackageDescription.Target.Dependency { private static func fromTOML(item: TOMLItem) -> PackageDescription.Target.Dependency { guard case .String(let name) = item else { fatalError("unexpected item") } return .Target(name: name) } } /** MARK: Manifest Loading This contains the declarative specification loaded from package manifest files, and the tools for working with the manifest. */ public struct Manifest { /// The top-level package definition. public let package: PackageDescription.Package /// Create a manifest from a pre-formed package. init(package: PackageDescription.Package) { self.package = package } /// Load the manifest at the given path. public init(path: String, baseURL: String? = nil) throws { guard path.isFile else { throw Error.NoManifest(path) } // For now, we load the manifest by having Swift interpret it directly // and using a special environment variable to trigger the PackageDescription // library to dump the package (as TOML) at exit. Eventually, we should // have two loading processes, one that loads only the the declarative // package specification using the Swift compiler directly and validates // it. // // FIXME: We also should make the mechanism for communicating the // package between the PackageDescription module more robust, for example by passing // in the id of another file descriptor to write the output onto. let libDir = Resources.runtimeLibPath let swiftcPath = Resources.path.swiftc var cmd = [swiftcPath, "--driver-mode=swift", "-I", libDir, "-L", libDir, "-lPackageDescription"] #if os(OSX) cmd += ["-target", "x86_64-apple-macosx10.10"] #endif cmd.append(path) let toml = try popen(cmd, environment: ["SWIFT_DUMP_PACKAGE": "1"]) // As a special case, we accept an empty file as an unnamed package. if toml.chuzzle() == nil { self.package = PackageDescription.Package() return } // canonicalize URLs var baseURL = baseURL if baseURL != nil && URL.scheme(baseURL!) == nil { baseURL = try realpath(baseURL!) } // Deserialize the package. do { self.package = PackageDescription.Package.fromTOML(try TOMLItem.parse(toml), baseURL: baseURL) } catch let err as TOMLParsingError { throw Error.InvalidManifest("unable to parse package dump", errors: err.errors, data: toml) } } public static var filename: String { return "Package.swift" } }
apache-2.0
201dab62a315e4e8449d109b00eb0dd5
37.956284
153
0.628139
4.699407
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Search/ZSSearchInfoViewController.swift
1
6393
// // ZSSearchInfoViewController.swift // zhuishushenqi // // Created by yung on 2019/10/28. // Copyright © 2019 QS. All rights reserved. // import UIKit import SnapKit class ZSSearchInfoViewController: BaseViewController, ZSSearchInfoTableViewCellDelegate, ZSSearchInfoBottomViewDelegate { var model:ZSAikanParserModel? { didSet { } } lazy var tableView:UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.sectionHeaderHeight = 0.01 tableView.sectionFooterHeight = 0.01 if #available(iOS 11, *) { tableView.contentInsetAdjustmentBehavior = .never } tableView.qs_registerCellClass(ZSSearchInfoTableViewCell.self) tableView.qs_registerHeaderFooterClass(ZSBookInfoHeaderView.self) let blurEffect = UIBlurEffect(style: .extraLight) let blurEffectView = UIVisualEffectView(effect: blurEffect) tableView.backgroundView = blurEffectView return tableView }() lazy var bottomView:ZSSearchInfoBottomView = { let view = ZSSearchInfoBottomView(frame: .zero) view.delegate = self return view }() override func viewDidLoad() { super.viewDidLoad() setupSubview() setupNavItem() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = false } override func popAction() { ZSReaderDownloader.share.cancelDownload() super.popAction() } private func setupSubview() { title = model?.bookName view.addSubview(tableView) view.addSubview(bottomView) tableView.snp.remakeConstraints { (make) in make.left.right.equalToSuperview() make.top.equalTo(kNavgationBarHeight) make.height.equalTo(ScreenHeight - kNavgationBarHeight - kTabbarBlankHeight - 60) } bottomView.snp.makeConstraints { (make) in let height = kTabbarBlankHeight + 60 make.left.right.bottom.equalToSuperview() make.height.equalTo(height) } bottomView.configure(book: model!) } private func setupNavItem() { let addItem = UIBarButtonItem(title: "缓存全本", style: UIBarButtonItem.Style.done, target: self, action: #selector(downloadAll)) self.navigationItem.rightBarButtonItem = addItem } @objc private func downloadAll() { guard let book = model else { return } ZSReaderDownloader.share.download(book: book, start: 0) { [weak self] (finished) in self?.tableView.reloadData() } } func infoCell(cell:ZSSearchInfoTableViewCell,click download:UIButton) { guard let indexPath = tableView.indexPath(for: cell) else { return } if let chapter = self.model?.chaptersModel[indexPath.row] { ZSReaderDownloader.share.download(chapter: chapter,book:model!, reg: model!.content) { [weak self] (chapter) in DispatchQueue.main.async { self?.tableView.reloadData() } } } } //MARK: - ZSSearchInfoBottomViewDelegate func bottomView(bottomView: ZSSearchInfoBottomView, clickAdd: UIButton) { let selected = clickAdd.isSelected if selected { if let book = self.model { ZSShelfManager.share.addAikan(book) } } else { if let book = self.model { ZSShelfManager.share.removeAikan(book) } } } func bottomView(bottomView: ZSSearchInfoBottomView, clickRead: UIButton) { guard let book = self.model else { return } if book.chaptersModel.count > 0 { let readerVC = ZSReaderController(chapter: nil, book) readerVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(readerVC, animated: true) } else { alert(with: "提示", message: "找不到该书籍", okTitle: "确定") } } deinit { } } extension ZSSearchInfoViewController:UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.model?.chaptersModel.count ?? 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let book = model { return ZSBookInfoHeaderView.height(for: book) } return 200 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.qs_dequeueReusableHeaderFooterView(ZSBookInfoHeaderView.self) if let book = model { headerView?.configure(model: book) } return headerView } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.qs_dequeueReusableCell(ZSSearchInfoTableViewCell.self) cell?.delegate = self cell?.selectionStyle = .none cell?.accessoryType = .disclosureIndicator if let dict = self.model?.chaptersModel[indexPath.row] { cell?.textLabel?.text = dict.chapterName if let chapter = ZSBookMemoryCache.share.content(for: dict.chapterUrl) { if chapter.chapterContent.length > 0 { cell?.downloadFinish() } } } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let chapters = model?.chaptersModel else { return } let pageVC = ZSReaderController(chapter: chapters[indexPath.row], model!) self.navigationController?.pushViewController(pageVC, animated: true) } }
mit
7705d7aa75118871a5fba170ec01a527
33.215054
133
0.632307
4.999214
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/QuartzDemo/Controllers/LinesController.swift
1
1104
// // LinesController.swift // QuartzDemo // // Created by 伯驹 黄 on 2017/4/7. // Copyright © 2017年 伯驹 黄. All rights reserved. // class LinesController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let quartzLineView = QuartzLineView() view.addSubview(quartzLineView) quartzLineView.translatesAutoresizingMaskIntoConstraints = false quartzLineView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true quartzLineView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true quartzLineView.topAnchor.constraint(equalTo: view.safeTopAnchor).isActive = true quartzLineView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true let image = UIImage(named: "Demo") let imageView = UIImageView(image: image!.kt_drawRectWithRoundedCorner(image!.size.width / 2)) imageView.frame.origin.y = 300 view.addSubview(imageView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
36685825bb5a984bc066944a7710d0a5
33.03125
102
0.711662
4.653846
false
false
false
false
koscida/Kos_AMAD_Spring2015
Spring_16/IGNORE_work/ios_labs/kos_lab_7/kos_lab_7/CountryTableViewController.swift
2
5276
// // CountryTableViewController.swift // kos_lab_7 // // Created by Brittany Kos on 3/28/16. // Copyright © 2016 Kode Studios. All rights reserved. // import UIKit class CountryTableViewController: UITableViewController { var countries : [Country] = [] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = false // load in json country file loadCountriesFile() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadCountriesFile() { //print("in loadCountriesFile()") // get data let filePath = NSBundle.mainBundle().pathForResource("city.list",ofType:"json") let data = NSData(contentsOfFile: filePath!) // store as array var json: [[String: AnyObject]] = [] do { json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! [[String: AnyObject]] } catch { print("Error loading JSON file: \(error)") } //print(json) // parse json, store in tmp var countriesDict = [String: Country]() for city in json { // get city's country data let cityCountry = city["country"] as! String // create a new city let newCity = City(countryId: city["_id"] as! Int, countryName: city["name"] as! String, countryLon: city["coord"]!["lon"] as! Float, countryLat: city["coord"]!["lat"] as! Float) // test if country exists if countriesDict[cityCountry] == nil { let newCountry = Country(countryName: cityCountry, countryCities: []) countriesDict[cityCountry] = newCountry } countriesDict[cityCountry]?.cities.append(newCity) } // alphabetize dict let countriesDictSorted = countriesDict.sort{$0.0 < $1.0} // go through tmp, store in perm for c in countriesDictSorted { // sort cities c.1.cities.sortInPlace({ $0.name < $1.name }) // append country countries.append(c.1) } tableView.reloadData() //print("exit loadCountriesFile()") } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countries.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("countryCell", forIndexPath: indexPath) let country = countries[indexPath.row] cell.textLabel?.text = country.name return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "showCitiesSegue") { let destination = segue.destinationViewController as! CityTableViewController let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)! let selectedCountry = countries[indexPath.row] destination.country = selectedCountry } } }
gpl-3.0
02faeaa6af8a2c2977fa9da8af225956
32.814103
190
0.624834
5.366226
false
false
false
false
seorenn/SRChoco
Source/ViewControllerExtensions.swift
1
1256
// // ViewControllerExtensions.swift // SRChoco // // Created by Heeseung Seo on 2016. 11. 2.. // Copyright © 2016년 Seorenn. All rights reserved. // #if os(iOS) import UIKit public extension UIViewController { static func instance(storyboardName: String? = nil, identifier: String? = nil) -> UIViewController { if let name = identifier { return UIStoryboard(name: storyboardName ?? String(describing: self), bundle: nil).instantiateViewController(withIdentifier: name) } else { return UIStoryboard(name: storyboardName ?? String(describing: self), bundle: nil).instantiateInitialViewController()! } } } #elseif os(macOS) || os(OSX) import Cocoa public extension NSViewController { static func instance(storyboardName: String? = nil, identifier: String? = nil) -> NSViewController { if let name = identifier { return NSStoryboard(name: storyboardName ?? String(describing: self), bundle: nil).instantiateController(withIdentifier: name) as! NSViewController } else { return NSStoryboard(name: storyboardName ?? String(describing: self), bundle: nil).instantiateInitialController() as! NSViewController } } } #endif
mit
b27a2ee48e3abad89f648d0ea027cf30
31.128205
159
0.680766
4.640741
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/VIPER/SearchResults/View/SearchResultsView.swift
1
3139
import UIKit private let ReuseId = "SearchResultsViewCell" final class SearchResultsView: UIView, UITableViewDelegate, UITableViewDataSource { private let tableView = UITableView(frame: .zero, style: .plain) private var searchResults = [SearchResultsViewData]() // MARK: - Init init() { super.init(frame: .zero) addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.separatorColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Internal func reloadWithSearchResults(_ searchResults: [SearchResultsViewData]) { self.searchResults = searchResults tableView.reloadData() } var peekSourceViews: [UIView] { return [tableView] } func peekDataAt( location: CGPoint, sourceView: UIView) -> SearchResultsPeekData? { guard let indexPath = tableView.indexPathForRow(at: location) else { return nil } guard let cell = tableView.cellForRow(at: indexPath) else { return nil } guard indexPath.row < searchResults.count else { return nil } let searchResult = searchResults[indexPath.row] let cellFrameInSourceView = cell.convert(cell.bounds, to: sourceView) return SearchResultsPeekData( viewData: searchResult, sourceRect: cellFrameInSourceView ) } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() tableView.frame = bounds } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: ReuseId) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: ReuseId) cell?.textLabel?.highlightedTextColor = .white } let searchResult = searchResults[(indexPath as NSIndexPath).row] let color = UIColor( red: CGFloat(searchResult.rgb.red), green: CGFloat(searchResult.rgb.green), blue: CGFloat(searchResult.rgb.blue), alpha: 0.3 ) cell?.textLabel?.text = searchResult.title cell?.contentView.backgroundColor = color return cell! } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) searchResults[(indexPath as NSIndexPath).row].onTap() } } struct SearchResultsPeekData { let viewData: SearchResultsViewData let sourceRect: CGRect }
mit
13bf47ad8a0828a2921f7361234865bc
29.182692
100
0.621217
5.412069
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/controller/DZMReadOperation.swift
1
8147
// // DZMReadOperation.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/5/15. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMReadOperation: NSObject { /// 阅读控制器 weak var vc:DZMReadController! // MARK: -- init init(vc:DZMReadController) { super.init() self.vc = vc } // MARK: -- 获取阅读控制器 DZMReadViewController /// 获取阅读View控制器 func GetReadViewController(readRecordModel:DZMReadRecordModel?) ->DZMReadViewController? { if readRecordModel != nil { let readViewController = DZMReadViewController() readViewController.readRecordModel = readRecordModel readViewController.readController = vc return readViewController } return nil } /// 获取当前阅读记录的阅读View控制器 func GetCurrentReadViewController(isUpdateFont:Bool = false, isSave:Bool = false) ->DZMReadViewController? { if isUpdateFont { vc.readModel.readRecordModel.updateFont(isSave: true) } if isSave { readRecordUpdate(readRecordModel: vc.readModel.readRecordModel) } return GetReadViewController(readRecordModel: vc.readModel.readRecordModel.copySelf()) } /// 获取上一页控制器 func GetAboveReadViewController() ->DZMReadViewController? { // 没有阅读模型 if vc.readModel == nil || !vc.readModel.readRecordModel.isRecord {return nil} // 阅读记录 var readRecordModel:DZMReadRecordModel? // 判断 if vc.readModel.isLocalBook.boolValue { // 本地小说 // 获得阅读记录 readRecordModel = vc.readModel.readRecordModel.copySelf() // 章节ID let id = vc.readModel.readRecordModel.readChapterModel!.id.integerValue() // 页码 let page = vc.readModel.readRecordModel.page.intValue // 到头了 if id == 1 && page == 0 {return nil} if page == 0 { // 这一章到头了 readRecordModel?.modify(chapterID: "\(id - 1)", toPage: DZMReadLastPageValue, isUpdateFont:true, isSave: false) }else{ // 没到头 readRecordModel?.page = NSNumber(value: (page - 1)) } }else{ // 网络小说 /* 网络小说操作提示: 1. 获得阅读记录 2. 获得当前章节ID 3. 获得当前阅读章节 读到的页码 4. 判断是否为这一章最后一页 5. 1). 判断不是第一页则 page - 1 继续翻页 2). 如果是第一页则判断上一章的章节ID是否有值,没值就是当前没有跟多章节(连载中)或者 全书完, 有值则判断是否存在缓存文件. 有缓存文件则拿出使用更新阅读记录, 没值则请求服务器获取,请求回来之后可动画展示出来 提示:如果是请求回来之后并更新了阅读记录 可使用 GetCurrentReadViewController() 获得当前阅读记录的控制器 进行展示 */ readRecordModel = nil } return GetReadViewController(readRecordModel: readRecordModel) } /// 获得下一页控制器 func GetBelowReadViewController() ->DZMReadViewController? { // 没有阅读模型 if vc.readModel == nil || !vc.readModel.readRecordModel.isRecord {return nil} // 阅读记录 var readRecordModel:DZMReadRecordModel? // 判断 if vc.readModel.isLocalBook.boolValue { // 本地小说 // 获得阅读记录 readRecordModel = vc.readModel.readRecordModel.copySelf() // 章节ID let id = vc.readModel.readRecordModel.readChapterModel!.id.integerValue() // 页码 let page = vc.readModel.readRecordModel.page.intValue // 最后一页 let lastPage = vc.readModel.readRecordModel.readChapterModel!.pageCount.intValue - 1 // 到头了 if id == vc.readModel.readChapterListModels.count && page == lastPage {return nil} if page == lastPage { // 这一章到头了 readRecordModel?.modify(chapterID: "\(id + 1)", isUpdateFont: true) }else{ // 没到头 readRecordModel?.page = NSNumber(value: (page + 1)) } }else{ // 网络小说 /* 网络小说操作提示: 1. 获得阅读记录 2. 获得当前章节ID 3. 获得当前阅读章节 读到的页码 4. 判断是否为这一章最后一页 5. 1). 判断不是最后一页则 page + 1 继续翻页 2). 如果是最后一页则判断下一章的章节ID是否有值,没值就是当前没有跟多章节(连载中)或者 全书完, 有值则判断是否存在缓存文件. 有缓存文件则拿出使用更新阅读记录, 没值则请求服务器获取,请求回来之后可动画展示出来 提示:如果是请求回来之后并更新了阅读记录 可使用 GetCurrentReadViewController() 获得当前阅读记录的控制器 进行展示 */ readRecordModel = nil } return GetReadViewController(readRecordModel: readRecordModel) } /// 跳转指定章节 指定页码 (toPage: -1 为最后一页 也可以使用 DZMReadLastPageValue) func GoToChapter(chapterID:String, toPage:NSInteger = 0) ->Bool { if vc.readModel != nil { // 有阅读模型 if DZMReadChapterModel.IsExistReadChapterModel(bookID: vc.readModel.bookID, chapterID: chapterID) { // 存在 vc.readModel.modifyReadRecordModel(chapterID: chapterID, page: toPage, isSave: false) vc.creatPageController(GetCurrentReadViewController(isUpdateFont: true, isSave: true)) return true }else{ // 不存在 /* 网络小说操作提示: 1. 请求章节内容 并缓存 2. 修改阅读记录 并展示 */ return false } } return false } // MARK: -- 同步记录 /// 更新记录 func readRecordUpdate(readViewController:DZMReadViewController?, isSave:Bool = true) { readRecordUpdate(readRecordModel: readViewController?.readRecordModel, isSave: isSave) } /// 更新记录 func readRecordUpdate(readRecordModel:DZMReadRecordModel?, isSave:Bool = true) { if readRecordModel != nil { vc.readModel.readRecordModel = readRecordModel if isSave { // 保存 vc.readModel.readRecordModel.save() // 更新UI DispatchQueue.main.async { [weak self] ()->Void in // 进度条数据初始化 self?.vc.readMenu.bottomView.sliderUpdate() } } } } }
apache-2.0
dccd9f2afe58940d16839fed6b8cfafe
27.79668
127
0.494957
4.509422
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/Group/RealmGroupInvitation.swift
1
1062
// // GroupInvitation.swift // Habitica Database // // Created by Phillip Thelen on 22.06.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift @objc class RealmGroupInvitation: Object, GroupInvitationProtocol { @objc dynamic var combinedID: String = "" var id: String? @objc dynamic var userID: String? var name: String? var inviterID: String? var isPartyInvitation: Bool = false var isPublicGuild: Bool = false override static func primaryKey() -> String { return "combinedID" } convenience init(userID: String?, protocolObject: GroupInvitationProtocol) { self.init() combinedID = (userID ?? "") + (protocolObject.id ?? "") self.userID = userID self.id = protocolObject.id self.name = protocolObject.name self.inviterID = protocolObject.inviterID self.isPartyInvitation = protocolObject.isPartyInvitation self.isPublicGuild = protocolObject.isPublicGuild } }
gpl-3.0
4433e704b67fbd3cc3971dcac8199ee8
27.675676
80
0.677663
4.348361
false
false
false
false
Staance/Alamofire
Source/MultipartFormData.swift
1
26999
// MultipartFormData.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif /** Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well and the w3 form documentation. - https://www.ietf.org/rfc/rfc2388.txt - https://www.ietf.org/rfc/rfc2045.txt - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 */ public class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let CRLF = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case Initial, Encapsulated, Final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { let boundaryText: String switch boundaryType { case .Initial: boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" case .Encapsulated: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" case .Final: boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" } return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } } class BodyPart { let headers: [String: String] let bodyStream: NSInputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: NSError? private let streamBufferSize: Int // MARK: - Lifecycle /** Creates a multipart form data object. - returns: The multipart form data object. */ public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /** * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more * information, please refer to the following article: * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html */ self.streamBufferSize = 1024 } // MARK: - Body Parts /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. */ public func appendBodyPart(data data: NSData, name: String) { let headers = contentHeaders(name: name) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, mimeType: String) { let headers = contentHeaders(name: name, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the data and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary - parameter data: The data to encode into the multipart form data. - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. */ public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) let stream = NSInputStream(data: data) let length = UInt64(data.length) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - `Content-Type: #{generated mimeType}` (HTTP Header) - Encoded file data - Multipart form boundary The filename in the `Content-Disposition` HTTP header is generated from the last path component of the `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the system associated MIME type. - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String) { if let fileName = fileURL.lastPathComponent, pathExtension = fileURL.pathExtension { let mimeType = mimeTypeForPathExtension(pathExtension) appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) } else { let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)) } } /** Creates a body part from the file and appends it to the multipart form data object. The body part data will be encoded using the following format: - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - Content-Type: #{mimeType} (HTTP Header) - Encoded file data - Multipart form boundary - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. */ public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.fileURL else { let failureReason = "The file URL does not point to a file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ var isReachable = true if #available(OSX 10.10, iOS 8.0, *) { isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) } else { isReachable = fileURL.checkResourceIsReachableAndReturnError(nil) } guard isReachable else { let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") setBodyPartError(error) return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false guard let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else { let failureReason = "The file URL is a directory, not a file: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ var bodyContentLength: UInt64? do { if let path = fileURL.path, fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber { bodyContentLength = fileSize.unsignedLongLongValue } } catch { // No-op } guard let length = bodyContentLength else { let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) setBodyPartError(error) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = NSInputStream(URL: fileURL) else { let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) setBodyPartError(error) return } appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part from the stream and appends it to the multipart form data object. The body part data will be encoded using the following format: - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - `Content-Type: #{mimeType}` (HTTP Header) - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. */ public func appendBodyPart( stream stream: NSInputStream, length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) appendBodyPart(stream: stream, length: length, headers: headers) } /** Creates a body part with the headers, stream and length and appends it to the multipart form data object. The body part data will be encoded using the following format: - HTTP headers - Encoded stream data - Multipart form boundary - parameter stream: The input stream to encode in the multipart form data. - parameter length: The content length of the stream. - parameter headers: The HTTP headers for the body part. */ public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /** Encodes all the appended body parts into a single `NSData` object. It is important to note that this method will load all the appended body parts into memory all at the same time. This method should only be used when the encoded data will have a small memory footprint. For large data cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - throws: An `NSError` if encoding encounters an error. - returns: The encoded `NSData` if encoding is successful. */ public func encode() throws -> NSData { if let bodyPartError = bodyPartError { throw bodyPartError } let encoded = NSMutableData() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encodeBodyPart(bodyPart) encoded.appendData(encodedData) } return encoded } /** Writes the appended body parts into the given file URL. This process is facilitated by reading and writing with input and output streams, respectively. Thus, this approach is very memory efficient and should be used for large body part data. - parameter fileURL: The file URL to write the multipart form data into. - throws: An `NSError` if encoding encounters an error. */ public func writeEncodedDataToDisk(fileURL: NSURL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { let failureReason = "A file already exists at the given file URL: \(fileURL)" throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } else if !fileURL.fileURL { let failureReason = "The URL does not point to a valid file: \(fileURL)" throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason) } let outputStream: NSOutputStream if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { outputStream = possibleOutputStream } else { let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason) } outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) outputStream.open() self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try writeBodyPart(bodyPart, toOutputStream: outputStream) } outputStream.close() outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } // MARK: - Private - Body Part Encoding private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { let encoded = NSMutableData() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.appendData(initialData) let headerData = encodeHeaderDataForBodyPart(bodyPart) encoded.appendData(headerData) let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) encoded.appendData(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.appendData(finalBoundaryData()) } return encoded } private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" } headerText += EncodingCharacters.CRLF return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() var error: NSError? let encoded = NSMutableData() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if inputStream.streamError != nil { error = inputStream.streamError break } if bytesRead > 0 { encoded.appendBytes(buffer, length: bytesRead) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) break } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) if let error = error { throw error } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) } private func writeInitialBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try writeData(initialData, toOutputStream: outputStream) } private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let headerData = encodeHeaderDataForBodyPart(bodyPart) return try writeData(headerData, toOutputStream: outputStream) } private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) inputStream.open() while inputStream.hasBytesAvailable { var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw streamError } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } try writeBuffer(&buffer, toOutputStream: outputStream) } else if bytesRead < 0 { let failureReason = "Failed to read from input stream: \(inputStream)" throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason) } else { break } } inputStream.close() inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) } private func writeFinalBoundaryDataForBodyPart( bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { if bodyPart.hasFinalBoundary { return try writeData(finalBoundaryData(), toOutputStream: outputStream) } } // MARK: - Private - Writing Buffered Data to Output Stream private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws { var buffer = [UInt8](count: data.length, repeatedValue: 0) data.getBytes(&buffer, length: data.length) return try writeBuffer(&buffer, toOutputStream: outputStream) } private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws { var bytesToWrite = buffer.count while bytesToWrite > 0 { if outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let streamError = outputStream.streamError { throw streamError } if bytesWritten < 0 { let failureReason = "Failed to write to output stream: \(outputStream)" throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } else if let streamError = outputStream.streamError { throw streamError } } } // MARK: - Private - Mime Type private func mimeTypeForPathExtension(pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(name name: String) -> [String: String] { return ["Content-Disposition": "form-data; name=\"\(name)\""] } private func contentHeaders(name name: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"", "Content-Type": "\(mimeType)" ] } private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { return [ "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", "Content-Type": "\(mimeType)" ] } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) } private func encapsulatedBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) } private func finalBoundaryData() -> NSData { return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(error: NSError) { if bodyPartError == nil { bodyPartError = error } } }
mit
63cb4826122eb9ddd14e9ef60282f11f
39.233979
128
0.638886
5.221857
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/Feedly/Models/FeedlyEntryParser.swift
1
3235
// // FeedlyEntryParser.swift // Account // // Created by Kiel Gillard on 3/10/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation import Articles import RSParser struct FeedlyEntryParser { let entry: FeedlyEntry private let rightToLeftTextSantizer = FeedlyRTLTextSanitizer() var id: String { return entry.id } /// When ingesting articles, the feedURL must match a feed's `webFeedID` for the article to be reachable between it and its matching feed. It reminds me of a foreign key. var feedUrl: String? { guard let id = entry.origin?.streamId else { // At this point, check Feedly's API isn't glitching or the response has not changed structure. assertionFailure("Entries need to be traceable to a feed or this entry will be dropped.") return nil } return id } /// Convoluted external URL logic "documented" here: /// https://groups.google.com/forum/#!searchin/feedly-cloud/feed$20url%7Csort:date/feedly-cloud/Rx3dVd4aTFQ/Hf1ZfLJoCQAJ var externalUrl: String? { let multidimensionalArrayOfLinks = [entry.canonical, entry.alternate] let withExistingValues = multidimensionalArrayOfLinks.compactMap { $0 } let flattened = withExistingValues.flatMap { $0 } let webPageLinks = flattened.filter { $0.type == nil || $0.type == "text/html" } return webPageLinks.first?.href } var title: String? { return rightToLeftTextSantizer.sanitize(entry.title) } var contentHMTL: String? { return entry.content?.content ?? entry.summary?.content } var contentText: String? { // We could strip HTML from contentHTML? return nil } var summary: String? { return rightToLeftTextSantizer.sanitize(entry.summary?.content) } var datePublished: Date { return entry.crawled } var dateModified: Date? { return entry.recrawled } var authors: Set<ParsedAuthor>? { guard let name = entry.author else { return nil } return Set([ParsedAuthor(name: name, url: nil, avatarURL: nil, emailAddress: nil)]) } /// While there is not yet a tagging interface, articles can still be searched for by tags. var tags: Set<String>? { guard let labels = entry.tags?.compactMap({ $0.label }), !labels.isEmpty else { return nil } return Set(labels) } var attachments: Set<ParsedAttachment>? { guard let enclosure = entry.enclosure, !enclosure.isEmpty else { return nil } let attachments = enclosure.compactMap { ParsedAttachment(url: $0.href, mimeType: $0.type, title: nil, sizeInBytes: nil, durationInSeconds: nil) } return attachments.isEmpty ? nil : Set(attachments) } var parsedItemRepresentation: ParsedItem? { guard let feedUrl = feedUrl else { return nil } return ParsedItem(syncServiceID: id, uniqueID: id, // This value seems to get ignored or replaced. feedURL: feedUrl, url: nil, externalURL: externalUrl, title: title, language: nil, contentHTML: contentHMTL, contentText: contentText, summary: summary, imageURL: nil, bannerImageURL: nil, datePublished: datePublished, dateModified: dateModified, authors: authors, tags: tags, attachments: attachments) } }
mit
b9dfcff6706e850fe0f416ce8e4cc161
27.619469
171
0.70068
3.625561
false
false
false
false
ndleon09/TopApps
TopApps/AppDetailViewController.swift
1
1310
// // AppDetailViewController.swift // TopApps // // Created by Nelson Dominguez on 24/04/16. // Copyright © 2016 Nelson Dominguez. All rights reserved. // import Foundation import UIKit import AlamofireImage class AppDetailViewController: TopAppsViewController, AppDetailUI { @IBOutlet weak var appIconImageView: UIImageView! @IBOutlet weak var appNameLabel: UILabel! @IBOutlet weak var appCategoryLabel: UILabel! @IBOutlet weak var appDescriptionLabel: UITextView! func show(app: App?) { guard let app = app, let url = app.image else { return } let radius: CGFloat = 8.0 let filter = AspectScaledToFillSizeWithRoundedCornersFilter( size: appIconImageView.frame.size, radius: radius ) let placeholder = UIImage(named: "placeholder")?.af_imageRounded(withCornerRadius: radius) appIconImageView?.af_setImage(withURL: URL(string: url)!, placeholderImage: placeholder, filter: filter, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.5), runImageTransitionIfCached: false, completion: nil) appNameLabel.text = app.name appCategoryLabel.text = app.category appDescriptionLabel.text = app.summary } }
mit
83e3f77b8ed916e69a00b4d9ebc4ff85
33.447368
252
0.689076
4.794872
false
false
false
false
DivineDominion/mac-multiproc-code
RelocationManagerServiceDomain/PersistentStack.swift
1
5721
// // PersistentStack.swift // RelocationManagerServiceDomain // // Created by Christian Tietze on 16.11.14. // Copyright (c) 2014 Christian Tietze. All rights reserved. // import Cocoa import CoreData public let kDefaultModelName = "RelocationManager" public let kDefaultStoreName = "ItemModel.sqlite" let kErrorDomain = "de.christiantietze.RelocationManager.Service" public class PersistentStack: NSObject { let storeType = NSSQLiteStoreType let storeURL: NSURL let modelURL: NSURL let errorHandler: HandlesError public var managedObjectContext: NSManagedObjectContext? // TODO forbid init() public init(storeURL: NSURL, modelURL: NSURL, errorHandler: HandlesError) { self.storeURL = storeURL self.modelURL = modelURL self.errorHandler = errorHandler super.init() self.setupManagedObjectContext() } func setupManagedObjectContext() { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return } let managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator self.managedObjectContext = managedObjectContext } /// Optional attribute because file operation could fail. public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { var error: NSError? = nil // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let storeOptions = self.defaultStoreOptions() var store = coordinator!.addPersistentStoreWithType(self.storeType, configuration: nil, URL: self.storeURL, options: storeOptions, error: &error) if store == nil { let error = wrapError(error, message: "Failed to initialize the application's saved data", reason: "There was an error creating or loading the application's saved data.") self.errorHandler.handle(error) return nil } return coordinator }() /// Required attribute because it's fatal if the `managedObjectModel` cannot be loaded. public lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource(kDefaultModelName, withExtension: "mom")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() // MARK: - Core Data Saving and Undo support public func objectContextWillSave() { // TODO: update creation/modification dates } public func save() { // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. if let moc = self.managedObjectContext { if !moc.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving") } var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { let error = wrapError(error, message: "Failed to save to data store") errorHandler.handle(error) } } } public func undoManager() -> NSUndoManager? { if let moc = self.managedObjectContext { return moc.undoManager } return nil } public func defaultStoreOptions() -> [String: String] { let opts = [String: String]() return opts } /// Save changes in the application's managed object context before the application terminates. public func saveToTerminate(sender: NSApplication) -> NSApplicationTerminateReply { if managedObjectContext == nil { return .TerminateNow } let moc = managedObjectContext! if !moc.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate") return .TerminateCancel } if !moc.hasChanges { return .TerminateNow } var error: NSError? = nil if !moc.save(&error) { let error = wrapError(error, message: "Failed to save to data store") errorHandler.handle(error) // Customize this code block to include application-specific recovery steps. let result = sender.presentError(error) if (result) { return .TerminateCancel } let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") let alert = NSAlert() alert.messageText = question alert.informativeText = info alert.addButtonWithTitle(quitButton) alert.addButtonWithTitle(cancelButton) let answer = alert.runModal() if answer == NSAlertFirstButtonReturn { return .TerminateCancel } } return .TerminateNow } }
mit
3c51569c37900214068a7532cc7b6f9d
36.638158
186
0.636252
5.755533
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/Delay.swift
53
5548
// // Delay.swift // RxSwift // // Created by tarunon on 2016/02/09. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation class DelaySink<ElementType, O: ObserverType> : Sink<O> , ObserverType where O.E == ElementType { typealias E = O.E typealias Source = Observable<E> typealias DisposeKey = Bag<Disposable>.KeyType private let _lock = NSRecursiveLock() private let _dueTime: RxTimeInterval private let _scheduler: SchedulerType private let _sourceSubscription = SingleAssignmentDisposable() private let _cancelable = SerialDisposable() // is scheduled some action private var _active = false // is "run loop" on different scheduler running private var _running = false private var _errorEvent: Event<E>? = nil // state private var _queue = Queue<(eventTime: RxTime, event: Event<E>)>(capacity: 0) private var _disposed = false init(observer: O, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { _dueTime = dueTime _scheduler = scheduler super.init(observer: observer, cancel: cancel) } // All of these complications in this method are caused by the fact that // error should be propagated immediatelly. Error can bepotentially received on different // scheduler so this process needs to be synchronized somehow. // // Another complication is that scheduler is potentially concurrent so internal queue is used. func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { _lock.lock() // { let hasFailed = _errorEvent != nil if !hasFailed { _running = true } _lock.unlock() // } if hasFailed { return } var ranAtLeastOnce = false while true { _lock.lock() // { let errorEvent = _errorEvent let eventToForwardImmediatelly = ranAtLeastOnce ? nil : _queue.dequeue()?.event let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !_queue.isEmpty ? _queue.peek().eventTime : nil if let _ = errorEvent { } else { if let _ = eventToForwardImmediatelly { } else if let _ = nextEventToScheduleOriginalTime { _running = false } else { _running = false _active = false } } _lock.unlock() // { if let errorEvent = errorEvent { self.forwardOn(errorEvent) self.dispose() return } else { if let eventToForwardImmediatelly = eventToForwardImmediatelly { ranAtLeastOnce = true self.forwardOn(eventToForwardImmediatelly) if case .completed = eventToForwardImmediatelly { self.dispose() return } } else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { let elapsedTime = _scheduler.now.timeIntervalSince(nextEventToScheduleOriginalTime) let interval = _dueTime - elapsedTime let normalizedInterval = interval < 0.0 ? 0.0 : interval scheduler.schedule((), dueTime: normalizedInterval) return } else { return } } } } func on(_ event: Event<E>) { if event.isStopEvent { _sourceSubscription.dispose() } switch event { case .error(_): _lock.lock() // { let shouldSendImmediatelly = !_running _queue = Queue(capacity: 0) _errorEvent = event _lock.unlock() // } if shouldSendImmediatelly { forwardOn(event) dispose() } default: _lock.lock() // { let shouldSchedule = !_active _active = true _queue.enqueue((_scheduler.now, event)) _lock.unlock() // } if shouldSchedule { _cancelable.disposable = _scheduler.scheduleRecursive((), dueTime: _dueTime, action: self.drainQueue) } } } func run(source: Source) -> Disposable { _sourceSubscription.setDisposable(source.subscribeSafe(self)) return Disposables.create(_sourceSubscription, _cancelable) } } class Delay<Element>: Producer<Element> { private let _source: Observable<Element> private let _dueTime: RxTimeInterval private let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { _source = source _dueTime = dueTime _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DelaySink(observer: observer, dueTime: _dueTime, scheduler: _scheduler, cancel: cancel) let subscription = sink.run(source: _source) return (sink: sink, subscription: subscription) } }
mit
1023f1193ed31521e2f66b20516eedc3
32.823171
145
0.55183
5.343931
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/Bundle.swift
1
17299
// 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 // @_implementationOnly import CoreFoundation @_silgen_name("swift_getTypeContextDescriptor") private func _getTypeContextDescriptor(of cls: AnyClass) -> UnsafeRawPointer open class Bundle: NSObject { private var _bundleStorage: AnyObject! private final var _bundle: CFBundle! { get { unsafeBitCast(_bundleStorage, to: CFBundle?.self) } set { _bundleStorage = newValue } } public static var _supportsFHSBundles: Bool { #if DEPLOYMENT_RUNTIME_OBJC return false #else return _CFBundleSupportsFHSBundles() #endif } public static var _supportsFreestandingBundles: Bool { #if DEPLOYMENT_RUNTIME_OBJC return false #else return _CFBundleSupportsFreestandingBundles() #endif } private static var _mainBundle : Bundle = { return Bundle(cfBundle: CFBundleGetMainBundle()) }() open class var main: Bundle { get { return _mainBundle } } private class var allBundlesRegardlessOfType: [Bundle] { // FIXME: This doesn't return bundles that weren't loaded using CFBundle or class Bundle. https://bugs.swift.org/browse/SR-10433 guard let bundles = CFBundleGetAllBundles()?._swiftObject as? [CFBundle] else { return [] } return bundles.map(Bundle.init(cfBundle:)) } private var isFramework: Bool { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) return bundleURL.pathExtension == "framework" #else #if os(Windows) if let name = _CFBundleCopyExecutablePath(_bundle)?._nsObject { return name.pathExtension.lowercased == "dll" } #else // We're assuming this is an OS like Linux or BSD that uses FHS-style library names (lib….so or lib….so.2.3.4) if let name = _CFBundleCopyExecutablePath(_bundle)?._nsObject { return name.hasPrefix("lib") && (name.pathExtension == "so" || name.range(of: ".so.").location != NSNotFound) } #endif return false #endif } open class var allBundles: [Bundle] { return allBundlesRegardlessOfType.filter { !$0.isFramework } } open class var allFrameworks: [Bundle] { return allBundlesRegardlessOfType.filter { $0.isFramework } } internal init(cfBundle: CFBundle) { super.init() _bundle = cfBundle } public init?(path: String) { super.init() // TODO: We do not yet resolve symlinks, but we must for compatibility // let resolvedPath = path._nsObject.stringByResolvingSymlinksInPath let resolvedPath = path guard resolvedPath.length > 0 else { return nil } let url = URL(fileURLWithPath: resolvedPath) _bundleStorage = CFBundleCreate(kCFAllocatorSystemDefault, url._cfObject) if (_bundleStorage == nil) { return nil } } public convenience init?(url: URL) { self.init(path: url.path) } #if os(Windows) @available(Windows, deprecated, message: "Not yet implemented.") public init(for aClass: AnyClass) { NSUnimplemented() } #else public init(for aClass: AnyClass) { let pointerInImageOfClass = _getTypeContextDescriptor(of: aClass) guard let imagePath = _CFBundleCopyLoadedImagePathForAddress(pointerInImageOfClass)?._swiftObject else { _bundleStorage = CFBundleGetMainBundle() return } let path = (try? FileManager.default._canonicalizedPath(toFileAtPath: imagePath)) ?? imagePath let url = URL(fileURLWithPath: path) if Bundle.main.executableURL == url { _bundleStorage = CFBundleGetMainBundle() return } for bundle in Bundle.allBundlesRegardlessOfType { if bundle.executableURL == url { _bundleStorage = bundle._bundle return } } let bundle = _CFBundleCreateWithExecutableURLIfMightBeBundle(kCFAllocatorSystemDefault, url._cfObject)?.takeRetainedValue() _bundleStorage = bundle ?? CFBundleGetMainBundle() } #endif public init?(identifier: String) { super.init() guard let result = CFBundleGetBundleWithIdentifier(identifier._cfObject) else { return nil } _bundle = result } public convenience init?(_executableURL: URL) { guard let bundleURL = _CFBundleCopyBundleURLForExecutableURL(_executableURL._cfObject)?.takeRetainedValue() else { return nil } self.init(url: bundleURL._swiftObject) } override open var description: String { return "\(String(describing: Bundle.self)) <\(bundleURL.path)> (\(isLoaded ? "loaded" : "not yet loaded"))" } /* Methods for loading and unloading bundles. */ open func load() -> Bool { return CFBundleLoadExecutable(_bundle) } open var isLoaded: Bool { return CFBundleIsExecutableLoaded(_bundle) } @available(*,deprecated,message:"Not available on non-Darwin platforms") open func unload() -> Bool { NSUnsupported() } open func preflight() throws { var unmanagedError:Unmanaged<CFError>? = nil try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in CFBundlePreflightExecutable(_bundle, unmanagedCFError) if let error = unmanagedCFError.pointee { throw error.takeRetainedValue()._nsObject } } } open func loadAndReturnError() throws { var unmanagedError:Unmanaged<CFError>? = nil try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in CFBundleLoadExecutableAndReturnError(_bundle, unmanagedCFError) if let error = unmanagedCFError.pointee { let retainedValue = error.takeRetainedValue() throw retainedValue._nsObject } } } /* Methods for locating various components of a bundle. */ open var bundleURL: URL { return CFBundleCopyBundleURL(_bundle)._swiftObject } open var resourceURL: URL? { return CFBundleCopyResourcesDirectoryURL(_bundle)?._swiftObject } open var executableURL: URL? { return CFBundleCopyExecutableURL(_bundle)?._swiftObject } open func url(forAuxiliaryExecutable executableName: String) -> URL? { return CFBundleCopyAuxiliaryExecutableURL(_bundle, executableName._cfObject)?._swiftObject } open var privateFrameworksURL: URL? { return CFBundleCopyPrivateFrameworksURL(_bundle)?._swiftObject } open var sharedFrameworksURL: URL? { return CFBundleCopySharedFrameworksURL(_bundle)?._swiftObject } open var sharedSupportURL: URL? { return CFBundleCopySharedSupportURL(_bundle)?._swiftObject } open var builtInPlugInsURL: URL? { return CFBundleCopyBuiltInPlugInsURL(_bundle)?._swiftObject } open var appStoreReceiptURL: URL? { // Always nil on this platform return nil } open var bundlePath: String { return bundleURL.path } open var resourcePath: String? { return resourceURL?.path } open var executablePath: String? { return executableURL?.path } open func path(forAuxiliaryExecutable executableName: String) -> String? { return url(forAuxiliaryExecutable: executableName)?.path } open var privateFrameworksPath: String? { return privateFrameworksURL?.path } open var sharedFrameworksPath: String? { return sharedFrameworksURL?.path } open var sharedSupportPath: String? { return sharedSupportURL?.path } open var builtInPlugInsPath: String? { return builtInPlugInsURL?.path } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Class open class func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, in bundleURL: URL) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLInDirectory(bundleURL._cfObject, name?._cfObject, ext?._cfObject, subpath?._cfObject)._swiftObject } open class func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, in bundleURL: NSURL) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeInDirectory(bundleURL._cfObject, ext?._cfObject, subpath?._cfObject)._nsObject as? [NSURL] } // ----------------------------------------------------------------------------------- // MARK: - URL Resource Lookup - Instance open func url(forResource name: String?, withExtension ext: String?) -> URL? { return self.url(forResource: name, withExtension: ext, subdirectory: nil) } open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURL(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject)?._swiftObject } open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> URL? { // If both name and ext are nil/zero-length, return nil if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) { return nil } return CFBundleCopyResourceURLForLocalization(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._swiftObject } open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfType(_bundle, ext?._cfObject, subpath?._cfObject)?._nsObject as? [NSURL] } open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> [NSURL]? { return CFBundleCopyResourceURLsOfTypeForLocalization(_bundle, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._nsObject as? [NSURL] } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Class open class func path(forResource name: String?, ofType ext: String?, inDirectory bundlePath: String) -> String? { return Bundle.url(forResource: name, withExtension: ext, subdirectory: bundlePath, in: URL(fileURLWithPath: bundlePath))?.path } open class func paths(forResourcesOfType ext: String?, inDirectory bundlePath: String) -> [String] { // Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway return urls(forResourcesWithExtension: ext, subdirectory: bundlePath, in: NSURL(fileURLWithPath: bundlePath))?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Path Resource Lookup - Instance open func path(forResource name: String?, ofType ext: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: nil)?.path } open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: subpath)?.path } open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> String? { return self.url(forResource: name, withExtension: ext, subdirectory: subpath, localization: localizationName)?.path } open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?) -> [String] { // Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway return self.urls(forResourcesWithExtension: ext, subdirectory: subpath)?.map { $0.path! } ?? [] } open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] { // Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway return self.urls(forResourcesWithExtension: ext, subdirectory: subpath, localization: localizationName)?.map { $0.path! } ?? [] } // ----------------------------------------------------------------------------------- // MARK: - Localized Strings open func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { let localizedString = CFBundleCopyLocalizedString(_bundle, key._cfObject, value?._cfObject, tableName?._cfObject)! return localizedString._swiftObject } // ----------------------------------------------------------------------------------- // MARK: - Other open var bundleIdentifier: String? { return CFBundleGetIdentifier(_bundle)?._swiftObject } open var infoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetInfoDictionary(_bundle) return __SwiftValue.fetch(cfDict) as? [String : Any] } open var localizedInfoDictionary: [String : Any]? { let cfDict: CFDictionary? = CFBundleGetLocalInfoDictionary(_bundle) return __SwiftValue.fetch(cfDict) as? [String : Any] } open func object(forInfoDictionaryKey key: String) -> Any? { if let localizedInfoDictionary = localizedInfoDictionary { return localizedInfoDictionary[key] } else { return infoDictionary?[key] } } open func classNamed(_ className: String) -> AnyClass? { // FIXME: This will return a class that may not be associated with the receiver. https://bugs.swift.org/browse/SR-10347. guard isLoaded || load() else { return nil } return NSClassFromString(className) } open var principalClass: AnyClass? { // NB: Cross-platform Swift doesn't have a notion of 'the first class in the ObjC segment' that ObjC platforms have. For swift-corelibs-foundation, if a bundle doesn't have a principal class named, the principal class is nil. guard let name = infoDictionary?["NSPrincipalClass"] as? String else { return nil } return classNamed(name) } open var preferredLocalizations: [String] { return Bundle.preferredLocalizations(from: localizations) } open var localizations: [String] { let cfLocalizations: CFArray? = CFBundleCopyBundleLocalizations(_bundle) let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } open var developmentLocalization: String? { let region = CFBundleGetDevelopmentRegion(_bundle)! return region._swiftObject } open class func preferredLocalizations(from localizationsArray: [String]) -> [String] { let cfLocalizations: CFArray? = CFBundleCopyPreferredLocalizationsFromArray(localizationsArray._cfObject) let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any] return nsLocalizations?.map { $0 as! String } ?? [] } open class func preferredLocalizations(from localizationsArray: [String], forPreferences preferencesArray: [String]?) -> [String] { let localizations = CFBundleCopyLocalizationsForPreferences(localizationsArray._cfObject, preferencesArray?._cfObject)! return localizations._swiftObject.map { return ($0 as! NSString)._swiftObject } } open var executableArchitectures: [NSNumber]? { let architectures = CFBundleCopyExecutableArchitectures(_bundle)! return architectures._swiftObject.map() { $0 as! NSNumber } } open override func isEqual(_ object: Any?) -> Bool { guard let bundle = object as? Bundle else { return false } return CFEqual(_bundle, bundle._bundle) } open override var hash: Int { return Int(bitPattern: CFHash(_bundle)) } }
apache-2.0
54b3b5138fe863494d309d712fd8b065
38.667431
233
0.628101
4.997111
false
false
false
false
pablogsIO/MadridShops
MadridShopsTests/Cache/SaveShopsTest.swift
1
1333
// // SaveShopsTest.swift // MadridShopsTests // // Created by Pablo García on 29/09/2017. // Copyright © 2017 KC. All rights reserved. // import XCTest @testable import MadridShops class SaveShopsTest: XCTestCase { var cdiList: CityDataInformationList? override func setUp() { super.setUp() let expectationTest = expectation(description: "Expectations") let downloadCDI = DownloadCityDataInformationInteractorNSURLSessionImpl() downloadCDI.execute(urlString: Constants.urlMadridShops){(cityDataInformationList: CityDataInformationList) in self.cdiList = cityDataInformationList expectationTest.fulfill() } waitForExpectations(timeout: 20.0, handler:nil) } func testSaveShops(){ let expectationTest = expectation(description: "Expectations") let cacheShops = SaveCityDataInformationListInteractorImpl() let coreData = CoreDataStack() let context = coreData.createContainer(dbName: Constants.coreDataPersistenceContainerModelName).viewContext cacheShops.execute(mapCityDataInformationToEntiy: mapCityDataInformationIntoShop, cityDataInformationList: cdiList!, context: context, onSuccess: { (cdiList) in expectationTest.fulfill() XCTAssert(true) }) { (_) in XCTAssert(false) } waitForExpectations(timeout: 20.0, handler:nil) } }
mit
b18933b689aba680ae34f3adb38a589b
25.62
162
0.75432
3.891813
false
true
false
false
polishedcode/tasty-imitation-keyboard
Keyboard/Shapes.swift
1
13987
// // Shapes.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 10/5/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF /////////////////// // SHAPE OBJECTS // /////////////////// class BackspaceShape: Shape { override func drawCall(_ color: UIColor) { drawBackspace(self.bounds, color: color) } } class ShiftShape: Shape { var withLock: Bool = false { didSet { self.overflowCanvas.setNeedsDisplay() } } override func drawCall(_ color: UIColor) { drawShift(self.bounds, color: color, withRect: self.withLock) } } class GlobeShape: Shape { override func drawCall(_ color: UIColor) { drawGlobe(self.bounds, color: color) } } class Shape: UIView { var color: UIColor? { didSet { if self.color != nil { self.overflowCanvas.setNeedsDisplay() } } } // in case shapes draw out of bounds, we still want them to show var overflowCanvas: OverflowCanvas! convenience init() { self.init(frame: CGRect.zero) } override required init(frame: CGRect) { super.init(frame: frame) self.isOpaque = false self.clipsToBounds = false self.overflowCanvas = OverflowCanvas(shape: self) self.addSubview(self.overflowCanvas) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var oldBounds: CGRect? override func layoutSubviews() { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && self.bounds.equalTo(oldBounds!) { return } oldBounds = self.bounds super.layoutSubviews() let overflowCanvasSizeRatio = CGFloat(1.25) let overflowCanvasSize = CGSize(width: self.bounds.width * overflowCanvasSizeRatio, height: self.bounds.height * overflowCanvasSizeRatio) self.overflowCanvas.frame = CGRect( x: CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0), y: CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0), width: overflowCanvasSize.width, height: overflowCanvasSize.height) self.overflowCanvas.setNeedsDisplay() } func drawCall(_ color: UIColor) { /* override me! */ } class OverflowCanvas: UIView { unowned var shape: Shape init(shape: Shape) { self.shape = shape super.init(frame: CGRect.zero) self.isOpaque = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2) let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2) ctx?.translateBy(x: xOffset, y: yOffset) self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.black) ctx?.restoreGState() } } } ///////////////////// // SHAPE FUNCTIONS // ///////////////////// func getFactors(_ fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) { let xSize = { () -> CGFloat in let scaledSize = (fromSize.width / CGFloat(2)) if scaledSize > toRect.width { return (toRect.width / scaledSize) / CGFloat(2) } else { return CGFloat(0.5) } }() let ySize = { () -> CGFloat in let scaledSize = (fromSize.height / CGFloat(2)) if scaledSize > toRect.height { return (toRect.height / scaledSize) / CGFloat(2) } else { return CGFloat(0.5) } }() let actualSize = min(xSize, ySize) return (actualSize, actualSize, actualSize, false, 0) } func centerShape(_ fromSize: CGSize, toRect: CGRect) { let xOffset = (toRect.width - fromSize.width) / CGFloat(2) let yOffset = (toRect.height - fromSize.height) / CGFloat(2) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() ctx?.translateBy(x: xOffset, y: yOffset) } func endCenter() { let ctx = UIGraphicsGetCurrentContext() ctx?.restoreGState() } func drawBackspace(_ bounds: CGRect, color: UIColor) { let factors = getFactors(CGSize(width: 44, height: 32), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor centerShape(CGSize(width: 44 * xScalingFactor, height: 32 * yScalingFactor), toRect: bounds) //// Color Declarations let color = color let color2 = UIColor.gray // TODO: //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 26 * yScalingFactor), controlPoint1: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 22 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 36 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 0 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 32 * xScalingFactor, y: 0 * yScalingFactor), controlPoint2: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.close() color.setFill() bezierPath.fill() //// Bezier 2 Drawing let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor)) bezier2Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 22 * yScalingFactor)) bezier2Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor)) bezier2Path.close() UIColor.gray.setFill() bezier2Path.fill() color2.setStroke() bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor bezier2Path.stroke() //// Bezier 3 Drawing let bezier3Path = UIBezierPath() bezier3Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor)) bezier3Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 10 * yScalingFactor)) bezier3Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor)) bezier3Path.close() UIColor.red.setFill() bezier3Path.fill() color2.setStroke() bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor bezier3Path.stroke() endCenter() } func drawShift(_ bounds: CGRect, color: UIColor, withRect: Bool) { let factors = getFactors(CGSize(width: 38, height: (withRect ? 34 + 4 : 32)), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor centerShape(CGSize(width: 38 * xScalingFactor, height: (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds) //// Color Declarations let color2 = color //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 19 * xScalingFactor, y: 0 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 14 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor), controlPoint2: CGPoint(x: 10 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 28 * yScalingFactor), controlPoint1: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 32 * yScalingFactor)) bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor), controlPoint1: CGPoint(x: 28 * xScalingFactor, y: 26 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor)) bezierPath.close() color2.setFill() bezierPath.fill() if withRect { //// Rectangle Drawing let rectanglePath = UIBezierPath(rect: CGRect(x: 10 * xScalingFactor, y: 34 * yScalingFactor, width: 18 * xScalingFactor, height: 4 * yScalingFactor)) color2.setFill() rectanglePath.fill() } endCenter() } func drawGlobe(_ bounds: CGRect, color: UIColor) { let factors = getFactors(CGSize(width: 41, height: 40), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor centerShape(CGSize(width: 41 * xScalingFactor, height: 40 * yScalingFactor), toRect: bounds) //// Color Declarations let color = color //// Oval Drawing let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0 * xScalingFactor, y: 0 * yScalingFactor, width: 40 * xScalingFactor, height: 40 * yScalingFactor)) color.setStroke() ovalPath.lineWidth = 1 * lineWidthScalingFactor ovalPath.stroke() //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 40 * yScalingFactor)) bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor)) bezierPath.close() color.setStroke() bezierPath.lineWidth = 1 * lineWidthScalingFactor bezierPath.stroke() //// Bezier 2 Drawing let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor)) bezier2Path.addLine(to: CGPoint(x: 39.5 * xScalingFactor, y: 19.5 * yScalingFactor)) bezier2Path.addLine(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor)) bezier2Path.close() color.setStroke() bezier2Path.lineWidth = 1 * lineWidthScalingFactor bezier2Path.stroke() //// Bezier 3 Drawing let bezier3Path = UIBezierPath() bezier3Path.move(to: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor)) bezier3Path.addCurve(to: CGPoint(x: 21.63 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor), controlPoint2: CGPoint(x: 41 * xScalingFactor, y: 19 * yScalingFactor)) bezier3Path.lineCapStyle = CGLineCap.round; color.setStroke() bezier3Path.lineWidth = 1 * lineWidthScalingFactor bezier3Path.stroke() //// Bezier 4 Drawing let bezier4Path = UIBezierPath() bezier4Path.move(to: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor)) bezier4Path.addCurve(to: CGPoint(x: 18.72 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor), controlPoint2: CGPoint(x: -2.5 * xScalingFactor, y: 19.04 * yScalingFactor)) bezier4Path.lineCapStyle = CGLineCap.round; color.setStroke() bezier4Path.lineWidth = 1 * lineWidthScalingFactor bezier4Path.stroke() //// Bezier 5 Drawing let bezier5Path = UIBezierPath() bezier5Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor)) bezier5Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 7 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 21 * yScalingFactor)) bezier5Path.lineCapStyle = CGLineCap.round; color.setStroke() bezier5Path.lineWidth = 1 * lineWidthScalingFactor bezier5Path.stroke() //// Bezier 6 Drawing let bezier6Path = UIBezierPath() bezier6Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor)) bezier6Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 33 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 22 * yScalingFactor)) bezier6Path.lineCapStyle = CGLineCap.round; color.setStroke() bezier6Path.lineWidth = 1 * lineWidthScalingFactor bezier6Path.stroke() endCenter() }
bsd-3-clause
7a1bf9dd12f8fc926b83d46d8fa395e6
38.623229
244
0.654894
3.895015
false
false
false
false
JohnSansoucie/MyProject2
BlueCapKit/Service Profile Definitions/TISensorTagServiceProfiles.swift
1
57109
// // TISensorTagServiceProfiles.swift // BlueCap // // Created by Troy Stribling on 7/6/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import Foundation import CoreBluetooth import BlueCapKit public struct TISensorTag { //*************************************************************************************************** // Accelerometer Service public struct AccelerometerService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA10-0451-4000-B000-000000000000" public static let name = "TI Accelerometer" public static let tag = "TI Sensor Tag" // Accelerometer Data public struct Data : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { private let xRaw:Int8 private let yRaw:Int8 private let zRaw:Int8 public let x:Double public let y:Double public let z:Double public init?(x:Double, y:Double, z:Double) { self.x = x self.y = y self.z = z if let rawValues = Data.rawFromValues([x, y, z]) { (self.xRaw, self.yRaw, self.zRaw) = rawValues } else { return nil } } private static func valuesFromRaw(rawValues:[Int8]) -> (Double, Double, Double) { return (-Double(rawValues[0])/64.0, -Double(rawValues[1])/64.0, Double(rawValues[2])/64.0) } private static func rawFromValues(values:[Double]) -> (Int8, Int8, Int8)? { let xRaw = Int8(doubleValue:(-64.0*values[0])) let yRaw = Int8(doubleValue:(-64.0*values[1])) let zRaw = Int8(doubleValue:(64.0*values[2])) if xRaw != nil && yRaw != nil && zRaw != nil { return (xRaw!, yRaw!, zRaw!) } else { return nil } } // CharacteristicConfigurable public static let uuid = "F000AA11-0451-4000-B000-000000000000" public static let name = "Accelerometer Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(x:1.0, y:0.5, z:-1.5)!) // RawArrayDeserializable public init?(rawValue:[Int8]) { if rawValue.count == 3 { self.xRaw = rawValue[0] self.yRaw = rawValue[1] self.zRaw = rawValue[2] (self.x, self.y, self.z) = Data.valuesFromRaw(rawValue) } else { return nil } } public var rawValue : [Int8] { return [self.xRaw, self.yRaw, self.zRaw] } // StringDeserializable public static let stringValues = [String]() public var stringValue : Dictionary<String,String> { return ["x":"\(self.x)", "y":"\(self.y)", "z":"\(self.z)", "xRaw":"\(self.xRaw)", "yRaw":"\(self.yRaw)", "zRaw":"\(self.zRaw)"] } public init?(stringValue:[String:String]) { let xRawInit = int8ValueFromStringValue("xRaw", stringValue) let yRawInit = int8ValueFromStringValue("yRaw", stringValue) let zRawInit = int8ValueFromStringValue("zRaw", stringValue) if xRawInit != nil && yRawInit != nil && zRawInit != nil { self.xRaw = xRawInit! self.yRaw = yRawInit! self.zRaw = zRawInit! (self.x, self.y, self.z) = Data.valuesFromRaw([self.xRaw, self.yRaw, self.zRaw]) } else { return nil } } } // Accelerometer Enabled public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 // CharacteristicConfigurable public static let uuid = "F000AA12-0451-4000-B000-000000000000" public static let name = "Accelerometer Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes"] public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No default: return nil } } else { return nil } } public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] } } } // Accelerometer Update Period public struct UpdatePeriod : RawDeserializable, CharacteristicConfigurable, StringDeserializable { public let periodRaw : UInt8 public let period : UInt16 private static func valueFromRaw(rawValue:UInt8) -> UInt16 { var period = 10*UInt16(rawValue) if period < 10 { period = 10 } return period } // CharacteristicConfigurable public static let uuid = "F000AA13-0451-4000-B000-000000000000" public static let name = "Accelerometer Update Period" public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let initialValue : NSData? = Serde.serialize(UInt8(100)) // RawDeserializable public var rawValue : UInt8 { return self.periodRaw } public init?(rawValue:UInt8) { self.periodRaw = rawValue self.period = UpdatePeriod.valueFromRaw(self.periodRaw) } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["period":"\(self.period)", "periodRaw":"\(self.periodRaw)"] } public init?(stringValue:[String:String]) { if let rawValue = uint8ValueFromStringValue("periodRaw", stringValue) { self.periodRaw = rawValue self.period = UpdatePeriod.valueFromRaw(self.periodRaw) } else { return nil } } } } //*************************************************************************************************** // Magnetometer Service: units are uT public struct MagnetometerService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA30-0451-4000-B000-000000000000" public static let name = "TI Magnetometer" public static let tag = "TI Sensor Tag" public struct Data : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { private let xRaw : Int16 private let yRaw : Int16 private let zRaw : Int16 public let x : Double public let y : Double public let z : Double public static func valuesFromRaw(values:[Int16]) -> (Double, Double, Double) { let x = -Double(values[0])*2000.0/65536.0 let y = -Double(values[1])*2000.0/65536.0 let z = Double(values[2])*2000.0/65536.0 return (x, y, z) } public static func rawFromValues(rawValues:[Double]) -> (Int16, Int16, Int16)? { let xRaw = Int16(doubleValue:(-rawValues[0]*65536.0/2000.0)) let yRaw = Int16(doubleValue:(-rawValues[1]*65536.0/2000.0)) let zRaw = Int16(doubleValue:(rawValues[2]*65536.0/2000.0)) if xRaw != nil && yRaw != nil && zRaw != nil { return (xRaw!, yRaw!, zRaw!) } else { return nil } } public init?(x:Double, y:Double, z:Double) { self.x = x self.y = y self.z = z if let values = Data.rawFromValues([x, y, z]) { (self.xRaw, self.yRaw, self.zRaw) = values } else { return nil } } // CharacteristicConfigurable public static let uuid = "f000aa31-0451-4000-b000-000000000000" public static let name = "Magnetometer Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(rawValue:[-2183, 1916, 1255])!) // RawArrayDeserializable public var rawValue : [Int16] { return [xRaw, yRaw, zRaw] } public init?(rawValue:[Int16]) { if rawValue.count == 3 { self.xRaw = rawValue[0] self.yRaw = rawValue[1] self.zRaw = rawValue[2] (self.x, self.y, self.z) = Data.valuesFromRaw(rawValue) } else { return nil } } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["x":"\(x)", "y":"\(y)", "z":"\(z)", "xRaw":"\(xRaw)", "yRaw":"\(yRaw)", "zRaw":"\(zRaw)"] } public init?(stringValue:[String:String]) { let xRawInit = int16ValueFromStringValue("xRaw", stringValue) let yRawInit = int16ValueFromStringValue("yRaw", stringValue) let zRawInit = int16ValueFromStringValue("zRaw", stringValue) if xRawInit != nil && yRawInit != nil && zRawInit != nil { self.xRaw = xRawInit! self.yRaw = yRawInit! self.zRaw = zRawInit! (self.x, self.y, self.z) = Data.valuesFromRaw([self.xRaw, self.yRaw, self.zRaw]) } else { return nil } } } // Magnetometer Enabled public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 // CharacteristicConfigurable public static let uuid = "f000aa32-0451-4000-b000-000000000000" public static let name = "Magnetometer Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes"] public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No default: return nil } } else { return nil } } public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] } } } // Magnetometer UpdatePeriod public struct UpdatePeriod : RawDeserializable, CharacteristicConfigurable, StringDeserializable { public let periodRaw : UInt8 public let period : UInt16 private static func valueFromRaw(rawValue:UInt8) -> UInt16 { var period = 10*UInt16(rawValue) if period < 10 { period = 10 } return period } // CharacteristicConfigurable public static let uuid = "f000aa33-0451-4000-b000-000000000000" public static let name = "Magnetometer Update Period" public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let initialValue : NSData? = Serde.serialize(UInt16(5000)) // RawDeserializable public var rawValue : UInt8 { return self.periodRaw } public init?(rawValue:UInt8) { self.periodRaw = rawValue self.period = UpdatePeriod.valueFromRaw(self.periodRaw) } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["period":"\(self.period)", "periodRaw":"\(self.periodRaw)"] } public init?(stringValue:[String:String]) { if let rawValue = uint8ValueFromStringValue("periodRaw", stringValue) { self.periodRaw = rawValue self.period = UpdatePeriod.valueFromRaw(self.periodRaw) } else { return nil } } } } //*************************************************************************************************** // Gyroscope Service: units are degrees public struct GyroscopeService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA50-0451-4000-B000-000000000000" public static let name = "TI Gyroscope" public static let tag = "TI Sensor Tag" // Gyroscope Data public struct Data : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { private let xRaw : Int16 private let yRaw : Int16 private let zRaw : Int16 public let x : Double public let y : Double public let z : Double static func valuesFromRaw(values:[Int16]) -> (Double, Double, Double) { let x = -Double(values[0])*Double(500.0)/65536.0 let y = -Double(values[1])*Double(500.0)/65536.0 let z = Double(values[2])*Double(500.0)/65536.0 return (x, y, z) } public static func rawFromValues(rawValues:[Double]) -> (Int16, Int16, Int16)? { let xRaw = Int16(doubleValue:(-rawValues[0]*65536.0/500.0)) let yRaw = Int16(doubleValue:(-rawValues[1]*65536.0/500.0)) let zRaw = Int16(doubleValue:(rawValues[2]*65536.0/500.0)) if xRaw != nil && yRaw != nil && zRaw != nil { return (xRaw!, yRaw!, zRaw!) } else { return nil } } public init?(x:Double, y:Double, z:Double) { self.x = x self.y = y self.z = z if let values = Data.rawFromValues([x, y, z]) { (self.xRaw, self.yRaw, self.zRaw) = values } else { return nil } } // CharacteristicConfigurable public static let uuid = "f000aa51-0451-4000-b000-000000000000" public static let name = "Gyroscope Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(rawValue:[-24, -219, -23])!) // RawArrayDeserializable public static let stringValues = [String]() public var rawValue : [Int16] { return [self.xRaw, self.yRaw, self.zRaw] } public init?(rawValue:[Int16]) { if rawValue.count == 3 { self.xRaw = rawValue[0] self.yRaw = rawValue[1] self.zRaw = rawValue[2] (self.x, self.y, self.z) = Data.valuesFromRaw(rawValue) } else { return nil } } // StringDeserializable public var stringValue : Dictionary<String,String> { return ["x":"\(x)", "y":"\(y)", "z":"\(z)", "xRaw":"\(xRaw)", "yRaw":"\(yRaw)", "zRaw":"\(zRaw)"] } public init?(stringValue:[String:String]) { let xRawInit = int16ValueFromStringValue("xRaw", stringValue) let yRawInit = int16ValueFromStringValue("yRaw", stringValue) let zRawInit = int16ValueFromStringValue("zRaw", stringValue) if xRawInit != nil && yRawInit != nil && zRawInit != nil { self.xRaw = xRawInit! self.yRaw = yRawInit! self.zRaw = zRawInit! (self.x, self.y, self.z) = Data.valuesFromRaw([self.xRaw, self.yRaw, self.zRaw]) } else { return nil } } } // Gyroscope Enabled public enum Enabled : UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case XAxis = 1 case YAxis = 2 case XYAxis = 3 case ZAxis = 4 case XZAxis = 5 case YZAxis = 6 case XYZAxis = 7 // CharacteristicConfigurable public static let uuid = "f000aa52-0451-4000-b000-000000000000" public static let name = "Gyroscope Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "No": self = Enabled.No case "XAxis": self = Enabled.XAxis case "YAxis": self = Enabled.YAxis case "XYAxis": self = Enabled.XYAxis case "ZAxis": self = Enabled.ZAxis case "XZAxis": self = Enabled.XZAxis case "YZAxis": self = Enabled.YZAxis case "XYZAxis": self = Enabled.XYZAxis default: return nil } } else { return nil } } public static var stringValues = ["No", "XAxis", "YAxis", "XYAxis", "ZAxis", "XZAxis", "YZAxis", "XYZAxis"] public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .XAxis: return [Enabled.name:"XAxis"] case .YAxis: return [Enabled.name:"YAxis"] case .XYAxis: return [Enabled.name:"XYAxis"] case .ZAxis: return [Enabled.name:"ZAxis"] case .XZAxis: return [Enabled.name:"XZAxis"] case .YZAxis: return [Enabled.name:"YZAxis"] case .XYZAxis: return [Enabled.name:"XYZAxis"] } } } } //*************************************************************************************************** // Temperature Service units Celsius public struct TemperatureService : ServiceConfigurable { public static let uuid = "F000AA00-0451-4000-B000-000000000000" public static let name = "TI Temperature" public static let tag = "TI Sensor Tag" public struct Data : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { private let objectRaw : Int16 private let ambientRaw : Int16 public let object : Double public let ambient : Double static func valuesFromRaw(objectRaw:Int16, ambientRaw:Int16) -> (Double, Double) { let ambient = Double(ambientRaw)/128.0; let vObj2 = Double(objectRaw)*0.00000015625; let tDie2 = ambient + 273.15; let s0 = 6.4*pow(10,-14); let a1 = 1.75*pow(10,-3); let a2 = -1.678*pow(10,-5); let b0 = -2.94*pow(10,-5); let b1 = -5.7*pow(10,-7); let b2 = 4.63*pow(10,-9); let c2 = 13.4; let tRef = 298.15; let s = s0*(1+a1*(tDie2 - tRef)+a2*pow((tDie2 - tRef),2)); let vOs = b0 + b1*(tDie2 - tRef) + b2*pow((tDie2 - tRef),2); let fObj = (vObj2 - vOs) + c2*pow((vObj2 - vOs),2); let object = pow(pow(tDie2,4) + (fObj/s),0.25) - 273.15; return (object, ambient) } // CharacteristicConfigurable public static let uuid = "f000aa01-0451-4000-b000-000000000000" public static let name = "Temperature Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(rawValue:[-172, 3388])!) // RawArrayDeserializable public var rawValue : [Int16] { return [self.objectRaw, self.ambientRaw] } public init?(rawValue:[Int16]) { if rawValue.count == 2 { self.objectRaw = rawValue[0] self.ambientRaw = rawValue[1] (self.object, self.ambient) = Data.valuesFromRaw(self.objectRaw, ambientRaw:self.ambientRaw) } else { return nil } } // StringDeserializable public static let stringValues = [String]() public var stringValue : Dictionary<String,String> { return [ "object":"\(object)", "ambient":"\(ambient)", "objectRaw":"\(objectRaw)", "ambientRaw":"\(ambientRaw)"] } public init?(stringValue:[String:String]) { let objectRawInit = int16ValueFromStringValue("objectRaw", stringValue) let ambientRawInit = int16ValueFromStringValue("ambientRaw", stringValue) if objectRawInit != nil && ambientRawInit != nil { self.objectRaw = objectRawInit! self.ambientRaw = ambientRawInit! (self.object, self.ambient) = Data.valuesFromRaw(self.objectRaw, ambientRaw:self.ambientRaw) } else { return nil } } } // Temperature Enabled public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 // CharacteristicConfigurable public static let uuid = "f000aa02-0451-4000-b000-000000000000" public static let name = "Temperature Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes"] public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No default: return nil } } else { return nil } } public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] } } } } //*************************************************************************************************** // Barometer Service // // Calibrated Pressure and Temperature are computed as follows // C1...C8 = Calibration Coefficients, TR = Raw temperature, PR = Raw Pressure, // T = Calibrated Temperature in Celcius, P = Calibrated Pressure in Pascals // // S = C3 + C4*TR/2^17 + C5*TR^2/2^34 // O = C6*2^14 + C7*TR/8 + C8TR^2/2^19 // P = (S*PR + O)/2^14 // T = C2/2^10 + C1*TR/2^24 public struct BarometerService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA40-0451-4000-B000-000000000000" public static let name = "TI Barometer" public static let tag = "TI Sensor Tag" public struct Data : RawPairDeserializable, CharacteristicConfigurable, StringDeserializable { public let temperatureRaw : Int16 public let pressureRaw : UInt16 // CharacteristicConfigurable public static let uuid = "f000aa41-0451-4000-b000-000000000000" public static let name = "Baraometer Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(rawValue:(-2343, 33995))!) // RawPairDeserializable public static let stringValues = [String]() public var rawValue : (Int16, UInt16) { return (self.temperatureRaw, self.pressureRaw) } public init?(rawValue:(Int16, UInt16)) { (self.temperatureRaw, self.pressureRaw) = rawValue } // StringDeserializable public var stringValue : Dictionary<String,String> { return ["temperatureRaw":"\(temperatureRaw)", "pressureRaw":"\(pressureRaw)"] } public init?(stringValue:[String:String]) { let temperatureRawInit = int16ValueFromStringValue("temperatureRaw", stringValue) let pressureRawInit = uint16ValueFromStringValue("pressureRaw", stringValue) if temperatureRawInit != nil && pressureRawInit != nil { self.temperatureRaw = temperatureRawInit! self.pressureRaw = pressureRawInit! } else { return nil } } } // Barometer Calibration public struct Calibration : RawArrayPairDeserializable, CharacteristicConfigurable, StringDeserializable { public let c1 : UInt16 public let c2 : UInt16 public let c3 : UInt16 public let c4 : UInt16 public let c5 : Int16 public let c6 : Int16 public let c7 : Int16 public let c8 : Int16 // CharacteristicConfigurable public static let uuid = "f000aa43-0451-4000-b000-000000000000" public static let name = "Baraometer Calibration Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Calibration(rawValue:([45697, 25592, 48894, 36174], [7001, 1990, -2369, 5542]))!) // RawArrayPairDeserializable public static var size : (Int, Int) { return (4*sizeof(UInt16), 4*sizeof(Int16)) } public var rawValue : ([UInt16], [Int16]) { return ([self.c1, self.c2, self.c3, self.c4], [self.c5, self.c6, self.c7, self.c8]) } public init?(rawValue:([UInt16], [Int16])) { let (unsignedValues, signedValues) = rawValue if unsignedValues.count == 4 && signedValues.count == 4 { self.c1 = unsignedValues[0] self.c2 = unsignedValues[1] self.c3 = unsignedValues[2] self.c4 = unsignedValues[3] self.c5 = signedValues[0] self.c6 = signedValues[1] self.c7 = signedValues[2] self.c8 = signedValues[3] } else { return nil } } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["c1":"\(c1)", "c2":"\(c2)", "c3":"\(c3)", "c4":"\(c4)", "c5":"\(c5)", "c6":"\(c6)", "c7":"\(c7)", "c8":"\(c8)"] } public init?(stringValue:[String:String]) { let c1Init = uint16ValueFromStringValue("c1", stringValue) let c2Init = uint16ValueFromStringValue("c2", stringValue) let c3Init = uint16ValueFromStringValue("c3", stringValue) let c4Init = uint16ValueFromStringValue("c4", stringValue) let c5Init = int16ValueFromStringValue("c5", stringValue) let c6Init = int16ValueFromStringValue("c6", stringValue) let c7Init = int16ValueFromStringValue("c7", stringValue) let c8Init = int16ValueFromStringValue("c8", stringValue) if c1Init != nil && c2Init != nil && c3Init != nil && c4Init != nil && c5Init != nil && c6Init != nil && c7Init != nil && c8Init != nil { self.c1 = c1Init! self.c2 = c2Init! self.c3 = c3Init! self.c4 = c4Init! self.c5 = c5Init! self.c6 = c6Init! self.c7 = c7Init! self.c8 = c8Init! } else { return nil } } } // Barometer Enabled public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 case Calibrate = 2 // CharacteristicConfigurable public static let uuid = "f000aa42-0451-4000-b000-000000000000" public static let name = "Baraometer Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes", "Calibrate"] public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No case "Calibrate": self = Enabled.Calibrate default: return nil } } else { return nil } } public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] case .Calibrate: return [Enabled.name:"Yes"] } } } } //*************************************************************************************************** // Hygrometer Service // Temperature units Celsius // Humidity units Relative Humdity public struct HygrometerService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA20-0451-4000-B000-000000000000" public static let name = "TI Hygrometer" public static let tag = "TI Sensor Tag" public struct Data : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { public var temperatureRaw : UInt16 public var humidityRaw : UInt16 public var temperature : Double public var humidity : Double private static func valuesFromRaw(temperatureRaw:UInt16, humidityRaw:UInt16) -> (Double, Double) { return (-46.86+175.72*Double(temperatureRaw)/65536.0, -6.0+125.0*Double(humidityRaw)/65536.0) } // CharacteristicConfigurable public static let uuid = "f000aa21-0451-4000-b000-000000000000" public static let name = "Hygrometer Data" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Data(rawValue:[2600, 3500])!) // RawArrayDeserializable public var rawValue : [UInt16] { return [self.temperatureRaw, self.humidityRaw] } public init?(rawValue:[UInt16]) { if rawValue.count == 2 { self.temperatureRaw = rawValue[0] self.humidityRaw = rawValue[1] (self.temperature, self.humidity) = Data.valuesFromRaw(self.temperatureRaw, humidityRaw:self.humidityRaw) } else { return nil } } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["temperature":"\(temperature)", "humidity":"\(humidity)", "temperatureRaw":"\(temperatureRaw)", "humidityRaw":"\(humidityRaw)"] } public init?(stringValue:[String:String]) { let temperatureRawInit = uint16ValueFromStringValue("temperatureRaw", stringValue) let humidityRawInit = uint16ValueFromStringValue("humidityRaw", stringValue) if temperatureRawInit != nil && humidityRawInit != nil { self.temperatureRaw = temperatureRawInit! self.humidityRaw = humidityRawInit! (self.temperature, self.humidity) = Data.valuesFromRaw(self.temperatureRaw, humidityRaw:self.humidityRaw) } else { return nil } } } // Hygrometer Enabled public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 // CharacteristicConfigurable public static let uuid = "f000aa22-0451-4000-b000-000000000000" public static let name = "Hygrometer Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes"] public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] } } public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No default: return nil } } else { return nil } } } } //*************************************************************************************************** // Sensor Tag Test Service public struct SensorTagTestService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "F000AA60-0451-4000-B000-000000000000" public static let name = "TI Sensor Tag Test" public static let tag = "TI Sensor Tag" public struct Data : RawDeserializable, CharacteristicConfigurable, StringDeserializable { var resultRaw : UInt8 var test1 : Bool var test2 : Bool var test3 : Bool var test4 : Bool var test5 : Bool var test6 : Bool var test7 : Bool var test8 : Bool // CharacteristicConfigurable public static let uuid = "f000aa61-0451-4000-b000-000000000000" public static let name = "Test Data" public static let properties = CBCharacteristicProperties.Read public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(0b11110000 as UInt8) private static func valuesFromRaw(rawValue:UInt8) -> [Bool] { return [self.testResult(rawValue, position:0), self.testResult(rawValue, position:1), self.testResult(rawValue, position:2), self.testResult(rawValue, position:3), self.testResult(rawValue, position:4), self.testResult(rawValue, position:5), self.testResult(rawValue, position:6), self.testResult(rawValue, position:7)] } private static func testResult(rawResult:UInt8, position:UInt8) -> Bool { return (rawResult & (1 << position)) > 0 } private static func testResultStringValue(value:Bool) -> String { return value ? "PASSED" : "FAILED" } // RawDeserializable public var rawValue : UInt8 { return self.resultRaw } public init?(rawValue:UInt8) { self.resultRaw = rawValue let values = Data.valuesFromRaw(rawValue) self.test1 = values[0] self.test2 = values[1] self.test3 = values[2] self.test4 = values[3] self.test5 = values[4] self.test6 = values[5] self.test7 = values[6] self.test8 = values[7] } // StringDeserializable public static let stringValues = [String]() public var stringValue : [String:String] { return ["resultRaw":"\(resultRaw)", "test1":"\(Data.testResultStringValue(test1))", "test2":"\(Data.testResultStringValue(test2))", "test3":"\(Data.testResultStringValue(test3))", "test4":"\(Data.testResultStringValue(test4))", "test5":"\(Data.testResultStringValue(test5))", "test6":"\(Data.testResultStringValue(test6))", "test7":"\(Data.testResultStringValue(test7))", "test8":"\(Data.testResultStringValue(test8))"] } public init?(stringValue:[String:String]) { if let rawValue = uint8ValueFromStringValue("resultRaw", stringValue) { let values = Data.valuesFromRaw(rawValue) self.resultRaw = rawValue self.test1 = values[0] self.test2 = values[1] self.test3 = values[2] self.test4 = values[3] self.test5 = values[4] self.test6 = values[5] self.test7 = values[6] self.test8 = values[7] } else { return nil } } } public enum Enabled: UInt8, RawDeserializable, StringDeserializable, CharacteristicConfigurable { case No = 0 case Yes = 1 // CharacteristicConfigurable public static let uuid = "f000aa62-0451-4000-b000-000000000000" public static let name = "Test Enabled" public static let properties = CBCharacteristicProperties.Read | CBCharacteristicProperties.Write public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(Enabled.No.rawValue) // StringDeserializable public static let stringValues = ["No", "Yes"] public init?(stringValue:[String:String]) { if let value = stringValue[Enabled.name] { switch value { case "Yes": self = Enabled.Yes case "No": self = Enabled.No default: return nil } } else { return nil } } public var stringValue : [String:String] { switch self { case .No: return [Enabled.name:"No"] case .Yes: return [Enabled.name:"Yes"] } } } } //*************************************************************************************************** // Key Pressed Service public struct KeyPressedService : ServiceConfigurable { public static let uuid = "ffe0" public static let name = "Sensor Tag Key Pressed" public static let tag = "TI Sensor Tag" public enum State : UInt8, RawDeserializable, CharacteristicConfigurable, StringDeserializable { case None = 0 case ButtonOne = 1 case ButtonTwo = 2 // CharacteristicConfigurable public static let uuid = "ffe1" public static let name = "Key Pressed" public static let properties = CBCharacteristicProperties.Notify public static let permissions = CBAttributePermissions.Readable | CBAttributePermissions.Writeable public static let initialValue : NSData? = Serde.serialize(0x01 as UInt8) // StringDeserializable public static let stringValues = ["None", "Button One", "Button Two"] public var stringValue : [String:String] { switch self { case .None: return [State.name:"None"] case .ButtonOne: return [State.name:"Button One"] case .ButtonTwo: return [State.name:"Button Two"] } } public init?(stringValue:[String:String]) { if let value = stringValue[State.name] { switch value { case "None": self = State.None case "Button One": self = State.ButtonOne case "Button Two": self = State.ButtonTwo default: return nil } } else { return nil } } } } } public class TISensorTagServiceProfiles { public class func create() { let profileManager = ProfileManager.sharedInstance //*************************************************************************************************** // Accelerometer Service let accelerometerService = ConfiguredServiceProfile<TISensorTag.AccelerometerService>() let accelerometerDataCharacteristic = RawArrayCharacteristicProfile<TISensorTag.AccelerometerService.Data>() let accelerometerEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.AccelerometerService.Enabled>() let accelerometerUpdatePeriodCharacteristic = RawCharacteristicProfile<TISensorTag.AccelerometerService.UpdatePeriod>() accelerometerEnabledCharacteristic.afterDiscovered(2).onSuccess {characteristic in characteristic.write(TISensorTag.AccelerometerService.Enabled.Yes) return } accelerometerService.addCharacteristic(accelerometerDataCharacteristic) accelerometerService.addCharacteristic(accelerometerEnabledCharacteristic) accelerometerService.addCharacteristic(accelerometerUpdatePeriodCharacteristic) profileManager.addService(accelerometerService) //*************************************************************************************************** // Magnetometer Service let magnetometerService = ConfiguredServiceProfile<TISensorTag.MagnetometerService>() let magnetometerDataCharacteristic = RawArrayCharacteristicProfile<TISensorTag.MagnetometerService.Data>() let magnetometerEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.MagnetometerService.Enabled>() let magnetometerUpdatePeriodCharacteristic = RawCharacteristicProfile<TISensorTag.MagnetometerService.UpdatePeriod>() magnetometerEnabledCharacteristic.afterDiscovered(2).onSuccess {characteristic in characteristic.write(TISensorTag.MagnetometerService.Enabled.Yes) return } magnetometerService.addCharacteristic(magnetometerDataCharacteristic) magnetometerService.addCharacteristic(magnetometerEnabledCharacteristic) magnetometerService.addCharacteristic(magnetometerUpdatePeriodCharacteristic) profileManager.addService(magnetometerService) //*************************************************************************************************** // Gyroscope Service let gyroscopeService = ConfiguredServiceProfile<TISensorTag.GyroscopeService>() let gyroscopeDataCharacteristic = RawArrayCharacteristicProfile<TISensorTag.GyroscopeService.Data>() let gyroscopeEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.GyroscopeService.Enabled>() gyroscopeEnabledCharacteristic.afterDiscovered(2).onSuccess {characteristic in characteristic.write(TISensorTag.GyroscopeService.Enabled.XYZAxis) return } gyroscopeService.addCharacteristic(gyroscopeDataCharacteristic) gyroscopeService.addCharacteristic(gyroscopeEnabledCharacteristic) profileManager.addService(gyroscopeService) //*************************************************************************************************** // Temperature Service let temperatureService = ConfiguredServiceProfile<TISensorTag.TemperatureService>() let temperatureDataCharacteristic = RawArrayCharacteristicProfile<TISensorTag.TemperatureService.Data>() let temperatureEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.TemperatureService.Enabled>() temperatureEnabledCharacteristic.afterDiscovered(2).onSuccess {characteristic in characteristic.write(TISensorTag.TemperatureService.Enabled.Yes) return } temperatureService.addCharacteristic(temperatureDataCharacteristic) temperatureService.addCharacteristic(temperatureEnabledCharacteristic) profileManager.addService(temperatureService) //*************************************************************************************************** // Barometer Service let barometerService = ConfiguredServiceProfile<TISensorTag.BarometerService>() let barometerDataCharacteristic = RawPairCharacteristicProfile<TISensorTag.BarometerService.Data>() let barometerCalibrationCharacteristic = RawArrayPairCharacteristicProfile<TISensorTag.BarometerService.Calibration>() let barometerEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.BarometerService.Enabled>() let barometerDiscoveredFuture = barometerEnabledCharacteristic.afterDiscovered(2) let barometerEnabledFuture = barometerDiscoveredFuture.flatmap {characteristic -> Future<Characteristic> in return characteristic.write(TISensorTag.BarometerService.Enabled.Yes) } barometerEnabledFuture.onSuccess {characteristic in characteristic.write(TISensorTag.BarometerService.Enabled.Calibrate) return } barometerService.addCharacteristic(barometerDataCharacteristic) barometerService.addCharacteristic(barometerCalibrationCharacteristic) barometerService.addCharacteristic(barometerEnabledCharacteristic) profileManager.addService(barometerService) //*************************************************************************************************** // Hygrometer Service let hygrometerService = ConfiguredServiceProfile<TISensorTag.HygrometerService>() let hygrometerDataCharacteristic = RawArrayCharacteristicProfile<TISensorTag.HygrometerService.Data>() let hygrometerEnabledCharacteristic = RawCharacteristicProfile<TISensorTag.HygrometerService.Enabled>() hygrometerEnabledCharacteristic.afterDiscovered(2).onSuccess {characteristic in characteristic.write(TISensorTag.HygrometerService.Enabled.Yes) return } hygrometerService.addCharacteristic(hygrometerDataCharacteristic) hygrometerService.addCharacteristic(hygrometerEnabledCharacteristic) profileManager.addService(hygrometerService) //*************************************************************************************************** // Sensor Tag Test Service let sensorTagTestService = ConfiguredServiceProfile<TISensorTag.SensorTagTestService>() let sensorTagTestData = RawCharacteristicProfile<TISensorTag.SensorTagTestService.Data>() let sensorTagTestEnabled = RawCharacteristicProfile<TISensorTag.SensorTagTestService.Enabled>() sensorTagTestService.addCharacteristic(sensorTagTestData) sensorTagTestService.addCharacteristic(sensorTagTestEnabled) profileManager.addService(sensorTagTestService) //*************************************************************************************************** // Key Pressed Service let keyPressedService = ConfiguredServiceProfile<TISensorTag.KeyPressedService>() let keyPressedStateCharacteristic = RawCharacteristicProfile<TISensorTag.KeyPressedService.State>() keyPressedService.addCharacteristic(keyPressedStateCharacteristic) profileManager.addService(keyPressedService) } }
mit
4cad51f9735d4ee7f1547b9d31e38f30
43.270543
155
0.508641
5.489139
false
true
false
false
Nibelungc/ios-ScrollBar
ios-ScrollBar/ViewController.swift
1
2747
// // ViewController.swift // ios-ScrollBar // // Created by Николай Кагала on 22/06/2017. // Copyright © 2017 Николай Кагала. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, ScrollBarDataSource, UITableViewDelegate { @IBOutlet private weak var tableView: UITableView! private var scrollBar: ScrollBar! private var items = [[String]]() private let identifier = "Cell" override func viewDidLoad() { super.viewDidLoad() reload() tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier) tableView.sectionHeaderHeight = 20 scrollBar = ScrollBar(scrollView: tableView) scrollBar.dataSource = self navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(reloadAction)) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(shortListAction)) } func reloadAction() { reload() } func shortListAction() { reload(max: 5) } func reload(min: Int = 0, max: Int = 10_000) { let maxCount = min + Int(arc4random_uniform(UInt32(max - min + 1))) items = [ (0...maxCount).map { "Cell \($0)" }, (0...maxCount).map { "Cell \($0)" }, (0...maxCount).map { "Cell \($0)" } ] navigationItem.title = "\(maxCount) Cells" tableView?.reloadData() } // MARK - ScrollBarDataSource func textForHintView(_ hintView: UIView, at point: CGPoint, for scrollBar: ScrollBar) -> String? { guard let indexPath = tableView.indexPathForRow(at: point) else { return nil } let title = items[indexPath.section][indexPath.row] return title } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return items.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) cell.textLabel?.text = items[indexPath.section][indexPath.row] return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = .groupTableViewBackground return view } }
mit
dde301382dd6c192f6b9e944c166b0ed
31.380952
137
0.637868
4.874552
false
false
false
false
AngryLi/ResourceSummary
iOS/Demos/Assignments_swift/assignment-final/SwiftFinal/SwiftFinal/Classes/navigate/Controller/LsNavigateController.swift
3
9707
// // LsNavigateController.swift // SwiftFinal // // Created by 李亚洲 on 15/6/14. // Copyright (c) 2015年 angryli. All rights reserved. // import UIKit enum FindRouteType { case System case Imediate } class LsNavigateController: UIViewController, MKMapViewDelegate, UIActionSheetDelegate { //MARK:拖拽属性 @IBOutlet weak var mapView: MKMapView! { didSet { mapView.delegate = self mapView.showsUserLocation = true mapView.userTrackingMode = MKUserTrackingMode.Follow } } @IBOutlet weak var startPlaceTextField: UITextField! @IBOutlet weak var endPlaceTextField: UITextField! //MARK:私有属性 private let locationManager = CLLocationManager() private var startPlaceMark : CLPlacemark? private var endPlaceMark : CLPlacemark? private var transportType = MKDirectionsTransportType.Any private var findRouteType = FindRouteType.Imediate private var geocoder = CLGeocoder() @IBAction func getCurrentPlace() { self.geocoder.reverseGeocodeLocation(self.mapView.userLocation.location) { (placeMarkArray, error) -> Void in if error == nil { if let placeMark = placeMarkArray.first as? CLPlacemark { self.startPlaceTextField.text = placeMark.name // self.addAnnotationWithPlacemark(placeMark) // self.startPlaceMark = placeMark } } } } override func viewDidLoad() { super.viewDidLoad() if let version = NSNumberFormatter().numberFromString(UIDevice.currentDevice().systemVersion)?.floatValue { if version > 8.0 { locationManager.requestWhenInUseAuthorization() } } locationManager.startUpdatingLocation() //显示当前位置为中心 UIView.animateWithDuration(1, animations: { () -> Void in let region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 0.3,0.3); self.mapView.setRegion(region, animated: true) }) } @IBAction func shareMyLocation(sender: UIBarButtonItem) { let shareImage = UIImage.captureWithView(self.mapView) let shareCompressImage = UIImage(image: shareImage, scale: 0.3) let data = UIImageJPEGRepresentation(shareCompressImage, 0.8) // println(data.length) let app = AppDelegate() app.sendImageContent(shareCompressImage, scene: 1) } @IBAction func searchPath() { if startPlaceTextField.text.isEmpty { let alert = UIAlertView(title: "提示", message: "你没有输入其实地点,默认使用当前位置", delegate: self, cancelButtonTitle: "确定") alert.show() self.getCurrentPlace() } if endPlaceTextField.text.isEmpty { let alert = UIAlertView(title: "提示", message: "你没有输入目的地", delegate: self, cancelButtonTitle: "确定") alert.show() return } let waysheet = UIActionSheet(title: "选择你想使用的定位程序", delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: "放弃查找", otherButtonTitles: "系统默认", "马上找") waysheet.showInView(self.view) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { print(buttonIndex) switch buttonIndex { case 1: self.findRouteType = FindRouteType.System findRoute() case 2: self.findRouteType = FindRouteType.Imediate findRoute() default: print("") } } func findRoute() { if startPlaceMark == nil { if !startPlaceTextField.text.isEmpty { self.geocoder.geocodeAddressString(startPlaceTextField.text, completionHandler: { (placeMarkArray, error) -> Void in if error == nil { if let placeMark : CLPlacemark = placeMarkArray.first as? CLPlacemark { self.addAnnotationWithPlacemark(placeMark) self.startPlaceMark = placeMark if self.endPlaceMark == nil { if !self.endPlaceTextField.text.isEmpty { self.geocoder.geocodeAddressString(self.endPlaceTextField.text, completionHandler: { (placeMarkArray, error) -> Void in if error == nil { if let secondplaceMark : CLPlacemark = placeMarkArray.first as? CLPlacemark { self.addAnnotationWithPlacemark(secondplaceMark) self.endPlaceMark = secondplaceMark if self.startPlaceMark != nil && self.endPlaceMark != nil { let region = MKCoordinateRegionMakeWithDistance(self.startPlaceMark!.location.coordinate, 0.3,0.3); self.mapView.setRegion(region, animated: true) self.addRoute(self.startPlaceMark!, destination: self.endPlaceMark!) //MARK:清空查询信息 self.startPlaceMark = nil self.endPlaceMark = nil } } } }) } else { let alert = UIAlertView(title: "警报", message: "不输入目的地是什么情况", delegate: self, cancelButtonTitle: "确定") alert.show() } } } }else { let alert = UIAlertView(title: "提示", message: "起始地点出错出错,默认使用当前位置", delegate: self, cancelButtonTitle: "确定") alert.show() } }) } } } func addAnnotationWithPlacemark(placeMark : CLPlacemark) { let anno = LsAnnotion(newTitle: placeMark.name, newSubtitle: placeMark.locality, newCoordinate: placeMark.location.coordinate) self.mapView.addAnnotation(anno) } func addRoute(resource:CLPlacemark, destination:CLPlacemark) { switch self.findRouteType { case FindRouteType.Imediate: let request = MKDirectionsRequest() request.setSource = MKMapItem(placemark: MKPlacemark(placemark: resource)) request.setDestination = MKMapItem(placemark: MKPlacemark(placemark: destination)) request.transportType = MKDirectionsTransportType.Automobile let directions = MKDirections(request: request) directions.calculateDirectionsWithCompletionHandler({ (response, error) -> Void in if error == nil { if let route: MKRoute = response.routes.first as? MKRoute { self.mapView.addOverlay(route.polyline) } } }) case FindRouteType.System: let currentLocation = MKMapItem(placemark: MKPlacemark(placemark: resource)) let toLocation = MKMapItem(placemark: MKPlacemark(placemark: destination)) var options : NSMutableDictionary = NSMutableDictionary() options[MKLaunchOptionsDirectionsModeKey] = MKLaunchOptionsDirectionsModeDriving options[MKLaunchOptionsShowsTrafficKey] = true MKMapItem.openMapsWithItems([currentLocation,toLocation], launchOptions: options as [NSObject : AnyObject]) default: print("") } } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { // let region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 0.3,0.3); // self.mapView.setRegion(region, animated: true) } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer! { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.redColor() renderer.lineWidth = 5 return renderer } @IBAction func backToMyLocation() { //显示当前位置为中心 UIView.animateWithDuration(2, animations: { () -> Void in let region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 0.3,0.3); self.mapView.setRegion(region, animated: true) }) } }
mit
1663d411e6c62e2fad77a0ddc610dd3b
39.737069
164
0.530632
5.780428
false
false
false
false
tlax/GaussSquad
GaussSquad/Controller/Store/CStore.swift
1
3875
import UIKit import StoreKit class CStore:CController, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKRequestDelegate { private weak var viewStore:VStore! private weak var request:SKProductsRequest? let model:MStore override init() { model = MStore() super.init() } required init?(coder:NSCoder) { return nil } deinit { request?.cancel() SKPaymentQueue.default().remove(self) } override func loadView() { let viewStore:VStore = VStore(controller:self) self.viewStore = viewStore view = viewStore } override func viewDidLoad() { super.viewDidLoad() SKPaymentQueue.default().add(self) DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in guard let purchaseIds:[MStore.PurchaseId] = self?.model.references else { return } let purchases:Set<MStore.PurchaseId> = Set<MStore.PurchaseId>(purchaseIds) self?.checkAvailabilities(purchases:purchases) } } //MARK: private private func checkAvailabilities(purchases:Set<MStore.PurchaseId>) { let request:SKProductsRequest = SKProductsRequest(productIdentifiers:purchases) self.request = request request.delegate = self request.start() } //MARK: public func restorePurchases() { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { AnalyticsManager.sharedInstance?.trackStore( action:AnalyticsManager.StoreAction.restore, purchase:nil) SKPaymentQueue.default().restoreCompletedTransactions() } } func purchase(skProduct:SKProduct?) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { guard let skProduct:SKProduct = skProduct else { return } AnalyticsManager.sharedInstance?.trackStore( action:AnalyticsManager.StoreAction.purchase, purchase:skProduct.localizedTitle) let skPayment:SKPayment = SKPayment(product:skProduct) SKPaymentQueue.default().add(skPayment) } } //MARK: storeKit delegate func request(_ request:SKRequest, didFailWithError error:Error) { model.error = error.localizedDescription viewStore.refreshStore() } func productsRequest(_ request:SKProductsRequest, didReceive response:SKProductsResponse) { let products:[SKProduct] = response.products for product:SKProduct in products { model.loadSkProduct(skProduct:product) } viewStore.refreshStore() } func paymentQueue(_ queue:SKPaymentQueue, updatedTransactions transactions:[SKPaymentTransaction]) { model.updateTransactions(transactions:transactions) viewStore.refreshStore() } func paymentQueue(_ queue:SKPaymentQueue, removedTransactions transactions:[SKPaymentTransaction]) { model.updateTransactions(transactions:transactions) viewStore.refreshStore() } func paymentQueueRestoreCompletedTransactionsFinished(_ queue:SKPaymentQueue) { viewStore.refreshStore() } func paymentQueue(_ queue:SKPaymentQueue, restoreCompletedTransactionsFailedWithError error:Error) { model.error = error.localizedDescription viewStore.refreshStore() } }
mit
4a46634e509c98d1e1704d51265e89d6
25.724138
102
0.597161
5.774963
false
false
false
false
MrZoidberg/metapp
metapp/Pods/RealmSwift/RealmSwift/List.swift
24
39379
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private #if swift(>=3.0) /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub(pattern: "RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.description(withMaxDepth: depth)) ?? type } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List` is the container type in Realm used to define to-many relationships. Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores. Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them is opened as read-only. Lists can be filtered and sorted with the same predicates as `Results<T>`. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// The type of the elements contained within the collection. public typealias Element = T // MARK: Properties /// The Realm which manages the list, or `nil` if the list is unmanaged. public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var isInvalidated: Bool { return _rlmArray.isInvalidated } // MARK: Initializers /// Creates a `List` that holds Realm model objects of type `T`. public override init() { super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } internal init(rlmArray: RLMArray<RLMObject>) { super.init(array: rlmArray) } // MARK: Index Retrieval /** Returns the index of an object in the list, or `nil` if the object is not present. - parameter object: An object to find. */ public func index(of object: T) -> Int? { return notFoundToNil(index: _rlmArray.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given index (get), or replaces the object at the given index (set). - warning: You can only set an object during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(position: Int) -> T { get { throwForNegativeIndex(position) return unsafeBitCast(_rlmArray.object(at: UInt(position)), to: T.self) } set { throwForNegativeIndex(position) _rlmArray.replaceObject(at: UInt(position), with: newValue.unsafeCastToRLMObject()) } } /// Returns the first object in the list, or `nil` if the list is empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the list, or `nil` if the list is empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's objects. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return _rlmArray.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return _rlmArray.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(_rlmArray.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given property. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(by: [SortDescriptor(property: property, ascending: ascending)]) } /** Returns a `Results` containing the objects in the list, but sorted. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byProperty:ascending:)` */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return filter(NSPredicate(value: true)).min(ofProperty: property) } /** Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose maximum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return filter(NSPredicate(value: true)).max(ofProperty: property) } /** Returns the sum of the values of a given property over all the objects in the list. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return filter(NSPredicate(value: true)).sum(ofProperty: property) } /** Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return filter(NSPredicate(value: true)).average(ofProperty: property) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver. - warning: This method may only be called during a write transaction. - parameter object: An object. */ public func append(_ object: T) { _rlmArray.add(object.unsafeCastToRLMObject()) } /** Appends the objects in the given sequence to the end of the list. - warning: This method may only be called during a write transaction. */ public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == T { for obj in objects { _rlmArray.add(obj.unsafeCastToRLMObject()) } } /** Inserts an object at the given index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(_ object: T, at index: Int) { throwForNegativeIndex(index) _rlmArray.insert(object.unsafeCastToRLMObject(), at: UInt(index)) } /** Removes an object at the given index. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index at which to remove the object. */ public func remove(objectAtIndex index: Int) { throwForNegativeIndex(index) _rlmArray.removeObject(at: UInt(index)) } /** Removes the last object in the list. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index of the object to be replaced. - parameter object: An object. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObject(at: UInt(index), with: object.unsafeCastToRLMObject()) } /** Moves the object at the given source index to the given destination index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from: Int, to: Int) { // swiftlint:disable:this variable_name throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObject(at: UInt(from), to: UInt(to)) } /** Exchanges the objects in the list at given indices. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter index1: The index of the object which should replace the object at index `index2`. - parameter index2: The index of the object which should replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2)) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<List>) -> ()) -> NotificationToken { return _rlmArray.addNotificationBlock { list, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension List : RealmCollection, RangeReplaceableCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the `List`. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C) where C.Iterator.Element == T { for _ in subrange.lowerBound..<subrange.upperBound { remove(objectAtIndex: subrange.lowerBound) } for x in newElements.reversed() { insert(x, at: subrange.lowerBound) } } /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: Unavailable extension List { @available(*, unavailable, renamed: "append(objectsIn:)") public func appendContentsOf<S: Sequence>(_ objects: S) where S.Iterator.Element == T { fatalError() } @available(*, unavailable, renamed: "remove(objectAtIndex:)") public func remove(at index: Int) { fatalError() } @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: Any...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byProperty:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } } #else /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List` is the container type in Realm used to define to-many relationships. Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores. Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them is opened as read-only. Lists can be filtered and sorted with the same predicates as `Results<T>`. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// The type of the elements contained within the collection. public typealias Element = T // MARK: Properties /// The Realm which manages the list. Returns `nil` for unmanaged lists. public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds Realm model objects of type `T`. public override init() { super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } internal init(rlmArray: RLMArray) { super.init(array: rlmArray) } // MARK: Index Retrieval /** Returns the index of an object in the list, or `nil` if the object is not present. - parameter object: An object to find. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(object.unsafeCastToRLMObject())) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given index (get), or replaces the object at the given index (set). - warning: You can only set an object during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = newValue.unsafeCastToRLMObject() } } /// Returns the first object in the list, or `nil` if the list is empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the list, or `nil` if the list is empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public override func valueForKeyPath(keyPath: String) -> AnyObject? { return _rlmArray.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicate: The predicate with which to filter the objects. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given property. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted("age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns a `Results` containing the objects in the list, but sorted. - warning: Lists may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(_:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).min(property) } /** Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose maximum value is desired. */ public func max<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).max(property) } /** Returns the sum of the values of a given property over all the objects in the list. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(property: String) -> U { return filter(NSPredicate(value: true)).sum(property) } /** Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(property: String) -> U? { return filter(NSPredicate(value: true)).average(property) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver. - warning: This method may only be called during a write transaction. - parameter object: An object. */ public func append(object: T) { _rlmArray.addObject(object.unsafeCastToRLMObject()) } /** Appends the objects in the given sequence to the end of the list. - warning: This method may only be called during a write transaction. - parameter objects: A sequence of objects. */ public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in objects { _rlmArray.addObject(obj.unsafeCastToRLMObject()) } } /** Inserts an object at the given index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(object.unsafeCastToRLMObject(), atIndex: UInt(index)) } /** Removes an object at the given index. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the list. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index of the object to be replaced. - parameter object: An object. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: object.unsafeCastToRLMObject()) } /** Moves the object at the given source index to the given destination index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from from: Int, to: Int) { // swiftlint:disable:this variable_name throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the list at given indices. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter index1: The index of the object which should replace the object at index `index2`. - parameter index2: The index of the object which should replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } // MARK: Notifications /** Registers a block to be called each time the list changes. The block will be asynchronously called with the initial list, and then called again after each write transaction which changes the list or any of the items in the list. The `change` parameter that is passed to the block reports, in the form of indices within the list, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. The block is called on the same thread as it was added on, and can only be added on threads which are currently within a run loop. Unless you are specifically creating and running a run loop on a background thread, this will normally only be the main thread. Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial list. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction, and will not include change information. ```swift let person = realm.objects(Person.self).first! print("dogs.count: \(person.dogs.count)") // => 0 let token = person.dogs.addNotificationBlock { changes in switch changes { case .Initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - warning: This method may only be called on a managed list. - parameter block: The block to be called each time the list changes. - returns: A token which must be held for as long as you want updates to be delivered. */ @warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock") public func addNotificationBlock(block: (RealmCollectionChange<List>) -> ()) -> NotificationToken { return _rlmArray.addNotificationBlock { list, change, error in block(RealmCollectionChange.fromObjc(self, change: change, error: error)) } } } extension List: RealmCollectionType, RangeReplaceableCollectionType { // MARK: Sequence Support /// Returns an `RLMGenerator` that yields successive elements in the list. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the list. */ public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>, with newElements: C) { for _ in subRange { removeAtIndex(subRange.startIndex) } for x in newElements.reverse() { insert(x, atIndex: subRange.startIndex) } } /// The position of the first element in a non-empty collection. /// Identical to `endIndex` in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// `endIndex` is not a valid argument to subscript, and is always reachable from `startIndex` by /// zero or more applications of `successor()`. public var endIndex: Int { return count } /// :nodoc: public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(anyCollection, change: change, error: error)) } } } #endif
mpl-2.0
fe2e55c1e726e323f0bf0efdb713e2fc
37.34372
130
0.671576
4.700848
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden_old/HTWDresden/SPButtonLesson.swift
1
9345
// // SPButtonLesson.swift // HTWDresden // // Created by Benjamin Herzog on 21.08.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import Foundation import UIKit class SPButtonLesson: UIButton { private let CELL_CORNER_RADIUS = 0 private let CELL_PADDING: CGFloat = 4 private var portrait: Bool private var currentDate: NSDate var stunde: Stunde { didSet{ kurzel?.text = stunde.kurzel raum?.text = stunde.raum if stunde.typ != nil { typ?.text = stunde.typ } if stunde.bemerkungen == nil || stunde.bemerkungen == "" { circle?.hidden = true } else { circle?.hidden = false if select || now { circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() :UIColor.HTWWhiteColor() } else { circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() :UIColor.HTWTextColor() } } } } private var width: CGFloat = 0 private var height: CGFloat = 0 private var x: CGFloat = 0 private var y: CGFloat = 0 private var circle: UIView? private var PixelPerMin: CGFloat = 0.0 var newGr: UITapGestureRecognizer? var tapHandler: ((sender: SPButtonLesson) -> Void)? { didSet { if newGr != nil { removeGestureRecognizer(newGr!) } newGr = UITapGestureRecognizer(target: self, action: "gestureRecognizerAction:") newGr?.numberOfTapsRequired = 1 addGestureRecognizer(newGr!) } } func gestureRecognizerAction(sender: UIGestureRecognizer) { tapHandler?(sender: self) } // MARK: - UI var kurzel: UILabel? var raum: UILabel? var typ: UILabel? // MARK: - Initialisers init(stunde: Stunde, portrait: Bool, currentDate: NSDate) { self.stunde = stunde self.portrait = portrait self.currentDate = currentDate PixelPerMin = portrait ? 0.5 : 0.35 super.init(frame: CGRectZero) self.frame = configure() farben() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() -> CGRect { var myFrame = CGRect(x: 0, y: 0, width: 0, height: 0) height = CGFloat(stunde.ende.timeIntervalSinceDate(stunde.anfang)) / CGFloat(60) * PixelPerMin width = portrait ? 108 : 90 if portrait { let today = currentDate.getDayOnly() var dayComponent = NSDateComponents() dayComponent.day = 1 var theCalendar = NSCalendar.currentCalendar() var tage = [NSDate]() tage.append(today) for var i = 1; i < ANZ_PORTRAIT; i++ { tage.append(theCalendar.dateByAddingComponents(dayComponent, toDate: tage[i-1], options: .allZeros)!) } for var i = 0; i < tage.count; i++ { if NSDate.isSameDayWithDate1(stunde.anfang, andDate2: tage[i]) { x = CGFloat(50 + i * 116) y = CGFloat(54 + CGFloat(stunde.anfang.timeIntervalSinceDate(tage[i].dateByAddingTimeInterval(60*60*7+60*30))) / 60 * PixelPerMin) break } } } else { let weekday = self.currentDate.weekDay() var dayComponent = NSDateComponents() dayComponent.day = 1 var threeDayComponent = NSDateComponents() threeDayComponent.day = 3 var theCalendar = NSCalendar.currentCalendar() let montag = currentDate.getDayOnly().dateByAddingTimeInterval(NSTimeInterval(-60 * 60 * 24 * weekday)) var tage = [NSDate]() var zaehler = 0 for var i = 1; i < ANZ_LANDSCAPE; i++ { if zaehler < 4 { tage.append(theCalendar.dateByAddingComponents(dayComponent, toDate: tage[i - 1], options: .allZeros)!) } else { tage.append(theCalendar.dateByAddingComponents(threeDayComponent, toDate: tage[i - 1], options: .allZeros)!) } zaehler++ if zaehler > 4 { zaehler = 0 } } for var i = 0; i < tage.count; i++ { if NSDate.isSameDayWithDate1(stunde.anfang, andDate2: tage[i]) { x = 1 if i != 0 { x = CGFloat(1 + i * 103 + 61 * UInt8(i/5)) } y = CGFloat(45 + CGFloat(stunde.anfang.timeIntervalSinceDate(tage[i].dateByAddingTimeInterval(60*60*7+60*30))) / 60 * PixelPerMin) break } } } myFrame = CGRect(x: x, y: y, width: width, height: height) return myFrame } func farben() { backgroundColor = UIColor.HTWWhiteColor() layer.cornerRadius = CGFloat(CELL_CORNER_RADIUS) kurzel = UILabel(frame: CGRect(x: x+CELL_PADDING, y: y, width: width*0.98, height: height*0.6)) kurzel?.text = stunde.kurzel.componentsSeparatedByString(" ")[0] kurzel?.textAlignment = .Left kurzel?.textColor = UIColor.HTWDarkGrayColor() kurzel?.font = portrait ? UIFont.HTWLargeFont() : UIFont.HTWBaseFont() raum = UILabel(frame: CGRect(x: x+CELL_PADDING, y: y+(height*0.5), width: width*0.98, height: height*0.4)) raum?.text = stunde.raum raum?.textAlignment = .Left raum?.textColor = UIColor.HTWGrayColor() raum?.font = portrait ? UIFont.HTWSmallFont() : UIFont.HTWSmallestFont() if stunde.typ != nil { typ = UILabel(frame: CGRect(x: x, y: y+(height*0.5), width: width-6, height: height*0.4)) typ?.text = stunde.typ typ?.font = portrait ? UIFont.HTWSmallFont() : UIFont.HTWVerySmallFont() typ?.textAlignment = .Right typ?.textColor = UIColor.HTWGrayColor() addSubview(typ!) } circle = UIView() if portrait { circle?.frame = CGRect(x: x+(width*6/7)+2,y: y+3,width: 10,height: 10) } else { circle?.frame = CGRect(x: x+(width*6/7)+2,y: y+3,width: 7,height: 7) } circle?.hidden = true circle?.layer.cornerRadius = circle!.frame.size.height/2; self.addSubview(circle!) if stunde.bemerkungen != nil && stunde.bemerkungen != "" { // Bemerkung ist vorhanden, muss im Button bemerkbar sein.. circle?.hidden = false circle?.backgroundColor = UIColor.HTWTextColor() circle?.tag = -9; } bounds = frame addSubview(kurzel!) addSubview(raum!) } // MARK: - Functions for the ViewController var now: Bool = false { didSet{ if stunde.anzeigen.boolValue { backgroundColor = UIColor.HTWBlueColor() kurzel?.textColor = UIColor.HTWWhiteColor() raum?.textColor = UIColor.HTWWhiteColor() typ?.textColor = UIColor.HTWWhiteColor() circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() : UIColor.HTWWhiteColor() } } } var select: Bool = false { didSet{ if select { backgroundColor = UIColor.HTWBlueColor() kurzel?.textColor = UIColor.HTWWhiteColor() raum?.textColor = UIColor.HTWWhiteColor() typ?.textColor = UIColor.HTWWhiteColor() circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() :UIColor.HTWWhiteColor() } else { backgroundColor = UIColor.HTWWhiteColor() kurzel?.textColor = UIColor.HTWDarkGrayColor() raum?.textColor = UIColor.HTWGrayColor() typ?.textColor = UIColor.HTWGrayColor() circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() :UIColor.HTWTextColor() } } } func markLesson() { backgroundColor = UIColor.HTWBlueColor() for view in subviews { if view is UILabel { (view as! UILabel).textColor = UIColor.HTWWhiteColor() } else if view.tag == -9 { (view as! UIView).backgroundColor = UIColor.HTWWhiteColor() } } } func unmarkLesson() { backgroundColor = UIColor.HTWWhiteColor() kurzel?.textColor = UIColor.HTWDarkGrayColor() raum?.textColor = UIColor.HTWGrayColor() typ?.textColor = UIColor.HTWGrayColor() circle?.backgroundColor = circle!.hidden ? UIColor.clearColor() :UIColor.HTWTextColor() } func isNow() -> Bool { if NSDate().inRange(stunde.anfang, date2: stunde.ende) { return true } return false } }
gpl-2.0
80e6434b4552a0161c71ed4e07ef52f1
34.131579
150
0.536865
4.334416
false
false
false
false
nferocious76/NFImageView
Example/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift
1
33025
// // UIButton+AlamofireImage.swift // // Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias ControlState = UIControl.State extension UIButton: AlamofireExtended {} extension AlamofireExtension where ExtendedType: UIButton { // MARK: - Properties /// The instance image downloader used to download all images. If this property is `nil`, the `UIButton` will /// fallback on the `sharedImageDownloader` for all downloads. The most common use case for needing to use a /// custom instance image downloader is when images are behind different basic auth credentials. public var imageDownloader: ImageDownloader? { get { objc_getAssociatedObject(type, &AssociatedKeys.imageDownloader) as? ImageDownloader } nonmutating set { objc_setAssociatedObject(type, &AssociatedKeys.imageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the /// `imageDownloader` is `nil`. public static var sharedImageDownloader: ImageDownloader { get { guard let downloader = objc_getAssociatedObject(UIButton.self, &AssociatedKeys.sharedImageDownloader) as? ImageDownloader else { return ImageDownloader.default } return downloader } set { objc_setAssociatedObject(UIButton.self, &AssociatedKeys.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var imageRequestReceipts: [UInt: RequestReceipt] { get { guard let receipts = objc_getAssociatedObject(type, &AssociatedKeys.imageReceipts) as? [UInt: RequestReceipt] else { return [:] } return receipts } nonmutating set { objc_setAssociatedObject(type, &AssociatedKeys.imageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var backgroundImageRequestReceipts: [UInt: RequestReceipt] { get { guard let receipts = objc_getAssociatedObject(type, &AssociatedKeys.backgroundImageReceipts) as? [UInt: RequestReceipt] else { return [:] } return receipts } nonmutating set { objc_setAssociatedObject(type, &AssociatedKeys.backgroundImageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Image Downloads /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter url: The URL used for your image request. /// - parameter cacheKey: An optional key used to identify the image in the cache. Defaults to `nil`. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// image will not change its image until the image request finishes. Defaults /// to `nil`. /// - parameter serializer: Image response serializer used to convert the image data to `UIImage`. Defaults /// to `nil` which will fall back to the instance `imageResponseSerializer` set on /// the `ImageDownloader`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func setImage(for state: ControlState, url: URL, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { setImage(for: state, urlRequest: urlRequest(with: url), cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter urlRequest: The URL request. /// - parameter cacheKey: An optional key used to identify the image in the cache. Defaults to `nil`. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// image will not change its image until the image request finishes. Defaults /// to `nil`. /// - parameter serializer: Image response serializer used to convert the image data to `UIImage`. Defaults /// to `nil` which will fall back to the instance `imageResponseSerializer` set on /// the `ImageDownloader`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func setImage(for state: ControlState, urlRequest: URLRequestConvertible, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { let response = AFIDataResponse<UIImage>(request: nil, response: nil, data: nil, metrics: nil, serializationDuration: 0.0, result: .failure(AFIError.requestCancelled)) completion?(response) return } cancelImageRequest(for: state) let imageDownloader = self.imageDownloader ?? UIButton.af.sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest { let cachedImage: Image? if let cacheKey = cacheKey { cachedImage = imageCache?.image(withIdentifier: cacheKey) } else { cachedImage = imageCache?.image(for: request, withIdentifier: filter?.identifier) } if let image = cachedImage { let response = AFIDataResponse<UIImage>(request: urlRequest.urlRequest, response: nil, data: nil, metrics: nil, serializationDuration: 0.0, result: .success(image)) type.setImage(image, for: state) completion?(response) return } } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { type.setImage(placeholderImage, for: state) } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Weakify the button to allow it to go out-of-memory while download is running if deallocated weak var button = type // Download the image, then set the image for the control state let requestReceipt = imageDownloader.download(urlRequest, cacheKey: cacheKey, receiptID: downloadID, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: { response in guard let strongSelf = button?.af, strongSelf.isImageURLRequest(response.request, equalToActiveRequestURLForState: state) && strongSelf.imageRequestReceipt(for: state)?.receiptID == downloadID else { completion?(response) return } if case let .success(image) = response.result { strongSelf.type.setImage(image, for: state) } strongSelf.setImageRequestReceipt(nil, for: state) completion?(response) }) setImageRequestReceipt(requestReceipt, for: state) } /// Cancels the active download request for the image, if one exists. public func cancelImageRequest(for state: ControlState) { guard let receipt = imageRequestReceipt(for: state) else { return } let imageDownloader = self.imageDownloader ?? UIButton.af.sharedImageDownloader imageDownloader.cancelRequest(with: receipt) setImageRequestReceipt(nil, for: state) } // MARK: - Background Image Downloads /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter url: The URL used for the image request. /// - parameter cacheKey: An optional key used to identify the image in the cache. Defaults to `nil`. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// background image will not change its image until the image request finishes. /// Defaults to `nil`. /// - parameter serializer: Image response serializer used to convert the image data to `UIImage`. Defaults /// to `nil` which will fall back to the instance `imageResponseSerializer` set on /// the `ImageDownloader`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func setBackgroundImage(for state: ControlState, url: URL, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { setBackgroundImage(for: state, urlRequest: urlRequest(with: url), cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } /// Asynchronously downloads an image from the specified URL request and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placeholder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter urlRequest: The URL request. /// - parameter cacheKey: An optional key used to identify the image in the cache. Defaults to `nil`. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// background image will not change its image until the image request finishes. /// Defaults to `nil`. /// - parameter serializer: Image response serializer used to convert the image data to `UIImage`. Defaults /// to `nil` which will fall back to the instance `imageResponseSerializer` set on /// the `ImageDownloader`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func setBackgroundImage(for state: ControlState, urlRequest: URLRequestConvertible, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { let response = AFIDataResponse<UIImage>(request: nil, response: nil, data: nil, metrics: nil, serializationDuration: 0.0, result: .failure(AFIError.requestCancelled)) completion?(response) return } cancelBackgroundImageRequest(for: state) let imageDownloader = self.imageDownloader ?? UIButton.af.sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest { let cachedImage: Image? if let cacheKey = cacheKey { cachedImage = imageCache?.image(withIdentifier: cacheKey) } else { cachedImage = imageCache?.image(for: request, withIdentifier: filter?.identifier) } if let image = cachedImage { let response = AFIDataResponse<UIImage>(request: urlRequest.urlRequest, response: nil, data: nil, metrics: nil, serializationDuration: 0.0, result: .success(image)) type.setBackgroundImage(image, for: state) completion?(response) return } } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { type.setBackgroundImage(placeholderImage, for: state) } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Weakify the button to allow it to go out-of-memory while download is running if deallocated weak var button = type // Download the image, then set the image for the control state let requestReceipt = imageDownloader.download(urlRequest, cacheKey: cacheKey, receiptID: downloadID, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: { response in guard let strongSelf = button?.af, strongSelf.isBackgroundImageURLRequest(response.request, equalToActiveRequestURLForState: state) && strongSelf.backgroundImageRequestReceipt(for: state)?.receiptID == downloadID else { completion?(response) return } if case let .success(image) = response.result { strongSelf.type.setBackgroundImage(image, for: state) } strongSelf.setBackgroundImageRequestReceipt(nil, for: state) completion?(response) }) setBackgroundImageRequestReceipt(requestReceipt, for: state) } /// Cancels the active download request for the background image, if one exists. public func cancelBackgroundImageRequest(for state: ControlState) { guard let receipt = backgroundImageRequestReceipt(for: state) else { return } let imageDownloader = self.imageDownloader ?? UIButton.af.sharedImageDownloader imageDownloader.cancelRequest(with: receipt) setBackgroundImageRequestReceipt(nil, for: state) } // MARK: - Internal - Image Request Receipts func imageRequestReceipt(for state: ControlState) -> RequestReceipt? { guard let receipt = imageRequestReceipts[state.rawValue] else { return nil } return receipt } func setImageRequestReceipt(_ receipt: RequestReceipt?, for state: ControlState) { var receipts = imageRequestReceipts receipts[state.rawValue] = receipt imageRequestReceipts = receipts } // MARK: - Internal - Background Image Request Receipts func backgroundImageRequestReceipt(for state: ControlState) -> RequestReceipt? { guard let receipt = backgroundImageRequestReceipts[state.rawValue] else { return nil } return receipt } func setBackgroundImageRequestReceipt(_ receipt: RequestReceipt?, for state: ControlState) { var receipts = backgroundImageRequestReceipts receipts[state.rawValue] = receipt backgroundImageRequestReceipts = receipts } // MARK: - Private - URL Request Helpers private func isImageURLRequest(_ urlRequest: URLRequestConvertible?, equalToActiveRequestURLForState state: ControlState) -> Bool { if let currentURL = imageRequestReceipt(for: state)?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentURL == requestURL { return true } return false } private func isBackgroundImageURLRequest(_ urlRequest: URLRequestConvertible?, equalToActiveRequestURLForState state: ControlState) -> Bool { if let currentRequestURL = backgroundImageRequestReceipt(for: state)?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentRequestURL == requestURL { return true } return false } private func urlRequest(with url: URL) -> URLRequest { var urlRequest = URLRequest(url: url) for mimeType in ImageResponseSerializer.acceptableImageContentTypes { urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") } return urlRequest } } // MARK: - Deprecated extension UIButton { @available(*, deprecated, message: "Replaced by `button.af.imageDownloader`") public var af_imageDownloader: ImageDownloader? { get { af.imageDownloader } set { af.imageDownloader = newValue } } @available(*, deprecated, message: "Replaced by `button.af.sharedImageDownloader`") public class var af_sharedImageDownloader: ImageDownloader { get { af.sharedImageDownloader } set { af.sharedImageDownloader = newValue } } @available(*, deprecated, message: "Replaced by `button.af.sharedImageDownloader`") public func af_setImage(for state: ControlState, url: URL, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { af.setImage(for: state, url: url, cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } @available(*, deprecated, message: "Replaced by `button.af.sharedImageDownloader`") public func af_setImage(for state: ControlState, urlRequest: URLRequestConvertible, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { af.setImage(for: state, urlRequest: urlRequest, cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } /// Cancels the active download request for the image, if one exists. public func af_cancelImageRequest(for state: ControlState) { af.cancelImageRequest(for: state) } @available(*, deprecated, message: "Replaced by `button.af.sharedImageDownloader`") public func af_setBackgroundImage(for state: ControlState, url: URL, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { af.setBackgroundImage(for: state, url: url, cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } @available(*, deprecated, message: "Replaced by `button.af.sharedImageDownloader`") public func af_setBackgroundImage(for state: ControlState, urlRequest: URLRequestConvertible, cacheKey: String? = nil, placeholderImage: UIImage? = nil, serializer: ImageResponseSerializer? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((AFIDataResponse<UIImage>) -> Void)? = nil) { af.setBackgroundImage(for: state, urlRequest: urlRequest, cacheKey: cacheKey, placeholderImage: placeholderImage, serializer: serializer, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion) } /// Cancels the active download request for the background image, if one exists. public func af_cancelBackgroundImageRequest(for state: ControlState) { af.cancelBackgroundImageRequest(for: state) } } // MARK: - Private - AssociatedKeys private struct AssociatedKeys { static var imageDownloader = "UIButton.af.imageDownloader" static var sharedImageDownloader = "UIButton.af.sharedImageDownloader" static var imageReceipts = "UIButton.af.imageReceipts" static var backgroundImageReceipts = "UIButton.af.backgroundImageReceipts" } #endif
mit
b0334905320ebbd1c38820bd3c17dcaf
52.525122
161
0.539773
6.440133
false
false
false
false
applivery/applivery-ios-sdk
AppliveryBehaviorTests/Mocks/UpdateViewMock.swift
1
746
// // UpdateViewMock.swift // AppliverySDK // // Created by Alejandro Jiménez on 8/12/15. // Copyright © 2015 Applivery S.L. All rights reserved. // import Foundation @testable import Applivery class UpdateViewMock: UpdateView { // OUTPUTS var spyShowUpdateMessage = (called: false, message: "") var spyShowLoadingCalled = false var spyStopLoadingCalled = false var spyShowErrorMessage = (called: false, message: "") func showUpdateMessage(_ message: String) { self.spyShowUpdateMessage = (true, message) } func showLoading() { self.spyShowLoadingCalled = true } func stopLoading() { self.spyStopLoadingCalled = true } func showErrorMessage(_ message: String) { self.spyShowErrorMessage = (true, message) } }
mit
a56a7f8a7b42629497ee77f3ff9645dd
18.578947
56
0.723118
3.444444
false
false
false
false
100mango/SwiftNotificationCenter
Example/Example/NotificationProtocol.swift
1
1389
// // NotificationProtocol.swift // SwiftNotificationCenterExample // // Created by Mango on 16/5/5. // Copyright © 2016年 Mango. All rights reserved. // import UIKit protocol UpdateTitle: class { func updateWithNewTitle(title: String) } protocol UIKeyboardManage { func UIKeyboardWillShow(beginFrame: CGRect, endFrame: CGRect) } class UIKeyboardSystemNotifictionMediator { static let mediator = UIKeyboardSystemNotifictionMediator() @objc func handleKeyboardNotification(notification: NSNotification) { guard notification.name == UIResponder.keyboardWillShowNotification else { return } guard let beginFrame = (notification .userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return } guard let endFrame = (notification .userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } Broadcaster.notify(UIKeyboardManage.self) { $0.UIKeyboardWillShow(beginFrame: beginFrame, endFrame: endFrame) } } static let register: () = { NotificationCenter.default.addObserver(mediator, selector: #selector(handleKeyboardNotification(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) }() }
mit
c9732c98ad3f370221096e59a0df87b3
27.875
181
0.683983
5.330769
false
false
false
false
Rhapsody/Observable-Swift
Observable-Swift/Observable.swift
1
1518
// // Observable.swift // Observable-Swift // // Created by Leszek Ślażyński on 20/06/14. // Copyright (c) 2014 Leszek Ślażyński. All rights reserved. // /// A struct representing information associated with value change event. public struct ValueChange<T> { public let oldValue: T public let newValue: T public init(_ o: T, _ n: T) { oldValue = o newValue = n } } // Implemented as a struct in order to have desired value and mutability sementics. /// A struct representing an observable value. public struct Observable<T> : UnownableObservable { public typealias ValueType = T public /*internal(set)*/ var beforeChange = EventReference<ValueChange<T>>() public /*internal(set)*/ var afterChange = EventReference<ValueChange<T>>() public var value : T { willSet { beforeChange.notify(ValueChange(value, newValue)) } didSet { afterChange.notify(ValueChange(oldValue, value)) } } public mutating func unshare(removeSubscriptions: Bool) { if removeSubscriptions { beforeChange = EventReference<ValueChange<T>>() afterChange = EventReference<ValueChange<T>>() } else { beforeChange = EventReference<ValueChange<T>>(event: beforeChange.event) beforeChange.event.unshare() afterChange = EventReference<ValueChange<T>>(event: afterChange.event) afterChange.event.unshare() } } public init(_ v : T) { value = v } }
mit
8cb9a27dc3423d4ae39fb95f6cbd25cb
29.857143
84
0.652778
4.581818
false
false
false
false
fespinoza/linked-ideas-osx
LinkedIdeasTests/ViewControllers/CanvasViewControllerMouseTests.swift
1
11339
// // CanvasViewControllerMouseTests.swift // LinkedIdeas // // Created by Felipe Espinoza Castillo on 29/05/2017. // Copyright © 2017 Felipe Espinoza Dev. All rights reserved. // import XCTest @testable import LinkedIdeas_Shared @testable import LinkedIdeas // MARK: - CanvasViewControllers: Mouse Tests extension CanvasViewControllerTests { func testDoubleClickInCanvas() { let clickedPoint = CGPoint(x: 200, y: 300) let mouseEvent = createMouseEvent(clickCount: 2, location: clickedPoint) canvasViewController.mouseDown(with: mouseEvent) XCTAssertEqual(canvasViewController.currentState, .newConcept(point: clickedPoint)) } func testSingleClickInCanvasWhenConceptIsBeingCreated() { canvasViewController.currentState = .newConcept(point: CGPoint.zero) let clickedPoint = CGPoint(x: 200, y: 300) let mouseEvent = createMouseEvent(clickCount: 1, location: clickedPoint) canvasViewController.mouseDown(with: mouseEvent) XCTAssertEqual(canvasViewController.currentState, .canvasWaiting) } func testSingleClickOnCanvasWhenConceptIsSelected() { let concept = Concept(stringValue: "Foo bar", centerPoint: CGPoint(x: 200, y: 300)) document.concepts.append(concept) canvasViewController.currentState = .selectedElement(element: concept) let clickedPoint = CGPoint(x: 10, y: 20) let clickEvent = createMouseEvent(clickCount: 1, location: clickedPoint) canvasViewController.mouseDown(with: clickEvent) XCTAssertEqual(canvasViewController.currentState, .canvasWaiting) } func testSingleClickOnConcept() { let clickedPoint = CGPoint(x: 200, y: 300) let conceptPoint = clickedPoint let concept = Concept(stringValue: "Foo bar", centerPoint: conceptPoint) document.concepts.append(concept) let clickEvent = createMouseEvent(clickCount: 1, location: clickedPoint) canvasViewController.fullClick(event: clickEvent) XCTAssertEqual(canvasViewController.currentState, .selectedElement(element: concept)) } func testShiftClickOnAnotherConcept() { let oldConcept = Concept(stringValue: "#1 selected", centerPoint: CGPoint(x: 20, y: 600)) document.concepts.append(oldConcept) let clickedPoint = CGPoint(x: 200, y: 300) let conceptPoint = clickedPoint let concept = Concept(stringValue: "#2 selected", centerPoint: conceptPoint) document.concepts.append(concept) canvasViewController.currentState = .selectedElement(element: oldConcept) let shiftClickEvent = createMouseEvent(clickCount: 1, location: clickedPoint, shift: true) canvasViewController.fullClick(event: shiftClickEvent) XCTAssertEqual(canvasViewController.currentState, .multipleSelectedElements(elements: [oldConcept, concept])) } func testShiftClickOnAlreadySelectedConcept() { let oldConcept = Concept(stringValue: "Random", centerPoint: CGPoint(x: 20, y: 600)) document.concepts.append(oldConcept) let clickedPoint = CGPoint(x: 200, y: 300) let conceptPoint = clickedPoint let concept = Concept(stringValue: "Foo bar", centerPoint: conceptPoint) document.concepts.append(concept) canvasViewController.currentState = .multipleSelectedElements(elements: [oldConcept, concept]) let shiftClickEvent = createMouseEvent(clickCount: 1, location: clickedPoint, shift: true) canvasViewController.fullClick(event: shiftClickEvent) XCTAssertEqual(canvasViewController.currentState, .selectedElement(element: oldConcept)) } func testShiftClickOnCanvas() { let oldConcept = Concept(stringValue: "Random", centerPoint: CGPoint(x: 20, y: 600)) document.concepts.append(oldConcept) let clickedPoint = CGPoint(x: 200, y: 300) let conceptPoint = CGPoint(x: 600, y: 800) let concept = Concept(stringValue: "Foo bar", centerPoint: conceptPoint) document.concepts.append(concept) canvasViewController.currentState = .selectedElement(element: oldConcept) let shiftClickEvent = createMouseEvent(clickCount: 1, location: clickedPoint, shift: true) canvasViewController.fullClick(event: shiftClickEvent) XCTAssertEqual(canvasViewController.currentState, .canvasWaiting) } func testShiftDragFromOneConceptToAnotherToCreateLink() { let oldConcept = Concept(stringValue: "Random", centerPoint: CGPoint(x: 20, y: 600)) document.concepts.append(oldConcept) let conceptPoint = CGPoint(x: 600, y: 800) let concept = Concept(stringValue: "Foo bar", centerPoint: conceptPoint) document.concepts.append(concept) canvasViewController.mouseDown(with: createMouseEvent(clickCount: 1, location: oldConcept.centerPoint, shift: true)) canvasViewController.mouseDragged( with: createMouseEvent( clickCount: 1, location: oldConcept.centerPoint.translate(deltaX: 10, deltaY: 20), shift: true ) ) canvasViewController.mouseDragged(with: createMouseEvent(clickCount: 1, location: concept.centerPoint, shift: true)) canvasViewController.mouseUp(with: createMouseEvent(clickCount: 1, location: concept.centerPoint, shift: true)) switch canvasViewController.currentState { case .selectedElement(let element): if (element as? Link) == nil { Swift.print(element) XCTFail("a link should have been created an selected") } default: XCTFail("current state should be selected element") } } func testShiftDragFromOneConceptToAnotherToCreateLinkWhileAnotherConceptIsSelected() { // Given let concepts = [ Concept(stringValue: "#1", centerPoint: CGPoint(x: 20, y: 600)), Concept(stringValue: "#2", centerPoint: CGPoint(x: 120, y: 1600)), Concept(stringValue: "#3", centerPoint: CGPoint(x: 200, y: 300)), ] concepts.forEach { document.concepts.append($0) } canvasViewController.currentState = .selectedElement(element: concepts[0]) // When canvasViewController.mouseDown( with: createMouseEvent(clickCount: 1, location: concepts[1].centerPoint, shift: true) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: concepts[1].centerPoint, shift: true) ) canvasViewController.mouseDragged( with: createMouseEvent( clickCount: 1, location: concepts[1].centerPoint.translate(deltaX: 1, deltaY: 2), shift: true ) ) canvasViewController.mouseDragged( with: createMouseEvent( clickCount: 1, location: concepts[1].centerPoint.translate(deltaX: 10, deltaY: 20), shift: true ) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: concepts[2].centerPoint, shift: true) ) canvasViewController.mouseUp(with: createMouseEvent(clickCount: 1, location: concepts[2].centerPoint, shift: true)) // Then switch canvasViewController.currentState { case .selectedElement(let element): if let link = element as? Link { XCTAssertEqual(link.origin, concepts[1]) XCTAssertEqual(link.target, concepts[2]) } else { Swift.print(element) XCTFail("a link should have been created an selected") } default: XCTFail("current state should be selected element, not \(canvasViewController.currentState)") } } func testDragRightHandlerForASelectedConcept() { let concept = Concept(stringValue: "Foo bar", centerPoint: CGPoint(x: 200, y: 300)) let initialConceptArea = concept.area document.concepts.append(concept) concept.isSelected = true canvasViewController.currentState = .selectedElement(element: concept) // when drag guard let rightHandler = concept.rightHandler else { XCTFail("❌ the concept is supposed to be selected, then the right handler should be available") return } let clickedPoint = rightHandler.area.center canvasViewController.mouseDown( with: createMouseEvent(clickCount: 1, location: clickedPoint) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: 10, deltaY: 0)) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: 20, deltaY: 10)) ) canvasViewController.mouseUp( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: 20, deltaY: 10)) ) XCTAssertEqual(canvasViewController.currentState, .selectedElement(element: concept)) XCTAssertNotEqual(initialConceptArea, concept.area) } func testDragLeftHandlerForASelectedConcept() { let concept = Concept(stringValue: "Foo bar", centerPoint: CGPoint(x: 200, y: 300)) let initialConceptArea = concept.area document.concepts.append(concept) concept.isSelected = true canvasViewController.currentState = .selectedElement(element: concept) // when drag guard let leftHandler = concept.leftHandler else { XCTFail("❌ the concept is supposed to be selected, then the left handler should be available") return } let clickedPoint = leftHandler.area.center canvasViewController.mouseDown( with: createMouseEvent(clickCount: 1, location: clickedPoint) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: -10, deltaY: 0)) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: -20, deltaY: 10)) ) canvasViewController.mouseUp( with: createMouseEvent(clickCount: 1, location: clickedPoint.translate(deltaX: -20, deltaY: 10)) ) XCTAssertEqual(canvasViewController.currentState, .selectedElement(element: concept)) XCTAssertNotEqual(initialConceptArea, concept.area) } func testShiftDragFromOneConceptToAnotherToCreateLinkWhenAnotherLinkIsSelected() { let concepts = [ Concept(stringValue: "Random", centerPoint: CGPoint(x: 20, y: 600)), Concept(stringValue: "Foo bar", centerPoint: CGPoint(x: 600, y: 800)), Concept(stringValue: "Another", centerPoint: CGPoint(x: 300, y: 400)), ] concepts.forEach { document.concepts.append($0) } let link = Link(origin: concepts[0], target: concepts[1]) document.links.append(link) canvasViewController.currentState = .selectedElement(element: link) canvasViewController.mouseDown( with: createMouseEvent(clickCount: 1, location: concepts[1].centerPoint, shift: true) ) canvasViewController.mouseDragged( with: createMouseEvent( clickCount: 1, location: concepts[1].centerPoint.translate(deltaX: 10, deltaY: 20), shift: true ) ) canvasViewController.mouseDragged( with: createMouseEvent(clickCount: 1, location: concepts[2].centerPoint, shift: true) ) canvasViewController.mouseUp(with: createMouseEvent(clickCount: 1, location: concepts[2].centerPoint, shift: true)) switch canvasViewController.currentState { case .selectedElement(let element): if let selectedLink = element as? Link { XCTAssertNotEqual(selectedLink, link) } else { XCTFail("a link should have been created an selected") } default: XCTFail("current state should be selected element") } } }
mit
8a98a98f2224c8ef21cc023e4b69a74f
35.798701
120
0.726575
4.415271
false
true
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/RemoteManagerImpl.swift
1
2363
class RemoteManagerImpl{ var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/Manager/" } internal func compositeCallURL(methodName: String, parameters:[String]) -> String { var resultURL = remoteURLPrefix /* This will be available in Swift 3.0 resultURL.append(methodName) resultURL.append("/") */ resultURL += methodName resultURL += "/" for parameter in parameters{ /* This will be available in Swift 3.0 resultURL.append(parameter) resultURL.append("/") */ resultURL += parameter resultURL += ".json" } return resultURL } internal func compositeCallURL2(methodName: String, parameters:[String]) -> String { var resultURL = remoteURLPrefix /* This will be available in Swift 3.0 resultURL.append(methodName) resultURL.append("/") */ resultURL += methodName resultURL += "/" for parameter in parameters{ /* This will be available in Swift 3.0 resultURL.append(parameter) resultURL.append("/") */ resultURL += parameter resultURL += "/" } return resultURL } /* let headers = ["Content-Type","applicaiton/json"] Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) .responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } ) */ internal func compositeCallURL(methodName: String) -> String { //Simple method, do not need to call compositeCallURL(methodName: String, parameters:[String]) -> String var resultURL = remoteURLPrefix /* This will be available in Swift 3.0 resultURL.append(methodName) resultURL.append("/") */ resultURL += methodName resultURL += "/" return resultURL } }
mit
aec323edd8e5aaa16955c8cc93fa6aa2
21.166667
106
0.564537
4.535509
false
false
false
false
Eonil/EditorLegacy
Modules/EditorWorkspaceNavigationFeature/Workbench1/AppDelegate.swift
1
1240
// // AppDelegate.swift // Workbench1 // // Created by Hoon H. on 2015/02/22. // Copyright (c) 2015 Eonil. All rights reserved. // import Cocoa import EditorWorkspaceNavigationFeature @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, WorkspaceNavigationViewControllerDelegate { @IBOutlet weak var window: NSWindow! // let sv = NSScrollView() let nv = WorkspaceNavigationViewController() func applicationDidFinishLaunching(aNotification: NSNotification) { window.appearance = NSAppearance(named: NSAppearanceNameVibrantDark) nv.delegate = self // sv.documentView = nv.view window.contentView = nv.view let u = NSBundle.mainBundle().URLForResource("TestData/Test1", withExtension: "eews") // let u = NSURL(fileURLWithPath: "/Users/Eonil/Documents/eewstest/Test1.eews")! nv.URLRepresentation = u } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func saveWorkspaceRepositoryConfiguration(AnyObject?) { nv.persistToFileSystem() } func workpaceNavigationViewControllerWantsToOpenFileAtURL(u: NSURL) { println("workpaceNavigationViewControllerWantsToOpenFileAtURL") println(u) } }
mit
82eea0a6af23b8a738488fbcfe5f1c63
22.396226
95
0.762903
3.780488
false
true
false
false
64characters/Telephone
UseCases/URI.swift
1
4637
// // URI.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation public final class URI: NSObject { @objc public let user: String @objc public let address: ServiceAddress @objc public let displayName: String @objc public let transport: Transport @objc public var host: String { return address.host } @objc public var port: String { return address.port } @objc public var stringValue: String { var a = user.isEmpty ? "\(address)" : "\(user)@\(address)" if transport == .tcp || transport == .tls { a.append(";transport=\(transport.stringValue)") } return displayName.isEmpty ? "sip:\(a)" : "\"\(displayName)\" <sip:\(a)>" } public override var description: String { return stringValue } @objc public init(user: String, address: ServiceAddress, displayName: String, transport: Transport = .udp) { self.user = user self.address = address self.displayName = displayName self.transport = transport } @objc public convenience init(user: String, host: String, displayName: String, transport: Transport = .udp) { self.init(user: user, address: ServiceAddress(host: host), displayName: displayName, transport: transport) } @objc public convenience init(address: ServiceAddress, transport: Transport = .udp) { self.init(user: "", address: address, displayName: "", transport: transport) } @objc public convenience init(host: String, port: String, transport: Transport = .udp) { self.init(address: ServiceAddress(host: host, port: port), transport: transport) } @objc public convenience init(host: String, transport: Transport = .udp) { self.init(address: ServiceAddress(host: host), transport: transport) } @objc(URIWithHost:port:transport:) public class func uri(host: String, port: String, transport: Transport) -> URI { return URI(host: host, port: port, transport: transport) } @objc(URIWithHost:transport:) public class func uri(host: String, transport: Transport) -> URI { return URI(host: host, transport: transport) } } public extension URI { @objc(initWithString:) convenience init?(_ string: String) { if let regex = try? NSRegularExpression(pattern: pattern), let match = regex.firstMatch(in: string, range: NSRange(string.startIndex..<string.endIndex, in: string)) { let host = substring(for: match.range(at: 4), in: string) if substring(for: match.range(at: 2), in: string).lowercased() == "sip" { self.init( user: substring(for: match.range(at: 3), in: string), host: host, displayName: substring(for: match.range(at: 1), in: string) ) } else { self.init(user: host, host: "", displayName: substring(for: match.range(at: 1), in: string)) } } else { return nil } } } extension URI { public override func isEqual(_ object: Any?) -> Bool { guard let uri = object as? URI else { return false } return isEqual(to: uri) } public override var hash: Int { var hasher = Hasher() hasher.combine(user) hasher.combine(address) hasher.combine(displayName) hasher.combine(transport) return hasher.finalize() } private func isEqual(to uri: URI) -> Bool { return user == uri.user && address == uri.address && displayName == uri.displayName && transport == uri.transport } } private func substring(for range: NSRange, in string: String) -> String { return Range(range, in: string).map { String(string[$0]) } ?? "" } private let pattern = #""" (?x) # Free-spacing mode. ^ "?(.*?)"? # Optional full name with optional quotes. \s? <? (?i)(sip|tel)(?-i): # Case-insensitive scheme. (?:(.+)@)?([^>]+) # Optional user and non-optional host excluding the > character. >? $ """#
gpl-3.0
73db14cb55815913631d3d41e5e2ea25
35.785714
121
0.626106
4.16442
false
false
false
false
tinrobots/Mechanica
Sources/Foundation/NSAttributedString+Utils.swift
1
2697
#if canImport(Foundation) import Foundation extension NSAttributedString { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) // MARK: - Initializers /// **Mechanica** /// /// Initializes and returns a `new` NSAttributedString object from the `html` contained in the given string. /// - Parameters: /// - html: an HTML string. /// - allowLossyConversion: If it is *true* and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. /// For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent. /// - Note: The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import. /// [Apple Documentation](https://developer.apple.com/reference/foundation/nsattributedstring/1524613-init) /// - Warning: Using the HTML importer (NSHTMLTextDocumentType) is only possible on the **main thread**. public convenience init?(html: String, allowLossyConversion: Bool = false) { guard let data = html.data(using: .utf8, allowLossyConversion: allowLossyConversion) else { return nil } try? self.init(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) } #endif // MARK: - Operators /// **Mechanica** /// /// Returns a `new` NSAttributedString appending the right NSAttributedString to the left NSAttributedString. static public func + (lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString { let attributedString = NSMutableAttributedString(attributedString: lhs) attributedString.append(rhs) return NSAttributedString(attributedString: attributedString) } /// **Mechanica** /// /// Returns a `new` NSAttributedString appending the right String to the left NSAttributedString. static func + (lhs: NSAttributedString, rhs: String) -> NSAttributedString { // swiftlint:disable force_cast let attributedString = lhs.mutableCopy() as! NSMutableAttributedString return (attributedString + rhs).copy() as! NSAttributedString // swiftlint:enable force_cast } /// **Mechanica** /// /// Returns a `new` NSAttributedString appending the right NSAttributedString to the left String. static public func + (lhs: String, rhs: NSAttributedString) -> NSAttributedString { let attributedString = NSMutableAttributedString(string: lhs) // swiftlint:disable:next force_cast return (attributedString + rhs).copy() as! NSAttributedString } //#endif } #endif
mit
7c25e3fcb490c5f6002de6a31cdb5e1f
41.634921
173
0.721519
4.874773
false
false
false
false
mennovf/Swift-MathEagle
MathEagle/Source/Optimization.swift
1
1312
// // Optimization.swift // SwiftMath // // Created by Rugen Heidbuchel on 27/01/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Foundation public class Optimization { //MARK: Parameters public static var accuracy = 1e-7 public static var maxTime = 10.0 public class func goldenSection(a0: Double, _ b0: Double, k_max: Int = 100, error err: Double? = nil, maxTime t_m: Double? = nil, f: (Double) -> Double) -> Double { let start = NSDate() let error = err ?? accuracy let t_max = t_m ?? maxTime var a = a0, b = b0 var v = a + INVERSE_GOLDEN_RATIO*(b-a) var fv = f(v) var u = a + b - v var fu = f(u) let k = 1 while k <= k_max && b-a > 2*error && NSDate().timeIntervalSinceDate(start) < t_max { if fu >= fv { a = u u = v fu = fv v = b - u + a fv = f(v) } else { b = v v = u fv = fu u = a + b - v fu = f(u) } } return (a+b)/2 } }
mit
5e346d4e8b626c0a9093bcf3c11617c5
22.446429
168
0.405488
3.987842
false
false
false
false
eigengo/reactive-architecture-cookbook-code
eas/ios/EAS/ViewController.swift
1
1289
// // ViewController.swift // EAS // // Created by Jan Machacek on 19/03/2017. // Copyright © 2017 Jan Machacek. All rights reserved. // import UIKit import ProtocolBuffers class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() foo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func foo() { let cs = ClientSession(url: URL(string: "http://localhost:8080/session")!, token: Data()) let sensor = try! Sensor.Builder().setLocation(SensorLocation.wrist).setDataTypes([SensorDataType.acceleration]).build() let values = [Float32](repeating: 0.987, count: 3600 * 50 * 3) let sensorData = try! SensorData.Builder().setSensors([sensor]).setValues(values).build() let s = try! Session.Builder().setSessionId(UUID().uuidString).setSensorData(sensorData).build() cs.upload(session: s) { data, response, error in if let data = data, let s = String(data: data, encoding: .utf8) { print("data = ", s) } if let response = response { print("response = ", response) } if let error = error { print("error = ", error) } } } }
gpl-3.0
a670848dc389e9c60375f485b44c599a
32.025641
128
0.634317
4.115016
false
false
false
false
sundeepgupta/butterfly
butterflyTests/SettingsVcSpec.swift
1
2355
import Quick import Nimble import butterfly class SettingsVcSpec: QuickSpec { override func spec() { var subject: SettingsVc! beforeEach { let storyboard = UIStoryboard(name: Constants.storyboardName, bundle: nil) let name = Utils.stringForClass(SettingsVc) subject = storyboard.instantiateViewControllerWithIdentifier(name) as! SettingsVc } context("IB connections.") { it("Connects the save button.") { let button = subject.navigationItem.rightBarButtonItem let selector: Selector = "save" expect(button?.action).to(equal(selector)) expect(subject.respondsToSelector(selector)).to(beTrue()) } it("Connects the cancel button.") { let button = subject.navigationItem.leftBarButtonItem let selector: Selector = "cancel" expect(button?.action).to(equal("cancel")) expect(subject.respondsToSelector(selector)).to(beTrue()) } it("Connects its outlets.") { subject.loadView() expect(subject.emailField).toNot(beNil()) } } context("Email") { func load(viewController: UIViewController) { viewController.loadView() viewController.viewDidLoad() } it("Renders the currently configured email") { let email = "[email protected]" Settings().saveEmail(email) load(subject) expect(subject.emailField.text).to(equal(email)) } it("Trims whitespace") { load(subject) subject.emailField.text = " [email protected] " let button = subject.navigationItem.rightBarButtonItem let selector = button?.action let app = UIApplication.sharedApplication() app.sendAction(selector!, to: subject, from: nil, forEvent: nil) expect(subject.emailField.text).to(equal("[email protected]")) } } } }
mit
58679707b2d9b637af2b5c399c7c4e9f
34.681818
93
0.512527
5.858209
false
false
false
false
Intercambio/CloudService
CloudService/CloudService/Path.swift
1
2482
// // Path.swift // CloudService // // Created by Tobias Kräntzer on 20.02.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import Foundation public struct Path: Hashable, Equatable, CustomStringConvertible { public let components: [String] public init() { self.components = [] } public init(components: [String]) { self.components = components } public init(href: String) { if href == "/" { self.components = [] } else { let components: [String] = href.components(separatedBy: "/") self.components = Array(components.dropFirst(1)) } } public var length: Int { return components.count } public var href: String { return "/\(components.joined(separator: "/"))" } public var isRoot: Bool { return components.count == 0 } public var name: String { return components.last ?? "/" } public var parent: Path? { guard components.count > 0 else { return nil } return Path(components: Array(components.dropLast(1))) } public var hashValue: Int { return components.count } public func isParent(of path: Path) -> Bool { return self == path.parent } public func isChild(of path: Path) -> Bool { return parent == path } public func isAncestor(of path: Path) -> Bool { return self != path && path.components.starts(with: components) } public func isDescendant(of path: Path) -> Bool { return self != path && components.starts(with: path.components) } public func appending(_ component: String) -> Path { var components = self.components components.append(component) return Path(components: components) } public func appending(_ components: [String]) -> Path { var comp = self.components comp.append(contentsOf: components) return Path(components: comp) } public static func ==(lhs: Path, rhs: Path) -> Bool { guard lhs.components.count == rhs.components.count else { return false } return zip(lhs.components, rhs.components).contains { (lhs, rhs) -> Bool in return lhs != rhs } == false } public var description: String { return href } }
gpl-3.0
82be056cdaf454cdda1f9a6649cd7cd8
24.040404
83
0.56434
4.573801
false
false
false
false
ccloveswift/CLSCommon
Classes/Core/class_log.swift
1
4007
// // class_log.swift // Pods // // Created by Cc on 2017/7/23. // // import Foundation public func CLSLogError(_ format: String, file: String = #file, method: String = #function, line: Int = #line) { class_log.instance.fCLSLog(class_log.logLevel.error, format, file, method, line, "") } public func CLSLogError(_ format: String, file: String = #file, method: String = #function, line: Int = #line, _ args: CVarArg...) { class_log.instance.fCLSLog(class_log.logLevel.error, format, file, method, line, args) } public func CLSLogWarn(_ format: String, file: String = #file, method: String = #function, line: Int = #line) { class_log.instance.fCLSLog(class_log.logLevel.warn, format, file, method, line, "") } public func CLSLogWarn(_ format: String, file: String = #file, method: String = #function, line: Int = #line, _ args: CVarArg...) { class_log.instance.fCLSLog(class_log.logLevel.warn, format, file, method, line, args) } public func CLSLogInfo(_ format: String, file: String = #file, method: String = #function, line: Int = #line) { class_log.instance.fCLSLog(class_log.logLevel.info, format, file, method, line, "") } public func CLSLogInfo(_ format: String, file: String = #file, method: String = #function, line: Int = #line, _ args: CVarArg...) { class_log.instance.fCLSLog(class_log.logLevel.info, format, file, method, line, args) } public func CLSLogDebug(_ format: String, file: String = #file, method: String = #function, line: Int = #line) { class_log.instance.fCLSLog(class_log.logLevel.debug, format, file, method, line, "") } public func CLSLogDebug(_ format: String, file: String = #file, method: String = #function, line: Int = #line, _ args: CVarArg...) { class_log.instance.fCLSLog(class_log.logLevel.debug, format, file, method, line, args) } public class class_log { public enum logLevel { case silent case error case warn case info case debug case verbose } public static let instance = class_log() public var mLogBlock: ((_ level: logLevel, _ format: String, _ file: String, _ method: String, _ line: Int, _ args: CVarArg...) ->Void)? public var mLogPrinter: class_log_print? private init() {} deinit { mLogBlock = nil } public func fCLSLog(_ level: logLevel, _ format: String, _ file: String, _ method: String, _ line: Int, _ args: CVarArg...) { if let block = mLogBlock { block(level, format, file, method, line, args) } if let printer = mLogPrinter { printer.fCLSLog(level, format, file, method, line, args) } } } open class class_log_print { private var mDateFormatter: DateFormatter? private func sGotHead() -> String { if mDateFormatter == nil { let formatter = DateFormatter.init() formatter.dateFormat = "[MMMM dd,yyyy HH:mm:ss.SSS]" mDateFormatter = formatter } let date = Date.init() let str = mDateFormatter!.string(from: date) return str } private func sGot2Head(_ level: class_log.logLevel) -> String { switch level { case .debug: return "[---Debug---]" case .error: return "[---Error---]" case .warn: return "[---Warn---]" case .info: return "[---Info---]" default: return "[---S/N---]" } } public init() { } open func fCLSLog(_ level: class_log.logLevel, _ format: String, _ file: String, _ method: String, _ line: Int, _ args: CVarArg...) { let fn = "[\((file as NSString).lastPathComponent):\(line)]" Swift.print(self.sGotHead(), fn, self.sGot2Head(level), String.init(format: format, args)) } }
mit
6030b1290eebab5b39190144e9c7ed4f
29.356061
140
0.578987
3.73439
false
false
false
false
ikesyo/Result
Result/Result.swift
1
7658
// Copyright (c) 2015 Rob Rix. All rights reserved. /// An enum representing either a failure with an explanatory error, or a success with a result value. public enum Result<T, Error: ErrorType>: ResultType, CustomStringConvertible, CustomDebugStringConvertible { case Success(T) case Failure(Error) // MARK: Constructors /// Constructs a success wrapping a `value`. public init(value: T) { self = .Success(value) } /// Constructs a failure wrapping an `error`. public init(error: Error) { self = .Failure(error) } /// Constructs a result from an Optional, failing with `Error` if `nil`. public init(_ value: T?, @autoclosure failWith: () -> Error) { self = value.map(Result.Success) ?? .Failure(failWith()) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(@autoclosure _ f: () throws -> T) { self.init(attempt: f) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(@noescape attempt f: () throws -> T) { do { self = .Success(try f()) } catch { self = .Failure(error as! Error) } } // MARK: Deconstruction /// Returns the value from `Success` Results or `throw`s the error. public func dematerialize() throws -> T { switch self { case let .Success(value): return value case let .Failure(error): throw error } } /// Case analysis for Result. /// /// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results. public func analysis<Result>(@noescape ifSuccess ifSuccess: T -> Result, @noescape ifFailure: Error -> Result) -> Result { switch self { case let .Success(value): return ifSuccess(value) case let .Failure(value): return ifFailure(value) } } // MARK: Higher-order functions /// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??` public func recover(@autoclosure value: () -> T) -> T { return self.value ?? value() } /// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??` public func recoverWith(@autoclosure result: () -> Result<T,Error>) -> Result<T,Error> { return analysis( ifSuccess: { _ in self }, ifFailure: { _ in result() }) } // MARK: Errors /// The domain for errors constructed by Result. public static var errorDomain: String { return "com.antitypical.Result" } /// The userInfo key for source functions in errors constructed by Result. public static var functionKey: String { return "\(errorDomain).function" } /// The userInfo key for source file paths in errors constructed by Result. public static var fileKey: String { return "\(errorDomain).file" } /// The userInfo key for source file line numbers in errors constructed by Result. public static var lineKey: String { return "\(errorDomain).line" } #if os(Linux) private typealias UserInfoType = Any #else private typealias UserInfoType = AnyObject #endif /// Constructs an error. public static func error(message: String? = nil, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> NSError { var userInfo: [String: UserInfoType] = [ functionKey: function, fileKey: file, lineKey: line, ] if let message = message { userInfo[NSLocalizedDescriptionKey] = message } return NSError(domain: errorDomain, code: 0, userInfo: userInfo) } // MARK: CustomStringConvertible public var description: String { return analysis( ifSuccess: { ".Success(\($0))" }, ifFailure: { ".Failure(\($0))" }) } // MARK: CustomDebugStringConvertible public var debugDescription: String { return description } } /// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal. public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { if let left = left.value, right = right.value { return left == right } else if let left = left.error, right = right.error { return left == right } return false } /// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values. public func != <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool { return !(left == right) } /// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> T) -> T { return left.recover(right()) } /// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits. public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> Result<T, Error>) -> Result<T, Error> { return left.recoverWith(right()) } // MARK: - Derive result from failable closure public func materialize<T>(@noescape f: () throws -> T) -> Result<T, NSError> { return materialize(try f()) } public func materialize<T>(@autoclosure f: () throws -> T) -> Result<T, NSError> { do { return .Success(try f()) } catch let error as NSError { return .Failure(error) } } // MARK: - Cocoa API conveniences #if !os(Linux) /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.: /// /// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) } public func `try`<T>(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> T?) -> Result<T, NSError> { var error: NSError? return `try`(&error).map(Result.Success) ?? .Failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line)) } /// Constructs a Result with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.: /// /// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) } public func `try`(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> Bool) -> Result<(), NSError> { var error: NSError? return `try`(&error) ? .Success(()) : .Failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line)) } #endif // MARK: - Operators infix operator >>- { // Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc. associativity left // Higher precedence than function application, but lower than function composition. precedence 100 } /// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors. /// /// This is a synonym for `flatMap`. public func >>- <T, U, Error> (result: Result<T, Error>, @noescape transform: T -> Result<U, Error>) -> Result<U, Error> { return result.flatMap(transform) } // MARK: - ErrorTypeConvertible conformance #if !os(Linux) /// Make NSError conform to ErrorTypeConvertible extension NSError: ErrorTypeConvertible { public static func errorFromErrorType(error: ErrorType) -> NSError { return error as NSError } } #endif // MARK: - /// An “error” that is impossible to construct. /// /// This can be used to describe `Result`s where failures will never /// be generated. For example, `Result<Int, NoError>` describes a result that /// contains an `Int`eger and is guaranteed never to be a `Failure`. public enum NoError: ErrorType { } import Foundation
mit
85301f0b2fadf8fe0fa6cfa2fb49d99e
31
162
0.684362
3.614367
false
false
false
false
ahoppen/swift
test/Generics/class_constraint.swift
5
1551
// RUN: %target-typecheck-verify-swift struct X<T: AnyObject> { } // expected-note 4{{requirement specified as 'T' : 'AnyObject'}} class C { } struct S { } protocol P { } let okay0: X<C> struct Y<T: AnyObject> { let okay1: X<T> } struct Y2<T: C> { let okay2: X<T> } let bad0: X<C & P> // expected-error{{'X' requires that 'any C & P' be a class type}} let bad1: X<P> // expected-error{{'X' requires that 'any P' be a class type}} let bad2: X<S> // expected-error{{'X' requires that 'S' be a class type}} struct Z<U> { let bad3: X<U> // expected-error{{'X' requires that 'U' be a class type}} } // SR-7168: layout constraints weren't getting merged. protocol P1 { associatedtype A var a: A { get } } protocol P2 { associatedtype B: P1 var b: B { get } } func requiresAnyObject<T: AnyObject>(_: T) { } func anyObjectConstraint<T: P2, U: P2>(_ t: T, _ u: U) where T.B.A: AnyObject, U.B: AnyObject, T.B == T.B.A, U.B.A == U.B { requiresAnyObject(t.b) requiresAnyObject(u.b) requiresAnyObject(t.b.a) requiresAnyObject(u.b.a) } func test_class_constraint_diagnostics_with_contextual_type() { func foo<T : AnyObject>(_: AnyObject) -> T {} // expected-note 2 {{where 'T' = 'any P'}} class A : P {} // TODO(diagnostics): We could also add a note here that protocols do not conform to themselves let _: P = foo(A() as AnyObject) // expected-error {{local function 'foo' requires that 'any P' be a class type}} let _: P = foo(A()) // expected-error {{local function 'foo' requires that 'any P' be a class type}} }
apache-2.0
bd0786e186af96fd003462e4f92800ee
25.741379
115
0.640877
2.899065
false
false
false
false
guan1/Matcha
iOS/Matcha/Matcha/Sources/MatchaEarlGrey.swift
1
6913
// // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import EarlGrey //this file was renamed because with the original name 'EarlGrey' the EarlGrey pod couldn't be used as dependency in our podspec //after pod update the original file will be re-created - you have to delete this file and rename the new one (note: also the class name was renamed from EarlGrey -> MatchaEarlGrey - but the compiler will tell you anyway) public func GREYAssert(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(expression, reason, details: "Expected expression to be true") } public func GREYAssertTrue(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(expression(), reason, details: "Expected the boolean expression to be true") } public func GREYAssertFalse(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(!expression(), reason, details: "Expected the boolean expression to be false") } public func GREYAssertNotNil(_ expression: @autoclosure ()-> Any?, reason: String) { GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil") } public func GREYAssertNil(_ expression: @autoclosure () -> Any?, reason: String) { GREYAssert(expression() == nil, reason, details: "Expected expression to be nil") } public func GREYAssertEqual(_ left: @autoclosure () -> AnyObject?, _ right: @autoclosure () -> AnyObject?, reason: String) { GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term") } public func GREYAssertNotEqual(_ left: @autoclosure () -> AnyObject?, _ right: @autoclosure () -> AnyObject?, reason: String) { GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term") } public func GREYAssertEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) { GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal" + " to the object of the right term") } public func GREYAssertNotEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) { GREYAssert(left() != right(), reason, details: "Expected object of the left term to not" + " equal the object of the right term") } public func GREYFail(_ reason: String) { MatchaEarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: "") } public func GREYFailWithDetails(_ reason: String, details: String) { MatchaEarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } private func GREYAssert(_ expression: @autoclosure () -> Bool, _ reason: String, details: String) { GREYSetCurrentAsFailable() GREYWaitUntilIdle() if !expression() { MatchaEarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } } private func GREYSetCurrentAsFailable() { let greyFailureHandlerSelector = #selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:)) let greyFailureHandler = Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler if greyFailureHandler.responds(to: greyFailureHandlerSelector) { greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line) } } private func GREYWaitUntilIdle() { GREYUIThreadExecutor.sharedInstance().drainUntilIdle() } open class MatchaEarlGrey: NSObject { open class func select(elementWithMatcher matcher:GREYMatcher, file: StaticString = #file, line: UInt = #line) -> GREYElementInteraction { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .selectElement(with: matcher) } open class func setFailureHandler(handler: GREYFailureHandler, file: StaticString = #file, line: UInt = #line) { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .setFailureHandler(handler) } open class func handle(exception: GREYFrameworkException, details: String, file: StaticString = #file, line: UInt = #line) { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .handle(exception, details: details) } @discardableResult open class func rotateDeviceTo(orientation: UIDeviceOrientation, errorOrNil: UnsafeMutablePointer<NSError?>!, file: StaticString = #file, line: UInt = #line) -> Bool { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .rotateDevice(to: orientation, errorOrNil: errorOrNil) } } extension GREYInteraction { @discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher) -> Self { return self.assert(with:matcher()) } @discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher, error:UnsafeMutablePointer<NSError?>!) -> Self { return self.assert(with: matcher(), error: error) } @discardableResult public func using(searchAction: GREYAction, onElementWithMatcher matcher: GREYMatcher) -> Self { return self.usingSearch(searchAction, onElementWith: matcher) } } extension GREYCondition { open func waitWithTimeout(seconds: CFTimeInterval) -> Bool { return self.wait(withTimeout: seconds) } open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval) -> Bool { return self.wait(withTimeout: seconds, pollInterval: pollInterval) } }
mit
65da6976a5d5538105c5a3884c15d67e
41.937888
221
0.64574
4.994942
false
false
false
false
dreamsxin/swift
test/SILGen/struct_resilience.swift
3
10866
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s import resilient_struct // Resilient structs are always address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@in Size, @owned @callee_owned (@in Size) -> @out Size) -> @out Size // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@in Size) -> @out Size): func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]]) s2.w = s.w // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // Use materializeForSet for inout access of properties in resilient structs // from a different resilience domain func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden @_TF17struct_resilience18resilientInOutTestFRV16resilient_struct4SizeT_ : $@convention(thin) (@inout Size) -> () func resilientInOutTest(_ s: inout Size) { // CHECK: function_ref @_TF17struct_resilience9inoutFuncFRSiT_ // CHECK: function_ref @_TFV16resilient_struct4Sizem1wSi inoutFunc(&s.w) // CHECK: return } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point): func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[NEW_POINT:%.*]] = apply %1(%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@in Rectangle, @owned @callee_owned (@in Rectangle) -> @out Rectangle) -> @out Rectangle // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@in Rectangle) -> @out Rectangle): func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var w: Int // Read-only instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Static stored property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var copyright: Int = 0 } // CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@in MySize, @owned @callee_owned (@in MySize) -> @out MySize) -> @out MySize public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience25publicTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int @_transparent public func publicTransparentFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @_TFV17struct_resilience6MySizeg1wSi // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience30publicTransparentLocalFunctionFVS_6MySizeFT_Si : $@convention(thin) (@in MySize) -> @owned @callee_owned () -> Int @_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int { // CHECK-LABEL: sil shared [fragile] @_TFF17struct_resilience30publicTransparentLocalFunctionFVS_6MySizeFT_SiU_FT_Si : $@convention(thin) (@owned @box MySize) -> Int // CHECK: function_ref @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK: return {{.*}} : $Int return { s.w } } // CHECK-LABEL: sil hidden [transparent] @_TF17struct_resilience27internalTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int @_transparent func internalTransparentFunction(_ s: MySize) -> Int { // The body of an internal transparent function will not be inlined into // other resilience domains, so we can access storage directly // CHECK: [[W_ADDR:%.*]] = struct_element_addr %0 : $*MySize, #MySize.w // CHECK-NEXT: [[RESULT:%.*]] = load [[W_ADDR]] : $*Int // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [fragile] [always_inline] @_TF17struct_resilience26publicInlineAlwaysFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int @inline(__always) public func publicInlineAlwaysFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @_TFV17struct_resilience6MySizeg1wSi // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // Make sure that @_versioned entities can be resilient @_versioned struct VersionedResilientStruct { @_versioned let x: Int @_versioned let y: Int @_versioned init(x: Int, y: Int) { self.x = x self.y = y } } // CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience27useVersionedResilientStructFVS_24VersionedResilientStructS0_ : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct @_versioned @_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct) -> VersionedResilientStruct { // CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructCfT1xSi1ySi_S0_ // CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructg1ySi // CHECK: function_ref @_TFV17struct_resilience24VersionedResilientStructg1xSi return VersionedResilientStruct(x: s.y, y: s.x) }
apache-2.0
1f061fdb8729aee1de52514e0c51490e
45.435897
246
0.674673
3.557957
false
false
false
false
AlexKorovyansky/WorkTimerOSX
WorkTimer/ViewController.swift
1
2155
// // ViewController.swift // WorkTimer // // Created by Alex Korovyansky on 09/12/14. // Copyright (c) 2014 Alex Korovyansky. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet var timer: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } override func viewDidAppear() { super.viewDidLoad() self.view.window?.movableByWindowBackground = true self.view.window?.level = Int(CGWindowLevelForKey(Int32(kCGFloatingWindowLevelKey))) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } func update() { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date) let hour = components.hour let minutes = components.minute let seconds = components.second let targetTimeInSeconds = 18*60*60 + 0*60 + 0; let currentTimeInSeconds = hour*60*60 + minutes*60 + seconds; let diffInSeconds = (targetTimeInSeconds - currentTimeInSeconds > 0) ? targetTimeInSeconds - currentTimeInSeconds : currentTimeInSeconds - targetTimeInSeconds let diffHours = diffInSeconds / (60*60) let diffMinutes = (diffInSeconds - diffHours*60*60) / 60 let diffSeconds = (diffInSeconds - diffHours*60*60 - diffMinutes*60) timer.stringValue = formatTimeComponent(diffHours) + ":" + formatTimeComponent(diffMinutes) if (targetTimeInSeconds - currentTimeInSeconds < 0) { timer.textColor = NSColor.redColor() } } func formatTimeComponent(timeComponent: Int) -> String{ return timeComponent < 10 ? "0\(timeComponent)" : "\(timeComponent)" } }
apache-2.0
9b4704ce9549fc24b5866a929231099e
30.231884
137
0.643155
4.70524
false
false
false
false
vivekjkumar/VoiceButton-Swift
VoiceConverter/VoiceButton/SpeechRecorder.swift
1
3700
// // AudioRecorder.swift // VoiceConverter // // Created by Vivek Jayakumar on 28/6/17. import UIKit import Speech protocol SpeechRecorderDelegate { func updateSpeechText(_ text: String) } class SpeechRecorder: NSObject, SFSpeechRecognizerDelegate { private var speechRecognizer: SFSpeechRecognizer? private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? private let audioEngine = AVAudioEngine() var delegate: SpeechRecorderDelegate? /// Initialise speech recogniser func setupSpeechRecorder(completion: @escaping (Bool, String) -> Void) { speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US")) speechRecognizer?.delegate = self SFSpeechRecognizer.requestAuthorization { (authStatus) in switch authStatus { case .authorized: completion(true, "Initialised") case .denied: completion(false, "User denied access to speech recognition") case .restricted: completion(false, "Speech recognition restricted on this device") case .notDetermined: completion(false, "Speech recognition not yet authorized") } } } /// Function to start recording and capture speech text func startRecording(completion: @escaping (Bool, String) -> Void) { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { completion (false, "audioSession properties weren't set because of an error.") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let inputNode = audioEngine.inputNode else { completion (false, "Audio engine has no input node") return } guard let recognitionRequest = recognitionRequest else { completion (false, "Unable to create an SFSpeechAudioBufferRecognitionRequest object") return } recognitionRequest.shouldReportPartialResults = true recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { [weak self] (result, error) in var isFinal = false if result != nil { if let speechText = result?.bestTranscription.formattedString { self?.delegate?.updateSpeechText(speechText) } isFinal = (result?.isFinal)! } if error != nil || isFinal { self?.audioEngine.stop() inputNode.removeTap(onBus: 0) self?.recognitionRequest = nil self?.recognitionTask = nil } }) let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() do { try audioEngine.start() } catch { completion (false, "audioEngine couldn't start because of an error.") } completion (true, "Initialised") } func stopRecording() { if recognitionTask != nil { recognitionTask?.cancel() recognitionTask = nil } audioEngine.inputNode?.removeTap(onBus: 0) } }
mit
82359266faeca50f32ecc0af36b8688a
28.83871
133
0.624865
5.76324
false
false
false
false
OSzhou/MyTestDemo
09_TextKit/Swift_TextKitAndAnimationEffect(文本动画)/TextKitStudy/Layout/TKSLinkDetectingTextStorage.swift
1
2747
// // TKSLinkDetectingTextStorage.swift // TextKitStudy // // Created by steven on 2/17/16. // Copyright © 2016 Steven lv. All rights reserved. // import UIKit class TKSLinkDetectingTextStorage: NSTextStorage { fileprivate lazy var imp:NSMutableAttributedString = { var _imp:NSMutableAttributedString = NSMutableAttributedString() return _imp }() override var string:String { get{ return self.imp.string } } override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [String : Any] { return self.imp.attributes(at: location, effectiveRange: range) } override func replaceCharacters(in range: NSRange, with str: String) { self.beginEditing() self.imp.replaceCharacters(in: range, with: str) self.edited(.editedCharacters, range: range, changeInLength: str.characters.count) self.endEditing() } override func setAttributes(_ attrs: [String : Any]?, range: NSRange) { self.beginEditing() self.imp.setAttributes(attrs, range: range) self.edited(.editedAttributes, range: range, changeInLength: 0) self.endEditing() } override func processEditing() { super.processEditing() //添加下划线 let linkDetector:NSDataDetector? = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let range:NSRange = (self.string as NSString).paragraphRange(for: NSMakeRange(0, self.string.characters.count)) self.imp.removeAttribute(NSLinkAttributeName, range: range) self.imp.removeAttribute(NSForegroundColorAttributeName, range: range) self.imp.removeAttribute(NSUnderlineStyleAttributeName, range: range) if linkDetector != nil { linkDetector!.enumerateMatches(in: self.imp.string, options:NSRegularExpression.MatchingOptions(rawValue: 0), range: range) { [weak self](textCheckingResult:NSTextCheckingResult?, flags:NSRegularExpression.MatchingFlags, stop:UnsafeMutablePointer<ObjCBool>) -> Void in if textCheckingResult != nil { self?.imp.addAttribute(NSLinkAttributeName, value: textCheckingResult!.url!, range: textCheckingResult!.range) // self?.imp.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: textCheckingResult!.range) self?.imp.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: textCheckingResult!.range) } } } } }
apache-2.0
1277d670af827bb299b006d18a11a46b
35.48
280
0.652047
5.142857
false
false
false
false
ortuman/SwiftForms
Sources/SwiftFormsPackage/cells/FormCheckCell.swift
2
1368
// // FormCheckCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 22/08/14. // Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved. // import UIKit open class FormCheckCell: FormTitleCell { // MARK: FormBaseCell open override func configure() { super.configure() selectionStyle = .default accessoryType = .none } open override func update() { super.update() titleLabel.text = rowDescriptor?.title var rowValue: Bool if let value = rowDescriptor?.value as? Bool { rowValue = value } else { rowValue = false rowDescriptor?.value = rowValue as AnyObject } accessoryType = (rowValue) ? .checkmark : .none } open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { guard let row = selectedRow as? FormCheckCell else { return } row.check() } // MARK: Private interface fileprivate func check() { var newValue: Bool if let value = rowDescriptor?.value as? Bool { newValue = !value } else { newValue = true } rowDescriptor?.value = newValue as AnyObject update() } }
mit
8ef4de8455a7307faaca914fc5693479
23.854545
131
0.577908
5.11985
false
false
false
false
Jude309307972/JudeTest
Swift04-1/Swift04-1/main.swift
1
1630
// // main.swift // Swift04-1 // // Created by 徐遵成 on 15/10/7. // Copyright © 2015年 Jude. All rights reserved. // import Foundation @objc protocol CertificateGenerator { func certificate() -> String optional func optionalful() } class EncryptionGenerator: CertificateGenerator { var publicKey = "UUID" let privateKey = "123 - 456 - 789" @objc func certificate() -> String { return publicKey + privateKey } } let generator = EncryptionGenerator() print(generator.certificate()) protocol MutatingProtocol { mutating func turn() } enum OnOffSwitch: MutatingProtocol { case Off, On mutating func turn() { switch self { case .Off: self = On case .On: self = Off } } } var lightSwitch = OnOffSwitch.On lightSwitch.turn() print(lightSwitch) protocol RandomNumberGenerator { func random() -> Double } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } } class Dice { let sides: Int let generator: RandomNumberGenerator //代理对象 init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int{ return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...10 { print("Randomdiceroll is \(d6.roll())") }
apache-2.0
00538b4707b0f0c938c3ed2cd15017c6
19.1625
65
0.625542
3.934146
false
false
false
false
litt1e-p/LPPhotoViewer-swift
LPPhotoViewer/LPPhotoView.swift
2
2664
// // LPPhotoView.swift // LPPhotoViewer // // Created by litt1e-p on 16/4/14. // Copyright © 2016年 litt1e-p. All rights reserved. // import UIKit //import WebImage import SDWebImage protocol LPPhotoViewDelegate: NSObjectProtocol { func photoViewWillClose(cell: LPPhotoView) func photoViewWillShow() } class LPPhotoView: UICollectionViewCell { weak var photoViewDelegate: LPPhotoViewDelegate? var imageURL: NSURL? { didSet { reset() activity.startAnimating() scrollView.imageView.sd_setImageWithURL(imageURL!, placeholderImage: nil, options: SDWebImageOptions.LowPriority, progress: { (receivedSize: Int, expectedSize: Int) in }) { (image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageURL: NSURL!) in guard error == nil else {print(error); return} self.activity.stopAnimating() self.scrollView.setImage(image!, size: image!.size) if imageURL.absoluteString.hasSuffix(".gif") { SDWebImageManager.sharedManager().cancelAll() SDWebImageManager.sharedManager().imageCache.clearMemory() } } } } var image: UIImage? { didSet { self.scrollView.setImage(image!, size: image!.size) } } func reset() { scrollView.contentInset = UIEdgeInsetsZero scrollView.contentOffset = CGPointZero scrollView.contentSize = CGSizeZero } override init(frame: CGRect) { super.init(frame: frame) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initViews() { contentView.addSubview(scrollView) contentView.addSubview(activity) activity.center = contentView.center scrollView.oneTapCallback = {[weak self] in self?.close() } scrollView.didLoadedImageCallback = {[weak self] in self!.photoViewDelegate?.photoViewWillShow() } } func close() { photoViewDelegate?.photoViewWillClose(self) } private lazy var scrollView: LPPhotoScrollView = { let scrollview = LPPhotoScrollView(frame:CGRect(x:0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)) return scrollview }() private lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) }
mit
f139a18b48f426977a977648ceaa55e1
29.238636
179
0.617813
5.097701
false
false
false
false
gabro/UniversalPicker
Example/UniversalPicker/ViewController.swift
1
1912
// // ViewController.swift // UniversalPicker // // Created by Gabriele Petronella on 11/02/2015. // Copyright (c) 2015 Gabriele Petronella. All rights reserved. // import UIKit import UniversalPicker class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pickPhoto() { UniversalPicker.pickPhoto(inViewController: self) { photo in if let _ = photo { DispatchQueue.main.async { let alert = UIAlertController(title: "Success!", message: "You picked a photo", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Not impressed", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } @IBAction func pickVideo() { UniversalPicker.pickVideo(inViewController: self) { videoURL in if let _ = videoURL { DispatchQueue.main.async { let alert = UIAlertController(title: "Success!", message: "You picked a video", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Not impressed", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } @IBAction func pickFile() { UniversalPicker.pickFile(inViewController: self) { fileURL in if let _ = fileURL { DispatchQueue.main.async { let alert = UIAlertController(title: "Success!", message: "You picked a file", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Not impressed", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } }
mit
e875761c97ebc9c713467cc13400ff32
30.866667
113
0.65795
4.296629
false
false
false
false
inder/ios-ranking-visualization
RankViz/RankViz/LineSegmentLayer.swift
1
4937
// // LineSegmentLayer.swift // Reverse Graph // // Created by Inder Sabharwal on 1/15/15. // Copyright (c) 2015 truquity. All rights reserved. // import Foundation import UIKit //draws a line segment between two points in a layer - that's it. class LineSegmentLayer: CALayer, Equatable { var lineThickness: CGFloat = 0.5 { didSet { self.setNeedsDisplay() } } var highlighted: Bool = false { didSet { if (highlighted) { lineThickness = 3 } else { lineThickness = 0.5 } self.setNeedsDisplay() } } var rank: Int? { didSet { self.setNeedsDisplay() } } override init() { super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var linePoints: [CGPoint] = [] func addLine(toPoint point: CGPoint) { linePoints.append(point) } // MARK: - drawing functions. override func drawInContext(ctx: CGContext!) { //println("drawInContext") UIGraphicsPushContext(ctx) var path = UIBezierPath() var lineStarted = false for (idx, point) in enumerate(linePoints) { if (point.y > 0 && point.y < self.bounds.height) { if (!lineStarted) { path.moveToPoint(point) lineStarted = true } else { path.addLineToPoint(point) } } } var lineColor = UIColor(red: 43.0 / 255.0, green: 63.0 / 255.0, blue: 86.0 / 255.0, alpha: 0.75) path.lineWidth = self.lineThickness if (!highlighted) { let dashes: [CGFloat] = [self.lineThickness, self.lineThickness * 3] path.setLineDash(dashes, count: dashes.count, phase: 0) } lineColor.setStroke() path.stroke() for (idx, point) in enumerate(linePoints) { var circle = CGRect(origin: CGPoint(x: point.x - 4, y: point.y - 4), size: CGSizeMake(8, 8)) path = UIBezierPath(ovalInRect: circle) UIColor.whiteColor().setFill() UIColor(red: 43.0 / 255.0, green: 63.0 / 255.0, blue: 86.0 / 255.0, alpha: 0.75).setStroke() if (highlighted) { path.lineWidth = 2 if (idx == 1) { path.lineWidth = 3 circle = CGRect(origin: CGPoint(x: point.x - 10, y: point.y - 10), size: CGSizeMake(20, 20)) path = UIBezierPath(ovalInRect: circle) UIColor.grayColor().setFill() } } else { let dashes: [CGFloat] = [self.lineThickness, self.lineThickness] path.setLineDash(dashes, count: dashes.count, phase: 0) path.lineWidth = self.lineThickness } path.fill() path.stroke() //draw the text on the filled layer to get anti-aliasing. if (highlighted && idx == 1) { if let r = rank { var label = CATextLayer() label.font = "Helvetica" label.fontSize = 16 label.frame = circle label.string = "\(r)" label.alignmentMode = kCAAlignmentCenter label.backgroundColor = UIColor.clearColor().CGColor label.foregroundColor = UIColor.whiteColor().CGColor self.addSublayer(label) } } } UIGraphicsPopContext() } // MARK: - deprecated properties and functions - #willbenuked. enum Direction { case UP case DOWN case STRAIGHT } var direction = Direction.DOWN init(startAt start: CGPoint, endAt end: CGPoint) { super.init() var frame: CGRect! if (end.y > start.y) { frame = CGRectMake(start.x, start.y, (end.x - start.x), (end.y - start.y) + lineThickness * 2) //up to down } else if (end.y < start.y) { direction = Direction.UP frame = CGRectMake(start.x, end.y, (end.x - start.x), (start.y - end.y) + lineThickness * 2) } else { direction = Direction.STRAIGHT frame = CGRectMake(start.x, end.y, (end.x - start.x), lineThickness * 2) } self.frame = frame } } func ==<T:Equatable>(lhs: [T?], rhs: [T?]) -> Bool { if lhs.count != rhs.count { return false } for index in 0 ..< lhs.count { if lhs[index] != rhs[index] { return false } } return true } // MARK: - Equatable protocol func ==(lhs: LineSegmentLayer, rhs: LineSegmentLayer) -> Bool { return rhs.rank == lhs.rank }
apache-2.0
ffe0ebfc255e2d8da08f48540a223f41
27.217143
112
0.512052
4.308028
false
false
false
false
alexanderwohltan/focus
Focus/GameScene.swift
1
1307
// // GameScene.swift // Focus // // Created by Alexander Wohltan on 16.10.14. // Copyright (c) 2014 alphacode. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Chalkduster") myLabel.text = "Hello, World!"; myLabel.fontSize = 65; myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(myLabel) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */ for touch: AnyObject in touches { let location = touch.locationInNode(self) let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.position = location let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
gpl-3.0
99acb5042101c363366904f709e638e3
28.044444
93
0.58531
4.787546
false
false
false
false
gscalzo/CubeRunner
CubeRunner/GameCenter.swift
1
2419
// // GameCenter.swift // FlappySwift // // Created by Giordano Scalzo on 07/03/2015. // Copyright (c) 2015 Effective Code. All rights reserved. // import GameKit import SIAlertView class GameCenter: NSObject { private var gameCenterEnabled = false private var leaderboardIdentifier = "" func authenticateLocalPlayer() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = { (viewController, error) in if let vc = viewController { let topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController topViewController?.presentViewController(vc, animated: true, completion: nil) } else if localPlayer.authenticated { self.gameCenterEnabled = true localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifier, error) -> Void in self.leaderboardIdentifier = leaderboardIdentifier }) } } } func reportScore(score: Int){ if !gameCenterEnabled { return } let gkScore = GKScore(leaderboardIdentifier: leaderboardIdentifier) gkScore.value = Int64(score) GKScore.reportScores([gkScore], withCompletionHandler: nil) } func showLeaderboard() { if !gameCenterEnabled { let alertView = SIAlertView(title: "Game Center Unavailable", andMessage: "Player is not signed in") alertView.addButtonWithTitle("OK", type: .Default) { _ in } alertView.show() return } let gcViewController = GKGameCenterViewController() gcViewController.gameCenterDelegate = self gcViewController.viewState = .Leaderboards gcViewController.leaderboardIdentifier = leaderboardIdentifier let topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController topViewController?.presentViewController(gcViewController, animated: true, completion: nil) } } extension GameCenter: GKGameCenterControllerDelegate { func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController){ gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } }
mit
ac59404c12f007125ea37d53911a46db
35.104478
125
0.661844
5.787081
false
false
false
false
wiipsp/ClearGuest
ClearGuest/ViewController.swift
1
9238
// // ViewController.swift // ClearGuest // // Created by Kobe on 14/12/11. // Copyright (c) 2014年 kobe. All rights reserved. // import UIKit import Foundation import AVFoundation import Alamofire import SystemConfiguration let KShowScanViewIdentifier: String = "showScanView" let ContactFilePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0].stringByAppendingPathComponent("pwd.data") //扩展UIDevice类的方法 extension UIDevice { public var SSID: String? { get { if let interfaces = CNCopySupportedInterfaces() { let interfacesArray = interfaces.takeRetainedValue() as! [String] if let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interfacesArray.first) { let interfaceData = unsafeInterfaceData.takeRetainedValue() as Dictionary return interfaceData["SSID"] as? String } } return nil } } } class ViewController: UIViewController, UIAlertViewDelegate { @IBOutlet weak var localPwd: UILabel! @IBOutlet weak var networkStatus: UILabel! @IBOutlet weak var getServerPwdBtn: UIButton! @IBOutlet weak var pushToLogin: UIButton! @IBOutlet weak var exitBtn: UIButton! var pushPwd:String? let opaqueview : UIView = UIView() let activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView() //启动等待菊花 func startWaitingImg(){ activityIndicator.startAnimating() opaqueview.hidden = false } //关闭等待菊花 func stopWaitingImg(){ activityIndicator.stopAnimating() opaqueview.hidden = true } override func viewDidLoad() { super.viewDidLoad() self.title = "Clear-Guest WIFI登录器" //设置按钮圆角 pushToLogin.layer.cornerRadius = 3 getServerPwdBtn.layer.cornerRadius = 3 exitBtn.layer.cornerRadius = 3 //启动监听如果有推送调用logMsg方法 NSNotificationCenter.defaultCenter().addObserver(self, selector: "logMsg:", name: "logMsg", object: nil) //先把当前密码显示出来 getLatestPwd() //启动监听当前网络状态 let reachability = Reachability.reachabilityForInternetConnection() reachabilityChanged(NSNotification(name: ReachabilityChangedNotification, object: reachability, userInfo: nil)) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability) //程序启动后检测当天网络状态 reachability.startNotifier() //绘制等待菊花 opaqueview.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height) activityIndicator.frame = CGRectMake(50,50,50,50) activityIndicator.center = opaqueview.center activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White opaqueview.backgroundColor = UIColor.blackColor() opaqueview.alpha = 0.8 self.view.addSubview(opaqueview) opaqueview.addSubview(activityIndicator) activityIndicator.stopAnimating() opaqueview.hidden = true } //当有推送过来的操作 func logMsg(notification: NSNotification) { let pwd = notification.userInfo!["record"] as! String println("get record Pwd:" + pwd) NSKeyedArchiver.archiveRootObject(pwd, toFile: ContactFilePath) getLatestPwd() } //关闭程序 func exitProgram(){ abort() } //网络改变的操作 func reachabilityChanged(note: NSNotification) { var response = "" let reachability = note.object as! Reachability if reachability.isReachable() { if reachability.isReachableViaWiFi() { if (UIDevice.currentDevice().SSID != nil) { response = "当前wifi为: \(UIDevice.currentDevice().SSID!)" } } else { response = "当前使用的是移动网络" } } else { response = "当前没有网络" } networkStatus.text = response } //把密码存入本地 func getLatestPwd(){ println("从归档中提取") self.pushPwd = NSKeyedUnarchiver.unarchiveObjectWithFile(ContactFilePath) as! String! if(pushPwd == nil){ println("归档中没有,创建数组") pushPwd = String() } let results:[String] = pushPwd!.componentsSeparatedByString("#") let response = "\(results.first!)的密码为: \n\(results.last!)" localPwd.text = response } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginByScan(sender: UIButton) { if UIDevice.currentDevice().SSID == "clear-guest" { self.performSegueWithIdentifier(KShowScanViewIdentifier, sender: self); }else{ var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "当前WIFI不是clear-guest,请连接后再试" alertView.addButtonWithTitle("确认") alertView.show() } } @IBAction func getServerPwd(sender: AnyObject) { startWaitingImg() Alamofire.request(.GET, "http://kobe.ora2000.com/ClearGuestWebservice/rest/clearguest/getLatestClearguestPwd") .responseString { (_, _, result, _) in self.stopWaitingImg() if (result == nil) { var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "当前服务器返回密码为空,请稍后再试" alertView.addButtonWithTitle("确认") alertView.show() }else if(result!.hasPrefix("<")){ var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "请先连接到internet,然后再获取密码" alertView.addButtonWithTitle("确认") alertView.show() }else{ NSKeyedArchiver.archiveRootObject(result!, toFile: ContactFilePath) self.getLatestPwd() } } } @IBAction func loginByPush(sender: UIButton) { if(pushPwd == nil || pushPwd!.isEmpty){ var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "密码为空!" alertView.addButtonWithTitle("确认") alertView.show() }else{ if UIDevice.currentDevice().SSID?.lowercaseString == "clear-guest" { let currntPwd = pushPwd?.componentsSeparatedByString("#").last println("converted pwd: " + currntPwd!) loginToClearGuest(currntPwd!) }else{ var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "当前WIFI不是clear-guest,请连接后再试" alertView.addButtonWithTitle("确认") alertView.show() } } } @IBAction func exitApp(sender: UIButton) { exitProgram() } //处理alert 的button click。 关闭程序 func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){ exitProgram() } //包装Form表单 提交login func loginToClearGuest(qrCode : String){ startWaitingImg() let parameters = [ "username": "guest", "password": qrCode, "buttonClicked" : "4" ] println("teset here:" + qrCode) var alertView = UIAlertView() alertView.title = "clear-guest" alertView.message = "登陆成功!" alertView.addButtonWithTitle("确认") Alamofire.request(.POST, "https://webauth-redirect.oracle.com/login.html", parameters: parameters).response { (request, response, data, error) in if(response?.statusCode == 200){ Alamofire.request(.GET, "http://kobe.ora2000.com/ClearGuestWebservice/rest/test") .responseString { (_, _, string, _) in self.stopWaitingImg() if(string == "Hello World!"){ alertView.delegate=self alertView.show() }else{ alertView.message = "登陆失败,请检查密码是否正确。" alertView.show() } } }else{ self.stopWaitingImg() alertView.message = "登陆失败!" alertView.show() } } } }
apache-2.0
b7d3baab6377afcc0d53b90ca3f998ae
35.680672
189
0.587171
5.023015
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/making-a-large-island.swift
2
1948
/** * https://leetcode.com/problems/making-a-large-island/ * * */ // Date: Wed Aug 4 14:11:42 PDT 2021 class Solution { func largestIsland(_ grid: [[Int]]) -> Int { let n = grid.count guard let m = grid.first?.count else { return 0 } var colorMap = [Int : Int]() var color = 2 var grid = grid for x in 0 ..< n { for y in 0 ..< m { if grid[x][y] == 1 { colorMap[color] = dfs(x, y, &grid, color) color += 1 } } } // print(grid) var result = colorMap[2, default: 0] let dt = [0, 1, 0, -1, 0] for x in 0 ..< n { for y in 0 ..< m { if grid[x][y] == 0 { var tempResult = 1 var visited: Set<Int> = [] for index in 0 ..< 4 { let xx = x + dt[index] let yy = y + dt[index + 1] if xx >= 0, xx < n, yy >= 0, yy < m, let count = colorMap[grid[xx][yy]], visited.contains(grid[xx][yy]) == false { tempResult += count visited.insert(grid[xx][yy]) } } result = max(result, tempResult) } } } return result } private func dfs(_ x: Int, _ y: Int, _ grid: inout [[Int]], _ color: Int) -> Int { guard grid[x][y] == 1 else { return 0 } var result = 1 grid[x][y] = color let dt = [0, 1, 0, -1, 0] for index in 0 ..< 4 { let xx = x + dt[index] let yy = y + dt[index + 1] if xx >= 0, xx < grid.count, yy >= 0, yy < (grid.first?.count ?? 0), grid[xx][yy] == 1 { result += dfs(xx, yy, &grid, color) } } return result } }
mit
7240d5ecc14f4df93449f72c3bc8d399
30.934426
138
0.381417
3.834646
false
false
false
false
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Data/BubbleChartDataSet.swift
79
2829
// // BubbleChartDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class BubbleChartDataSet: BarLineScatterCandleChartDataSet { internal var _xMax = Double(0.0) internal var _xMin = Double(0.0) internal var _maxSize = CGFloat(0.0) public var xMin: Double { return _xMin } public var xMax: Double { return _xMax } public var maxSize: CGFloat { return _maxSize } public func setColor(color: UIColor, alpha: CGFloat) { super.setColor(color.colorWithAlphaComponent(alpha)) } internal override func calcMinMax(#start: Int, end: Int) { if (yVals.count == 0) { return } let entries = yVals as! [BubbleChartDataEntry] // need chart width to guess this properly var endValue : Int if end == 0 { endValue = entries.count - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = yMin(entries[start]) _yMax = yMax(entries[start]) for (var i = start; i <= endValue; i++) { let entry = entries[i] let ymin = yMin(entry) let ymax = yMax(entry) if (ymin < _yMin) { _yMin = ymin } if (ymax > _yMax) { _yMax = ymax } let xmin = xMin(entry) let xmax = xMax(entry) if (xmin < _xMin) { _xMin = xmin } if (xmax > _xMax) { _xMax = xmax } let size = largestSize(entry) if (size > _maxSize) { _maxSize = size } } } /// Sets/gets the width of the circle that surrounds the bubble when highlighted public var highlightCircleWidth: CGFloat = 2.5 private func yMin(entry: BubbleChartDataEntry) -> Double { return entry.value } private func yMax(entry: BubbleChartDataEntry) -> Double { return entry.value } private func xMin(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func xMax(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func largestSize(entry: BubbleChartDataEntry) -> CGFloat { return entry.size } }
mit
2c32d5319fa4f7dfe0e185b3074d3f94
21.632
84
0.499823
4.894464
false
false
false
false
saagarjha/iina
iina/CropBoxViewController.swift
3
1085
// // CropBoxViewController.swift // iina // // Created by lhc on 5/9/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa /** The generic view controller of `CropBoxView`. */ class CropBoxViewController: NSViewController { weak var mainWindow: MainWindowController! var cropx: Int = 0 var cropy: Int = 0 // in flipped coord var cropw: Int = 0 var croph: Int = 0 var readableCropString: String { return "(\(cropx), \(cropy)) (\(cropw)\u{d7}\(croph))" } lazy var cropBoxView: CropBoxView = { let view = CropBoxView() view.settingsViewController = self view.translatesAutoresizingMaskIntoConstraints = false return view }() func selectedRectUpdated() { guard mainWindow.isInInteractiveMode else { return } let rect = cropBoxView.selectedRect updateCropValues(from: rect) } private func updateCropValues(from rect: NSRect) { cropx = Int(rect.minX) cropy = Int(CGFloat(mainWindow.player.info.videoHeight!) - rect.height - rect.minY) cropw = Int(rect.width) croph = Int(rect.height) } }
gpl-3.0
7027d067264faa63a5ee7c60ba11a7b0
23.636364
87
0.684502
3.777003
false
false
false
false
ProjectGinsberg/SDK
ExampleApp/iOS/Example1/Src/VCCharts.swift
1
3283
// // ViewController.swift // Example1 // // Created by CD on 22/07/2014. // Copyright (c) 2014 Ginsberg. All rights reserved. // import UIKit // // Initial charting tests. Place holder for now // class VCCharts: UIViewController, GAPIProtocol, UIWebViewDelegate { // // MARK: Outlets // @IBOutlet weak var vMain: UIView! @IBOutlet weak var btCancel: UIButton! @IBOutlet weak var wvChart1: UIWebView! @IBOutlet weak var wvChart2: UIWebView! @IBOutlet weak var wvChart3: UIWebView! @IBOutlet weak var svCharts: UIScrollView! // // MARK: View Controller // override func viewDidLoad() { super.viewDidLoad() //Make buttons nice btCancel.layer.borderWidth = 0.0; btCancel.layer.cornerRadius = 15; //Make scroll area just nice and big for now svCharts.contentSize = CGSizeMake(svCharts.contentSize.width, 2000.0); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) GAPI.Instance().SetCallbacks(self); //Setup example chart var baseUrl = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath); let pathhtml = NSBundle.mainBundle().pathForResource("index", ofType: "html"); var c:String = String(contentsOfFile:pathhtml!, encoding:NSUTF8StringEncoding, error: nil)!; wvChart1.loadHTMLString(c, baseURL: baseUrl) //Add example values c.replaceRange(c.rangeOfString("series1=")!.endIndex...c.rangeOfString(";//End")!.startIndex, with: "[{x:1, y:5},{x:2, y:4},{x:3, y:3},{x:4, y:2},{x:5, y:1}]"); wvChart2.loadHTMLString(c, baseURL: baseUrl) wvChart3.loadHTMLString(c, baseURL: baseUrl) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } //WebView - To convert /* - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { return YES; } - (void)webViewDidStartLoad:(UIWebView *)webView { } - (void)webViewDidFinishLoad:(UIWebView *)webView { } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { } */ // // MARK: Actions // @IBAction func pressedUpdate(sender: UIButton) { } @IBAction func pressedCancel(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil); } // // MARK: Callbacks // func SetBusy(truth: Bool) { } func Comment(text: String) { } func CommentError(text: String) { let alert = UIAlertView(); alert.title = "Connection Error" alert.message = "Please check internet connection." alert.addButtonWithTitle("OK") alert.show(); } func CommentResult(text: String) { } func CommentSystem(text: String) { } func DataReceived(endPoint:String, withData:NSDictionary?, andString:String) { } }
mit
d3b41bea0c68576930fcab5403eead26
20.886667
168
0.589705
4.472752
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/iPhone/Classes/Animations/SplashLoginTransition.swift
1
2444
// // SplashLoginTransition.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 19/07/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class SplashLoginTransition: ControllerTransition { override func animatePush(toContext context : UIViewControllerContextTransitioning) { let fromVC = self.controllerOrigin as! SplashViewController let toVC = self.controllerDestination as! LoginViewController let containerView = context.containerView let fromView = context.view(forKey: .from)! let toView = context.view(forKey: .to)! let duration = self.transitionDuration(using: context) fromView.frame = UIScreen.main.bounds containerView.addSubview(fromView) toView.frame = UIScreen.main.bounds containerView.addSubview(toView) toView.backgroundColor = .clear toVC.constraintWidthLogo.constant = 68 toVC.constraintHeightLogo.constant = 68 toVC.lblNameCompany.alpha = 0 toVC.constraintCenterForm.constant = (UIScreen.main.bounds.size.height + toVC.viewFormUser.bounds.size.height) / 2 containerView.layoutIfNeeded() UIView.animate(withDuration: duration * 0.5, animations: { fromView.backgroundColor = .white fromVC.imgLogo.alpha = 0 containerView.layoutIfNeeded() }) { (_) in UIView.animate(withDuration: duration * 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: { toVC.constraintWidthLogo.constant = 107 toVC.constraintHeightLogo.constant = 107 toVC.constraintCenterForm.constant = toVC.initialValueConstraintCenterForm toVC.lblNameCompany.alpha = 1 containerView.layoutIfNeeded() }) { (_) in fromView.backgroundColor = fromVC.initialColor toView.backgroundColor = .white context.completeTransition(true) } } } override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.5 } }
apache-2.0
6cd2ae0a957bfd4e18efc7abdd3b8934
33.408451
160
0.609906
5.489888
false
false
false
false
fluidsonic/JetPack
Sources/Extensions/UIKit/UIImage.swift
1
7468
import UIKit public extension UIImage { @nonobjc convenience init(placeholderOfSize size: CGSize) { guard size.isPositive else { fatalError("\(#function) requires a positive size") } guard let context = CGContext(data: nil, width: Int(ceil(size.width)), height: Int(ceil(size.height)), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { fatalError("\(#function) could not create context") } guard let cgimage = context.makeImage() else { fatalError("\(#function) could not create image from context") } self.init(cgImage: cgimage, scale: 1, orientation: .up) } @nonobjc convenience init?(named name: String, inBundle bundle: Bundle) { self.init(named: name, in: bundle, compatibleWith: nil) } @nonobjc static func fromColor(_ color: UIColor, withSize size: CGSize = CGSize(square: 1), scale: CGFloat = 1) -> UIImage { let frame = CGRect(size: size) UIGraphicsBeginImageContextWithOptions(frame.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { fatalError("Cannot create UIGraphics image context.") } defer { UIGraphicsEndImageContext() } context.setFillColor(color.cgColor) context.fill(frame) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { fatalError("Cannot create image from image context.") } return image } @nonobjc var hasAlphaChannel: Bool { guard let cgImage = cgImage else { return false // TODO support CIImage } let info = cgImage.alphaInfo switch info { case .first, .last, .alphaOnly, .premultipliedFirst, .premultipliedLast: return true case .none, .noneSkipFirst, .noneSkipLast: return false @unknown default: fatalError() } } @nonobjc func imageConstrainedToSize(_ maximumSize: CGSize, interpolationQuality: CGInterpolationQuality = .high) -> UIImage { let orientedMaximumSize = imageOrientation.isLandscape ? CGSize(width: maximumSize.height, height: maximumSize.width) : maximumSize guard let cgImage = self.cgImage else { return self // TODO support CIImage } let currentSize = CGSize(width: cgImage.width, height: cgImage.height) let horizontalScale = orientedMaximumSize.width / currentSize.width let verticalScale = orientedMaximumSize.height / currentSize.height let scale = min(horizontalScale, verticalScale) var targetSize = currentSize.scale(by: scale) targetSize.height = floor(targetSize.height) targetSize.width = floor(targetSize.width) if targetSize.height >= currentSize.height && targetSize.width >= currentSize.width { return self } // TODO handle nil color space guard let context = CGContext(data: nil, width: Int(targetSize.width), height: Int(targetSize.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: cgImage.bitmapInfo.rawValue) else { return self // TODO when can this happen? } context.interpolationQuality = interpolationQuality context.draw(cgImage, in: CGRect(size: targetSize)) let newCoreImage = context.makeImage()! let newImage = UIImage(cgImage: newCoreImage, scale: self.scale, orientation: self.imageOrientation) return newImage } @nonobjc func imageCroppedToSize(_ maximumSize: CGSize) -> UIImage { let orientedMaximumSize = imageOrientation.isLandscape ? CGSize(width: maximumSize.height, height: maximumSize.width) : maximumSize guard let cgImage = self.cgImage else { return self } let currentSize = CGSize(width: cgImage.width, height: cgImage.height) let targetSize = CGSize( width: min(currentSize.width, orientedMaximumSize.width), height: min(currentSize.height, orientedMaximumSize.height) ) if targetSize.height >= currentSize.height && targetSize.width >= currentSize.width { return self } // TODO handle nil color space guard let context = CGContext(data: nil, width: Int(targetSize.width), height: Int(targetSize.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: cgImage.bitmapInfo.rawValue) else { return self // TODO when can this happen? } let drawFrame = CGRect( left: floor((targetSize.width - currentSize.width) / 2), top: floor((targetSize.height - currentSize.height) / 2), width: currentSize.width, height: currentSize.height ) context.draw(cgImage, in: drawFrame) let newCoreImage = context.makeImage()! let newImage = UIImage(cgImage: newCoreImage, scale: self.scale, orientation: self.imageOrientation) return newImage } @nonobjc func imageWithAlpha(_ alpha: CGFloat) -> UIImage { guard alpha <= 0 else { return self } return imageWithBlendMode(.sourceIn, destinationColor: UIColor(white: 0, alpha: alpha)) } @nonobjc fileprivate func imageWithBlendMode(_ blendMode: CGBlendMode, color: UIColor, colorIsDestination: Bool) -> UIImage { let frame = CGRect(size: size) UIGraphicsBeginImageContextWithOptions(frame.size, !hasAlphaChannel, scale) if colorIsDestination { color.set() UIRectFill(frame) draw(in: frame, blendMode: blendMode, alpha: 1) } else { draw(in: frame) color.set() UIRectFillUsingBlendMode(frame, blendMode) } guard var image = UIGraphicsGetImageFromCurrentImageContext() else { fatalError("Why does this still return an implicit optional? When can it be nil?") } UIGraphicsEndImageContext() if image.capInsets != capInsets { image = image.resizableImage(withCapInsets: capInsets) } if image.renderingMode != renderingMode { image = image.withRenderingMode(renderingMode) } return image } @nonobjc func imageWithBlendMode(_ blendMode: CGBlendMode, destinationColor: UIColor) -> UIImage { return imageWithBlendMode(blendMode, color: destinationColor, colorIsDestination: true) } @nonobjc func imageWithBlendMode(_ blendMode: CGBlendMode, sourceColor: UIColor) -> UIImage { return imageWithBlendMode(blendMode, color: sourceColor, colorIsDestination: false) } @nonobjc func imageWithHueFromColor(_ color: UIColor) -> UIImage { return imageWithBlendMode(.hue, sourceColor: color) } @nonobjc func imageWithColor(_ color: UIColor) -> UIImage { return imageWithBlendMode(.sourceIn, sourceColor: color) } /** Decompresses the underlying and potentially compressed image data (like PNG or JPEG). You can use this to force decompression on a background thread prior to using this image on the main thread so subsequent operations like rendering are faster. */ @nonobjc func inflate() { guard let cgImage = cgImage, let dataProvider = cgImage.dataProvider else { return } _ = dataProvider.data } @nonobjc func luminocityImage() -> UIImage { return imageWithBlendMode(.luminosity, destinationColor: .white) } } public extension UIImage.Orientation { init?(CGImageOrientation: Int) { switch CGImageOrientation { case 1: self = .up case 2: self = .upMirrored case 3: self = .down case 4: self = .downMirrored case 5: self = .leftMirrored case 6: self = .right case 7: self = .rightMirrored case 8: self = .left default: return nil } } var isLandscape: Bool { switch self { case .left, .leftMirrored, .right, .rightMirrored: return true case .down, .downMirrored, .up, .upMirrored: return false @unknown default: fatalError() } } var isPortrait: Bool { return !isLandscape } }
mit
8bec388dced08d1cd51906895cb90673
26.355311
243
0.73353
3.978689
false
false
false
false
jantimar/Weather-forecast
Weather forecast/Constants.swift
1
939
// // Constants.swift // Weather forecast // // Created by Jan Timar on 8.5.2015. // Copyright (c) 2015 Jan Timar. All rights reserved. // import Foundation struct Constants { static let TempratureUnitKey = "sk.jantimar.Weather-forecast.TempratureUnitKey" static let LengthUnitKey = "sk.jantimar.Weather-forecast.LengthUnitKey" static let TempretureCelldentifire = "TempretureTableViewCelldentifire" static let FoundCityCellIdentifire = "FoundCityCellIdentifire" static let FoundCityMapAnnotationIdentifire = "FoundCityMapAnnotationIdentifire" static let UsingSpecificPositionKey = "sk.jantimar.Weather-forecast.UsingSpecificPositionKey" static let LatitudeKey = "sk.jantimar.Weather-forecast.LatitudenKey" static let LongitudeKey = "sk.jantimar.Weather-forecast.LongitudeKey" static let UserCoordinateKey = "sk.jantimar.Weather-forecast.UserCoordinateKey" static let AnimationDuration = 0.5 }
mit
0eb920aa2b9cae491ff86be1370a0a89
41.727273
97
0.784878
3.653696
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/MetadataParserHelper.swift
1
2932
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SDWebImage import Shared import Storage import XCGLogger import WebKit private let log = Logger.browserLogger class MetadataParserHelper: TabEventHandler { init() { register(self, forTabEvents: .didChangeURL) } func tab(_ tab: Tab, didChangeURL url: URL) { // Get the metadata out of the page-metadata-parser, and into a type safe struct as soon // as possible. guard let webView = tab.webView, let url = webView.url, url.isWebPage(includeDataURIs: false), !InternalURL.isValid(url: url) else { return } webView.evaluateJavaScript("__firefox__.metadata && __firefox__.metadata.getMetadata()") { (result, error) in guard error == nil else { return } guard let dict = result as? [String: Any], let pageURL = tab.url?.displayURL, let pageMetadata = PageMetadata.fromDictionary(dict) else { log.debug("Page contains no metadata!") return } tab.pageMetadata = pageMetadata TabEvent.post(.didLoadPageMetadata(pageMetadata), for: tab) let userInfo: [String: Any] = [ "isPrivate": tab.isPrivate, "pageMetadata": pageMetadata, "tabURL": pageURL ] NotificationCenter.default.post(name: .OnPageMetadataFetched, object: nil, userInfo: userInfo) } } } class MediaImageLoader: TabEventHandler { private let prefs: Prefs init(_ prefs: Prefs) { self.prefs = prefs register(self, forTabEvents: .didLoadPageMetadata) } func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) { let cacheImages = !NoImageModeHelper.isActivated(prefs) if let urlString = metadata.mediaURL, let mediaURL = URL(string: urlString), cacheImages { prepareCache(mediaURL) } } fileprivate func prepareCache(_ url: URL) { let manager = SDWebImageManager.shared if manager.cacheKey(for: url) == nil { self.downloadAndCache(fromURL: url) } } fileprivate func downloadAndCache(fromURL webUrl: URL) { let manager = SDWebImageManager.shared manager.loadImage(with: webUrl, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in if let image = image { self.cache(image: image, forURL: webUrl) } } } fileprivate func cache(image: UIImage, forURL url: URL) { SDImageCache.shared.storeImageData(toDisk: image.sd_imageData(), forKey: url.absoluteString) } }
mpl-2.0
02fffca7db862c8afea6cf9feb789ae5
32.701149
117
0.609823
4.66879
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/DropWhileCursorTests.swift
1
2102
import XCTest import GRDB private struct TestError : Error { } class DropWhileCursorTests: GRDBTestCase { func testDropWhileCursorFromCursor() throws { do { let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 5) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in true }) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in false }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 5) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in throw TestError() }) _ = try cursor.next() XCTFail() } catch is TestError { } catch { XCTFail() } } func testDropWhileCursorFromThrowingCursor() throws { var i = 0 let base: AnyCursor<Int> = AnyCursor { guard i < 4 else { throw TestError() } defer { i += 1 } return i } let cursor = base.drop(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 3) do { _ = try cursor.next() XCTFail() } catch is TestError { } catch { XCTFail() } } }
mit
a430bc285385af33b2236557c9c61a77
31.84375
69
0.495718
4.325103
false
true
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Network/pwg.categories/pwg.categories.add.swift
1
2831
// // pwg.categories.add // piwigoKit // // Created by Eddy Lelièvre-Berna on 03/06/2022. // Copyright © 2022 Piwigo.org. All rights reserved. // import Foundation // MARK: - pwg.images.upload public let kPiwigoCategoriesAdd = "format=json&method=pwg.categories.add" public struct CategoriesAddJSON: Decodable { public var status: String? public var data = CategoriesAdd(id: NSNotFound, info: "") public var errorCode = 0 public var errorMessage = "" private enum RootCodingKeys: String, CodingKey { case status = "stat" case data = "result" case errorCode = "err" case errorMessage = "message" } private enum ErrorCodingKeys: String, CodingKey { case code = "code" case message = "msg" } public init(from decoder: Decoder) throws { do { // Root container keyed by RootCodingKeys guard let rootContainer = try? decoder.container(keyedBy: RootCodingKeys.self) else { return } // dump(rootContainer) // Status returned by Piwigo status = try rootContainer.decodeIfPresent(String.self, forKey: .status) if status == "ok" { // Decodes response from the data and store them in the array data = try rootContainer.decodeIfPresent(CategoriesAdd.self, forKey: .data) ?? CategoriesAdd(id: NSNotFound, info: "") // dump(data) } else if status == "fail" { // Retrieve Piwigo server error do { // Retrieve Piwigo server error errorCode = try rootContainer.decode(Int.self, forKey: .errorCode) errorMessage = try rootContainer.decode(String.self, forKey: .errorMessage) } catch { // Error container keyed by ErrorCodingKeys ("format=json" forgotten in call) let errorContainer = try rootContainer.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .errorCode) errorCode = Int(try errorContainer.decode(String.self, forKey: .code)) ?? NSNotFound errorMessage = try errorContainer.decode(String.self, forKey: .message) } } else { // Unexpected Piwigo server error errorCode = -1 errorMessage = "Unexpected error encountered while calling server method with provided parameters." } } catch let error { print(error.localizedDescription) } } } // MARK: - Result public struct CategoriesAdd: Decodable { public let id: Int? // 1042 public let info: String? // "Album added" }
mit
f6634e73d7f4e6b7e31cad6507e78a95
33.5
134
0.576529
4.945804
false
false
false
false
yanif/circator
MetabolicCompass/View/BaseControls/FontScaleLabel.swift
1
1187
// // FontScaleLabel.swift // MetabolicCompass // // Created by Vladimir on 5/25/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation import UIKit public class FontScaleLabel: UILabel { private var notScaledFont:UIFont? = nil public static var scaleFactor: CGFloat = 1.0 // required public init(coder aDecoder: NSCoder) { // super.init(coder: aDecoder)! // self.commonInit() // } // // override init(frame: CGRect) { // super.init(frame: frame) // self.commonInit() // } // // func commonInit(){ // // } override public func awakeFromNib() { super.awakeFromNib() if self.notScaledFont == nil { self.notScaledFont = self.font; self.font = self.notScaledFont; } } override public var font: UIFont!{ get { return super.font } set { self.notScaledFont = newValue; if newValue != nil{ let scaledFont = newValue!.fontWithSize(newValue!.pointSize * FontScaleLabel.scaleFactor) super.font = scaledFont } } } }
apache-2.0
2078eeeb69e5f1f2c2dd4a3427b8d4dc
21.807692
105
0.569983
4.089655
false
false
false
false
Cellane/iWeb
Sources/App/Extensions/ViewRenderer+DefaultData.swift
1
593
import Vapor import Flash extension ViewRenderer { public func makeDefault(_ path: String, for request: Request, _ data: NodeRepresentable? = nil, from provider: Provider.Type? = nil) throws -> View { var node = try data?.makeNode(in: nil) ?? Node(nil) try node.set("flash", request.storage[Helper.flashKey]) try node.set("me", User.fetchPersisted(for: request).makeNode(in: nil)) let viewData = try node.converted(to: ViewData.self, in: ViewData.defaultContext) let viewsDir = provider?.viewsDir ?? "" return try make(viewsDir + path, viewData) } }
mit
20818aa6dca7a9b8ddf59add84ad394f
33.882353
96
0.686341
3.638037
false
false
false
false
jad6/CV
Swift/Jad's CV/Sections/References/RefereesCollectionViewFlowLayout.swift
1
1077
// // RefereesCollectionViewFlowLayout.swift // Jad's CV // // Created by Jad Osseiran on 25/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit let kRefereeCardBaseSize = CGSize(width: 310.0, height: 200.0) class RefereesCollectionViewFlowLayout: UICollectionViewFlowLayout { //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) self.setupSpacing() } override init() { super.init() self.setupSpacing() } //MARK:- Layout override func prepareLayout() { super.prepareLayout() itemSize = kRefereeCardBaseSize } //MARK:- Logic func setupSpacing() { minimumLineSpacing = 10.0 minimumInteritemSpacing = 10.0 if UIDevice.isPad() { sectionInset = UIEdgeInsets(top: 30.0, left: 30.0, bottom: 30.0, right: 30.0) } else { sectionInset = UIEdgeInsets(top: 15.0, left: 0.0, bottom: 15.0, right: 0.0) } } }
bsd-3-clause
7e69bc5e3f66dea027e16f49c3840d02
20.979592
89
0.57753
4.079545
false
false
false
false
cameronklein/BigScreenGifs
BigScreenGifs/BigScreenGifs/Gif.swift
1
2668
// // Gif.swift // BigScreenGifs // // Created by Cameron Klein on 9/19/15. // Copyright © 2015 Cameron Klein. All rights reserved. // import UIKit import AVKit class Gif { let id : String let description : String? let url : NSURL let size : CGSize let asset : AVAsset // MARK: - Initializers init(id: String, description: String?, url: NSURL, size: CGSize) { self.id = id self.description = description self.url = url self.size = size self.asset = AVAsset(URL: url) } enum GifError : ErrorType { case NoID, NoSize, NoType, NoUrl, WrongType, invalidURL } convenience init(json: NSDictionary) throws { guard let id = json["id"] as? String else { throw GifError.NoID } guard let width = json["width"] as? CGFloat else { throw GifError.NoSize } guard let height = json["width"] as? CGFloat else { throw GifError.NoSize } guard let type = json["type"] as? String else { throw GifError.NoType } guard let urlString = json["mp4"] as? String else { throw GifError.NoUrl } guard let url = NSURL(string: urlString) else { throw GifError.invalidURL } guard type == "image/gif" else { throw GifError.WrongType } let description = json["title"] as? String self.init(id: id, description: description, url: url, size: CGSizeMake(width, height)) } class func gifsFromGalleryDictionary(json: NSDictionary) -> [Gif] { var array = [Gif]() guard let images = json["data"] as? [NSDictionary] else { return array } for image in images { do { let gif = try Gif(json: image) array.append(gif) } catch GifError.NoID { print("Gif Initialization Error: No ID!") } catch GifError.NoSize { print("Gif Initialization Error: No Size!") } catch GifError.NoType { print("Gif Initialization Error: No Type!") } catch GifError.NoUrl { print("Gif Initialization Error: No URL!") } catch GifError.WrongType { print("Gif Initialization Error: Wrong Type!") } catch GifError.invalidURL { print("Gif Initialization Error: Invalid URL!") } catch { print("Something went very wrong") } } return array } }
mit
a019ea3a6680c6bc2d0b40091053b147
31.925926
94
0.532808
4.51269
false
false
false
false
j-j-m/DataTableKit
DataTableKit/Classes/TablePrototypeCellHeightCalculator.swift
1
3219
// // Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov // // 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 open class TablePrototypeCellHeightCalculator: RowHeightCalculator { private(set) weak var tableView: UITableView? private var prototypes = [String: UITableViewCell]() private var cachedHeights = [Int: CGFloat]() private var separatorHeight = 1 / UIScreen.main.scale public init(tableView: UITableView?) { self.tableView = tableView } open func height(forRow row: Row, at indexPath: IndexPath) -> CGFloat { guard let tableView = tableView else { return 0 } let hash = row.hashValue ^ Int(tableView.bounds.size.width).hashValue if let height = cachedHeights[hash] { return height } var prototypeCell = prototypes[row.reuseIdentifier] if prototypeCell == nil { prototypeCell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier) prototypes[row.reuseIdentifier] = prototypeCell } guard let cell = prototypeCell else { return 0 } cell.prepareForReuse() row.configure(cell) cell.bounds = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: cell.bounds.height) cell.setNeedsLayout() cell.layoutIfNeeded() let height = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height + (tableView.separatorStyle != .none ? separatorHeight : 0) cachedHeights[hash] = height return height } open func estimatedHeight(forRow row: Row, at indexPath: IndexPath) -> CGFloat { guard let tableView = tableView else { return 0 } let hash = row.hashValue ^ Int(tableView.bounds.size.width).hashValue if let height = cachedHeights[hash] { return height } if let estimatedHeight = row.estimatedHeight , estimatedHeight > 0 { return estimatedHeight } return UITableViewAutomaticDimension } open func invalidate() { cachedHeights.removeAll() } }
mit
90147169524fedf2eb72bfeb1769bad9
36
159
0.68251
4.922018
false
false
false
false
johnno1962d/swift
test/decl/protocol/req/optional.swift
1
8294
// RUN: %target-parse-verify-swift // ----------------------------------------------------------------------- // Declaring optional requirements // ----------------------------------------------------------------------- @objc class ObjCClass { } @objc protocol P1 { optional func method(_ x: Int) // expected-note 4{{requirement 'method' declared here}} optional var prop: Int { get } // expected-note 3{{requirement 'prop' declared here}} optional subscript (i: Int) -> ObjCClass? { get } // expected-note 3{{requirement 'subscript' declared here}} } @objc protocol P2 { @objc(objcMethodWithInt:) optional func method(y: Int) // expected-note 1{{requirement 'method(y:)' declared here}} } // ----------------------------------------------------------------------- // Providing witnesses for optional requirements // ----------------------------------------------------------------------- // One does not have provide a witness for an optional requirement class C1 : P1 { } // ... but it's okay to do so. class C2 : P1 { @objc func method(_ x: Int) { } @objc var prop: Int = 0 @objc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // "Near" matches. // ----------------------------------------------------------------------- class C3 : P1 { func method(_ x: Int) { } // expected-warning@-1{{non-'@objc' method 'method' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} var prop: Int = 0 // expected-warning@-1{{non-'@objc' property 'prop' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} subscript (i: Int) -> ObjCClass? { // expected-warning@-1{{non-'@objc' subscript does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} get { return nil } set {} } } class C4 { } extension C4 : P1 { func method(_ x: Int) { } // expected-warning@-1{{non-'@objc' method 'method' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} var prop: Int { return 5 } // expected-warning@-1{{non-'@objc' property 'prop' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} subscript (i: Int) -> ObjCClass? { // expected-warning@-1{{non-'@objc' subscript does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} get { return nil } set {} } } class C5 : P1 { } extension C5 { func method(_ x: Int) { } // expected-warning@-1{{non-'@objc' method 'method' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} var prop: Int { return 5 } // expected-warning@-1{{non-'@objc' property 'prop' does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} subscript (i: Int) -> ObjCClass? { // expected-warning@-1{{non-'@objc' subscript does not satisfy optional requirement of '@objc' protocol 'P1'}}{{3-3=@objc }} // expected-note@-2{{add '@nonobjc' to silence this warning}}{{3-3=@nonobjc }} get { return nil } set {} } } // Note: @nonobjc suppresses warnings class C6 { } extension C6 : P1 { @nonobjc func method(_ x: Int) { } @nonobjc var prop: Int { return 5 } @nonobjc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // Note: warn about selector matches where the Swift names didn't match. @objc class C7 : P1 { // expected-note{{class 'C7' declares conformance to protocol 'P1' here}} @objc(method:) func otherMethod(x: Int) { } // expected-error{{Objective-C method 'method:' provided by method 'otherMethod(x:)' conflicts with optional requirement method 'method' in protocol 'P1'}} // expected-note@-1{{rename method to match requirement 'method'}}{{23-34=method}}{{35-35=_ }} } @objc class C8 : P2 { // expected-note{{class 'C8' declares conformance to protocol 'P2' here}} func objcMethod(int x: Int) { } // expected-error{{Objective-C method 'objcMethodWithInt:' provided by method 'objcMethod(int:)' conflicts with optional requirement method 'method(y:)' in protocol 'P2'}} // expected-note@-1{{add '@nonobjc' to silence this error}}{{3-3=@nonobjc }} // expected-note@-2{{rename method to match requirement 'method(y:)'}}{{3-3=@objc(objcMethodWithInt:) }}{{8-18=method}}{{19-22=y}} } // ----------------------------------------------------------------------- // Using optional requirements // ----------------------------------------------------------------------- // Optional method references in generics. func optionalMethodGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in generics. func optionalPropertyGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in generics. func optionalSubscriptGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // Optional method references in existentials. func optionalMethodExistential(_ t: P1) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in existentials. func optionalPropertyExistential(_ t: P1) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in existentials. func optionalSubscriptExistential(_ t: P1) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // ----------------------------------------------------------------------- // Restrictions on the application of optional // ----------------------------------------------------------------------- // optional cannot be used on non-protocol declarations optional var optError: Int = 10 // expected-error{{'optional' can only be applied to protocol members}} optional struct optErrorStruct { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } optional class optErrorClass { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int = 0 // expected-error{{'optional' can only be applied to protocol members}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} } protocol optErrorProtocol { optional func foo(_ x: Int) // expected-error{{'optional' can only be applied to members of an @objc protocol}} optional associatedtype Assoc // expected-error{{'optional' modifier cannot be applied to this declaration}} {{3-12=}} } @objc protocol optionalInitProto { optional init() // expected-error{{'optional' cannot be applied to an initializer}} }
apache-2.0
b18e3f9eaa27035525b8e41ec850f4fc
33.558333
205
0.604051
3.964627
false
false
false
false
tlax/GaussSquad
GaussSquad/View/CalculatorOptions/VCalculatorOptionsCell.swift
1
1496
import UIKit class VCalculatorOptionsCell:UICollectionViewCell { private weak var labelTitle:UILabel! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.backgroundColor = UIColor.clear labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.font = UIFont.medium(size:15) labelTitle.textAlignment = NSTextAlignment.center self.labelTitle = labelTitle addSubview(labelTitle) NSLayoutConstraint.equals( view:labelTitle, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { backgroundColor = UIColor.squadBlue labelTitle.textColor = UIColor.white } else { backgroundColor = UIColor.white labelTitle.textColor = UIColor.black } } //MARK: public func config(model:MCalculatorFunctions) { labelTitle.text = model.title hover() } }
mit
34b9f71fb787d1fe5d95038a45b6b2d2
20.070423
68
0.556818
5.62406
false
false
false
false
kitasuke/TwitterClientDemo
TwitterClientDemo/Classes/ViewControllers/FollowersViewController.swift
1
6864
// // FollowersViewController.swift // TwitterClientDemo // // Created by Yusuke Kita on 5/20/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class FollowersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView? private var users = [User]() private var paginator = Paginator() private let CellHeightUser: CGFloat = 64 private var loading = false private enum Section: Int { case Indicator = 0 case Contents = 1 } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupTableView() self.fetchFollowersList(readMore: false) self.fetchMeInBackground() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDelegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 // Indicator + Contents } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Section.Indicator.rawValue: return count(users) > 0 ? 0 : 1 // show indicator if no contents case Section.Contents.rawValue: return count(users) default: return 0 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.section { case Section.Indicator.rawValue: return CGRectGetHeight(tableView.frame) case Section.Contents.rawValue: return CellHeightUser default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case Section.Indicator.rawValue: let cell = tableView.dequeueReusableCellWithIdentifier(CellName.Indicator.rawValue, forIndexPath: indexPath) as! IndicatorCell return cell case Section.Contents.rawValue: let cell = tableView.dequeueReusableCellWithIdentifier(CellName.User.rawValue, forIndexPath: indexPath) as! UserCell let user = users[indexPath.row] cell.setup(user, indexPath: indexPath) self.registerGestureRecognizers(cell) return cell default: return UITableViewCell() } } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // read more if needed if paginator.hasNext && !loading && count(users) - 10 < indexPath.row { // TODO self.fetchFollowersList(readMore: true) } } // MARK: - Gesture handler internal func openMessageView(recognizer: UITapGestureRecognizer) { if let row = recognizer.view?.tag { let user = users[row] UserStore.sharedStore.currentUser = user let messageViewController = UIStoryboard(name: StoryboardName.Message.rawValue, bundle: nil).instantiateInitialViewController() as! MessageViewController self.navigationController?.pushViewController(messageViewController, animated: true) } } internal func openProfileView(recognizer: UITapGestureRecognizer) { if let row = recognizer.view?.tag { let user = users[row] UserStore.sharedStore.currentUser = user let profileViewController = UIStoryboard(name: StoryboardName.Profile.rawValue, bundle: nil).instantiateInitialViewController() as! ProfileViewController self.navigationController?.pushViewController(profileViewController, animated: true) } } // MARK: - IBAction @IBAction func openMyProfileView(sender: UIBarButtonItem) { UserStore.sharedStore.currentUser = UserStore.sharedStore.me let profileViewController = UIStoryboard(name: StoryboardName.Profile.rawValue, bundle: nil).instantiateInitialViewController() as! ProfileViewController self.navigationController?.pushViewController(profileViewController, animated: true) } // MARK: - Setup private func setupTableView() { self.tableView?.estimatedRowHeight = CellHeightUser let userCellName = CellName.User.rawValue self.tableView?.registerNib(UINib(nibName: userCellName, bundle: nil), forCellReuseIdentifier: userCellName) let indicatorCellName = CellName.Indicator.rawValue self.tableView?.registerNib(UINib(nibName: indicatorCellName, bundle: nil), forCellReuseIdentifier: indicatorCellName) } private func registerGestureRecognizers(cell: UserCell) { cell.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("openMessageView:"))) cell.profileImageView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("openProfileView:"))) } // MARK: - Fetcher private func fetchFollowersList(#readMore: Bool) { loading = true let nextCorsor = readMore ? paginator.nextCursor : -1 // TODO UIApplication.sharedApplication().networkActivityIndicatorVisible = true dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in TwitterStore.sharedStore.fetchFollowers({ [unowned self] (result: Result<[String : AnyObject]>) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false self.loading = false if let error = result.error { let alertController = ConnectionAlert.Error(message: error.description).alertController self.presentViewController(alertController, animated: true, completion: nil) return } if let values = result.value { self.users += values["users"] as! [User] self.paginator = values["paginator"] as! Paginator dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView?.reloadData() }) } }, nextCursor: nextCorsor) }) } private func fetchMeInBackground() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in TwitterStore.sharedStore.fetchMe({ (result: Result<User>) -> Void in // TODO }) }) } }
mit
2ffa720135880240032c6ed7b144fa3e
39.376471
165
0.649184
5.52657
false
false
false
false
ymkil/LKImagePicker
LKImagePicker/AssetManager.swift
1
18964
// // AssetManager.swift // LKImagePicker // // Created by Mkil on 19/12/2016. // Copyright © 2016 黎宁康. All rights reserved. // import Foundation import Photos import AssetsLibrary public struct AssetManager { // MARK: - 获取相册和相册列表 /// 获取相册 public static func getImageAlbum(_ allowPickingVideo: Bool, _ allowPickingImage: Bool, _ sortDate: Bool, _ completion: @escaping (LKAlbumModel) -> Void) { var model: LKAlbumModel? = nil let option = PHFetchOptions() if !allowPickingVideo { option.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) } if !allowPickingImage { option.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue) } option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: sortDate)] let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) for i in 0..<smartAlbums.count { // guard smartAlbums[i] is PHAssetCollection else { continue } if isPhotoAlbum(smartAlbums[i].localizedTitle!) { let fetchResult = PHAsset.fetchAssets(in: smartAlbums[i], options: option) model = LKAlbumModel(result: fetchResult, name: smartAlbums[i].localizedTitle!,allowPickingVideo,allowPickingImage,sortDate) completion(model!) break } } } /// 获取相册列表 public static func getAllAlbums(_ allowPickingVideo: Bool, _ allowPickingImage: Bool, _ sortDate: Bool, _ completion: @escaping ([LKAlbumModel]) -> Void) { var albumArray: [LKAlbumModel] = [] let option = PHFetchOptions() if !allowPickingVideo { option.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) } if !allowPickingImage { option.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.video.rawValue) } option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: sortDate)] let myPhotoStreamAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumMyPhotoStream, options: nil) let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) for i in 0..<myPhotoStreamAlbums.count { let fetchResult = PHAsset.fetchAssets(in: myPhotoStreamAlbums[i], options: option) guard !(fetchResult.count < 1) else { continue } albumArray.append(LKAlbumModel(result: fetchResult, name: myPhotoStreamAlbums[i].localizedTitle!,allowPickingVideo,allowPickingImage,sortDate)) } for i in 0..<smartAlbums.count { // guard smartAlbums[i] is PHAssetCollection else { continue } let fetchResult = PHAsset.fetchAssets(in: smartAlbums[i], options: option) guard !(fetchResult.count < 1) else { continue } if ((smartAlbums[i].localizedTitle!.contains("Deleted")) || (smartAlbums[i].localizedTitle == "最近删除")) { continue } if isPhotoAlbum(smartAlbums[i].localizedTitle!) { albumArray.insert(LKAlbumModel(result: fetchResult, name: smartAlbums[i].localizedTitle!,allowPickingVideo,allowPickingImage,sortDate), at: 0) } else { albumArray.append(LKAlbumModel(result: fetchResult, name: smartAlbums[i].localizedTitle!,allowPickingVideo,allowPickingImage,sortDate)) } } for i in 0..<topLevelUserCollections.count { guard topLevelUserCollections[i] is PHAssetCollection else { continue } let fetchResult = PHAsset.fetchAssets(in: topLevelUserCollections[i] as! PHAssetCollection, options: option) guard fetchResult.count >= 1 else { continue } albumArray.append(LKAlbumModel(result: fetchResult, name: topLevelUserCollections[i].localizedTitle!,allowPickingVideo,allowPickingImage,sortDate)) } completion(albumArray) } /// 获取照片数组 public static func getAssetsFromFetchResult(_ result:PHFetchResult<PHAsset>, _ allowPickingVideo:Bool, _ allowPickingImage:Bool, _ sortDate: Bool, _ completion: @escaping ([LKAssetModel]) -> Void) { var photoArr:[LKAssetModel] = [] result.enumerateObjects({ (obj, idx, stop) -> Void in let asset = obj var type = LKAssetModelMediaType.photo if asset.mediaType == .video { type = .video } else if asset.mediaType == .audio { type = .audio } else if asset.mediaType == .image { type = .photo } if !allowPickingVideo && type == .video { return } if !allowPickingImage && type == .photo { return } var timeLength = type == .video ? String(format: "%0.0f", asset.duration) : "" if type == .video { timeLength = getNewTimeFromDurationSecond(duration: timeLength.toInt) } photoArr.append(LKAssetModel(asset,false,type,timeLength)) }) completion(photoArr) } /// 获取封面图 public static func getSurfacePlot(_ model: LKAlbumModel, _ sortDate:Bool, _ shouldFixOrientation:Bool, completion:@escaping (UIImage) -> Void) { var asset = model.result.lastObject if !sortDate { asset = model.result.firstObject } if let asset = asset { getPhoto(asset, 80, shouldFixOrientation, completion: { (photo,info, isDegraded) -> Void in if let image = photo { completion(image) } }, progressHandler: nil, networkAccessAllowed: true) } } // MARK: - 获取照片本身 @discardableResult public static func getPhoto(_ asset: PHAsset, _ shouldFixOrientation: Bool,completion:@escaping (UIImage?,[AnyHashable : Any]?,Bool) -> Void, progressHandler: ((Double, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void)?, networkAccessAllowed: Bool) -> PHImageRequestID { var fullScreenWidth = Configuration.ScreenWinth if fullScreenWidth > Configuration.photoPreviewMaxWidth { fullScreenWidth = Configuration.photoPreviewMaxWidth } return getPhoto(asset, fullScreenWidth, shouldFixOrientation, completion: completion, progressHandler: progressHandler, networkAccessAllowed: networkAccessAllowed) } @discardableResult public static func getPhoto(_ asset: PHAsset, _ width: CGFloat, _ shouldFixOrientation:Bool, completion:@escaping (UIImage?,[AnyHashable : Any]?,Bool) -> Void, progressHandler:((Double, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void)?, networkAccessAllowed: Bool) -> PHImageRequestID { var imageSize: CGSize let phAsset = asset let aspectRatio = CGFloat(phAsset.pixelWidth) / CGFloat(phAsset.pixelHeight) let pixelWidth = width * Configuration.LKScreenScale let pixelHeight = pixelWidth / aspectRatio imageSize = CGSize(width: pixelWidth, height: pixelHeight) let option = PHImageRequestOptions() option.resizeMode = .fast // 需检测获取图片的瞬间是否会出现内存过高的问题 let imageRequestID = PHImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFill, options: option) { (result, info) -> Void in var resultImage = result let downloadFinined = info![PHImageCancelledKey] == nil && info![PHImageErrorKey] == nil if downloadFinined && (resultImage != nil) { resultImage = self.fixOrientation(resultImage!, shouldFixOrientation) completion(resultImage!, info, info?[PHImageResultIsDegradedKey] as! Bool) } // 从iCloud下载图片 if info![PHImageResultIsInCloudKey] != nil && (resultImage == nil) { let option = PHImageRequestOptions() option.progressHandler = { (progress, error, stop, info) in DispatchQueue.main.async { if let block = progressHandler { block(progress, error, stop, info) } } } option.isNetworkAccessAllowed = true option.resizeMode = .fast PHImageManager.default().requestImageData(for: asset, options: option) { (imageData,dataUTI,orientation,info) -> Void in var resultImage = UIImage(data: imageData!, scale: 0.1) resultImage = self.scaleImage(resultImage!, imageSize) if let _ = resultImage { resultImage = self.fixOrientation(resultImage!, shouldFixOrientation) } completion(resultImage, info, info?[PHImageResultIsDegradedKey] as! Bool) } } } return imageRequestID } /// Get Original Photo / 获取原图 /// 该方法会先返回缩略图,再返回原图,如果info[PHImageResultIsDegradedKey] 为 YES,则表明当前返回的是缩略图,否则是原图。 public static func getOriginalPhoto(asset:PHAsset, _ shouldFixOrientation:Bool, completion:((UIImage?, [AnyHashable : Any]?) -> Void)?) { AssetManager.getOriginalPhoto(asset: asset, shouldFixOrientation) { (photo, info, isDegraded) in if let completion = completion { completion(photo,info) } } } public static func getOriginalPhoto(asset:PHAsset, _ shouldFixOrientation:Bool, newCompletion:((UIImage?, [AnyHashable : Any]?, Bool?) -> Void)?) { let option = PHImageRequestOptions() option.isNetworkAccessAllowed = true PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (result, info) in let downloadFinined = info![PHImageCancelledKey] == nil && info![PHImageErrorKey] == nil if downloadFinined , var photo = result { photo = self.fixOrientation(photo, shouldFixOrientation) let isDegraded = info?[PHImageResultIsDegradedKey] as? Bool if let completion = newCompletion { completion(photo, info, isDegraded) } } } } /// Save photo private static var assetLibrary:ALAssetsLibrary = { return ALAssetsLibrary() }() public static func savePhoto(_ image:UIImage, completion:((Error?) -> Void)?) { let data = UIImageJPEGRepresentation(image, 0.9) if #available(iOS 9, *) , let data = data { PHPhotoLibrary.shared().performChanges({ let options = PHAssetResourceCreationOptions() options.shouldMoveFile = true PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: options) }, completionHandler: { (success, error) in DispatchQueue.main.sync { if success , let completion = completion { completion(nil) } else if let error = error { if let completion = completion { completion(error) } } } }) } else { assetLibrary.writeImage(toSavedPhotosAlbum: image.cgImage, orientation: AssetManager.imageOrientation(image), completionBlock: { (assetURL, error) in if let error = error { if let completion = completion { completion(error) } } else { // 多给系统0.5秒的时间,让系统去更新相册数据 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(500)) { if let completion = completion { completion(nil) } } } }) } } /// 获得一组照片的大小 public static func getPhotosBytesWithArray(_ photos:[LKAssetModel], completion:((String) -> Void)?) { var dataLength:Float = 0 var assetCount = 0 for modle in photos { PHImageManager.default().requestImageData(for: modle.asset, options: nil) { (imageData, dataUTI, orientation, info) in if modle.type != .video , let imageData = imageData{ dataLength += Float(imageData.count) assetCount += 1 } if assetCount >= photos.count { let bytes = AssetManager.getBytesFromDataLength(dataLength: dataLength) if let completion = completion { completion(bytes) } } } } } // MARK: - Private Method public static func getBytesFromDataLength(dataLength:Float) -> String{ var bytes:String if dataLength >= 0.1 * (1024 * 1024) { bytes = String(format: "%0.1fM", dataLength/1024/1024.0) } else if dataLength >= 1024 { bytes = String(format: "%0.0fK", dataLength/1024.0) } else { bytes = String(format: "%zdB", dataLength) } return bytes } /// 得到授权返回true public static func authorizationStatusAuthorized() -> Bool { return PHPhotoLibrary.authorizationStatus() != .denied } public static func imageOrientation(_ image: UIImage) -> ALAssetOrientation { var orientation:ALAssetOrientation switch image.imageOrientation { case .up: orientation = .up case .down: orientation = .down case .left: orientation = .left case .right: orientation = .right case .upMirrored: orientation = .upMirrored case .downMirrored: orientation = .downMirrored case .leftMirrored: orientation = .leftMirrored case .rightMirrored: orientation = .rightMirrored } return orientation } // MARK: - Tool /// 修正图片方向 @discardableResult public static func fixOrientation(_ aImage:UIImage,_ shouldFixOrientation:Bool) -> UIImage { guard shouldFixOrientation else { return aImage } if aImage.imageOrientation == .up { return aImage } let transform = CGAffineTransform() switch aImage.imageOrientation { case .down,.downMirrored: transform.translatedBy(x: aImage.size.width, y: aImage.size.height) transform.rotated(by: CGFloat(M_PI)) case .left,.leftMirrored: transform.translatedBy(x: aImage.size.width, y: 0) transform.rotated(by: CGFloat(M_PI_2)) case .right,.rightMirrored: transform.translatedBy(x: 0, y: aImage.size.height) transform.rotated(by: -(CGFloat)(M_PI_2)) default: break } switch aImage.imageOrientation { case .upMirrored,.downMirrored: transform.translatedBy(x: aImage.size.width, y: 0) transform.scaledBy(x: -1, y: -1) case .leftMirrored,.rightMirrored: transform.translatedBy(x: aImage.size.height, y: 0) transform.scaledBy(x: -1, y: -1) default: break } // 获得新的 context,进行 transform let ctx = CGContext(data: nil, width: aImage.cgImage!.width, height: aImage.cgImage!.height, bitsPerComponent: aImage.cgImage!.bitsPerComponent, bytesPerRow: 0, space: aImage.cgImage!.colorSpace!, bitmapInfo: aImage.cgImage!.bitmapInfo.rawValue) ctx?.concatenate(transform) switch aImage.imageOrientation { case .left,.leftMirrored,.right,.rightMirrored: ctx?.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.height, height: aImage.size.width)) default: ctx?.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.width, height: aImage.size.height)) } let cgImg = ctx?.makeImage() let img = UIImage(cgImage: cgImg!) // Swift 中CGcongtext 和 CGimage 自动释放 return img } public static func scaleImage(_ image: UIImage, _ size: CGSize) -> UIImage { if image.size.width > size.width { UIGraphicsBeginImageContext(size) image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } else { return image } } public static func isPhotoAlbum(_ albumName: String) -> Bool { var versionStr = UIDevice.current.systemVersion.replacingOccurrences(of: ".", with: "") if versionStr.characters.count <= 1 { versionStr.append("00") }else if versionStr.characters.count <= 2 { versionStr.append("0") } let version = versionStr.toFloat if version >= 800 && version <= 802 { return albumName == "最近添加" || albumName == "Recently Added" } else { return albumName == "Camera Roll" || albumName == "相机胶卷" || albumName == "所有照片" || albumName == "All Photos" } } public static func getNewTimeFromDurationSecond(duration:Int) -> String { var newTime:String if duration < 10 { newTime = String(format: "0:0%zd", duration) } else if duration < 60 { newTime = String(format: "0:%zd", duration) } else { let min = duration / 60 let sec = duration % 60 if sec < 10 { newTime = String(format: "%zd:0%zd", min,sec) } else { newTime = String(format: "%zd:%zd", min,sec) } } return newTime } }
mit
d928584b31e0c058f5000d3bd34ae07e
42.576112
312
0.585586
4.951304
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCIPINCodeRequest.swift
1
1553
// // HCIPINCodeRequest.swift // Bluetooth // // Created by Carlos Duclos on 8/10/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// The PIN Code Request event is used to indicate that a PIN code is required to create a new link key. The Host shall respond using either the PIN_Code_Request_Reply or the PIN_Code_Request_Negative_Reply command, depending on whether the Host can provide the Controller with a PIN code or not. /// /// - Note: If the PIN Code Request event is masked away, then the BR/EDR Controller will assume that the Host has no PIN Code. /// When the BR/EDR Controller generates a PIN Code Request event in order for the local Link Manager to respond to the request from the remote Link Manager (as a result of a Create_Connection or Authentication_Requested com- mand from the remote Host), the local Host must respond with either a PIN_Code_Request_Reply or PIN_Code_Request_Negative_Reply com- mand before the remote Link Manager detects LMP response timeout @frozen public struct HCIPINCodeRequest: HCIEventParameter { public static let event = HCIGeneralEvent.pinCodeRequest public static let length: Int = 6 public let address: BluetoothAddress public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[0], data[1], data[2], data[3], data[4], data[5]))) self.address = address } }
mit
f6d9cf8bee93b8de86408c90105521c6
46.030303
423
0.716495
4.347339
false
false
false
false
therealbnut/UIntExtend
source/IntegerExtend.swift
1
7615
// // IntegerExtend.swift // Earley // // Created by Andrew Bennett on 4/11/2015. // Copyright © 2015 TeamBnut. All rights reserved. // public struct IntegerExtend<HalfType: UnsignedIntegerExtendType> { private let unsignedValue: UnsignedIntegerExtend<HalfType> private var lo: HalfType { return unsignedValue.lo } private var hi: HalfType { return unsignedValue.hi } public init(truncatingBitPattern value: UnsignedIntegerExtend<HalfType>) { unsignedValue = value } public init(lo: HalfType, hi: HalfType) { unsignedValue = UnsignedIntegerExtend(lo: lo, hi: hi) } public static var bitCount: UIntMax { return HalfType.bitCount << 1 } private var isPositive: Bool { return !((unsignedValue.hi & ~(HalfType.allZeros >> 1)) == HalfType.allZeros) } private var abs: IntegerExtend { return IntegerExtend(lo: unsignedValue.lo, hi: unsignedValue.hi & (HalfType.allZeros >> 1)) } } extension UnsignedIntegerExtend { init(truncatingBitPattern value: IntegerExtend<HalfType>) { self = value.unsignedValue } } extension IntegerExtend: IntegerLiteralConvertible { public typealias IntegerLiteralType = IntMax public init(integerLiteral value: IntMax) { unsignedValue = UnsignedIntegerExtend(lo: HalfType(UIntMax(value)), hi: HalfType.allZeros) } public init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) { value } } extension IntegerExtend: SignedIntegerType { public init(_ value: IntMax) { unsignedValue = UnsignedIntegerExtend(lo: HalfType(UIntMax(value)), hi: HalfType.allZeros) } } extension IntegerExtend: CustomStringConvertible { public var description: String { return self.isPositive ? self.abs.description : "-\(self.abs.description)" } } extension IntegerExtend: Hashable { public var hashValue: Int { return unsignedValue.hashValue } } extension IntegerExtend: IntegerArithmeticType { public func toIntMax() -> IntMax { return lo.toIntMax() } public static func addWithOverflow(lhs: IntegerExtend, _ rhs: IntegerExtend) -> (IntegerExtend, overflow: Bool) { let value = UnsignedIntegerExtend.addWithOverflow(lhs.unsignedValue, rhs.unsignedValue) return (IntegerExtend(truncatingBitPattern: value.0), value.overflow) } public static func subtractWithOverflow(lhs: IntegerExtend, _ rhs: IntegerExtend) -> (IntegerExtend, overflow: Bool) { let value = UnsignedIntegerExtend.subtractWithOverflow(lhs.unsignedValue, rhs.unsignedValue) return (IntegerExtend(truncatingBitPattern: value.0), value.overflow) } public static func multiplyWithOverflow(lhs: IntegerExtend, _ rhs: IntegerExtend) -> (IntegerExtend, overflow: Bool) { let value = UnsignedIntegerExtend.multiplyWithOverflow(lhs.unsignedValue, rhs.unsignedValue) return (IntegerExtend(truncatingBitPattern: value.0), value.overflow) } public static func divideWithOverflow(lhs: IntegerExtend, _ rhs: IntegerExtend) -> (IntegerExtend, overflow: Bool) { let value = UnsignedIntegerExtend.divideWithOverflow(lhs.unsignedValue, rhs.unsignedValue) return (IntegerExtend(truncatingBitPattern: value.0), value.overflow) } public static func remainderWithOverflow(lhs: IntegerExtend, _ rhs: IntegerExtend) -> (IntegerExtend, overflow: Bool) { let value = UnsignedIntegerExtend.remainderWithOverflow(lhs.unsignedValue, rhs.unsignedValue) return (IntegerExtend(truncatingBitPattern: value.0), value.overflow) } } extension IntegerExtend: BitwiseOperationsType { public init(_ halfType: HalfType) { self.init(lo: halfType, hi: HalfType.allZeros) } public static var allZeros: IntegerExtend { return IntegerExtend(lo: HalfType.allZeros, hi: HalfType.allZeros) } } extension IntegerExtend: BidirectionalIndexType { public func predecessor() -> IntegerExtend { let value = IntegerExtend<HalfType>.subtractWithOverflow(self, IntegerExtend(1)) assert(!value.overflow, "Cannot find predecessor of \(self)") return value.0 } public func successor() -> IntegerExtend { let value = IntegerExtend<HalfType>.addWithOverflow(self, IntegerExtend(1)) assert(!value.overflow, "Cannot find successor of \(self)") return value.0 } } extension IntegerExtend: ForwardIndexType { public typealias Distance = IntegerExtend @warn_unused_result public func advancedBy(n: Distance) -> IntegerExtend { let value = IntegerExtend<HalfType>.addWithOverflow(self, n) assert(!value.overflow, "Overflow in advancedBy \(self)") return value.0 } @warn_unused_result public func advancedBy(n: Distance, limit: IntegerExtend) -> IntegerExtend { let value = IntegerExtend<HalfType>.addWithOverflow(self, n) if value.overflow || value.0 > limit { return limit } return value.0 } @warn_unused_result public func distanceTo(end: IntegerExtend) -> Distance { let value = IntegerExtend<HalfType>.subtractWithOverflow(end, self) assert(!value.overflow, "Cannot find distanceTo \(self)") return value.0 } } //extension IntegerExtend: RandomAccessIndexType { //} // //extension IntegerExtend: Strideable { //} @warn_unused_result public func == <T: Equatable>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> Bool { return lhs.unsignedValue == rhs.unsignedValue } @warn_unused_result public func < <T: Comparable>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> Bool { return lhs.unsignedValue < rhs.unsignedValue } @warn_unused_result public func <= <T: Comparable>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> Bool { return lhs.unsignedValue <= rhs.unsignedValue } @warn_unused_result public func > <T: Comparable>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> Bool { return lhs.unsignedValue > rhs.unsignedValue } @warn_unused_result public func >= <T: Comparable>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> Bool { return lhs.unsignedValue >= rhs.unsignedValue } @warn_unused_result public func & <T: BitwiseOperationsType>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: lhs.unsignedValue & rhs.unsignedValue) } @warn_unused_result public func | <T: BitwiseOperationsType>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: lhs.unsignedValue | rhs.unsignedValue) } @warn_unused_result public func ^ <T: BitwiseOperationsType>(lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: lhs.unsignedValue ^ rhs.unsignedValue) } @warn_unused_result public prefix func ~ <T: BitwiseOperationsType>(that: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: ~that.unsignedValue) } @warn_unused_result public func << <T: BitwiseOperationsType where T: IntegerType, T: IntegerExtendType> (lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: lhs.unsignedValue << rhs.unsignedValue) } @warn_unused_result public func >> <T: BitwiseOperationsType where T: IntegerType, T: IntegerExtendType> (lhs: IntegerExtend<T>, rhs: IntegerExtend<T>) -> IntegerExtend<T> { return IntegerExtend(truncatingBitPattern: lhs.unsignedValue >> rhs.unsignedValue) }
mit
5787a1c5346c743e51a1e5448ee3cc18
34.087558
108
0.710796
4.301695
false
false
false
false
zcLu/DanTangSwift
DanTangSwift/DanTangSwift/Classes/DanTang/Controller/DanTangDetailController.swift
1
5846
// // DanTangDetailController.swift // DanTangSwift // // Created by LuzhiChao on 2017/4/7. // Copyright © 2017年 LuzhiChao. All rights reserved. // import UIKit import MJRefresh let cellID = "cellID" class DanTangDetailController: BaseController { var tableView = UITableView() var bannerImageArray = [String]() var bannerModels = [HomeBannerModel]() var listModels = [HomeListModel]() var type: Int = 0 var offset: Int = 0 override func viewDidLoad() { super.viewDidLoad() setTableView() print(type) loadBannerData() loadListData(type: type, offset: 0) // 下拉刷新上拉加载 tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNew)) tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore)) } // 下拉刷新 @objc private func loadNew() { offset = 0 tableView.mj_header.beginRefreshing() loadBannerData() loadListData(type: type, offset: offset) tableView.mj_header.endRefreshing() } // 上拉加载 @objc private func loadMore() { tableView.mj_footer.beginRefreshing() loadListData(type: type, offset: offset) tableView.mj_footer.endRefreshing() } /// 请求banner数据 func loadBannerData() { // 如果是首页就有banner guard type == 4 else { return } AFNetworkManager.get(api.bannerUrl, param: ["channel":"iOS"], success: { (response) in //QL2(response) // 组装model if let data = response["data"]["banners"].arrayObject { for item in data { let banner = HomeBannerModel(dict: item as! [String : AnyObject]) self.bannerModels.append(banner) } } // banner几张图片 for item in self.bannerModels { self.bannerImageArray.append(item.image_url!) } let cycleView = CycleView.cycleScrollView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 150), imageNameGroup: self.bannerImageArray.count > 0 ? self.bannerImageArray : ["walkthrough_1", "walkthrough_2", "walkthrough_3"]) cycleView.selectClosure = { (index: Int) -> Void in print(index) print(self.bannerModels[index].targetModel?.id! ?? 0) let bannerDetail = BannerDetailController() bannerDetail.id = self.bannerModels[index].targetModel?.id! ?? 0 bannerDetail.title = self.bannerModels[index].targetModel?.title self.navigationController?.pushViewController(bannerDetail, animated: true) } self.tableView.tableHeaderView = cycleView self.tableView.reloadData() }) { (error) in } } /// 获取首页列表数据 /// /// - Parameter type: 数据类型 func loadListData(type: Int, offset: Int) { let idUrl = "/\(type)/items" let param = [ "gender": "1", "generation": "1", "limit": "20", "offset": String(offset) ] AFNetworkManager.get(api.listUrl+idUrl, param: param, success: { (response) in // QL1(response) if self.offset == 0 { self.listModels.removeAll() } self.offset += 20 // 组装model if let data = response["data"]["items"].arrayObject { for item in data { let list = HomeListModel(dict: item as! [String : AnyObject]) self.listModels.append(list) } } self.tableView.reloadData() }) { (error) in } } func setTableView() { tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - NavHeight - TabHeight - HomeTitlesViewHeight), style: .plain) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none view.addSubview(tableView) tableView.register(UINib.init(nibName: "DanTangDetailCell", bundle: nil), forCellReuseIdentifier: cellID) } } // MARK: - UITableViewDelegate extension DanTangDetailController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { QL2(indexPath.row) let detailController = WebController() detailController.urlString = listModels[indexPath.row].content_url detailController.title = "攻略详情" navigationController?.pushViewController(detailController, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150 } } // MARK: - UITableViewDataSource extension DanTangDetailController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! DanTangDetailCell cell.homeList = listModels[indexPath.row] cell.like = { (index) in print(index) let nav = DTNavigationController(rootViewController: LoginController()) self.present(nav, animated: true, completion: nil) } return cell } }
mit
95587bb040decf635c7c53543b199b85
32.970414
240
0.587877
4.852916
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Search/AikanParserModel.swift
1
10449
// // AikanParserModel.swift // CJReader // // Created by yung on 2019/10/9. // import UIKit import HandyJSON class ZSAikanParserModel: NSObject, NSCoding, NSCopying, HandyJSON { var errDate:Date? var searchUrl:String = "" var name:String = "" var type:Int64 = 0 var enabled:Bool = false var checked:Bool = false var searchEncoding:String = "" var host:String = "" var contentReplace:String = "" var contentRemove:String = "" var contentTagReplace:String = "" var content:String = "" var chapterUrl:String = "" var chapterName:String = "" var chapters:String = "" var chaptersModel:[ZSBookChapter] = [] var detailBookIcon:String = "" var detailChaptersUrl:String = "" var bookLastChapterName:String = "" var bookUpdateTime:String = "" var bookUrl:String = "" var bookIcon:String = "" var bookDesc:String = "" var bookCategory:String = "" var bookAuthor:String = "" var bookName:String = "" var books:String = "" var chaptersReverse:Bool = false var detailBookDesc:String = "" var bookType:ZSReaderBookStyle = .online var update:Bool = false var latestChapterName:String = "" required override init() { } required init?(coder aDecoder: NSCoder) { self.errDate = aDecoder.decodeObject(forKey: "errDate") as? Date self.searchUrl = aDecoder.decodeObject(forKey: "searchUrl") as! String self.name = aDecoder.decodeObject(forKey: "name") as! String self.type = aDecoder.decodeInt64(forKey: "type") self.enabled = aDecoder.decodeBool(forKey: "enabled") self.checked = aDecoder.decodeBool(forKey: "checked") self.searchEncoding = aDecoder.decodeObject(forKey: "searchEncoding") as! String self.host = aDecoder.decodeObject(forKey: "host") as! String self.contentReplace = aDecoder.decodeObject(forKey: "contentReplace") as! String self.contentRemove = aDecoder.decodeObject(forKey: "contentRemove") as! String self.contentTagReplace = aDecoder.decodeObject(forKey: "contentTagReplace") as? String ?? "" self.content = aDecoder.decodeObject(forKey: "content") as! String self.chapterUrl = aDecoder.decodeObject(forKey: "chapterUrl") as! String self.chapterName = aDecoder.decodeObject(forKey: "chapterName") as! String self.chapters = aDecoder.decodeObject(forKey: "chapters") as! String self.detailBookIcon = aDecoder.decodeObject(forKey: "detailBookIcon") as! String self.detailChaptersUrl = aDecoder.decodeObject(forKey: "detailChaptersUrl") as! String self.bookLastChapterName = aDecoder.decodeObject(forKey: "bookLastChapterName") as! String self.detailBookDesc = aDecoder.decodeObject(forKey: "detailBookDesc") as! String self.bookUpdateTime = aDecoder.decodeObject(forKey: "bookUpdateTime") as! String self.bookUrl = aDecoder.decodeObject(forKey: "bookUrl") as! String self.bookIcon = aDecoder.decodeObject(forKey: "bookIcon") as! String self.bookDesc = aDecoder.decodeObject(forKey: "bookDesc") as! String self.bookCategory = aDecoder.decodeObject(forKey: "bookCategory") as! String self.bookAuthor = aDecoder.decodeObject(forKey: "bookAuthor") as! String self.bookName = aDecoder.decodeObject(forKey: "bookName") as! String self.books = aDecoder.decodeObject(forKey: "books") as! String self.chaptersReverse = aDecoder.decodeBool(forKey: "chaptersReverse") self.chaptersModel = aDecoder.decodeObject(forKey: "chaptersModel") as? [ZSBookChapter] ?? [] self.bookType = ZSReaderBookStyle(rawValue: aDecoder.decodeInteger(forKey: "bookType")) ?? ZSReaderBookStyle.online self.update = aDecoder.decodeBool(forKey: "update") self.latestChapterName = aDecoder.decodeObject(forKey: "latestChapterName") as? String ?? "" } func encode(with aCoder: NSCoder) { aCoder.encode(self.errDate, forKey: "errDate") aCoder.encode(self.searchUrl, forKey: "searchUrl") aCoder.encode(self.name, forKey: "name") aCoder.encode(self.type, forKey: "type") aCoder.encode(self.enabled, forKey: "enabled") aCoder.encode(self.checked, forKey: "checked") aCoder.encode(self.searchEncoding, forKey: "searchEncoding") aCoder.encode(self.host, forKey: "host") aCoder.encode(self.contentReplace, forKey: "contentReplace") aCoder.encode(self.contentRemove, forKey: "contentRemove") aCoder.encode(self.contentTagReplace, forKey: "contentTagReplace") aCoder.encode(self.content, forKey: "content") aCoder.encode(self.chapterUrl, forKey: "chapterUrl") aCoder.encode(self.chapterName, forKey: "chapterName") aCoder.encode(self.chapters, forKey: "chapters") aCoder.encode(self.detailBookIcon, forKey: "detailBookIcon") aCoder.encode(self.detailChaptersUrl, forKey: "detailChaptersUrl") aCoder.encode(self.bookLastChapterName, forKey: "bookLastChapterName") aCoder.encode(self.bookUpdateTime, forKey: "bookUpdateTime") aCoder.encode(self.bookUrl, forKey: "bookUrl") aCoder.encode(self.bookIcon, forKey: "bookIcon") aCoder.encode(self.bookDesc, forKey: "bookDesc") aCoder.encode(self.bookCategory, forKey: "bookCategory") aCoder.encode(self.bookAuthor, forKey: "bookAuthor") aCoder.encode(self.bookName, forKey: "bookName") aCoder.encode(self.books, forKey: "books") aCoder.encode(self.chaptersReverse, forKey: "chaptersReverse") aCoder.encode(self.chaptersModel, forKey: "chaptersModel") aCoder.encode(self.detailBookDesc, forKey: "detailBookDesc") aCoder.encode(self.bookType.rawValue, forKey: "bookType") aCoder.encode(self.update, forKey: "update") aCoder.encode(self.latestChapterName, forKey: "latestChapterName") } func copySelf() ->ZSAikanParserModel { let copyModel = ZSAikanParserModel() copyModel.errDate = self.errDate copyModel.searchUrl = self.searchUrl copyModel.name = self.name copyModel.type = self.type copyModel.enabled = self.enabled copyModel.checked = self.checked copyModel.searchEncoding = self.searchEncoding copyModel.host = self.host copyModel.contentReplace = self.contentReplace copyModel.contentRemove = self.contentRemove copyModel.contentTagReplace = self.contentTagReplace copyModel.content = self.content copyModel.chapterUrl = self.chapterUrl copyModel.chapterName = self.chapterName copyModel.chapters = self.chapters copyModel.detailBookIcon = self.detailBookIcon copyModel.detailChaptersUrl = self.detailChaptersUrl copyModel.bookLastChapterName = self.bookLastChapterName copyModel.bookUpdateTime = self.bookUpdateTime copyModel.bookUrl = self.bookUrl copyModel.bookIcon = self.bookIcon copyModel.bookDesc = self.bookDesc copyModel.bookCategory = self.bookCategory copyModel.bookAuthor = self.bookAuthor copyModel.bookName = self.bookName copyModel.books = self.books copyModel.chaptersReverse = self.chaptersReverse copyModel.chaptersModel = self.chaptersModel copyModel.detailBookDesc = self.detailBookDesc copyModel.bookType = self.bookType copyModel.update = self.update copyModel.latestChapterName = self.latestChapterName return copyModel } func copy(with zone: NSZone? = nil) -> Any { let copyModel = ZSAikanParserModel() copyModel.errDate = self.errDate copyModel.searchUrl = self.searchUrl copyModel.name = self.name copyModel.type = self.type copyModel.enabled = self.enabled copyModel.checked = self.checked copyModel.searchEncoding = self.searchEncoding copyModel.host = self.host copyModel.contentReplace = self.contentReplace copyModel.contentRemove = self.contentRemove copyModel.contentTagReplace = self.contentTagReplace copyModel.content = self.content copyModel.chapterUrl = self.chapterUrl copyModel.chapterName = self.chapterName copyModel.chapters = self.chapters copyModel.detailBookIcon = self.detailBookIcon copyModel.detailChaptersUrl = self.detailChaptersUrl copyModel.bookLastChapterName = self.bookLastChapterName copyModel.bookUpdateTime = self.bookUpdateTime copyModel.bookUrl = self.bookUrl copyModel.bookIcon = self.bookIcon copyModel.bookDesc = self.bookDesc copyModel.bookCategory = self.bookCategory copyModel.bookAuthor = self.bookAuthor copyModel.bookName = self.bookName copyModel.books = self.books copyModel.chaptersReverse = self.chaptersReverse copyModel.chaptersModel = self.chaptersModel copyModel.detailBookDesc = self.detailBookDesc copyModel.bookType = self.bookType copyModel.update = self.update copyModel.latestChapterName = self.latestChapterName return copyModel } func transformShelf() ->ZSShelfModel { let shelfModel = ZSShelfModel() shelfModel.icon = self.bookIcon.length > 0 ? self.bookIcon:self.detailBookIcon shelfModel.bookName = self.bookName shelfModel.author = self.bookAuthor shelfModel.bookUrl = self.bookUrl shelfModel.bookType = self.bookType shelfModel.update = self.update shelfModel.latestChapterName = self.latestChapterName return shelfModel } func updateShelf(shelf:ZSShelfModel) ->ZSShelfModel { // shelf.icon = self.bookIcon.length > 0 ? self.bookIcon:self.detailBookIcon // shelf.bookName = self.bookName // shelf.author = self.bookAuthor // shelf.bookUrl = self.bookUrl // shelf.bookType = self.bookType shelf.update = self.update shelf.latestChapterName = self.latestChapterName return shelf } /// 是否是可用的model func available() ->Bool { if bookAuthor.length == 0 && bookName.length == 0 || bookUrl.length == 0 { return false } return true } }
mit
35769f84e69f13ec3a8ea9c2d2c4db16
43.987069
123
0.681901
4.235795
false
true
false
false
open-telemetry/opentelemetry-swift
Sources/Importers/OpenTracingShim/TelemetryInfo.swift
1
659
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetryApi struct TelemetryInfo { var tracer: Tracer var baggageManager: BaggageManager var propagators: ContextPropagators var emptyBaggage: Baggage? var spanContextTable: SpanContextShimTable init(tracer: Tracer, baggageManager: BaggageManager, propagators: ContextPropagators) { self.tracer = tracer self.baggageManager = baggageManager self.propagators = propagators emptyBaggage = baggageManager.baggageBuilder().build() spanContextTable = SpanContextShimTable() } }
apache-2.0
56e722a85bc52b23842e8c023e68c318
27.652174
91
0.735964
4.393333
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Subscriptions/ServersListViewModel.swift
1
1321
// // ServersListViewModel.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 30/05/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation final class ServersListViewModel { internal let title = localized("servers.title") internal let addNewServer = localized("servers.add_new_server") internal let connectServerNavIdentifier = "ConnectServerNav" internal lazy var serversList: [[String: String]] = DatabaseManager.servers ?? [] internal var viewHeight: CGFloat { return CGFloat(min(serversList.count, 6)) * ServerCell.cellHeight } internal var initialTableViewPosition: CGFloat { return (-viewHeight) - 80 } internal func updateServersList() { serversList = DatabaseManager.servers ?? [] } internal func isSelectedServer(_ index: Int) -> Bool { return DatabaseManager.selectedIndex == index } internal func server(for index: Int) -> [String: String]? { if serversList.count <= index { return nil } return serversList[index] } internal func serverName(for index: Int) -> String { return server(for: index)?[ServerPersistKeys.serverName] ?? "" } internal var numberOfItems: Int { return serversList.count } }
mit
ef7aedd4bb3eb27eba2e768c6f4f8794
24.882353
85
0.661364
4.505119
false
false
false
false
manavgabhawala/swift
test/SILGen/without_actually_escaping.swift
1
787
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s var escapeHatch: Any = 0 // CHECK-LABEL: sil hidden @_T025without_actually_escaping9letEscapeyycyyc1f_tF func letEscape(f: () -> ()) -> () -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> ()): // TODO: Use a canary wrapper instead of just copying the nonescaping value // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ESCAPABLE_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[SUB_CLOSURE:%.*]] = function_ref @ // CHECK: [[RESULT:%.*]] = apply [[SUB_CLOSURE]]([[ESCAPABLE_COPY]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] return withoutActuallyEscaping(f) { return $0 } }
apache-2.0
7c5402cfe9ee1b2b825335501c04f8b9
45.294118
93
0.617535
3.406926
false
true
false
false
brave/browser-ios
ThirdParty/SQLiteSwift/Sources/SQLite/Extensions/FTS4.swift
14
11982
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // #if SWIFT_PACKAGE import SQLiteObjc #endif extension Module { public static func FTS4(_ column: Expressible, _ more: Expressible...) -> Module { return FTS4([column] + more) } public static func FTS4(_ columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module { return FTS4(FTS4Config().columns(columns).tokenizer(tokenizer)) } public static func FTS4(_ config: FTS4Config) -> Module { return Module(name: "fts4", arguments: config.arguments()) } } extension VirtualTable { /// Builds an expression appended with a `MATCH` query against the given /// pattern. /// /// let emails = VirtualTable("emails") /// /// emails.filter(emails.match("Hello")) /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: An expression appended with a `MATCH` query against the given /// pattern. public func match(_ pattern: String) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } public func match(_ pattern: Expression<String>) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } public func match(_ pattern: Expression<String?>) -> Expression<Bool?> { return "MATCH".infix(tableName(), pattern) } /// Builds a copy of the query with a `WHERE … MATCH` clause. /// /// let emails = VirtualTable("emails") /// /// emails.match("Hello") /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A query with the given `WHERE … MATCH` clause applied. public func match(_ pattern: String) -> QueryType { return filter(match(pattern)) } public func match(_ pattern: Expression<String>) -> QueryType { return filter(match(pattern)) } public func match(_ pattern: Expression<String?>) -> QueryType { return filter(match(pattern)) } } public struct Tokenizer { public static let Simple = Tokenizer("simple") public static let Porter = Tokenizer("porter") public static func Unicode61(removeDiacritics: Bool? = nil, tokenchars: Set<Character> = [], separators: Set<Character> = []) -> Tokenizer { var arguments = [String]() if let removeDiacritics = removeDiacritics { arguments.append("removeDiacritics=\(removeDiacritics ? 1 : 0)".quote()) } if !tokenchars.isEmpty { let joined = tokenchars.map { String($0) }.joined(separator: "") arguments.append("tokenchars=\(joined)".quote()) } if !separators.isEmpty { let joined = separators.map { String($0) }.joined(separator: "") arguments.append("separators=\(joined)".quote()) } return Tokenizer("unicode61", arguments) } public static func Custom(_ name: String) -> Tokenizer { return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) } public let name: String public let arguments: [String] fileprivate init(_ name: String, _ arguments: [String] = []) { self.name = name self.arguments = arguments } fileprivate static let moduleName = "SQLite.swift" } extension Tokenizer : CustomStringConvertible { public var description: String { return ([name] + arguments).joined(separator: " ") } } extension Connection { public func registerTokenizer(_ submoduleName: String, next: @escaping (String) -> (String, Range<String.Index>)?) throws { try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { ( input: UnsafePointer<Int8>, offset: UnsafeMutablePointer<Int32>, length: UnsafeMutablePointer<Int32>) in let string = String(cString: input) guard let (token, range) = next(string) else { return nil } let view:String.UTF8View = string.utf8 if let from = range.lowerBound.samePosition(in: view), let to = range.upperBound.samePosition(in: view) { offset.pointee += Int32(string[string.startIndex..<range.lowerBound].utf8.count) length.pointee = Int32(view.distance(from: from, to: to)) return token } else { return nil } }) } } /// Configuration options shared between the [FTS4](https://www.sqlite.org/fts3.html) and /// [FTS5](https://www.sqlite.org/fts5.html) extensions. open class FTSConfig { public enum ColumnOption { /// [The notindexed= option](https://www.sqlite.org/fts3.html#section_6_5) case unindexed } typealias ColumnDefinition = (Expressible, options: [ColumnOption]) var columnDefinitions = [ColumnDefinition]() var tokenizer: Tokenizer? var prefixes = [Int]() var externalContentSchema: SchemaType? var isContentless: Bool = false /// Adds a column definition @discardableResult open func column(_ column: Expressible, _ options: [ColumnOption] = []) -> Self { self.columnDefinitions.append((column, options)) return self } @discardableResult open func columns(_ columns: [Expressible]) -> Self { for column in columns { self.column(column) } return self } /// [Tokenizers](https://www.sqlite.org/fts3.html#tokenizer) open func tokenizer(_ tokenizer: Tokenizer?) -> Self { self.tokenizer = tokenizer return self } /// [The prefix= option](https://www.sqlite.org/fts3.html#section_6_6) open func prefix(_ prefix: [Int]) -> Self { self.prefixes += prefix return self } /// [The content= option](https://www.sqlite.org/fts3.html#section_6_2) open func externalContent(_ schema: SchemaType) -> Self { self.externalContentSchema = schema return self } /// [Contentless FTS4 Tables](https://www.sqlite.org/fts3.html#section_6_2_1) open func contentless() -> Self { self.isContentless = true return self } func formatColumnDefinitions() -> [Expressible] { return columnDefinitions.map { $0.0 } } func arguments() -> [Expressible] { return options().arguments } func options() -> Options { var options = Options() options.append(formatColumnDefinitions()) if let tokenizer = tokenizer { options.append("tokenize", value: Expression<Void>(literal: tokenizer.description)) } options.appendCommaSeparated("prefix", values:prefixes.sorted().map { String($0) }) if isContentless { options.append("content", value: "") } else if let externalContentSchema = externalContentSchema { options.append("content", value: externalContentSchema.tableName()) } return options } struct Options { var arguments = [Expressible]() @discardableResult mutating func append(_ columns: [Expressible]) -> Options { arguments.append(contentsOf: columns) return self } @discardableResult mutating func appendCommaSeparated(_ key: String, values: [String]) -> Options { if values.isEmpty { return self } else { return append(key, value: values.joined(separator: ",")) } } @discardableResult mutating func append(_ key: String, value: CustomStringConvertible?) -> Options { return append(key, value: value?.description) } @discardableResult mutating func append(_ key: String, value: String?) -> Options { return append(key, value: value.map { Expression<String>($0) }) } @discardableResult mutating func append(_ key: String, value: Expressible?) -> Options { if let value = value { arguments.append("=".join([Expression<Void>(literal: key), value])) } return self } } } /// Configuration for the [FTS4](https://www.sqlite.org/fts3.html) extension. open class FTS4Config : FTSConfig { /// [The matchinfo= option](https://www.sqlite.org/fts3.html#section_6_4) public enum MatchInfo : CustomStringConvertible { case fts3 public var description: String { return "fts3" } } /// [FTS4 options](https://www.sqlite.org/fts3.html#fts4_options) public enum Order : CustomStringConvertible { /// Data structures are optimized for returning results in ascending order by docid (default) case asc /// FTS4 stores its data in such a way as to optimize returning results in descending order by docid. case desc public var description: String { switch self { case .asc: return "asc" case .desc: return "desc" } } } var compressFunction: String? var uncompressFunction: String? var languageId: String? var matchInfo: MatchInfo? var order: Order? override public init() { } /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) open func compress(_ functionName: String) -> Self { self.compressFunction = functionName return self } /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) open func uncompress(_ functionName: String) -> Self { self.uncompressFunction = functionName return self } /// [The languageid= option](https://www.sqlite.org/fts3.html#section_6_3) open func languageId(_ columnName: String) -> Self { self.languageId = columnName return self } /// [The matchinfo= option](https://www.sqlite.org/fts3.html#section_6_4) open func matchInfo(_ matchInfo: MatchInfo) -> Self { self.matchInfo = matchInfo return self } /// [FTS4 options](https://www.sqlite.org/fts3.html#fts4_options) open func order(_ order: Order) -> Self { self.order = order return self } override func options() -> Options { var options = super.options() for (column, _) in (columnDefinitions.filter { $0.options.contains(.unindexed) }) { options.append("notindexed", value: column) } options.append("languageid", value: languageId) options.append("compress", value: compressFunction) options.append("uncompress", value: uncompressFunction) options.append("matchinfo", value: matchInfo) options.append("order", value: order) return options } }
mpl-2.0
3d0313bc7010070c5b483c5f2cbfef84
33.025568
144
0.627286
4.413043
false
false
false
false
tnantoka/GitHubAuth
Pod/Classes/SignInViewController.swift
1
3624
// // SignInViewController.swift // Pods // // Created by Tatsuya Tobioka on 11/14/15. // // import UIKit class SignInViewController: UIViewController, UIWebViewDelegate { let tokenUrl = NSURL(string: "https://github.com/login/oauth/access_token")! var callback: (String, NSError?) -> Void = { accessToken in } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = NSLocalizedString("Sign in", comment: "") guard let webview = view as? UIWebView else { return } webview.delegate = self let params = "client_id=\(GitHubAuth.shared.clientId)&scope=\(GitHubAuth.shared.scopes.joinWithSeparator(","))" let urlString = "https://github.com/login/oauth/authorize?\(params)" guard let url = NSURL(string: urlString) else { return } let req = NSURLRequest(URL: url) webview.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Actions @IBAction func cancelItemDidTap(sender: AnyObject) { callback("", GitHubAuthError.Canceled.error) } // MARK: - UIWebViewDelegate func webViewDidStartLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let url = request.URL where url.host == GitHubAuth.shared.callbackURL.host else { return true } guard let code = url.query?.componentsSeparatedByString("code=").last else { return true } let req = NSMutableURLRequest(URL: tokenUrl) req.HTTPMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Content-Type") req.addValue("application/json", forHTTPHeaderField: "Accept") let params = [ "client_id" : GitHubAuth.shared.clientId, "client_secret" : GitHubAuth.shared.clientSecret, "code" : code ] req.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: []) let task = NSURLSession.sharedSession().dataTaskWithRequest(req) { data, response, error in guard let data = data else { return self.callback("", error) } do { let content = try NSJSONSerialization.JSONObjectWithData(data, options: []) if let accessToken = content["access_token"] as? String { self.callback(accessToken, nil) } else { self.callback("", GitHubAuthError.NoAccessToken.error) } } catch let error as NSError { self.callback("", error) } } task.resume() UIApplication.sharedApplication().networkActivityIndicatorVisible = false return false } }
mit
02cc589d505015e841c1fc82c2eb8c67
35.24
137
0.635486
5.214388
false
false
false
false
alessandroorru/SimpleSwiftLogger
Log.swift
1
3868
public enum Log : Int { case Trace, Debug, Info, Warning, Error, None public typealias PrintFunction = (items: Any..., separator: String, terminator: String) -> Void public typealias SimpleFormatter = (object: Any) -> String public typealias ExtendedFormatter = (object: Any, file: String, line: Int, function: String) -> String public typealias ColorForLevel = (level: Log) -> UIColor public static var Level : Log = Log.Error public static var printFunction : PrintFunction = Swift.print public static var simpleFormatter : SimpleFormatter = Log.format public static var extendedFormatter : ExtendedFormatter = Log.format public static var colorForLevel : ColorForLevel = Log.colorForLevel public static var dateFormatter : NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .MediumStyle dateFormatter.locale = NSLocale.systemLocale() return dateFormatter }() public func print(object:Any, extended: Bool = true, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { guard rawValue >= Log.Level.rawValue else { return } let color = colorString() var formattedString : String switch extended { case false: formattedString = Log.simpleFormatter(object: object) case true: formattedString = Log.extendedFormatter(object: object, file: file, line: line, function: function) } if Log.colorsEnabled { formattedString = "\(Log.ESCAPE)\(color)\(formattedString)\(Log.RESET)" } Log.printFunction(items: formattedString, separator: ",", terminator: "\n") } // MARK: - Private private func colorString() -> String { let color = Log.colorForLevel(self) var r : CGFloat = 0 var g : CGFloat = 0 var b : CGFloat = 0 var a : CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) return String(format: "fg%.0f,%.0f,%.0f;", arguments: [round(r*255), round(g*255), round(b*255)]) } private static func colorForLevel(level: Log) -> UIColor { switch level { case .Trace: return UIColor.whiteColor() case .Debug: return UIColor.darkGrayColor() case .Info: return UIColor.yellowColor() case .Warning: return UIColor.orangeColor() case .Error: return UIColor.redColor() default: return UIColor.whiteColor() } } private static func format(object: Any) -> String { return "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" } private static func format(object: Any, file: String, line: Int, function: String) -> String { let file = file.componentsSeparatedByString("/").last! var logString = "\n\n[\(file):\(line)] \(function) | \n" logString += "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" logString += "\n" return logString } private static var colorsEnabled: Bool = { let xcodeColors = NSProcessInfo().environment["XcodeColors"] let xcodeColorsAvailable = xcodeColors != nil && xcodeColors == "YES" return xcodeColorsAvailable }() private static let ESCAPE = "\u{001b}[" private static let RESET_FG = "\(ESCAPE) fg;" // Clear any foreground color private static let RESET_BG = "\(ESCAPE) bg;" // Clear any background color private static let RESET = "\(ESCAPE);" // Clear any foreground or background color } infix operator => {} public func =>(lhs: Any, rhs: Log) { rhs.print(lhs, extended: false) }
mit
e147d44da64adabe5110c6d763fdb8e1
36.201923
138
0.609359
4.728606
false
false
false
false
petester42/SwiftCharts
SwiftCharts/Views/InfoBubble.swift
5
2267
// // InfoBubble.swift // SwiftCharts // // Created by ischuetz on 11/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit // Quick implementation of info bubble, for demonstration purposes // For serious usage you may consider using a library specialized in this e.g. CMPopTipView class InfoBubble: UIView { private let arrowWidth: CGFloat private let arrowHeight: CGFloat private let bgColor: UIColor private let arrowX: CGFloat init(frame: CGRect, arrowWidth: CGFloat, arrowHeight: CGFloat, bgColor: UIColor = UIColor.whiteColor(), arrowX: CGFloat) { self.arrowWidth = arrowWidth self.arrowHeight = arrowHeight self.bgColor = bgColor let arrowHalf = arrowWidth / 2 self.arrowX = max(arrowHalf, min(frame.size.width - arrowHalf, arrowX)) super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, self.bgColor.CGColor) CGContextSetStrokeColorWithColor(context, self.bgColor.CGColor) let rrect = CGRectInset(rect, 0, 20) let radius: CGFloat = 0 let minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect) let miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect) let outlinePath = CGPathCreateMutable() CGPathMoveToPoint(outlinePath, nil, minx, miny) CGPathAddLineToPoint(outlinePath, nil, maxx, miny) CGPathAddLineToPoint(outlinePath, nil, maxx, maxy) CGPathAddLineToPoint(outlinePath, nil, self.arrowX + self.arrowWidth / 2, maxy) CGPathAddLineToPoint(outlinePath, nil, self.arrowX, maxy + self.arrowHeight) CGPathAddLineToPoint(outlinePath, nil, self.arrowX - self.arrowWidth / 2, maxy) CGPathAddLineToPoint(outlinePath, nil, minx, maxy) CGPathCloseSubpath(outlinePath) CGContextAddPath(context, outlinePath) CGContextFillPath(context) } }
apache-2.0
ac3a76209fac24abed97ba23c3b6b8e0
36.163934
126
0.685929
4.635992
false
false
false
false
ziper1/swifter
Common/HttpHandlers.swift
1
2324
// // Handlers.swift // Swifter // Copyright (c) 2014 Damian Kołakowski. All rights reserved. // import Foundation class HttpHandlers { class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) { return { request in if let localPath = request.capturedUrlGroups.first { let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath) if let fileBody = NSData(contentsOfFile: filesPath) { return HttpResponse.RAW(200, fileBody) } } return HttpResponse.NotFound } } class func directoryBrowser(dir: String) -> ( HttpRequest -> HttpResponse ) { return { request in if let pathFromUrl = request.capturedUrlGroups.first { let filePath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(pathFromUrl) let fileManager = NSFileManager.defaultManager() var isDir: ObjCBool = false; if ( fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) ) { if ( isDir ) { do { let files = try fileManager.contentsOfDirectoryAtPath(filePath) var response = "<h3>\(filePath)</h3></br><table>" response += files.map {"<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}.joinWithSeparator("") response += "</table>" return HttpResponse.OK(.HTML(response)) } catch { return HttpResponse.NotFound } } else { if let fileBody = NSData(contentsOfFile: filePath) { return HttpResponse.RAW(200, fileBody) } } } } return HttpResponse.NotFound } } } private extension String { var stringByExpandingTildeInPath: String { return (self as NSString).stringByExpandingTildeInPath } func stringByAppendingPathComponent(str: String) -> String { return (self as NSString).stringByAppendingPathComponent(str) } }
bsd-3-clause
37c057d1ff3d41d2c3c5cc0e2050cdf0
37.733333
136
0.536375
5.8075
false
false
false
false
kellyi/LeapDemoSwift
LeapDemoSwift/LeapMotionManager.swift
1
2098
// // LeapMotionManager.swift // LeapDemoSwift // // Created by Kelly Innes on 10/24/15. // Copyright © 2015 Kelly Innes. All rights reserved. // import Foundation class LeapMotionManager: NSObject, LeapDelegate { static let sharedInstance = LeapMotionManager() let controller = LeapController() var rightHandPosition = LeapVector() var leftHandPosition = LeapVector() func run() { controller?.addDelegate(self) print("running") } // MARK: - LeapDelegate Methods func onInit(_ controller: LeapController!) { print("initialized") } func onConnect(_ controller: LeapController!) { print("connected") controller.enable(LEAP_GESTURE_TYPE_CIRCLE, enable: true) controller.enable(LEAP_GESTURE_TYPE_KEY_TAP, enable: true) controller.enable(LEAP_GESTURE_TYPE_SCREEN_TAP, enable: true) controller.enable(LEAP_GESTURE_TYPE_SWIPE, enable: true) } func onDisconnect(_ controller: LeapController!) { print("disconnected") } func onServiceConnect(_ controller: LeapController!) { print("service disconnected") } func onDeviceChange(_ controller: LeapController!) { print("device changed") } func onExit(_ controller: LeapController!) { print("exited") } func onFrame(_ controller: LeapController!) { let currentFrame = controller.frame(0) as LeapFrame let hands = currentFrame.hands as! [LeapHand] for hand in hands { if hand.isLeft { leftHandPosition = hand.palmPosition print("left hand position: \(leftHandPosition)") } else if hand.isRight { rightHandPosition = hand.palmPosition print("right hand position: \(rightHandPosition)") } } } func onFocusGained(_ controller: LeapController!) { print("focus gained") } func onFocusLost(_ controller: LeapController!) { print("focus lost") } }
mit
20d09cf6a6895e2043f1f9c2e0c1589e
26.592105
69
0.610396
4.244939
false
false
false
false
JadenGeller/Graham
Graham/Graham/Integer.swift
1
11785
// // Integer.swift // Graham // // Created by Jaden Geller on 10/26/15. // Copyright © 2015 Jaden Geller. All rights reserved. // typealias BigInt = Integer<Decimal> public struct Integer<B: Base> { public let digits: [Digit<B>] public let sign: Sign } extension Integer: IntegerLiteralConvertible, StringLiteralConvertible { private init<S: SequenceType where S.Generator.Element == Character>(characters: S, sign: Sign) { let digits = Array(characters.dropWhile{ $0 == "0" }.reverse().map(Digit<B>.init)) self.init(digits: digits, sign: digits.isEmpty ? .Positive : sign) // Zero is always positive } public init(stringLiteral value: String) { if value.characters.first! == "-" { self.init(characters: value.characters.dropFirst(), sign: .Negative) } else if value.characters.first! == "+" { self.init(characters: value.characters.dropFirst(), sign: .Positive) } else { self.init(characters: value.characters, sign: .Positive) } } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } public init(_ value: IntMax) { self.init(characters: String(abs(value)).characters, sign: value >= 0 ? Sign.Positive : Sign.Negative) } public init(integerLiteral value: IntMax) { self.init(value) } } extension Integer: CustomStringConvertible { public var description: String { if self == 0 { return "0" } else { return ((self < 0) ? "-" : "") + digits.reduce("", combine: { $1.description + $0 }) } } } extension Integer: Comparable { } func <=><B: Base>(lhs: Integer<B>, rhs: Integer<B>) -> ComparisonResult { let sign = lhs.sign <=> rhs.sign guard case .Equal = sign else { return sign } let negative = lhs.sign == .Negative // == rhs.sign let count = lhs.digits.count <=> rhs.digits.count guard case .Equal = count else { return negative ? count.negated : count } for (l, r) in zip(lhs.digits, rhs.digits).reverse() { let digit = l <=> r guard case .Equal = digit else { return negative ? digit.negated : digit } } return .Equal } public func ==<B: Base>(lhs: Integer<B>, rhs: Integer<B>) -> Bool { return (lhs <=> rhs) == .Equal } public func <<B: Base>(lhs: Integer<B>, rhs: Integer<B>) -> Bool { return (lhs <=> rhs) == .LessThan } // //struct Integer2<B : Base> : Printable, DebugPrintable, IntegerLiteralConvertible, Strideable, SignedNumberType, SequenceType, IntegerArithmeticType, Hashable, BidirectionalIndexType, StringLiteralConvertible { // // init(var decimalValue value: IntMax) { // let radix = IntMax(B.radix) // // let sign: IntegerSign = value < 0 ? .Negative : .Positive // value = abs(value) // // var num = "" // while value > 0 { // let digit = Digit<B>.representationForValue(UInt8(value % radix)) // num.insert(digit, atIndex: num.startIndex) // value = value / radix // } // self.init(string: num, sign: sign) // } // // // // // // // // private init(var backing: [Digit<B>], sign: IntegerSign) { // // Remove leading zeros // while let msb = backing.last where msb.isZero { backing.removeLast() } // // self.backing = backing // self.sign = sign // } // // func advancedBy(value: Integer<B>) -> Integer<B> { // return Integer.addWithOverflow(self, value).0 // } // // func distanceTo(other: Integer<B>) -> Integer<B> { // return Integer.subtractWithOverflow(other, self).0 // } // // func successor() -> Integer<B> { // return self.advancedBy(Integer(1)) // } // // func predecessor() -> Integer<B> { // return self.advancedBy(Integer(-1)) // } // // func shift(count: Integer<B>) -> Integer<B> { // if count.isPositive { return shiftRight(count) } // else if count.isNegative { return shiftLeft(count.negated) } // else { return self } // } // // func shiftRight(count: Integer<B>) -> Integer<B> { // assert(count > 0, "Cannot shift right by a non-positive count") // // var backing = self.backing // for _ in 1...count { // if backing.count == 0 { break } // backing.removeAtIndex(0) // } // return Integer(backing: backing, sign: sign) // } // // func shiftLeft(count: Integer<B>) -> Integer<B> { // assert(count > 0, "Cannot shift left by a non-positive count") // // var backing = self.backing // for _ in 1...count { // backing.insert(Digit.zero, atIndex: 0) // } // return Integer(backing: backing, sign: sign) // } // // var negated: Integer<B> { // get { // return Integer(backing: backing, sign: sign.opposite) // } // } // // var isZero: Bool { // get { // return backing.reduce(true, combine: { lhs, rhs in lhs && rhs.isZero }) // } // } // // var description: String { // get { // // } // } // // var debugDescription: String { // get { // return description // } // } // // var hashValue: Int { // get { // return reduce(self, 0, { total, digit in total &+ digit.hashValue }) // } // } // // func generate() -> GeneratorOf<Digit<B>> { // return GeneratorOf(backing.generate()) // } // // func toIntMax() -> IntMax { // fatalError("To implement") // } // // static func addWithOverflow(lhs: Integer<B>, _ rhs: Integer<B>) -> (Integer<B>, overflow: Bool) { // switch (lhs.isNegative, rhs.isNegative) { // case (true, true): return (addWithOverflow(rhs.negated, lhs.negated).0.negated, false) // case (false, true): return (subtractWithOverflow(lhs, rhs.negated).0, false) // case (true, false): return (subtractWithOverflow(rhs, lhs.negated).0, false) // default: // if rhs.isNegative { return (subtractWithOverflow(lhs, rhs.negated).0, false) } // // var backing = [Digit<B>]() // var carry = Digit<B>.zero // for (l, r) in weakZip(lhs, rhs) { // if l == nil && r == nil { break } // // let (digit, newCarry) = Digit.addWithDigitOverflow(l ?? Digit.zero, r ?? Digit.zero, carry: carry) // carry = newCarry // backing.append(digit) // } // if !carry.isZero { backing.append(carry) } // // return (Integer(backing: backing, sign: .Positive), false) // } // } // // static func subtractWithOverflow(lhs: Integer<B>, _ rhs: Integer<B>) -> (Integer<B>, overflow: Bool) { // if rhs.isNegative { return (addWithOverflow(lhs, rhs.negated).0, false) } // if lhs < rhs { return (subtractWithOverflow(rhs, lhs).0.negated, false) } // // var backing = [Digit<B>]() // var borrow = Digit<B>.zero // for (l, r) in weakZip(lhs, rhs) { // if l == nil && r == nil { break } // // let (digit, newBorrow) = Digit.subtractWithDigitUnderflow(l ?? Digit.zero, r ?? Digit.zero, borrow: borrow) // borrow = newBorrow // backing.append(digit) // } // // return (Integer(backing: backing, sign: .Positive), false) // } // // private static func multiply(lhs: Integer<B>, _ rhs: Digit<B>) -> Integer<B> { // // var backing = [Digit<B>]() // // var carry = Digit<B>.zero // for n in lhs { // // let (rawDigit, newCarryMutiplication) = Digit.multiplyWithDigitOverflow(n, rhs) // let (digit, newCarryAddition) = Digit.addWithDigitOverflow(rawDigit, carry, carry: 0) // // carry = newCarryMutiplication + newCarryAddition // backing.append(digit) // } // if !carry.isZero { backing.append(carry) } // // return Integer(backing: backing, sign: .Positive) // // } // // static func multiplyWithOverflow(lhs: Integer<B>, _ rhs: Integer<B>) -> (Integer<B>, overflow: Bool) { // var total: Integer = 0 // // for (index, digit) in enumerate(rhs) { // if digit == 0 { continue } // optimization // total += multiply(lhs, digit) << Integer(decimalValue: IntMax(index)) // } // // return (Integer(backing: total.backing, sign: IntegerSign.multiply(lhs.sign, rhs: rhs.sign)), false) // } // // static func slowDivide(var numerator: Integer<B>, _ denominator: Integer<B>) -> (quotient: Integer<B>, remainder: Integer<B>) { // var count: Integer<B> = 0 // // while !numerator.isNegative { // numerator -= denominator // count++ // } // // // We went over once it became negative, so backtrack // count-- // numerator += denominator // // return (count, numerator) // } // // static func longDivide(numerator: Integer<B>, _ denominator: Integer<B>) -> (quotient: Integer<B>, remainder: Integer<B>) { // var end = numerator.backing.endIndex // var start = end - denominator.backing.count // // while start >= numerator.backing.startIndex { // let range = start..<end // let smallNum = Integer(backing: Array(numerator.backing[range]), sign: .Positive) // let (quotient, remainder) = slowDivide(smallNum, denominator) // // if !quotient.isZero { // // We can divide! // // var numeratorBacking = numerator.backing // numeratorBacking[range] = remainder.backing[0..<(remainder.backing.count)] // let newNumerator = Integer(backing: numeratorBacking, sign: .Positive) // // let value = quotient << Integer(decimalValue: IntMax(start)) // if newNumerator.isZero { // return (value, 0) // } // else { // let (recursiveQuotient, recursiveRemainder) = longDivide(newNumerator, denominator) // return (value + recursiveQuotient, recursiveRemainder) // } // } // // start-- // } // // return (0, numerator) // } // // static func divideWithOverflow(lhs: Integer<B>, _ rhs: Integer<B>) -> (Integer<B>, overflow: Bool) { // if rhs.isZero { fatalError("division by zero") } // return (longDivide(lhs, rhs).quotient, false) // } // // static func remainderWithOverflow(lhs: Integer<B>, _ rhs: Integer<B>) -> (Integer<B>, overflow: Bool) { // if rhs.isZero { fatalError("division by zero") } // return (longDivide(lhs, rhs).remainder, false) // } // // func convertBase<T>() -> Integer<T> { // var num: Integer<T> = 0 // var muliplier: Integer<T> = 1 // var radix = Integer<T>(decimalValue: IntMax(B.radix)) // // for digit in backing { // num += Integer<T>(decimalValue: IntMax(digit.backing)) * muliplier // muliplier *= radix // } // // return num // } // //}
mit
4da3bd1e676cafa078554bd97446e965
33.459064
211
0.536151
3.73384
false
false
false
false
firebase/firebase-ios-sdk
FirebaseStorage/Sources/StorageMetadata.swift
1
8901
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /** * Class which represents the metadata on an object in Firebase Storage. This metadata is * returned on successful operations, and can be used to retrieve download URLs, content types, * and a Storage reference to the object in question. Full documentation can be found at the GCS * Objects#resource docs. * @see https://cloud.google.com/storage/docs/json_api/v1/objects#resource */ @objc(FIRStorageMetadata) open class StorageMetadata: NSObject { // MARK: - Public APIs /** * The name of the bucket containing this object. */ @objc public let bucket: String /** * Cache-Control directive for the object data. */ @objc public var cacheControl: String? /** * Content-Disposition of the object data. */ @objc public var contentDisposition: String? /** * Content-Encoding of the object data. */ @objc public var contentEncoding: String? /** * Content-Language of the object data. */ @objc public var contentLanguage: String? /** * Content-Type of the object data. */ @objc public var contentType: String? /** * MD5 hash of the data; encoded using base64. */ @objc public let md5Hash: String? /** * The content generation of this object. Used for object versioning. */ @objc public let generation: Int64 /** * User-provided metadata, in key/value pairs. */ @objc public var customMetadata: [String: String]? /** * The version of the metadata for this object at this generation. Used * for preconditions and for detecting changes in metadata. A metageneration number is only * meaningful in the context of a particular generation of a particular object. */ @objc public let metageneration: Int64 /** * The name of this object, in gs://bucket/path/to/object.txt, this is object.txt. */ @objc public internal(set) var name: String? /** * The full path of this object, in gs://bucket/path/to/object.txt, this is path/to/object.txt. */ @objc public internal(set) var path: String? /** * Content-Length of the data in bytes. */ @objc public let size: Int64 /** * The creation time of the object in RFC 3339 format. */ @objc public let timeCreated: Date? /** * The modification time of the object metadata in RFC 3339 format. */ @objc public let updated: Date? /** * Never used API */ @available(*, deprecated) @objc public let storageReference: StorageReference? = nil /** * Creates a Dictionary from the contents of the metadata. * @return A Dictionary that represents the contents of the metadata. */ @objc open func dictionaryRepresentation() -> [String: AnyHashable] { let stringFromDate = StorageMetadata.RFC3339StringFromDate return [ "bucket": bucket, "cacheControl": cacheControl, "contentDisposition": contentDisposition, "contentEncoding": contentEncoding, "contentLanguage": contentLanguage, "contentType": contentType, "md5Hash": md5Hash, "size": size != 0 ? size : nil, "generation": generation != 0 ? "\(generation)" : nil, "metageneration": metageneration != 0 ? "\(metageneration)" : nil, "timeCreated": timeCreated.map(stringFromDate), "updated": updated.map(stringFromDate), "name": path, ].compactMapValues { $0 }.merging(["metadata": customMetadata]) { current, _ in current } } /** * Determines if the current metadata represents a "file". */ @objc public var isFile: Bool { return fileType == .file } // TODO: Nothing in the implementation ever sets `.folder`. /** * Determines if the current metadata represents a "folder". */ @objc public var isFolder: Bool { return fileType == .folder } // MARK: - Public Initializers @objc override public convenience init() { self.init(dictionary: [:]) } /** * Creates an instance of StorageMetadata from the contents of a dictionary. * @return An instance of StorageMetadata that represents the contents of a dictionary. */ @objc public init(dictionary: [String: AnyHashable]) { initialMetadata = dictionary bucket = dictionary["bucket"] as? String ?? "" cacheControl = dictionary["cacheControl"] as? String ?? nil contentDisposition = dictionary["contentDisposition"] as? String ?? nil contentEncoding = dictionary["contentEncoding"] as? String ?? nil contentLanguage = dictionary["contentLanguage"] as? String ?? nil contentType = dictionary["contentType"] as? String ?? nil customMetadata = dictionary["metadata"] as? [String: String] ?? nil size = StorageMetadata.intFromDictionaryValue(dictionary["size"]) generation = StorageMetadata.intFromDictionaryValue(dictionary["generation"]) metageneration = StorageMetadata.intFromDictionaryValue(dictionary["metageneration"]) timeCreated = StorageMetadata.dateFromRFC3339String(dictionary["timeCreated"]) updated = StorageMetadata.dateFromRFC3339String(dictionary["updated"]) md5Hash = dictionary["md5Hash"] as? String ?? nil // GCS "name" is our path, our "name" is just the last path component of the path if let name = dictionary["name"] as? String { path = name self.name = (name as NSString).lastPathComponent } fileType = .unknown } // MARK: - NSObject overrides @objc override open func copy() -> Any { let clone = StorageMetadata(dictionary: dictionaryRepresentation()) clone.initialMetadata = initialMetadata return clone } @objc override open func isEqual(_ object: Any?) -> Bool { guard let ref = object as? StorageMetadata else { return false } return ref.dictionaryRepresentation() == dictionaryRepresentation() } @objc override public var hash: Int { return (dictionaryRepresentation() as NSDictionary).hash } @objc override public var description: String { return "\(type(of: self)) \(dictionaryRepresentation())" } // MARK: - Internal APIs internal func updatedMetadata() -> [String: AnyHashable] { return remove(matchingMetadata: dictionaryRepresentation(), oldMetadata: initialMetadata) } internal enum StorageMetadataType { case unknown case file case folder } internal var fileType: StorageMetadataType // MARK: - Private APIs and data private var initialMetadata: [String: AnyHashable] private static func intFromDictionaryValue(_ value: Any?) -> Int64 { if let value = value as? Int { return Int64(value) } if let value = value as? Int64 { return value } if let value = value as? String { return Int64(value) ?? 0 } return 0 } private static var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZZZ" dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) return dateFormatter }() private static func dateFromRFC3339String(_ value: Any?) -> Date? { if let stringValue = value as? String { return dateFormatter.date(from: stringValue) ?? nil } return nil } internal static func RFC3339StringFromDate(_ date: Date) -> String { return dateFormatter.string(from: date) } private func remove(matchingMetadata: [String: AnyHashable], oldMetadata: [String: AnyHashable]) -> [String: AnyHashable] { var newMetadata = matchingMetadata for (key, oldValue) in oldMetadata { guard let newValue = newMetadata[key] else { // Adds 'NSNull' for entries that only exist in oldMetadata. newMetadata[key] = NSNull() continue } if let oldString = oldValue as? String, let newString = newValue as? String { if oldString == newString { newMetadata[key] = nil } } else if let oldDictionary = oldValue as? [String: AnyHashable], let newDictionary = newValue as? [String: AnyHashable] { let outDictionary = remove(matchingMetadata: newDictionary, oldMetadata: oldDictionary) if outDictionary.count == 0 { newMetadata[key] = nil } else { newMetadata[key] = outDictionary } } } return newMetadata } }
apache-2.0
2e48acf64a9646b2267d374ea6588ccc
31.604396
97
0.681159
4.437188
false
false
false
false
ikesyo/swift-corelibs-foundation
TestFoundation/TestCalendar.swift
1
9882
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestCalendar: XCTestCase { static var allTests: [(String, (TestCalendar) -> () throws -> Void)] { return [ ("test_allCalendars", test_allCalendars), ("test_gettingDatesOnGregorianCalendar", test_gettingDatesOnGregorianCalendar ), ("test_gettingDatesOnHebrewCalendar", test_gettingDatesOnHebrewCalendar ), ("test_gettingDatesOnChineseCalendar", test_gettingDatesOnChineseCalendar), ("test_gettingDatesOnISO8601Calendar", test_gettingDatesOnISO8601Calendar), ("test_copy",test_copy), ("test_addingDates", test_addingDates), ("test_datesNotOnWeekend", test_datesNotOnWeekend), ("test_datesOnWeekend", test_datesOnWeekend), ("test_customMirror", test_customMirror), ("test_ampmSymbols", test_ampmSymbols), ("test_currentCalendarRRstability", test_currentCalendarRRstability), ] } func test_allCalendars() { for identifier in [ Calendar.Identifier.buddhist, Calendar.Identifier.chinese, Calendar.Identifier.coptic, Calendar.Identifier.ethiopicAmeteAlem, Calendar.Identifier.ethiopicAmeteMihret, Calendar.Identifier.gregorian, Calendar.Identifier.hebrew, Calendar.Identifier.indian, Calendar.Identifier.islamic, Calendar.Identifier.islamicCivil, Calendar.Identifier.islamicTabular, Calendar.Identifier.islamicUmmAlQura, Calendar.Identifier.iso8601, Calendar.Identifier.japanese, Calendar.Identifier.persian, Calendar.Identifier.republicOfChina ] { let calendar = Calendar(identifier: identifier) XCTAssertEqual(identifier,calendar.identifier) } } func test_gettingDatesOnGregorianCalendar() { let date = Date(timeIntervalSince1970: 1449332351) var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! let components = calendar.dateComponents([.year, .month, .day], from: date) XCTAssertEqual(components.year, 2015) XCTAssertEqual(components.month, 12) XCTAssertEqual(components.day, 5) // Test for problem reported by Malcolm Barclay via swift-corelibs-dev // https://lists.swift.org/pipermail/swift-corelibs-dev/Week-of-Mon-20161128/001031.html let fromDate = Date() let interval = 200 let toDate = Date(timeInterval: TimeInterval(interval), since: fromDate) let fromToComponents = calendar.dateComponents([.second], from: fromDate, to: toDate) XCTAssertEqual(fromToComponents.second, interval); // Issue with 32-bit CF calendar vector on Linux // Crashes on macOS 10.12.2/Foundation 1349.25 // (Possibly related) rdar://24384757 /* let interval2 = Int(INT32_MAX) + 1 let toDate2 = Date(timeInterval: TimeInterval(interval2), since: fromDate) let fromToComponents2 = calendar.dateComponents([.second], from: fromDate, to: toDate2) XCTAssertEqual(fromToComponents2.second, interval2); */ } func test_gettingDatesOnISO8601Calendar() { let date = Date(timeIntervalSince1970: 1449332351) var calendar = Calendar(identifier: .iso8601) calendar.timeZone = TimeZone(identifier: "UTC")! let components = calendar.dateComponents([.year, .month, .day], from: date) XCTAssertEqual(components.year, 2015) XCTAssertEqual(components.month, 12) XCTAssertEqual(components.day, 5) } func test_gettingDatesOnHebrewCalendar() { let date = Date(timeIntervalSince1970: 1552580351) var calendar = Calendar(identifier: .hebrew) calendar.timeZone = TimeZone(identifier: "UTC")! let components = calendar.dateComponents([.year, .month, .day], from: date) XCTAssertEqual(components.year, 5779) XCTAssertEqual(components.month, 7) XCTAssertEqual(components.day, 7) XCTAssertEqual(components.isLeapMonth, false) } func test_gettingDatesOnChineseCalendar() { let date = Date(timeIntervalSince1970: 1591460351.0) var calendar = Calendar(identifier: .chinese) calendar.timeZone = TimeZone(identifier: "UTC")! let components = calendar.dateComponents([.year, .month, .day], from: date) XCTAssertEqual(components.year, 37) XCTAssertEqual(components.month, 4) XCTAssertEqual(components.day, 15) XCTAssertEqual(components.isLeapMonth, true) } func test_ampmSymbols() { let calendar = Calendar(identifier: .gregorian) XCTAssertEqual(calendar.amSymbol, "AM") XCTAssertEqual(calendar.pmSymbol, "PM") } func test_currentCalendarRRstability() { var AMSymbols = [String]() for _ in 1...10 { let cal = Calendar.current AMSymbols.append(cal.amSymbol) } XCTAssertEqual(AMSymbols.count, 10, "Accessing current calendar should work over multiple callouts") } func test_copy() { var calendar = Calendar.current //Mutate below fields and check if change is being reflected in copy. calendar.firstWeekday = 2 calendar.minimumDaysInFirstWeek = 2 let copy = calendar XCTAssertTrue(copy == calendar) //verify firstWeekday and minimumDaysInFirstWeek of 'copy'. XCTAssertEqual(copy.firstWeekday, 2) XCTAssertEqual(copy.minimumDaysInFirstWeek, 2) } func test_addingDates() { let calendar = Calendar(identifier: .gregorian) let thisDay = calendar.date(from: DateComponents(year: 2016, month: 10, day: 4))! let diffComponents = DateComponents(day: 1) let dayAfter = calendar.date(byAdding: diffComponents, to: thisDay) let dayAfterComponents = calendar.dateComponents([.year, .month, .day], from: dayAfter!) XCTAssertEqual(dayAfterComponents.year, 2016) XCTAssertEqual(dayAfterComponents.month, 10) XCTAssertEqual(dayAfterComponents.day, 5) } func test_datesNotOnWeekend() { let calendar = Calendar(identifier: .gregorian) let mondayInDecember = calendar.date(from: DateComponents(year: 2018, month: 12, day: 10))! XCTAssertFalse(calendar.isDateInWeekend(mondayInDecember)) let tuesdayInNovember = calendar.date(from: DateComponents(year: 2017, month: 11, day: 14))! XCTAssertFalse(calendar.isDateInWeekend(tuesdayInNovember)) let wednesdayInFebruary = calendar.date(from: DateComponents(year: 2016, month: 2, day: 17))! XCTAssertFalse(calendar.isDateInWeekend(wednesdayInFebruary)) let thursdayInOctober = calendar.date(from: DateComponents(year: 2015, month: 10, day: 22))! XCTAssertFalse(calendar.isDateInWeekend(thursdayInOctober)) let fridayInSeptember = calendar.date(from: DateComponents(year: 2014, month: 9, day: 26))! XCTAssertFalse(calendar.isDateInWeekend(fridayInSeptember)) } func test_datesOnWeekend() { let calendar = Calendar(identifier: .gregorian) let saturdayInJanuary = calendar.date(from: DateComponents(year:2017, month: 1, day: 7))! XCTAssertTrue(calendar.isDateInWeekend(saturdayInJanuary)) let sundayInFebruary = calendar.date(from: DateComponents(year: 2016, month: 2, day: 14))! XCTAssertTrue(calendar.isDateInWeekend(sundayInFebruary)) } func test_customMirror() { let calendar = Calendar(identifier: .gregorian) let calendarMirror = calendar.customMirror XCTAssertEqual(calendar.identifier, calendarMirror.descendant("identifier") as? Calendar.Identifier) XCTAssertEqual(calendar.locale, calendarMirror.descendant("locale") as? Locale) XCTAssertEqual(calendar.timeZone, calendarMirror.descendant("timeZone") as? TimeZone) XCTAssertEqual(calendar.firstWeekday, calendarMirror.descendant("firstWeekday") as? Int) XCTAssertEqual(calendar.minimumDaysInFirstWeek, calendarMirror.descendant("minimumDaysInFirstWeek") as? Int) } } class TestNSDateComponents: XCTestCase { static var allTests: [(String, (TestNSDateComponents) -> () throws -> Void)] { return [ ("test_copyNSDateComponents", test_copyNSDateComponents), ] } func test_copyNSDateComponents() { let components = NSDateComponents() components.year = 1987 components.month = 3 components.day = 17 components.hour = 14 components.minute = 20 components.second = 0 let copy = components.copy(with: nil) as! NSDateComponents XCTAssertTrue(components.isEqual(copy)) XCTAssertTrue(components == copy) XCTAssertFalse(components === copy) XCTAssertEqual(copy.year, 1987) XCTAssertEqual(copy.month, 3) XCTAssertEqual(copy.day, 17) XCTAssertEqual(copy.isLeapMonth, false) //Mutate NSDateComponents and verify that it does not reflect in the copy components.hour = 12 XCTAssertEqual(components.hour, 12) XCTAssertEqual(copy.hour, 14) } }
apache-2.0
3f539d80e81ddcc80a82bfe045c9b262
41.230769
116
0.668083
4.716945
false
true
false
false
frootloops/swift
test/NameBinding/named_lazy_member_loading_objc_category.swift
3
975
// REQUIRES: objc_interop // REQUIRES: OS=macosx // RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post // // Prime module cache // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -typecheck %s // // Check that named-lazy-member-loading reduces the number of Decls deserialized // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -disable-named-lazy-member-loading -stats-output-dir %t/stats-pre %s // RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -stats-output-dir %t/stats-post %s // RUN: %utils/process-stats-dir.py --evaluate-delta 'NumTotalClangImportedEntities < -10' %t/stats-pre %t/stats-post import NamedLazyMembers public func foo(d: SimpleDoer) { let _ = d.categoricallyDoSomeWork() let _ = d.categoricallyDoSomeWork(withSpeed:10) let _ = d.categoricallyDoVeryImportantWork(speed:10, thoroughness:12) let _ = d.categoricallyDoSomeWorkWithSpeed(speed:10, levelOfAlacrity:12) }
apache-2.0
056081de72c9e98430e773f2ecbc3079
47.75
140
0.74359
3.085443
false
false
false
false
vlfm/VFTableViewAdapter
src/ViewController/ManualTableViewController.swift
1
2877
import UIKit open class ManualTableViewController: UIViewController { private var tableViewStyle: UITableViewStyle = .plain private var isWillAppearFirstTime = true public var clearsSelectionOnViewWillAppear: Bool = true public var tableView: UITableView! public let tableViewAdapter = TableViewAdapter() required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(style: UITableViewStyle) { tableViewStyle = style super.init(nibName: nil, bundle: nil) tableViewStyle = style } override open func viewDidLoad() { super.viewDidLoad() tableViewAdapter.target = self tableView = UITableView(frame: CGRect.zero, style: tableViewStyle) if shouldAddTableViewToViewHierarchy() { view.addSubview(tableView) } tableView.dataSource = tableViewAdapter tableView.delegate = tableViewAdapter tableView.estimatedRowHeight = 100 registerTableViewComponents() } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = view.bounds tableView.reloadData() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isWillAppearFirstTime { createTable() isWillAppearFirstTime = false } if clearsSelectionOnViewWillAppear { if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } } open func shouldAddTableViewToViewHierarchy() -> Bool { return true } open func registerTableViewComponents() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: TableRow.ReuseIdentifier.reuseIdentifier(forCellType: UITableViewCell.self)) } public final func createTable() { guard isViewLoaded else { return } tableViewAdapter.createTable {table in self.createTable(table: table) self.didCreateTable(table: table) } tableView.reloadData() } public final func updateTable() { guard isViewLoaded else { return } tableViewAdapter.updateTable {table in self.updateTable(table: table) self.didUpdateTable(table: table) } tableView.reloadData() } open func createTable(table: Table) { } open func updateTable(table: Table) { } open func didCreateTable(table: Table) { } open func didUpdateTable(table: Table) { } }
apache-2.0
8f4df73922199058797e7bdeae2a4120
26.141509
149
0.61001
5.895492
false
false
false
false
oz-swu/studyIOS
studyIOS/studyIOS/Classes/Tools/HttpTemplate.swift
1
814
// // HttpTemplate.swift // AlamofireTest // // Created by musou on 26/06/2017. // Copyright © 2017 musou. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class HttpTemplate { class func request (url: String, method: MethodType, parameters: [String : NSString]? = nil, callback: @escaping (_ result: AnyObject) -> ()) { let method = (method == .get) ? HTTPMethod.get : HTTPMethod.post; Alamofire.request(url, method: method, parameters: parameters).responseJSON { (response) in guard let resultData = response.result.value else { print(response.result.error!); return; } callback(resultData as AnyObject); } } }
mit
50ba25e7c079b337d4e0cc8f167fd16e
23.636364
147
0.587946
4.370968
false
false
false
false
joerocca/GitHawk
Pods/Apollo/Sources/Apollo/AsynchronousOperation.swift
3
852
import Foundation class AsynchronousOperation: Operation { @objc class func keyPathsForValuesAffectingIsExecuting() -> Set<String> { return ["state"] } @objc class func keyPathsForValuesAffectingIsFinished() -> Set<String> { return ["state"] } enum State { case initialized case ready case executing case finished } var state: State = .initialized { willSet { willChangeValue(forKey: "state") } didSet { didChangeValue(forKey: "state") } } override var isAsynchronous: Bool { return true } override var isReady: Bool { let ready = super.isReady if ready { state = .ready } return ready } override var isExecuting: Bool { return state == .executing } override var isFinished: Bool { return state == .finished } }
mit
f6782d27316c8412116a306e3aa4ca09
17.12766
75
0.627934
4.655738
false
false
false
false