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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
brenogazzola/CabCentral | CabCentralTests/MKCoordinateRegionTests.swift | 1 | 1657 | //
// MKCoordinateRegionTests.swift
// CabCentral
//
// Created by Breno Gazzola on 8/29/15.
// Copyright (c) 2015 Breno Gazzola. All rights reserved.
//
import XCTest
import MapKit
class MKCoordinateRegionTests: XCTestCase {
let regionRadius : CLLocationDistance = 2000
let latitude = -23.589548
let longitude = -46.673392
var region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(), 0.0, 0.0)
override func setUp() {
super.setUp()
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
region = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius, regionRadius)
}
override func tearDown() {
super.tearDown()
}
// Test if southwest is different from origin
func testSouthwest() {
let southwest = region.getSouthwesternEdge()
XCTAssertNotEqual(southwest.latitude, region.center.latitude)
XCTAssertNotEqual(southwest.longitude, region.center.longitude)
}
// Test if northeast is different from origin
func testNortheast() {
let northeast = region.getNortheasternEdge()
XCTAssertNotEqual(northeast.latitude, region.center.latitude)
XCTAssertNotEqual(northeast.longitude, region.center.longitude)
}
// Test if southwest is before (both ways) northeast
func testBoth(){
let southwest = region.getSouthwesternEdge()
let northeast = region.getNortheasternEdge()
XCTAssertTrue(southwest.latitude < northeast.latitude)
XCTAssertTrue(southwest.longitude < northeast.longitude)
}
}
| mit | da45dbe5a5da95659eca8cd621fdcc2a | 29.127273 | 91 | 0.688594 | 4.775216 | false | true | false | false |
li978406987/DayDayZB | DayDayZB/Classes/Home/ViewModel/ReccommendViewModel.swift | 1 | 4164 | //
// ReccommendViewModel.swift
// DayDayZB
//
// Created by 洛洛大人 on 16/11/10.
// Copyright © 2016年 洛洛大人. All rights reserved.
//
import UIKit
class ReccommendViewModel : BaseViewModel {
// Mark : - 懒加载属性
lazy var anchorAll : [AnchorGroup] = [AnchorGroup]()
lazy var cycleModels = [CycleModel]()
fileprivate lazy var bigDataGroup :AnchorGroup = AnchorGroup()
fileprivate lazy var prettyDataGroup :AnchorGroup = AnchorGroup()
}
// Mark: - 发送网络请求
extension ReccommendViewModel {
func requestData(finishCallBack : @escaping () -> ()) {
// 创建Group
let dGroup = DispatchGroup()
// 1.请求第一部分的推荐数据
dGroup.enter()
NetWorkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom?client_sys=ios") { (result) in
// 1.将result转成字典类型
guard let resultDic = result as? [String : Any] else { return }
// 2.根绝date该key 获取数据
guard let dataArray = resultDic["data"] as? [[String : Any]] else { return }
// 3.遍历字典 ,转成模型对象
// 3.1 设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "columnHotIcon"
// 3.2 获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict : dict)
self.bigDataGroup.anchors.append(anchor)
}
dGroup.leave()
}
// 2.请求第二部分的颜值数据
dGroup.enter()
NetWorkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=4&client_sys=ios&offset=0") { (result) in
// 1.将result转成字典类型
guard let resultDic = result as? [String : Any] else { return }
// 2.根绝date该key 获取数据
guard let dataArray = resultDic["data"] as? [[String : Any]] else { return }
// 3.遍历字典 ,转成模型对象
// 3.1 设置组的属性
self.prettyDataGroup.tag_name = "颜值"
self.prettyDataGroup.icon_name = "columnYanzhiIcon"
// 3.2 获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict : dict)
self.prettyDataGroup.anchors.append(anchor)
}
// 离开组
dGroup.leave()
}
// 3.请求后面部分的游戏数据
dGroup.enter()
loadAnchorData(URLString: "http://capi.douyucdn.cn/api/v1/getHotCate?aid=ios&client_sys=ios&time=1478688180&auth=3c532e2588a3570bfd59a2a41a1c279a") {
dGroup.leave()
}
// 6.所有的数据都请求到,之后排序
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyDataGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallBack()
}
}
// 请求无限轮播的数据
func requestCycleData(finishCallBack : @escaping () -> ()) {
NetWorkTools.requestData(type: .get, URLString: "http://capi.douyucdn.cn/api/v1/slide/6?version=2.401&client_sys=ios") { (result) in
// 1.将result转成字典类型
guard let resultDic = result as? [String : Any] else { return }
// 2.根绝date该key 获取数据
guard let dataArray = resultDic["data"] as? [[String : Any]] else { return }
// 3.遍历字典 ,转成模型对象
// 3.2 获取主播数据
for dict in dataArray {
self.cycleModels.append(CycleModel(dict : dict as! [String : NSObject]))
}
finishCallBack()
}
}
}
| mit | 3f6254f5dae70117d63deea43d1e28e1 | 29.087302 | 157 | 0.523345 | 4.40302 | false | false | false | false |
Aevit/SCScreenshot | SCScreenshot/SCScreenshot/Tools/SCPhotoTool/SCPhotoTool.swift | 1 | 6520 | //
// SCPhotoTool.swift
// SCScreenshot
//
// Created by Aevit on 15/8/31.
// Copyright (c) 2015年 Aevit. All rights reserved.
//
import UIKit
import Photos
public class SCPhotoTool: NSObject {
public class func createCollectionWithTitle(collectionTitle: String!, didGetCollectionBlock: ((assetCollection: PHAssetCollection) -> Void)?) {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", collectionTitle)
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
// var collectionFound = false
if let _: AnyObject = collection.firstObject {
// collectionFound = true
let aAssetCollection = collection.firstObject as! PHAssetCollection
if let block = didGetCollectionBlock {
block(assetCollection: aAssetCollection)
}
} else {
var assetCollectionPlaceholder: PHObjectPlaceholder!
// PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
let createAlbumRequest: PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(collectionTitle)
assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { (success, error) -> Void in
if (success) {
// collectionFound = true
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([assetCollectionPlaceholder.localIdentifier], options: nil)
let aAssetCollection = collectionFetchResult.firstObject as! PHAssetCollection
if let block = didGetCollectionBlock {
block(assetCollection: aAssetCollection)
}
}
})
}
}
/**
fetch results from photos
- parameter aAssetCollectionTitle: collection title, if it is nil, then will fetch from the camera roll, or will fetch from the collection
- parameter fetchOptions: fetchOption
- returns: fetchResults or nil
*/
public class func fetchResultWithAssetCollectionTitle(aAssetCollectionTitle: String!, fetchOptions: PHFetchOptions?) -> PHFetchResult? {
// // what predicate can add, you can see the class: PHAsset, here is just the example
// let fetchOptions = PHFetchOptions()
// fetchOptions.predicate = NSPredicate(format: "favorite == %@", false)
// fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)]
if (aAssetCollectionTitle == nil) {
// get from the camera roll
return PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
}
let collection: PHAssetCollection? = getAssetCollectionWithTitle(aAssetCollectionTitle)
if (collection == nil) {
return nil
}
// get from the collection
return PHAsset.fetchAssetsInAssetCollection(collection!, options: fetchOptions)
}
public class func requestAImage(aAsset: PHAsset?, size: CGSize, didRequestAImage: ((UIImage!, [NSObject : AnyObject]!) -> Void)?) {
if aAsset == nil {
return
}
var imgSize = size
if CGSizeEqualToSize(imgSize, CGSizeZero) {
imgSize = PHImageManagerMaximumSize
}
PHImageManager.defaultManager().requestImageForAsset(aAsset!, targetSize: imgSize, contentMode: PHImageContentMode.AspectFill, options: nil, resultHandler: { (rsImage, rsInfo) -> Void in
// do with the aImage: UIImage, and you can get more information about "info"
if let block = didRequestAImage {
block(rsImage, rsInfo)
}
})
}
public class func addImage(aImage: UIImage!, aAssetCollection: PHAssetCollection?, aFetchResult: PHFetchResult?, didAddImageBlock: (((Bool, NSError!) -> Void)!)) {
if (aImage == nil) {
return
}
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
// if aAssetCollection == nil, only save to camera roll
let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(aImage)
if (aAssetCollection != nil) {
let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
let collectionChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: aAssetCollection!, assets: aFetchResult!)
collectionChangeRequest!.addAssets([assetPlaceholder!])
}
}, completionHandler: { (success, error) -> Void in
if (didAddImageBlock != nil) {
didAddImageBlock(success, error)
}
})
}
public class func getAssetCollectionWithTitle(assetCollectionTitle: String!) -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", assetCollectionTitle)
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
let aAssetCollection = collection.firstObject as? PHAssetCollection
return aAssetCollection
}
return nil
// let collectionRs: PHFetchResult = PHCollection.fetchTopLevelUserCollectionsWithOptions(nil)
//
// var albumId: String = ""
// collectionRs.enumerateObjectsUsingBlock({(obj: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
// let aCollection: PHAssetCollection = obj as! PHAssetCollection
// if aCollection.localizedTitle == self.screenshotAlbumName {
// albumId = aCollection.localIdentifier
// NSUserDefaults.standardUserDefaults().setObject(albumId, forKey: self.screenshotAlbumIdKey)
// stop.initialize(true)
// }
// })
//
// return albumId
}
}
| mit | 42b26d83f4a665e8f9d2f4de48abc379 | 44.263889 | 194 | 0.631789 | 5.809269 | false | false | false | false |
space-app-challenge-london/iOS-client | Pods/AEXML/Sources/Options.swift | 4 | 1654 | import Foundation
/// Options used in `AEXMLDocument`
public struct AEXMLOptions {
/// Values used in XML Document header
public struct DocumentHeader {
/// Version value for XML Document header (defaults to 1.0).
public var version = 1.0
/// Encoding value for XML Document header (defaults to "utf-8").
public var encoding = "utf-8"
/// Standalone value for XML Document header (defaults to "no").
public var standalone = "no"
/// XML Document header
public var xmlString: String {
return "<?xml version=\"\(version)\" encoding=\"\(encoding)\" standalone=\"\(standalone)\"?>"
}
}
/// Settings used by `Foundation.XMLParser`
public struct ParserSettings {
/// Parser reports the namespaces and qualified names of elements. (defaults to `false`)
public var shouldProcessNamespaces = false
/// Parser reports the prefixes indicating the scope of namespace declarations. (defaults to `false`)
public var shouldReportNamespacePrefixes = false
/// Parser reports declarations of external entities. (defaults to `false`)
public var shouldResolveExternalEntities = false
}
/// Values used in XML Document header (defaults to `DocumentHeader()`)
public var documentHeader = DocumentHeader()
/// Settings used by `Foundation.XMLParser` (defaults to `ParserSettings()`)
public var parserSettings = ParserSettings()
/// Designated initializer - Creates and returns default `AEXMLOptions`.
public init() {}
}
| mit | dee4206cd6b77a58b0456e1b59bc8744 | 36.590909 | 109 | 0.639661 | 5.458746 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Library/RecentlyClosedTabsPanel.swift | 1 | 5796 | /* 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 Storage
import XCGLogger
private let log = Logger.browserLogger
private struct RecentlyClosedPanelUX {
static let IconSize = CGSize(width: 23, height: 23)
static let IconBorderColor = UIColor.Photon.Grey30
static let IconBorderWidth: CGFloat = 0.5
}
class RecentlyClosedTabsPanel: UIViewController, LibraryPanel {
weak var libraryPanelDelegate: LibraryPanelDelegate?
let profile: Profile
fileprivate lazy var tableViewController = RecentlyClosedTabsPanelSiteTableViewController(profile: profile)
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.theme.tableView.headerBackground
tableViewController.libraryPanelDelegate = libraryPanelDelegate
tableViewController.recentlyClosedTabsPanel = self
self.addChild(tableViewController)
tableViewController.didMove(toParent: self)
self.view.addSubview(tableViewController.view)
tableViewController.view.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
}
}
class RecentlyClosedTabsPanelSiteTableViewController: SiteTableViewController {
weak var libraryPanelDelegate: LibraryPanelDelegate?
var recentlyClosedTabs: [ClosedTab] = []
weak var recentlyClosedTabsPanel: RecentlyClosedTabsPanel?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(RecentlyClosedTabsPanelSiteTableViewController.longPress))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "Recently Closed Tabs List"
self.recentlyClosedTabs = profile.recentlyClosedTabs.tabs
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == .began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
presentContextMenu(for: indexPath)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
guard let twoLineCell = cell as? TwoLineTableViewCell else {
return cell
}
let tab = recentlyClosedTabs[indexPath.row]
let displayURL = tab.url.displayURL ?? tab.url
twoLineCell.setLines(tab.title, detailText: displayURL.absoluteDisplayString)
let site: Favicon? = (tab.faviconURL != nil) ? Favicon(url: tab.faviconURL!) : nil
cell.imageView!.layer.borderColor = RecentlyClosedPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = RecentlyClosedPanelUX.IconBorderWidth
cell.imageView?.setIcon(site, forURL: displayURL, completed: { (color, url) in
if url == displayURL {
cell.imageView?.image = cell.imageView?.image?.createScaled(RecentlyClosedPanelUX.IconSize)
cell.imageView?.contentMode = .center
cell.imageView?.backgroundColor = color
}
})
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let libraryPanelDelegate = libraryPanelDelegate else {
log.warning("No site or no URL when selecting row.")
return
}
let visitType = VisitType.typed // Means History, too.
libraryPanelDelegate.libraryPanel(didSelectURL: recentlyClosedTabs[indexPath.row].url, visitType: visitType)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
// Functions that deal with showing header rows.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.recentlyClosedTabs.count
}
}
extension RecentlyClosedTabsPanelSiteTableViewController: LibraryPanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
let closedTab = recentlyClosedTabs[indexPath.row]
let site: Site
if let title = closedTab.title {
site = Site(url: String(describing: closedTab.url), title: title)
} else {
site = Site(url: String(describing: closedTab.url), title: "")
}
return site
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
return getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate)
}
}
extension RecentlyClosedTabsPanel: Themeable {
func applyTheme() {
tableViewController.tableView.reloadData()
}
}
| mpl-2.0 | 0f4cbea3b0f6ea198724cae5eb0acfd2 | 38.428571 | 134 | 0.706694 | 5.322314 | false | false | false | false |
per-dalsgaard/20-apps-in-20-weeks | App 15 - PokeFinder/PokeFinder/Pokemon.swift | 1 | 850 | //
// Pokemon.swift
// PokeFinder
//
// Created by Per Kristensen on 22/04/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import Foundation
class Pokemon {
var _number: Int!
var name: String {
get {
return POKEMONS[_number - 1].capitalized
}
}
var number: Int {
get {
if _number == nil {
return 0
}
return _number
}
set {
_number = newValue
}
}
static func loadPokemons() -> [Pokemon] {
var pokemons = [Pokemon]()
for (index, _) in POKEMONS.enumerated() {
let pokemon = Pokemon()
pokemon.number = index + 1
pokemons.append(pokemon)
}
return pokemons
}
}
| mit | 30348b9c78f0e6016a1b1957638b447c | 17.866667 | 56 | 0.46172 | 4.421875 | false | false | false | false |
zon/that-bus | ios/That Bus/RegisterController.swift | 1 | 1326 | import Foundation
import UIKit
class RegisterController : UIViewController, UITextFieldDelegate {
let layout = RegisterLayout()
required init() {
super.init(nibName: nil, bundle: nil)
title = "Register"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = layout
layout.email.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
layout.setInsets(top: navigationController?.navigationBar.frame.maxY, bottom: tabBarController?.tabBar.frame.height)
}
override func viewDidAppear(_ animated: Bool) {
if let item = navigationController?.navigationBar.topItem {
item.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTouch))
}
layout.email.becomeFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
resignFirstResponder()
nextTouch()
return false
}
func backTouch() {
dismiss(animated: true, completion: nil)
}
func nextTouch() {
// let quantity = TicketQuantity(name: "Ride Tickets", price: 10, count: 10)
}
}
| gpl-3.0 | 4ef64c7a0e03049e9079376b7cf111ea | 27.212766 | 127 | 0.625943 | 4.929368 | false | false | false | false |
giangbvnbgit128/AnViet | Pods/DKImagePickerController/DKImagePickerController/View/DKAssetGroupListVC.swift | 3 | 8268 | //
// DKAssetGroupListVC.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/8.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import Photos
let DKImageGroupCellIdentifier = "DKImageGroupCellIdentifier"
class DKAssetGroupCell: UITableViewCell {
class DKAssetGroupSeparator: UIView {
override var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
if newValue != UIColor.clear {
super.backgroundColor = newValue
}
}
}
}
fileprivate let thumbnailImageView: UIImageView = {
let thumbnailImageView = UIImageView()
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.clipsToBounds = true
return thumbnailImageView
}()
var groupNameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 13)
return label
}()
var totalCountLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.textColor = UIColor.gray
return label
}()
var customSelectedBackgroundView: UIView = {
let selectedBackgroundView = UIView()
let selectedFlag = UIImageView(image: DKImageResource.blueTickImage())
selectedFlag.frame = CGRect(x: selectedBackgroundView.bounds.width - selectedFlag.bounds.width - 20,
y: (selectedBackgroundView.bounds.width - selectedFlag.bounds.width) / 2,
width: selectedFlag.bounds.width, height: selectedFlag.bounds.height)
selectedFlag.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin]
selectedBackgroundView.addSubview(selectedFlag)
return selectedBackgroundView
}()
lazy var customSeparator: DKAssetGroupSeparator = {
let separator = DKAssetGroupSeparator(frame: CGRect(x: 10, y: self.bounds.height - 1, width: self.bounds.width, height: 0.5))
separator.backgroundColor = UIColor.lightGray
separator.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
return separator
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectedBackgroundView = self.customSelectedBackgroundView
self.contentView.addSubview(thumbnailImageView)
self.contentView.addSubview(groupNameLabel)
self.contentView.addSubview(totalCountLabel)
self.addSubview(self.customSeparator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let imageViewY = CGFloat(10)
let imageViewHeight = self.contentView.bounds.height - 2 * imageViewY
self.thumbnailImageView.frame = CGRect(x: imageViewY, y: imageViewY,
width: imageViewHeight, height: imageViewHeight)
self.groupNameLabel.frame = CGRect(x: self.thumbnailImageView.frame.maxX + 10, y: self.thumbnailImageView.frame.minY + 5,
width: 200, height: 20)
self.totalCountLabel.frame = CGRect(x: self.groupNameLabel.frame.minX, y: self.thumbnailImageView.frame.maxY - 20, width: 200, height: 20)
}
}
class DKAssetGroupListVC: UITableViewController, DKGroupDataManagerObserver {
convenience init(selectedGroupDidChangeBlock: @escaping (_ groupId: String?) -> (), defaultAssetGroup: PHAssetCollectionSubtype?) {
self.init(style: .plain)
self.defaultAssetGroup = defaultAssetGroup
self.selectedGroupDidChangeBlock = selectedGroupDidChangeBlock
}
fileprivate var groups: [String]?
fileprivate var selectedGroup: String?
fileprivate var defaultAssetGroup: PHAssetCollectionSubtype?
fileprivate var selectedGroupDidChangeBlock:((_ group: String?)->())?
fileprivate lazy var groupThumbnailRequestOptions: PHImageRequestOptions = {
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.resizeMode = .exact
return options
}()
override var preferredContentSize: CGSize {
get {
if let groups = self.groups {
return CGSize(width: UIViewNoIntrinsicMetric, height: CGFloat(groups.count) * self.tableView.rowHeight)
} else {
return super.preferredContentSize
}
}
set {
super.preferredContentSize = newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(DKAssetGroupCell.self, forCellReuseIdentifier: DKImageGroupCellIdentifier)
self.tableView.rowHeight = 70
self.tableView.separatorStyle = .none
self.clearsSelectionOnViewWillAppear = false
getImageManager().groupDataManager.addObserver(self)
}
internal func loadGroups() {
getImageManager().groupDataManager.fetchGroups { [weak self] groups, error in
guard let strongSelf = self else { return }
if error == nil {
strongSelf.groups = groups!
strongSelf.selectedGroup = strongSelf.defaultAssetGroupOfAppropriate()
if let selectedGroup = strongSelf.selectedGroup {
strongSelf.tableView.selectRow(at: IndexPath(row: groups!.index(of: selectedGroup)!, section: 0),
animated: false,
scrollPosition: .none)
}
strongSelf.selectedGroupDidChangeBlock?(strongSelf.selectedGroup)
}
}
}
fileprivate func defaultAssetGroupOfAppropriate() -> String? {
if let groups = self.groups {
if let defaultAssetGroup = self.defaultAssetGroup {
for groupId in groups {
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(groupId)
if defaultAssetGroup == group.originalCollection.assetCollectionSubtype {
return groupId
}
}
}
return self.groups!.first
}
return nil
}
// MARK: - UITableViewDelegate, UITableViewDataSource methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groups?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DKImageGroupCellIdentifier, for: indexPath) as! DKAssetGroupCell
let assetGroup = getImageManager().groupDataManager.fetchGroupWithGroupId(groups![indexPath.row])
cell.groupNameLabel.text = assetGroup.groupName
let tag = indexPath.row + 1
cell.tag = tag
if assetGroup.totalCount == 0 {
cell.thumbnailImageView.image = DKImageResource.emptyAlbumIcon()
} else {
getImageManager().groupDataManager.fetchGroupThumbnailForGroup(assetGroup.groupId,
size: CGSize(width: tableView.rowHeight, height: tableView.rowHeight).toPixel(),
options: self.groupThumbnailRequestOptions) { image, info in
if cell.tag == tag {
cell.thumbnailImageView.image = image
}
}
}
cell.totalCountLabel.text = String(assetGroup.totalCount)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
DKPopoverViewController.dismissPopoverViewController()
self.selectedGroup = self.groups![indexPath.row]
selectedGroupDidChangeBlock?(self.selectedGroup)
}
// MARK: - DKGroupDataManagerObserver methods
func groupDidUpdate(_ groupId: String) {
let indexPath = IndexPath(row: self.groups!.index(of: groupId)!, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .none)
}
func groupDidRemove(_ groupId: String) {
let indexPath = IndexPath(row: self.groups!.index(of: groupId)!, section: 0)
self.groups?.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .none)
if self.selectedGroup == groupId {
self.selectedGroup = self.groups?.first
selectedGroupDidChangeBlock?(self.selectedGroup)
self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .none)
}
}
}
| apache-2.0 | a5dfc3f10c9a6a37a92c79ce6e525d58 | 33.016461 | 146 | 0.688846 | 4.803021 | false | false | false | false |
SwiftGen/SwiftGen | Sources/SwiftGenKit/Parsers/Fonts/Font.swift | 1 | 905 | //
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
extension Fonts {
struct Font {
let filePath: String
let familyName: String
let style: String
let postScriptName: String
init(filePath: String, familyName: String, style: String, postScriptName: String) {
self.filePath = filePath
self.familyName = familyName
self.style = style
self.postScriptName = postScriptName
}
}
}
// Right now the postScriptName is the value of the font we are looking up, so we do
// equatable comparisons on that. If we ever care about the familyName or style it can be added
extension Fonts.Font: Equatable {
static func == (lhs: Fonts.Font, rhs: Fonts.Font) -> Bool {
lhs.postScriptName == rhs.postScriptName
}
}
extension Fonts.Font: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(postScriptName)
}
}
| mit | f972d9792682d370f00a54f505e218ff | 23.432432 | 95 | 0.696903 | 4.109091 | false | false | false | false |
nathawes/swift | validation-test/Reflection/reflect_Enum_TwoCaseNoPayload.swift | 19 | 11549 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_TwoCaseNoPayload
// RUN: %target-codesign %t/reflect_Enum_TwoCaseNoPayload
// RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_TwoCaseNoPayload | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: reflection_test_support
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
struct Marker {
let value = 1
}
enum TwoCaseNoPayloadEnum {
case preferred
case other
}
class ClassWithTwoCaseNoPayloadEnum {
var e1: TwoCaseNoPayloadEnum?
var e2: TwoCaseNoPayloadEnum = .preferred
var e3: TwoCaseNoPayloadEnum = .other
var e4: TwoCaseNoPayloadEnum? = .preferred
var e5: TwoCaseNoPayloadEnum? = .other
let marker = Marker()
}
reflect(object: ClassWithTwoCaseNoPayloadEnum())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Enum_TwoCaseNoPayload.ClassWithTwoCaseNoPayloadEnum)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=32 alignment=8 stride=32 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=e1 offset=16
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e2 offset=17
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (field name=e3 offset=18
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (field name=e4 offset=19
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e5 offset=20
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=marker offset=24
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Enum_TwoCaseNoPayload.ClassWithTwoCaseNoPayloadEnum)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=e1 offset=8
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e2 offset=9
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (field name=e3 offset=10
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (field name=e4 offset=11
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e5 offset=12
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=marker offset=16
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))))
reflect(enum: TwoCaseNoPayloadEnum.preferred)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-64: Type info:
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1))
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=preferred index=0)
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-32: Type info:
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1))
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=preferred index=0)
reflect(enum: TwoCaseNoPayloadEnum.other)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-64: Type info:
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1))
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=other index=1)
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-32: Type info:
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1))
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=other index=1)
reflect(enum: Optional<TwoCaseNoPayloadEnum>.some(.other))
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-64: (case name=some index=0
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (case name=none index=1))
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=some index=0
// CHECK-64: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-64: )
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32: (case name=some index=0
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (case name=none index=1))
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=some index=0
// CHECK-32: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum)
// CHECK-32: )
reflect(enum: Optional<TwoCaseNoPayloadEnum>.none)
// CHECK-64: Reflecting an enum.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum))
// CHECK-64: Type info:
// CHECK-64: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-64: (case name=some index=0
// CHECK-64: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-64: (case name=preferred index=0)
// CHECK-64: (case name=other index=1)))
// CHECK-64: (case name=none index=1))
// CHECK-64: Enum value:
// CHECK-64: (enum_value name=none index=1)
// CHECK-32: Reflecting an enum.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (enum reflect_Enum_TwoCaseNoPayload.TwoCaseNoPayloadEnum))
// CHECK-32: Type info:
// CHECK-32: (single_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=253 bitwise_takable=1
// CHECK-32: (case name=some index=0
// CHECK-32: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1
// CHECK-32: (case name=preferred index=0)
// CHECK-32: (case name=other index=1)))
// CHECK-32: (case name=none index=1))
// CHECK-32: Enum value:
// CHECK-32: (enum_value name=none index=1)
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 7d6be4ab3fd31a27ee220fee1c5cafa7 | 44.113281 | 135 | 0.692181 | 3.065021 | false | false | false | false |
kuangniaokuang/Cocktail-Pro | smartmixer/smartmixer/UserCenter/AboutViewPhone.swift | 1 | 6234 | //
// AboutViewPhone.swift
// smartmixer
//
// Created by 姚俊光 on 14-9-9.
// Copyright (c) 2014年 Smart Group. All rights reserved.
//
import UIKit
class AboutViewPhone: UITableViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate,UIAlertViewDelegate{
//头像图片
@IBOutlet var headImage:UIImageView!
//名字
@IBOutlet var userName:UILabel!
var delegate:NumberDelegate!
class func AboutViewPhoneInit()->AboutViewPhone{
var aboutview = UIStoryboard(name: "UserCenter"+deviceDefine, bundle: nil).instantiateViewControllerWithIdentifier("aboutView") as AboutViewPhone
return aboutview
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationItem.backBarButtonItem?.title = ""
headImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png")
userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
}
func gotoMark(){
UIApplication.sharedApplication().openURL(NSURL(string: itunesLink)!)
}
@IBAction func back(sender: UIBarButtonItem) {
self.navigationController?.popViewControllerAnimated(true)
self.navigationController?.setNavigationBarHidden(true, animated: true)
rootController.showOrhideToolbar(true)
}
//欢迎页面
var welcome:WelcomePlus!
//选取照片
var imagePicker:UIImagePickerController!
var popview:UIPopoverController!
var usernewName:String!
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(indexPath.section==0 && indexPath.row==0){//点击更换头像
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
imagePicker.allowsEditing = true
if(deviceDefine==""){
self.presentViewController(imagePicker, animated: true, completion: nil)
}else{
popview = UIPopoverController(contentViewController: imagePicker)
popview.presentPopoverFromRect(CGRect(x: 145, y: 90, width: 10, height: 10), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}else if(indexPath.section==0 && indexPath.row==1){//点击修改名字
if(osVersion<8){
var alert = UIAlertView(title: "编辑昵称", message: nil, delegate: self, cancelButtonTitle: "取消")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.textFieldAtIndex(0)?.text = self.userName.text
alert.addButtonWithTitle("确定")
alert.show()
}else{
var alert = UIAlertController(title: "编辑昵称", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler { (choiceNameTF) -> Void in
choiceNameTF.borderStyle = .None
choiceNameTF.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
choiceNameTF.placeholder = "输入你的昵称"
choiceNameTF.delegate = self
choiceNameTF.becomeFirstResponder()
}
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler:nil))
alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler:{ (action) -> Void in
NSUserDefaults.standardUserDefaults().setObject(self.usernewName, forKey: "UserName")
self.userName.text=self.usernewName
}
))
self.view.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
}else if(indexPath.row==2){
gotoMark()
}else if(indexPath.row==5){
welcome = WelcomePlus.WelcomePlusInit()
welcome.firstPop=false;
welcome.modalPresentationStyle = UIModalPresentationStyle.OverFullScreen
self.view.window?.rootViewController?.presentViewController(welcome, animated: true, completion: nil)
}else{
if(deviceDefine==""){
var aboutDetail = AboutDetail.AboutDetailInit()
aboutDetail.currentTag = indexPath.row
self.navigationController?.pushViewController(aboutDetail, animated: true)
}else if(self.delegate != nil){
self.delegate.NumberAction(self, num: indexPath.row)
}
}
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
var title = alertView.buttonTitleAtIndex(buttonIndex)
if(title=="确定"){
self.userName.text=alertView.textFieldAtIndex(0)?.text
NSUserDefaults.standardUserDefaults().setObject(self.userName.text, forKey: "UserName")
}
}
func textFieldDidEndEditing(textField: UITextField) {
usernewName = textField.text
}
//写入Document中
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var image = info["UIImagePickerControllerEditedImage"] as UIImage
headImage.image = image
var imageData = UIImagePNGRepresentation(image)
imageData.writeToFile(applicationDocumentsPath+"/myimage.png", atomically: false)
self.dismissViewControllerAnimated(true, completion: nil)
if(osVersion<8 && deviceDefine != ""){
popview.dismissPopoverAnimated(true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 | 39c9d7d2c54b18800f6d843c9954678c | 44.671642 | 182 | 0.657353 | 5.558583 | false | false | false | false |
cornerAnt/PilesSugar | PilesSugar/PilesSugar/Module/Explore/ExploreMain/Model/ExploreMainModel.swift | 1 | 1783 | //
// ExploreMainModel.swift
// PilesSugar
//
// Created by SoloKM on 16/1/24.
// Copyright © 2016年 SoloKM. All rights reserved.
//
import UIKit
import SwiftyJSON
class ExploreMainModel: NSObject {
var group_id: String!
var content_type: String!
var group_name: String!
var group_items: [Group_item]!
class func loadExploreMainModels(data:NSData) -> [ExploreMainModel]{
let json = JSON(data: data)
var exploreMainModels = [ExploreMainModel]()
for (_,subJson):(String, JSON) in json["data"]{
let exploreMainModel = ExploreMainModel()
exploreMainModel.group_id = subJson["group_id"].stringValue
exploreMainModel.content_type = subJson["content_type"].stringValue
exploreMainModel.group_name = subJson["group_name"].stringValue
exploreMainModel.group_items = [Group_item]()
for (_,subSubJson):(String, JSON) in subJson["group_items"]{
let group_item = Group_item()
group_item.name = subSubJson["name"].stringValue
group_item.icon_url = subSubJson["icon_url"].stringValue
group_item.target = subSubJson["target"].stringValue
exploreMainModel.group_items.append(group_item)
}
exploreMainModels.append(exploreMainModel)
}
return exploreMainModels
}
}
class Group_item: NSObject {
var name: String!
var icon_url: String!
var target: String!
}
| apache-2.0 | 31199902d0aef715dfa7cb26479a0a09 | 23.383562 | 79 | 0.530899 | 4.797844 | false | false | false | false |
dereknex/ios-charts | Charts/Classes/Highlight/HorizontalBarChartHighlighter.swift | 59 | 3587 | //
// HorizontalBarChartHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
internal class HorizontalBarChartHighlighter: BarChartHighlighter
{
internal override func getHighlight(#x: Double, y: Double) -> ChartHighlight?
{
var h = super.getHighlight(x: x, y: y)
if h === nil
{
return h
}
else
{
if let set = _chart?.data?.getDataSetByIndex(h!.dataSetIndex) as? BarChartDataSet
{
if set.isStacked
{
// create an array of the touch-point
var pt = CGPoint()
pt.x = CGFloat(y)
// take any transformer to determine the x-axis value
_chart?.getTransformer(set.axisDependency).pixelToValue(&pt)
return getStackedHighlight(old: h, set: set, xIndex: h!.xIndex, dataSetIndex: h!.dataSetIndex, yValue: Double(pt.x))
}
}
return h
}
}
internal override func getXIndex(x: Double) -> Int
{
if let barChartData = _chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
// create an array of the touch-point
var pt = CGPoint(x: 0.0, y: x)
// take any transformer to determine the x-axis value
_chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int(round(pt.y))
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var xIndex = Int(baseNoSpace) / setCount
let valCount = barChartData.xValCount
if xIndex < 0
{
xIndex = 0
}
else if xIndex >= valCount
{
xIndex = valCount - 1
}
return xIndex
}
}
else
{
return 0
}
}
/// Returns the base y-value to the corresponding x-touch value in pixels.
/// :param: y
/// :returns:
internal override func getBase(y: Double) -> Double
{
if let barChartData = _chart?.data as? BarChartData
{
// create an array of the touch-point
var pt = CGPoint()
pt.y = CGFloat(y)
// take any transformer to determine the x-axis value
_chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
let yVal = Double(pt.y)
let setCount = barChartData.dataSetCount ?? 0
// calculate how often the group-space appears
let steps = Int(yVal / (Double(setCount) + Double(barChartData.groupSpace)))
let groupSpaceSum = Double(barChartData.groupSpace) * Double(steps)
let baseNoSpace = yVal - groupSpaceSum
return baseNoSpace
}
else
{
return 0.0
}
}
}
| apache-2.0 | 23d144e58ce5fb554369db997f782ee2 | 28.644628 | 136 | 0.486758 | 5.267254 | false | false | false | false |
modocache/swift | test/SILOptimizer/devirt_unbound_generic.swift | 7 | 4122 | // RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s
// We used to crash on this when trying to devirtualize t.boo(a, 1),
// because it is an "apply" with unbound generic arguments and
// devirtualizer is not able to devirtualize unbound generic
// invocations yet.
//
// rdar://19912272
protocol P {
associatedtype Node
}
class C<T:P> {
typealias Node = T.Node
func foo(_ n:Node) {
}
func boo<S>(_ n:Node, s:S) {
}
}
func test1<T>(_ t:C<T>, a: T.Node) {
t.boo(a, s:1)
}
class Base<T> {
func foo() {
}
class func boo() {
}
}
class Derived<T> : Base<T> {
override func foo() {
}
override class func boo() {
}
}
// Check that the instance method Derived<T>.foo can be devirtualized, because Derived.foo is an internal function,
// Derived has no subclasses and it is a WMO compilation.
// CHECK: sil hidden [noinline] @_TF22devirt_unbound_generic5test2urFGCS_7Derivedx_T_
// CHECK-NOT: class_method
// CHECK: function_ref @_TFC22devirt_unbound_generic7Derived3foofT_T_
// CHECK-NOT: class_method
// CHECK: return
@inline(never)
func test2<T>(_ d: Derived<T>) {
d.foo()
}
public func doTest2<T>(_ t:T) {
test2(Derived<T>())
}
// Check that the class method Derived<T>.boo can be devirtualized, because Derived.boo is an internal function,
// Derived has no subclasses and it is a WMO compilation.
// CHECK: sil hidden [noinline] @_TF22devirt_unbound_generic5test3urFGCS_7Derivedx_T_
// CHECK-NOT: class_method
// CHECK: function_ref @_TZFC22devirt_unbound_generic7Derived3boofT_T_
// CHECK-NOT: class_method
// CHECK: return
@inline(never)
func test3<T>(_ d: Derived<T>) {
type(of: d).boo()
}
public func doTest3<T>(_ t:T) {
test3(Derived<T>())
}
public protocol ProtocolWithAssocType {
associatedtype Element
}
private class CP<Base: ProtocolWithAssocType> {
var value: Base.Element
init(_ v: Base.Element) {
value = v
}
func getCount() -> Int32 {
return 1
}
}
private class Base1: ProtocolWithAssocType {
typealias Element = Int32
}
private class Base2<T>: ProtocolWithAssocType {
typealias Element = Int32
}
private class CP2: CP<Base2<Int>> {
init() {
super.init(1)
}
override func getCount() -> Int32 {
return 2
}
}
private class CP3: CP<Base2<Int>> {
init() {
super.init(1)
}
override func getCount() -> Int32 {
return 3
}
}
public class CC<CT> {
func next() -> CT? {
return nil
}
}
public protocol QQ {
associatedtype Base: PP
}
public protocol PP {
associatedtype Element
}
internal class D<DT: QQ> : CC<DT.Base.Element> {
override func next() -> DT.Base.Element? {
return nil
}
}
public struct S: PP {
public typealias Element = Int32
}
final public class E: QQ {
public typealias Base = S
}
// Check that c.next() inside test4 gets completely devirtualized.
// CHECK-LABEL: sil @{{.*}}test4
// CHECK-NOT: class_method
// CHECK: return
public func test4() -> Int32? {
let c: CC<Int32> = D<E>();
return c.next()
}
public func test5() -> Int32? {
return testDevirt(D<E>())
}
// Check that testDevirt is specialized and uses speculative devirtualization.
// CHECK-LABEL: sil shared [noinline] @{{.*}}testDevirt
// CHECK: checked_cast_br [exact] %{{.*}} : $CC<Int32> to $CC<Int32>
// CHECK: class_method
// CHECK: }
@inline(never)
public func testDevirt<T>(_ c: CC<T>) -> T? {
return c.next()
}
// The compiler used to crash on this code, because of
// generic types involved in the devirtualization.
//
// rdar://25891588
//
// CHECK-LABEL: sil private [noinline] @{{.*}}test6
// CHECK-NOT: class_method
// CHECK-NOT: checked_cast_br
// CHECK-NOT: class_method
// CHECK: }
@inline(never)
private func test6<T: ProtocolWithAssocType>(_ c: CP<T>) -> T.Element {
return c.value
}
public func doTest6() {
test6(CP<Base1>(1))
}
// CHECK-LABEL: sil private [noinline] @{{.*}}test7
// CHECK-NOT: class_method
// CHECK: checked_cast_br
// CHECK-NOT: class_method
// CHECK: }
@inline(never)
private func test7<T: ProtocolWithAssocType>(_ c: CP<T>) -> Int32 {
return c.getCount()
}
public func doTest7() {
test7(CP2())
}
| apache-2.0 | ec0833ae8cd51ad98d4cc878d0422faf | 19.009709 | 115 | 0.659146 | 3.129841 | false | true | false | false |
OEASLAN/OEANotification | Classes/OEANotification.swift | 1 | 7342 | //
// OEANotification.swift
// OEANotification
//
// Created by Ömer Emre Aslan on 15/11/15.
// Copyright © 2015 omer. All rights reserved.
//
import UIKit
public class OEANotification : UIView {
static let constant = Constants()
static var rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight)
static var viewController: UIViewController!
static var notificationCount = 0
static var rotated:Bool = false
// MARK: - Initial notification methods
/**
Initial static method of creating notification.
- since: 0.1.0
- author: @OEASLAN - [email protected]
- parameter title: The title of notification.
- parameter subTitle: The subtitle of notification.
- parameter type: The type of notification which are Success, Warning, and Info.
- parameter isDismissable: The notification center from which the notification should be dispatched.
- return: void
*/
static public func notify(
title: String,
subTitle: String,
type: NotificationType,
isDismissable: Bool
){
self.notify(title, subTitle: subTitle, image: nil, type: type, isDismissable: isDismissable)
}
/**
Initial static method of creating notification.
- since: 0.1.0
- author: @OEASLAN - [email protected]
- parameter title: The title of notification.
- parameter subTitle: The subtitle of notification.
- parameter type: The type of notification which are Success, Warning, and Info.
- parameter image: The main icon image of notification like avatar, success, warning etc. icons
- parameter isDismissable: The notification center from which the notification should be dispatched.
- return: void
*/
static public func notify(
title: String,
subTitle: String,
image: UIImage?,
type: NotificationType,
isDismissable: Bool
) {
self.notify(title, subTitle: subTitle, image: image, type: type, isDismissable: isDismissable, completion: nil, touchHandler: nil)
}
/**
Initial static method of creating notification.
- since: 0.1.0
- author: @OEASLAN - [email protected]
- parameter title: The title of notification.
- parameter subTitle: The subtitle of notification.
- parameter type: The type of notification which are Success, Warning, and Info.
- parameter image: The main icon image of notification like avatar, success, warning etc. icons
- parameter completion: The main icon image of notification like avatar, success, warning etc. icons
- parameter isDismissable: The notification center from which the notification should be dispatched.
- return: void
*/
static public func notify(
title: String,
subTitle: String,
image: UIImage?,
type: NotificationType,
isDismissable: Bool,
completion: (() -> Void)?,
touchHandler: (() ->Void)?
) {
let notificationView: NotificationView = NotificationView(
frame: rect,
title: title,
subTitle: subTitle,
image: image,
type: type,
completionHandler: completion,
touchHandler: touchHandler,
isDismissable: isDismissable
)
OEANotification.notificationCount++
OEANotification.removeOldNotifications()
print(OEANotification.viewController.view.frame)
if OEANotification.viewController.navigationController != nil {
OEANotification.viewController.navigationController!.view.addSubview(notificationView)
} else {
OEANotification.viewController.view.addSubview(notificationView)
}
}
/**
Sets the default view controller as a main view controller.
- since: 0.1.0
- author: @OEASLAN - [email protected]
- parameter viewController: The main controller which shows the notification.
- return: void
*/
static public func setDefaultViewController (viewController: UIViewController) {
self.viewController = viewController
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotateRecognizer", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
// MARK: - Helper methods
static public func removeOldNotifications() {
if OEANotification.viewController.navigationController != nil {
for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] {
if subUIView.isKindOfClass(NotificationView) {
let view: NotificationView = subUIView as! NotificationView
view.notificationTimer.invalidate()
subUIView.removeFromSuperview()
OEANotification.notificationCount--
}
}
} else {
for subUIView in OEANotification.viewController.view.subviews as [UIView] {
if subUIView.isKindOfClass(NotificationView) {
let view: NotificationView = subUIView as! NotificationView
view.notificationTimer.invalidate()
subUIView.removeFromSuperview()
OEANotification.notificationCount--
}
}
}
}
// Close active notification
static public func closeNotification() {
if OEANotification.viewController.navigationController != nil {
for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] {
if subUIView.isKindOfClass(NotificationView) {
let view: NotificationView = subUIView as! NotificationView
view.close()
}
}
} else {
for subUIView in OEANotification.viewController.view.subviews as [UIView] {
if subUIView.isKindOfClass(NotificationView) {
let view: NotificationView = subUIView as! NotificationView
view.close()
}
}
}
}
// Checking device's rotation process and remove notifications to handle UI conflicts.
static public func rotateRecognizer() {
removeOldNotifications()
UIApplication.sharedApplication().delegate?.window??.windowLevel = UIWindowLevelNormal
self.rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight)
}
}
public enum NotificationType {
case Warning
case Success
case Info
}
| mit | 8255ec88fbf554bf0cb62096ef6443b1 | 39.10929 | 196 | 0.613079 | 5.465376 | false | false | false | false |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/FutureQueue.swift | 1 | 10461 | //
// FutureQueue.swift
// Flow
//
// Created by Måns Bernhardt on 2015-11-05.
// Copyright © 2015 iZettle. All rights reserved.
//
import Foundation
/// A queue for futures.
///
/// Future queues are useful for handling exclusive access to a resource, and/or when it is important that independent operations are performed one after the other.
/// Enqueuing an asynchronous operation will delay its execution until the queue becomes empty.
public final class FutureQueue<Resource> {
private let maxConcurrentCount: Int
private var concurrentCount = 0
private let queueScheduler: Scheduler
private var _closedError: Error?
private let isEmptyCallbacker = Callbacker<Bool>()
private var _mutex = pthread_mutex_t()
// enqueued items.
private var items: [Executable] = [] {
didSet {
isEmptyCallbacker.callAll(with: isEmpty)
}
}
/// The resource protected by this queue
public let resource: Resource
/// Creates a new queue instance.
/// - Parameter resource: An instance of a resource for convenient access, typically a resource we want to ensure exlusive access to.
/// - Parameter maxConcurrentCount: The max number of simultaniously performed operations, defaults to 1.
/// - Parameter executeOn: An optional scheduler where the enqueue callback will be scheduled on.
public init(resource: Resource, maxConcurrentCount: Int = 1, executeOn: Scheduler = .current) {
precondition(maxConcurrentCount > 0, "maxConcurrentCount must 1 or greater")
self.resource = resource
self.maxConcurrentCount = maxConcurrentCount
queueScheduler = executeOn
OSAtomicIncrement32(&futureQueueUnitTestAliveCount)
memPrint("Queue init", futureQueueUnitTestAliveCount)
}
deinit {
OSAtomicDecrement32(&futureQueueUnitTestAliveCount)
memPrint("Queue deinit", futureQueueUnitTestAliveCount)
}
}
public extension FutureQueue {
/// Enqueues an `operation` that will be executed when or once the queue becomes empty.
/// - Returns: A future that will complete when the future returned from `operation` completes.
@discardableResult
public func enqueue<Output>(_ operation: @escaping () throws -> Future<Output>) -> Future<Output> {
if let error = closedError {
return Future(error: error)
}
return Future { completion in
let item = QueueItem<Output>(operation: operation, completion: completion)
self.mutex.protect {
self.items.append(item)
}
self.executeNextItem()
return Disposer(item.cancel)
}
}
/// Enqueues an `operation` that will be executed when or once the queue becomes empty.
/// - Returns: A future that will complete with the result from `operation`.
@discardableResult
public func enqueue<Output>(_ operation: @escaping () throws -> Output) -> Future<Output> {
return enqueue { return Future(try operation()) }
}
/// Enqueues an `operation` that will be executed with a new sub-queue when or once the queue becomes empty.
///
/// Once the `operation` is ready to be executed it will be called with a new insance of `self` holding a copy of `self`'s resource.
/// This sub-queue can be used to enqueue sub-operations and the `operation` enqueued on `self` will not complete until
/// the sub-queue becomes empty and the retuned future from `operation` completes.
///
/// - Returns: A future that will complete when the future returned from `operation` completes as well as the sub-queue becomes empty.
@discardableResult
public func enqueueBatch<Output>(_ operation: @escaping (FutureQueue) throws -> Future<Output>) -> Future<Output> {
let childQueue = FutureQueue(resource: resource, executeOn: queueScheduler)
return enqueue() {
try operation(childQueue).flatMapResult { r in
Future<Output> { c in
childQueue.isEmptySignal.atOnce().filter { $0 }.onValue { _ in
c(r)
}
}
}
}.onError { error in
childQueue.abortQueuedOperations(with: error, shouldCloseQueue: true)
}.onCancel {
childQueue.abortQueuedOperations(with: NSError(domain: "com.izettle.future.error", code:1, userInfo: [ NSLocalizedDescriptionKey : "No more queueing allowed on closed child queue" ]), shouldCloseQueue: true)
}
}
/// Enqueues an `operation` that will be executed with a new sub-queue when or once the queue becomes empty.
///
/// Once the `operation` is ready to be executed it will be called with a new insance of `self` holding a copy of `self`'s resource.
/// This sub-queue can be used to enqueue sub-operations and the `operation` enqueued on `self` will not complete until
/// the sub-queue becomes empty.
///
/// - Returns: A future that will complete with the result from `operation` once the sub-queue becomes empty.
@discardableResult
public func enqueueBatch<Output>(_ operation: @escaping (FutureQueue) throws -> Output) -> Future<Output> {
return enqueueBatch { return Future(try operation($0)) }
}
}
public extension FutureQueue {
/// Do we have any enqueued operations?
var isEmpty: Bool {
return mutex.protect { items.isEmpty }
}
/// Returns a signal that will signal when `isEmpty` is changed.
var isEmptySignal: ReadSignal<Bool> {
return ReadSignal(getValue: { self.isEmpty }, callbacker: isEmptyCallbacker).distinct()
}
/// Returns a signal that will signal when the queue becomes empty
var didBecomeEmpty: Signal<()> {
return isEmptySignal.filter { $0 }.toVoid()
}
}
public extension FutureQueue where Resource == () {
/// Creates a new queue instance.
/// - Parameter maxConcurrentCount: The max number of simultaniously performed operations, defaults to 1.
/// - Parameter executeOn: An optional scheduler where the enqueue callback will be scheduled on.
convenience init(maxConcurrentCount: Int = 1, executeOn: Scheduler = .current) {
self.init(resource: (), maxConcurrentCount: maxConcurrentCount, executeOn: executeOn)
}
}
public extension FutureQueue {
/// Will abort all non completed enqueued futures and complete the future returned from enqueue with `error`.
/// - Parameter error: The error to complete non yet completed futures returned from enqueue.
/// - Parameter shouldCloseQueue: If true, all succeeding enqueued operations won't be executed and the
/// future returned from `enqueue()` will immediately abort with `error`. Defaults to false.
func abortQueuedOperations(with error: Error, shouldCloseQueue: Bool = false) {
lock()
if shouldCloseQueue {
_closedError = error
}
let items = self.items
self.items = []
unlock()
for item in items {
item.abort(with: error)
}
}
/// The error passed to `abortQueuedExecutionWithError()` if called with `shouldCloseQueue` as true.
var closedError: Error? {
return mutex.protect { _closedError }
}
}
private extension FutureQueue {
var mutex: PThreadMutex { return PThreadMutex(&_mutex) }
func lock() { mutex.lock() }
func unlock() { mutex.unlock() }
func removeItem(_ item: Executable) {
mutex.protect {
_ = items.index { $0 === item }.map { items.remove(at: $0) }
}
}
func executeNextItem() {
lock()
guard concurrentCount < maxConcurrentCount else { return unlock() }
guard let item = items.filter({ !$0.isExecuting }).first else { return unlock() }
concurrentCount += 1
unlock()
item.execute(on: queueScheduler) {
self.mutex.protect {
self.concurrentCount -= 1
}
self.removeItem(item)
self.executeNextItem()
}
}
}
var queueItemUnitTestAliveCount: Int32 = 0
var futureQueueUnitTestAliveCount: Int32 = 0
/// QueueItem is generic on Output but we can't hold a queue of heterogeneous items, hence this helper protocol
private protocol Executable: class {
func execute(on scheduler: Scheduler, completion: @escaping () -> Void)
var isExecuting: Bool { get }
func abort(with error: Error)
func cancel()
}
private final class QueueItem<Output> : Executable {
private let operation: () throws -> Future<Output>
private let completion: (Result<Output>) -> ()
private weak var future: Future<Output>?
private var hasBeenCancelled = false
private var _mutex = pthread_mutex_t()
init(operation: @escaping () throws -> Future<Output>, completion: @escaping (Result<Output>) -> ()) {
self.completion = completion
self.operation = operation
mutex.initialize()
OSAtomicIncrement32(&queueItemUnitTestAliveCount)
memPrint("Queue Item init", queueItemUnitTestAliveCount)
}
deinit {
mutex.deinitialize()
OSAtomicDecrement32(&queueItemUnitTestAliveCount)
memPrint("Queue Item deinit", queueItemUnitTestAliveCount)
}
private var mutex: PThreadMutex { return PThreadMutex(&_mutex) }
private func lock() { mutex.lock() }
private func unlock() { mutex.unlock() }
private func complete(_ result: (Result<Output>)) {
lock()
let f = future
unlock()
f?.cancel()
completion(result)
}
func execute(on scheduler: Scheduler, completion: @escaping () -> Void) {
let f = Future().flatMap(on: scheduler, operation).onResult { r in
self.complete(r)
}.always(completion)
lock()
future = f
if hasBeenCancelled {
unlock()
f.cancel()
} else {
unlock()
}
}
func abort(with error: Error) {
complete(.failure(error))
}
var isExecuting: Bool {
lock()
defer { unlock() }
return future != nil
}
func cancel() {
lock()
hasBeenCancelled = true
let f = future
unlock()
f?.cancel()
}
}
| mit | f0bbb516b26a6029c69a2490df8f316f | 36.353571 | 219 | 0.641457 | 4.707021 | false | false | false | false |
crossroadlabs/ExpressCommandLine | swift-express/Core/RunSubtaskStep.swift | 1 | 2297 | //===--- RunSubtaskStep.swift --------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line 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.
//
//Swift Express Command Line is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
protocol RunSubtaskStep : Step {
func executeSubtaskAndWait(task: SubTask) throws -> Int32
}
extension RunSubtaskStep {
func executeSubtaskAndWait(task: SubTask) throws -> Int32 {
return try runSubTaskAndHandleSignals(task)
}
}
// Can run only one task in app.
func runSubTaskAndHandleSignals(task: SubTask) throws -> Int32 {
if !signalsRegistered {
_registerSignals()
}
if currentRunningTask != nil {
throw SwiftExpressError.SubtaskError(message: "Can't start new task. Some task already running")
}
defer {
currentRunningTask = nil
}
currentRunningTask = task
return try task.runAndWait()
}
private var currentRunningTask:SubTask? = nil
private var signalsRegistered:Bool = false
private func _registerSignals() {
trap_signal(.INT, action: { signal -> Void in
if currentRunningTask != nil {
currentRunningTask!.interrupt()
currentRunningTask = nil
} else {
exit(signal)
}
})
trap_signal(.TERM, action: { signal -> Void in
if currentRunningTask != nil {
currentRunningTask!.terminate()
currentRunningTask = nil
} else {
exit(signal)
}
})
signalsRegistered = true
} | gpl-3.0 | 6ae967d406b139f52bb6388a1d3e8022 | 30.479452 | 104 | 0.642577 | 4.530572 | false | false | false | false |
johndatserakis/RibbonReminder | Ribbon Reminder/RibbonViewController.swift | 1 | 18089 | //
// RibbonViewController.swift
// Ribbon Reminder
//
// Created by John Datserakis on 11/13/14.
// Copyright (c) 2014 John Datserakis. All rights reserved.
//
import UIKit
class RibbonViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableRibbon: UITableView!
var verticalContentOffset = CGFloat()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "itemChanged:", name: "reloadTableViewData", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func itemChanged(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue()) {
UIView.transitionWithView(self.view, duration: 0.500, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
self.tableRibbon.reloadData()
}, completion: { (fininshed: Bool) -> () in
})
}
}
@IBAction func backpressedRibbon(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func showTapped(sender: UIButton) {
var cell = sender.superview as UITableViewCell
var indexPath = tableRibbon.indexPathForCell(cell)
if indexPath?.row == 0 {
println("Row 1 was clicked - Show")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(false, forKey: "notificationIsVisible0")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible0")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 1 {
println("Row 2 was clicked - Show")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(false, forKey: "notificationIsVisible1")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible1")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 2 {
println("Row 3 was clicked - Show")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(false, forKey: "notificationIsVisible2")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible2")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 3 {
println("Row 4 was clicked - Show")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(false, forKey: "notificationIsVisible3")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible3")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 4 {
println("Row 5 was clicked - Show")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(false, forKey: "notificationIsVisible4")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(false, forKey: "NCnotificationIsVisible4")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
}
func hideTapped(sender: UIButton) {
var cell = sender.superview as UITableViewCell
var indexPath = tableRibbon.indexPathForCell(cell)
if indexPath?.row == 0 {
println("Row 1 was clicked - Hide")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: "notificationIsVisible0")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible0")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 1 {
println("Row 2 was clicked - Hide")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: "notificationIsVisible1")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible1")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 2 {
println("Row 3 was clicked - Hide")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: "notificationIsVisible2")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible2")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 3 {
println("Row 4 was clicked - Hide")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: "notificationIsVisible3")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible3")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
if indexPath?.row == 4 {
println("Row 5 was clicked - Hide")
var userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setBool(true, forKey: "notificationIsVisible4")
let sharedDefaults = NSUserDefaults(suiteName: "group.RibbonSharingDefaults")
sharedDefaults?.setBool(true, forKey: "NCnotificationIsVisible4")
NSNotificationCenter.defaultCenter().postNotificationName("reloadTableViewData", object: nil)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell_Ribbon", forIndexPath: indexPath) as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell_Ribbon")
}
//Label Work
var label_title : UILabel? = self.view.viewWithTag(2) as? UILabel;
var newFont = UIFont(name: "Wawati TC", size: 20)
label_title?.font = newFont
var userDefaults = NSUserDefaults.standardUserDefaults()
if indexPath.row == 0 {
if userDefaults.stringForKey("textfield0") != nil {
label_title?.text = userDefaults.stringForKey("textfield0")
} else {
label_title?.text = "Thumb"
}
if userDefaults.boolForKey("notificationIsVisible0") == false {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if userDefaults.boolForKey("notificationIsVisible0") == true {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_open_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "showTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if label_title?.text == "Thumb" {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
}
if indexPath.row == 1 {
if userDefaults.stringForKey("textfield1") != nil {
label_title?.text = userDefaults.stringForKey("textfield1")
} else {
label_title?.text = "Index"
}
if userDefaults.boolForKey("notificationIsVisible1") == false {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if userDefaults.boolForKey("notificationIsVisible1") == true {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_open_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "showTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if label_title?.text == "Index" {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
}
if indexPath.row == 2 {
if userDefaults.stringForKey("textfield2") != nil {
label_title?.text = userDefaults.stringForKey("textfield2")
} else {
label_title?.text = "Middle"
}
if userDefaults.boolForKey("notificationIsVisible2") == false {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if userDefaults.boolForKey("notificationIsVisible2") == true {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_open_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "showTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if label_title?.text == "Middle" {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
}
if indexPath.row == 3 {
if userDefaults.stringForKey("textfield3") != nil {
label_title?.text = userDefaults.stringForKey("textfield3")
} else {
label_title?.text = "Ring"
}
if userDefaults.boolForKey("notificationIsVisible3") == false {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if userDefaults.boolForKey("notificationIsVisible3") == true {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_open_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "showTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if label_title?.text == "Ring" {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
}
if indexPath.row == 4 {
if userDefaults.stringForKey("textfield4") != nil {
label_title?.text = userDefaults.stringForKey("textfield4")
} else {
label_title?.text = "Pinky"
}
if userDefaults.boolForKey("notificationIsVisible4") == false {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if userDefaults.boolForKey("notificationIsVisible4") == true {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_open_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "showTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
if label_title?.text == "Pinky" {
var accessoryButton = UIButton(frame: CGRectMake(0, 0, 40, 33))
var accessoryImage = UIImage(named: "eye_closed_button 2_002")
accessoryButton.setImage(accessoryImage, forState: UIControlState.Normal)
accessoryButton.addTarget(self, action: "hideTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell?.accessoryView = accessoryButton
}
}
return cell!
}
}
| mit | b7196e5b312c1d30a264d12cabc98790 | 40.872685 | 136 | 0.57593 | 5.983791 | false | false | false | false |
KarlWarfel/nutshell-ios | Nutshell/DataModel/NutshellHealthKitConfiguration.swift | 1 | 8388 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import HealthKit
import CocoaLumberjack
import CoreData
class NutshellHealthKitConfiguration: HealthKitConfiguration
{
// Override to load workout events and sync smbg events from Tidepool service in addition to pushing up Dexcom blood glucose monitoring events
override func turnOnInterface() {
super.turnOnInterface()
monitorForWorkoutData(true)
HealthKitDataPusher.sharedInstance.enablePushToHealthKit(true)
}
override func turnOffInterface() {
super.turnOffInterface()
monitorForWorkoutData(false)
HealthKitDataPusher.sharedInstance.enablePushToHealthKit(false)
}
//
// MARK: - Loading workout events from Healthkit
//
func monitorForWorkoutData(monitor: Bool) {
// Set up HealthKit observation and background query.
if (HealthKitManager.sharedInstance.isHealthDataAvailable) {
if monitor {
HealthKitManager.sharedInstance.startObservingWorkoutSamples() {
(newSamples: [HKSample]?, deletedSamples: [HKDeletedObject]?, error: NSError?) in
if (newSamples != nil) {
NSLog("********* PROCESSING \(newSamples!.count) new workout samples ********* ")
dispatch_async(dispatch_get_main_queue()) {
self.processWorkoutEvents(newSamples!)
}
}
if (deletedSamples != nil) {
NSLog("********* PROCESSING \(deletedSamples!.count) deleted workout samples ********* ")
dispatch_async(dispatch_get_main_queue()) {
self.processDeleteWorkoutEvents(deletedSamples!)
}
}
}
} else {
HealthKitManager.sharedInstance.stopObservingWorkoutSamples()
}
}
}
private func processWorkoutEvents(workouts: [HKSample]) {
let moc = NutDataController.controller().mocForNutEvents()!
if let entityDescription = NSEntityDescription.entityForName("Workout", inManagedObjectContext: moc) {
for event in workouts {
if let workout = event as? HKWorkout {
NSLog("*** processing workout id: \(event.UUID.UUIDString)")
if let metadata = workout.metadata {
NSLog(" metadata: \(metadata)")
}
if let wkoutEvents = workout.workoutEvents {
if !wkoutEvents.isEmpty {
NSLog(" workout events: \(wkoutEvents)")
}
}
let we = NSManagedObject(entity: entityDescription, insertIntoManagedObjectContext: nil) as! Workout
// Workout fields
we.appleHealthDate = workout.startDate
we.calories = workout.totalEnergyBurned?.doubleValueForUnit(HKUnit.kilocalorieUnit())
we.distance = workout.totalDistance?.doubleValueForUnit(HKUnit.mileUnit())
we.duration = workout.duration
we.source = workout.sourceRevision.source.name
// NOTE: use the Open mHealth enum string here!
we.subType = Workout.enumStringForHKWorkoutActivityType(workout.workoutActivityType)
// EventItem fields
// Default title format: "Run - 4.2 miles"
var title: String = Workout.userStringForHKWorkoutActivityTypeEnumString(we.subType!)
if let miles = we.distance {
let floatMiles = Float(trunc(Float(miles)*2.0)/2.0)
//KBW added rounding function to show only the .5 resolution
//KBW show only one digit of precision
title = title + " - " + String(format: "%.1f",floatMiles) + " miles"
}
we.title = title
// Default notes string is the application name sourcing the event
we.notes = we.source
// Common fields
we.time = workout.startDate
we.type = "workout"
we.id = event.UUID.UUIDString
we.userid = NutDataController.controller().currentUserId
let now = NSDate()
we.createdTime = now
we.modifiedTime = now
// TODO: we set a time zone offset for this event, ASSUMING the workout was done in the same time zone location. We do adjust for times in a different daylight savings zone offset. Should we just leave this field nil unless we can be reasonably clear about the time zone (e.g., events very recently created)?
let dstAdjust = NutUtils.dayLightSavingsAdjust(workout.startDate)
we.timezoneOffset = (NSCalendar.currentCalendar().timeZone.secondsFromGMT + dstAdjust)/60
// Check to see if we already have this one, with possibly a different id
if let time = we.time, userId = we.userid {
let request = NSFetchRequest(entityName: "Workout")
request.predicate = NSPredicate(format: "(time == %@) AND (userid = %@)", time, userId)
do {
let existingWorkouts = try moc.executeFetchRequest(request) as! [Workout]
for workout: Workout in existingWorkouts {
if workout.duration == we.duration &&
workout.title == we.title &&
workout.notes == we.notes {
NSLog("Deleting existing workout of same time and duration: \(workout)")
moc.deleteObject(workout)
}
}
} catch {
NSLog("Workout dupe query failed!")
}
}
moc.insertObject(we)
NSLog("added workout: \(we)")
} else {
NSLog("ERROR: \(#function): Expected HKWorkout!")
}
}
}
DatabaseUtils.databaseSave(moc)
}
private func processDeleteWorkoutEvents(workouts: [HKDeletedObject]) {
let moc = NutDataController.controller().mocForNutEvents()!
for workout in workouts {
NSLog("Processing deleted workout sample with UUID: \(workout.UUID)");
let id = workout.UUID.UUIDString
let request = NSFetchRequest(entityName: "Workout")
// Note: look for any workout with this id, regardless of current user - we should only see it for one user, but multiple user operation is not yet completely defined.
request.predicate = NSPredicate(format: "(id == %@)", id)
do {
let existingWorkouts = try moc.executeFetchRequest(request) as! [Workout]
for workout: Workout in existingWorkouts {
NSLog("Deleting workout: \(workout)")
moc.deleteObject(workout)
}
DatabaseUtils.databaseSave(moc)
} catch {
NSLog("Existing workout query failed!")
}
}
}
}
| bsd-2-clause | 4b79fa17b8bd0a2b39a1bcf79f3521f7 | 48.633136 | 328 | 0.543395 | 5.764948 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentityTests/Helpers/IdentityAnalyticsClientTestHelpers.swift | 1 | 1568 | //
// IdentityAnalyticsClientTestHelpers.swift
// StripeIdentityTests
//
// Created by Mel Ludowise on 6/13/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
import StripeCoreTestUtils
import XCTest
// Some test helper methods to easily check Identity analytic payloads for
// specific property or metadata property values.
func XCTAssert<T: Equatable>(
analytic: [String: Any]?,
hasProperty propertyName: String,
withValue value: T,
file: StaticString = #filePath,
line: UInt = #line
) {
XCTAssertEqual(analytic?[propertyName] as? T, value, file: file, line: line)
}
func XCTAssert<T: Equatable>(
analytic: [String: Any]?,
hasMetadata propertyName: String,
withValue value: T,
file: StaticString = #filePath,
line: UInt = #line
) {
let metadata = analytic?["event_metadata"] as? [String: Any]
XCTAssertEqual(metadata?[propertyName] as? T, value, file: file, line: line)
}
func XCTAssert(
analytic: [String: Any]?,
hasMetadataError propertyName: String,
withDomain domain: String,
code: Int,
fileName: String,
file: StaticString = #filePath,
line: UInt = #line
) {
let metadata = analytic?["event_metadata"] as? [String: Any]
let error = metadata?[propertyName] as? [String: Any]
XCTAssertEqual(error?["domain"] as? String, domain, "domain", file: file, line: line)
XCTAssertEqual(error?["code"] as? Int, code, "code", file: file, line: line)
XCTAssertEqual(error?["file"] as? String, fileName, "file", file: file, line: line)
}
| mit | 61b008bc7813f28d30dc7e6acbe8735e | 29.72549 | 89 | 0.685386 | 3.821951 | false | true | false | false |
PureSwift/BinaryJSON | Sources/BinaryJSON/Extensions.swift | 1 | 5307 | //
// Extensions.swift
// BinaryJSON
//
// Created by Alsey Coleman Miller on 12/15/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
import SwiftFoundation
// MARK: - Protocol
/// Type can be converted to BSON.
public protocol BSONEncodable {
/// Encodes the reciever into BSON.
func toBSON() -> BSON.Value
}
/// Type can be converted from BSON.
public protocol BSONDecodable {
/// Decodes the reciever from BSON.
init?(BSONValue: BSON.Value)
}
// MARK: - SwiftFoundation Types
// MARK: Null
extension SwiftFoundation.Null: BSONEncodable {
public func toBSON() -> BSON.Value { return .Null }
}
extension SwiftFoundation.Null: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Null else { return nil }
self = value
}
}
// MARK: Date
extension SwiftFoundation.Date: BSONEncodable {
public func toBSON() -> BSON.Value { return .Date(self) }
}
extension SwiftFoundation.Date: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Date else { return nil }
self = value
}
}
// MARK: Data
extension SwiftFoundation.Data: BSONEncodable {
public func toBSON() -> BSON.Value { return .Binary(BSON.Binary(data: self)) }
}
extension SwiftFoundation.Data: BSONDecodable {
public init?(BSONValue: BSON.Value) {
// generic binary is convertible to data
guard let value = BSONValue.rawValue as? BSON.Binary where value.subtype == .Generic
else { return nil }
self = value.data
}
}
// MARK: - Swift Standard Library Types
// MARK: Encodable
extension String: BSONEncodable {
public func toBSON() -> BSON.Value { return .String(self) }
}
extension String: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? String else { return nil }
self = value
}
}
extension Int32: BSONEncodable {
public func toBSON() -> BSON.Value { return .Number(.Integer32(self)) }
}
extension Int32: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Int32 else { return nil }
self = value
}
}
extension Int64: BSONEncodable {
public func toBSON() -> BSON.Value { return .Number(.Integer64(self)) }
}
extension Int64: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Int64 else { return nil }
self = value
}
}
extension Double: BSONEncodable {
public func toBSON() -> BSON.Value { return .Number(.Double(self)) }
}
extension Double: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Double else { return nil }
self = value
}
}
extension Bool: BSONEncodable {
public func toBSON() -> BSON.Value { return .Number(.Boolean(self)) }
}
extension Bool: BSONDecodable {
public init?(BSONValue: BSON.Value) {
guard let value = BSONValue.rawValue as? Bool else { return nil }
self = value
}
}
// MARK: - Collection Extensions
// MARK: Encodable
public extension CollectionType where Generator.Element: BSONEncodable {
func toBSON() -> BSON.Value {
var BSONArray = BSON.Array()
for BSONEncodable in self {
let BSONValue = BSONEncodable.toBSON()
BSONArray.append(BSONValue)
}
return .Array(BSONArray)
}
}
public extension Dictionary where Value: BSONEncodable, Key: StringLiteralConvertible {
/// Encodes the reciever into BSON.
func toBSON() -> BSON.Value {
var document = BSON.Document()
for (key, value) in self {
let BSONValue = value.toBSON()
let keyString = String(key)
document[keyString] = BSONValue
}
return .Document(document)
}
}
// MARK: Decodable
public extension BSONDecodable {
/// Decodes from an array of BSON values.
static func fromBSON(BSONArray: BSON.Array) -> [Self]? {
var BSONDecodables = [Self]()
for BSONValue in BSONArray {
guard let BSONDecodable = self.init(BSONValue: BSONValue) else { return nil }
BSONDecodables.append(BSONDecodable)
}
return BSONDecodables
}
}
// MARK: - RawRepresentable Extensions
// MARK: Encode
public extension RawRepresentable where RawValue: BSONEncodable {
/// Encodes the reciever into BSON.
func toBSON() -> BSON.Value {
return rawValue.toBSON()
}
}
// MARK: Decode
public extension RawRepresentable where RawValue: BSONDecodable {
/// Decodes the reciever from BSON.
init?(BSONValue: BSON.Value) {
guard let rawValue = RawValue(BSONValue: BSONValue) else { return nil }
self.init(rawValue: rawValue)
}
}
| mit | f4994a70d78c88fccde9eb773f6483dd | 20.481781 | 92 | 0.598379 | 4.417985 | false | false | false | false |
CSSE497/pathfinder-ios | framework/Pathfinder/RouteAction.swift | 1 | 2446 | //
// RouteAction.swift
// Pathfinder
//
// Created by Adam Michael on 11/1/15.
// Copyright © 2015 Pathfinder. All rights reserved.
//
import Foundation
import CoreLocation
/// A data object containing a commodity, a location and a field indicating pickup or dropoff.
public class RouteAction {
// MARK: - Enums -
/// The possible actions that can be performed on commodities by transports.
public enum Action : CustomStringConvertible {
case Start
case Pickup
case Dropoff
public var description: String {
switch self {
case .Start: return "Start"
case .Pickup: return "Pickup"
case .Dropoff: return "Dropoff"
}
}
}
// MARK: - Instance Variables -
/// Whether the action is a pickup or dropoff.
public let action: Action
/// The commodity that is picked up or dropped off.
public var commodity: Commodity?
/// The location where the action is to occur.
public let location: CLLocationCoordinate2D
init(action: Action, location: CLLocationCoordinate2D) {
self.action = action
self.location = location
}
init(action: Action, commodity: Commodity, location: CLLocationCoordinate2D) {
self.action = action
self.commodity = commodity
self.location = location
}
class func parse(message: NSDictionary) -> RouteAction? {
if let actionString = message["action"] as? String {
let latitude = message["latitude"] as! Double
let longitude = message["longitude"] as! Double
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
print("Attempting to parse RouteAction at location \(location)")
if actionString == "Start" {
return RouteAction(action: Action.Start, location: location)
} else if actionString == "PickUp" {
if let commodity = Commodity.parse(message["commodity"] as! NSDictionary) {
print("Parsed commodity with status \(commodity.status)")
return RouteAction(action: Action.Pickup, commodity: commodity, location: location)
}
} else if actionString == "DropOff" {
if let commodity = Commodity.parse(message["commodity"] as! NSDictionary) {
print("Parsed commodity with status \(commodity.status)")
return RouteAction(action: Action.Dropoff, commodity: commodity, location: location)
}
}
}
print("Failed to parse RouteAction: \(message)")
return nil
}
} | mit | 3141865506341a6760b02769d6dfdf6b | 30.766234 | 94 | 0.678937 | 4.208262 | false | false | false | false |
Senspark/ee-x | src/ios/ee/apps_flyer/AppsFlyerBridge.swift | 1 | 5214 | //
// AppsFlyerBridge.swift
// ee-x-6914a733
//
// Created by eps on 6/25/20.
//
import AppsFlyerLib
private let kTag = "\(AppsFlyerBridge.self)"
private let kPrefix = "AppsFlyerBridge"
private let kInitialize = "\(kPrefix)Initialize"
private let kStartTracking = "\(kPrefix)StartTracking"
private let kGetDeviceId = "\(kPrefix)GetDeviceId"
private let kSetDebugEnabled = "\(kPrefix)SetDebugEnabled"
private let kSetStopTracking = "\(kPrefix)SetStopTracking"
private let kTrackEvent = "\(kPrefix)TrackEvent"
@objc(EEAppsFlyerBridge)
class AppsFlyerBridge: NSObject, IPlugin, AppsFlyerLibDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _tracker = AppsFlyerLib.shared()
public required init(_ bridge: IMessageBridge, _ logger: ILogger) {
_bridge = bridge
_logger = logger
super.init()
registerHandlers()
}
public func destroy() {
deregisterHandlers()
Thread.runOnMainThread {
self._tracker.delegate = nil
}
}
func registerHandlers() {
_bridge.registerHandler(kInitialize) { message in
let dict = EEJsonUtils.convertString(toDictionary: message)
guard
let devKey = dict["devKey"] as? String,
let iosAppId = dict["iosAppId"] as? String
else {
assert(false, "Invalid argument")
return ""
}
self.intialize(devKey, iosAppId)
return ""
}
_bridge.registerHandler(kStartTracking) { _ in
self.startTracking()
return ""
}
_bridge.registerHandler(kGetDeviceId) { _ in
self.deviceId
}
_bridge.registerHandler(kSetDebugEnabled) { message in
self.setDebugEnabled(Utils.toBool(message))
return ""
}
_bridge.registerHandler(kSetStopTracking) { message in
self.setStopTracking(Utils.toBool(message))
return ""
}
_bridge.registerHandler(kTrackEvent) { message in
let dict = EEJsonUtils.convertString(toDictionary: message)
guard
let name = dict["name"] as? String,
let values = dict["values"] as? [String: Any]
else {
assert(false, "Invalid argument")
return ""
}
self.trackEvent(name, values)
return ""
}
}
func deregisterHandlers() {
_bridge.deregisterHandler(kInitialize)
_bridge.deregisterHandler(kStartTracking)
_bridge.deregisterHandler(kGetDeviceId)
_bridge.deregisterHandler(kSetDebugEnabled)
_bridge.deregisterHandler(kSetStopTracking)
_bridge.deregisterHandler(kTrackEvent)
}
func intialize(_ devKey: String, _ iosAppId: String) {
Thread.runOnMainThread {
self._tracker.appsFlyerDevKey = devKey
self._tracker.appleAppID = iosAppId
self._tracker.delegate = self
self._tracker.shouldCollectDeviceName = true
self._tracker.anonymizeUser = false
}
}
func startTracking() {
Thread.runOnMainThread {
self._tracker.start()
}
}
var deviceId: String {
return _tracker.getAppsFlyerUID()
}
func setDebugEnabled(_ enabled: Bool) {
Thread.runOnMainThread {
self._tracker.isDebug = enabled
}
}
func setStopTracking(_ enabled: Bool) {
Thread.runOnMainThread {
self._tracker.isStopped = enabled
}
}
func trackEvent(_ name: String, _ values: [String: Any]) {
Thread.runOnMainThread {
self._tracker.logEvent(name, withValues: values)
}
}
public func onConversionDataSuccess(_ conversionInfo: [AnyHashable: Any]) {
_logger.debug("\(kTag): \(#function): \(conversionInfo)")
}
public func onConversionDataFail(_ error: Error) {
_logger.debug("\(kTag): \(#function): \(error.localizedDescription)")
}
public func onAppOpenAttribution(_ attributionData: [AnyHashable: Any]) {
_logger.debug("\(kTag): \(#function): \(attributionData)")
}
public func onAppOpenAttributionFailure(_ error: Error) {
_logger.debug("\(kTag): \(#function): \(error.localizedDescription)")
}
public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
_tracker.handleOpen(url, options: options)
return false
}
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
_tracker.handleOpen(url, sourceApplication: sourceApplication, withAnnotation: annotation)
return false
}
public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
_tracker.continue(userActivity) { items in
restorationHandler(items as? [UIUserActivityRestoring])
}
return false
}
}
| mit | 5c2974004551e24f5a1eb792c9634cc7 | 31.5875 | 174 | 0.616034 | 4.688849 | false | false | false | false |
blokadaorg/blokada | ios/NETX/PacketLoop.swift | 1 | 16886 | //
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Network
import NetworkExtension
enum LogLevel: UInt32 {
case NONE = 0
case INFO
case DEBUG
case ALL
};
enum SessionState {
case NotInitialized
case IsRecovering(NWUDPSession)
case WasRecovered(NWUDPSession)
case IsReady(NWUDPSession)
case IsInvalid(NWUDPSession)
case IsCancelling(NWUDPSession)
}
protocol TunnelSessionDelegate: class {
func createSession() -> NWUDPSession
func readPacketObjects(completionHandler: @escaping ([NEPacket]) -> Void)
func writePackets(_ packets: [Data], withProtocols protocols: [NSNumber]) -> Void
func hasBetterEndpoint(_ session: NWUDPSession) -> Bool
}
func invalidSession(_ session: NWUDPSession) -> Bool {
switch session.state {
case .invalid: return true
case .failed: return true
case .cancelled: return true
default: return !session.isViable
}
}
let maxPacketSize = 1500
let maxDatagrams = 100
let bufferSize = maxPacketSize * maxDatagrams
let sessionQueue = DispatchQueue(label: "session")
class PacketLoop: NSObject {
var session: SessionState = .NotInitialized
var sessionObserver: NSKeyValueObservation?
var sessionTicker: Timer? = nil
weak var delegate: TunnelSessionDelegate?
var tunnel: OpaquePointer?
var wireguardReadBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var wireguardWriteBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var wireguardTimerBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxPacketSize)
var wireguardTicker: Timer? = nil
// Preallocated data arrays
var wireguardReadDatagrams = [Data]()
var wireguardReadPackets = [Data]()
var wireguardReadPacketProtocols = [NSNumber]()
var wireguardWriteDatagrams = [Data]()
func start(privateKey: String, gatewayKey: String, delegate: TunnelSessionDelegate) {
self.delegate = delegate
// Main thread is where timers works
DispatchQueue.main.sync {
if self.tunnel != nil {
fatalError("started before stopped")
}
self.tunnel = new_tunnel(privateKey, gatewayKey, tunnel_log, LogLevel.DEBUG.rawValue)
// observing doesn't work so we poll. https://github.com/apple/swift/pull/20757
self.startSessionTicker()
self.startWireguardTicker()
// Egress to the gateway
self.delegate?.readPacketObjects(completionHandler: self.handleOutboundPackets)
}
}
func startSessionTicker() {
if sessionTicker != nil {
NELogger.e("PacketLoop: startSessionTicker when ticker is already running")
return
}
self.sessionTicker = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
guard let delegate = self.delegate else { return }
sessionQueue.sync {
if self.sessionTicker == nil {
return
}
switch self.session {
case .NotInitialized:
let session = delegate.createSession()
// TODO: move setReadHandler to createSession()
session.setReadHandler(self.handleInboundPackets, maxDatagrams: maxDatagrams)
self.session = .IsRecovering(session)
case .IsRecovering(let session):
if session.state == .ready {
self.session = .WasRecovered(session)
break
}
// Try again
self.session = .IsInvalid(session)
case .WasRecovered(let session):
DispatchQueue.main.async {
self.handshakeNow()
}
self.session = .IsReady(session)
NELogger.v("PacketLoop: recovered session with endpoint: \(session.endpoint.description)")
case .IsReady(let session):
if invalidSession(session) {
self.session = .IsInvalid(session)
break
}
if session.hasBetterPath {
NELogger.v("PacketLoop: upgrade session")
let session = NWUDPSession(upgradeFor: session)
session.setReadHandler(self.handleInboundPackets, maxDatagrams: maxDatagrams)
self.session = .IsRecovering(session)
break
}
// Work around for not being able to specify multiple endpoints.
// If wifi doesn't support IPv6 while mobile does, and that's our current stack
// we won't switch to wifi without this.
if delegate.hasBetterEndpoint(session) {
NELogger.w("PacketLoop: switch to cheaper endpoint path")
self.session = .IsInvalid(session)
}
case .IsInvalid(let session):
NELogger.v("PacketLoop: cancel invalid session")
session.cancel()
self.session = .IsCancelling(session)
case .IsCancelling(let session):
if session.state == .cancelled {
NELogger.v("PacketLoop: replace invalid session")
let session = delegate.createSession()
session.setReadHandler(self.handleInboundPackets, maxDatagrams: maxDatagrams)
self.session = .IsRecovering(session)
}
}
}
}
}
func startWireguardTicker() {
if wireguardTicker != nil {
NELogger.e("PacketLoop: startWireguardTicker when ticker is already running")
return
}
self.wireguardTicker = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
guard let tunnel = self.tunnel else { return }
if self.wireguardTicker == nil {
return
}
let res = wireguard_tick(tunnel, self.wireguardTimerBuffer, UInt32(maxPacketSize))
switch res.op {
case WRITE_TO_NETWORK:
let packet = Data(bytesNoCopy: self.wireguardTimerBuffer, count: Int(res.size), deallocator: .none)
self.sendDatagrams(datagrams: [packet])
NELogger.v("PacketLoop: wireguard_tick")
case WIREGUARD_DONE:
break
case WIREGUARD_ERROR:
NELogger.e("PacketLoop: WIREGUARD_ERROR in wireguard_tick: \(res.size)")
default:
NELogger.e("PacketLoop: Unexpected return type in wireguard_tick: \(res.op)")
}
}
}
// Stop is used to clean things up as deinit is unreliable. We also keep buffers alive in between to avoid
// race conditions with packet reading/writing completion handlers which might complete after we deinit.
func stop() {
sessionQueue.sync {
if let tunnel = tunnel {
tunnel_free(tunnel)
}
tunnel = nil
sessionTicker?.invalidate()
sessionTicker = nil
session = .NotInitialized
wireguardTicker?.invalidate()
wireguardTicker = nil
// Clear pending packets
wireguardReadDatagrams = [Data]()
wireguardReadPackets = [Data]()
wireguardReadPacketProtocols = [NSNumber]()
wireguardWriteDatagrams = [Data]()
}
}
func handleOutboundPackets(_ packets: [NEPacket]) {
guard let tunnel = self.tunnel else { return }
var offset: UInt = 0
for packet in packets {
if offset + UInt(maxPacketSize) > bufferSize {
// Flush if might not have enough space
sendDatagrams(datagrams: self.wireguardWriteDatagrams)
self.wireguardWriteDatagrams.removeAll(keepingCapacity: true)
offset = 0
}
// We encapsulate as many packets as we can into the wireguardWriteBuffer
let writeBuff = self.wireguardWriteBuffer.advanced(by: Int(offset))
let res = packet.data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> wireguard_result in
let dataPtr = ptr.baseAddress?.bindMemory(to: UInt8.self, capacity: packet.data.count)
return wireguard_write(tunnel, dataPtr, UInt32(packet.data.count), writeBuff, UInt32(maxPacketSize))
}
switch res.op {
case WRITE_TO_NETWORK:
self.wireguardWriteDatagrams.append(Data(bytesNoCopy: writeBuff, count: Int(res.size), deallocator: .none))
offset += res.size
case WIREGUARD_DONE:
break
case WIREGUARD_ERROR:
NELogger.e("PacketTunnelProvider: WIREGUARD_ERROR in wireguard_write: \(res.size)")
default:
NELogger.e("PacketTunnelProvider: Unexpected return type: \(res.op)")
}
}
if self.wireguardWriteDatagrams.count > 0 {
// Send
self.sendDatagrams(datagrams: self.wireguardWriteDatagrams)
self.wireguardWriteDatagrams.removeAll(keepingCapacity: true)
}
// Extra wrapping due to memory leak while doing recursive calls
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.readPacketObjects(completionHandler: self.handleOutboundPackets)
}
}
func handleInboundPackets(datagrams: [Data]?, err: Error?) {
guard let datagrams = datagrams else {
if err != nil /* && !self.reconnecting.value */ {
NELogger.e("PacketTunnelProvider: error while reading datagrams: \(String(describing: err))")
return // self.handleUDPError(err: err!)
}
return
}
guard let tunnel = self.tunnel else { return }
var offset: UInt = 0
var flushQueue = false
// This is the main loop
for wireguardDatagram in datagrams {
// Check if we ran out of space and need to flush
if offset + UInt(maxPacketSize) >= bufferSize {
flushReadStructs()
offset = 0
}
let readBuff = self.wireguardReadBuffer.advanced(by: Int(offset))
let res = wireguardDatagram.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> wireguard_result in
let dataPtr = ptr.baseAddress?.bindMemory(to: UInt8.self, capacity: Int(maxPacketSize))
return wireguard_read(tunnel, dataPtr, UInt32(wireguardDatagram.count), readBuff, UInt32(maxPacketSize))
}
switch res.op {
case WIREGUARD_DONE:
break
case WRITE_TO_NETWORK:
self.wireguardReadDatagrams.append(Data(bytesNoCopy: readBuff, count: Int(res.size), deallocator: .none))
offset += res.size
flushQueue = true
case WRITE_TO_TUNNEL_IPV4, WRITE_TO_TUNNEL_IPV6:
let family = (res.op == WRITE_TO_TUNNEL_IPV4) ? AF_INET : AF_INET6
self.wireguardReadPackets.append(Data(bytesNoCopy: readBuff, count: Int(res.size), deallocator: .none))
self.wireguardReadPacketProtocols.append(NSNumber(value: family))
offset += res.size
case WIREGUARD_ERROR:
NELogger.e("PacketTunnelProvider: WIREGUARD_ERROR in wireguard_read: \(res.size)")
default:
NELogger.e("PacketTunnelProvider: Unexpected return type: \(res.op)")
}
}
// If wireguard library wants to send prior pending packets to network, handle that case
// and repeat calling wireguard_read() until WIREGUARD_DONE or error is returned.
if flushQueue {
if offset + UInt(maxPacketSize) >= bufferSize {
flushReadStructs()
offset = 0
}
let readBuff = self.wireguardReadBuffer.advanced(by: Int(offset))
flushLoop: while true {
let res = wireguard_read(tunnel, nil, 0, readBuff, UInt32(maxPacketSize))
switch res.op {
case WRITE_TO_NETWORK:
self.wireguardReadDatagrams.append(Data(bytesNoCopy: readBuff, count: Int(res.size), deallocator: .none))
offset += res.size
case WIREGUARD_DONE:
break flushLoop
case WIREGUARD_ERROR:
NELogger.e("PacketTunnelProvider: WIREGUARD_ERROR in repeat wireguard_read: \(res.size)")
break flushLoop
default:
NELogger.e("PacketTunnelProvider: Unexpected return type: \(res.op)")
break flushLoop
}
}
}
flushReadStructs()
}
func flushReadStructs() {
if self.wireguardReadPackets.count > 0 {
self.delegate?.writePackets(self.wireguardReadPackets, withProtocols: self.wireguardReadPacketProtocols)
}
if self.wireguardReadDatagrams.count > 0 {
self.sendDatagrams(datagrams: self.wireguardReadDatagrams)
}
self.wireguardReadPackets.removeAll(keepingCapacity: true)
self.wireguardReadDatagrams.removeAll(keepingCapacity: true)
self.wireguardReadPacketProtocols.removeAll(keepingCapacity: true)
}
func sleep() {
NELogger.v("PacketLoop: sleep")
sessionQueue.sync {
sessionTicker?.invalidate()
sessionTicker = nil
wireguardTicker?.invalidate()
wireguardTicker = nil
if case let SessionState.IsReady(session) = session {
session.cancel()
}
self.session = .NotInitialized
// Clear pending packets
wireguardReadDatagrams = [Data]()
wireguardReadPackets = [Data]()
wireguardReadPacketProtocols = [NSNumber]()
wireguardWriteDatagrams = [Data]()
}
}
func wake() {
NELogger.v("PacketLoop: wake")
// Main thread is where timers works
DispatchQueue.main.sync {
startSessionTicker()
startWireguardTicker()
}
}
func handshakeNow() {
guard let tunnel = tunnel else { return }
let handshake = UnsafeMutablePointer<UInt8>.allocate(capacity: maxPacketSize)
defer { handshake.deallocate() }
let res = wireguard_force_handshake(tunnel, handshake, UInt32(maxPacketSize))
switch res.op {
case WRITE_TO_NETWORK:
let packet = Data(bytesNoCopy: handshake, count: Int(res.size), deallocator: .none)
self.sendDatagrams(datagrams: [packet])
NELogger.v("PacketLoop: force handshake")
case WIREGUARD_DONE:
break
case WIREGUARD_ERROR:
NELogger.e("PacketLoop: WIREGUARD_ERROR in handshakeNow: \(res.size)")
default:
NELogger.e("PacketLoop: Unexpected return type in handshakeNow: \(res.op)")
}
}
func sendDatagrams(datagrams: [Data]) {
if (datagrams.count == 0) {
NELogger.e("PacketLoop: tried to send 0 datagrams")
return
}
// writeMultipleDatagrams says we should wait for it to return before issuing
// another write. Thus we use a serial queue.
sessionQueue.sync {
switch self.session {
case .IsReady(let session):
if session.state != .ready || !session.isViable {
break
}
session.writeMultipleDatagrams(datagrams) { err in
if err != nil {
NELogger.e("PacketLoop: Error sending packets: \(String(describing: err))")
self.session = .IsInvalid(session)
}
}
default:
// No current session
break
}
}
}
}
private func tunnel_log(msg: UnsafePointer<Int8>?) {
guard let msg = msg else { return }
let str = String(cString: msg)
NELogger.v("PacketLoop: Tunnel: \(str)")
}
| mpl-2.0 | 2d0b961fd2c1c3e16f6d6a322c73e133 | 38.917258 | 125 | 0.58247 | 4.814656 | false | false | false | false |
congncif/PagingDataController | Example/Pods/SiFUtilities/Helpers/ValueKeeper.swift | 1 | 1462 | //
// ValueKeeper.swift
// Pods
//
// Created by FOLY on 7/7/17.
//
//
import Foundation
open class ValueKeeper<Value> {
private var value: Value?
private var delay: Double
private var timeout: DispatchTime
private var getValueAsync: ((@escaping (Value?) -> Void) -> Void)
public init(defaultValue: Value? = nil,
delay: Double = 0,
timeout: DispatchTime = DispatchTime.distantFuture,
getValueAsync: @escaping ((@escaping (Value?) -> Void) -> Void)) {
value = defaultValue
self.delay = delay
self.timeout = timeout
self.getValueAsync = getValueAsync
}
open var syncValue: Value? {
var val = value
// let semaphore = DispatchSemaphore(value: 0)
let group = DispatchGroup()
group.enter()
DispatchQueue
.global()
.asyncAfter(deadline: DispatchTime.now() + delay, execute: { [weak self] in
guard let this = self else {
// semaphore.signal()
group.leave()
return
}
this.getValueAsync({ newValue in
val = newValue
// semaphore.signal()
group.leave()
})
})
// _ = semaphore.wait(timeout: timeout)
_ = group.wait(timeout: timeout)
return val
}
}
| mit | f654fd74b8a9e66eae4105189a4990f3 | 27.115385 | 87 | 0.51026 | 4.809211 | false | false | false | false |
tjarratt/Xcode-Better-Refactor-Tools | Fake4SwiftKit/Use Cases/Parse Swift Protocol/Dependencies/XMASParseSelectedProtocolWorkFlow.swift | 3 | 1682 | import Foundation
import SourceKittenFramework
let errorDomain : String = "parse-swift-protocol-domain"
@objc open class XMASParseSelectedProtocolWorkFlow : NSObject {
var swiftParser : XMASSwiftParser
fileprivate(set) open var selectedProtocolOracle : XMASSelectedProtocolOracle
public init(protocolOracle : XMASSelectedProtocolOracle) {
swiftParser = XMASSwiftParser.init()
selectedProtocolOracle = protocolOracle
}
@objc open func selectedProtocolInFile(_ filePath : String!) throws -> ProtocolDeclaration {
guard let sourceFile = File.init(path: filePath) as File! else {
throw NSError.init(domain: errorDomain, code: 5, userInfo: [NSLocalizedFailureReasonErrorKey: "could not read " + filePath])
}
let fileStructure = Structure.init(file: sourceFile)
guard let substructure = fileStructure.dictionary["key.substructure"] as? [SourceKitRepresentable] else {
throw NSError.init(domain: errorDomain, code: 55, userInfo: nil)
}
for item in substructure {
guard let protocolDict = item as? [String: SourceKitRepresentable] else {
continue
}
guard let protocolDecl : ProtocolDeclaration = try swiftParser.parseProtocolDeclaration(protocolDict, filePath: filePath) else {
continue
}
if selectedProtocolOracle.isProtocolSelected(protocolDecl) {
return protocolDecl
}
}
let userInfo = [NSLocalizedFailureReasonErrorKey: "No protocol was selected"]
throw NSError.init(domain: errorDomain, code: 1, userInfo: userInfo)
}
}
| mit | ea9eaeee80458153b0679af4282791b2 | 39.047619 | 140 | 0.681926 | 5.128049 | false | false | false | false |
danielsaidi/KeyboardKit | Tests/KeyboardKitTests/Appearance/KeyboardAction+ButtonTests.swift | 1 | 10273 | //
// KeyboardAction+ButtonTests.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-05-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import KeyboardKit
import SwiftUI
import UIKit
class KeyboardAction_SystemTests: QuickSpec {
override func spec() {
let actions = KeyboardAction.testActions
var context: KeyboardContext!
var expected: [KeyboardAction]! {
didSet {
unexpected = actions
expected.forEach { action in
unexpected.removeAll { $0 == action }
}
}
}
var unexpected: [KeyboardAction]!
beforeEach {
context = MockKeyboardContext()
expected = []
unexpected = []
}
describe("standard button background color") {
func result(for action: KeyboardAction) -> Color {
action.standardButtonBackgroundColor(for: context)
}
it("is clear for some actions") {
expected = [.none]
expected.forEach { expect(result(for: $0)).to(equal(.clear)) }
unexpected.forEach { expect(result(for: $0)).toNot(equal(.clear)) }
}
it("is clear interactable for some actions") {
expected = [.emoji(Emoji("")), .emojiCategory(.smileys)]
expected.forEach { expect(result(for: $0)).to(equal(.clearInteractable)) }
unexpected.forEach { expect(result(for: $0)).toNot(equal(.clearInteractable)) }
}
it("is blue for primary actions") {
expected = [.done, .go, .ok, .search]
expected.forEach { expect(result(for: $0)).to(equal(.blue)) }
unexpected.forEach { expect(result(for: $0)).toNot(equal(.blue)) }
}
it("is standard for all other actions") {
let nonStandard: [KeyboardAction] = [.none, .emoji(Emoji("")), .emojiCategory(.smileys), .done, .go, .ok, .search]
expected = actions.filter { !nonStandard.contains($0) }
expected.forEach {
if $0.isSystemAction {
expect(result(for: $0)).to(equal(Color.standardDarkButton(for: context)))
} else {
expect(result(for: $0)).to(equal(Color.standardButton(for: context)))
}
}
}
}
describe("standard button image") {
func result(for action: KeyboardAction) -> Image? {
action.standardButtonImage
}
it("is defined for some actions") {
expected = [
.backspace,
.command,
.control,
.dictation,
.dismissKeyboard,
.image(description: "", keyboardImageName: "", imageName: ""),
.keyboardType(.email),
.keyboardType(.emojis),
.keyboardType(.images),
.moveCursorBackward,
.moveCursorForward,
.newLine,
.nextKeyboard,
.option,
.settings,
.shift(currentState: .lowercased),
.shift(currentState: .uppercased),
.shift(currentState: .capsLocked),
.systemImage(description: "", keyboardImageName: "", imageName: ""),
.tab
]
expected.forEach { expect(result(for: $0)).toNot(beNil()) }
unexpected.forEach { expect(result(for: $0)).to(beNil()) }
}
}
describe("standard button font") {
it("is defined for all actions") {
actions.forEach {
expect($0.standardButtonFont).to(equal(UIFont.preferredFont(forTextStyle: $0.standardButtonTextStyle)))
}
}
}
describe("standard button font weight") {
func result(for action: KeyboardAction) -> UIFont.Weight? {
action.standardButtonFontWeight
}
it("is light for actions with image and lower cased char") {
expect(result(for: .character("A"))).to(beNil())
expect(result(for: .character("a"))).to(equal(.light))
expect(result(for: .backspace)).to(equal(.light))
}
}
describe("standard button foreground color") {
func result(for action: KeyboardAction) -> Color {
action.standardButtonForegroundColor(for: context)
}
it("is white for primary actions") {
expected = [.done, .go, .ok, .search]
expected.forEach { expect(result(for: $0)).to(equal(.white)) }
unexpected.forEach { expect(result(for: $0)).toNot(equal(.white)) }
}
it("is standard for all other actions") {
let nonStandard: [KeyboardAction] = [.done, .go, .ok, .search]
expected = actions.filter { !nonStandard.contains($0) }
expected.forEach {
expect(result(for: $0)).to(equal(Color.standardButtonTint(for: context)))
}
}
}
describe("standard button shadow color") {
func result(for action: KeyboardAction) -> Color {
action.standardButtonShadowColor(for: context)
}
it("is clear for emoji, not others") {
expected = [.none, .emoji(Emoji(""))]
expected.forEach { expect(result(for: $0)).to(equal(.clear)) }
unexpected.forEach { expect(result(for: $0)).toNot(equal(.clear)) }
}
}
describe("system button text") {
func result(for action: KeyboardAction) -> String? {
action.standardButtonText
}
it("is defined for some actions") {
expect(result(for: .character("A"))).to(equal("A"))
expect(result(for: .emoji(Emoji("🛸")))).to(equal("🛸"))
expect(result(for: .emojiCategory(.animals))).to(equal("🐻"))
expect(result(for: .keyboardType(.alphabetic(.capsLocked)))).to(equal("ABC"))
expect(result(for: .keyboardType(.alphabetic(.lowercased)))).to(equal("ABC"))
expect(result(for: .keyboardType(.alphabetic(.uppercased)))).to(equal("ABC"))
expect(result(for: .keyboardType(.numeric))).to(equal("123"))
expect(result(for: .keyboardType(.symbolic))).to(equal("#+="))
expect(result(for: .keyboardType(.custom("")))).to(beNil())
expect(result(for: .keyboardType(.email))).to(beNil())
expect(result(for: .keyboardType(.images))).to(beNil())
expect(result(for: .none)).to(beNil())
expect(result(for: .backspace)).to(beNil())
expect(result(for: .command)).to(beNil())
expect(result(for: .control)).to(beNil())
expect(result(for: .custom(name: ""))).to(beNil())
expect(result(for: .dictation)).to(beNil())
expect(result(for: .dismissKeyboard)).to(beNil())
expect(result(for: .escape)).to(beNil())
expect(result(for: .function)).to(beNil())
expect(result(for: .moveCursorBackward)).to(beNil())
expect(result(for: .moveCursorForward)).to(beNil())
expect(result(for: .newLine)).to(beNil())
expect(result(for: .nextKeyboard)).to(beNil())
expect(result(for: .option)).to(beNil())
expect(result(for: .shift(currentState: .lowercased))).to(beNil())
expect(result(for: .shift(currentState: .uppercased))).to(beNil())
expect(result(for: .shift(currentState: .capsLocked))).to(beNil())
expect(result(for: .space)).to(beNil())
expect(result(for: .tab)).to(beNil())
}
}
describe("standard button text style") {
func getActions(_ actions: KeyboardAction...) -> [KeyboardAction] { actions }
it("is custom for some actions, but defined for all") {
let expectedTitle = getActions(.emoji(Emoji("")))
let expectedCallout = getActions(.emojiCategory(.smileys))
var expectedBody = actions.filter { $0 == .space || ($0.isSystemAction && $0.standardButtonText != nil) }
expectedBody.append(.character("abc"))
actions.forEach {
if case .emoji = $0 {
expect($0.standardButtonTextStyle).to(equal(.title1))
} else if case .keyboardType(.emojis) = $0 {
expect($0.standardButtonTextStyle).to(equal(.title2))
} else if expectedTitle.contains($0) {
expect($0.standardButtonTextStyle).to(equal(.title1))
} else if expectedCallout.contains($0) {
expect($0.standardButtonTextStyle).to(equal(.callout))
} else if expectedBody.contains($0) {
expect($0.standardButtonTextStyle).to(equal(.body))
} else {
expect($0.standardButtonTextStyle).to(equal(.title2))
}
}
expect(KeyboardAction.character("a").standardButtonTextStyle).to(equal(.title1))
expect(KeyboardAction.character("A").standardButtonTextStyle).to(equal(.title2))
}
}
}
}
| mit | a119cc24937010d534a1deaf4138fc0a | 41.941423 | 130 | 0.493033 | 4.979622 | false | false | false | false |
SuPair/firefox-ios | Client/Frontend/Browser/FaviconHandler.swift | 4 | 4273 | /* 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 Shared
import Storage
import SDWebImage
import Deferred
class FaviconHandler {
static let MaximumFaviconSize = 1 * 1024 * 1024 // 1 MiB file size limit
private var tabObservers: TabObservers!
private let backgroundQueue = OperationQueue()
init() {
self.tabObservers = registerFor(.didLoadPageMetadata, queue: backgroundQueue)
}
deinit {
unregister(tabObservers)
}
func loadFaviconURL(_ faviconURL: String, forTab tab: Tab) -> Deferred<Maybe<(Favicon, Data?)>> {
guard let iconURL = URL(string: faviconURL), let currentURL = tab.url else {
return deferMaybe(FaviconError())
}
let deferred = Deferred<Maybe<(Favicon, Data?)>>()
let manager = SDWebImageManager.shared()
let url = currentURL.absoluteString
let site = Site(url: url, title: "")
let options: SDWebImageOptions = tab.isPrivate ? SDWebImageOptions([.lowPriority, .cacheMemoryOnly]) : SDWebImageOptions([.lowPriority])
var fetch: SDWebImageOperation? = nil
let onProgress: SDWebImageDownloaderProgressBlock = { (receivedSize, expectedSize, _) -> Void in
if receivedSize > FaviconHandler.MaximumFaviconSize || expectedSize > FaviconHandler.MaximumFaviconSize {
fetch?.cancel()
}
}
let onSuccess: (Favicon, Data?) -> Void = { [weak tab] (favicon, data) -> Void in
tab?.favicons.append(favicon)
guard !(tab?.isPrivate ?? true), let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile else {
deferred.fill(Maybe(success: (favicon, data)))
return
}
profile.favicons.addFavicon(favicon, forSite: site) >>> {
deferred.fill(Maybe(success: (favicon, data)))
}
}
let onCompletedSiteFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let urlString = url?.absoluteString else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
let favicon = Favicon(url: urlString, date: Date())
guard let img = img else {
favicon.width = 0
favicon.height = 0
onSuccess(favicon, data)
return
}
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
let onCompletedPageFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let img = img, let urlString = url?.absoluteString else {
// If we failed to download a page-level icon, try getting the domain-level icon
// instead before ultimately failing.
let siteIconURL = currentURL.domainURL.appendingPathComponent("favicon.ico")
fetch = manager.loadImage(with: siteIconURL, options: options, progress: onProgress, completed: onCompletedSiteFavicon)
return
}
let favicon = Favicon(url: urlString, date: Date())
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
fetch = manager.loadImage(with: iconURL, options: options, progress: onProgress, completed: onCompletedPageFavicon)
return deferred
}
}
extension FaviconHandler: TabEventHandler {
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
tab.favicons.removeAll(keepingCapacity: false)
guard let faviconURL = metadata.faviconURL else {
return
}
loadFaviconURL(faviconURL, forTab: tab) >>== { (favicon, data) in
TabEvent.post(.didLoadFavicon(favicon, with: data), for: tab)
}
}
}
class FaviconError: MaybeErrorType {
internal var description: String {
return "No Image Loaded"
}
}
| mpl-2.0 | 4088fb9d51854c3fe83f682eab6200ea | 35.211864 | 150 | 0.614557 | 4.93418 | false | false | false | false |
digoreis/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0065.xcplaygroundpage/Contents.swift | 1 | 24832 | /*:
# A New Model for Collections and Indices
* Proposal: [SE-0065](0065-collections-move-indices.md)
* Authors: [Dmitri Gribenko](https://github.com/gribozavr), [Dave Abrahams](https://github.com/dabrahams), [Maxim Moiseev](https://github.com/moiseev)
* Review Manager: [Chris Lattner](https://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-April/000115.html), [Swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160229/011552.html)
* Pull Request: [apple/swift#2108](https://github.com/apple/swift/pull/2108)
* Previous Revisions: [1](https://github.com/apple/swift-evolution/blob/21fac2e8034e79e4f44c1c8799808fc8cba83395/proposals/0065-collections-move-indices.md), [2](https://github.com/apple/swift-evolution/blob/1a821cf7ccbdf1d7566e9ce2e991bdd835ba3b7d/proposals/0065-collections-move-indices.md), [3](https://github.com/apple/swift-evolution/blob/d44c3e7c189ba39ddf8a914ae8b78b71f88fdcdf/proposals/0065-collections-move-indices.md), [4](https://github.com/apple/swift-evolution/blob/57639040dc08d2f0b16d9bda527db069589b58d1/proposals/0065-collections-move-indices.md)
## Summary
We propose a new model for `Collection`s wherein responsibility for
index traversal is moved from the index to the collection itself. For
example, instead of writing `i.successor()`, one would write
`c.index(after: i)`. We also propose the following changes as a
consequence of the new model:
* A collection's `Index` can be any `Comparable` type.
* The distinction between intervals and ranges disappears, leaving
only ranges.
* A closed range that includes the maximal value of its `Bound` type
is now representable and does not trap.
* Existing “private” in-place index traversal methods are now available
publicly.
## Motivation
In collections that don't support random access, (string views, sets,
dictionaries, trees, etc.) it's very common that deriving one index
value from another requires somehow inspecting the collection's data.
For example, you could represent an index into a hash table as an
offset into the underlying storage, except that one needs to actually
look at *structure* of the hash table to reach the next bucket. In
the current model, supporting `i.successor()` means that the index
must additionally store not just an offset, but a reference to the
collection's structure.
The consequences for performance aren't pretty:
* Code that handles indices has to perform atomic reference counting,
which has significant overhead and can prevent the optimizer from
making other improvements.
* Additional references to a collection's storage block the
library-level copy-on-write optimization: in-place mutation of
uniquely-referenced data. A live index makes underlying storage
non-uniquely referenced, forcing unnecessary copies when the
collection is mutated. In the standard library, `Dictionary` and
`Set` use a double-indirection trick to work around this issue.
Unfortunately, even this trick is not a solution, because (as we
have recently realized) it isn't threadsafe. [^1]
By giving responsibility for traversal to the collection, we ensure
that operations that need the collection's structure always have it,
without the costs of holding references in indices.
## Other Benefits
Although this change is primarily motivated by performance, it has
other significant benefits:
* Simplifies implementation of non-trivial indices.
* Allows us to eliminate the `Range`/`Interval` distinction.
* Making traversal a direct property of the `Collection` protocol,
rather than its associated `Index` type, is closer to most peoples'
mental model for collections, and simplifies the writing of many
generic constraints.
* Makes it feasible to fix existing concurrency issues in `Set` and
`Dictionary` indices.
* Allows `String` views to share a single index type, letting us
eliminate the need for cumbersome index conversion functions (not
part of this proposal, but planned).
## Out of Scope
This proposal intentionally does not:
* Expand the set of concrete collections provided by the standard
library.
* Expand the set of collection protocols to provide functionality
beyond what is already provided (for example, protocols for sorted
collections, queues etc.) Discussing how other concrete collections
fit into the current protocol hierarchy is in scope, though.
## Limitations of the Model
Ideally, our collection model would allow us to implement every
interesting data structure with memory safety, optimal performance,
value semantics, and a variety of other useful properties such as
minimal invalidation of indexes upon mutation. In practice, these
goals and the Swift language model interact in complicated ways,
preventing some designs altogether, and suggesting a variety of
implementation strategies for others that can be selected based on
one's priorities. We've done some in-depth investigation of these
implications, but presenting and explaining them is well beyond the
scope of this proposal.
We can, however, be fairly sure that this change does not regress our
ability to build any Collections that could have been built in Swift
2.2. After all, it is still *possible* to implement indices that store
references and have the old traversal methods (the collection's
traversal methods would simply forward to those of the index), so we
haven't lost the ability to express anything.
## Overview of Type And Protocol Changes
This section covers the proposed structural changes to the library at
a high level. Details such as protocols introduced purely to work
around compiler limitations (e.g. `Indexable` or `IndexableBase`) have
been omitted. For a complete view of the code
and documentation changes implementing this proposal, please see this
[pull request](https://github.com/apple/swift/pull/2108).
### Collection Protocol Hierarchy
In the proposed model, indices don't have any requirements beyond
`Comparable`, so the `ForwardIndex`, `BidirectionalIndex`, and
`RandomAccessIndex` protocols are eliminated. Instead, we introduce
`BidirectionalCollection` and `RandomAccessCollection` to provide the
same traversal distinctions, as shown here:
```
+--------+
|Sequence|
+---+----+
|
+----+-----+
|Collection|
+----+-----+
|
+--------------+-------------+
| | |
| +--------+--------+ |
| |MutableCollection| |
| +-----------------+ |
| |
+---------+-------------+ +---------+----------------+
|BidirectionalCollection| |RangeReplaceableCollection|
+---------+-------------+ +--------------------------+
|
+--------+-------------+
|RandomAccessCollection|
+----------------------+
```
These protocols compose naturally with the existing protocols
`MutableCollection` and `RangeReplaceableCollection` to describe a
collection's capabilities, e.g.
```swift
struct Array<Element>
: RandomAccessCollection,
MutableCollection,
RangeReplaceableCollection { ... }
struct UnicodeScalarView : BidirectionalCollection { ... }
```
### Range Types
The proposal adds several new types to support ranges:
* The old `Range<T>`, `ClosedInterval<T>`, and
`OpenInterval<T>` are replaced with four new generic range types:
* Two for general ranges (whose bounds are `Comparable`): `Range<T>`
and `ClosedRange<T>`. Having a separate `ClosedRange` type allows
us to address the vexing inability of the old `Range` to represent
a range containing the maximal value of its bound.
* Two for ranges that additionally conform to
`RandomAccessCollection` (requiring bounds that are `Strideable`
with `Stride` conforming to `Integer`): `CountableRange<T>` and
`CountableClosedRange<T>`. These types can be folded into
`Range` and `ClosedRange` when Swift acquires conditional
conformance capability.
### The Associated `Indices` Type
The following code iterates over the indices of all elements in
`collection`:
```swift
for index in collection.indices { ... }
```
In Swift 2, `collection.indices` returned a `Range<Index>`, but
because a range is a simple pair of indices and indices can no longer
be advanced on their own, `Range<Index>` is no longer iterable.
In order to keep code like the above working, `Collection` has
acquired an associated `Indices` type that is always iterable, and
three generic types were introduced to provide a default `Indices` for
each `Collection` traversal category: `DefaultIndices<C>`,
`DefaultBidirectionalIndices<C>`, and `DefaultRandomAccessIndices<C>`.
These types store the underlying collection as a means of traversal.
Collections like `Array` whose `Indices` don't need the collection
simply use `typealias Indices = CountableRange<Index>`.
### Expanded Default Slice Types
Because Swift doesn't support conditional protocol conformances and
the three traversal distinctions have been moved into the `Collection`
hierarchy, the four generic types `Slice`, `MutableSlice`,
`RangeReplaceableSlice`, and `MutableRangeReplaceableSlice` have
become twelve, with the addition of variations such as
`RangeReplaceableBidirectionalSlice`.
### The `Comparable` Requirement on Indices
In this model indices store the minimal amount of information required
to describe an element's position. Usually an index can be
represented with one or two `Int`s that efficiently encode the path to
the element from the root of a data structure. Since one is free to
choose the encoding of the “path”, we think it is possible to choose
it in such a way that indices are cheaply comparable. That has been
the case for all of the indices required to implement the standard
library, and a few others we investigated while researching this
change.
It's worth noting that this requirement isn't strictly
necessary. Without it, though, indices would have no requirements
beyond `Equatable`, and creation of a `Range<T>` would have to be
allowed for any `T` conforming to `Equatable`. As a consequence, most
interesting range operations, such as containment checks, would be
unavailable unless `T` were also `Comparable`, and we'd be unable to
provide bounds-checking in the general case.
That said, the requirement has real benefits. For example, it allows
us to support distance measurement between arbitrary indices, even in
collections without random access traversal. In the old model,
`x.distance(to: y)` for these collections had the undetectable
precondition that `x` precede `y`, with unpredictable consequences for
violation in the general case.
## Detailed API Changes
This section describes changes to methods, properties, and associated
types at a high level. Details related to working around compiler
limitations have been omitted. For a complete view of the code
and documentation changes implementing this proposal, please see this
[pull request](https://github.com/apple/swift/pull/2108).
### `Collection`s
The following APIs were added:
```swift
protocol Collection {
...
/// A type that can represent the number of steps between pairs of
/// `Index` values where one value is reachable from the other.
///
/// Reachability is defined by the ability to produce one value from
/// the other via zero or more applications of `index(after: _)`.
associatedtype IndexDistance : SignedInteger = Int
/// A collection type whose elements are the indices of `self` that
/// are valid for subscripting, in ascending order.
associatedtype Indices : Collection = DefaultIndices<Self>
/// The indices that are valid for subscripting `self`, in ascending order.
///
/// - Note: `indices` can hold a strong reference to the collection itself,
/// causing the collection to be non-uniquely referenced. If you need to
/// mutate the collection while iterating over its indices, use the
/// `index(after: _)` method starting with `startIndex` to produce indices
/// instead.
///
/// ```
/// var c = [10, 20, 30, 40, 50]
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == [2, 4, 6, 8, 10]
/// ```
var indices: Indices { get }
/// Returns the position immediately after `i`.
///
/// - Precondition: `(startIndex..<endIndex).contains(i)`
@warn_unused_result
func index(after i: Index) -> Index
/// Replaces `i` with its successor.
func formIndex(after i: inout Index)
/// Returns the result of advancing `i` by `n` positions.
///
/// - Returns:
/// - If `n > 0`, the `n`th index after `i`.
/// - If `n < 0`, the `n`th index before `i`.
/// - Otherwise, `i` unmodified.
///
/// - Precondition: `n >= 0` unless `Self` conforms to
/// `BidirectionalCollection`.
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
///
/// - Complexity:
/// - O(1) if `Self` conforms to `RandomAccessCollection`.
/// - O(`abs(n)`) otherwise.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns the result of advancing `i` by `n` positions, or until it
/// equals `limit`.
///
/// - Returns:
/// - If `n > 0`, the `n`th index after `i` or `limit`, whichever
/// is reached first.
/// - If `n < 0`, the `n`th index before `i` or `limit`, whichever
/// is reached first.
/// - Otherwise, `i` unmodified.
///
/// - Precondition: `n >= 0` unless `Self` conforms to
/// `BidirectionalCollection`.
///
/// - Complexity:
/// - O(1) if `Self` conforms to `RandomAccessCollection`.
/// - O(`abs(n)`) otherwise.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index) -> Index
/// Advances `i` by `n` positions.
///
/// - Precondition: `n >= 0` unless `Self` conforms to
/// `BidirectionalCollection`.
/// - Precondition:
/// - If `n > 0`, `n <= self.distance(from: i, to: self.endIndex)`
/// - If `n < 0`, `n >= self.distance(from: i, to: self.startIndex)`
///
/// - Complexity:
/// - O(1) if `Self` conforms to `RandomAccessCollection`.
/// - O(`abs(n)`) otherwise.
func formIndex(_ i: inout Index, offsetBy n: IndexDistance)
/// Advances `i` by `n` positions, or until it equals `limit`.
///
/// - Precondition: `n >= 0` unless `Self` conforms to
/// `BidirectionalCollection`.
///
/// - Complexity:
/// - O(1) if `Self` conforms to `RandomAccessCollection`.
/// - O(`abs(n)`) otherwise.
func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index)
/// Returns the distance between `start` and `end`.
///
/// - Precondition: `start <= end` unless `Self` conforms to
/// `BidirectionalCollection`.
/// - Complexity:
/// - O(1) if `Self` conforms to `RandomAccessCollection`.
/// - O(`n`) otherwise, where `n` is the method's result.
func distance(from start: Index, to end: Index) -> IndexDistance
}
protocol BidirectionalCollection {
/// Returns the position immediately preceding `i`.
///
/// - Precondition: `i > startIndex && i <= endIndex`
func index(before i: Index) -> Index
/// Replaces `i` with its predecessor.
///
/// - Precondition: `i > startIndex && i <= endIndex`
func formIndex(before i: inout Index)
}
```
Note:
* The `formIndex` overloads essentially enshrine the previously-hidden
`_successorInPlace` et al., which can be important for performance
when handling the rare heavyweight index type such as `AnyIndex`.
* `RandomAccessCollection` does not add any *syntactic* requirements
beyond those of `BidirectionalCollection`. Instead, it places
tighter performance bounds on operations such as `c.index(i,
offsetBy: n)` (O(1) instead of O(`n`)).
## `Range`s
The four range [Range Types](#range-types) share the common interface
shown below:
```swift
public struct Range<Bound: Comparable> : Equatable {
/// Creates an instance with the given bounds.
///
/// - Note: As this initializer does not check its precondition, it
/// should be used as an optimization only, when one is absolutely
/// certain that `lower <= upper`. In general, the `..<` and `...`
/// operators are to be preferred for forming ranges.
///
/// - Precondition: `lower <= upper`
init(uncheckedBounds: (lower: Bound, upper: Bound))
/// Returns `true` if the range contains the `value`.
func contains(_ value: Bound) -> Bool
/// Returns `true` iff `self` and `other` contain a value in common.
func overlaps(_ other: Self) -> Bool
/// Returns `true` iff `self.contains(x)` is `false` for all values of `x`.
var isEmpty: Bool { get }
/// The range's lower bound.
var lowerBound: Bound { get }
/// The range's upper bound.
var upperBound: Bound { get }
/// Returns `self` clamped to `limits`.
///
/// The bounds of the result, even if it is empty, are always
/// limited to the bounds of `limits`.
func clamped(to limits: Self) -> Self
}
```
In addition, every implementable lossless conversion between range
types is provided as a label-less `init` with one argument:
```swift
let a = 1..<10
let b = ClosedRange(a) // <=== Here
```
Note in particular:
* In `Range<T>`, `T` is `Comparable` rather than an index
type that can be advanced, so a generalized range is no longer a
`Collection`, and `startIndex`/`endIndex` have become
`lowerBound`/`upperBound`.
* The semantic order of `Interval`'s `clamp` method, which was
unclear at its use-site, has been inverted and updated with a
preposition for clarity.
## Downsides
The proposed approach has several disadvantages, which we explore here
in the interest of full disclosure:
* In Swift 2, `RandomAccessIndex` has operations like `+` that provide
easy access to arbitrary position offsets in some collections. That
could also be seen as discouragement from trying to do random access
operations with less-refined index protocols, because in those cases
one has to resort to constructs like `i.advancedBy(n)`. In this
proposal, there is only `c.index(i, offsetBy: n)`, which makes
random access equally (in)convenient for all collections, and there
is no particular syntactic penalty for doing things that might turn
out to be inefficient.
* Index movement is more complex in principle, since it now involves
not only the index, but the collection as well. The impact of this
complexity is limited somewhat because it's very common that code
moving indices occurs in a method of the collection type, where
“implicit `self`” kicks in. The net result is that index
manipulations end up looking like free function calls:
```swift
let j = index(after: i) // self.index(after: i)
let k = index(j, offsetBy: 5) // self.index(j, offsetBy: 5)
```
* The
[new index manipulation methods](https://github.com/apple/swift/blob/swift-3-indexing-model/stdlib/public/core/Collection.swift#L135)
increase the API surface area of `Collection`, which is already
quite large since algorithms are implemented as extensions.
* Because Swift is unable to express conditional protocol
conformances, implementing this change has required us to create a
great deal of complexity in the standard library API. Aside from
the two excess “`Countable`” range types, there are new overloads
for slicing and twelve distinct slice types that capture all the
combinations of traversal, mutability, and range-replaceability.
While these costs are probably temporary, they are very real in the
meantime.
* The API complexity mentioned above stresses the type checker,
requiring
[several](https://github.com/apple/swift/commit/1a875cb922fa0c98d51689002df8e202993db2d3)
[changes](https://github.com/apple/swift/commit/6c56af5c1bc319825872a25041ec33ab0092db05)
just to get our test code to type-check in reasonable time. Again,
an ostensibly temporary—but still real—cost.
## Impact on existing code
Code that **does not need to change**:
* Code that works with `Array`, `ArraySlice`, `ContiguousArray`, and
their indices.
* Code that operates on arbitrary collections and indices (on concrete
instances or in generic context), but does no index traversal.
* Iteration over collections' indices with `c.indices` does not change.
* APIs of high-level collection algorithms don't change, even for
algorithms that accept indices as parameters or return indices (e.g.,
`index(of:)`, `min()`, `sort()`, `prefix()`, `prefix(upTo:)` etc.)
Code that **needs to change**:
* Code that advances indices (`i.successor()`, `i.predecessor()`,
`i.advanced(by:)` etc.) or calculates distances between indices
(`i.distance(to:)`) now needs to call a method on the collection
instead.
```swift
// Before:
var i = c.index { $0 % 2 == 0 }
let j = i.successor()
print(c[j])
// After:
var i = c.index { $0 % 2 == 0 } // No change in algorithm API.
let j = c.index(after: i) // Advancing an index requires a collection instance.
print(c[j]) // No change in subscripting.
```
The transformation from `i.successor()` to `c.index(after: i)` is
non-trivial. Performing it correctly requires knowing how to get
the corresponding collection. In general, it is not possible to
perform this migration automatically. A very sophisticated migrator
could handle some easy cases.
* Custom collection implementations need to change. A simple fix would
be to just move the methods from indices to collections to satisfy
new protocol requirements. This is a more or less mechanical fix that
does not require design work. This fix would allow the code to
compile and run.
In order to take advantage of performance improvements in
the new model, and remove reference-counted stored properties from
indices, the representation of the index might need to be redesigned.
Implementing custom collections, as compared to using collections, is
a niche case. We believe that for custom collection types it is
sufficient to provide clear steps for manual migration that don't
require a redesign. Implementing this in an automated migrator might
be possible, but would be a heroic migration for a rare case.
## Implementation Status
[This pull request](https://github.com/apple/swift/pull/2108) contains
a complete implementation.
## Alternatives considered
We considered index-less models, for example, [D's
std.range](https://dlang.org/library/std/range.html) (see also [On
Iteration by Andrei
Alexandrescu](http://www.informit.com/articles/printerfriendly/1407357)).
Ranges work well for reference-typed collections, but it is not clear
how to adjust the concept of D's range (similar to `Slice` in Swift) for
mutable value-typed collections. In D, you process a collection by
repeatedly slicing off elements. Once you have found an element that
you would like to mutate, it is not clear how to actually change the
original collection, if the collection and its slice are value types.
----
[^1]: `Dictionary` and `Set` use a double-indirection trick to avoid
disturbing the reference count of the storage with indices.
```
+--+ class struct
|RC|---------+ +-----------------+
+--+ Storage |<---------| DictionaryIndex |
| | | value |
+----------+ +-----------------+
^
+--+ | class struct
|RC|-------------+ +------------+
+--+ Indirection |<-------| Dictionary |
| ("owner") | | value |
+--------------+ +------------+
```
Instances of `Dictionary` point to an indirection, while
instances of `DictionaryIndex` point to the storage itself.
This allows us to have two separate reference counts. One of
the refcounts tracks just the live `Dictionary` instances, which
allows us to perform precise uniqueness checks.
The issue that we were previously unaware of is that this scheme
is not thread-safe. When uniquely-referenced storage is being
mutated in place, indices can be concurrently being incremented
(on a different thread). This would be a read/write data race.
Fixing this data race (to provide memory safety) would require
locking dictionary storage on every access, which would be an
unacceptable performance penalty.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | b3a234cc37f9da8d140121f7a9ba11fd | 39.876442 | 564 | 0.704095 | 4.154026 | false | false | false | false |
tardieu/swift | test/stdlib/MixedTypeArithmeticsDiagnostics.swift | 8 | 1046 | //===--- MixedTypeArithmeticsDiagnostics.swift ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-typecheck-verify-swift
func mixedTypeArithemtics() {
_ = (42 as Int64) + (0 as Int) // expected-warning {{'+' is deprecated:}}
do {
var x = Int8()
x += (42 as Int) // expected-warning {{'+=' is deprecated:}}
}
_ = (42 as Int32) - (0 as Int) // expected-warning {{'-' is deprecated:}}
do {
var x = Int16()
x -= (42 as Int) // expected-warning {{'-=' is deprecated:}}
}
// With Int on both sides should NOT result in warning
do {
var x = Int()
x += (42 as Int)
}
}
| apache-2.0 | 76c03e3fa2b4b4f27daa44c10ef25f0d | 28.885714 | 80 | 0.563098 | 3.962121 | false | false | false | false |
elainekmao/yelp-app | Yelp/YelpClient.swift | 1 | 3173 | //
// YelpClient.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2014 Timothy Lee. All rights reserved.
//
import UIKit
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA"
let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ"
let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV"
let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y"
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
class var sharedInstance : YelpClient {
struct Static {
static var token : dispatch_once_t = 0
static var instance : YelpClient? = nil
}
dispatch_once(&Static.token) {
Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
}
return Static.instance!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
var baseUrl = NSURL(string: "http://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
var token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(term, sort: nil, categories: nil, deals: nil, completion: completion)
}
func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term, "ll": "37.785771,-122.406165"]
if sort != nil {
parameters["sort"] = sort!.rawValue
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = ",".join(categories!)
}
if deals != nil {
parameters["deals_filter"] = deals!
}
println(parameters)
return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
var dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
completion(nil, error)
})
}
}
| gpl-2.0 | d6d1d3428fe9e8c5a70f34ba3b976bba | 36.77381 | 168 | 0.641034 | 4.264785 | false | false | false | false |
xmartlabs/Bender | Sources/Layers/BGRAtoRGBA.swift | 1 | 1927 | //
// BGRAtoRGBA.swift
// Bender
//
// Created by Mathias Claassen on 5/8/17.
//
//
import MetalPerformanceShaders
import MetalPerformanceShadersProxy
/// Transforms an image from RGBA to BGRA. (You can use it the other way around too)
open class BGRAtoRGBA: NetworkLayer {
// Custom kernels
let pipelineBGRAtoRGBA: MTLComputePipelineState!
public override init(id: String? = nil) {
// Load custom metal kernels
pipelineBGRAtoRGBA = MetalShaderManager.shared.getFunction(name: "bgra_to_rgba", in: Bundle(for: BGRAtoRGBA.self))
super.init(id: id)
}
open override func validate() {
let incoming = getIncoming()
assert(incoming.count == 1, "BGRAtoRGBA supports one input, not \(incoming.count)")
}
open override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) {
super.initialize(network: network, device: device, temporaryImage: temporaryImage)
let incoming = getIncoming()
outputSize = incoming[0].outputSize
createOutputs(size: outputSize, temporary: temporaryImage)
}
open override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) {
let input = getIncoming()[0].getOutput(index: index)
let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index)
let encoder = commandBuffer.makeComputeCommandEncoder()!
encoder.label = "BGRA to RGBA encoder"
encoder.setComputePipelineState(pipelineBGRAtoRGBA)
encoder.setTexture(input.texture, index: 0)
encoder.setTexture(output.texture, index: 1)
let threadsPerGroups = MTLSizeMake(32, 8, 1)
let threadGroups = output.texture.threadGrid(threadGroup: threadsPerGroups)
encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups)
encoder.endEncoding()
input.setRead()
}
}
| mit | 1d398f0bae0f35ef89d58172169b8c1c | 36.057692 | 122 | 0.701609 | 4.450346 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Model/Objects/Mask.swift | 3 | 2375 | //
// Mask.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
// MARK: - MaskMode
enum MaskMode: String, Codable {
case add = "a"
case subtract = "s"
case intersect = "i"
case lighten = "l"
case darken = "d"
case difference = "f"
case none = "n"
}
// MARK: - Mask
final class Mask: Codable, DictionaryInitializable {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Mask.CodingKeys.self)
mode = try container.decodeIfPresent(MaskMode.self, forKey: .mode) ?? .add
opacity = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .opacity) ?? KeyframeGroup(LottieVector1D(100))
shape = try container.decode(KeyframeGroup<BezierPath>.self, forKey: .shape)
inverted = try container.decodeIfPresent(Bool.self, forKey: .inverted) ?? false
expansion = try container
.decodeIfPresent(KeyframeGroup<LottieVector1D>.self, forKey: .expansion) ?? KeyframeGroup(LottieVector1D(0))
}
init(dictionary: [String: Any]) throws {
if
let modeRawType = dictionary[CodingKeys.mode.rawValue] as? String,
let mode = MaskMode(rawValue: modeRawType)
{
self.mode = mode
} else {
mode = .add
}
if let opacityDictionary = dictionary[CodingKeys.opacity.rawValue] as? [String: Any] {
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
} else {
opacity = KeyframeGroup(LottieVector1D(100))
}
let shapeDictionary: [String: Any] = try dictionary.value(for: CodingKeys.shape)
shape = try KeyframeGroup<BezierPath>(dictionary: shapeDictionary)
inverted = (try? dictionary.value(for: CodingKeys.inverted)) ?? false
if let expansionDictionary = dictionary[CodingKeys.expansion.rawValue] as? [String: Any] {
expansion = try KeyframeGroup<LottieVector1D>(dictionary: expansionDictionary)
} else {
expansion = KeyframeGroup(LottieVector1D(0))
}
}
// MARK: Internal
enum CodingKeys: String, CodingKey {
case mode
case opacity = "o"
case inverted = "inv"
case shape = "pt"
case expansion = "x"
}
let mode: MaskMode
let opacity: KeyframeGroup<LottieVector1D>
let shape: KeyframeGroup<BezierPath>
let inverted: Bool
let expansion: KeyframeGroup<LottieVector1D>
}
| apache-2.0 | 5b4e0421f4a31a060fd8a08a73d2e593 | 27.963415 | 114 | 0.691789 | 3.932119 | false | false | false | false |
nghiaphunguyen/NKit | NKit/Source/Layout/NKConstraints.swift | 1 | 5452 | //
// NKConstraints.swift
// NKit
//
// Created by Nghia Nguyen on 9/28/16.
// Copyright © 2016 Nghia Nguyen. All rights reserved.
//
import UIKit
public struct NKConstraintItem {
let view: UIView
let attribute: NSLayoutConstraint.Attribute
public func constraintWithRelativeItem(right: NKConstraintRelativeItem, relation: NSLayoutConstraint.Relation) -> NSLayoutConstraint {
self.view.translatesAutoresizingMaskIntoConstraints = false
right.item?.view.translatesAutoresizingMaskIntoConstraints = false
let attribute = right.item?.attribute ?? self.attribute
return NSLayoutConstraint(item: self.view, attribute: self.attribute, relatedBy: relation, toItem: right.item?.view, attribute: attribute, multiplier: right.multiple, constant: right.constant)
}
}
public struct NKConstraintRelativeItem {
let item: NKConstraintItem?
let multiple: CGFloat
let constant: CGFloat
let priority: UInt
public init(item: NKConstraintItem? = nil, multiple: CGFloat = 1, constant: CGFloat = 0, priority: UInt = 1000) {
self.item = item
self.multiple = multiple
self.constant = constant
self.priority = priority
}
}
public func +(left: NKConstraintItem, right: CGFloat) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: left, constant: right)
}
public func -(left: NKConstraintItem, right: CGFloat) -> NKConstraintRelativeItem {
return left + (-right)
}
public func *(left: NKConstraintItem, right: CGFloat) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: left, multiple: right, constant: 0)
}
public func /(left: NKConstraintItem, right: CGFloat) -> NKConstraintRelativeItem {
return left * (1 / right)
}
public func +(left: NKConstraintRelativeItem, right: CGFloat) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: left.item, multiple: left.multiple, constant: right + left.constant)
}
public func -(left: NKConstraintRelativeItem, right: CGFloat) -> NKConstraintRelativeItem {
return left + (-right)
}
public func *(left: NKConstraintRelativeItem, right: CGFloat) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: left.item, multiple: right * left.multiple, constant: left.constant)
}
public func /(left: NKConstraintRelativeItem, right: CGFloat) -> NKConstraintRelativeItem {
return left * (1 / right)
}
public func ~(left: NKConstraintRelativeItem, right: UInt) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: left.item, multiple: left.multiple, constant: left.constant, priority: right)
}
public func ~(left: CGFloat, right: UInt) -> NKConstraintRelativeItem {
return NKConstraintRelativeItem(item: nil, constant: left, priority: right)
}
@discardableResult public func ==(left: NKConstraintItem, right: NKConstraintItem) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(item: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .equal)
result.isActive = true
return result
}
@discardableResult public func >=(left: NKConstraintItem, right: NKConstraintItem) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(item: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .greaterThanOrEqual)
result.isActive = true
return result
}
@discardableResult public func <=(left: NKConstraintItem, right: NKConstraintItem) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(item: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .lessThanOrEqual)
result.isActive = true
return result
}
@discardableResult public func ==(left: NKConstraintItem, right: NKConstraintRelativeItem) -> NSLayoutConstraint {
let result = left.constraintWithRelativeItem(right: right, relation: .equal)
result.isActive = true
return result
}
@discardableResult public func >=(left: NKConstraintItem, right: NKConstraintRelativeItem) -> NSLayoutConstraint {
let result = left.constraintWithRelativeItem(right: right, relation: .greaterThanOrEqual)
result.isActive = true
return result
}
@discardableResult public func <=(left: NKConstraintItem, right: NKConstraintRelativeItem) -> NSLayoutConstraint {
let result = left.constraintWithRelativeItem(right: right, relation: .lessThanOrEqual)
result.isActive = true
return result
}
@discardableResult public func ==(left: NKConstraintItem, right: CGFloat) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(constant: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .equal)
result.isActive = true
return result
}
@discardableResult public func >=(left: NKConstraintItem, right: CGFloat) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(constant: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .greaterThanOrEqual)
result.isActive = true
return result
}
@discardableResult public func <=(left: NKConstraintItem, right: CGFloat) -> NSLayoutConstraint {
let relativeItem = NKConstraintRelativeItem(constant: right)
let result = left.constraintWithRelativeItem(right: relativeItem, relation: .lessThanOrEqual)
result.isActive = true
return result
}
| mit | acb5f1c2d37c8b906b5728a366a56dca | 37.118881 | 200 | 0.747019 | 4.438925 | false | false | false | false |
WeltN24/SwiftFilePath | SwiftFilePath/PathExtensionFile.swift | 1 | 3024 | //
// File.swift
// SwiftFilePath
//
// Created by nori0620 on 2015/01/08.
// Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved.
//
// Add File Behavior to Path by extension
extension Path {
public var ext:String {
return (path_string as NSString).pathExtension
}
public func touch() -> Result<Path,Error> {
assert(!self.isDir,"Can NOT touch to dir")
return self.exists
? self.updateModificationDate()
: self.createEmptyFile()
}
public func updateModificationDate(_ date: Date = Date() ) -> Result<Path,Error>{
var error: Error?
let result: Bool
do {
try fileManager.setAttributes(
[FileAttributeKey.modificationDate: date],
ofItemAtPath: path_string)
result = true
} catch let error1 {
error = error1
result = false
}
return result
? Result(success: self)
: Result(failure: error!)
}
private func createEmptyFile() -> Result<Path,Error>{
return self.writeString("")
}
// MARK: - read/write String
public func readString() -> String? {
assert(!self.isDir,"Can NOT read data from dir")
var readError:Error?
let read: String?
do {
read = try String(contentsOfFile: path_string,
encoding: String.Encoding.utf8)
} catch let error {
readError = error
read = nil
}
if let error = readError {
print("readError< \(error.localizedDescription) >")
}
return read
}
public func writeString(_ string:String) -> Result<Path,Error> {
assert(!self.isDir,"Can NOT write data from dir")
var error: Error?
let result: Bool
do {
try string.write(toFile: path_string,
atomically:true,
encoding: String.Encoding.utf8)
result = true
} catch let error1 {
error = error1
result = false
}
return result
? Result(success: self)
: Result(failure: error!)
}
// MARK: - read/write NSData
public func readData() -> Data? {
assert(!self.isDir,"Can NOT read data from dir")
return (try? Data(contentsOf: URL(fileURLWithPath: path_string)))
}
public func writeData(_ data:Data) -> Result<Path,Error> {
assert(!self.isDir,"Can NOT write data from dir")
var error: Error?
let result: Bool
do {
try data.write(to: URL(fileURLWithPath: path_string), options:.atomic)
result = true
} catch let error1 {
error = error1
result = false
}
return result
? Result(success: self)
: Result(failure: error!)
}
}
| mit | 5888af2c5a8aed67ef96dd9d666e0259 | 27.509434 | 85 | 0.524487 | 4.670788 | false | false | false | false |
10686142/eChance | eChance/RegisterVC.swift | 1 | 6818 | //
// RegisterVC.swift
// Iraffle
//
// Created by Vasco Meerman on 03/05/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import Alamofire
import UIKit
class RegisterVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// Outlets
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var genderTextField: UITextField!
@IBOutlet weak var dateOfBirthTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
// Models
let user = UsersModel()
let date = TimerCall()
let datePicker = UIDatePicker()
// Constants and Variables
let defaults = UserDefaults.standard
let URL_USER_REGISTER = "https://echance.nl/SwiftToSQL_API/v1/register.php"
var dateSend: String!
var pickOption = ["", "Man", "Vrouw", "Onzijdig"]
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
pickerView.delegate = self
genderTextField.inputView = pickerView
createGenderPicker()
createDatePicker()
}
func createGenderPicker() {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneGenderPickerPressed))
toolbar.setItems([doneButton], animated: false)
genderTextField.inputAccessoryView = toolbar
}
func createDatePicker() {
// Format datepicker to D M Y
datePicker.locale = NSLocale.init(localeIdentifier: "en_GB") as Locale
//Format for picker to date with years
datePicker.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePickerPressed))
toolbar.setItems([doneButton], animated: false)
dateOfBirthTextField.inputAccessoryView = toolbar
dateOfBirthTextField.inputView = datePicker
}
func doneGenderPickerPressed() {
self.view.endEditing(true)
}
func donePickerPressed() {
// format picker output to date with years
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "dd-MM-yyyy"
dateOfBirthTextField.text = dateFormatter.string(from: datePicker.date)
let dateCheck = datePicker.date
let eligebleAge = date.checkAgeUnder18(date: dateCheck)
if eligebleAge == true {
let dateFormatterSend = DateFormatter()
dateFormatterSend.dateStyle = .short
dateFormatterSend.timeStyle = .none
dateFormatterSend.dateFormat = "yyyy-MM-dd"
dateSend = dateFormatterSend.string(from: datePicker.date)
self.view.endEditing(true)
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Je moet 18 jaar of ouder zijn om je in te schrijven..")
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genderTextField.text = pickOption[row]
}
@IBAction func submitPressed(_ sender: Any) {
let userFName = firstNameTextField.text
let userLName = lastNameTextField.text
let userBDate = dateSend
let userGender = genderTextField.text
let userPassword = passwordTextField.text
let confirmPassword = confirmPasswordTextField.text
let userEmail = emailTextField.text
if userFName != "" && userLName != "" && userBDate != "" && userGender != "" && userPassword != "" && confirmPassword != "" && userEmail != ""{
let parameters: Parameters=[
"first_name":userFName!,
"last_name":userLName!,
"password":userPassword!,
"birth_date":userBDate!,
"email":userEmail!,
"gender":userGender!
]
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
if let result = response.result.value {
let jsonData = result as! NSDictionary
let message = jsonData.value(forKey: "message") as! String?
if message == "User already exist"{
self.registerErrorAlert(title: "Oeps!", message: "Deze email is al een keer geregistreerd")
self.emailTextField.text = ""
}
else{
// Save the userID from the registered user
let uid = jsonData.value(forKey: "uid") as! Int?
let userDict = ["userID": uid!, "userFN": userFName!, "userLN": userLName!, "userBD": userBDate!, "userE": userEmail!, "userP": userPassword!, "userG": userGender!] as [String : Any]
self.defaults.set(userDict, forKey: "user")
self.defaults.set("1", forKey: "fromRegister")
self.performSegue(withIdentifier: "toExplanation", sender: nil)
}
}
}
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Zorg dat alle velden ingevuld zijn;)")
}
}
func registerErrorAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
| mit | e6a7fb16b37f019b10c1120f6f1a4056 | 36.048913 | 210 | 0.580167 | 5.207792 | false | false | false | false |
trill-lang/LLVMSwift | Sources/LLVM/ObjectFile.swift | 1 | 13393 | #if SWIFT_PACKAGE
import cllvm
import llvmshims
#endif
/// Enumerates the possible failures that can be thrown initializing
/// a MemoryBuffer.
public enum BinaryFileError: Error {
/// The MemoryBuffer failed to be initialized for a specific reason.
case couldNotCreate(String)
}
/// A `BinaryFile` is a (mostly) architecture-independent representation of an
/// in-memory image file.
public class BinaryFile {
let llvm: LLVMBinaryRef
/// The backing buffer for this binary file.
public let buffer: MemoryBuffer
/// The kind of this binary file.
public let kind: Kind
/// The kinds of binary files known to LLVM.
public enum Kind {
/// A static library archive file.
case archive
/// A universal Mach-O binary with multiple component object files for
/// different architectures.
case machOUniversalBinary
/// A COFF imports table file.
case coffImportFile
/// LLVM IR.
case ir
/// A Windows resource file.
case winRes
/// A COFF file.
case coff
/// A 32-bit little-endian ELF binary.
case elf32L
/// A 32-bit big-endian ELF binary.
case elf32B
/// A 64-bit little-endian ELF binary.
case elf64L
/// A 64-bit big-endian ELF binary.
case elf64B
/// A 32-bit little-endian Mach-O binary.
case machO32L
/// A 32-bit big-endian Mach-O binary.
case machO32B
/// A 64-bit little-endian Mach-O binary.
case machO64L
/// A 64-bit big-endian Mach-O binary.
case machO64B
/// A web assembly binary.
case wasm
internal init(llvm: LLVMBinaryType) {
switch llvm {
case LLVMBinaryTypeArchive: self = .archive
case LLVMBinaryTypeMachOUniversalBinary: self = .machOUniversalBinary
case LLVMBinaryTypeCOFFImportFile: self = .coff
case LLVMBinaryTypeIR: self = .ir
case LLVMBinaryTypeWinRes: self = .winRes
case LLVMBinaryTypeCOFF: self = .coff
case LLVMBinaryTypeELF32L: self = .elf32L
case LLVMBinaryTypeELF32B: self = .elf32B
case LLVMBinaryTypeELF64L: self = .elf64L
case LLVMBinaryTypeELF64B: self = .elf64B
case LLVMBinaryTypeMachO32L: self = .machO32L
case LLVMBinaryTypeMachO32B: self = .machO32B
case LLVMBinaryTypeMachO64L: self = .machO64L
case LLVMBinaryTypeMachO64B: self = .machO64B
case LLVMBinaryTypeWasm: self = .wasm
default: fatalError("unknown binary type \(llvm)")
}
}
}
init(llvm: LLVMBinaryRef, buffer: MemoryBuffer) {
self.llvm = llvm
self.kind = Kind(llvm: LLVMBinaryGetType(llvm))
self.buffer = buffer
}
/// Creates a Binary File with the contents of a provided memory buffer.
///
/// - Parameters:
/// - memoryBuffer: A memory buffer containing a valid binary file.
/// - context: The context to allocate the given binary in.
/// - throws: `BinaryFileError` if there was an error on creation.
public init(memoryBuffer: MemoryBuffer, in context: Context = .global) throws {
var error: UnsafeMutablePointer<Int8>?
self.llvm = LLVMCreateBinary(memoryBuffer.llvm, context.llvm, &error)
if let error = error {
defer { LLVMDisposeMessage(error) }
throw BinaryFileError.couldNotCreate(String(cString: error))
}
self.kind = Kind(llvm: LLVMBinaryGetType(self.llvm))
self.buffer = memoryBuffer
}
/// Creates an `ObjectFile` with the contents of the object file at
/// the provided path.
/// - parameter path: The absolute file path on your filesystem.
/// - throws: `MemoryBufferError` or `BinaryFileError` if there was an error
/// on creation
public convenience init(path: String) throws {
let memoryBuffer = try MemoryBuffer(contentsOf: path)
try self.init(memoryBuffer: memoryBuffer)
}
/// Deinitialize this value and dispose of its resources.
deinit {
LLVMDisposeBinary(llvm)
}
}
/// An in-memory representation of a format-independent object file.
public class ObjectFile: BinaryFile {
override init(llvm: LLVMBinaryRef, buffer: MemoryBuffer) {
super.init(llvm: llvm, buffer: buffer)
precondition(self.kind != .machOUniversalBinary,
"File format is not an object file; use MachOUniversalBinaryFile instead")
}
/// Creates an object file with the contents of a provided memory buffer.
///
/// - Parameters:
/// - memoryBuffer: A memory buffer containing a valid object file.
/// - context: The context to allocate the given binary in.
/// - throws: `BinaryFileError` if there was an error on creation.
public override init(memoryBuffer: MemoryBuffer, in context: Context = .global) throws {
try super.init(memoryBuffer: memoryBuffer, in: context)
precondition(self.kind != .machOUniversalBinary,
"File format is not an object file; use MachOUniversalBinaryFile instead")
}
/// Returns a sequence of all the sections in this object file.
public var sections: SectionSequence {
return SectionSequence(llvm: LLVMObjectFileCopySectionIterator(llvm), object: self)
}
/// Returns a sequence of all the symbols in this object file.
public var symbols: SymbolSequence {
return SymbolSequence(llvm: LLVMObjectFileCopySymbolIterator(llvm), object: self)
}
}
/// An in-memory representation of a Mach-O universal binary file.
public final class MachOUniversalBinaryFile: BinaryFile {
/// Creates an `MachOUniversalBinaryFile` with the contents of the object file at
/// the provided path.
/// - parameter path: The absolute file path on your filesystem.
/// - throws: `MemoryBufferError` or `BinaryFileError` if there was an error
/// on creation
public convenience init(path: String) throws {
let memoryBuffer = try MemoryBuffer(contentsOf: path)
try self.init(memoryBuffer: memoryBuffer)
}
/// Creates a Mach-O universal binary file with the contents of a provided
/// memory buffer.
///
/// - Parameters:
/// - memoryBuffer: A memory buffer containing a valid universal Mach-O file.
/// - context: The context to allocate the given binary in.
/// - throws: `BinaryFileError` if there was an error on creation.
public override init(memoryBuffer: MemoryBuffer, in context: Context = .global) throws {
try super.init(memoryBuffer: memoryBuffer, in: context)
guard self.kind == .machOUniversalBinary else {
throw BinaryFileError.couldNotCreate("File is not a Mach-O universal binary")
}
}
/// Retrieves the object file for a specific architecture, if it exists.
///
/// - Parameters:
/// - architecture: The architecture of a Mach-O file contained in this
/// universal binary file.
/// - Returns: An object file for the given architecture if it exists.
/// - throws: `BinaryFileError` if there was an error on creation.
public func objectFile(for architecture: Triple.Architecture) throws -> Slice {
var error: UnsafeMutablePointer<Int8>?
let archName = architecture.rawValue
let archFile: LLVMBinaryRef = LLVMMachOUniversalBinaryCopyObjectForArch(self.llvm, archName, archName.count, &error)
if let error = error {
defer { LLVMDisposeMessage(error) }
throw BinaryFileError.couldNotCreate(String(cString: error))
}
let buffer = MemoryBuffer(llvm: LLVMBinaryCopyMemoryBuffer(archFile))
return Slice(parent: self, llvm: archFile, buffer: buffer)
}
/// Represents an architecture-specific slice of a Mach-O universal binary
/// file.
public final class Slice: ObjectFile {
// Maintain a strong reference to our parent binary so the backing buffer
// doesn't disappear on us.
private let parent: MachOUniversalBinaryFile
fileprivate init(parent: MachOUniversalBinaryFile, llvm: LLVMBinaryRef, buffer: MemoryBuffer) {
self.parent = parent
super.init(llvm: llvm, buffer: buffer)
}
private override init(llvm: LLVMBinaryRef, buffer: MemoryBuffer) {
fatalError()
}
private override init(memoryBuffer: MemoryBuffer, in context: Context = .global) throws {
fatalError()
}
}
}
/// A Section represents one of the binary sections in an object file.
public struct Section {
/// The section's declared name.
public let name: String
/// The size of the contents of the section.
public let size: Int
/// The raw contents of the section.
public let contents: UnsafeBufferPointer<CChar>
/// The address of the section in the object file.
public let address: Int
/// The parent sequence of this section.
private let sectionIterator: LLVMSectionIteratorRef
internal init(fromIterator si: LLVMSectionIteratorRef) {
self.sectionIterator = si
self.name = String(cString: LLVMGetSectionName(si))
self.size = Int(LLVMGetSectionSize(si))
self.contents = UnsafeBufferPointer<CChar>(start: LLVMGetSectionContents(si), count: self.size)
self.address = Int(LLVMGetSectionAddress(si))
}
/// Returns a sequence of all the relocations in this object file.
public var relocations: RelocationSequence {
return RelocationSequence(
llvm: LLVMGetRelocations(self.sectionIterator),
sectionIterator: self.sectionIterator
)
}
/// Returns whether a symbol matching the given `Symbol` can be found in
/// this section.
public func contains(symbol: Symbol) -> Bool {
return LLVMGetSectionContainsSymbol(self.sectionIterator, symbol.symbolIterator) != 0
}
}
/// A sequence for iterating over the sections in an object file.
public class SectionSequence: Sequence {
let llvm: LLVMSectionIteratorRef?
let objectFile: ObjectFile
init(llvm: LLVMSectionIteratorRef?, object: ObjectFile) {
self.llvm = llvm
self.objectFile = object
}
/// Makes an iterator that iterates over the sections in an object file.
public func makeIterator() -> AnyIterator<Section> {
return AnyIterator {
guard let it = self.llvm else {
return nil
}
if LLVMObjectFileIsSectionIteratorAtEnd(self.objectFile.llvm, it) != 0 {
return nil
}
defer { LLVMMoveToNextSection(it) }
return Section(fromIterator: it)
}
}
/// Deinitialize this value and dispose of its resources.
deinit {
LLVMDisposeSectionIterator(llvm)
}
}
/// A symbol is a top-level addressable entity in an object file.
public struct Symbol {
/// The symbol name.
public let name: String
/// The size of the data in the symbol.
public let size: Int
/// The address of the symbol in the object file.
public let address: Int
/// The parent sequence of this symbol.
fileprivate let symbolIterator: LLVMSymbolIteratorRef
internal init(fromIterator si: LLVMSymbolIteratorRef) {
self.name = String(cString: LLVMGetSymbolName(si))
self.size = Int(LLVMGetSymbolSize(si))
self.address = Int(LLVMGetSymbolAddress(si))
self.symbolIterator = si
}
}
/// A Relocation represents the contents of a relocated symbol in the dynamic
/// linker.
public struct Relocation {
/// Retrieves the type of this relocation.
///
/// The value of this integer is dependent upon the type of object file
/// it was retrieved from.
public let type: Int
/// The offset the relocated symbol resides at.
public let offset: Int
/// The symbol that is the subject of the relocation.
public let symbol: Symbol
/// Get a string that represents the type of this relocation for display
/// purposes.
public let typeName: String
internal init(fromIterator ri: LLVMRelocationIteratorRef) {
self.type = Int(LLVMGetRelocationType(ri))
self.offset = Int(LLVMGetRelocationOffset(ri))
self.symbol = Symbol(fromIterator: LLVMGetRelocationSymbol(ri))
self.typeName = String(cString: LLVMGetRelocationTypeName(ri))
}
}
/// A sequence for iterating over the relocations in an object file.
public class RelocationSequence: Sequence {
let llvm: LLVMRelocationIteratorRef
let sectionIterator: LLVMSectionIteratorRef
init(llvm: LLVMRelocationIteratorRef, sectionIterator: LLVMSectionIteratorRef) {
self.llvm = llvm
self.sectionIterator = sectionIterator
}
/// Creates an iterator that will iterate over all relocations in an object
/// file.
public func makeIterator() -> AnyIterator<Relocation> {
return AnyIterator {
if LLVMIsRelocationIteratorAtEnd(self.sectionIterator, self.llvm) != 0 {
return nil
}
defer { LLVMMoveToNextRelocation(self.llvm) }
return Relocation(fromIterator: self.llvm)
}
}
/// Deinitialize this value and dispose of its resources.
deinit {
LLVMDisposeSectionIterator(llvm)
}
}
/// A sequence for iterating over the symbols in an object file.
public class SymbolSequence: Sequence {
let llvm: LLVMSymbolIteratorRef?
let object: ObjectFile
init(llvm: LLVMSymbolIteratorRef?, object: ObjectFile) {
self.llvm = llvm
self.object = object
}
/// Creates an iterator that will iterate over all symbols in an object
/// file.
public func makeIterator() -> AnyIterator<Symbol> {
return AnyIterator {
guard let it = self.llvm else {
return nil
}
if LLVMObjectFileIsSymbolIteratorAtEnd(self.object.llvm, it) != 0 {
return nil
}
defer { LLVMMoveToNextSymbol(it) }
return Symbol(fromIterator: it)
}
}
/// Deinitialize this value and dispose of its resources.
deinit {
LLVMDisposeSymbolIterator(llvm)
}
}
| mit | 8b498836f963791a576eaeeda1cdf267 | 33.607235 | 120 | 0.705966 | 4.074536 | false | false | false | false |
vermont42/Conjugar | Conjugar/PersonNumber.swift | 1 | 1385 | //
// PersonNumber.swift
// Conjugar
//
// Created by Joshua Adams on 3/31/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
enum PersonNumber: String, CaseIterable {
case firstSingular = "fs"
case firstPlural = "fp"
case secondSingularTú = "ss"
case secondSingularVos = "sv"
case secondPlural = "sp"
case thirdSingular = "ts"
case thirdPlural = "tp"
case none = "no"
var pronoun: String {
switch self {
case .firstSingular:
return "yo"
case .secondSingularTú:
return "tú"
case .secondSingularVos:
return "vos"
case .thirdSingular:
return "él"
case .firstPlural:
return "nosotros"
case .secondPlural:
return "vosotros"
case .thirdPlural:
return "ellas"
case .none:
return "none"
}
}
var shortDisplayName: String {
switch self {
case .firstSingular:
return "1S"
case .secondSingularTú:
return "2S"
case .secondSingularVos:
return "2SV"
case .thirdSingular:
return "3S"
case .firstPlural:
return "1P"
case .secondPlural:
return "2P"
case .thirdPlural:
return "3P"
case .none:
return "none"
}
}
static let actualPersonNumbers: [PersonNumber] = [.firstSingular, .secondSingularTú, .secondSingularVos, .thirdSingular, .firstPlural, .secondPlural, .thirdPlural]
}
| agpl-3.0 | 43157cad86447a5e7f4f71615e9ca414 | 21.225806 | 165 | 0.632075 | 3.60733 | false | false | false | false |
MomentaBV/CwlUtils | Sources/CwlUtils/CwlDebugContext.swift | 1 | 15398 | //
// CwlDebugContext.swift
// CwlUtils
//
// Created by Matt Gallagher on 2016/05/15.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
/// A set of identifiers for the different queues in the DebugContextCoordinator
///
/// - unspecified: used when a initial DebugContextThread is not specified on startup (not used otherwise)
/// - main: used by `main` and `mainAsync` contexts
/// - `default`: used for a concurrent queues and for timers on direct
/// - custom: any custom queue
public enum DebugContextThread: Hashable {
case unspecified
case main
case `default`
case custom(String)
/// Convenience test to determine if an `Exec` instance wraps a `DebugContext` identifying `self` as its `thread`.
public func matches(_ exec: Exec) -> Bool {
if case .custom(let debugContext as DebugContext) = exec, debugContext.thread ==
self {
return true
} else {
return false
}
}
/// Implementation of Hashable property
public var hashValue: Int {
switch self {
case .unspecified: return Int(0).hashValue
case .main: return Int(1).hashValue
case .default: return Int(2).hashValue
case .custom(let s): return Int(3).hashValue ^ s.hashValue
}
}
}
/// Basic equality tests for `DebugContextThread`
///
/// - Parameters:
/// - left: a `DebugContextThread`
/// - right: another `DebugContextThread`
/// - Returns: true if they are equal value
public func ==(left: DebugContextThread, right: DebugContextThread) -> Bool {
switch (left, right) {
case (.custom(let l), .custom(let r)) where l == r: return true
case (.unspecified, .unspecified): return true
case (.main, .main): return true
case (.default, .default): return true
default: return false
}
}
/// Simulates running a series of blocks across threads over time by instead queuing the blocks and running them serially in time priority order, incrementing the `currentTime` to reflect the time priority of the last run block.
/// The result is a deterministic simulation of time scheduled blocks, which is otherwise subject to thread scheduling non-determinism.
public class DebugContextCoordinator {
// We use DispatchTime for time calculations but time 0 is treated as a special value ("now") so we start at time = 1, internally, and subtract 1 when returning through the public `currentTime` accessor.
var internalTime: UInt64 = 1
var queues: Dictionary<DebugContextThread, DebugContextQueue> = [:]
var stopRequested: Bool = false
/// Returns the current simulated time in nanoseconds
public var currentTime: UInt64 { return internalTime - 1 }
/// Returns the last runs simulated thread
fileprivate (set) public var currentThread: DebugContextThread
/// Constructs an empty instance
public init() {
currentThread = .unspecified
}
/// Implementation mimicking Exec.direct but returning an Exec.custom(DebugContext)
public var direct: Exec {
return .custom(DebugContext(type: .immediate, thread: .default, coordinator: self))
}
/// Implementation mimicking Exec.main but returning an Exec.custom(DebugContext)
public var main: Exec {
return .custom(DebugContext(type: .conditionallyAsync(true), thread: .main, coordinator: self))
}
/// Implementation mimicking Exec.mainAsync but returning an Exec.custom(DebugContext)
public var mainAsync: Exec {
return .custom(DebugContext(type: .serialAsync, thread: .main, coordinator: self))
}
/// Implementation mimicking Exec.default but returning an Exec.custom(DebugContext)
public var `default`: Exec {
return .custom(DebugContext(type: .concurrentAsync, thread: .default, coordinator: self))
}
/// Implementation mimicking Exec.syncQueue but returning an Exec.custom(DebugContext)
public var syncQueue: Exec {
let uuidString = CFUUIDCreateString(nil, CFUUIDCreate(nil)) as String? ?? ""
return .custom(DebugContext(type: .mutex, thread: .custom(uuidString), coordinator: self))
}
/// Implementation mimicking Exec.asyncQueue but returning an Exec.custom(DebugContext)
public var asyncQueue: Exec {
let uuidString = CFUUIDCreateString(nil, CFUUIDCreate(nil)) as String? ?? ""
return .custom(DebugContext(type: .serialAsync, thread: .custom(uuidString), coordinator: self))
}
/// Performs all scheduled actions in a serial loop.
///
/// - parameter stoppingAfter: If nil, loop will continue until `stop` invoked or until no actions remain. If non-nil, loop will abort after an action matching Cancellable is completed.
public func runScheduledTasks(stoppingAfter: Cancellable? = nil) {
stopRequested = false
currentThread = .unspecified
while !stopRequested, let nextTimer = runNextTask() {
if stoppingAfter != nil, stoppingAfter === nextTimer {
break
}
}
if stopRequested {
queues = [:]
}
}
/// Performs all scheduled actions in a serial loop.
///
/// - parameter stoppingAfter: If nil, loop will continue until `stop` invoked or until no actions remain. If non-nil, loop will abort after an action matching Cancellable is completed.
public func runScheduledTasks(untilTime: UInt64) {
stopRequested = false
currentThread = .unspecified
while !stopRequested, let (threadIndex, time) = nextTask(), time <= untilTime {
_ = runTask(threadIndex: threadIndex, time: time)
}
if stopRequested {
queues = [:]
}
}
/// Causes `runScheduledTasks` to exit as soon as possible, if it is running.
public func stop() {
stopRequested = true
}
/// Discards all scheduled actions and resets time to 1. Useful if the `DebugContextCoordinator` is to be reused.
public func reset() {
internalTime = 1
queues = [:]
}
func getOrCreateQueue(forName: DebugContextThread) -> DebugContextQueue {
if let t = queues[forName] {
return t
}
let t = DebugContextQueue()
queues[forName] = t
return t
}
// Fundamental method for scheduling a block on the coordinator for later invocation.
func schedule(block: @escaping () -> Void, thread: DebugContextThread, timeInterval interval: Int, repeats: Bool) -> DebugContextTimer {
let i = interval > 0 ? UInt64(interval) : 0 as UInt64
let debugContextTimer = DebugContextTimer(thread: thread, rescheduleInterval: repeats ? i : nil, coordinator: self)
getOrCreateQueue(forName: thread).schedule(pending: PendingBlock(time: internalTime + i, timer: debugContextTimer, block: block))
return debugContextTimer
}
// Remove a block from the scheduler
func cancelTimer(_ toCancel: DebugContextTimer) {
if let t = queues[toCancel.thread] {
t.cancelTimer(toCancel)
}
}
func nextTask() -> (DebugContextThread, UInt64)? {
var lowestTime = UInt64.max
var selectedIndex = DebugContextThread.unspecified
// We want a deterministic ordering, so we'll iterate over the queues by key sorted by hashValue
for index in queues.keys.sorted(by: { (left, right) -> Bool in left.hashValue < right.hashValue }) {
if let t = queues[index], t.nextTime < lowestTime {
selectedIndex = index
lowestTime = t.nextTime
}
}
if lowestTime == UInt64.max {
return nil
}
return (selectedIndex, lowestTime)
}
func runTask(threadIndex: DebugContextThread, time: UInt64) -> DebugContextTimer? {
(currentThread, internalTime) = (threadIndex, time)
return queues[threadIndex]?.popAndInvokeNext()
}
// Run the next event. If nil is returned, no further events remain. If
func runNextTask() -> DebugContextTimer? {
if let (threadIndex, time) = nextTask() {
return runTask(threadIndex: threadIndex, time: time)
}
return nil
}
}
// This structure is used to represent scheduled actions in the DebugContextCoordinator.
struct PendingBlock {
let time: UInt64
weak var timer: DebugContextTimer?
let block: () -> Void
init(time: UInt64, timer: DebugContextTimer?, block: @escaping () -> Void) {
self.time = time
self.timer = timer
self.block = block
}
var nextInterval: PendingBlock? {
if let t = timer, let i = t.rescheduleInterval, t.coordinator != nil {
return PendingBlock(time: time + i, timer: t, block: block)
}
return nil
}
}
// A `DebugContextQueue` is just an array of `PendingBlock`, sorted by scheduled time. It represents the blocks queued for execution on a thread in the `DebugContextCoordinator`.
class DebugContextQueue {
var pendingBlocks: Array<PendingBlock> = []
init() {
}
// Insert a block in scheduled order
func schedule(pending: PendingBlock) {
var insertionIndex = 0
while pendingBlocks.count > insertionIndex && pendingBlocks[insertionIndex].time <= pending.time {
insertionIndex += 1
}
pendingBlocks.insert(pending, at: insertionIndex)
}
// Remove a block
func cancelTimer(_ toCancel: DebugContextTimer) {
if let index = pendingBlocks.index(where: { tuple -> Bool in tuple.timer === toCancel }) {
pendingBlocks.remove(at: index)
}
}
// Return the earliest scheduled time in the queue
var nextTime: UInt64 {
return pendingBlocks.first?.time ?? UInt64.max
}
// Runs the next block in the queue
func popAndInvokeNext() -> DebugContextTimer? {
if let next = pendingBlocks.first {
pendingBlocks.remove(at: 0)
next.block()
if let nextInterval = next.nextInterval {
schedule(pending: nextInterval)
}
// We ran a block, don't return nil (next.timer may return nil if it has self-cancelled)
return next.timer ?? DebugContextTimer()
}
return nil
}
}
/// An implementation of `ExecutionContext` that schedules its non-immediate actions on a `DebugContextCoordinator`. This type is constructed using the `Exec` mimicking properties and functions on `DebugContextCoordinator`.
public struct DebugContext: ExecutionContext {
let underlyingType: ExecutionType
let thread: DebugContextThread
weak var coordinator: DebugContextCoordinator?
init(type: ExecutionType, thread: DebugContextThread, coordinator: DebugContextCoordinator) {
self.underlyingType = type
self.thread = thread
self.coordinator = coordinator
}
/// A description about how functions will be invoked on an execution context.
public var type: ExecutionType {
switch underlyingType {
case .conditionallyAsync:
if let ctn = coordinator?.currentThread, thread == ctn {
return .conditionallyAsync(false)
}
fallthrough
default: return underlyingType
}
}
/// Run `execute` normally on the execution context
public func invoke(_ execute: @escaping () -> Void) {
guard let c = coordinator else { return }
switch type {
case .mutex:
let previousThread = c.currentThread
c.currentThread = thread
execute()
c.currentThread = previousThread
case .immediate, .conditionallyAsync(false): execute()
default: invokeAsync(execute)
}
}
/// Run `execute` asynchronously on the execution context
public func invokeAsync(_ execute: @escaping () -> Void) {
_ = coordinator?.schedule(block: execute, thread: thread, timeInterval: 0, repeats: false)
}
/// Run `execute` on the execution context but don't return from this function until the provided function is complete.
public func invokeAndWait(_ execute: @escaping () -> Void) {
guard let c = coordinator else { return }
switch type {
case .mutex:
let previousThread = c.currentThread
c.currentThread = thread
execute()
c.currentThread = previousThread
case .immediate, .conditionallyAsync(false):
execute()
default:
c.runScheduledTasks(stoppingAfter: c.schedule(block: execute, thread: thread, timeInterval: 0, repeats: false))
}
}
/// Run `execute` on the execution context after `interval` (plus `leeway`) unless the returned `Cancellable` is cancelled or released before running occurs.
public func singleTimer(interval: DispatchTimeInterval, leeway: DispatchTimeInterval, handler: @escaping () -> Void) -> Cancellable {
guard let c = coordinator else { return DebugContextTimer() }
return c.schedule(block: handler, thread: thread, timeInterval: interval.toNanoseconds(), repeats: false)
}
/// Run `execute` on the execution context after `interval` (plus `leeway`), passing the `parameter` value as an argument, unless the returned `Cancellable` is cancelled or released before running occurs.
public func singleTimer<T>(parameter: T, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, handler: @escaping (T) -> Void) -> Cancellable {
guard let c = coordinator else { return DebugContextTimer() }
return c.schedule(block: { handler(parameter) }, thread: thread, timeInterval: interval.toNanoseconds(), repeats: false)
}
/// Run `execute` on the execution context after `interval` (plus `leeway`), and again every `interval` (within a `leeway` margin of error) unless the returned `Cancellable` is cancelled or released before running occurs.
public func periodicTimer(interval: DispatchTimeInterval, leeway: DispatchTimeInterval, handler: @escaping () -> Void) -> Cancellable {
guard let c = coordinator else { return DebugContextTimer() }
return c.schedule(block: handler, thread: thread, timeInterval: interval.toNanoseconds(), repeats: true)
}
/// Run `execute` on the execution context after `interval` (plus `leeway`), passing the `parameter` value as an argument, and again every `interval` (within a `leeway` margin of error) unless the returned `Cancellable` is cancelled or released before running occurs.
public func periodicTimer<T>(parameter: T, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, handler: @escaping (T) -> Void) -> Cancellable {
guard let c = coordinator else { return DebugContextTimer() }
return c.schedule(block: { handler(parameter) }, thread: thread, timeInterval: interval.toNanoseconds(), repeats: true)
}
/// Gets a timestamp representing the host uptime the in the current context
public func timestamp() -> DispatchTime {
guard let c = coordinator else { return DispatchTime.now() }
return DispatchTime(uptimeNanoseconds: c.currentTime)
}
}
// All actions scheduled with a `DebugContextCoordinator` are referenced by a DebugContextTimer (even those actions that are simply asynchronous invocations without a delay).
class DebugContextTimer: Cancellable {
let thread: DebugContextThread
let rescheduleInterval: UInt64?
weak var coordinator: DebugContextCoordinator?
init() {
thread = .unspecified
coordinator = nil
rescheduleInterval = nil
}
init(thread: DebugContextThread, rescheduleInterval: UInt64?, coordinator: DebugContextCoordinator) {
self.thread = thread
self.coordinator = coordinator
self.rescheduleInterval = rescheduleInterval
}
/// Cancellable implementation
public func cancel() {
coordinator?.cancelTimer(self)
coordinator = nil
}
deinit {
cancel()
}
}
| isc | 0dbfd306e356e61cf6eb97d7aec46994 | 37.205955 | 268 | 0.735078 | 3.921803 | false | false | false | false |
jum/Charts | ChartsDemo-macOS/ChartsDemo-macOS/Demos/LineDemoViewController.swift | 5 | 1536 | //
// LineDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class LineDemoViewController: NSViewController
{
@IBOutlet var lineChartView: LineChartView!
override open func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) }
let ys2 = Array(1..<10).map { x in return cos(Double(x) / 2.0 / 3.141) }
let yse1 = ys1.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
let yse2 = ys2.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
let data = LineChartData()
let ds1 = LineChartDataSet(entries: yse1, label: "Hello")
ds1.colors = [NSUIColor.red]
data.addDataSet(ds1)
let ds2 = LineChartDataSet(entries: yse2, label: "World")
ds2.colors = [NSUIColor.blue]
data.addDataSet(ds2)
self.lineChartView.data = data
self.lineChartView.gridBackgroundColor = NSUIColor.white
self.lineChartView.chartDescription?.text = "Linechart Demo"
}
override open func viewWillAppear()
{
self.lineChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0)
}
}
| apache-2.0 | 37e65c03a7dd2f88ff2165119f1b9815 | 30.346939 | 93 | 0.630208 | 3.968992 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/AssistantV1/Models/DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill.swift | 1 | 4728 | /**
* (C) Copyright IBM Corp. 2020, 2021.
*
* 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
/**
DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill.
Enums with an associated value of DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill:
DialogNodeOutputGeneric
*/
public struct DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: Codable, Equatable {
/**
The type of the search query.
*/
public enum QueryType: String {
case naturalLanguage = "natural_language"
case discoveryQueryLanguage = "discovery_query_language"
}
/**
The type of response returned by the dialog node. The specified response type must be supported by the client
application or channel.
**Note:** The **search_skill** response type is used only by the v2 runtime API.
*/
public var responseType: String
/**
The text of the search query. This can be either a natural-language query or a query that uses the Discovery query
language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery
service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators).
*/
public var query: String
/**
The type of the search query.
*/
public var queryType: String
/**
An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery
service documentation]([Discovery service
documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter).
*/
public var filter: String?
/**
The version of the Discovery service API to use for the query.
*/
public var discoveryVersion: String?
/**
An array of objects specifying channels for which the response is intended.
*/
public var channels: [ResponseGenericChannel]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
case query = "query"
case queryType = "query_type"
case filter = "filter"
case discoveryVersion = "discovery_version"
case channels = "channels"
}
/**
Initialize a `DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill` with member variables.
- parameter responseType: The type of response returned by the dialog node. The specified response type must be
supported by the client application or channel.
**Note:** The **search_skill** response type is used only by the v2 runtime API.
- parameter query: The text of the search query. This can be either a natural-language query or a query that
uses the Discovery query language syntax, depending on the value of the **query_type** property. For more
information, see the [Discovery service
documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators).
- parameter queryType: The type of the search query.
- parameter filter: An optional filter that narrows the set of documents to be searched. For more information,
see the [Discovery service documentation]([Discovery service
documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter).
- parameter discoveryVersion: The version of the Discovery service API to use for the query.
- parameter channels: An array of objects specifying channels for which the response is intended.
- returns: An initialized `DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill`.
*/
public init(
responseType: String,
query: String,
queryType: String,
filter: String? = nil,
discoveryVersion: String? = nil,
channels: [ResponseGenericChannel]? = nil
)
{
self.responseType = responseType
self.query = query
self.queryType = queryType
self.filter = filter
self.discoveryVersion = discoveryVersion
self.channels = channels
}
}
| apache-2.0 | 964982ca8613dcdf61fe93a76139f6b1 | 39.410256 | 119 | 0.707699 | 4.766129 | false | false | false | false |
aichamorro/fitness-tracker | Clients/Apple/UIGraphView/UIGraphView/UIGraphView.swift | 1 | 5208 | //
// UIGraphView.swift
// UIGraphView
//
// Created by Alberto Chamorro on 28/01/2017.
// Copyright © 2017 OnsetBits. All rights reserved.
//
import UIKit
import QuartzCore
public typealias UIGraphViewSampleData = (horizontal: [Double], vertical: [Double])
public protocol UIGraphViewDataSource: class {
func data(for dispersionGraph: UIGraphView) -> UIGraphViewSampleData
}
public protocol UIGraphViewDelegate: class {
func graphView(_ graphView: UIGraphView, shouldAddHorizontalTagFor index: Int) -> Bool
func graphView(_ graphView: UIGraphView, horizontalTagFor index: Int) -> String
}
public extension UIGraphViewDelegate {
func graphView(_ graphView: UIGraphView, shouldAddHorizontalTagFor index: Int) -> Bool {
return true
}
func graphView(_ graphView: UIGraphView, horizontalTagFor index: Int) -> String {
return ""
}
}
@IBDesignable
final public class UIGraphView: UIView {
@IBInspectable public var lineColor: UIColor = UIColor.black
@IBInspectable public var lineWidth: CGFloat = 2.0
@IBInspectable public var font: UIFont = UIFont.systemFont(ofSize: 10)
fileprivate var drawingFunction: UIGraphViewDrawingStyle!
fileprivate var dataMapper: UIGraphViewValuesIterator?
var verticalMinValue: NSString!
var verticalMaxValue: NSString!
var textAttributes: [String:Any]!
weak public var datasource: UIGraphViewDataSource? {
didSet {
reloadData()
}
}
weak public var delegate: UIGraphViewDelegate? {
didSet {
reloadData()
}
}
public func reloadData() {
guard let data = datasource?.data(for: self) else { return }
if data.horizontal.count != data.vertical.count {
fatalError("The datasource provided, does not produce the expected data: number of horizontal and vertical items are different")
}
guard let horizontalRange = data.horizontal.range, let verticalRange = data.vertical.range else {
verticalMaxValue = ""
verticalMinValue = ""
return
}
// Graph Info
verticalMinValue = String(format: "%.2f", verticalRange.lowerBound) as NSString
verticalMaxValue = String(format: "%.2f", verticalRange.upperBound) as NSString
// From value to pixel
let mappingFunction = UIGraphViewValueMapperFactory.create(horizontalData: data.horizontal, verticalData: data.vertical)
dataMapper = { rect, operation in zip(data.horizontal, data.vertical).forEach { operation(mappingFunction(rect, $0, $1)) } }
drawingFunction = UIGraphViewDrawingStyles.points(pointRadius: 4, color: UIColor.white)
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .center
textAttributes = [
NSFontAttributeName: font,
NSParagraphStyleAttributeName: textStyle,
NSForegroundColorAttributeName: UIColor.white.withAlphaComponent(0.8)]
setNeedsDisplay()
}
}
extension UIGraphView {
override public func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
let graphRect = rect.reducedHeight(by: 20).reducedAndCenterd(xFactor: 0.8, yFactor: 1)
// Draw reference lines
context.setStrokeColor(UIColor.white.withAlphaComponent(0.3).cgColor)
context.move(to: CGPoint(x: rect.minX, y: graphRect.maxY))
context.addLine(to: CGPoint(x: rect.maxX, y: graphRect.maxY))
context.move(to: CGPoint(x: rect.minX, y: graphRect.minY))
context.addLine(to: CGPoint(x: rect.maxX, y: graphRect.minY))
context.strokePath()
context.executeBatch { context in
context.setLineCap(.round)
context.setLineDash(phase: 0, lengths: [3])
context.move(to: CGPoint(x: rect.minX, y: graphRect.midY))
context.addLine(to: CGPoint(x: rect.maxX, y: graphRect.midY))
context.strokePath()
}
if let dataMapper = dataMapper {
// Draw max and min values
verticalMaxValue.draw(at: CGPoint(x: rect.minX + 5, y: graphRect.minY + 5), withAttributes: textAttributes)
verticalMinValue.draw(at: CGPoint(x: rect.minX + 5, y: graphRect.maxY - 15), withAttributes: textAttributes)
let horizontalTagHeight = (rect.maxY - graphRect.maxY)/4
// Draw graph and horiontal tags
drawingFunction(context, graphRect, dataMapper) { point, index in
if self.delegate?.graphView(self, shouldAddHorizontalTagFor: index) ?? true {
let tag = (self.delegate?.graphView(self, horizontalTagFor: index) ?? "") as NSString
tag.draw(at: CGPoint(x: point.x - 5, y: graphRect.maxY + horizontalTagHeight), withAttributes: self.textAttributes)
}
}
}
UIGraphicsEndImageContext()
}
}
}
| gpl-3.0 | d46fa26468fd54a44b5e5b233d81ecd2 | 37.57037 | 140 | 0.63165 | 4.750912 | false | false | false | false |
benlangmuir/swift | test/Profiler/coverage_var_init.swift | 2 | 3581 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_var_init %s | %FileCheck %s
// RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s
struct S {
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1iSivpfi" {{.*}} // variable initialization expression of coverage_var_init.S.i
// CHECK-NEXT: [[@LINE+1]]:11 -> [[@LINE+1]]:12 : 0
var i = 0
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1jSivpfi" {{.*}} // variable initialization expression of coverage_var_init.S.j
// CHECK-NEXT: [[@LINE+1]]:11 -> [[@LINE+1]]:16 : 0
var j = 1 + 2
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1kSiycvpfi" {{.*}} // variable initialization expression of coverage_var_init.S.k
// CHECK-NEXT: [[@LINE+3]]:11 -> [[@LINE+3]]:20 : 0
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1kSiycvpfiSiycfU_" {{.*}} // closure #1 () -> Swift.Int in variable initialization expression of coverage_var_init.S.k
// CHECK-NEXT: [[@LINE+1]]:11 -> [[@LINE+1]]:20 : 0
var k = { 1 + 2 }
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1lSivpfi" {{.*}} // variable initialization expression of coverage_var_init.S.l
// CHECK-NEXT: [[@LINE+1]]:11 -> [[@LINE+1]]:16 : 0
var l = #line
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1mSaySiGvpfi" {{.*}} // variable initialization expression of coverage_var_init.S.m
// CHECK-NEXT: [[@LINE+1]]:11 -> [[@LINE+1]]:20 : 0
var m = [1, 2, 3]
// CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_var_init1SV1nSSvpfi" {{.*}} // variable initialization expression of coverage_var_init.S.n
// CHECK-NEXT: [[@LINE+3]]:11 -> [[@LINE+3]]:33 : 0
// CHECK-NEXT: [[@LINE+2]]:26 -> [[@LINE+2]]:27 : 1
// CHECK-NEXT: [[@LINE+1]]:30 -> [[@LINE+1]]:31 : (0 - 1)
var n = "\(.random() ? 1 : 2)"
}
final class VarInit {
// CHECK: sil_coverage_map {{.*}} "$s17coverage_var_init7VarInitC018initializedWrapperE0SivpfP"
// CHECK-NEXT: [[@LINE+1]]:4 -> [[@LINE+1]]:42 : 0
@Wrapper var initializedWrapperInit = 2
// CHECK: sil_coverage_map {{.*}} // variable initialization expression of coverage_var_init.VarInit.(_autoclosureWrapperInit
// CHECK-NEXT: [[@LINE+1]]:52 -> [[@LINE+1]]:53
@AutoClosureWrapper var autoclosureWrapperInit = 3
// CHECK: sil_coverage_map {{.*}} "$s17coverage_var_init7VarInitC04lazydE033_49373CB2DFB47C8DC62FA963604688DFLLSSvgSSyXEfU_"
// CHECK-NEXT: [[@LINE+1]]:42 -> [[@LINE+3]]:4 : 0
private lazy var lazyVarInit: String = {
return "lazyVarInit"
}()
// CHECK: sil_coverage_map {{.*}} "$s17coverage_var_init7VarInitC05basicdE033_49373CB2DFB47C8DC62FA963604688DFLLSSvpfiSSyXEfU_"
// CHECK-NEXT: [[@LINE+1]]:38 -> [[@LINE+3]]:4 : 0
private var basicVarInit: String = {
return "Hello"
}()
// CHECK: sil_coverage_map {{.*}} "$s17coverage_var_init7VarInitC06simpleD033_49373CB2DFB47C8DC62FA963604688DFLLSSvg"
// CHECK-NEXT: [[@LINE+1]]:33 -> [[@LINE+3]]:4 : 0
private var simpleVar: String {
return "Hello"
}
func coverageFunction() {
print(lazyVarInit)
print(basicVarInit)
print(simpleVar)
print(initializedWrapperInit)
}
}
@propertyWrapper struct Wrapper {
init(wrappedValue: Int) {}
var wrappedValue: Int { 1 }
}
@propertyWrapper
struct AutoClosureWrapper<T> {
var wrappedValue: T
init(wrappedValue: @autoclosure () -> T) {
self.wrappedValue = wrappedValue()
}
}
VarInit().coverageFunction()
| apache-2.0 | 28b1b39c07a24a1c7cf605c10dd588ec | 42.670732 | 185 | 0.650935 | 3.160635 | false | false | false | false |
MAARK/Charts | ChartsDemo-iOS/Swift/DemoBaseViewController.swift | 4 | 13504 | //
// DemoBaseViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-03.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
enum Option {
case toggleValues
case toggleIcons
case toggleHighlight
case animateX
case animateY
case animateXY
case saveToGallery
case togglePinchZoom
case toggleAutoScaleMinMax
case toggleData
case toggleBarBorders
// CandleChart
case toggleShadowColorSameAsCandle
case toggleShowCandleBar
// CombinedChart
case toggleLineValues
case toggleBarValues
case removeDataSet
// CubicLineSampleFillFormatter
case toggleFilled
case toggleCircles
case toggleCubic
case toggleHorizontalCubic
case toggleStepped
// HalfPieChartController
case toggleXValues
case togglePercent
case toggleHole
case spin
case drawCenter
// RadarChart
case toggleXLabels
case toggleYLabels
case toggleRotate
case toggleHighlightCircle
var label: String {
switch self {
case .toggleValues: return "Toggle Y-Values"
case .toggleIcons: return "Toggle Icons"
case .toggleHighlight: return "Toggle Highlight"
case .animateX: return "Animate X"
case .animateY: return "Animate Y"
case .animateXY: return "Animate XY"
case .saveToGallery: return "Save to Camera Roll"
case .togglePinchZoom: return "Toggle PinchZoom"
case .toggleAutoScaleMinMax: return "Toggle auto scale min/max"
case .toggleData: return "Toggle Data"
case .toggleBarBorders: return "Toggle Bar Borders"
// CandleChart
case .toggleShadowColorSameAsCandle: return "Toggle shadow same color"
case .toggleShowCandleBar: return "Toggle show candle bar"
// CombinedChart
case .toggleLineValues: return "Toggle Line Values"
case .toggleBarValues: return "Toggle Bar Values"
case .removeDataSet: return "Remove Random Set"
// CubicLineSampleFillFormatter
case .toggleFilled: return "Toggle Filled"
case .toggleCircles: return "Toggle Circles"
case .toggleCubic: return "Toggle Cubic"
case .toggleHorizontalCubic: return "Toggle Horizontal Cubic"
case .toggleStepped: return "Toggle Stepped"
// HalfPieChartController
case .toggleXValues: return "Toggle X-Values"
case .togglePercent: return "Toggle Percent"
case .toggleHole: return "Toggle Hole"
case .spin: return "Spin"
case .drawCenter: return "Draw CenterText"
// RadarChart
case .toggleXLabels: return "Toggle X-Labels"
case .toggleYLabels: return "Toggle Y-Labels"
case .toggleRotate: return "Toggle Rotate"
case .toggleHighlightCircle: return "Toggle highlight circle"
}
}
}
class DemoBaseViewController: UIViewController, ChartViewDelegate {
private var optionsTableView: UITableView? = nil
let parties = ["Party A", "Party B", "Party C", "Party D", "Party E", "Party F",
"Party G", "Party H", "Party I", "Party J", "Party K", "Party L",
"Party M", "Party N", "Party O", "Party P", "Party Q", "Party R",
"Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
"Party Y", "Party Z"]
@IBOutlet weak var optionsButton: UIButton!
var options: [Option]!
var shouldHideData: Bool = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initialize()
}
private func initialize() {
self.edgesForExtendedLayout = []
}
func optionTapped(_ option: Option) {}
func handleOption(_ option: Option, forChartView chartView: ChartViewBase) {
switch option {
case .toggleValues:
for set in chartView.data!.dataSets {
set.drawValuesEnabled = !set.drawValuesEnabled
}
chartView.setNeedsDisplay()
case .toggleIcons:
for set in chartView.data!.dataSets {
set.drawIconsEnabled = !set.drawIconsEnabled
}
chartView.setNeedsDisplay()
case .toggleHighlight:
chartView.data!.highlightEnabled = !chartView.data!.isHighlightEnabled
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 3)
case .animateY:
chartView.animate(yAxisDuration: 3)
case .animateXY:
chartView.animate(xAxisDuration: 3, yAxisDuration: 3)
case .saveToGallery:
UIImageWriteToSavedPhotosAlbum(chartView.getChartImage(transparent: false)!, nil, nil, nil)
case .togglePinchZoom:
let barLineChart = chartView as! BarLineChartViewBase
barLineChart.pinchZoomEnabled = !barLineChart.pinchZoomEnabled
chartView.setNeedsDisplay()
case .toggleAutoScaleMinMax:
let barLineChart = chartView as! BarLineChartViewBase
barLineChart.autoScaleMinMaxEnabled = !barLineChart.isAutoScaleMinMaxEnabled
chartView.notifyDataSetChanged()
case .toggleData:
shouldHideData = !shouldHideData
updateChartData()
case .toggleBarBorders:
for set in chartView.data!.dataSets {
if let set = set as? BarChartDataSet {
set.barBorderWidth = set.barBorderWidth == 1.0 ? 0.0 : 1.0
}
}
chartView.setNeedsDisplay()
default:
break
}
}
@IBAction func optionsButtonTapped(_ sender: Any) {
if let optionsTableView = self.optionsTableView {
optionsTableView.removeFromSuperview()
self.optionsTableView = nil
return
}
let optionsTableView = UITableView()
optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.9)
optionsTableView.delegate = self
optionsTableView.dataSource = self
optionsTableView.translatesAutoresizingMaskIntoConstraints = false
self.optionsTableView = optionsTableView
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1,
constant: 40))
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .trailing,
relatedBy: .equal,
toItem: sender as! UIView,
attribute: .trailing,
multiplier: 1,
constant: 0))
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .top,
relatedBy: .equal,
toItem: sender,
attribute: .bottom,
multiplier: 1,
constant: 5))
self.view.addSubview(optionsTableView)
constraints.forEach { $0.isActive = true }
let constraint = NSLayoutConstraint(item: optionsTableView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 220)
constraint.isActive = true
}
func updateChartData() {
fatalError("updateChartData not overridden")
}
func setup(pieChartView chartView: PieChartView) {
chartView.usePercentValuesEnabled = true
chartView.drawSlicesUnderHoleEnabled = false
chartView.holeRadiusPercent = 0.58
chartView.transparentCircleRadiusPercent = 0.61
chartView.chartDescription?.enabled = false
chartView.setExtraOffsets(left: 5, top: 10, right: 5, bottom: 5)
chartView.drawCenterTextEnabled = true
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText = NSMutableAttributedString(string: "Charts\nby Daniel Cohen Gindi")
centerText.setAttributes([.font : UIFont(name: "HelveticaNeue-Light", size: 13)!,
.paragraphStyle : paragraphStyle], range: NSRange(location: 0, length: centerText.length))
centerText.addAttributes([.font : UIFont(name: "HelveticaNeue-Light", size: 11)!,
.foregroundColor : UIColor.gray], range: NSRange(location: 10, length: centerText.length - 10))
centerText.addAttributes([.font : UIFont(name: "HelveticaNeue-Light", size: 11)!,
.foregroundColor : UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)], range: NSRange(location: centerText.length - 19, length: 19))
chartView.centerAttributedText = centerText;
chartView.drawHoleEnabled = true
chartView.rotationAngle = 0
chartView.rotationEnabled = true
chartView.highlightPerTapEnabled = true
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .top
l.orientation = .vertical
l.drawInside = false
l.xEntrySpace = 7
l.yEntrySpace = 0
l.yOffset = 0
// chartView.legend = l
}
func setup(radarChartView chartView: RadarChartView) {
chartView.chartDescription?.enabled = false
}
func setup(barLineChartView chartView: BarLineChartViewBase) {
chartView.chartDescription?.enabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.pinchZoomEnabled = false
// ChartYAxis *leftAxis = chartView.leftAxis;
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
chartView.rightAxis.enabled = false
}
// TODO: Cannot override from extensions
//extension DemoBaseViewController: ChartViewDelegate {
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
NSLog("chartValueSelected");
}
func chartValueNothingSelected(_ chartView: ChartViewBase) {
NSLog("chartValueNothingSelected");
}
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
}
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
}
}
extension DemoBaseViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if optionsTableView != nil {
return 1
}
return 0
}
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if optionsTableView != nil {
return options.count
}
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if optionsTableView != nil {
return 40.0;
}
return 44.0;
}
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell?.backgroundView = nil
cell?.backgroundColor = .clear
cell?.textLabel?.textColor = .white
}
cell?.textLabel?.text = self.options[indexPath.row].label
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if optionsTableView != nil {
tableView.deselectRow(at: indexPath, animated: true)
optionsTableView?.removeFromSuperview()
self.optionsTableView = nil
self.optionTapped(self.options[indexPath.row])
}
}
}
| apache-2.0 | 16cd74fd986a02e570ae7c60c56a0360 | 36.096154 | 178 | 0.576983 | 5.704689 | false | false | false | false |
loisie123/Cuisine-Project | Cuisine/MenuUserViewController.swift | 1 | 2532 | //
// MenuUserViewController.swift
// Cuisine
//
// Created by Lois van Vliet on 15-01-17.
// Copyright © 2017 Lois van Vliet. All rights reserved.
//
import UIKit
import Firebase
class MenuUserViewController: UIViewController {
@IBOutlet weak var nameUser: UILabel!
@IBOutlet weak var profiePicture: UIImageView!
var ref:FIRDatabaseReference?
var databaseHandle: FIRDatabaseHandle?
var UserName = String()
var daysOfTheWeek = [String]()
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
// show image:
let userID = FIRAuth.auth()?.currentUser?.uid
ref?.child("users").child(userID!).child("urlToImage").observeSingleEvent(of: .value, with: { (snapshot) in
if let urlImage = snapshot.value as? String{
if let url = NSURL(string: urlImage) {
if let data = NSData(contentsOf: url as URL) {
self.profiePicture.image = UIImage(data: data as Data)
}
}
}
})
ref?.child("users").child(userID!).child("name").observeSingleEvent(of: .value, with: { (snapshot) in
if let UserName = snapshot.value as? String{
self.nameUser.text = "Welcome \(UserName)"
}
})
}
//MARK:- Log out function
@IBAction func LogOutButtonPressed(_ sender: Any) {
let alertController = UIAlertController(title: "Log Out", message: "Are you sure you want to log out?", preferredStyle: UIAlertControllerStyle.alert)
let logOutAction = UIAlertAction(title: "Log Out", style: .default) {action in
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
print("SIGNED OUT")
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
self.performSegue(withIdentifier: "logoutVC", sender: nil)
}
let cancelAction = UIAlertAction(title: "No", style: .default)
alertController.addAction(cancelAction)
alertController.addAction(logOutAction)
self.present(alertController, animated: true, completion: nil)
}
}
| mit | 6b6b7c9ccf5547b936c3545e51b05d11 | 28.430233 | 157 | 0.546819 | 5.102823 | false | false | false | false |
txaidw/TapStrengthGestureRecognizer | MultiTapStrengthRecognizerView/MultiTapStrengthRecognizerView.swift | 1 | 5219 | //
// MultiTapStrengthRecognizerView.swift
// TapStrengthGestureRecognizer
//
// Created by Txai Wieser on 15/12/15.
// Copyright © 2015 Txai Wieser. All rights reserved.
//
import UIKit
import CoreMotion
class MultiTapStrengthRecognizerView: UIView, GlobalCMMotionManagerNotificationReceiver {
weak var delegate:TapStrengthGestureRecognizerDelegate?
var listOfTouches:[UIStrengthTouch] = []
var pressureValues:[Float] = []
// MARK: Default Initializers
func setup() {
self.multipleTouchEnabled = true
GlobalCMMotionManager.registerForNotification(self)
}
deinit {
GlobalCMMotionManager.unregisterForNotification(self)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func didRecognizeTapStrength(touch:UIStrengthTouch) {
print(touch.strength)
}
// MARK: MotionManager Notification
func motionManagerNotification() {
accelerateNotification(GlobalCMMotionManager.$.accelerometerData?.acceleration ?? CMAcceleration(x: 0, y: 0, z: 0))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.listOfTouches.appendContentsOf(touches.map { return UIStrengthTouch(touch: $0) })
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let t = touches { self.listOfTouches.removeObjectsInArray(t.map { return UIStrengthTouch(touch: $0) }) }
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.listOfTouches.removeObjectsInArray(touches.map { return UIStrengthTouch(touch: $0) })
}
func accelerateNotification(acceleration:CMAcceleration) {
if pressureValues.count >= 50 { pressureValues.removeFirst() }
pressureValues.append(Float(acceleration.z))
let average = pressureValues.reduce(0) { $0 + $1 } / Float(pressureValues.count)
for touch in listOfTouches {
if touch.attempts > 0 {
// calculate average pressure
// start with most recent past pressure sample
if touch.attempts == 3 {
let mostRecent = pressureValues[pressureValues.count-2];
touch.strength = fabs(average - mostRecent);
}
// caluculate pressure as difference between average and current acceleration
let diff = fabs(average - Float(acceleration.z));
if (touch.strength < diff) { touch.strength = diff; }
touch.attempts--;
if (touch.attempts == 0) {
didRecognizeTapStrength(touch)
self.listOfTouches.removeObject(touch)
}
}
}
}
}
// MARK: Extra Types
protocol TapStrengthGestureRecognizerDelegate:class {
func didReceiveTap(strength:Double)
}
class UIStrengthTouch: Equatable {
let touch:UITouch
var strength:Float
var attempts:Int
init(touch: UITouch, strength: Float = 0, attempts: Int = 3) {
self.touch = touch
self.strength = strength
self.attempts = attempts
}
}
func ==(lhs: UIStrengthTouch, rhs: UIStrengthTouch) -> Bool {
return lhs.touch == rhs.touch
}
protocol GlobalCMMotionManagerNotificationReceiver:class {
func motionManagerNotification()
}
class GlobalCMMotionManager {
static let sharedInstance = GlobalCMMotionManager()
static var $:CMMotionManager { return sharedInstance.motionManager }
let motionManager = CMMotionManager()
let GLOBAL_CM_MOTION_MANAGER = "GLOBAL_CM_MOTION_MANAGER"
private init() {
motionManager.accelerometerUpdateInterval = 0.001/60.0
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { [weak self] (data: CMAccelerometerData?, error:NSError?) -> Void in
if let me = self {
NSNotificationCenter.defaultCenter().postNotificationName(me.GLOBAL_CM_MOTION_MANAGER, object: me.motionManager)
}
}
}
static func registerForNotification(object:GlobalCMMotionManagerNotificationReceiver) {
NSNotificationCenter.defaultCenter().addObserver(object, selector: Selector("motionManagerNotification"), name: self.sharedInstance.GLOBAL_CM_MOTION_MANAGER, object: nil)
}
static func unregisterForNotification(object:GlobalCMMotionManagerNotificationReceiver) {
NSNotificationCenter.defaultCenter().removeObserver(object)
}
}
// Swift 2 Array Extension
extension Array where Element: Equatable {
mutating func removeObject(object: Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}
mutating func removeObjectsInArray(array: [Element]) {
for object in array {
self.removeObject(object)
}
}
} | mit | 960ec30a93d3fc678fb86f826e2627c9 | 33.335526 | 178 | 0.654657 | 4.760949 | false | false | false | false |
pixelglow/PredicatePal | PredicatePal/UnionExpression.swift | 1 | 2125 | //
// UnionExpression.swift
// PredicatePal
//
// Created by Glen Low on 7/12/2015.
// Copyright © 2015 Glen Low. All rights reserved.
//
import Foundation
/// A set union expression composing a set subexpression and a sequence subexpression.
/// - parameter E1: Full type of the LHS set subexpression.
/// - parameter E2: Full type of the RHS sequence subexpression.
public struct UnionExpression<E1: Expression, E2: Expression where E1.ExpressionType: SetType, E2.ExpressionType: CollectionType, E1.ExpressionType.Element == E2.ExpressionType.Generator.Element>: Expression {
public typealias ExpressionType = E1.ExpressionType
let leftSub: E1
let rightSub: E2
}
public prefix func*<E1 : Expression, E2: Expression>(expression: UnionExpression<E1, E2>) -> NSExpression {
return NSExpression(forUnionSet: *expression.leftSub, with: *expression.rightSub)
}
/// Union an expression with another expression.
/// - parameter leftSub: The LHS set subexpression.
/// - parameter rightSub: The RHS sequence subexpression.
/// - returns: The resulting set expression.
public func |<E1: Expression, E2: Expression>(leftSub: E1, rightSub: E2) -> UnionExpression<E1, E2> {
return UnionExpression(leftSub: leftSub, rightSub: rightSub)
}
/// Union an expression with a constant.
/// - parameter leftSub: The LHS set subexpression.
/// - parameter rightConst: The RHS sequence constant.
/// - returns: The resulting set expression.
public func |<E1: Expression, C: SequenceType where E1.ExpressionType.Element == C.Generator.Element>(leftSub: E1, rightConst: C) -> UnionExpression<E1, Const<C>> {
return UnionExpression(leftSub: leftSub, rightSub: Const(rightConst))
}
/// Union a constant with an expression.
/// - parameter leftConst: The LHS set constant.
/// - parameter rightSub: The RHS sequence subexpression.
/// - returns: The resulting set expression.
public func |<E2: Expression, C: SetType where E2.ExpressionType.Generator.Element == C.Element>(leftConst: C, rightSub: E2) -> UnionExpression<Const<C>, E2> {
return UnionExpression(leftSub: Const(leftConst), rightSub: rightSub)
}
| bsd-2-clause | eb363ec0c20008fcc9edce00b004e872 | 44.191489 | 209 | 0.742938 | 3.833935 | false | false | false | false |
arnaudbenard/my-npm | Pods/Charts/Charts/Classes/Renderers/ScatterChartRenderer.swift | 10 | 11581 | //
// ScatterChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol ScatterChartRendererDelegate
{
func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData!
func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter!
func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Double
func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Double
func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Double
func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Double
func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int
}
public class ScatterChartRenderer: ChartDataRendererBase
{
public weak var delegate: ScatterChartRendererDelegate?
public init(delegate: ScatterChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(#context: CGContext)
{
var scatterData = delegate!.scatterChartRendererData(self)
if (scatterData === nil)
{
return
}
for (var i = 0; i < scatterData.dataSetCount; i++)
{
var set = scatterData.getDataSetByIndex(i)
if (set !== nil && set!.isVisible)
{
drawDataSet(context: context, dataSet: set as! ScatterChartDataSet)
}
}
}
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawDataSet(#context: CGContext, dataSet: ScatterChartDataSet)
{
var trans = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
var entries = dataSet.yVals
var shapeSize = dataSet.scatterShapeSize
var shapeHalf = shapeSize / 2.0
var point = CGPoint()
var valueToPixelMatrix = trans.valueToPixelMatrix
var shape = dataSet.scatterShape
CGContextSaveGState(context)
for (var j = 0, count = Int(min(ceil(CGFloat(entries.count) * _animator.phaseX), CGFloat(entries.count))); j < count; j++)
{
var e = entries[j]
point.x = CGFloat(e.xIndex)
point.y = CGFloat(e.value) * phaseY
point = CGPointApplyAffineTransform(point, valueToPixelMatrix);
if (!viewPortHandler.isInBoundsRight(point.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y))
{
continue
}
if (shape == .Square)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
CGContextFillRect(context, rect)
}
else if (shape == .Circle)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
CGContextFillEllipseInRect(context, rect)
}
else if (shape == .Cross)
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor)
_lineSegments[0].x = point.x - shapeHalf
_lineSegments[0].y = point.y
_lineSegments[1].x = point.x + shapeHalf
_lineSegments[1].y = point.y
CGContextStrokeLineSegments(context, _lineSegments, 2)
_lineSegments[0].x = point.x
_lineSegments[0].y = point.y - shapeHalf
_lineSegments[1].x = point.x
_lineSegments[1].y = point.y + shapeHalf
CGContextStrokeLineSegments(context, _lineSegments, 2)
}
else if (shape == .Triangle)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
// create a triangle path
CGContextBeginPath(context)
CGContextMoveToPoint(context, point.x, point.y - shapeHalf)
CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf)
CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf)
CGContextClosePath(context)
CGContextFillPath(context)
}
else if (shape == .Custom)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
var customShape = dataSet.customScatterShape
if (customShape === nil)
{
return
}
// transform the provided custom path
CGContextSaveGState(context)
CGContextTranslateCTM(context, -point.x, -point.y)
CGContextBeginPath(context)
CGContextAddPath(context, customShape)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
CGContextRestoreGState(context)
}
public override func drawValues(#context: CGContext)
{
var scatterData = delegate!.scatterChartRendererData(self)
if (scatterData === nil)
{
return
}
var defaultValueFormatter = delegate!.scatterChartDefaultRendererValueFormatter(self)
// if values are drawn
if (scatterData.yValCount < Int(ceil(CGFloat(delegate!.scatterChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)))
{
var dataSets = scatterData.dataSets as! [ScatterChartDataSet]
for (var i = 0; i < scatterData.dataSetCount; i++)
{
var dataSet = dataSets[i]
if (!dataSet.isDrawValuesEnabled)
{
continue
}
var valueFont = dataSet.valueFont
var valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
var entries = dataSet.yVals
var positions = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency).generateTransformedValuesScatter(entries, phaseY: _animator.phaseY)
var shapeSize = dataSet.scatterShapeSize
var lineHeight = valueFont.lineHeight
for (var j = 0, count = Int(ceil(CGFloat(positions.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(positions[j].x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if ((!viewPortHandler.isInBoundsLeft(positions[j].x)
|| !viewPortHandler.isInBoundsY(positions[j].y)))
{
continue
}
var val = entries[j].value
var text = formatter!.stringFromNumber(val)
ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[j].x, y: positions[j].y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(#context: CGContext)
{
}
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var scatterData = delegate!.scatterChartRendererData(self)
var chartXMax = delegate!.scatterChartRendererChartXMax(self)
var chartXMin = delegate!.scatterChartRendererChartXMin(self)
var chartYMax = delegate!.scatterChartRendererChartYMax(self)
var chartYMin = delegate!.scatterChartRendererChartYMin(self)
CGContextSaveGState(context)
var pts = [CGPoint](count: 4, repeatedValue: CGPoint())
for (var i = 0; i < indices.count; i++)
{
var set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as! ScatterChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var xIndex = indices[i].xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX)
{
continue
}
let yVal = set.yValForXIndex(xIndex)
if (yVal.isNaN)
{
continue
}
var y = CGFloat(yVal) * _animator.phaseY; // get the y-position
pts[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax))
pts[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin))
pts[2] = CGPoint(x: CGFloat(chartXMin), y: y)
pts[3] = CGPoint(x: CGFloat(chartXMax), y: y)
var trans = delegate!.scatterChartRenderer(self, transformerForAxis: set.axisDependency)
trans.pointValuesToPixel(&pts)
// draw the highlight lines
CGContextStrokeLineSegments(context, pts, pts.count)
}
CGContextRestoreGState(context)
}
} | mit | c7a9a8be0fdbcae3f23f517d08fe38f8 | 36.849673 | 259 | 0.553579 | 5.969588 | false | false | false | false |
RajanFernandez/MotoParks | MotoParks/Model/ApplicationContext.swift | 1 | 1968 | //
// ApplicationContext.swift
// MotoParks
//
// Created by Rajan Fernandez on 31/03/17.
// Copyright © 2017 Rajan Fernandez. All rights reserved.
//
import MapKit
let LocationManagerIsAuthorised = "LocationManagerIsAuthorised"
class ApplicationContext: NSObject {
static let Key: String = "ApplicationContextKey"
let userLocation: CLLocation
var parks: [Park]
init(userLocation: CLLocation, parks: [Park]) {
self.userLocation = userLocation
self.parks = parks
}
init?(applicationContext: [String: Any]) {
guard
let latitude = applicationContext[Keys.userLocationLatitude] as? Double,
let longitude = applicationContext[Keys.userLocationLongitude] as? Double
else { return nil }
self.userLocation = CLLocation(latitude: latitude, longitude: longitude)
var parks = [Park]()
if let parksArray = applicationContext[Keys.parks] as? [[String: Any]] {
for parkDict in parksArray {
if let park = Park(dictionary: parkDict) {
parks.append(park)
}
}
}
self.parks = parks
}
// MARK: NSCoding
private struct Keys {
static let userLocationLatitude: String = "UserLocationLatitude"
static let userLocationLongitude: String = "UserLocationLongitude"
static let parks: String = "Parks"
}
var messagePayload: [String: Any] {
var dict = [String: Any]()
dict[Keys.userLocationLatitude] = userLocation.coordinate.latitude
dict[Keys.userLocationLongitude] = userLocation.coordinate.longitude
if parks.count > 0 {
var parksArray = [Any]()
for park in parks {
parksArray.append(park.dictionary)
}
dict[Keys.parks] = parksArray
}
return dict
}
}
| mit | de58117c68c5f8cc545756aa94edc55d | 27.926471 | 85 | 0.59634 | 4.705742 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/Swizzle/SwizzleManager.swift | 1 | 1997 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
import WebKit
public final class SwizzleManager {
private static var didSwizzle = false
static var options: SwizzleOptions = .all
private init() {}
/// An entry point to enabled extra functionality for some properties that Xcore
/// swizzles. It also provides a hook swizzle additional selectors.
///
/// **Usage**
///
/// Start the `SwizzleManager` when your app launches:
///
///
/// ```swift
/// func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/// SwizzleManager.start([
/// UIViewController.runOnceSwapSelectors
/// ])
/// return true
/// }
/// ```
///
/// - Parameters:
/// - options: A list of options to customize which Xcore classes to swizzle.
/// - additionalSelectors: additional selectors to swizzle.
public static func start(
options: SwizzleOptions = .all,
_ additionalSelectors: @autoclosure () -> [() -> Void] = []
) {
guard !didSwizzle else { return }
defer { didSwizzle = true }
self.options = options
xcoreSwizzle(options: options)
additionalSelectors().forEach {
$0()
}
}
private static func xcoreSwizzle(options: SwizzleOptions) {
if options.contains(.userContentController) {
WKUserContentController.runOnceSwapSelectors()
}
}
}
extension SwizzleManager {
/// A list of features available to swizzle.
public struct SwizzleOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let userContentController = Self(rawValue: 1 << 0)
public static let all: Self = [
userContentController
]
}
}
| mit | b35f40cd0b701ec8ff52552785c13ed0 | 27.112676 | 148 | 0.611723 | 4.965174 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/SwitchCaseOnNewlineRule.swift | 1 | 5807 | //
// SwitchCaseOnNewlineRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 10/15/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct SwitchCaseOnNewlineRule: ConfigurationProviderRule, Rule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "switch_case_on_newline",
name: "Switch Case on Newline",
description: "Cases inside a switch should always be on a newline",
nonTriggeringExamples: [
"case 1:\n return true",
"default:\n return true",
"case let value:\n return true",
"/*case 1: */return true",
"//case 1:\n return true",
"let x = [caseKey: value]",
"let x = [key: .default]",
"if case let .someEnum(value) = aFunction([key: 2]) {",
"guard case let .someEnum(value) = aFunction([key: 2]) {",
"for case let .someEnum(value) = aFunction([key: 2]) {",
"case .myCase: // error from network",
"case let .myCase(value) where value > 10:\n return false",
"enum Environment {\n case development\n}",
"enum Environment {\n case development(url: URL)\n}",
"enum Environment {\n case development(url: URL) // staging\n}",
"case #selector(aFunction(_:)):\n return false\n"
],
triggeringExamples: [
"↓case 1: return true",
"↓case let value: return true",
"↓default: return true",
"↓case \"a string\": return false",
"↓case .myCase: return false // error from network",
"↓case let .myCase(value) where value > 10: return false",
"↓case #selector(aFunction(_:)): return false\n"
]
)
public func validate(file: File) -> [StyleViolation] {
let pattern = "(case[^\n]*|default):[^\\S\n]*[^\n]"
return file.rangesAndTokens(matching: pattern).filter { range, tokens in
guard let firstToken = tokens.first, tokenIsKeyword(token: firstToken) else {
return false
}
let tokenString = content(for: firstToken, file: file)
guard ["case", "default"].contains(tokenString) else {
return false
}
// check if the first token in the line is `case`
let lineAndCharacter = file.contents.bridge()
.lineAndCharacter(forCharacterOffset: range.location)
guard let (lineNumber, _) = lineAndCharacter else {
return false
}
let line = file.lines[lineNumber - 1]
let allLineTokens = file.syntaxMap.tokens(inByteRange: line.byteRange)
let lineTokens = allLineTokens.filter(tokenIsKeyword)
guard let firstLineToken = lineTokens.first else {
return false
}
let firstTokenInLineString = content(for: firstLineToken, file: file)
guard firstTokenInLineString == tokenString else {
return false
}
return isViolation(lineTokens: allLineTokens, file: file, line: line)
}.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.0.location))
}
}
private func tokenIsKeyword(token: SyntaxToken) -> Bool {
return SyntaxKind(rawValue: token.type) == .keyword
}
private func tokenIsComment(token: SyntaxToken) -> Bool {
guard let kind = SyntaxKind(rawValue: token.type) else {
return false
}
return SyntaxKind.commentKinds().contains(kind)
}
private func content(for token: SyntaxToken, file: File) -> String {
return contentForRange(start: token.offset, length: token.length, file: file)
}
private func contentForRange(start: Int, length: Int, file: File) -> String {
return file.contents.bridge().substringWithByteRange(start: start, length: length) ?? ""
}
private func trailingComments(tokens: [SyntaxToken]) -> [SyntaxToken] {
var lastWasComment = true
return tokens.reversed().filter { token in
let shouldRemove = lastWasComment && tokenIsComment(token: token)
if !shouldRemove {
lastWasComment = false
}
return shouldRemove
}.reversed()
}
private func isViolation(lineTokens: [SyntaxToken], file: File, line: Line) -> Bool {
let trailingCommentsTokens = trailingComments(tokens: lineTokens)
guard let firstToken = lineTokens.first, !isEnumCase(file: file, token: firstToken) else {
return false
}
var commentsLength = 0
if let firstComment = trailingCommentsTokens.first,
let lastComment = trailingCommentsTokens.last {
commentsLength = (lastComment.offset + lastComment.length) - firstComment.offset
}
let line = contentForRange(start: line.byteRange.location,
length: line.byteRange.length - commentsLength, file: file)
let cleaned = line.trimmingCharacters(in: .whitespacesAndNewlines)
return !cleaned.hasSuffix(":")
}
private func isEnumCase(file: File, token: SyntaxToken) -> Bool {
let kinds = file.structure.kinds(forByteOffset: token.offset).flatMap {
SwiftDeclarationKind(rawValue: $0.kind)
}
// it's a violation unless it's actually an enum case declaration
return kinds.contains(.enumcase)
}
}
| mit | 0aa773e392d8422c4596c22b8f2979bf | 37.872483 | 98 | 0.59962 | 4.652209 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Services/UserLocationService.swift | 1 | 6869 | //
// UserLocationService.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 30.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import CoreLocation
import RxSwift
import RxCoreLocation
// MARK: - Domain-Specific Errors
extension UserLocationService {
enum DomainError: String, Error {
var domain: String { "UserLocationService" }
case locationAuthorizationError = "Trying access the user location, but sufficient authorization was not granted."
case locationUndeterminableError = "Trying access the user location, but it could not be determined."
}
}
// MARK: - Persistency Keys
private extension UserLocationService {
enum PersistencyKeys {
case userLocation
case authorizationStatus
var collection: String {
switch self {
case .userLocation: return "/user_location/user_location/"
case .authorizationStatus: return "/user_location/authorization_status/"
}
}
var identifier: String {
switch self {
case .userLocation: return "default"
case .authorizationStatus: return "default"
}
}
var identity: PersistencyModelIdentity {
PersistencyModelIdentity(collection: collection, identifier: identifier)
}
}
}
// MARK: - Dependencies
extension UserLocationService {
struct Dependencies {
let persistencyService: PersistencyProtocol
}
}
// MARK: - Class Definition
final class UserLocationService {
// MARK: - Properties
private let dependencies: Dependencies
private let locationManager: CLLocationManager
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
}
}
// MARK: - User Location Permissions Requesting
protocol UserLocationPermissionRequesting {
func requestWhenInUseLocationAccess() -> Completable
func createSaveLocationAuthorizationStatusCompletable(_ authorizationStatus: UserLocationAuthorizationStatus) -> Completable
func createGetLocationAuthorizationStatusObservable() -> Observable<UserLocationAuthorizationStatus?>
}
extension UserLocationService: UserLocationPermissionRequesting {
func requestWhenInUseLocationAccess() -> Completable {
Completable
.create { handler in
let locationManager = CLLocationManager()
guard locationManager.authorizationStatus == .notDetermined else {
handler(.completed)
return Disposables.create()
}
locationManager.requestWhenInUseAuthorization()
handler(.completed)
return Disposables.create()
}
}
func createSaveLocationAuthorizationStatusCompletable(_ authorizationStatus: UserLocationAuthorizationStatus) -> Completable {
dependencies.persistencyService
.saveResource(
PersistencyModel(identity: PersistencyKeys.authorizationStatus.identity, entity: authorizationStatus),
type: UserLocationAuthorizationStatus.self
)
}
func createGetLocationAuthorizationStatusObservable() -> Observable<UserLocationAuthorizationStatus?> {
dependencies.persistencyService
.observeResource(
with: PersistencyKeys.authorizationStatus.identity,
type: UserLocationAuthorizationStatus.self
)
.map { $0?.entity }
}
func createUserDidDecideLocationAccessAuthorizationCompletable() -> Completable {
createGetLocationAuthorizationStatusObservable()
.filterNil()
.skip { $0.authorizationStatus == .undetermined }
.take(1)
.asSingle()
.flatMapCompletable { _ in Completable.emptyCompletable }
}
}
// MARK: - User Location Permissions Writing
protocol UserLocationPermissionWriting {
func createSaveLocationAuthorizationStatusCompletable(_ authorizationStatus: UserLocationAuthorizationStatus) -> Completable
}
extension UserLocationService: UserLocationPermissionWriting {}
// MARK: - User Location Permissions Reading
protocol UserLocationPermissionReading {
func createGetLocationAuthorizationStatusObservable() -> Observable<UserLocationAuthorizationStatus?>
func createUserDidDecideLocationAccessAuthorizationCompletable() -> Completable
}
extension UserLocationService: UserLocationPermissionReading {}
// MARK: - User Location Accessing
protocol UserLocationAccessing {
func createDeleteUserLocationCompletable() -> Completable
func createSaveUserLocationCompletable(location: CLLocation?) -> Completable
func createGetUserLocationObservable() -> Observable<CLLocation?>
}
extension UserLocationService: UserLocationAccessing {
func createDeleteUserLocationCompletable() -> Completable {
dependencies.persistencyService.deleteResource(with: PersistencyKeys.userLocation.identity)
}
func createSaveUserLocationCompletable(location: CLLocation?) -> Completable {
guard let location = location else {
return Completable.create { handler in
handler(.completed)
return Disposables.create()
}
}
return dependencies.persistencyService.saveResource(
PersistencyModel(
identity: PersistencyKeys.userLocation.identity,
entity: UserLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
),
type: UserLocation.self)
}
func createGetUserLocationObservable() -> Observable<CLLocation?> {
dependencies.persistencyService
.observeResource(with: PersistencyKeys.userLocation.identity, type: UserLocation.self)
.map { userLocation in
guard let userLocation = userLocation else {
return nil
}
return CLLocation(latitude: userLocation.entity.latitude, longitude: userLocation.entity.longitude)
}
}
}
// MARK: - User Location Writing
protocol UserLocationWriting {
func createDeleteUserLocationCompletable() -> Completable
func createSaveUserLocationCompletable(location: CLLocation?) -> Completable
}
extension UserLocationService: UserLocationWriting {}
// MARK: - User Location Reading
protocol UserLocationReading {
func createGetUserLocationObservable() -> Observable<CLLocation?>
}
extension UserLocationService: UserLocationReading {}
// MARK: - Helpers
extension UserLocationAuthorizationStatus {
var authorizationStatusIsSufficient: Bool {
switch self.authorizationStatus {
case .undetermined, .systemRevoked, .userRevoked:
return false
case .authorizedWhileUsing, .authorizedAnytime:
return true
}
}
}
extension CLAuthorizationStatus {
var authorizationStatusIsSufficient: Bool {
switch self {
case .notDetermined, .restricted, .denied:
return false
case .authorizedWhenInUse, .authorizedAlways:
return true
@unknown default:
return false
}
}
}
| mit | 7b971f6722d7b4a3927d56c5953150e8 | 28.86087 | 128 | 0.747234 | 5.429249 | false | false | false | false |
mkoehnke/AnimatedBlurLabel | Example/AnimatedBlurLabelDemo/UIKitExtensions.swift | 1 | 2182 | //
// UIKitExtensions.swift
//
// Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension UILabel {
func setTitle(_ title: String?, subtitle: String?, alignment: NSTextAlignment = .center) {
if let title = title, let subtitle = subtitle {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
paragraph.alignment = alignment
paragraph.lineSpacing = 1.6;
paragraph.lineHeightMultiple = 0.95;
let attributes = [NSParagraphStyleAttributeName : paragraph, NSForegroundColorAttributeName : textColor, NSFontAttributeName : UIFont.systemFont(ofSize: 33.0, weight: UIFontWeightThin)];
let string = NSMutableAttributedString(string: "\(title)\n\(subtitle)", attributes: attributes)
string.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 42.0, weight: UIFontWeightBold), range: NSMakeRange(0, title.characters.count))
attributedText = string
}
}
}
| mit | 264d9d77a12ea2417d2835fdf0198e86 | 48.590909 | 198 | 0.718148 | 5.004587 | false | false | false | false |
jxxcarlson/exploring_swift | heatFlow.playground/Contents.swift | 1 | 3205 |
import Cocoa
typealias vector = [Double]
typealias matrix = [vector]
func next_state(x: vector, k: Double) -> vector {
var y = vector(count: x.count, repeatedValue:0.0)
let lastIndex = x.count - 1
// Boundary conditions:
y[0] = x[0]
y[lastIndex] = x[lastIndex]
for (var i = 1; i < lastIndex; i++) {
let u = (k/2)*(x[i-1] + x[i + 1])
let v = (1-k)*x[i]
y[i] = u + v
}
return y
}
func run(initial_state:vector, n: Int) -> matrix {
var sa:matrix = [initial_state]
for(var i = 1; i < n; i++) {
sa = sa + [next_state(sa[i-1], k: 0.8)]
}
return sa
}
var c1: vector = [1.0, 0, 0, 0, 0, 0.3, 0.9, 0.3, 0, 0]
var result = run(c1, n: 10)
for state in result {
print(state)
}
print(result[0])
result.count
result[0].count
class Thermograph {
var state = vector()
init( data: vector ) {
state = data
}
func draw(frame: NSRect) {
let width = frame.width
let height = frame.height
let n = state.count
var x = CGFloat(0.0)
let dx = CGFloat(width/CGFloat(n))
for (var i = 0; i < n; i++) {
let currentRect = NSMakeRect(x, 0, dx, height)
x = x + dx
let temperature = CGFloat(state[i])
let currentColor = NSColor(red: temperature, green: 0.0,
blue: 0.0, alpha: 1.0)
currentColor.set()
NSRectFill(currentRect)
}
}
}
class Thermograph2D {
var state = matrix()
init( data: matrix ) {
state = data
}
func draw(frame: NSRect) {
let width = frame.width
let height = frame.height
let n_rows = state.count
let n_cols = (state[0]).count
var x = CGFloat(0.0)
var y = CGFloat(0.0)
let dx = CGFloat(width/CGFloat(n_cols))
let dy = CGFloat(height/CGFloat(n_rows))
for (var row = 0; row < n_rows; row++) {
x = CGFloat(0.0)
for (var col = 0; col < n_cols; col++ ) {
let currentRect = NSMakeRect(x, y, dx, dy)
x = x + dx
let temperature = CGFloat(state[row][col])
print("t[\(row),\(col)] = \(temperature)")
let currentColor = NSColor(red: temperature, green: 0.0,
blue: 0.0, alpha: 1.0)
currentColor.set()
NSRectFill(currentRect)
}
y = y + dy
}
}
}
let k = 3
let tg = Thermograph(data:result[k])
// let tg = Thermograph(data:[1, 0.8, 0.6, 0.4, 0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
print(tg.state)
class GView: NSView {
override func drawRect(dirtyRect: NSRect) {
tg.draw(frame)
}
}
let view = GView(frame: NSRect(x: 0, y: 0, width: 500, height: 20))
let tg2d = Thermograph2D(data: result)
class GView2D: NSView {
override func drawRect(dirtyRect: NSRect) {
tg2d.draw(frame)
}
}
let view2D = GView2D(frame: NSRect(x: 0, y: 0, width: 500, height: 500))
| mit | 5596f6832377fc9fadce2b51395daf51 | 20.085526 | 83 | 0.489236 | 3.304124 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/mosaic-layout-master/TRMosaicLayout/Classes/TRMosaicLayout.swift | 3 | 10458 | //
// TRMosaicLayout.swift
// Pods
//
// Created by Vincent Le on 7/1/16.
//
//
import UIKit
public enum TRMosaicCellType {
case big
case small
}
public protocol TRMosaicLayoutDelegate {
func collectionView(_ collectionView:UICollectionView, mosaicCellSizeTypeAtIndexPath indexPath:IndexPath) -> TRMosaicCellType
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout: TRMosaicLayout, insetAtSection:Int) -> UIEdgeInsets
func heightForSmallMosaicCell() -> CGFloat
}
open class TRMosaicLayout: UICollectionViewLayout {
open var delegate:TRMosaicLayoutDelegate!
var columns = TRMosaicColumns()
var cachedCellLayoutAttributes = [IndexPath:UICollectionViewLayoutAttributes]()
let numberOfColumnsInSection = 3
var contentWidth:CGFloat {
get { return collectionView!.bounds.size.width }
}
// MARK: UICollectionViewLayout Implementation
override open func prepare() {
super.prepare()
resetLayoutState()
configureMosaicLayout()
}
/**
Iterates throught all items in section and
creates new layouts for each item as a mosaic cell
*/
func configureMosaicLayout() {
// Queue containing cells that have yet to be added due to column constraints
var smallCellIndexPathBuffer = [IndexPath]()
var lastBigCellOnLeftSide = false
// Loops through all items in the first section, this layout has only one section
for cellIndex in 0..<collectionView!.numberOfItems(inSection: 0) {
(lastBigCellOnLeftSide, smallCellIndexPathBuffer) = createCellLayout(withIndexPath: cellIndex,
bigCellSide: lastBigCellOnLeftSide,
cellBuffer: smallCellIndexPathBuffer)
}
if !smallCellIndexPathBuffer.isEmpty {
addSmallCellLayout(atIndexPath: smallCellIndexPathBuffer[0], atColumn: indexOfShortestColumn())
smallCellIndexPathBuffer.removeAll()
}
}
/**
Creates new layout for the cell at specified index path
- parameter index: index path of cell
- parameter bigCellSide: specifies which side to place big cell
- parameter cellBuffer: buffer containing small cell
- returns: tuple containing cellSide and cellBuffer, only one of which will be mutated
*/
func createCellLayout(withIndexPath index: Int, bigCellSide: Bool, cellBuffer: [IndexPath]) -> (Bool, [IndexPath]) {
let cellIndexPath = IndexPath(item: index, section: 0)
let cellType:TRMosaicCellType = mosaicCellType(index: cellIndexPath)
var newBuffer = cellBuffer
var newSide = bigCellSide
if cellType == .big {
newSide = createBigCellLayout(withIndexPath: cellIndexPath, cellSide: bigCellSide)
} else if cellType == .small {
newBuffer = createSmallCellLayout(withIndexPath: cellIndexPath, buffer: newBuffer)
}
return (newSide, newBuffer)
}
/**
Creates new layout for the big cell at specified index path
- returns: returns new cell side
*/
func createBigCellLayout(withIndexPath indexPath:IndexPath, cellSide: Bool) -> Bool {
addBigCellLayout(atIndexPath: indexPath, atColumn: cellSide ? 1 : 0)
return !cellSide
}
/**
Creates new layout for the small cell at specified index path
- returns: returns new cell buffer
*/
func createSmallCellLayout(withIndexPath indexPath:IndexPath, buffer: [IndexPath]) -> [IndexPath] {
var newBuffer = buffer
newBuffer.append(indexPath)
if newBuffer.count >= 2 {
let column = indexOfShortestColumn()
addSmallCellLayout(atIndexPath: newBuffer[0], atColumn: column)
addSmallCellLayout(atIndexPath: newBuffer[1], atColumn: column)
newBuffer.removeAll()
}
return newBuffer
}
/**
Returns the entire content view of the collection view
*/
override open var collectionViewContentSize: CGSize {
get {
let height = columns.smallestColumn.columnHeight
return CGSize(width: contentWidth, height: height)
}
}
/**
Returns all layout attributes within the given rectangle
*/
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributesInRect = [UICollectionViewLayoutAttributes]()
cachedCellLayoutAttributes.forEach {
if rect.intersects($1.frame) {
attributesInRect.append($1)
}
}
return attributesInRect
}
/**
Returns all layout attributes for the current indexPath
*/
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.cachedCellLayoutAttributes[indexPath]
}
// MARK: Layout
/**
Configures the layout for cell type: Big
Adds the new layout to cache
Updates the column heights for each effected column
*/
func addBigCellLayout(atIndexPath indexPath:IndexPath, atColumn column:Int) {
let cellHeight = layoutAttributes(withCellType: .big, indexPath: indexPath, atColumn: column)
columns[column].appendToColumn(withHeight: cellHeight)
columns[column + 1].appendToColumn(withHeight: cellHeight)
}
/**
Configures the layout for cell type: Small
Adds the new layout to cache
Updates the column heights for each effected column
*/
func addSmallCellLayout(atIndexPath indexPath:IndexPath, atColumn column:Int) {
let cellHeight = layoutAttributes(withCellType: .small, indexPath: indexPath, atColumn: column)
columns[column].appendToColumn(withHeight: cellHeight)
}
/**
Creates layout attribute with the given parameter and adds it to cache
- parameter type: Cell type
- parameter indexPath: Index of cell
- parameter column: Index of column
- returns: new cell height from layout
*/
func layoutAttributes(withCellType type:TRMosaicCellType, indexPath:IndexPath, atColumn column:Int) -> CGFloat {
let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let frame = mosaicCellRect(withType: type, atIndexPath: indexPath, atColumn: column)
layoutAttributes.frame = frame
let cellHeight = layoutAttributes.frame.size.height + insetForMosaicCell().top
cachedCellLayoutAttributes[indexPath] = layoutAttributes
return cellHeight
}
// MARK: Cell Sizing
/**
Creates the bounding rectangle for the given cell type
- parameter type: Cell type
- parameter indexPath: Index of cell
- parameter column: Index of column
- returns: Bounding rectangle
*/
func mosaicCellRect(withType type: TRMosaicCellType, atIndexPath indexPath:IndexPath, atColumn column:Int) -> CGRect {
var cellHeight = cellContentHeightFor(mosaicCellType: type)
var cellWidth = cellContentWidthFor(mosaicCellType: type)
var originX = CGFloat(column) * (contentWidth / CGFloat(numberOfColumnsInSection))
var originY = columns[column].columnHeight
let sectionInset = insetForMosaicCell()
originX += sectionInset.left
originY += sectionInset.top
cellWidth -= sectionInset.right
cellHeight -= sectionInset.bottom
return CGRect(x: originX, y: originY, width: cellWidth, height: cellHeight)
}
/**
Calculates height for the given cell type
- parameter cellType: Cell type
- returns: Calculated height
*/
func cellContentHeightFor(mosaicCellType cellType:TRMosaicCellType) -> CGFloat {
let height = delegate.heightForSmallMosaicCell()
if cellType == .big {
return height * 2
}
return height
}
/**
Calculates width for the given cell type
- parameter cellType: Cell type
- returns: Calculated width
*/
func cellContentWidthFor(mosaicCellType cellType:TRMosaicCellType) -> CGFloat {
let width = contentWidth / 3
if cellType == .big {
return width * 2
}
return width
}
// MARK: Orientation
/**
Determines if a layout update is needed when the bounds have been changed
- returns: True if layout needs update
*/
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let currentBounds:CGRect = self.collectionView!.bounds
if currentBounds.size.equalTo(newBounds.size) {
self.prepare()
return true
}
return false
}
// MARK: Delegate Wrappers
/**
Returns the cell type for the specified cell at index path
- returns: Cell type
*/
func mosaicCellType(index indexPath:IndexPath) -> TRMosaicCellType {
return delegate.collectionView(collectionView!, mosaicCellSizeTypeAtIndexPath:indexPath)
}
/**
- returns: Returns the UIEdgeInsets that will be used for every cell as a border
*/
func insetForMosaicCell() -> UIEdgeInsets {
return delegate.collectionView(collectionView!, layout: self, insetAtSection: 0)
}
}
extension TRMosaicLayout {
// MARK: Helper Functions
/**
- returns: The index of the column with the smallest height
*/
func indexOfShortestColumn() -> Int {
var index = 0
for i in 1..<numberOfColumnsInSection {
if columns[i] < columns[index] {
index = i
}
}
return index
}
/**
Resets the layout cache and the heights array
*/
func resetLayoutState() {
columns = TRMosaicColumns()
cachedCellLayoutAttributes = [IndexPath:UICollectionViewLayoutAttributes]()
}
}
| mit | 24ee5d8d03d89e5e326592a0d5ea3a9c | 31.478261 | 139 | 0.635494 | 5.438378 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers/27628-swift-abstractclosureexpr-setparams.swift | 9 | 2012 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
let a {
{
{
{{
{{{
typea
{
}typealias e:A<T:T {{{{
typealias B }
{struct A {()a{struct A
{let t:d
{
enum A { typealias B }}
class d
{
{-> : A{{{
}}
{
case,
{
{{
func c{{struct B? = Int }
var:a{
class A
class C<D: d
case,
{{
{
{{
class d
{
func c{{
}
{struct B? = nil
{
class d where h:e
func crash<T>:a{
}}typealias e{
{
^
let i}
{
{{
{
{
}}}}}}}}}}}
"
struct A {{
{e a{
{
{struct Q{
{
{{
{{struct B<H , f=1
class A<D: A
{{{
class A{{
{
}}typealias B }
{
}
"
{e a{func e{
{{
{let g{{{
^
{
for h:A
class A {
protocol d
{{
{
{()a{{
func a{{
class A {class a: D: C<H , f=1
{
{{
{
}protocol d
{
}}
enum A {struct A {{
func crash<d {let t:T {T> : C{
{
{{{
typea
}
var b{
{{
{{
typea
{{{{{
func c{
var d{
let a {ypealias F=i}
{
{{
protocol A c{
{
enum S{
let h:A<ere d
class A<T> : A {{g=1
func c{func a{A<T {
let h:e{{
case,
{{
{
{let a{{
{class a
{{
class a{ typealias e:a
{
{
{
func crash<T {
{
{
{{
{ypealias F=0A.c
{}}}}
{{
var b{{{
func c{
{{{let g{
{{
var f
typealias e
}
struct A
enum A { :{struct c:{
enum S<D.c{
struct A
protocol A { :a{
{
{func e:a{
{
{{
}
{
}
var b{
var b{struct B:A {{
{
{
enum A {A
}
{{
{
{ypealias F=0A.c:a{->:{
( "
{
{{
}}}}
{
{() ->{
class a {
{
{
class A {
{-> Bool {{
func crash<T {{{{{
{d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{{g=i{}class C>{
{
{{struct A<T> Bool {
protocol A { typealias e{{
{
class A
class a {let h=i}}class a {let:a{
struct A<D: D.B? = Int }}}
{class A{
var:d
typea
s :A {
{
typea
class A{{
{
{
{
for}
{{let a {
class A{{
{
let<T al c:a{
{let a {
{
{()a{{()a
{{
class A
func c
{}
{
{
struct B<T:A {
{{
{
{{class a{T> Bool {ypealias F=c:d{{class A{class
{
let h:A{
var b{{{
func a{let c{{
{let<T
{
{{{let g=1
{
{
{{
func b {
protocol a{
class C>() ->:a{
class A{
typealias B }}}class a {{let h:a{{{
{
typealias d
{
| apache-2.0 | f6e90ffc3a0292c2b1c32727e52e1131 | 8.022422 | 87 | 0.528827 | 2.069959 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Auth/AuthManager.swift | 1 | 7218 | // Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class AuthManager {
static var sharedInstance = AuthManager()
private var accessTokenCache: AccessToken?
// OAuth parameters
private var clientAccountCache: ClientAccount?
private var scope: String?
private var redirectUri: String?
private let AccessTokenExpirationBufferInMinutes = 15
// OAuth flow has client account
private var isOAuthMode: Bool {
return clientAccount != nil
}
private var accessToken: AccessToken? {
get {
if accessTokenCache == nil {
accessTokenCache = KeychainManager.sharedInstance.fetchAccessToken()
}
return accessTokenCache
}
set {
accessTokenCache = newValue
KeychainManager.sharedInstance.store(accessToken: newValue)
}
}
private var clientAccount: ClientAccount? {
get {
if clientAccountCache == nil {
clientAccountCache = KeychainManager.sharedInstance.fetchClientAccount()
}
return clientAccountCache
}
set {
clientAccountCache = newValue
KeychainManager.sharedInstance.store(clientAccount: newValue)
}
}
func authorize(clientAccount: ClientAccount, scope: String, redirectUri: String, controller: UIViewController) {
self.clientAccount = clientAccount
self.scope = scope
self.redirectUri = redirectUri
authorizeFrom(controller: controller)
}
func authorize(token: String) {
accessToken = AccessToken(accessToken: token)
}
func deauthorize() {
accessToken = nil
clientAccount = nil
}
func authorized() -> Bool {
guard let _ = accessToken?.accessTokenString else {
return false
}
guard refreshAccessTokenWithExpirationBuffer(AccessTokenExpirationBufferInMinutes) else {
return false
}
return true
}
func getAuthorization() -> [String: String]? {
guard refreshAccessTokenWithExpirationBuffer(AccessTokenExpirationBufferInMinutes) else {
return nil
}
if let accessTokenString = self.accessToken?.accessTokenString {
return ["Authorization": "Bearer " + accessTokenString]
}
return nil
}
private func authorizeFrom(controller: UIViewController) {
guard isOAuthMode else {
return
}
let url = createAuthCodeRequestURL()
let web = ConnectController(URL: url) { url in
if let accessToken = self.fetchAccessTokenFromRedirectUri(url) {
self.accessToken = accessToken
return true
}
return false
}
let navigationController = UINavigationController(rootViewController: web)
controller.present(navigationController, animated: true, completion: nil)
}
private func createAuthCodeRequestURL() -> URL {
var components = URLComponents(string: "https://api.ciscospark.com/v1/authorize")!
components.queryItems = [
URLQueryItem(name: "client_id", value: (clientAccount?.clientId)!),
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(name: "redirect_uri", value: redirectUri!.encodeQueryParamString),
URLQueryItem(name: "scope", value: scope!.encodeQueryParamString),
URLQueryItem(name: "state", value: "set_state_here")]
components.percentEncodedQuery = components.query
return components.url!
}
private func fetchAccessTokenFromRedirectUri(_ url: URL) -> AccessToken? {
guard url.absoluteString.lowercased().contains(redirectUri!.lowercased()) else {
return nil
}
let query = url.queryParameters
if let error = query["error"] {
Logger.error("ErrorCode: \(error)")
if let description = query["error_description"] {
Logger.error("Error description: \(description.decodeString)")
}
} else if let authCode = query["code"] {
do {
return try OAuthClient().fetchAccessTokenFromOAuthCode(authCode, clientAccount: clientAccount!, redirectUri: redirectUri!)
} catch let error as NSError {
Logger.error("Failed to fetch access token: \(error.localizedFailureReason)")
}
}
return nil
}
private func refreshAccessTokenWithExpirationBuffer(_ bufferInMinutes: Int) -> Bool {
guard accessTokenWillExpireInMinutes(bufferInMinutes) else {
return true
}
return refreshAccessToken()
}
private func accessTokenWillExpireInMinutes(_ minutes: Int) -> Bool {
// Assume access token (authorized with signle token instead of OAuth parameters) won't expire.
guard isOAuthMode else {
return false
}
let thresholdDate = Date(timeInterval: Double(minutes*60), since: Date())
let expirationdate = accessToken!.accessTokenExpirationDate
return thresholdDate.isAfterDate(expirationdate)
}
private func refreshAccessToken() -> Bool {
do {
let accessToken = try OAuthClient().refreshAccessTokenFromRefreshToken((self.accessToken?.refreshTokenString)!, clientAccount: clientAccount!)
accessToken.refreshTokenString = self.accessToken?.refreshTokenString
accessToken.refreshTokenExpiration = self.accessToken?.refreshTokenExpiration
self.accessToken = accessToken
} catch let error as NSError {
deauthorize()
Logger.error("Failed to refresh token: \(error.localizedFailureReason)")
PhoneNotificationCenter.sharedInstance.notifyRefreshAccessTokenFailed()
return false
}
return true
}
}
| mit | f00e421480b0a462bcd2c5ba961d73fe | 35.454545 | 154 | 0.640205 | 5.535276 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/ChipresAna/Programa3.swift | 1 | 859 | /*
Title: Ejercicio 53 Lección 1
Autor: Chipres Castellanos Ana Maria
Description: Encontrar e imprimir la suma:
1+3+5
1+3+5+7
1+3+5+7+9
1+3+5+7+9+11
1+3+5+7+9+11+13
1+3+5+7+9+11+13+....+(N-1)+N
Date: 1-03-2017
*/
//importar libreria
import Foundation
//Cantidad de iteraciones
var veces = 6
var i = 0
var num = 1
var suma = 0
//Creacion del arreglo
var miArreglo: [Int] = []
while i <= veces
{
//Hacemos la formula
var nuevoNum = num + 2
//Agregamos al arreglo
miArreglo.append(nuevoNum)
//Incremento
i = i + 1
//Cambiar valores
num = nuevoNum
}
//Sumando todos los valores
for elementos in miArreglo {
print(elementos)
//Sumando
suma = suma + elementos
}
//Imprimir respuesta
print("\n\nLa suma es: ")
print(suma) | gpl-3.0 | 961fa0435ba76ba5192ba7a2c7fad9eb | 14.245283 | 51 | 0.583236 | 2.533923 | false | false | false | false |
Limon-O-O/Medusa | Medusa/Utilities.swift | 1 | 2856 | //
// Utilities.swift
// MED
//
// Created by Limon on 6/16/16.
// Copyright © 2016 MED. All rights reserved.
//
import AVFoundation
extension Med where Base: AVCaptureDeviceInput {
static func captureDeviceInput(withPosition position: AVCaptureDevice.Position) throws -> AVCaptureDeviceInput {
guard let captureDevice = position == .back ? AVCaptureDevice.med.CaptureDevice.back.value : AVCaptureDevice.med.CaptureDevice.front.value,
let captureDeviceInput = try? AVCaptureDeviceInput(device: captureDevice) else { throw MedusaError.captureDeviceError }
return captureDeviceInput
}
static func audioDeviceInput() throws -> AVCaptureDeviceInput {
guard let audioDevice = AVCaptureDevice.default(for: .audio),
let audioDeviceInput = try? AVCaptureDeviceInput(device: audioDevice) else { throw MedusaError.audioDeviceError }
return audioDeviceInput
}
}
extension Med where Base: AVCaptureDevice {
fileprivate enum CaptureDevice {
case back
case front
var value: AVCaptureDevice? {
switch self {
case .back:
return AVCaptureDevice.med.device(withPosition: .back)
case .front:
return AVCaptureDevice.med.device(withPosition: .front)
}
}
}
private static func device(withPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? {
return AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: .video, position: position)
}
}
extension Med where Base: FileManager {
static func freeDiskSpace(min: UInt64 = 30) -> Bool {
do {
let attribute = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
let freesize = attribute[FileAttributeKey.systemFreeSize] as? UInt64 ?? 0
let minSzie: UInt64 = min * 1024 * 1024
return freesize > minSzie
} catch {
return false
}
}
static func removeExistingFile(at URL: Foundation.URL) {
let fileManager = FileManager.default
let outputPath = URL.path
if fileManager.fileExists(atPath: outputPath) {
do {
try fileManager.removeItem(at: URL)
} catch {
med_print(error.localizedDescription)
}
}
}
static func moveItem(at sourceURL: Foundation.URL, toURL dstURL: Foundation.URL) {
removeExistingFile(at: dstURL)
let fileManager = FileManager.default
let dstPath = sourceURL.path
if fileManager.fileExists(atPath: dstPath) {
do {
try fileManager.moveItem(at: sourceURL, to: dstURL)
} catch {
med_print(error.localizedDescription)
}
}
}
}
| mit | 1e2264eb45153952c6fedd6ee4b68132 | 31.816092 | 147 | 0.640981 | 5.080071 | false | false | false | false |
413738916/ZhiBoTest | ZhiBoSwift/ZhiBoSwift/Classes/Home/Controller/AmuseViewController.swift | 1 | 1497 | //
// GameViewController.swift
// ZhiBoSwift
//
// Created by 123 on 2017/10/23.
// Copyright © 2017年 ct. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorViewController {
// MARK: 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
// MARK:- 设置UI界面
extension AmuseViewController {
override func setupUI() {
super.setupUI()
// 将菜单的View添加到collectionView中
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension AmuseViewController {
override func loadData() {
// 1.给父类中ViewModel进行赋值
baseVM = amuseVM
// 2.请求数据
amuseVM.loadAmuseData {
// 2.1.刷新表格
self.collectionView.reloadData()
// 2.2.调整数据
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
//
// 3.数据请求完成
self.loadDataFinished()
}
}
}
| mit | caf4e505750ea04c1e5f7df25ec68395 | 22.728814 | 97 | 0.607143 | 4.620462 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/scripts/Colosseum/CMSExpr.swift | 1 | 19834 | //
// CMSExpr.swift
// GoD Tool
//
// Created by Stars Momodu on 03/06/2021.
//
import Foundation
typealias CMSVariable = String
typealias CMSMacro = String
typealias CMSLocation = Int
enum CMSConstant: CustomStringConvertible {
case void(Int), integer(Int), float(Float)
case unknownType(typeID: Int, value: Int)
var description: String {
switch self {
case .void(_):
return "null"
case .integer(let raw):
return "\(raw < 0x100 ? raw.string : raw.hexString())"
case .float(let raw):
return "\(raw)"
case .unknownType(let typeID, let value):
return "Type\(typeID)(\(value))"
}
}
var integerValue: Int {
switch self {
case .void(let i), .integer(let i), .unknownType(_, value: let i):
return i
case .float(let f):
return Int(f)
}
}
}
indirect enum CMSExpr {
case nop
case bracket(CMSExpr) // Adds brackets () around the sub expression
case constant(CMSConstant) // Just an integer or float literal
case macroDefinition(CMSMacro, String) // a line assigning a value to a macro
case macroConstant(CMSConstant, CMSMacroTypes) // a constant value that has been replaced by a macro
case msgMacroConstant(XGString) // a special macro for integers representing msg ids which have the string included in the macro
case scriptFunctionConstant(Int, Int) // a special macro for integers representing a function index in a script
case variable(CMScriptVar, CMSExpr) // global variables, local variables, function arguments or raw value on top of the stack
case variableAssignment(CMSExpr, CMSExpr) // assign the result of an expression to a variable
case structAssignment(CMSExpr, CMSExpr, Int) // assign a range of contiguous values of the specified length from one variable to another
case operation(CMSOperators, [CMSExpr]) // apply a unary or binary operator to the sub expression(s) +, -, *, &, ==, <, !, etc.
case call(Int, [CMSExpr]) // calls a function defined in a script with the sub expressions passed as arguments
case callBuiltIn(Int, [CMSExpr]) // calls a function built into the game engine with the sub expressions passed as arguments
case print(String, [CMSExpr]) // a special function that prints a string with optional sub expressions for interpolation
case yield(CMSExpr) // a special function which pauses code execution for a given number of frames
case CMSReturn // regular return
case CMSReturnResult(CMSExpr) // return the result of the sub expression
case jumpFalse(CMSExpr, CMSLocation) // used for branched logic. The code from a goto to its location represent if, while type logic
case location(CMSLocation) // the target of a goto statement
case silentLocation(CMSLocation) // locations that aren't printed because the goto + location are replaced with if, else, while, etc.
case jump(CMSLocation) // forced jump to a different location. Typically used for while loops or else statements
case functionDefinition(String, [CMSVariable]) // the first line of a function specifying its name and declaring its arguments
case function(CMSExpr, [CMSExpr]) // the definition of a function and the block of sequential statements in it
case ifStatement([(CMSExpr, [CMSExpr])]) // the condition for the statement and the block of sequential statements if the condition is met
case whileLoop(CMSExpr, [CMSExpr]) // the condition for the loop and the block of sequential statements while the condition is met
case commentSingleLine(String) // represents a comment to be ignored by the compiler
case commentMultiLine(String) // represents a comment to be ignored by the compiler
case error(String) // an expression used when there's an error but still acts as though it's a normal expression and will be printed in the decompiled code for easier debugging
case exit // possibly only used to mark the very end of an entire script file. Unsure if this ever actually used within a function
func unbracketed() -> CMSExpr {
switch self {
case .bracket(let expr):
return expr.unbracketed()
default:
return self
}
}
var isVariable: Bool {
switch self {
case .variable: return true
default: return false
}
}
var isFullStatement: Bool {
// A statement that performs some kind of action when on a line on its own
switch self.unbracketed() {
case .nop, .variable, .constant, .location, .silentLocation, .commentSingleLine, .commentMultiLine, .macroConstant, .msgMacroConstant:
return false
default:
return true
}
}
var macroName: String {
switch self {
case .macroDefinition(let s, _):
return s
default:
return ""
}
}
var macroRawValue: String {
switch self {
case .macroDefinition(_, let s):
return s
default:
return ""
}
}
var comment: CMSExpr? {
switch self {
case .callBuiltIn(102, let exprs), .callBuiltIn(152, let exprs):
if !fileDecodingMode,
case .macroConstant(.integer(let battleID), .battleID) = exprs[0],
let battle = XGBattle(index: battleID) {
return .commentMultiLine(battle.description)
}
return nil
default:
return nil
}
}
func text(script: XGScript?) -> String {
switch self {
case .nop:
return ""
case .bracket(let expr):
return "(\(expr.text(script: script)))"
case .operation(let op, let exprs):
switch exprs.count {
case 1: return "\(op)\(exprs[0].text(script: script))"
case 2: return "\(exprs[1].text(script: script)) \(op) \(exprs[0].text(script: script))"
default: return CMSExpr.error("Invalid operation: \(op) \(exprs.map{$0.text(script: script)})").text(script: script)
}
case .constant(let constant):
return constant.description
case .variable(let descriptor, let valueExpression):
var isValidExpression = false
var argValue = ""
var arrayIndexValue: String?
switch valueExpression.unbracketed() {
case .constant(.integer(let value)):
isValidExpression = true
argValue = "\(value)"
case .constant(.float), .macroConstant, .msgMacroConstant, .scriptFunctionConstant:
isValidExpression = descriptor.isLiteral
case .operation(.add, let subExprs):
if descriptor.isGlobalVar {
arrayIndexValue = subExprs[1].text(script: script)
argValue = subExprs[0].text(script: script)
}
fallthrough
case .operation:
isValidExpression = descriptor.isGlobalVar || descriptor.isLiteral
case .callBuiltIn, .call:
isValidExpression = descriptor.isLiteral
case .variable:
isValidExpression = descriptor.isGlobalVar || descriptor.isLiteral
if descriptor.isGlobalVar {
argValue = valueExpression.text(script: script)
}
default:
isValidExpression = false
}
guard isValidExpression else {
printg("Error: Unexpected variable \(descriptor), \(valueExpression.text(script: script))")
return CMSExpr.error("Unexpected variable: \(descriptor), \(valueExpression.text(script: script))").text(script: script)
}
if descriptor.isGlobalVar {
if let arrayIndex = arrayIndexValue {
return "gvar\(arrayIndex)[\(argValue)]"
} else {
return "gvar\(argValue)"
}
} else if descriptor.isLocalVar {
return "arg\(argValue)"
} else if descriptor.isLiteral {
return "\(valueExpression.text(script: script))"
}
printg("Error: Unexpected variable \(descriptor), \(valueExpression.text(script: script))")
return CMSExpr.error("Unexpected variable: \(descriptor), \(valueExpression.text(script: script))").text(script: script)
case .variableAssignment(let variable, let expr):
return "\(variable.text(script: script)) = \(expr.text(script: script))"
case .structAssignment(let var1, let var2, let length):
return "\(var1.text(script: script))[0:\(length)] = \(var2.text(script: script))[0:\(length)]"
case .call(let functionIndex, let exprs):
var text = "function\(functionIndex)("
for expr in exprs {
text += "\(expr.text(script: script)), "
}
if exprs.count > 0 {
text.removeLast(); text.removeLast()
}
text += ")"
return text
case .CMSReturn:
return "return"
case .CMSReturnResult(let expr):
return "return \(expr.text(script: script))"
case .callBuiltIn(let functionIndex, let exprs):
var text = "Standard.function\(functionIndex)("
if let functionName = ScriptBuiltInFunctions[functionIndex]?.name {
text = "Standard.\(functionName)("
}
for expr in exprs {
text += "\(expr.text(script: script)), "
}
if exprs.count > 0 {
text.removeLast(); text.removeLast()
}
text += ")"
if let comment = self.comment {
switch comment {
case .commentMultiLine:
text += "\n" + comment.text(script: nil) + "\n"
case .commentSingleLine:
text += comment.text(script: nil) + "n"
default:
assertionFailure("Comment should be either a single or multiline comment")
text += "\n"
}
}
return text
case .location(let value):
return "@location_\(value.hex())"
case .silentLocation(_):
return ""
case .jumpFalse(let condition, let location):
return "goto \(CMSExpr.location(location).text(script: script)) ifnot \(condition.text(script: script))"
case .jump(let location):
return "goto \(CMSExpr.location(location).text(script: script))"
case .functionDefinition(let functionName, let argNames):
var text = "function \(functionName)("
for name in argNames {
text += "\(name), "
}
if argNames.count > 0 {
text.removeLast(); text.removeLast()
}
text += ")"
return text
case .function(let definition, let exprs):
var text = "\(definition.text(script: script)) {\n"
for expression in exprs {
for line in expression.text(script: script).split(separator: "\n") {
text += " \(line)\n"
}
}
return text + "}\n\n"
case .print(let string, let args):
var text = "System.printf(\"\(string)\""
for arg in args {
text += ", \(arg.text(script: script))"
}
text += ")"
return text
case .yield(let frames):
return "System.yield(\(frames.text(script: script)))"
case .ifStatement(let blocks):
let parts = blocks.count
var lines = [String]()
for i in 0 ..< parts {
let (condition, exprs) = blocks[i]
var keyword = "else if"
if i == 0 {
keyword = "if"
}
var conditionText: String?
switch condition {
case .nop: // is else statement with no condition
if i > 0 {
keyword = "else"
} else {
assertionFailure("The if statement needs a condition")
}
case .jumpFalse(let c, _):
conditionText = "(\(c.text(script: script)))"
default:
assertionFailure("Make sure to always have a jump false as condition")
}
if i == 0 {
lines += [keyword + " " + (conditionText ?? "") + " {\n"]
} else {
let last = lines.count - 1
lines[last] = lines[last].replacingOccurrences(of: "\n", with: "") + " " + keyword + (conditionText == nil ? "" : " ") + (conditionText ?? "") + " {\n"
}
for expr in exprs {
let subText = "\(expr.text(script: script))"
for line in subText.split(separator: "\n") {
lines.append(" \(line)\n")
}
}
lines += ["}\n\n"]
}
return lines.joined(separator: "\n")
case .whileLoop(let condition, let exprs):
let text = CMSExpr.ifStatement([(condition, exprs)]).text(script: script)
let spliced = text.substring(from: 2, to: text.length)
return "while" + spliced
case .commentMultiLine(let text):
var commentText = "/*\n"
for line in text.split(separator: "\n") {
commentText += " * \(line)\n"
}
return commentText + "\n */"
case .commentSingleLine(let text):
return "// " + text
case .macroDefinition(let macroName, let rawValue):
return "define \(macroName) \(rawValue)"
case .macroConstant(let constant, let type):
return type.textForValue(constant, script: script)
case .msgMacroConstant(let string):
return CMSExpr.macroForString(xs: string)
case .scriptFunctionConstant(let type, let index):
switch type {
case 0:
return "Null"
case 0x596:
return "&Common.\(index)"
case 0x100:
return "&This.\(index)"
default:
return "&UnknownScript.\(index)"
}
case .exit:
return "exit"
case .error(let text):
return "&Error(\(text))"
}
}
func updateMacroTypes(withType type: CMSMacroTypes? = nil, script: XGScript?) -> (updatedExpr: CMSExpr, updatedType: CMSMacroTypes?, macroConstants: [CMSExpr]) {
switch self {
case .bracket(let subExpr):
let (newSub, updatedType, constants) = subExpr.updateMacroTypes(withType: type, script: script)
return (.bracket(newSub),updatedType, constants)
case .macroConstant(let constant, let type):
let constants = type.needsDefine ? [CMSExpr.macroDefinition(self.macroName,type.textForValue(constant, script: script))] : []
return (self, type, constants)
case .msgMacroConstant(_):
return (self, .msgID, [])
case .operation(let operatorValue, let subs):
let operatorOverrideType = operatorValue.forcedReturnType
let typeToSet = operatorOverrideType != nil ? nil : type
if subs.count == 1 {
let (newSub, updatedType, constants) = subs[0].updateMacroTypes(withType: typeToSet, script: script)
return (.operation(operatorValue, [newSub]), operatorOverrideType ?? updatedType, constants)
} else if subs.count == 2 {
let (newSub1, updatedType1, constants1) = subs[0].updateMacroTypes(withType: typeToSet, script: script)
let (newSub2, updatedType2, constants2) = subs[1].updateMacroTypes(withType: typeToSet, script: script)
if updatedType1 != nil, updatedType2 == nil {
let (newSub2, _, constants2) = subs[1].updateMacroTypes(withType: updatedType1, script: script)
return (.operation(operatorValue, [newSub1, newSub2]), operatorOverrideType ?? updatedType1, constants1 + constants2)
} else if updatedType2 != nil, updatedType1 == nil {
let (newSub1, _, constants1) = subs[0].updateMacroTypes(withType: updatedType2, script: script)
return (.operation(operatorValue, [newSub1, newSub2]), operatorOverrideType ?? updatedType2, constants1 + constants2)
} else {
return (.operation(operatorValue, [newSub1, newSub2]), operatorOverrideType ?? updatedType1, constants1 + constants2)
}
} else {
return (self, operatorOverrideType, [])
}
case .constant(.integer(let constant)):
switch type {
case .msgID:
return (.msgMacroConstant(getStringSafelyWithID(id: constant)), .msgID, [])
case .scriptFunction:
return (.scriptFunctionConstant(constant >> 16, constant & 0xFFFF), .scriptFunction, [])
default:
if let newType = type {
let newExpr = newType.needsMacro ? CMSExpr.macroConstant(.integer(constant), newType) : self
return (newExpr, newType, newType.needsDefine ? [CMSExpr.macroDefinition(newType.textForValue(.integer(constant), script: script), "\(self.text(script: script))")] : [])
} else {
return (self, nil, [])
}
}
case .variable(let variableType, let sub):
if variableType.isLiteral {
let (newSub, newType, constants) = sub.updateMacroTypes(withType: type, script: script)
return (.variable(variableType, newSub), newType, constants)
} else {
return (self, nil, [])
}
case .variableAssignment(let sub1, let sub2):
let (newSub1, _, constants1) = sub1.updateMacroTypes(withType: type, script: script)
let (newSub2, _, constants2) = sub2.updateMacroTypes(withType: type, script: script)
return (.variableAssignment(newSub1, newSub2), nil, constants1 + constants2)
case .structAssignment(let sub1, let sub2, let length):
let (newSub1, _, constants1) = sub1.updateMacroTypes(withType: type, script: script)
let (newSub2, _, constants2) = sub2.updateMacroTypes(withType: type, script: script)
return (.structAssignment(newSub1, newSub2, length), nil, constants1 + constants2)
case .call(let index, let subs):
var constants = [CMSExpr]()
let newSubs = subs.map { (sub) -> CMSExpr in
let (newSub, _, newConstants) = sub.updateMacroTypes(withType: type, script: script)
constants += newConstants
return newSub
}
return (.call(index, newSubs), nil, constants)
case .callBuiltIn(let index, let subs):
var returnType: CMSMacroTypes?
var newSubs = [CMSExpr]()
var newConstants = [CMSExpr]()
for i in 0 ..< subs.count {
if let data = ScriptBuiltInFunctions[index],
let paramTypes = data.parameterTypes,
i < paramTypes.count,
paramTypes[i] != nil {
let (newSub, _, newConstantValues) = subs[i].updateMacroTypes(withType: paramTypes[i], script: script)
newSubs.append(newSub)
newConstants += newConstantValues
} else {
let (newSub, _, newConstantValues) = subs[i].updateMacroTypes(script: script)
newSubs.append(newSub)
newConstants += newConstantValues
}
}
returnType = ScriptBuiltInFunctions[index]?.returnType
return (.callBuiltIn(index, newSubs), returnType, newConstants)
case .print(let text, let subs):
var constants = [CMSExpr]()
let newSubs = subs.map { (sub) -> CMSExpr in
let (newSub, _, newConstants) = sub.updateMacroTypes(withType: type, script: script)
constants += newConstants
return newSub
}
return (.print(text, newSubs), nil, constants)
case .yield(let sub):
let (newSub, _, constants) = sub.updateMacroTypes(withType: type, script: script)
return (.yield(newSub), nil, constants)
case .CMSReturnResult(let sub):
let (newSub, _, constants) = sub.updateMacroTypes(withType: type, script: script)
return (.CMSReturnResult(newSub), nil, constants)
case .jumpFalse(let condition, let location):
let (newSub, _, constants) = condition.updateMacroTypes(withType: type, script: script)
return (.jumpFalse(newSub, location), nil, constants)
case .ifStatement(let blocks):
var constants = [CMSExpr]()
var newBlocks = [(CMSExpr, [CMSExpr])]()
blocks.forEach { (condition, block) in
let (newCondition, _, newConstants1) = condition.updateMacroTypes(withType: .bool, script: script)
constants += newConstants1
let newSubs = block.map { (sub) -> CMSExpr in
let (newSub, _, newConstants2) = sub.updateMacroTypes(withType: type, script: script)
constants += newConstants2
return newSub
}
newBlocks.append((newCondition, newSubs))
}
return (.ifStatement(newBlocks), nil, constants)
case .whileLoop(let condition, let block):
var constants = [CMSExpr]()
let (newCondition, _, newConstants1) = condition.updateMacroTypes(withType: .bool, script: script)
constants += newConstants1
let newSubs = block.map { (sub) -> CMSExpr in
let (newSub, _, newConstants2) = sub.updateMacroTypes(withType: type, script: script)
constants += newConstants2
return newSub
}
return (.whileLoop(newCondition, newSubs), nil, constants)
case .function(let definition, let block):
var constants = [CMSExpr]()
let newSubs = block.map { (sub) -> CMSExpr in
let (newSub, _, newConstants) = sub.updateMacroTypes(withType: type, script: script)
constants += newConstants
return newSub
}
return (.function(definition, newSubs), nil, constants)
default:
return (self, nil, [])
}
}
static func macroWithName(_ name: String) -> String {
return "#\(name)"
}
static func macroForString(xs: XGString) -> String {
if xs.id == 0 {
return "$:0:"
}
if xs.table == nil {
return "$:\(xs.id):"
}
// must replace double quotes with special character since xds doesn't use escaped characters
var updatedString = xs.string.replacingOccurrences(of: "\"", with: "[Quote]")
updatedString = updatedString.replacingOccurrences(of: "\n", with: "[New Line]")
return "$:\(xs.id):" + "\"\(updatedString)\""
}
}
extension Array where Element == CMSExpr {
var description: String {
var text = ""
for expr in self {
text += "\(expr)\n"
}
if text.length > 0 {
text.removeLast()
}
return text
}
}
| gpl-2.0 | 35ff88965cbd693dcbbe2125dba19cb9 | 36.142322 | 177 | 0.683977 | 3.532953 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/TransitionExample/ViewController/Session2/NormalDismissAnimation.swift | 1 | 1439 | //
// NormalDismissAnimation.swift
// iOSExample
//
// Created by iCrany on 2017/6/3.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
class NormalDismissAnimation: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.8
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromVCTemp: UIViewController? = transitionContext.viewController(forKey: .from)
let toVCTemp: UIViewController? = transitionContext.viewController(forKey: .to)
guard let fromVC = fromVCTemp else {
return
}
guard let toVC = toVCTemp else {
return
}
// let initFrame: CGRect = transitionContext.initialFrame(for: fromVC)
let finalFrame: CGRect = transitionContext.finalFrame(for: fromVC)
transitionContext.containerView.addSubview(toVC.view)
transitionContext.containerView.sendSubview(toBack: toVC.view)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
fromVC.view.frame = finalFrame.offsetBy(dx: 0, dy: finalFrame.size.height)
}, completion: {(_: Bool) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| mit | 1c7381c927968bdc58cbc0bed62128e8 | 30.282609 | 109 | 0.701181 | 5.120996 | false | false | false | false |
untitledstartup/OAuthSwift | OAuthSwift/NSURL+OAuthSwift.swift | 1 | 727 | //
// NSURL+OAuthSwift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
extension NSURL {
func URLByAppendingQueryString(queryString: String) -> NSURL {
if queryString.utf16.count == 0 {
return self
}
var absoluteURLString = self.absoluteString
if absoluteURLString!.hasSuffix("?") {
absoluteURLString = (absoluteURLString! as NSString).substringToIndex(absoluteURLString!.utf16.count - 1)
}
let URLString = absoluteURLString! + (absoluteURLString!.rangeOfString("?") != nil ? "&" : "?") + queryString
return NSURL(string: URLString)!
}
}
| mit | 18a7c63233dac086ec7ca7c190811c15 | 23.233333 | 117 | 0.636864 | 4.630573 | false | false | false | false |
overtake/TelegramSwift | packages/TGUIKit/Sources/SelectionRectView.swift | 1 | 14028 | //
// SelectionRectView.swift
// TGUIKit
//
// Created by Mikhail Filimonov on 02/10/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
public enum SelectionRectDimensions {
case none
case original
case square
case x2_3
case x3_5
case x3_4
case x4_5
case x5_7
case x9_16
case x16_9
public var description: String {
switch self {
case .none:
return localizedString("SelectAreaControl.Dimension.None")
case .original:
return localizedString("SelectAreaControl.Dimension.Original")
case .square:
return localizedString("SelectAreaControl.Dimension.Square")
case .x2_3:
return "2x3"
case .x3_5:
return "3x5"
case .x3_4:
return "3x4"
case .x4_5:
return "4x5"
case .x5_7:
return "5x7"
case .x9_16:
return "9x16"
case .x16_9:
return "16x9"
}
}
func aspectRation(_ size: NSSize) -> CGFloat {
switch self {
case .none:
return 0
case .original:
return size.height / size.width
case .square:
return 1
case .x2_3:
return 3 / 2
case .x3_5:
return 5 / 3
case .x3_4:
return 4 / 3
case .x4_5:
return 5 / 4
case .x5_7:
return 7 / 5
case .x9_16:
return 16 / 9
case .x16_9:
return 9 / 16
}
}
fileprivate func applyRect(_ rect: NSRect, for corner: SelectingCorner?, areaSize: NSSize, force: Bool = false) -> NSRect {
let aspectRatio = self.aspectRation(areaSize)
var newCropRect = rect
if aspectRatio > 0, corner != nil || force {
newCropRect.size.height = rect.width * aspectRatio
} else {
return rect
}
let currentCenter = NSMakePoint(rect.midX, rect.midY)
if (newCropRect.size.height > areaSize.height)
{
newCropRect.size.height = areaSize.height;
newCropRect.size.width = newCropRect.height / aspectRatio;
}
if let corner = corner {
switch corner {
case .topLeft, .topRight:
newCropRect.origin.y += (rect.height - newCropRect.height)
default:
break
}
} else {
newCropRect.origin.x = currentCenter.x - newCropRect.width / 2;
newCropRect.origin.y = currentCenter.y - newCropRect.height / 2;
}
// if newCropRect.maxY > areaSize.height {
// newCropRect.origin.x = areaSize.width - newCropRect.width;
// }
//
// if (newCropRect.maxY > areaSize.height) {
// newCropRect.origin.y = areaSize.height - newCropRect.size.height;
// }
//
//
return newCropRect
}
public static var all: [SelectionRectDimensions] {
return [.original, .square, .x2_3, .x3_5, .x3_4, .x4_5, .x5_7, .x9_16, .x16_9]
}
}
public enum SelectingCorner {
case topLeft
case topRight
case bottomLeft
case bottomRight
}
private func generateCorner(_ corner: SelectingCorner, _ color: NSColor) -> CGImage {
return generateImage(NSMakeSize(20, 20), contextGenerator: { size, ctx in
ctx.clear(NSMakeRect(0, 0, size.width, size.height))
ctx.setFillColor(color.cgColor)
switch corner {
case .bottomLeft:
ctx.fill(NSMakeRect(0, 0, 2, size.height))
ctx.fill(NSMakeRect(0, 0, size.width, 2))
case .bottomRight:
ctx.fill(NSMakeRect(size.width - 2, 0, 2, size.height))
ctx.fill(NSMakeRect(0, 0, size.width, 2))
case .topLeft:
ctx.fill(NSMakeRect(0, 0, 2, size.height))
ctx.fill(NSMakeRect(0, size.height - 2, size.width, 2))
case .topRight:
ctx.fill(NSMakeRect(size.width - 2, 0, 2, size.height))
ctx.fill(NSMakeRect(0, size.height - 2, size.width, 2))
}
})!
}
public func generateSelectionAreaCorners(_ color: NSColor) -> (topLeft: CGImage, topRight: CGImage, bottomLeft: CGImage, bottomRight: CGImage) {
return (topLeft: generateCorner(.topLeft, color), topRight: generateCorner(.topRight, color), bottomLeft: generateCorner(.bottomLeft, color), bottomRight: generateCorner(.bottomRight, color))
}
public class SelectionRectView: View {
private let topLeftCorner: ImageButton = ImageButton()
private let topRightCorner: ImageButton = ImageButton()
private let bottomLeftCorner: ImageButton = ImageButton()
private let bottomRightCorner: ImageButton = ImageButton()
public var minimumSize: NSSize = NSMakeSize(40, 40)
public var isCircleCap: Bool = false
private var _updatedRect: ValuePromise<NSRect> = ValuePromise(ignoreRepeated: true)
public var updatedRect: Signal<NSRect, NoError> {
return _updatedRect.get()
}
public var dimensions: SelectionRectDimensions = .none {
didSet {
if oldValue != dimensions && selectedRect != NSZeroRect {
// applyRect(selectedRect, force: true)
}
}
}
private var startSelectedRect: NSPoint? = nil
private var moveSelectedRect: NSPoint? = nil
public private(set) var selectedRect: NSRect = NSZeroRect {
didSet {
updateRectLayout()
_updatedRect.set(selectedRect)
}
}
public var topLeftPosition: NSPoint {
return topLeftCorner.frame.origin
}
public var topRightPosition: NSPoint {
return topRightCorner.frame.origin
}
public var bottomLeftPosition: NSPoint {
return bottomLeftCorner.frame.origin
}
public var bottomRightPosition: NSPoint {
return bottomRightCorner.frame.origin
}
public var isWholeSelected: Bool {
let rect = NSMakeRect(0, 0, frame.width, frame.height)
return rect == selectedRect
}
private var highlighedRect: NSRect {
return NSMakeRect(max(1, selectedRect.minX), max(1, selectedRect.minY), min(selectedRect.width, frame.width - 2), min(selectedRect.height, frame.height - 2))
}
private func updateRectLayout() {
topLeftCorner.setFrameOrigin(highlighedRect.minX - 2, highlighedRect.minY - 2)
topRightCorner.setFrameOrigin(highlighedRect.maxX - topRightCorner.frame.width + 2, highlighedRect.minY - 2)
bottomLeftCorner.setFrameOrigin(highlighedRect.minX - 2, highlighedRect.maxY - bottomLeftCorner.frame.height + 2)
bottomRightCorner.setFrameOrigin(highlighedRect.maxX - topRightCorner.frame.width + 2, highlighedRect.maxY - bottomRightCorner.frame.height + 2)
needsDisplay = true
}
private var currentCorner: SelectingCorner? = nil
public override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
currentCorner = nil
guard let window = window else {return}
var point = self.convert(window.mouseLocationOutsideOfEventStream, from: nil)
point = NSMakePoint(ceil(point.x), ceil(point.y))
if NSPointInRect(point, topLeftCorner.frame) {
currentCorner = .topLeft
} else if NSPointInRect(point, topRightCorner.frame) {
currentCorner = .topRight
} else if NSPointInRect(point, bottomLeftCorner.frame) {
currentCorner = .bottomLeft
} else if NSPointInRect(point, bottomRightCorner.frame) {
currentCorner = .bottomRight
} else if NSPointInRect(point, selectedRect) {
startSelectedRect = selectedRect.origin
moveSelectedRect = point
} else {
moveSelectedRect = nil
startSelectedRect = nil
}
}
public override func mouseUp(with event: NSEvent) {
super.mouseUp(with: event)
let point = convert(event.locationInWindow, from: nil)
if event.clickCount == 2, NSPointInRect(point, selectedRect) {
applyRect(bounds)
}
moveSelectedRect = nil
startSelectedRect = nil
currentCorner = nil
}
public override func mouseDragged(with event: NSEvent) {
guard let window = window else {return}
let point = self.convert(window.mouseLocationOutsideOfEventStream, from: nil)
if let currentCorner = currentCorner {
applyDragging(currentCorner)
} else {
if let current = moveSelectedRect, let selectedOriginPoint = startSelectedRect {
let new = NSMakePoint(current.x - ceil(point.x), current.y - ceil(point.y))
applyRect(NSMakeRect(selectedOriginPoint.x - new.x, selectedOriginPoint.y - new.y, selectedRect.width, selectedRect.height))
} else {
super.mouseDragged(with: event)
}
}
}
public override func layout() {
super.layout()
needsDisplay = true
updateRectLayout()
}
public var inDragging: Bool {
return currentCorner != nil || moveSelectedRect != nil
}
public func applyRect(_ newRect: NSRect, force: Bool = false, dimensions: SelectionRectDimensions = .none) {
self.dimensions = dimensions
selectedRect = dimensions.applyRect(NSMakeRect(min(max(0, newRect.minX), frame.width - newRect.width), min(max(0, newRect.minY), frame.height - newRect.height), max(min(newRect.width, frame.width), minimumSize.width), max(min(newRect.height, frame.height), minimumSize.height)), for: self.currentCorner, areaSize: frame.size, force: force)
}
required public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(topLeftCorner)
addSubview(topRightCorner)
addSubview(bottomLeftCorner)
addSubview(bottomRightCorner)
topLeftCorner.autohighlight = false
topRightCorner.autohighlight = false
bottomLeftCorner.autohighlight = false
bottomRightCorner.autohighlight = false
topLeftCorner.set(image: generateCorner(.topLeft, .white), for: .Normal)
topRightCorner.set(image: generateCorner(.topRight, .white), for: .Normal)
bottomLeftCorner.set(image: generateCorner(.bottomLeft, .white), for: .Normal)
bottomRightCorner.set(image: generateCorner(.bottomRight, .white), for: .Normal)
topLeftCorner.setFrameSize(NSMakeSize(20, 20))
topRightCorner.setFrameSize(NSMakeSize(20, 20))
bottomLeftCorner.setFrameSize(NSMakeSize(20, 20))
bottomRightCorner.setFrameSize(NSMakeSize(20, 20))
topLeftCorner.userInteractionEnabled = false
topRightCorner.userInteractionEnabled = false
bottomLeftCorner.userInteractionEnabled = false
bottomRightCorner.userInteractionEnabled = false
// topLeftCorner.set(handler: { [weak self] control in
// self?.applyDragging(.topLeft)
// }, for: .MouseDragging)
//
// topRightCorner.set(handler: { [weak self] control in
// self?.applyDragging(.topRight)
// }, for: .MouseDragging)
//
// bottomLeftCorner.set(handler: { [weak self] control in
// self?.applyDragging(.bottomLeft)
// }, for: .MouseDragging)
//
// bottomRightCorner.set(handler: { [weak self] control in
// self?.applyDragging(.bottomRight)
// }, for: .MouseDragging)
}
private func applyDragging(_ corner: SelectingCorner) {
moveSelectedRect = nil
startSelectedRect = nil
guard let window = window else {return}
var current = self.convert(window.mouseLocationOutsideOfEventStream, from: nil)
current = NSMakePoint(min(max(0, ceil(current.x)), frame.width), min(max(0, ceil(current.y)), frame.height))
// guard NSPointInRect(current, frame) else {
// return
// }
let newRect: NSRect
switch corner {
case .topLeft:
newRect = NSMakeRect(current.x, current.y, (frame.width - current.x) - (frame.width - selectedRect.maxX), (frame.height - current.y) - (frame.height - selectedRect.maxY))
case .topRight:
newRect = NSMakeRect(selectedRect.minX, current.y, frame.width - selectedRect.minX - (frame.width - current.x), (frame.height - current.y) - (frame.height - selectedRect.maxY))
case .bottomLeft:
newRect = NSMakeRect(current.x, selectedRect.minY, (frame.width - current.x) - (frame.width - selectedRect.maxX), frame.height - selectedRect.minY - (frame.height - current.y))
case .bottomRight:
newRect = NSMakeRect(selectedRect.minX, selectedRect.minY, frame.width - selectedRect.minX - (frame.width - current.x), frame.height - selectedRect.minY - (frame.height - current.y))
}
applyRect(newRect)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
ctx.setFillColor(NSColor.black.withAlphaComponent(0.8).cgColor)
let rect = NSMakeRect(max(1, selectedRect.minX), max(1, selectedRect.minY), min(selectedRect.width, frame.width - 2), min(selectedRect.height, frame.height - 2))
ctx.setBlendMode(.normal)
ctx.fill(bounds)
ctx.setBlendMode(.clear)
if isCircleCap {
ctx.fillEllipse(in: rect)
} else {
ctx.fill(rect)
ctx.setBlendMode(.normal)
ctx.setStrokeColor(.white)
ctx.setLineWidth(1)
ctx.stroke(rect)
}
}
}
| gpl-2.0 | 6c4646b549c989686855599817bfcb8a | 34.87468 | 347 | 0.613032 | 4.308047 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Themes/ThemeBrowserCell.swift | 1 | 10937 | import Foundation
import WordPressShared.WPStyleGuide
import CocoaLumberjack
/// Actions provided in cell button triggered action sheet
///
public enum ThemeAction {
case activate
case active
case customize
case details
case support
case tryCustomize
case view
static func activeActionsForTheme(_ theme: Theme) ->[ThemeAction] {
if theme.custom {
if theme.hasDetailsURL() {
return [customize, details]
}
return [customize]
}
return [customize, details, support]
}
static func inactiveActionsForTheme(_ theme: Theme) ->[ThemeAction] {
if theme.custom {
if theme.hasDetailsURL() {
return [tryCustomize, activate, details]
}
return [tryCustomize, activate]
}
return [tryCustomize, activate, view, details, support]
}
var title: String {
switch self {
case .activate:
return NSLocalizedString("Activate", comment: "Theme Activate action title")
case .active:
return NSLocalizedString("Active", comment: "Label for active Theme")
case .customize:
return NSLocalizedString("Customize", comment: "Theme Customize action title")
case .details:
return NSLocalizedString("Details", comment: "Theme Details action title")
case .support:
return NSLocalizedString("Support", comment: "Theme Support action title")
case .tryCustomize:
return NSLocalizedString("Try & Customize", comment: "Theme Try & Customize action title")
case .view:
return NSLocalizedString("View", comment: "Theme View action title")
}
}
func present(_ theme: Theme, _ presenter: ThemePresenter) {
switch self {
case .activate:
presenter.activateTheme(theme)
case .customize, .active:
presenter.presentCustomizeForTheme(theme)
case .details:
presenter.presentDetailsForTheme(theme)
case .support:
presenter.presentSupportForTheme(theme)
case .tryCustomize:
presenter.presentPreviewForTheme(theme)
case .view:
presenter.presentViewForTheme(theme)
}
}
}
open class ThemeBrowserCell: UICollectionViewCell {
// MARK: - Constants
@objc public static let reuseIdentifier = "ThemeBrowserCell"
// MARK: - Private Aliases
fileprivate typealias Styles = WPStyleGuide.Themes
// MARK: - Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var infoBar: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var highlightView: UIView!
@IBOutlet weak var activityView: UIActivityIndicatorView!
// MARK: - Properties
@objc open var theme: Theme? {
didSet {
refreshGUI()
}
}
@objc open var showPriceInformation: Bool = false
open weak var presenter: ThemePresenter?
fileprivate var placeholderImage = UIImage(named: "theme-loading")
fileprivate var activeEllipsisImage = UIImage(named: "icon-menu-ellipsis-white")
fileprivate var inactiveEllipsisImage = UIImage(named: "icon-menu-ellipsis")
// MARK: - GUI
override open var isHighlighted: Bool {
didSet {
let alphaFinal: CGFloat = isHighlighted ? 0.3 : 0
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.highlightView.alpha = alphaFinal
})
}
}
override open func awakeFromNib() {
super.awakeFromNib()
actionButton.isExclusiveTouch = true
layer.borderWidth = Styles.cellBorderWidth
infoBar.layer.borderWidth = Styles.cellBorderWidth
nameLabel.font = Styles.cellNameFont
infoLabel.font = Styles.cellInfoFont
actionButton.layer.borderWidth = Styles.cellBorderWidth
}
override open func prepareForReuse() {
super.prepareForReuse()
theme = nil
presenter = nil
showPriceInformation = false
}
fileprivate func refreshGUI() {
if let theme = theme {
if let imageUrl = theme.screenshotUrl, !imageUrl.isEmpty {
refreshScreenshotImage(imageUrl)
} else {
showPlaceholder()
}
nameLabel.text = theme.name
if theme.isCurrentTheme() {
backgroundColor = Styles.activeCellBackgroundColor
infoBar.backgroundColor = Styles.activeCellBackgroundColor
layer.borderColor = Styles.activeCellBorderColor.cgColor
infoBar.layer.borderColor = Styles.activeCellDividerColor.cgColor
actionButton.layer.borderColor = Styles.activeCellDividerColor.cgColor
actionButton.setImage(activeEllipsisImage, for: .normal)
nameLabel.textColor = Styles.activeCellNameColor
infoLabel.textColor = Styles.activeCellInfoColor
infoLabel.text = NSLocalizedString("ACTIVE", comment: "Label for active Theme browser cell")
} else {
backgroundColor = Styles.inactiveCellBackgroundColor
infoBar.backgroundColor = Styles.inactiveCellBackgroundColor
layer.borderColor = Styles.inactiveCellBorderColor.cgColor
infoBar.layer.borderColor = Styles.inactiveCellDividerColor.cgColor
actionButton.layer.borderColor = Styles.inactiveCellDividerColor.cgColor
actionButton.setImage(inactiveEllipsisImage, for: .normal)
nameLabel.textColor = Styles.inactiveCellNameColor
if theme.isPremium() && showPriceInformation {
infoLabel.textColor = Styles.inactiveCellPriceColor
infoLabel.text = theme.price
} else {
infoLabel.text = nil
}
}
} else {
imageView.image = nil
nameLabel.text = nil
infoLabel.text = nil
activityView.stopAnimating()
}
prepareForVoiceOver()
}
fileprivate func showPlaceholder() {
imageView.contentMode = .center
imageView.backgroundColor = Styles.placeholderColor
imageView.image = placeholderImage
activityView.stopAnimating()
}
fileprivate func showScreenshot() {
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = UIColor.clear
activityView.stopAnimating()
}
private func imageUrlForWidth(imageUrl: String) -> String {
var screenshotUrl = imageUrl
// Themes not hosted on WP.com have an incorrect screenshotUrl
// it uses a // url (this is used on the web) when the scheme is not known.
if !screenshotUrl.hasPrefix("http") && screenshotUrl.hasPrefix("//") {
// Since not all sites support https
screenshotUrl = String(format: "http:%@", imageUrl)
}
guard var components = URLComponents(string: screenshotUrl) else {
return screenshotUrl
}
var queryItems: [URLQueryItem] = components.queryItems ?? []
if let screenshotWidth = presenter?.screenshotWidth {
queryItems.append(URLQueryItem(name: "w", value: "\(presenter!.screenshotWidth)"))
}
queryItems.append(URLQueryItem(name: "zoom", value: "\(UIScreen.main.scale)"))
components.queryItems = queryItems
guard let urlString = components.url?.absoluteString else {
return screenshotUrl
}
return urlString
}
fileprivate func refreshScreenshotImage(_ imageUrl: String) {
let imageUrlWithWidth = imageUrlForWidth( imageUrl: imageUrl )
let screenshotUrl = URL(string: imageUrlWithWidth)
imageView.backgroundColor = Styles.placeholderColor
activityView.startAnimating()
imageView.downloadImage(from: screenshotUrl, success: { [weak self] _ in
self?.showScreenshot()
}, failure: { [weak self] error in
if let error = error as NSError?, error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return
}
DDLogError("Error loading theme screenshot: \(String(describing: error?.localizedDescription))")
self?.showPlaceholder()
})
}
// MARK: - Actions
@IBAction fileprivate func didTapActionButton(_ sender: UIButton) {
guard let theme = theme, let presenter = presenter else {
return
}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let themeActions = theme.isCurrentTheme() ? ThemeAction.activeActionsForTheme(theme) : ThemeAction.inactiveActionsForTheme(theme)
themeActions.forEach { themeAction in
alertController.addActionWithTitle(themeAction.title,
style: .default,
handler: { (action: UIAlertAction) in
themeAction.present(theme, presenter)
})
}
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel action title")
alertController.addCancelActionWithTitle(cancelTitle, handler: nil)
alertController.modalPresentationStyle = .popover
alertController.presentFromRootViewController()
if let popover = alertController.popoverPresentationController {
popover.sourceView = actionButton
popover.sourceRect = actionButton.bounds
popover.permittedArrowDirections = .any
popover.canOverlapSourceViewRect = true
}
}
}
extension ThemeBrowserCell: Accessible {
func prepareForVoiceOver() {
prepareCellForVoiceOver()
prepareActionButtonForVoiceOver()
prepareNameLabelForVoiceOver()
}
private func prepareCellForVoiceOver() {
imageView.isAccessibilityElement = true
if let name = theme?.name {
imageView.accessibilityLabel = name
imageView.accessibilityTraits = [.button, .summaryElement]
}
if let details = theme?.details {
imageView.accessibilityHint = details
}
}
private func prepareActionButtonForVoiceOver() {
actionButton.isAccessibilityElement = true
actionButton.accessibilityLabel = NSLocalizedString("More", comment: "Action button to display more available options")
actionButton.accessibilityTraits = .button
}
private func prepareNameLabelForVoiceOver() {
nameLabel.isAccessibilityElement = false
}
}
| gpl-2.0 | 8c6263c58718e035ffb205e13b234952 | 34.976974 | 137 | 0.631435 | 5.600102 | false | false | false | false |
bridger/NumberPad | NumberPad/NameCanvasViewController.swift | 1 | 9801 | //
// NameCanvasViewController.swift
// NumberPad
//
// Created by Bridger Maxwell on 7/19/15.
// Copyright © 2015 Bridger Maxwell. All rights reserved.
//
import UIKit
protocol NameCanvasDelegate {
func nameCanvasViewControllerDidFinish(nameCanvasViewController: NameCanvasViewController)
}
class NameCanvasAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.2
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from) else {
return
}
let containerView = transitionContext.containerView
if (presenting) {
containerView.addAutoLayoutSubview(subview: toViewController.view)
// Slide the toViewController from the bottom
containerView.addConstraint( toViewController.view.al_centerY == containerView.al_centerY )
let centeringConstraint = toViewController.view.al_centerX == containerView.al_centerX
centeringConstraint.priority = UILayoutPriorityRequired - 1
containerView.addConstraint(centeringConstraint)
let hideConstraint = toViewController.view.al_left == containerView.al_right
containerView.addConstraint(hideConstraint)
containerView.layoutIfNeeded()
containerView.backgroundColor = UIColor.clear
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
containerView.removeConstraint(hideConstraint)
containerView.layoutIfNeeded()
containerView.backgroundColor = UIColor(white: 1.0, alpha: 0.7)
}, completion: { (bool) in
transitionContext.completeTransition(true)
})
} else {
let hideConstraint = fromViewController.view.al_left == containerView.al_right
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
containerView.addConstraint(hideConstraint)
containerView.layoutIfNeeded()
containerView.backgroundColor = UIColor.clear
}, completion: { (bool) in
fromViewController.view.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
}
}
class NameCanvasViewController: UIViewController {
var canvasView: UIView!
var label: UILabel!
var doneButton: UIButton!
var delegate: NameCanvasDelegate?
var touchTracker = TouchTracker()
override func viewDidLoad() {
self.view.translatesAutoresizingMaskIntoConstraints = false
self.canvasView = UIView()
self.view.addAutoLayoutSubview(subview: self.canvasView)
self.canvasView.backgroundColor = UIColor.selectedBackgroundColor()
self.canvasView.clipsToBounds = true
self.label = UILabel()
self.view.addAutoLayoutSubview(subview: self.label)
self.label.font = UIFont.preferredFont(forTextStyle: .headline)
self.label.textColor = UIColor.textColor()
self.label.text = "Draw a name"
self.doneButton = UIButton()
self.view.addAutoLayoutSubview(subview: self.doneButton)
self.doneButton.setTitle("Done", for: [])
self.doneButton.setTitleColor(UIColor.textColor(), for: [])
self.doneButton.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
self.doneButton.addTarget(self, action: #selector(NameCanvasViewController.doneButtonPressed), for: [.touchUpInside])
self.view.addVerticalConstraints( |[self.label]-0-[self.canvasView]| )
self.view.addHorizontalConstraints( |[self.label]-0-[self.doneButton]| )
self.view.addConstraint(self.label.al_baseline == self.doneButton.al_baseline)
self.view.addConstraint( self.label.al_leading == self.canvasView.al_leading )
self.view.addConstraint( self.doneButton.al_trailing == self.canvasView.al_trailing )
self.canvasView.addConstraint( self.canvasView.al_width == 300 )
self.canvasView.addConstraint( self.canvasView.al_height == 110 )
}
typealias TouchID = NSInteger
var activeStrokes: [TouchID: Stroke] = [:]
var completedStrokes: [Stroke] = []
var boundingRect: CGRect = CGRect.null
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let point = touch.location(in: self.canvasView)
if self.canvasView.bounds.contains(point) {
let touchID = touchTracker.id(for: touch)
let stroke = Stroke()
activeStrokes[touchID] = stroke
// Use precise locations for the stroke
for coalesced in event?.coalescedTouches(for: touch) ?? [] {
let point = coalesced.preciseLocation(in: self.canvasView)
stroke.append( point)
}
self.boundingRect = self.boundingRect.union(CGRect(x: point.x, y: point.y, width: 0, height: 0))
self.canvasView.layer.addSublayer(stroke.layer)
stroke.layer.strokeColor = UIColor.selectedTextColor().cgColor
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchID = touchTracker.id(for: touch)
if let stroke = activeStrokes[touchID] {
// Use precise locations for the stroke drawing
for coalesced in event?.coalescedTouches(for: touch) ?? [] {
let point = coalesced.preciseLocation(in: self.canvasView)
stroke.append( point)
}
let point = touch.location(in: self.canvasView)
self.boundingRect = self.boundingRect.union(CGRect(x: point.x, y: point.y, width: 0, height: 0))
stroke.updateLayer()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let touchID = touchTracker.id(for: touch)
if let stroke = activeStrokes[touchID] {
completedStrokes.append(stroke)
activeStrokes[touchID] = nil
}
}
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
guard let touches = touches else {
return
}
for touch in touches {
let touchID = touchTracker.id(for: touch)
if let stroke = activeStrokes[touchID] {
activeStrokes[touchID] = nil
stroke.layer.removeFromSuperlayer()
}
}
}
func doneButtonPressed() {
guard let delegate = delegate else {
return
}
delegate.nameCanvasViewControllerDidFinish(nameCanvasViewController: self)
}
// The image will be tightly fitting on the x axis, but on the y axis it will be positioned just
// like it is within the canvas view itself. This way, all drawings will be a consistent height.
// This returns nil if the user didn't draw anything
func renderedImage(pointHeight: CGFloat, scale: CGFloat, color: CGColor) -> UIImage? {
if completedStrokes.count == 0 {
return nil
}
let strokeWidth = 2.5 * scale
let height = Int(pointHeight * scale)
let ratio = CGFloat(height) / self.canvasView.frame.size.height
let width = Int(self.boundingRect.size.width * ratio + strokeWidth * 2)
guard width > 0 && height > 0 else {
return nil
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let graphicsContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
// Flip the y axis
var transform = CGAffineTransform(scaleX: 1, y: -1)
transform = transform.translatedBy(x: 0, y: CGFloat(-height))
// Scale the points down to fit into the image
transform = transform.scaledBy(x: ratio, y: ratio)
transform = transform.translatedBy(x: -self.boundingRect.origin.x + strokeWidth, y: 0)
graphicsContext.concatenate(transform)
for stroke in completedStrokes {
var firstPoint = true
for point in stroke.points {
if firstPoint {
graphicsContext.move(to: point)
firstPoint = false
} else {
graphicsContext.addLine(to: point)
}
}
graphicsContext.setLineCap(.round)
graphicsContext.setStrokeColor(color)
graphicsContext.setLineWidth(strokeWidth)
graphicsContext.strokePath()
}
if let cgImage = graphicsContext.makeImage() {
return UIImage(cgImage: cgImage, scale: scale, orientation: .up)
}
return nil
}
}
| apache-2.0 | 8b0d8a1e3ace8e0a2276a4e879324b01 | 40.176471 | 194 | 0.610612 | 5.308776 | false | false | false | false |
Alamofire/AlamofireImage | Tests/AFError+AlamofireImageTests.swift | 1 | 3853 | //
// AFError+AlamofireImageTests.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
extension AFError {
// ResponseSerializationFailureReason
var isInputDataNilOrZeroLength: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputDataNilOrZeroLength { return true }
return false
}
var isInputFileNil: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileNil { return true }
return false
}
var isInputFileReadFailed: Bool {
if case let .responseSerializationFailed(reason) = self, reason.isInputFileReadFailed { return true }
return false
}
// ResponseValidationFailureReason
var isDataFileNil: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileNil { return true }
return false
}
var isDataFileReadFailed: Bool {
if case let .responseValidationFailed(reason) = self, reason.isDataFileReadFailed { return true }
return false
}
var isMissingContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isMissingContentType { return true }
return false
}
var isUnacceptableContentType: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableContentType { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true }
return false
}
}
// MARK: -
extension AFError.ResponseSerializationFailureReason {
var isInputDataNilOrZeroLength: Bool {
if case .inputDataNilOrZeroLength = self { return true }
return false
}
var isInputFileNil: Bool {
if case .inputFileNil = self { return true }
return false
}
var isInputFileReadFailed: Bool {
if case .inputFileReadFailed = self { return true }
return false
}
}
// MARK: -
extension AFError.ResponseValidationFailureReason {
var isDataFileNil: Bool {
if case .dataFileNil = self { return true }
return false
}
var isDataFileReadFailed: Bool {
if case .dataFileReadFailed = self { return true }
return false
}
var isMissingContentType: Bool {
if case .missingContentType = self { return true }
return false
}
var isUnacceptableContentType: Bool {
if case .unacceptableContentType = self { return true }
return false
}
var isUnacceptableStatusCode: Bool {
if case .unacceptableStatusCode = self { return true }
return false
}
}
| mit | 206a7c6e16e83789f88d6488e731196d | 31.378151 | 114 | 0.695562 | 4.920817 | false | false | false | false |
fs/ios-base-swift | Swift-Base/Tools/ViewControllers/LoggedPageViewController.swift | 1 | 1748 | //
// LoggedPageViewController.swift
// Tools
//
// Created by Almaz Ibragimov on 01.01.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import UIKit
public class LoggedPageViewController: UIPageViewController {
// MARK: - Instance Properties
public fileprivate(set) final var isViewAppeared = false
// MARK: - Initializers
deinit {
Log.i("deinit", sender: self)
}
// MARK: - Instance Methods
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
Log.i("didReceiveMemoryWarning()", sender: self)
}
public override func viewDidLoad() {
super.viewDidLoad()
Log.i("viewDidLoad()", sender: self)
self.isViewAppeared = false
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Log.i("viewWillAppear()", sender: self)
self.isViewAppeared = false
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Log.i("viewDidAppear()", sender: self)
self.isViewAppeared = true
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Log.i("viewWillDisappear()", sender: self)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Log.i("viewDidDisappear()", sender: self)
self.isViewAppeared = false
}
// MARK: -
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
Log.i("prepare(for: \(String(describing: segue.identifier)))", sender: self)
}
}
| mit | 9a4a5723384c4954ba567335578cffa6 | 21.986842 | 84 | 0.645106 | 4.760218 | false | false | false | false |
sahandnayebaziz/Dana-Hills | Dana Hills/Calendar.swift | 1 | 2852 | //
// Calendar.swift
// Dana Hills
//
// Created by Nayebaziz, Sahand on 9/22/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import Foundation
import PromiseKit
import Alamofire
import AFDateHelper
enum CalendarDayType: String {
case T1, T2, T3, T4, T5, T6, TSC, TSC0, LS16
func toString() -> String {
switch self {
case .LS16:
return "Late Start"
case .TSC0:
return "TSC/0"
default:
return rawValue
}
}
}
struct CalendarDay: Equatable {
var date: Date
var type: CalendarDayType?
var message: String?
}
func ==(lhs: CalendarDay, rhs: CalendarDay) -> Bool {
return lhs.date == rhs.date && lhs.type == rhs.type && lhs.message == rhs.message
}
extension DanaHillsBack {
private static func getCalendarDay(fromLine line: String) -> CalendarDay? {
guard line.count >= 2 else {
return nil
}
guard line.substring(to: line.index(line.startIndex, offsetBy: 2)) != "//" else {
return nil
}
var components = line.components(separatedBy: " ")
guard components.count >= 2 else {
return nil
}
guard let date = Date(fromString: components[0], format: .custom("MM/dd/yyyy")) else {
return nil
}
let calendarDayType = CalendarDayType(rawValue: components[1])
guard components.count > 2 else {
return CalendarDay(date: date, type: calendarDayType, message: nil)
}
components.remove(at: 0) // remove date
if calendarDayType != nil { components.remove(at: 0) } // remove type?
components.remove(at: 0) // remove "message: "
let message: String? = components.count > 0 ? components.joined(separator: " ") : nil
return CalendarDay(date: date, type: calendarDayType, message: message)
}
static func getSchedule() -> Promise<[CalendarDay]> {
return Promise { resolve, reject in
let url = URL(string: "https://sahandnayebaziz.github.io/Dana-Hills/calendar.txt")!
request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.responseString { response in
guard let responseString = response.result.value else {
return reject(DanaHillsBackError.BadResponse)
}
var days: [CalendarDay] = []
for line in responseString.components(separatedBy: .newlines) {
if let day = getCalendarDay(fromLine: line) {
days.append(day)
}
}
return resolve(days)
}
}
}
}
| mit | 9387a7abec5a9ab6a5289f70e80fee22 | 29.655914 | 100 | 0.556998 | 4.326252 | false | false | false | false |
stefan-vainberg/SlidingImagePuzzle | SlidingImagePuzzle/SlidingImagePuzzle/PuzzleBoardViewController.swift | 1 | 15386 | //
// PuzzleBoardViewController.swift
// SlidingImagePuzzle
//
// Created by Stefan Vainberg on 11/8/14.
// Copyright (c) 2014 Stefan. All rights reserved.
//
import Foundation
import UIKit
protocol PuzzleBoardViewControllerDelegate
{
func didFinishGeneratingPuzzle() -> Void
func didWinPuzzleGame() -> Void
}
class PuzzleBoardViewController : UIViewController, PuzzleGameControllerDelegate, PuzzleGestureHandlerDelegate
{
// PRIVATE
var initialImage:UIImage?
var puzzleBoardView:PuzzleBoardView?
var puzzleGameController:PuzzleGameController?
var delegate:PuzzleBoardViewControllerDelegate?
var gameController:PuzzleGameController?
var gameGestureHandler:PuzzleGestureHandler?
var currentlyMovingPuzzlePiece:UIImageView?
var currentlyMovingPuzzlePieceInitialOrigin:CGPoint?
var puzzlePieces:([[UIImage]])?
var puzzlePieceSize:CGFloat?
convenience init(image:UIImage)
{
self.init()
initialImage = image
let device = UIDevice.currentDevice().userInterfaceIdiom
if (device == .Phone) {
puzzlePieceSize = 50
}
else {
puzzlePieceSize = 150
}
self.puzzlePieces = []
}
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience override init()
{
self.init(nibName: nil, bundle: nil)
}
override func loadView() {
super.loadView()
self.view = UIView()
self.view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
puzzleBoardView = PuzzleBoardView(initialImage: initialImage!)
puzzleBoardView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
puzzleBoardView!.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(puzzleBoardView!)
// constraint puzzle image view to the superview
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
}
override func viewDidLoad() {
super.viewDidLoad()
self.SetupGamePieces()
// update the board with the pieces
self.puzzleBoardView!.UpdateWithPuzzlePieces(self.puzzlePieces!)
self.view.removeConstraints(self.view.constraints())
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: self.puzzleBoardView!.boardGameSize!.width))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: self.puzzleBoardView!.boardGameSize!.height))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: puzzleBoardView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
self.delegate!.didFinishGeneratingPuzzle()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.BeginGame()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// INITIAL BOARD GENERATION
// Setup
func SetupGamePieces() -> Void
{
// figure out the size of the image, and use that to calculate individual puzzle squares
let numRows = floor(initialImage!.size.height / CGFloat(puzzlePieceSize!))
let numColumns = floor(initialImage!.size.width / CGFloat(puzzlePieceSize!))
// instantiate the imagePieces
for row in 0..<Int(numRows)
{
self.puzzlePieces!.append(Array(count: Int(numColumns), repeatedValue: UIImage()))
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(initialImage!.size.width, initialImage!.size.height), false, 1.0)
initialImage!.drawInRect(CGRectMake(0, 0, initialImage!.size.width, initialImage!.size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
for (var row = 0; row < Int(numRows); row++)
{
for var column = 0; column < Int(numColumns); column++
{
let croppedRect = CGRectMake(CGFloat(column)*puzzlePieceSize!, CGFloat(row)*puzzlePieceSize!, puzzlePieceSize!, puzzlePieceSize!)
let gamePuzzleImageCGImage = CGImageCreateWithImageInRect(image.CGImage, croppedRect)
let puzzlePiece = UIImage(CGImage: gamePuzzleImageCGImage, scale: 1.0, orientation: initialImage!.imageOrientation)
puzzlePieces![row][column] = puzzlePiece!
}
}
}
func BeginGame() -> Void
{
// first step is to black out one random piece, thereby removing it from the image. This is now the piece that can be moved over
let randomRow = arc4random_uniform(UInt32(self.puzzlePieces!.count))
let randomColumn = arc4random_uniform(UInt32(self.puzzlePieces![0].count))
self.puzzleBoardView!.BlackOutPiece((Int(randomRow), Int(randomColumn)))
let blackImageView = puzzleBoardView!.board![Int(randomRow)][Int(randomColumn)]
gameController = PuzzleGameController(blackedOutImage: blackImageView)
gameController!.delegate = self
gameController!.GenerateInitialGameTileMovements(150, imagesArray: &self.puzzleBoardView!.board!, illegalTouchDirection: TouchDirection.None)
}
// PuzzleGameControllerDelegate
func didFinishInitialGameGeneration(imagesArray:[[UIImageView]]) {
// start processing gestures
gameGestureHandler = PuzzleGestureHandler()
gameGestureHandler!.puzzleGameDelegate = self
puzzleBoardView!.addGestureRecognizer(gameGestureHandler!)
puzzleBoardView!.board = imagesArray
}
// PuzzleGestureHandlerDelegate
func didBeginPuzzleGesture(touchPoint: CGPoint) {
currentlyMovingPuzzlePiece = self.puzzleBoardView!.PieceAtPoint(touchPoint)
currentlyMovingPuzzlePieceInitialOrigin = currentlyMovingPuzzlePiece!.frame.origin
// we can't move the blacked out piece
if (currentlyMovingPuzzlePiece == self.gameController!.currentBlackedOutImage) {
self.gameGestureHandler!.state = UIGestureRecognizerState.Failed
return
}
// make sure that the black piece is adjacent to the selected piece
// figure out which puzzle piece is getting touched
let selectedPiece = currentlyMovingPuzzlePiece!
let selectedPieceArrayLocation = self.puzzleBoardView!.arrayLocationOfPiece(touchPoint)
let blackedOutPieceArrayLocation = self.gameController!.blackedOutImagePosition(self.puzzleBoardView!.board!)
if (selectedPieceArrayLocation.row == blackedOutPieceArrayLocation.row || selectedPieceArrayLocation.column == blackedOutPieceArrayLocation.column) {
// we know that that the black piece is horizontally vertical to our targetted piece. now see if it's within one spot of it
if (selectedPieceArrayLocation.row > blackedOutPieceArrayLocation.row + 1 || selectedPieceArrayLocation.row < blackedOutPieceArrayLocation.row - 1 || selectedPieceArrayLocation.column > blackedOutPieceArrayLocation.column + 1 || selectedPieceArrayLocation.column < blackedOutPieceArrayLocation.column - 1) {
self.gameGestureHandler!.state = UIGestureRecognizerState.Failed
return
}
}
else {
self.gameGestureHandler!.state = UIGestureRecognizerState.Failed
return
}
}
func didMovePuzzleGesture(startingTouchPoint:CGPoint, currentTouchPoint:CGPoint, direction:TouchDirection) -> Void
{
// figure out which puzzle piece is getting touched
let selectedPiece = currentlyMovingPuzzlePiece!
let blackedOutPiece = self.gameController!.currentBlackedOutImage
let selectedPieceArrayLocation = self.puzzleBoardView!.arrayLocationOfPiece(startingTouchPoint)
let blackedOutPieceArrayLocation = self.gameController!.blackedOutImagePosition(self.puzzleBoardView!.board!)
// figure out the rectangle of possible motion for the piece.
let legalMotionRect = CGRectMake(min(currentlyMovingPuzzlePieceInitialOrigin!.x, blackedOutPiece.frame.origin.x),
min(currentlyMovingPuzzlePieceInitialOrigin!.y , blackedOutPiece.frame.origin.y),
max (abs(blackedOutPiece.frame.origin.x + blackedOutPiece.bounds.size.width - (currentlyMovingPuzzlePieceInitialOrigin!.x)),
abs(currentlyMovingPuzzlePieceInitialOrigin!.x + currentlyMovingPuzzlePiece!.bounds.size.width - (blackedOutPiece.frame.origin.x))),
max (abs(blackedOutPiece.frame.origin.y + blackedOutPiece.bounds.size.height - (currentlyMovingPuzzlePieceInitialOrigin!.y)),
abs(currentlyMovingPuzzlePieceInitialOrigin!.y + currentlyMovingPuzzlePiece!.bounds.size.height - (blackedOutPiece.frame.origin.y))))
if(direction == TouchDirection.Left || direction == TouchDirection.Right) {
if (legalMotionRect.size.width == selectedPiece.bounds.size.width) {
return
// can't move left or right if the black piece is underneath
}
let frameMovement = currentTouchPoint.x - startingTouchPoint.x
// don't want to move past the legal motion rect
if (selectedPiece.frame.origin.x + frameMovement < legalMotionRect.origin.x || selectedPiece.frame.origin.x + selectedPiece.bounds.size.width + frameMovement > legalMotionRect.origin.x + legalMotionRect.size.width) {
return
}
selectedPiece.frame = CGRectMake(selectedPiece.frame.origin.x + frameMovement, selectedPiece.frame.origin.y, selectedPiece.bounds.size.width, selectedPiece.bounds.size.height)
if (selectedPiece.frame.origin.x < legalMotionRect.origin.x) {
selectedPiece.frame = CGRectMake(legalMotionRect.origin.x, selectedPiece.frame.origin.y, selectedPiece.bounds.size.width, selectedPiece.bounds.size.height)
}
else if (selectedPiece.frame.origin.x + selectedPiece.bounds.size.width > legalMotionRect.origin.x + legalMotionRect.size.width) {
selectedPiece.frame = CGRectMake(legalMotionRect.origin.x + legalMotionRect.size.width - selectedPiece.bounds.size.width, selectedPiece.frame.origin.y, selectedPiece.bounds.size.width, selectedPiece.bounds.size.height)
}
}
else {
if (legalMotionRect.size.height == selectedPiece.bounds.size.height) {
return
// can't move up or down if black piece is to left or right
}
let frameMovement = currentTouchPoint.y - startingTouchPoint.y
// don't want to move past the legal motion rect
if (selectedPiece.frame.origin.y + frameMovement < legalMotionRect.origin.y || selectedPiece.frame.origin.y + selectedPiece.bounds.size.height + frameMovement > legalMotionRect.origin.y + legalMotionRect.size.height) {
return
}
selectedPiece.frame = CGRectMake(selectedPiece.frame.origin.x, selectedPiece.frame.origin.y + frameMovement, selectedPiece.bounds.size.width, selectedPiece.bounds.size.height)
}
}
func didCompletePuzzleGesture(startingTouchPoint: CGPoint, currentTouchPoint: CGPoint, direction: TouchDirection)
{
// the blacked out piece needs to be swapped in the board array wih the currently selected piece
let blackedOutPieceLocation = self.gameController!.blackedOutImagePosition(self.puzzleBoardView!.board!)
let selectedPieceArrayLocation = self.puzzleBoardView!.arrayLocationOfPiece(CGPointMake(currentlyMovingPuzzlePieceInitialOrigin!.x + currentlyMovingPuzzlePiece!.bounds.size.width/2,
currentlyMovingPuzzlePieceInitialOrigin!.y + currentlyMovingPuzzlePiece!.bounds.size.height/2))
let selectedPiece = self.puzzleBoardView!.board![selectedPieceArrayLocation.row][selectedPieceArrayLocation.column]
self.puzzleBoardView!.board![selectedPieceArrayLocation.row][selectedPieceArrayLocation.column] = self.gameController!.currentBlackedOutImage
self.puzzleBoardView!.board![blackedOutPieceLocation.row][blackedOutPieceLocation.column] = selectedPiece
UIView.animateWithDuration(0.1, animations: { () -> Void in
})
UIView.animateWithDuration(0.1, animations: { () -> Void in
selectedPiece.center = self.gameController!.currentBlackedOutImage.center
}){
(finished:Bool) -> Void in
if (finished) {
if(self.gameController!.CheckDidWinGame(self.puzzleBoardView!.board!)) {
self.didWinGame()
}
}
}
self.gameController!.currentBlackedOutImage.center = CGPointMake(currentlyMovingPuzzlePieceInitialOrigin!.x + selectedPiece.bounds.size.width/2,
currentlyMovingPuzzlePieceInitialOrigin!.y + selectedPiece.bounds.size.height/2)
}
func didWinGame() -> Void
{
self.gameController!.unBlackoutBlackImage()
self.delegate!.didWinPuzzleGame()
}
} | cc0-1.0 | 984f096abe2035303be98aad16dcdc57 | 48.475884 | 320 | 0.688613 | 5.04459 | false | false | false | false |
Irvel/Actionable-Screenshots | ActionableScreenshots/ActionableScreenshots/Models/Tag.swift | 1 | 952 | //
// Screenshot.swift
// ActionableScreenshots
//
// Created by Jesus Galvan on 10/14/17.
// Copyright © 2017 Jesus Galvan. All rights reserved.
//
import Foundation
import RealmSwift
enum TagType: String {
case detectedApplication
case detectedObject
case userInput
}
/**
Store a semantic classification or Tag
*/
class Tag:Object {
private var _type: TagType?
var type: TagType? {
get {
if let resolTypeRaw = typeRaw {
_type = TagType(rawValue: resolTypeRaw)
return _type
}
return .userInput
}
set {
typeRaw = newValue?.rawValue
_type = newValue
}
}
@objc dynamic var id: String?
@objc dynamic var typeRaw: String?
let screenshots = LinkingObjects(fromType: Screenshot.self, property: "tags")
override static func primaryKey() -> String {
return "id"
}
}
| gpl-3.0 | bd91327b764bab0c1d26183247d596bf | 20.133333 | 81 | 0.59306 | 4.303167 | false | false | false | false |
DivineDominion/mac-multiproc-code | RelocationManagerServiceDomain/Dependencies.swift | 1 | 1936 | //
// Dependencies.swift
// RelocationManager
//
// Created by Christian Tietze on 19/03/15.
// Copyright (c) 2015 Christian Tietze. All rights reserved.
//
import Foundation
class Dependencies: NSObject {
var bundle: NSBundle {
return NSBundle.mainBundle()
}
var sharedBundleDirectory: NSURL {
return NSURL()
}
lazy var persistentStack: PersistentStack = {
let storeURL = self.sharedBundleDirectory.URLByAppendingPathComponent(kDefaultStoreName);
let modelURL = self.bundle.URLForResource(kDefaultModelName, withExtension: "momd")
let errorHandler = ServiceLocator.errorHandler()
return PersistentStack(storeURL: storeURL, modelURL: modelURL!, errorHandler: errorHandler)
}()
lazy var listener: NSXPCListener = {
let bundleId = self.bundle.bundleIdentifier!
return NSXPCListener(machServiceName: bundleId)
}()
/// Returns `Dependencies` object (self) upon success, or `nil` upon failure.
func setUp() -> Dependencies? {
if let moc = persistentStack.managedObjectContext {
ServiceLocator.sharedInstance.setManagedObjectContext(moc)
setUpListener()
return self
}
return nil
}
private func setUpListener() {
listener.delegate = self
listener.resume()
}
}
extension Dependencies: NSXPCListenerDelegate {
func listener(listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
// TODO set up invalidation handler
if let controller = PrepareConnection().prepare(newConnection).build() {
controller.openConnection()
// TODO retain controller
return true
}
return false
}
}
| mit | 62341d0dbe2fa46fcf73afffb129a109 | 25.888889 | 110 | 0.615186 | 5.579251 | false | false | false | false |
jdbateman/Lendivine | Lendivine/Countries.swift | 1 | 10662 | //
// Countries.swift
// Lendivine
//
// Created by john bateman on 3/12/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This class implements a higher level interface to initialize core data with countries queried from the RESTCountries api, and to interact with the collection of countries persisted to core data.
import Foundation
import CoreData
/* A custom NSNotification that indicates any updated country data from the web service is now available in core data. */
let countriesUpdateNotificationKey = "com.lendivine.countries.update"
class Countries {
/*!
@brief Initialize Core data with all countries from the RESTCountries.eu api. Country objects are persisted in core data.
@discussion This is an asynchronous method that interacts with a REST service. Objects are persisted to the shared core data context. No duplicate country objects are persisted.
*/
class func persistCountriesFromWebService(completionHandler: ((success: Bool, error: NSError?) -> Void)? ) {
// Acquire countries from rest api.
restCountriesAPI.getCountries() { countries, error in
if let countries = countries {
Countries.persistNewCountries(countries)
Countries.sendUpdatedCountriesNotification()
if completionHandler != nil {
completionHandler!(success: true, error: nil)
}
} else {
if completionHandler != nil {
completionHandler!(success: false, error: error)
}
}
}
}
/*! Provides a count of countries that reside in core data in memory. Note that these objects have not necessarily been persisted to the sqlite store yet. */
class func countCountries() -> Int {
var error: NSError?
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
let count = CoreDataContext.sharedInstance().countriesContext.countForFetchRequest(fetchRequest, error:&error)
if (count == NSNotFound) {
print("Error: \(error)")
return 0
}
return count
}
/*! Provides a count of the number of Country objects that match the specified Country that reside in core data in memory. Note that these objects have not necessarily been persisted to the sqlite store yet. */
class func countCountry(country: Country?) -> Int {
guard let country = country else {
return 0
}
var error: NSError?
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
fetchRequest.predicate = NSPredicate(format: "name == %@", country.name!)
let count = CoreDataContext.sharedInstance().countriesContext.countForFetchRequest(fetchRequest, error:&error)
if (count == NSNotFound) {
print("Error: \(error)")
return 0
}
return count
}
/*! Returns true if a Country object with the same name already exists in core data memory. */
class func doesCountryExistInCoreData(country: Country?) -> Bool {
guard let country = country else {
return false
}
var error: NSError?
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
fetchRequest.predicate = NSPredicate(format: "name == %@", country.name!)
let count = CoreDataContext.sharedInstance().countriesContext.countForFetchRequest(fetchRequest, error:&error)
if (count == NSNotFound) {
print("Error: \(error)")
return false
} else if count == 0 {
return false
}
return true
}
/*! Saves new countries to core data context. Does not persist duplicate Country objects. */
class func persistNewCountries(countries: [Country]?) {
var duplicateCountries = [Country]()
guard let countries = countries else {
return
}
for country in countries {
if Countries.countCountry(country) > 1 {
//if Countries.doesCountryExistInCoreData(country) {
duplicateCountries.append(country)
}
}
// When the Country NSManaged objects were created they were saved to the in-memory version of the core data context.
// Here will save all countries from core data memory to the core data sqlite store on disk.
CoreDataContext.sharedInstance().saveCountriesContext()
// remove all duplicates
//print("removing \(duplicateCountries.count) duplicate countries")
for dupCountry in duplicateCountries {
// delete the object from core data memory
CoreDataContext.sharedInstance().countriesContext.deleteObject(dupCountry)
}
// commit the deletes to the core data sqlite data store on disk
CoreDataContext.sharedInstance().saveCountriesContext()
}
/*! Return a randomized comma separated string of country names. */
class func getRandomCountries(numberOfCountries:Int = 20) -> String? {
var countries = [String]()
var randomCountries = [String]()
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: false)]
_ = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:
CoreDataContext.sharedInstance().countriesScratchContext, sectionNameKeyPath: nil, cacheName: nil)
var results: [AnyObject]?
do {
results = try CoreDataContext.sharedInstance().countriesContext.executeFetchRequest(fetchRequest)
if let results = results {
for result in results {
if let result = result as? Country {
if let name = result.name {
countries.append(name)
}
}
}
}
} catch let error1 as NSError {
print("Error in getRandomCountries(): \(error1)")
results = nil
}
// add the requested number of randomly selected countries
for _ in 0..<numberOfCountries {
let index = Int(arc4random_uniform(UInt32(countries.count)))
randomCountries.append(countries[index])
}
let randomCountriesString = randomCountries.joinWithSeparator(",")
return randomCountriesString
}
enum RandomCountryResultType {
case Name, TwoLetterCode
}
/*! Return a randomized comma separated string of two letter country codes. */
class func getRandomCountryCodes(numberOfCountries:Int = 20, resultType:RandomCountryResultType = .Name) -> String? {
var countries = [String]()
var randomCountries = [String]()
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: false)]
_ = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:
CoreDataContext.sharedInstance().countriesScratchContext, sectionNameKeyPath: nil, cacheName: nil)
var results: [AnyObject]?
do {
results = try CoreDataContext.sharedInstance().countriesContext.executeFetchRequest(fetchRequest)
if let results = results {
for result in results {
if let result = result as? Country {
if resultType == .Name {
if let name = result.name {
countries.append(name)
}
} else if resultType == .TwoLetterCode {
if let countryCode = result.countryCodeTwoLetter {
countries.append(countryCode)
}
}
}
}
}
} catch let error1 as NSError {
//error!.memory = error1
print("Error in getRandomCountryCodes(): \(error1)")
results = nil
}
// add the requested number of randomly selected countries
for _ in 0..<numberOfCountries {
let index = Int(arc4random_uniform(UInt32(countries.count)))
randomCountries.append(countries[index])
}
let randomCountriesString = randomCountries.joinWithSeparator(",")
return randomCountriesString
}
// MARK: - Fetched results controller
static var fetchedResultsController: NSFetchedResultsController = {
// Create the fetch request
let fetchRequest = NSFetchRequest(entityName: Country.entityName)
// Add a sort descriptor to enforce a sort order on the results.
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
// Create the Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:
CoreDataContext.sharedInstance().countriesScratchContext, sectionNameKeyPath: nil, cacheName: nil)
// Return the fetched results controller. It will be the value of the lazy variable
return fetchedResultsController
} ()
/* Perform a fetch of Country objects to update the fetchedResultsController with the current data from the core data store. */
class func fetchCountries() {
do {
try fetchedResultsController.performFetch()
} catch let error1 as NSError {
let error = error1
print("\(error)")
}
}
// MARK - notifications
/*! Send a notification indicating that any new country obtained from the rest service is now avaiable in core data. */
class func sendUpdatedCountriesNotification() {
NSNotificationCenter.defaultCenter().postNotificationName(countriesUpdateNotificationKey, object: self)
}
} | mit | bae4a9740238ceda678a90baac8152f3 | 37.490975 | 214 | 0.598537 | 5.965865 | false | false | false | false |
djwbrown/swift | test/attr/attr_specialize.swift | 2 | 14698 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}},
@_specialize(where T == T1) // expected-error{{use of undeclared type 'T1'}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'T' == 'T'}}
@_specialize(where T == S<T>) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
// expected-error@-1{{same-type constraint 'T' == 'S<T>' is recursive}}
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error {{Missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // expected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected identifier for type name}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{use of undeclared type 'Z'}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{use of undeclared type 'MyClass'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}}
// expected-note@-2{{same-type constraint 'X' == 'Int' written here}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{use of undeclared type 'X1'}} expected-error{{use of undeclared type 'Y1'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{use of undeclared type 'exported'}} expected-error{{use of undeclared type 'kind'}} expected-error{{use of undeclared type 'partial'}} expected-error{{expected identifier for type name}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
// expected-error@-1{{type 'T' constrained to non-protocol type 'Int'}}
@_specialize(where T: S1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
// expected-error@-1{{type 'T' constrained to non-protocol type 'S1'}}
@_specialize(where T: C1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-error{{Missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject)
// expected-error@-1{{generic parameter 'T' has conflicting layout constraints '_Trivial(64)' and '_Trivial(32)'}}
// expected-error@-2{{generic parameter 'T' has conflicting layout constraints '_RefCountedObject' and '_Trivial(32)'}}
// expected-warning@-3{{redundant layout constraint 'T' : '_Trivial'}}
// expected-note@-4 3{{layout constraint constraint 'T' : '_Trivial(32)' written here}}
@_specialize(where T: _Trivial, T: _Trivial(64))
// expected-warning@-1{{redundant layout constraint 'T' : '_Trivial'}}
// expected-note@-2 1{{layout constraint constraint 'T' : '_Trivial(64)' written here}}
@_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject)
// expected-warning@-1{{redundant layout constraint 'T' : '_RefCountedObject'}}
// expected-note@-2 1{{layout constraint constraint 'T' : '_NativeRefCountedObject' written here}}
@_specialize(where Array<T> == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
// expected-error@-1{{generic signature requires types 'Array<T>' and 'Int' to be the same}}
@_specialize(where T.Element == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public protocol Proto: class {
}
@_specialize(where T: _RefCountedObject)
// expected-warning@-1{{redundant layout constraint 'T' : '_RefCountedObject'}}
@_specialize(where T: _Trivial)
// expected-error@-1{{generic parameter 'T' has conflicting layout constraints '_Trivial' and '_NativeClass'}}
@_specialize(where T: _Trivial(64))
// expected-error@-1{{generic parameter 'T' has conflicting layout constraints '_Trivial(64)' and '_NativeClass'}}
public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 {
return 44444
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@_specialize(exported: true, where S: _NativeRefCountedObject)
@_specialize(exported: true, where S: _Class)
@_specialize(exported: true, where S: _NativeClass)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-error{{Missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
| apache-2.0 | b903405b8c80e21d73995c53f9adfaae | 51.30605 | 419 | 0.700708 | 3.721955 | false | false | false | false |
cathy810218/onebusaway-iphone | OneBusAway/ui/regions/RegionBuilderViewController.swift | 1 | 7269 | //
// RegionBuilderViewController.swift
// org.onebusaway.iphone
//
// Created by Aaron Brethorst on 8/24/16.
// Copyright © 2016 OneBusAway. All rights reserved.
//
import Foundation
import UIKit
import OBAKit
import SVProgressHUD
@objc protocol RegionBuilderDelegate {
func regionBuilderDidCreateRegion(_ region: OBARegionV2)
}
class RegionBuilderViewController: OBAStaticTableViewController {
var modelService: OBAModelService?
weak var delegate: RegionBuilderDelegate?
/*
This sidecar userDataModel object is required in order to shuttle data
between the cells and this controller because the data rows used to
create the cells are copied around as opposed to being strongly
referenced. This is generally an advantageous approach except when
you really do want shared mutable state. In order to minimize the
amount of shared mutable state, we maintain this dictionary.
*/
var userDataModel = NSMutableDictionary.init(capacity: 12)
lazy var region: OBARegionV2 = {
let r = OBARegionV2.init()
// give the region a random identifier that shouldn't conflict with
// any real OBA region for a long time to come.
r.identifier = Int(arc4random_uniform(32768) + 100)
r.custom = true
return r
}()
lazy var baseURLRow: OBATextFieldRow = {
let row = OBATextFieldRow.init(labelText: NSLocalizedString("msg_base_url", comment: ""), textFieldText: self.region.baseURL?.absoluteString)
row.keyboardType = .URL
RegionBuilderViewController.applyPropertiesToTextRow(row, model: self.userDataModel)
return row
}()
lazy var nameRow: OBATextFieldRow = {
let row = OBATextFieldRow.init(labelText: NSLocalizedString("msg_name", comment: ""), textFieldText: self.region.regionName)
RegionBuilderViewController.applyPropertiesToTextRow(row, model: self.userDataModel)
return row
}()
lazy var obaRealTimeRow: OBASwitchRow = {
let row = OBASwitchRow.init(title: NSLocalizedString("msg_supports_oba_realtime_apis", comment: ""), action: nil)
row.switchValue = self.region.supportsObaRealtimeApis
row.dataKey = row.title
row.model = self.userDataModel
return row
}()
lazy var isActiveRow: OBASwitchRow = {
let row = OBASwitchRow.init(title: NSLocalizedString("msg_is_active", comment: ""), action: nil)
row.switchValue = self.region.active
row.dataKey = row.title
row.model = self.userDataModel
return row
}()
lazy var contactEmailRow: OBATextFieldRow = {
let row = OBATextFieldRow.init(labelText: NSLocalizedString("msg_contact_email", comment: ""), textFieldText: self.region.contactEmail)
row.keyboardType = .emailAddress
row.autocapitalizationType = .none
RegionBuilderViewController.applyPropertiesToTextRow(row, model: self.userDataModel)
return row
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("msg_add_region", comment: "")
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: OBAStrings.cancel, style: .plain, target: self, action: #selector(cancel))
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: OBAStrings.save, style: .done, target: self, action: #selector(save))
let requiredSection = OBATableSection.init(title: NSLocalizedString("msg_required", comment: ""))
requiredSection.addRow(self.baseURLRow)
requiredSection.addRow(self.nameRow)
let optionalSection = OBATableSection.init(title: NSLocalizedString("msg_optional", comment: ""))
optionalSection.addRow(self.obaRealTimeRow)
optionalSection.addRow(self.isActiveRow)
optionalSection.addRow(self.contactEmailRow)
self.sections = [requiredSection, optionalSection]
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let indexPath = self.indexPath(for: self.baseURLRow)
if let cell: OBATextFieldCell = self.tableView.cellForRow(at: indexPath!) as! OBATextFieldCell? {
cell.textField.becomeFirstResponder()
}
}
// MARK: - Actions
@objc func cancel() {
self.dismiss(animated: true, completion: nil)
}
@objc func save() {
self.view.endEditing(true)
self.loadDataIntoRegion()
guard self.region.isValidModel() else {
let alert = UIAlertController.init(title: NSLocalizedString("msg_invalid_region", comment: ""), message: NSLocalizedString("msg_alert_custom_region_not_valid", comment: "Invalid region error message"), preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: OBAStrings.dismiss, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
SVProgressHUD.show()
self.modelService = OBAModelService(baseURL: self.region.baseURL!)
let URL = self.modelService!.obaJsonDataSource.config.constructURL(OBAAgenciesWithCoverageAPIPath, withArgs: nil)
self.modelService!.requestAgenciesWithCoverage().then { agencies -> Void in
for agency in (agencies as! [OBAAgencyWithCoverageV2]) {
if let bounds = agency.regionBounds {
self.region.addBound(bounds)
}
}
if let delegate = self.delegate {
delegate.regionBuilderDidCreateRegion(self.region)
}
self.dismiss(animated: true, completion: nil)
}.always {
SVProgressHUD.dismiss()
}.catch { error in
let msg = String(format: NSLocalizedString("text_unable_load_data_region_param", comment: ""), URL!.absoluteString, (error as NSError).localizedDescription)
let alert = UIAlertController.init(title: NSLocalizedString("msg_invalid_region_base_url", comment: ""), message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: OBAStrings.dismiss, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - Private
/**
Common configuration for lazily loaded properties.
*/
fileprivate class func applyPropertiesToTextRow(_ row: OBATextFieldRow, model: NSMutableDictionary) {
row.dataKey = row.labelText
row.model = model
}
fileprivate func loadDataIntoRegion() {
// Required Fields
if let text = self.userDataModel[self.baseURLRow.dataKey!] {
self.region.obaBaseUrl = text as! String
}
if let text = self.userDataModel[self.nameRow.dataKey!] {
self.region.regionName = text as! String
}
// Optional Fields
self.region.contactEmail = self.userDataModel[self.contactEmailRow.dataKey!] as? String
if let val = self.userDataModel[self.obaRealTimeRow.dataKey!] as! Bool? {
self.region.supportsObaRealtimeApis = val
}
if let val = self.userDataModel[self.isActiveRow.dataKey!] as! Bool? {
self.region.active = val
}
}
}
| apache-2.0 | b0ac162ae33f4938e8903ae13f8fa120 | 38.075269 | 237 | 0.674051 | 4.568196 | false | false | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/Views/ColorPickerView.swift | 1 | 7776 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
// based on https://github.com/jawngee/ILColorPicker
import UIKit
/**
The `ColorPickerViewDelegate` protocol defines a set of optional methods you can use to receive value-change messages for ColorPickerViewDelegate objects.
*/
@available(iOS 8, *)
@objc(IMGLYColorPickerViewDelegate) public protocol ColorPickerViewDelegate {
/**
Is called when a color has been picked.
- parameter colorPickerView: The sender of the event.
- parameter color: The picked color value.
*/
func colorPicked(colorPickerView: ColorPickerView, didPickColor color: UIColor)
/**
Is called when the picking process has been cancled.
- parameter colorPickerView: The sender of the event.
*/
func canceledColorPicking(colorPickerView: ColorPickerView)
}
/**
The `ColorPickerView` class provides a class that is used to pick colors.
It contains three elements. A hue-picker, a brightness-saturation-picker and a preview of the picked color.
*/
@available(iOS 8, *)
@objc(IMGLYColorPickerView) public class ColorPickerView: UIView {
/// The receiver’s delegate.
/// - seealso: `ColorPickerViewDelegate`.
public weak var pickerDelegate: ColorPickerViewDelegate?
/// The currently selected color.
public var color = UIColor.blackColor() {
didSet {
huePickerView.color = color
alphaPickerView.color = color
saturationBrightnessPickerView.color = color
}
}
/// The initial set color.
public var initialColor = UIColor.blackColor() {
didSet {
color = initialColor
}
}
private var saturationBrightnessPickerView = SaturationBrightnessPickerView()
private var huePickerView = HuePickerView()
private var alphaPickerView = AlphaPickerView()
private var leftMostSpacer = UIView()
private var leftSpacer = UIView()
private var rightSpacer = UIView()
private var rightMostSpacer = UIView()
// MARK: - init
/**
:nodoc:
*/
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
/**
:nodoc:
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
configureSaturationBrightnessPicker()
configureHuePickView()
configureAlphaPickerView()
configureSpacers()
configureConstraints()
}
// MARK: - configuration
private func configureSaturationBrightnessPicker() {
self.addSubview(saturationBrightnessPickerView)
saturationBrightnessPickerView.translatesAutoresizingMaskIntoConstraints = false
saturationBrightnessPickerView.pickerDelegate = self
}
private func configureHuePickView() {
self.addSubview(huePickerView)
huePickerView.translatesAutoresizingMaskIntoConstraints = false
huePickerView.pickerDelegate = self
}
private func configureAlphaPickerView() {
self.addSubview(alphaPickerView)
alphaPickerView.translatesAutoresizingMaskIntoConstraints = false
alphaPickerView.pickerDelegate = self
}
private func configureSpacers() {
leftMostSpacer.translatesAutoresizingMaskIntoConstraints = false
leftSpacer.translatesAutoresizingMaskIntoConstraints = false
rightSpacer.translatesAutoresizingMaskIntoConstraints = false
rightMostSpacer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(leftMostSpacer)
self.addSubview(leftSpacer)
self.addSubview(rightSpacer)
self.addSubview(rightMostSpacer)
}
private func configureConstraints() {
let views = [
"saturationBrightnessPickerView" : saturationBrightnessPickerView,
"huePickerView" : huePickerView,
"alphaPickerView" : alphaPickerView,
"leftMostSpacer" : leftMostSpacer,
"leftSpacer" : leftSpacer,
"rightSpacer" : rightSpacer,
"rightMostSpacer" : rightMostSpacer
]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[saturationBrightnessPickerView(256)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[huePickerView(256)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[alphaPickerView(256)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[leftMostSpacer(1)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[leftSpacer(1)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[rightSpacer(1)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[rightMostSpacer(1)]", options: [], metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[leftMostSpacer]-[huePickerView(20)]-[leftSpacer]-[saturationBrightnessPickerView(256)]-[rightSpacer]-[alphaPickerView(20)]-[rightMostSpacer]-|", options: [], metrics: nil, views: views))
self.addConstraint(NSLayoutConstraint(item: leftMostSpacer, attribute: .Width, relatedBy: .Equal, toItem: leftSpacer, attribute: .Width, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: leftSpacer, attribute: .Width, relatedBy: .Equal, toItem: rightSpacer, attribute: .Width, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: rightSpacer, attribute: .Width, relatedBy: .Equal, toItem: rightMostSpacer, attribute: .Width, multiplier: 1.0, constant: 0))
}
}
@available(iOS 8, *)
extension ColorPickerView: SaturationBrightnessPickerViewDelegate {
/**
:nodoc:
*/
public func colorPicked(saturationBrightnessPickerView: SaturationBrightnessPickerView, didPickColor color: UIColor) {
let alpha = alphaPickerView.alphaValue
let colorWithAlpha = color.colorWithAlphaComponent(alpha)
alphaPickerView.color = colorWithAlpha
pickerDelegate?.colorPicked(self, didPickColor: colorWithAlpha)
}
}
@available(iOS 8, *)
extension ColorPickerView: HuePickerViewDelegate {
/**
:nodoc:
*/
public func huePicked(huePickerView: HuePickerView, hue: CGFloat) {
saturationBrightnessPickerView.hue = hue
let color = saturationBrightnessPickerView.color
let alpha = alphaPickerView.alphaValue
let colorWithAlpha = color.colorWithAlphaComponent(alpha)
alphaPickerView.color = colorWithAlpha
pickerDelegate?.colorPicked(self, didPickColor: colorWithAlpha)
}
}
@available(iOS 8, *)
extension ColorPickerView: AlphaPickerViewDelegate {
/**
:nodoc:
*/
public func alphaPicked(alphaPickerView: AlphaPickerView, alpha: CGFloat) {
let color = saturationBrightnessPickerView.color
pickerDelegate?.colorPicked(self, didPickColor: color.colorWithAlphaComponent(alpha))
}
}
| mit | cbc4f816354cd07170285de96ce6beb1 | 40.132275 | 265 | 0.712246 | 5.028461 | false | true | false | false |
JNU-Include/Swift-Study | Learning Swift.playground/Pages/Inheritance.xcplaygroundpage/Contents.swift | 1 | 981 | //Inheritance
//Subclass <- Superclass
//Overriding
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "Traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
}
}
let someVehicle = Vehicle()
print(someVehicle.description)
class Bicycle: Vehicle {
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.currentSpeed
bicycle.description
bicycle.hasBasket
class Tandem: Bicycle {
var numberOfPassengers = 0
}
let tandom = Tandem()
tandom.currentSpeed
tandom.description
tandom.makeNoise()
tandom.hasBasket
tandom.numberOfPassengers
class Train: Vehicle {
override func makeNoise() {
print("칙칙폭폭")
}
}
let train = Train()
train.makeNoise()
class Car: Vehicle {
var gear = 1
override var description: String{
return super.description + " in gear \(gear)"
}
}
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
print(car.description)
| apache-2.0 | 6338e9adff82b47a2a95049dc4435065 | 13.308824 | 60 | 0.669065 | 3.630597 | false | false | false | false |
net-a-porter-mobile/XCTest-Gherkin | Pod/Core/Step.swift | 1 | 6007 | //
// Step.swift
// whats-new
//
// Created by Sam Dean on 26/10/2015.
// Copyright © 2015 net-a-porter. All rights reserved.
//
import Foundation
public struct StepMatches<T: MatchedStringRepresentable> {
let allMatches: [T]
let namedMatches: [String: T]
public var count: Int {
return allMatches.count
}
public subscript(_ index: Int) -> T {
return allMatches[index]
}
public subscript(_ key: String) -> T? {
return namedMatches[key]
}
public func map<U: MatchedStringRepresentable>(_ f: (T) -> U) -> StepMatches<U> {
return StepMatches<U>(allMatches: allMatches.map(f), namedMatches: namedMatches.mapValues(f))
}
}
/**
Represents a single step definition - create it with the expression and the
test to run as a block.
*/
class Step: Hashable, Equatable, CustomDebugStringConvertible {
let expression: String
let function: (StepMatches<String>)->()
fileprivate let file: String
fileprivate let line: Int
// Compute this as part of init
let regex: NSRegularExpression
let groupsNames: [String]
/**
Create a new Step definition with an expression to match against and a function to be
run when it matches.
The `file` and `line` parameters are for debugging; they should show where the step was
initially defined.
*/
init(_ expression: String, options: NSRegularExpression.Options, file: String, line: Int, _ function: @escaping (StepMatches<String>)->() ) {
self.expression = expression
self.function = function
self.file = file
self.line = line
if #available(iOS 11.0, OSX 10.13, *) {
let namedGroupExpr = try! NSRegularExpression(pattern: "(\\(\\?<(\\w+)>.+?\\))")
groupsNames = namedGroupExpr.matches(in: expression, range: NSMakeRange(0, expression.count)).map { namedGroupMatch in
return (expression as NSString).substring(with: namedGroupMatch.range(at: 2))
}
} else {
groupsNames = []
}
var pattern = expression
if options.contains(.matchesFullString) {
if !expression.hasPrefix("^") {
pattern = "^\(expression)"
}
if !expression.hasSuffix("$") {
pattern = "\(expression)$"
}
}
self.regex = try! NSRegularExpression(pattern: pattern, options: options)
}
func matches(from match: NSTextCheckingResult, expression: String) -> (matches: StepMatches<String>, stepDescription: String) {
let namedMatches: [String: String]
let debugDescription: String
if #available(iOS 11.0, OSX 10.13, *) {
let cleanedMatches = groupsNames
.compactMap { (groupName) -> (groupName: String, range: Range<String.Index>)? in
let nsRange = match.range(withName: groupName)
guard
nsRange.location != NSNotFound,
let range = Range(nsRange, in: expression)
else {
return nil
}
return (groupName, range)
}
.reversed()
debugDescription = cleanedMatches.reduce(into: expression, { (result, row) in
let replacement = row.groupName.humanReadableString.lowercased()
result.replaceSubrange(row.range, with: replacement)
})
namedMatches = cleanedMatches.reduce(into: [String: String]()) { (result, row) in
result[row.groupName] = expression.substring(with: row.range)
}
} else {
debugDescription = expression
namedMatches = .init()
}
let allMatches = (1..<match.numberOfRanges).compactMap { at -> String? in
let range = match.range(at: at)
guard range.location != NSNotFound else {
return nil
}
return (expression as NSString).substring(with: range)
}
return (StepMatches(allMatches: allMatches, namedMatches: namedMatches), debugDescription)
}
func hash(into hasher: inout Hasher) {
hasher.combine(expression)
hasher.combine(file)
hasher.combine(line)
}
var debugDescription: String {
return "/\(expression)/ \(shortLocationDescription)"
}
var fullLocationDescription: String {
return "(\(file):\(line))"
}
var shortLocationDescription: String {
return "(\((file as NSString).lastPathComponent):\(line))"
}
}
func ==(lhs: Step, rhs: Step) -> Bool {
return lhs.expression == rhs.expression
}
extension Collection where Element == Step {
func printStepsDefinitions() {
print("-------------")
print("Defined steps")
print("-------------")
print(self.map { String(reflecting: $0) }.sorted { $0.lowercased() < $1.lowercased() }.joined(separator: "\n"))
print("-------------")
}
}
extension Collection where Element == String {
func printAsTemplatedCodeForAllMissingSteps(suggestedSteps: (String) -> [Step]) {
print("Copy paste these steps in a StepDefiner subclass:")
print("-------------")
self.forEach {
print("step(\"\($0)"+"\") {XCTAssertTrue(true)}")
let suggestedSteps = suggestedSteps($0)
if !suggestedSteps.isEmpty {
print("-------------\nOr maybe you meant one of these steps:\n-------------")
print(suggestedSteps.map { String(reflecting: $0) }.joined(separator: "\n"))
}
}
print("-------------")
}
func printAsUnusedSteps() {
print("-------------")
print("Unused steps")
print("-------------")
print(self.sorted { $0.lowercased() < $1.lowercased() }.joined(separator: "\n"));
print("-------------")
}
}
| apache-2.0 | 48818da14a04cb233ffd7becab452ee9 | 32 | 145 | 0.567266 | 4.659426 | false | false | false | false |
wwq0327/iOS9Example | The Swift Programming Language.playground/Pages/Day1 Swift语法学习:值类型与引用类型.xcplaygroundpage/Contents.swift | 1 | 1846 | import Foundation
//: # 值类型与引用类型
//: ## 值类型
//: 字符串类型为值类型,制会被拷贝到新的对象上,且新旧两个对象的值是独立互不影响的。
var str = "Hello, playground"
var str1 = str
print("str: \(str), str1: \(str1)")
str = "hello, world"
print("str: \(str), str1: \(str1)")
//: Out: "str: hello, world, str1: Hello, playground\n"
//: 原对象的值作了修改,但新的第二个对象的值并没有受到影响,在对str1赋值的时候,也只是将str作了一个副本,然后再将这个副本给了str1。
//: ## 引用类型
//: 对于类来说,由于类在Swift中是引用类型,在传递参数的时候,就是数据本身传递给新的变量的,因而新旧变量的值都会产生相应的变化。
class StringA {
var str = "hello, world"
}
var strA = StringA()
var strB = strA
print("strA: \(strA.str), strB: \(strB.str)")
strA.str = "hello, swift"
print("strA: \(strA.str), strB: \(strB.str)")
// 修改引用者的值
strB.str = "你好,世界!"
print("strA: \(strA.str), strB: \(strB.str)")
//: Out: "strA: 你好,世界!, strB: 你好,世界!\n"
//: 新旧变量的值都发生着相应的变化。
//: ## Swift中值类型有
//: - 枚举型
enum CommpassPoint {
case North
case South
case East
case West
}
var p1 = CommpassPoint.North
var p2 = p1
print("p1: \(p1), p2: \(p2)")
p2 = .South
print("p1: \(p1), p2: \(p2)")
//: "p1: North, p2: South\n"
//: 所输出的两个值不一样,即枚举类型属于值类型
//: - 结构体
struct Human {
var name = "Wyatt"
var apge = "35"
}
var person1 = Human()
var person2 = person1
print("P1: \(person1.name), P2: \(person2.name)")
person1.name = "hahaha"
print("P1: \(person1.name), P2: \(person2.name)")
//: ## Swift中引用类型有
//: - 类
| apache-2.0 | e8a59441f99fa7f990a936ac715c130e | 17.611111 | 73 | 0.621642 | 2.214876 | false | false | false | false |
koher/Alamofire | Source/Download.swift | 1 | 9020 | // Alamofire.swift
//
// Copyright (c) 2014–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 Foundation
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
dispatch_sync(self.queue) {
downloadTask = self.session.downloadTaskWithRequest(request)
}
case .ResumeData(let resumeData):
dispatch_sync(self.queue) {
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
}
let request = Request(session: self.session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
self.delegate[request.delegate.task] = request.delegate
if self.startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: headers The HTTP headers. `nil` by default.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request {
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return download(mutableURLRequest, destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
// MARK: -
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { temporaryURL, response -> NSURL in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
/// The resume data of the underlying download task if available after a failure.
public var resumeData: NSData? {
var data: NSData?
if let delegate = self.delegate as? DownloadTaskDelegate {
data = delegate.resumeData
}
return data
}
// MARK: - DownloadTaskDelegate
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask? { return self.task as? NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return self.resumeData }
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
self.error = fileManagerError
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let downloadTaskDidWriteData = self.downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else {
self.progress.totalUnitCount = totalBytesExpectedToWrite
self.progress.completedUnitCount = totalBytesWritten
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
self.progress.totalUnitCount = expectedTotalBytes
self.progress.completedUnitCount = fileOffset
}
}
}
}
| mit | 63dee1f64cbde1e96310687916d0e95a | 44.09 | 327 | 0.703482 | 5.825581 | false | false | false | false |
candyan/RepairMan | RepairMan/views/ItemPhotosEditorView.swift | 1 | 8819 | //
// ItemPhotosEditorView.swift
//
//
// Created by Cherry on 9/2/15.
//
//
import UIKit
class ItemPhotosEditorView: UIView {
private var itemPhotos = NSMutableArray(capacity: 8)
private var photoButtons = NSMutableArray(capacity: 8)
private var addButton: UIButton?
private weak var draggingButton: UIButton?
var addButtonDidTouchUpInsideBlock: (()->())?
var photoButtonDidTouchUpInsideBlock: ((photo: UIImage, index: Int)->())?
private var imageButtonSize: CGFloat {
return (self.bounds.width - 10 * 2 - 3 * 7) / 4.0
}
var photos: NSArray! {
return NSArray(array: itemPhotos)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.loadSubviews()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addItemPhoto(photo: UIImage!) {
self.itemPhotos.addObject(photo)
let button = self.photoButtons.objectAtIndex(self.itemPhotos.count - 1) as! UIButton
button.setImage(photo, forState: .Normal)
self.setNeedsLayout()
}
func removeItemPhotoAtIndex(index: Int) {
if index < self.itemPhotos.count {
self.itemPhotos.removeObjectAtIndex(index)
}
for (buttonIndex, button) in enumerate(self.photoButtons) {
if buttonIndex < self.itemPhotos.count {
let image = self.itemPhotos[buttonIndex] as! UIImage
button.setImage(image, forState: .Normal)
} else {
button.setImage(nil, forState: .Normal)
}
}
self.setNeedsLayout()
}
func removeItemPhoto(photo: UIImage!) {
let index = self.itemPhotos.indexOfObject(photo)
if index != NSNotFound {
self.removeItemPhotoAtIndex(index)
}
}
func showInTableView(tableView: UITableView!) {
self.setFrameWidth(tableView.bounds.width)
let height = self.imageButtonSize * 2 + 13 * 3
self.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: height)
tableView.tableHeaderView = self
self.setNeedsLayout()
}
func photoButtonTouchUpInsideHandler(sender: UIButton?) {
if self.photoButtonDidTouchUpInsideBlock != nil {
let index = self.photoButtons.indexOfObject(sender!)
let photo = self.itemPhotos.objectAtIndex(index) as! UIImage
self.photoButtonDidTouchUpInsideBlock!(photo: photo, index: index)
}
}
func addButtonTouchUpInsideHandler(sender: UIButton?) {
if self.addButtonDidTouchUpInsideBlock != nil {
self.addButtonDidTouchUpInsideBlock!()
}
}
func photoPanGestureRecognizedHandler(gr: UIPanGestureRecognizer?) {
if gr?.state == .Began {
draggingButton = gr?.view as? UIButton
if draggingButton != nil {
self.bringSubviewToFront(draggingButton!)
}
}
if gr?.state == .Changed {
let grButton = gr?.view as! UIButton
let currentButtonIndex = self.photoButtons.indexOfObject(grButton)
let translationPosition = gr?.translationInView(self)
let frame = CGRect(x: grButton.frame.origin.x + translationPosition!.x,
y: grButton.frame.origin.y + translationPosition!.y,
width: grButton.frame.width, height: grButton.frame.height)
if frame.maxY >= self.bounds.height || frame.maxY < 0 {
gr?.enabled = false
gr?.enabled = true
return
}
grButton.setFrameOriginPoint(frame.origin)
gr?.setTranslation(CGPointZero, inView: self)
let panToButtonIndex = frame.origin.photoIndexForViewSize(self.bounds.size)
if currentButtonIndex != panToButtonIndex && panToButtonIndex < self.itemPhotos.count {
let photo = self.itemPhotos.objectAtIndex(currentButtonIndex) as! UIImage
self.itemPhotos.removeObjectAtIndex(currentButtonIndex)
self.itemPhotos.insertObject(photo, atIndex: panToButtonIndex)
let photoButton = self.photoButtons.objectAtIndex(currentButtonIndex) as! UIButton
self.photoButtons.removeObjectAtIndex(currentButtonIndex)
self.photoButtons.insertObject(photoButton, atIndex: panToButtonIndex)
self.setNeedsLayout()
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 4,
initialSpringVelocity: 10,
options: .CurveEaseInOut,
animations: { () -> Void in
self.layoutIfNeeded()
}, completion: nil)
}
}
if gr?.state == .Cancelled || gr?.state == .Ended || gr?.state == .Failed {
self.draggingButton = nil
self.setNeedsLayout()
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 4,
initialSpringVelocity: 10,
options: .CurveEaseInOut,
animations: { () -> Void in
self.layoutIfNeeded()
}, completion: nil)
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.addButton?.hidden = (self.itemPhotos.count >= 8)
self.bringSubviewToFront(self.addButton!)
for (index, photoButton) in enumerate(self.photoButtons) {
let photoPosition = index.photoPosition
let originY = (13 + photoPosition.y * (self.imageButtonSize + 13))
let originX = (10 + photoPosition.x * (self.imageButtonSize + 7))
photoButton.setFrameSize(CGSize(width: self.imageButtonSize, height: self.imageButtonSize))
if self.draggingButton != photoButton as? UIButton {
photoButton.setFrameOriginPoint(CGPoint(x: originX, y: originY))
}
if index == self.itemPhotos.count {
self.addButton?.frame = CGRect(x: originX, y: originY,
width: self.imageButtonSize, height: self.imageButtonSize)
}
}
}
}
extension ItemPhotosEditorView {
private func loadSubviews() {
for _ in 1...8 {
let button = UIButton.photoImageButton()
self.photoButtons.addObject(button!)
button?.addTarget(self, action: "photoButtonTouchUpInsideHandler:", forControlEvents: .TouchUpInside)
let panGR = UIPanGestureRecognizer(target: self, action: "photoPanGestureRecognizedHandler:")
panGR.maximumNumberOfTouches = 1
panGR.delegate = self
button?.addGestureRecognizer(panGR)
self.addSubview(button!)
}
addButton = UIButton(frame: CGRectZero)
self.addSubview(addButton!)
addButton!.setImage(UIImage(named: "ItemAddImage"), forState: .Normal)
addButton!.backgroundColor = UIColor(hex: 0x4A90E2)
addButton!.addTarget(self, action: "addButtonTouchUpInsideHandler:", forControlEvents: .TouchUpInside)
let bottomSL = YASeparatorLine(frame: CGRectZero, lineColor: UIColor(hex: 0x000000, alpha: 0.2), lineWidth: 1)
self.addSubview(bottomSL)
bottomSL.mas_makeConstraints { (maker) -> Void in
maker.bottom.equalTo()(self)
maker.leading.equalTo()(self).offset()(10)
maker.trailing.equalTo()(self).offset()(-0)
maker.height.mas_equalTo()(0.5)
}
}
}
extension ItemPhotosEditorView: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
let view = gestureRecognizer.view
if view == nil {
return false
}
let viewIndex = photoButtons.indexOfObject(view!)
return viewIndex < itemPhotos.count
}
}
extension Int {
private var photoPosition: CGPoint {
return CGPoint(x: self % 4, y: self / 4)
}
}
extension CGPoint {
private func photoIndexForViewSize(size: CGSize) -> Int {
let row = self.y < (size.height / 2.0) ? 0 : 1 as Int
let col = Int(floor(self.x / (size.width / 4.0)))
return row * 4 + col
}
}
extension UIButton {
private class func photoImageButton() -> UIButton? {
let button = UIButton(frame: CGRectZero)
button.backgroundColor = UIColor(hex: 0xEEEEEE)
return button
}
} | mit | 271abcca3908a2f8d87a04f26239141b | 33.588235 | 118 | 0.596893 | 4.899444 | false | false | false | false |
xasos/UIUC-Laundry | UIUC-Laundry/Timer.swift | 1 | 479 | //import Foundation
//@IBOutlet var countDownLabel: UILabel!
//
//var count = 10
//
//verride func viewDidLoad() {
// super.viewDidLoad()
//
// var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
//}
//
//func update() {
//
// if(count > 0)
// {
// countDownLabel.text = String(count--)
// }
//
// if(count == 0) {
// // send notification
// }
//
//} | mit | ef8bf9702c17d6905664c550cdfce93f | 19.869565 | 135 | 0.559499 | 3.397163 | false | false | false | false |
MattKiazyk/Operations | framework/Operations/Operations/GroupOperation.swift | 1 | 2545 | //
// GroupOperation.swift
// Operations
//
// Created by Daniel Thorpe on 18/07/2015.
// Copyright © 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
/**
An `Operation` subclass which enables the grouping
of other operations. Use `GroupOperation`s to associate
related operations together, thereby creating higher
levels of abstractions.
Additionally, `GroupOperation`s are useful as a way
of creating Operations which may repeat themselves before
subsequent operations can run. For example, authentication
operations.
*/
public class GroupOperation: Operation {
private let _queue = OperationQueue()
private let _finishingOperation = NSBlockOperation(block: {})
private var _aggregateErrors = Array<ErrorType>()
public init(operations: [NSOperation]) {
super.init()
_queue.suspended = true
_queue.delegate = self
for operation in operations {
_queue.addOperation(operation)
}
}
public convenience init(operations: NSOperation...) {
self.init(operations: operations)
}
public override func cancel() {
_queue.cancelAllOperations()
super.cancel()
}
public override func execute() {
_queue.suspended = false
_queue.addOperation(_finishingOperation)
}
public func addOperation(operation: NSOperation) {
_queue.addOperation(operation)
}
final func aggregateError(error: ErrorType) {
_aggregateErrors.append(error)
}
public func operationDidFinish(operation: NSOperation, withErrors errors: [ErrorType]) {
// no-op, subclasses can override for their own functionality.
}
}
extension GroupOperation: OperationQueueDelegate {
public func operationQueue(queue: OperationQueue, willAddOperation operation: NSOperation) {
assert(!_finishingOperation.finished && !_finishingOperation.executing, "Cannot add new operations to a group after the group has completed.")
if operation !== _finishingOperation {
_finishingOperation.addDependency(operation)
}
}
public func operationQueue(queue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [ErrorType]) {
_aggregateErrors.extend(errors)
if operation === _finishingOperation {
_queue.suspended = true
finish(errors: _aggregateErrors)
}
else {
operationDidFinish(operation, withErrors: errors)
}
}
}
| mit | 8e5d30840fdf0ec82ced9febaaaf9242 | 27.58427 | 150 | 0.676887 | 5.118712 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Insurance | PerchReadyApp/apps/Perch/iphone/native/Perch/Security/ReadyAppsChallengeHandler.swift | 1 | 5082 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
import UIKit
/**
This class interacts with the MobileFirst Server to authenticate the user upon login. If the user has been timed out,
it will present the user with the login view controller, so they can login.
*/
class ReadyAppsChallengeHandler : ChallengeHandler {
var loginViewController : LoginViewController!
private var isFirstAuth = true
override init(){
let configManager = ConfigManager.sharedInstance
super.init(realm: configManager.perchRealm)
}
// Resets variables to original values in the case of a logout
func reset() {
isFirstAuth = true
}
/**
Callback method for MobileFirst platform authenticator which determines if the user has been timed out.
- parameter response:
*/
override func isCustomResponse(response: WLResponse!) -> Bool {
MQALogger.log("--------- isCustomResponse in readyapps------")
//check for bad token here
if (response != nil && response.getResponseJson() != nil) {
let jsonResponse = response.getResponseJson() as NSDictionary
let authRequired = jsonResponse.objectForKey("authRequired") as! Bool?
if authRequired != nil {
return authRequired!
}
}
return false
}
/**
Callback method for MobileFirst platform which handles the success scenario
- parameter response:
*/
override func onSuccess(response: WLResponse!) {
MQALogger.log("Challenge Handler Success: \(response)")
submitSuccess(response)
let responseJson = response.getResponseJson() as NSDictionary
LoginDataManager.sharedInstance.parseLoginResponse(responseJson)
if loginViewController != nil {
loginViewController.setKeychainCredentials()
loginViewController.loginSuccess()
loginViewController = nil
}
}
/**
Callback method for MobileFirst platform which handles the failure scenario
- parameter response:
*/
override func onFailure(response: WLFailResponse!) {
MQALogger.log("Challenger Handler failure: \(response)");
submitFailure(response)
if loginViewController != nil {
loginViewController.loginFailed()
}
}
/**
Callback method for MobileFirst platform which handles challenge presented by the server, It shows the login view controllers, so the user
can re-authenticate.
- parameter response:
*/
override func handleChallenge(response: WLResponse!) {
// Tell the Pin View controller that auth is required. Pass the Pin VC a callback for when the pin vc is ready for login to be presented
if isFirstAuth {
isFirstAuth = false
var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topVC?.presentedViewController != nil) {
topVC = topVC!.presentedViewController
}
if let pinVC = topVC as? PinViewController {
pinVC.authRequired({[unowned self] in self.presentLogin()})
}
} else {
// In this case, we just need to re-authenticate, so just present the login view controller as normal
if loginViewController == nil {
let loginStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
loginViewController = loginStoryboard.instantiateViewControllerWithIdentifier("LoginVC") as! LoginViewController
}
// Present login view controller
var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topVC?.presentedViewController != nil) {
topVC = topVC!.presentedViewController
}
loginViewController.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
topVC?.presentViewController(loginViewController, animated: true, completion: nil)
}
}
// Function is called by the Pin view controller when the login vc is ready to be presented
func presentLogin() {
if loginViewController == nil {
let loginStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
loginViewController = loginStoryboard.instantiateViewControllerWithIdentifier("LoginVC") as! LoginViewController
// Present login view controller
var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topVC?.presentedViewController != nil) {
topVC = topVC!.presentedViewController
}
loginViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
topVC?.presentViewController(loginViewController, animated: false, completion: nil)
}
}
}
| epl-1.0 | f7777e389e56341d2300cb7c2cbb3724 | 37.492424 | 144 | 0.648494 | 6.020142 | false | false | false | false |
raphaelseher/CE-App | CE/EventDetailViewController.swift | 1 | 8488 | //Event App with data from veranstaltungen.kaernten.at
//Copyright (C) 2015 Raphael Seher
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along
//with this program; if not, write to the Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import UIKit
import MapKit
class EventDetailViewController: UIViewController, MKMapViewDelegate, UIWebViewDelegate {
@IBOutlet weak var eventImageView: UIImageView!
@IBOutlet weak var eventTitleLabel: UILabel!
@IBOutlet weak var eventCategorieLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var eventDescriptionWebView: UIWebView!
@IBOutlet weak var startDateLabel: UILabel!
@IBOutlet weak var endDateLabel: UILabel!
@IBOutlet weak var startTimeLabel: UILabel!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var eventLocationNameLabel: UILabel!
@IBOutlet weak var eventLocationStreetAddressLabel: UILabel!
@IBOutlet weak var eventLocationPlaceLabel: UILabel!
@IBOutlet weak var toLabel: UILabel!
@IBOutlet weak var fromLabel: UILabel!
@IBOutlet weak var eventDescriptionWebViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var mapViewHeightLayoutConstraint: NSLayoutConstraint!
var event : Event = Event()
var venue : MKAnnotation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.mapView.delegate = self;
self.navigationController?.setNavigationBarHidden(false, animated: false)
initEventDetail()
}
override func viewWillAppear(animated: Bool) {
//analytics
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: "EventsDetailActivity")
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initEventDetail() {
self.eventImageView.setImageWithURL(NSURL(string: event.image.contentUrl))
self.eventTitleLabel.text = event.name
self.initDateTime()
self.initLocation()
self.initCategories()
self.initMapView()
self.initDescription()
}
func initDateTime() {
let dayMonthYearDateFormatter : NSDateFormatter = NSDateFormatter()
let timeFormatter : NSDateFormatter = NSDateFormatter()
dayMonthYearDateFormatter.dateFormat = "dd.MM.YYYY"
timeFormatter.dateFormat = "HH:mm"
if event.startDate != nil {
self.startDateLabel.text = dayMonthYearDateFormatter.stringFromDate(event.startDate)
self.startTimeLabel.text = timeFormatter.stringFromDate(event.startDate)
}
if event.endDate != nil {
self.endDateLabel.text = dayMonthYearDateFormatter.stringFromDate(event.endDate)
self.endTimeLabel.text = timeFormatter.stringFromDate(event.endDate)
} else {
self.fromLabel.text = "am"
self.toLabel.text = ""
self.endTimeLabel.text = ""
self.endDateLabel.text = ""
}
}
func initLocation() {
self.eventLocationNameLabel.text = event.location.name
if event.location.address != nil {
self.eventLocationStreetAddressLabel.text = event.location.address.streetAddress
if event.location.address.addressLocality == nil {
self.eventLocationPlaceLabel.text = event.location.address.postalCode
} else {
self.eventLocationPlaceLabel.text = "\(event.location.address.addressLocality), \(event.location.address.postalCode)"
}
} else {
self.eventLocationStreetAddressLabel.text = ""
self.eventLocationPlaceLabel.text = ""
}
}
func initCategories() {
//categories
var categoriesAsArray : [String] = []
for category in event.categories {
categoriesAsArray.append(category.name)
}
self.eventCategorieLabel.text = categoriesAsArray.joinWithSeparator(",")
}
func initDescription() {
//description
var htmlString = "<style>html {font-family: -apple-system, 'Helvetica', 'Arial', sans-serif; font-size:12pt;} body {margin: 0; padding: 0;} </style>"
htmlString += event.eventDescription
self.eventDescriptionWebView.loadHTMLString(htmlString, baseURL: nil)
self.eventDescriptionWebView.delegate = self;
}
func webViewDidFinishLoad(webView: UIWebView) {
//resize the webView
self.eventDescriptionWebViewHeightConstraint.constant = webView.scrollView.contentSize.height
self.view.layoutIfNeeded()
}
//open links from webView in Safari
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL!)
return false
}
return true
}
func initMapView() {
//map
if event.location.geo != nil {
let mapViewPin = MKPointAnnotation()
mapViewPin.coordinate = CLLocationCoordinate2D(latitude: event.location.geo.longitude, longitude: event.location.geo.latitude)
mapViewPin.title = event.location.name
if event.location.address != nil {
mapViewPin.subtitle = event.location.address.streetAddress
}
self.mapView.addAnnotation(mapViewPin)
self.mapView.selectAnnotation(mapViewPin, animated: true)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: mapViewPin.coordinate, span: span)
self.mapView.setRegion(region, animated: true)
} else {
self.mapViewHeightLayoutConstraint.constant = 0;
self.mapView.needsUpdateConstraints()
}
}
// MARK:- Sharing
@IBAction func actionButtonAction(sender: AnyObject) {
var sharingItems = [AnyObject]()
let sharingText = self.event.name
let sharingImage = self.eventImageView.image
let sharingURL = NSURL(string: self.event.url)
if let text = sharingText {
sharingItems.append(text)
}
if let image = sharingImage {
sharingItems.append(image)
}
if let url = sharingURL {
sharingItems.append(url)
}
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
// MARK:- Map Delegate
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
self.venue = annotation
let reuseId = "pinAnnotation"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView!.canShowCallout = true
anView!.image = UIImage(named: "marker")
anView!.calloutOffset = CGPoint(x: -1.0, y: -3.0)
let navigationButton = UIButton(type: UIButtonType.Custom)
navigationButton.frame.size.width = 52
navigationButton.frame.size.height = 52
navigationButton.backgroundColor = UIColor.blueColor()
navigationButton.setImage(UIImage(named: "car"), forState: .Normal)
navigationButton.addTarget(self, action: "startNavigation:", forControlEvents: UIControlEvents.TouchUpInside)
anView!.leftCalloutAccessoryView = navigationButton
}
else {
//we are re-using a view, update its annotation reference...
anView!.annotation = annotation
}
return anView
}
func startNavigation(sender:UIButton!) {
let placemark = MKPlacemark(coordinate: venue.coordinate, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = self.venue.title!
mapItem.openInMapsWithLaunchOptions(nil)
}
}
| gpl-2.0 | 139390b73d93ff75dbf2b9849fdeedaf | 35.119149 | 153 | 0.721018 | 4.715556 | false | false | false | false |
LaszloPinter/CircleColorPicker | CircleColorPicker/ColorPicker/Views/LinearPickers/BrightnessPickerView.swift | 1 | 2077 | //
// BrightnessPickerView.swift
// CircleColorPicker
//
// Created by Laszlo Pinter on 11/17/17.
// Copyright © 2017 Laszlo Pinter. All rights reserved.
//
import UIKit
open class BrightnessPickerView: LinearPickerView {
open override func handleOrientationChange() {
(frontLayerView as! BrightnessMask).isVertical = isVertical
}
open override func createFrontLayerView() -> UIView{
let frontLayer = BrightnessMask(frame: CGRect.init(origin: CGPoint.zero, size: self.bounds.size))
frontLayer.isVertical = isVertical
return frontLayer
}
class BrightnessMask: UIView {
public var isVertical = false
func drawScale(context: CGContext){
let startColor = UIColor.init(hue: 1, saturation: 0, brightness: 0, alpha: 1).cgColor
let endColor = UIColor.init(hue: 1, saturation: 0, brightness: 0, alpha: 0).cgColor
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = [startColor, endColor] as CFArray
if let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: nil) {
var startPoint: CGPoint!
var endPoint: CGPoint!
if isVertical {
startPoint = CGPoint(x: self.bounds.width, y: self.bounds.height)
endPoint = CGPoint(x: self.bounds.width, y: 0)
}else {
startPoint = CGPoint(x: 0, y: self.bounds.height)
endPoint = CGPoint(x: self.bounds.width, y: self.bounds.height)
}
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: .drawsBeforeStartLocation)
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
drawScale(context: context)
}
}
}
| mit | 2ffde5ab0ad167ad8e10f99da5fbe79c | 34.186441 | 122 | 0.577071 | 4.990385 | false | false | false | false |
dn-m/RhythmSpellingTools | RhythmSpellingTools/RhythmSpelling.BeamJunction.swift | 1 | 8494 | //
// RhythmSpelling.BeamJunction.swift
// RhythmSpellingTools
//
// Created by James Bean on 2/13/17.
//
//
import Collections
import Rhythm
import ArithmeticTools
extension RhythmSpelling {
/// Model of `State` values for each beam-level
public struct BeamJunction {
/// Whether a beamlet is pointed forward or backward.
public enum BeamletDirection: Double {
case forward = 1
case backward = -1
}
/// Whether to start, stop, or maintain a beam for a given beam-level
public enum State {
/// Start a beam on a given level.
case start
/// Stop a beam on a given level.
case stop
/// Maintain a beam on a given level.
case maintain
/// Add a beamlet on a given level.
case beamlet(direction: BeamletDirection)
}
// MARK: - Instance Properties
public let states: [Int: State]
// MARK: - Initializers
/// Creates a `Junction` with a mapping of `State` to beam-level.
public init(_ states: [Int: State] = [:]) {
self.states = states
}
}
}
extension RhythmSpelling.BeamJunction {
/// Create a `Junction` with the given context:
///
/// - prev: Previous beaming value (if it exists)
/// - cur: Current beaming value
/// - next: Next beaming value (if it exists)
public init(_ prev: Int?, _ cur: Int, _ next: Int?) {
typealias Ranges = (
start: CountableClosedRange<Int>?,
stop: CountableClosedRange<Int>?,
maintain: CountableClosedRange<Int>?,
beamlet: (CountableClosedRange<Int>, BeamletDirection)?
)
/// - returns: `Ranges` for a singleton value.
func singleton(_ cur: Int) -> Ranges {
return (start: nil, stop: nil, maintain: nil, beamlet: (1...cur, .forward))
}
/// - returns: `Ranges` for a first value.
func first(_ cur: Int, _ next: Int) -> Ranges {
guard cur > 0 else {
return (start: nil, stop: nil, maintain: nil, beamlet: nil)
}
guard next > 0 else {
return (start: nil, stop: nil, maintain: nil, beamlet: (1...cur, .forward))
}
let startRange = 1 ... min(cur,next)
let beamletRange = cur > next ? (next + 1) ... cur : nil
return (
start: startRange,
stop: nil,
maintain: nil,
beamlet: beamletRange == nil ? nil : (beamletRange!, .forward)
)
}
/// - returns: `Ranges` for a middle value.
func middle(_ prev: Int, _ cur: Int, _ next: Int) -> Ranges {
guard cur > 0 else {
return (start: nil, stop: nil, maintain: nil, beamlet: nil)
}
guard prev > 0 else {
if next <= 0 {
return (
start: nil,
stop: nil,
maintain: nil,
beamlet: (cur - next) > 0 ? (0 ... (cur - next), .backward) : nil
)
}
return (
start: 1 ... next,
stop: nil,
maintain: nil,
beamlet: (cur - next) > 0 ? (0 ... (cur - next), .backward) : nil
)
}
guard next > 0 else {
if prev <= 0 {
return (
start: nil,
stop: nil,
maintain: nil,
beamlet: (cur - next) > 0 ? (0 ... (cur - next), .backward) : nil
)
}
return (
start: nil,
stop: 1 ... prev,
maintain: nil,
beamlet: (cur - prev) > 0 ? (1 ... (cur - prev), .backward) : nil
)
}
let maintain = min(prev,cur,next)
let startAmount = max(0, min(cur,next) - prev)
let stopAmount = max(0, min(cur,prev) - next)
let beamletAmount = cur - max(prev,next)
var beamletRange: CountableClosedRange<Int>? {
guard beamletAmount > 0 else {
return nil
}
let lowerBound = max(maintain,startAmount,stopAmount)
return (lowerBound + 2) ... (lowerBound + 1) + beamletAmount
}
return (
start: startAmount > 0 ? (maintain + 1) ... maintain + startAmount : nil,
stop: stopAmount > 0 ? (maintain + 1) ... maintain + stopAmount : nil,
maintain: 1 ... min(prev,cur,next),
beamlet: beamletRange == nil ? nil : (beamletRange!, .backward)
)
}
/// - returns: `Ranges` for a last value.
func last(_ prev: Int, _ cur: Int) -> Ranges {
guard cur > 0 else {
return (start: nil, stop: nil, maintain: nil, beamlet: nil)
}
guard prev > 0 else {
return (start: nil, stop: nil, maintain: nil, beamlet: (1...cur, .backward))
}
let stopRange = 1 ... min(cur,prev)
let beamletRange = cur > prev ? (prev + 1) ... cur : nil
return (
start: nil,
stop: stopRange,
maintain: nil,
beamlet: beamletRange == nil ? nil : (beamletRange!, .backward)
)
}
/// - returns: `Ranges` for the given context.
func ranges(_ prev: Int?, _ cur: Int, _ next: Int?) -> Ranges {
switch (prev, cur, next) {
case (nil, cur, nil):
return singleton(cur)
case (nil, let cur, let next?):
return first(cur, next)
case (let prev?, let cur, let next?):
return middle(prev, cur, next)
case (let prev?, let cur, nil):
return last(prev, cur)
default:
fatalError("Ill-formed context")
}
}
// TODO: Refactor
var result: [Int: State] = [:]
let (start, stop, maintain, beamlets) = ranges(prev,cur,next)
start?.forEach { result[$0] = .start }
stop?.forEach { result[$0] = .stop }
maintain?.forEach { result[$0] = .maintain }
// TODO: Refactor
let beamletDirection = beamlets?.1
let beamletRange = beamlets?.0
beamletRange?.forEach { result[$0] = .beamlet(direction: beamletDirection!) }
self.init(result)
}
}
extension RhythmSpelling.BeamJunction: Equatable {
/// - returns: `true` if `BeamJunction` values are equivalent. Otherwise, `false`.
public static func == (lhs: RhythmSpelling.BeamJunction, rhs: RhythmSpelling.BeamJunction)
-> Bool
{
return lhs.states == rhs.states
}
}
extension RhythmSpelling.BeamJunction.State: Equatable {
public static func == (
lhs: RhythmSpelling.BeamJunction.State,
rhs: RhythmSpelling.BeamJunction.State
) -> Bool
{
switch (lhs,rhs) {
case (.start, start), (.stop, .stop), (.maintain, .maintain):
return true
case (.beamlet(let a), .beamlet(let b)):
return a == b
default:
return false
}
}
}
extension RhythmSpelling.BeamJunction: CustomStringConvertible {
public var description: String {
return states.description
}
}
extension RhythmSpelling.BeamJunction.State: CustomStringConvertible {
/// Printed description.
public var description: String {
switch self {
case .start:
return "start"
case .stop:
return "stop"
case .maintain:
return "maintain"
case .beamlet(let direction):
return "beamlet (\(direction))"
}
}
}
| mit | 73f43dd9b4bedeebde87fb1c2f1ac9ab | 30.69403 | 94 | 0.465387 | 4.561762 | false | false | false | false |
mkihmouda/Ya-Translator-Chat | IChat/BlureView.swift | 1 | 861 | //
// BlureView.swift
// YaTranslator
//
// Created by Mac on 12/5/16.
// Copyright © 2016 Mac. All rights reserved.
//
import UIKit
class BlureView: UIView {
override func awakeFromNib() {
self.addBlureEffects() // add blure effects
}
func addBlureEffects(){
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = CGRect(origin: CGPoint(x: 0 ,y : 0 ), size: CGSize(width: self.frame.size.width , height: self.frame.size.height))
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
blurEffectView.alpha = 0.75
self.addSubview(blurEffectView)
self.sendSubview(toBack: blurEffectView)
}
}
| mit | 23a52ae6c78d365cba60c009a458116f | 26.741935 | 146 | 0.647674 | 4.410256 | false | false | false | false |
Averylamp/openwhisk-xcode | whiskbot-demo-app/WhiskBot/ChatViewController.swift | 2 | 2997 | /*
* Copyright 2015-2016 IBM Corporation
*
* 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.
*/
//
// ChatViewController.swift
// WhiskBot
//
// Created by whisk on 1/17/17.
// Copyright © 2017 Avery Lamp. All rights reserved.
//
import UIKit
class ChatViewController: UIViewController {
@IBOutlet weak var chatButton: UIButton!
@IBOutlet weak var stopImage: UIImageView!
@IBOutlet weak var microphoneImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
chatButton.tintColor = UIColor.white
stopImage.alpha = 0.0
}
@IBAction func infoButtonClicked(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let splashVC = storyboard.instantiateViewController(withIdentifier: "splashVC")
self.present(splashVC, animated: true, completion: nil)
}
var circleLayer: CAShapeLayer? = nil
@IBAction func chatButtonTouchDown(_ sender: Any) {
if circleLayer == nil {
circleLayer = CAShapeLayer()
circleLayer?.path = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: chatButton.frame.size), cornerRadius: chatButton.frame.width / 2).cgPath
circleLayer?.lineWidth = 3
circleLayer?.fillColor = nil
circleLayer?.strokeColor = UIColor.green.cgColor
circleLayer?.strokeEnd = 0.0
CATransaction.setAnimationDuration(0.0)
circleLayer?.strokeEnd = 0.0
chatButton.layer.addSublayer(circleLayer!)
}
CATransaction.setAnimationDuration(1.0)
circleLayer?.strokeEnd = 1.0
UIView.animate(withDuration: 1.0) {
self.microphoneImage.alpha = 0.0
self.stopImage.alpha = 1.0
}
print("Touch Down")
}
@IBAction func chatButtonDragExit(_ sender: Any) {
CATransaction.setAnimationDuration(1.0)
circleLayer?.strokeEnd = 0.0
UIView.animate(withDuration: 1.0) {
self.microphoneImage.alpha = 1.0
self.stopImage.alpha = 0.0
}
print("Drag Exit")
}
@IBAction func chatButtonTouchUpInside(_ sender: Any) {
CATransaction.setAnimationDuration(1.0)
circleLayer?.strokeEnd = 0.0
UIView.animate(withDuration: 1.0) {
self.microphoneImage.alpha = 1.0
self.stopImage.alpha = 0.0
}
print("Touch Up Inside")
}
}
| apache-2.0 | 97372886e4ddde0853f436b5b3179ab1 | 31.923077 | 165 | 0.642523 | 4.58104 | false | false | false | false |
tiagomartinho/webhose-cocoa | webhose-cocoa/Pods/Quick/Sources/Quick/DSL/World+DSL.swift | 45 | 7844 | import Foundation
/**
Adds methods to World to support top-level DSL functions (Swift) and
macros (Objective-C). These functions map directly to the DSL that test
writers use in their specs.
*/
extension World {
internal func beforeSuite(_ closure: @escaping BeforeSuiteClosure) {
suiteHooks.appendBefore(closure)
}
internal func afterSuite(_ closure: @escaping AfterSuiteClosure) {
suiteHooks.appendAfter(closure)
}
internal func sharedExamples(_ name: String, closure: @escaping SharedExampleClosure) {
registerSharedExample(name, closure: closure)
}
internal func describe(_ description: String, flags: FilterFlags, closure: () -> Void) {
guard currentExampleMetadata == nil else {
raiseError("'describe' cannot be used inside '\(currentPhase)', 'describe' may only be used inside 'context' or 'describe'. ")
}
guard currentExampleGroup != nil else {
raiseError("Error: example group was not created by its parent QuickSpec spec. Check that describe() or context() was used in QuickSpec.spec() and not a more general context (i.e. an XCTestCase test)")
}
let group = ExampleGroup(description: description, flags: flags)
currentExampleGroup.appendExampleGroup(group)
performWithCurrentExampleGroup(group, closure: closure)
}
internal func context(_ description: String, flags: FilterFlags, closure: () -> Void) {
guard currentExampleMetadata == nil else {
raiseError("'context' cannot be used inside '\(currentPhase)', 'context' may only be used inside 'context' or 'describe'. ")
}
self.describe(description, flags: flags, closure: closure)
}
internal func fdescribe(_ description: String, flags: FilterFlags, closure: () -> Void) {
var focusedFlags = flags
focusedFlags[Filter.focused] = true
self.describe(description, flags: focusedFlags, closure: closure)
}
internal func xdescribe(_ description: String, flags: FilterFlags, closure: () -> Void) {
var pendingFlags = flags
pendingFlags[Filter.pending] = true
self.describe(description, flags: pendingFlags, closure: closure)
}
internal func beforeEach(_ closure: @escaping BeforeExampleClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'. ")
}
currentExampleGroup.hooks.appendBefore(closure)
}
#if _runtime(_ObjC)
@objc(beforeEachWithMetadata:)
internal func beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) {
currentExampleGroup.hooks.appendBefore(closure)
}
#else
internal func beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) {
currentExampleGroup.hooks.appendBefore(closure)
}
#endif
internal func afterEach(_ closure: @escaping AfterExampleClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'. ")
}
currentExampleGroup.hooks.appendAfter(closure)
}
#if _runtime(_ObjC)
@objc(afterEachWithMetadata:)
internal func afterEach(closure: @escaping AfterExampleWithMetadataClosure) {
currentExampleGroup.hooks.appendAfter(closure)
}
#else
internal func afterEach(closure: @escaping AfterExampleWithMetadataClosure) {
currentExampleGroup.hooks.appendAfter(closure)
}
#endif
internal func it(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
if beforesCurrentlyExecuting {
raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'. ")
}
if aftersCurrentlyExecuting {
raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'. ")
}
guard currentExampleMetadata == nil else {
raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'. ")
}
let callsite = Callsite(file: file, line: line)
let example = Example(description: description, callsite: callsite, flags: flags, closure: closure)
currentExampleGroup.appendExample(example)
}
internal func fit(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
var focusedFlags = flags
focusedFlags[Filter.focused] = true
self.it(description, flags: focusedFlags, file: file, line: line, closure: closure)
}
internal func xit(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
var pendingFlags = flags
pendingFlags[Filter.pending] = true
self.it(description, flags: pendingFlags, file: file, line: line, closure: closure)
}
internal func itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, flags: FilterFlags, file: String, line: UInt) {
guard currentExampleMetadata == nil else {
raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'. ")
}
let callsite = Callsite(file: file, line: line)
let closure = World.sharedWorld.sharedExample(name)
let group = ExampleGroup(description: name, flags: flags)
currentExampleGroup.appendExampleGroup(group)
performWithCurrentExampleGroup(group) {
closure(sharedExampleContext)
}
group.walkDownExamples { (example: Example) in
example.isSharedExample = true
example.callsite = callsite
}
}
internal func fitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, flags: FilterFlags, file: String, line: UInt) {
var focusedFlags = flags
focusedFlags[Filter.focused] = true
self.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: focusedFlags, file: file, line: line)
}
#if _runtime(_ObjC)
@objc(itWithDescription:flags:file:line:closure:)
private func objc_it(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
it(description, flags: flags, file: file, line: line, closure: closure)
}
@objc(fitWithDescription:flags:file:line:closure:)
private func objc_fit(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
fit(description, flags: flags, file: file, line: line, closure: closure)
}
@objc(xitWithDescription:flags:file:line:closure:)
private func objc_xit(_ description: String, flags: FilterFlags, file: String, line: UInt, closure: @escaping () -> Void) {
xit(description, flags: flags, file: file, line: line, closure: closure)
}
@objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:flags:file:line:)
private func objc_itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, flags: FilterFlags, file: String, line: UInt) {
itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: flags, file: file, line: line)
}
#endif
internal func pending(_ description: String, closure: () -> Void) {
print("Pending: \(description)")
}
private var currentPhase: String {
if beforesCurrentlyExecuting {
return "beforeEach"
} else if aftersCurrentlyExecuting {
return "afterEach"
}
return "it"
}
}
| mit | 8ae1aa040ff5209e937a1ca3accf800a | 43.822857 | 213 | 0.67899 | 4.797554 | false | false | false | false |
whiteath/ReadFoundationSource | Foundation/Bridging.swift | 10 | 4445 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
// Support protocols for casting
public protocol _ObjectBridgeable {
func _bridgeToAnyObject() -> AnyObject
}
public protocol _StructBridgeable {
func _bridgeToAny() -> Any
}
/// - Note: This is a similar interface to the _ObjectiveCBridgeable protocol
public protocol _ObjectTypeBridgeable : _ObjectBridgeable {
associatedtype _ObjectType : AnyObject
func _bridgeToObjectiveC() -> _ObjectType
static func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Self?)
@discardableResult
static func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Self?) -> Bool
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Self
}
/// - Note: This does not exist currently on Darwin but it is the inverse correlation to the bridge types such that a
/// reference type can be converted via a callout to a conversion method.
public protocol _StructTypeBridgeable : _StructBridgeable {
associatedtype _StructType
func _bridgeToSwift() -> _StructType
}
// Default adoption of the type specific variants to the Any variant
extension _ObjectTypeBridgeable {
public func _bridgeToAnyObject() -> AnyObject {
return _bridgeToObjectiveC()
}
}
extension _StructTypeBridgeable {
public func _bridgeToAny() -> Any {
return _bridgeToSwift()
}
}
// slated for removal, these are the swift-corelibs-only variant of the _ObjectiveCBridgeable
internal protocol _CFBridgeable {
associatedtype CFType
var _cfObject: CFType { get }
}
internal protocol _SwiftBridgeable {
associatedtype SwiftType
var _swiftObject: SwiftType { get }
}
internal protocol _NSBridgeable {
associatedtype NSType
var _nsObject: NSType { get }
}
/// - Note: This is an internal boxing value for containing abstract structures
internal final class _SwiftValue : NSObject, NSCopying {
internal private(set) var value: Any
static func fetch(_ object: AnyObject?) -> Any? {
if let obj = object {
return fetch(nonOptional: obj)
}
return nil
}
static func fetch(nonOptional object: AnyObject) -> Any {
if object === kCFBooleanTrue {
return true
} else if object === kCFBooleanFalse {
return false
} else if let container = object as? _SwiftValue {
return container.value
} else if let val = object as? _StructBridgeable {
return val._bridgeToAny()
} else {
return object
}
}
static func store(_ value: Any?) -> NSObject? {
if let val = value {
return store(val)
}
return nil
}
static func store(_ value: Any) -> NSObject {
if let val = value as? NSObject {
return val
} else if let val = value as? _ObjectBridgeable {
return val._bridgeToAnyObject() as! NSObject
} else {
return _SwiftValue(value)
}
}
init(_ value: Any) {
self.value = value
}
override var hash: Int {
if let hashable = value as? AnyHashable {
return hashable.hashValue
}
return ObjectIdentifier(self).hashValue
}
override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as _SwiftValue:
guard let left = other.value as? AnyHashable,
let right = self.value as? AnyHashable else { return self === other }
return left == right
case let other as AnyHashable:
guard let hashable = self.value as? AnyHashable else { return false }
return other == hashable
default:
return false
}
}
public func copy(with zone: NSZone?) -> Any {
return _SwiftValue(value)
}
}
| apache-2.0 | 9edf9c9536f430b5954a0cd17fdbace0 | 29.238095 | 118 | 0.613048 | 5.144676 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Components/NetworkConditionHelper.swift | 1 | 2759 | // Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import CoreTelephony
import WireSyncEngine
enum NetworkQualityType: Int, Comparable {
case unknown = 0
case type2G
case type3G
case type4G
case typeWifi
static func < (lhs: NetworkQualityType, rhs: NetworkQualityType) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
final class NetworkConditionHelper {
static var shared: NetworkConditionHelper = {
return NetworkConditionHelper()
}()
let networkInfo: CTTelephonyNetworkInfo
init() {
networkInfo = CTTelephonyNetworkInfo()
}
func qualityType() -> NetworkQualityType {
let serverConnection = SessionManager.shared?.serverConnection
if serverConnection?.isOffline == true {
return .unknown
} else if serverConnection?.isMobileConnection == false {
return .typeWifi
}
return bestQualityType(cellularTypeDict: networkInfo.serviceCurrentRadioAccessTechnology)
}
func bestQualityType(cellularTypeDict: [String: String]?) -> NetworkQualityType {
guard let cellularTypeDict = cellularTypeDict else { return .unknown }
return cellularTypeDict.values.map { cellularTypeString in
self.qualityType(from: cellularTypeString)}.sorted().last ?? .unknown
}
private func qualityType(from cellularTypeString: String?) -> NetworkQualityType {
switch cellularTypeString {
case CTRadioAccessTechnologyGPRS,
CTRadioAccessTechnologyEdge,
CTRadioAccessTechnologyCDMA1x:
return .type2G
case CTRadioAccessTechnologyWCDMA,
CTRadioAccessTechnologyHSDPA,
CTRadioAccessTechnologyHSUPA,
CTRadioAccessTechnologyCDMAEVDORev0,
CTRadioAccessTechnologyCDMAEVDORevA,
CTRadioAccessTechnologyCDMAEVDORevB,
CTRadioAccessTechnologyeHRPD:
return .type3G
case CTRadioAccessTechnologyLTE:
return .type4G
default:
return .unknown
}
}
}
| gpl-3.0 | 0513fde741edcf9f24f4638bd315e135 | 30 | 97 | 0.68938 | 4.971171 | false | false | false | false |
phuc0302/swift-data | FwiData/org/monstergroup/lib/Services/FwiService.swift | 1 | 11141 | // Project name: FwiData
// File name : FwiService.swift
//
// Author : Phuc, Tran Huu
// Created date: 1/15/15
// Version : 1.00
// --------------------------------------------------------------
// Copyright (c) 2015 Monster Group. All rights reserved.
// --------------------------------------------------------------
import Foundation
import UIKit
import FwiCore
public class FwiService : FwiOperation, NSURLConnectionDelegate, NSURLConnectionDataDelegate {
// MARK: Class's constructors
public override init() {
super.init()
}
// MARK: Class's properties
private var req: NSURLRequest?
private var con: NSURLConnection?
private var res: NSHTTPURLResponse?
// Network
private var error: NSError?
private var timer: NSTimer?
private var statusCode: Int32 = -1
// File Handler
private var path: String! = nil
private var output: NSFileHandle! = nil
// MARK: Class's public methods
public override func businessLogic() {
if let tempDir = NSTemporaryDirectory(), identifier = String.randomIdentifier(), request = req {
if let customRequest = request as? FwiRequest {
customRequest.prepare()
}
// Prepare data buffer
path = "\(tempDir)\(identifier)"
// Start process
var runLoop = NSRunLoop.currentRunLoop();
// Initialize connection
con = NSURLConnection(request: request, delegate: self, startImmediately: true)
con?.scheduleInRunLoop(runLoop, forMode: NSDefaultRunLoopMode)
// Initialize timer
if self.isLongOperation != true {
timer = NSTimer(timeInterval: request.timeoutInterval, target: self, selector: Selector("cancel"), userInfo: nil, repeats: false)
runLoop.addTimer(timer!, forMode: NSDefaultRunLoopMode)
}
// Open network connection
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
con?.start()
runLoop.run()
// Print out error if available
if let err = error {
var errorMessage = "HTTP Url : \(request.URL)\n"
errorMessage += "HTTP Method: \(request.HTTPMethod)\n"
errorMessage += "HTTP Status: \(statusCode) (\(err.localizedDescription))\n"
errorMessage += "\(String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil))"
println("[FwiService] Transfer Error:\n\(errorMessage)")
}
}
else {
println("[FwiService] Execute business error: Could not locate temporary folder or could not generate identifier or URL request is invalid.")
return
}
}
public override func cancel() {
self.shutdownConnection()
// Define error
statusCode = NetworkStatus_Cancelled
if let url = req?.URL {
var info: [NSObject : AnyObject] = [NSURLErrorFailingURLErrorKey:url.description,
NSURLErrorFailingURLStringErrorKey:url.description,
NSLocalizedDescriptionKey:NSHTTPURLResponse.localizedStringForStatusCode(Int(statusCode))]
error = NSError(domain: NSURLErrorDomain, code: Int(statusCode), userInfo: info)
}
else {
var info: [NSObject : AnyObject] = [NSURLErrorFailingURLErrorKey:"",
NSURLErrorFailingURLStringErrorKey:"",
NSLocalizedDescriptionKey:NSHTTPURLResponse.localizedStringForStatusCode(Int(statusCode))]
error = NSError(domain: NSURLErrorDomain, code: Int(statusCode), userInfo: info)
}
super.cancel()
}
/** Execute with completion blocks. */
public func sendRequestWithCompletion(completion: ((locationPath: NSURL?, error: NSError?, statusCode: Int32) -> Void)?) {
super.executeWithCompletion({ () -> Void in
/* Condition validation: Only generate temp url when status is success */
var locationPath: NSURL? = nil
if FwiNetworkStatusIsSuccces(self.statusCode) {
locationPath = NSURL(fileURLWithPath: self.path)
}
// Return result to client
if let completionBlock = completion {
completionBlock(locationPath: locationPath, error: self.error, statusCode: self.statusCode)
}
// Delete data
var manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath(self.path) {
manager.removeItemAtPath(self.path, error: nil)
}
})
}
// MARK: Class's private methods
private func shutdownConnection() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false;
if output != nil {
output?.closeFile()
}
if timer != nil {
timer?.invalidate()
}
if con != nil {
con?.cancel()
}
}
// MARK: NSURLConnectionDelegate's members
public func connection(connection: NSURLConnection, didFailWithError error: NSError) {
self.shutdownConnection()
self.error = error
statusCode = Int32(error.code)
}
public func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
FwiLog("\(challenge.protectionSpace.authenticationMethod)")
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
var serverTrust = challenge.protectionSpace.serverTrust
var certificate = SecTrustGetCertificateAtIndex(serverTrust, 0).takeUnretainedValue() as SecCertificateRef
// Ask delegate
var shouldAllow: Bool? = false
if let serviceDelegate = self.delegate as? FwiServiceDelegate {
shouldAllow = serviceDelegate.serviceRequireAuthenticationChallenge?(self, certificate: certificate)
}
// Create storage if neccessary
if shouldAllow == false {
challenge.sender.cancelAuthenticationChallenge(challenge)
} else {
var credential = NSURLCredential(trust: serverTrust!)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
}
} else {
challenge.sender.cancelAuthenticationChallenge(challenge)
}
}
// MARK: NSURLConnectionDataDelegate's members
public func connection(connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {
if totalBytesWritten == totalBytesExpectedToWrite {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
else {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
}
public func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
res = response as? NSHTTPURLResponse
/* Condition validation: Validate response status */
if let status = res?.statusCode {
statusCode = Int32(status)
if !FwiNetworkStatusIsSuccces(statusCode) {
if let url = req?.URL {
var info: [NSObject : AnyObject] = [NSURLErrorFailingURLErrorKey:url.description,
NSURLErrorFailingURLStringErrorKey:url.description,
NSLocalizedDescriptionKey:NSHTTPURLResponse.localizedStringForStatusCode(Int(statusCode))]
error = NSError(domain: NSURLErrorDomain, code: Int(statusCode), userInfo: info)
}
else {
var info: [NSObject : AnyObject] = [NSURLErrorFailingURLErrorKey:"",
NSURLErrorFailingURLStringErrorKey:"",
NSLocalizedDescriptionKey:NSHTTPURLResponse.localizedStringForStatusCode(Int(statusCode))]
error = NSError(domain: NSURLErrorDomain, code: Int(statusCode), userInfo: info)
}
}
}
/* Condition validation: Validate content length */
var contentSize: Int = 4096
if let contentLength = res?.allHeaderFields["Content-Length"] as? String, length = contentLength.toInt() { // Try to obtain content length from response headers
contentSize = length
}
// Open output stream
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
output = NSFileHandle(forWritingAtPath: path)
// Notify delegate
if let serviceDelegate = self.delegate as? FwiServiceDelegate {
serviceDelegate.service?(self, totalBytesWillReceive: contentSize)
}
}
public func connection(connection: NSURLConnection, didReceiveData data: NSData) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
/* Condition validation */
if data.length == 0 {
return
}
output.writeData(data)
// Notify delegate
if let serviceDelegate = self.delegate as? FwiServiceDelegate {
serviceDelegate.service?(self, bytesReceived: data.length)
}
}
public func connectionDidFinishLoading(connection: NSURLConnection) {
self.shutdownConnection()
}
}
// Creation
public extension FwiService {
// MARK: Class's constructors
public convenience init(request: NSURLRequest) {
self.init()
self.req = request
}
// public class func serviceWithURL(url: NSURL) {
//
// }
// public class func serviceWithURL:(NSURL *)url method:(FwiMethodType)method;
// public class func serviceWithURL:(NSURL *)url method:(FwiMethodType)method requestMessage:(FwiJson *)requestMessage;
// public class func serviceWithURL:(NSURL *)url method:(FwiMethodType)method requestDictionary:(NSDictionary *)requestDictionary;
}
// Delegate
@objc
public protocol FwiServiceDelegate : FwiOperationDelegate {
/** Request authentication permission from delegate. */
optional func serviceRequireAuthenticationChallenge(service: FwiService, certificate cert: SecCertificateRef) -> Bool
/** Notify receive data process. */
optional func service(service: FwiService, totalBytesWillReceive totalBytes: Int)
optional func service(service: FwiService, bytesReceived bytes: Int)
} | lgpl-3.0 | af1e457aba4fe50a8537115349afedf2 | 39.516364 | 169 | 0.60964 | 5.973727 | false | false | false | false |
904388172/-TV | DouYuTV/DouYuTV/Classes/Home/View/MenuView.swift | 1 | 3380 | //
// MenuView.swift
// DouYuTV
//
// Created by GS on 2017/10/26.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class MenuView: UIView {
//MARK: - 定义属性
var groups: [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
//MARK: - 从xib中加载出来
override func awakeFromNib() {
super.awakeFromNib()
//xib方式注册cell
collectionView.register(UINib(nibName: "CollectionMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
//必须在这个方法里面布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
// 行间距
layout.minimumLineSpacing = 0
//item之间的间距
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
}
}
//MARK: - 从xib中快速创建的类方法
extension MenuView {
class func menuView() -> MenuView {
return Bundle.main.loadNibNamed("MenuView", owner: nil, options: nil)?.first as! MenuView
}
}
//MARK: - UICollectionView dataSource
extension MenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil {
return 0
}
let pageNum = (groups!.count - 1) / 8 + 1
if pageNum <= 1 {
pageControl.isHidden = true
} else {
//只显示两个
// pageNum = 2
//显示多个
pageControl.numberOfPages = pageNum
}
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! CollectionMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
//像里面的cell传递数据
private func setupCellDataWithCell(cell: CollectionMenuCell, indexPath: IndexPath) {
//0页:0~7
//1页:8~15
//2页:16~23
//1.取出起始位置,终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
//2.判断越界问题
if endIndex > (groups?.count)! - 1 {
endIndex = (groups?.count)! - 1
}
//3.取出数据,赋值给cell
cell.groups = Array(groups![startIndex...endIndex])
}
}
//MARK: - UICollectionView Delegate
extension MenuView: UICollectionViewDelegate {
//监听滚动
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//计算pageControl的currentIndex
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| mit | 0cbdf4fa74b2e0e4050939229ae562f5 | 24.878049 | 126 | 0.612001 | 4.934884 | false | false | false | false |
shrtlist/MCSessionP2P | MCSessionP2P/MCTestViewController.swift | 1 | 4106 | /*
* Copyright 2020 [email protected]
*
* 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 MultipeerConnectivity
import UIKit
/*!
@class MCTestViewController
@abstract
Presents peer connection states in a table view
*/
class MCTestViewController: UITableViewController {
let sessionController = SessionController()
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
sessionController.delegate = self
title = "MCSession: \(sessionController.displayName)"
}
// MARK: Deinitialization
deinit {
// Nil out delegate
sessionController.delegate = nil
}
// MARK: UITableViewDataSource protocol conformance
override func numberOfSections(in tableView: UITableView) -> Int {
// We have 3 sections in our grouped table view,
// one for each MCSessionState
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
// Each tableView section represents an MCSessionState
guard let sessionState = MCSessionState(rawValue: section) else { return rows }
switch sessionState {
case .connecting:
rows = sessionController.connectingPeers.count
case .connected:
rows = sessionController.connectedPeers.count
case .notConnected:
rows = sessionController.disconnectedPeers.count
@unknown default:
fatalError()
}
// Always show at least 1 row for each MCSessionState.
if rows < 1 {
rows = 1
}
return rows
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Each tableView section represents an MCSessionState
let sessionState = MCSessionState(rawValue: section)
return MCSession.stringForPeerConnectionState(sessionState!)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "None"
var peers: [MCPeerID]
// Each tableView section represents an MCSessionState
guard let sessionState = MCSessionState(rawValue: indexPath.section) else { return cell }
let peerIndex = indexPath.row
switch sessionState {
case .connecting:
peers = sessionController.connectingPeers
case .connected:
peers = sessionController.connectedPeers
case .notConnected:
peers = sessionController.disconnectedPeers
@unknown default:
fatalError()
}
if (peers.count > 0) && (peerIndex < peers.count) {
let peerID = peers[peerIndex]
cell.textLabel?.text = peerID.displayName
}
return cell
}
// MARK: UITableViewDelegate protocol conformance
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension MCTestViewController: SessionControllerDelegate {
func sessionDidChangeState() {
// Ensure UI updates occur on the main queue.
DispatchQueue.main.async(execute: { [weak self] in
self?.tableView.reloadData()
})
}
}
| apache-2.0 | 8d3032fb8adcec1b7328d77a26f95c69 | 29.414815 | 109 | 0.644666 | 5.511409 | false | false | false | false |
Yurssoft/QuickFile | QuickFile/Models/Data/Data Structs/YSFolder.swift | 1 | 893 | //
// YSFolderModel.swift
// YSGGP
//
// Created by Yurii Boiko on 1/3/17.
// Copyright © 2017 Yurii Boiko. All rights reserved.
//
import Foundation
struct YSFolder: Codable {
var folderName: String = ""
var folderID: String = ""
static func rootFolder() -> YSFolder {
var folder = YSFolder()
folder.folderID = "root"
folder.folderName = "Root"
return folder
}
static func searchFolder() -> YSFolder {
var folder = YSFolder()
folder.folderID = "search"
folder.folderName = "Search"
return folder
}
func toDictionary() -> [String: Any] {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try? encoder.encode(self)
let fileDictionary = YSNetworkResponseManager.convertToDictionary(from: data)
return fileDictionary
}
}
| mit | 4b35b65ab531a5ba55853cfe1f8bb755 | 25.235294 | 85 | 0.621076 | 4.247619 | false | false | false | false |
CardinalNow/CardinalDebugToolkit | Sources/Views/TableViewCells/DebugMenuInfoCell.swift | 1 | 2438 | //
// DebugMenuBaseCell.swift
// CardinalDebugToolkit
//
// Copyright (c) 2018 Cardinal Solutions (https://www.cardinalsolutions.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
class DebugMenuInfoCell: DebugMenuBaseCell {
public override var detailTextLabel: UILabel? {
return valueLabel
}
@IBOutlet var valueLabel: UILabel!
private var info: String?
private var shouldResetAfterCopy = false
// MARK: - lifecycle
override func prepareForReuse() {
super.prepareForReuse()
shouldResetAfterCopy = false
}
// MARK: - public methods
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected, let info = info {
UIPasteboard.general.string = info
valueLabel.text = "Copied"
shouldResetAfterCopy = true
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: {
self.resetAfterCopy()
})
}
}
func configure(withTitle title: String, info: String?) {
self.info = info
titleLabel.text = title
valueLabel.text = info
}
func resetAfterCopy() {
guard shouldResetAfterCopy else { return }
shouldResetAfterCopy = false
valueLabel.text = info
}
}
| mit | 198ba12df0d405079622bf19525c092d | 31.506667 | 84 | 0.686218 | 4.6 | false | false | false | false |
ronaldbroens/jenkinsapp | JenkinsApp/AppDelegate.swift | 1 | 4579 | //
// AppDelegate.swift
// JenkinsApp
//
// Created by Ronald Broens on 07/02/15.
// Copyright (c) 2015 Ronald Broens. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
// in AppDelegate.swift
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]?) -> Void)) {
print("test123")
print(userInfo!["value1"])
print(userInfo!["value2"])
// pass back values to Apple Watch
var retValues = Dictionary<String,String>()
retValues["Job1"] = "url1"
retValues["Job2"] = "url2"
retValues["Job10"] = "url1"
retValues["Job20"] = "url2"
reply(retValues)
}
/*func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
//var sizzel = JenkinsTestClass()
//sizzel.Test()
// retrieved parameters from Apple Watch
println(userInfo["value1"])
println(userInfo["value2"])
// pass back values to Apple Watch
var retValues = Dictionary<String,String>()
retValues["retVal1"] = "return Test 1"
retValues["retVal2"] = "return Test 2"
reply(retValues)
}*/
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| apache-2.0 | f5fbacc0ccc39a955a00dfc8d81ca253 | 43.892157 | 285 | 0.700371 | 5.738095 | false | false | false | false |
ali-zahedi/AZViewer | AZViewer/AZLoader.swift | 1 | 8764 | //
// AZLoader.swift
// AZViewer
//
// Created by Ali Zahedi on 1/20/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import Foundation
public class AZLoader: AZBaseView{
// MARK: Public
public static let shared = AZLoader()
public var isActive: Bool {
set{
if newValue != self._isActive {
self._isActive = newValue
}
}get{
return self._isActive
}
}
public var color: UIColor = AZStyle.shared.sectionLoaderColor
public var horizontalAlignment: AZHorizontalAlignment = .middle
// background color, alpha, corner radius
public var cornerRadius: CGFloat = AZStyle.shared.sectionLoaderCornerRadius
public var blurIsHidden: Bool = false
// MARK: Internal
// MARK: Private
fileprivate var parenView: UIView?
fileprivate var view: AZBaseView!
fileprivate var blurEffectView: UIVisualEffectView!
fileprivate var _isActive: Bool = false {
didSet{
if self._isActive {
self.startLoader()
}else{
self.endLoader()
}
}
}
// MARK: Override
override public init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Function
fileprivate func defaultInit(){
for v in [] as [UIView] {
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
// prepare view
self.prepareView()
// at the end
self.backgroundColor = self.style.sectionLoaderBlurBackgroundColor
self.alpha = self.style.sectionLoaderBlurAlpha
}
public func parent(parent: UIView){
self.parenView = parent
}
}
// prepare
extension AZLoader{
// view
fileprivate func prepareView(){
self.view = AZBaseView()
self.view.translatesAutoresizingMaskIntoConstraints = false
self.view.backgroundColor = self.backgroundColor
self.view.alpha = self.alpha
self.view.layer.cornerRadius = self.cornerRadius
// prepare blur effect
if self.blurIsHidden{
self.view.backgroundColor = UIColor.clear
}else{
self.prepareBlurEffect()
}
}
// blur effect
fileprivate func prepareBlurEffect(){
self.blurEffectView = UIVisualEffectView(effect: self.style.sectionLoaderBlurEffect)
self.blurEffectView.translatesAutoresizingMaskIntoConstraints = false
self.blurEffectView.layer.cornerRadius = self.cornerRadius
self.blurEffectView.clipsToBounds = true
self.view.addSubview(self.blurEffectView)
NSLayoutConstraint(item: self.blurEffectView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self.blurEffectView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self.blurEffectView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self.blurEffectView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0).isActive = true
self.blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
// animation
extension AZLoader{
// start loader
fileprivate func startLoader(){
// released last blur for use shared
self.prepareView()
var viewAppend: UIView!
var size: CGSize!
// find parent
if let v = self.parenView{
viewAppend = v
}else{
// find master view
guard let v: UIView = UIApplication.shared.keyWindow else{
NSLog("AZLoader can't find key window")
return
}
viewAppend = v
}
//
viewAppend.addSubview(self.view)
// find size
let minSize = min(viewAppend.bounds.width, viewAppend.bounds.height)
if minSize > 50 || minSize == 0 {
size = CGSize(width: 50, height: 50)
}else{
size = CGSize(width: minSize, height: minSize)
}
self.view.frame.size = size
// NSLayout
NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: viewAppend, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self.view, attribute: self.horizontalAlignment.attribute(), relatedBy: .equal, toItem: viewAppend, attribute: self.horizontalAlignment.attribute(), multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: self.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: size.height).isActive = true
NSLayoutConstraint(item: self.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: size.width).isActive = true
self.setUpAnimation(in: self.view.layer, size: size)
}
// end loader
fileprivate func endLoader(){
self.view.removeFromSuperview()
self.removeAnimation(sender: self.view)
}
// remove loader animation
fileprivate func removeAnimation(sender: UIView){
sender.layer.sublayers?.forEach({ $0.removeFromSuperlayer() })
}
// add loader animation
func setUpAnimation(in layer: CALayer, size: CGSize) {
let bigCircleSize: CGFloat = size.width
let smallCircleSize: CGFloat = size.width / 2
let longDuration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
circleOf(shape: .ringTwoHalfHorizontal,
duration: longDuration,
timingFunction: timingFunction,
layer: layer,
size: bigCircleSize,
color: color, reverse: false)
circleOf(shape: .ringTwoHalfVertical,
duration: longDuration,
timingFunction: timingFunction,
layer: layer,
size: smallCircleSize,
color: color, reverse: true)
}
// create animation for each circle
func createAnimationIn(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
if !reverse {
rotateAnimation.values = [0, Double.pi, 2 * Double.pi]
} else {
rotateAnimation.values = [0, -Double.pi, -2 * Double.pi]
}
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
return animation
}
// create animation
func circleOf(shape: AZIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) {
let circle = shape.layerWith(size: CGSize(width: size, height: size), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size) / 2,
y: (layer.bounds.size.height - size) / 2,
width: size,
height: size)
let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| apache-2.0 | ecf86b0f59694c9831ed16d7efbc2cf9 | 34.913934 | 224 | 0.616684 | 5.047811 | false | false | false | false |
PlutoMa/SwiftProjects | 018.Spotlight Search/SpotlightSearch/SpotlightSearch/ViewController.swift | 1 | 5969 | //
// ViewController.swift
// SpotlightSearch
//
// Created by Dareway on 2017/11/1.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
import CoreSpotlight
let notificationName = NSNotification.Name.init("receivedIdFromSpotlightSearch")
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView = UITableView(frame: CGRect.zero, style: .plain)
let dataSource: [[String : Any]] = [
["name" : "Dangal", "cover" : UIImage.init(named: "roasterDad")!, "description" : "This is a warm and humorous inspirational story. Maha Via Singh Pe (Amirkhan) was a India national wrestling champion, forced to give up wrestling because of life. He wants his son to help him achieve his dream - to win a world class gold medal. The results gave birth to four daughters thought this dream shattered Singer unexpectedly found her amazing talent on the body, see the champions hope he was determined not to let the talent waste daughter, like other girls can only cook over a lifetime, after consideration, agreed with his wife a year two daughters training according to the wrestler standard: replace the skirt, cut my hair, let them practice wrestling, and won a championship final to win the women the opportunity to become a model inspired thousands on thousands of.", "ranking" : 8.6],
["name" : "Guardians of the Galaxy", "cover" : UIImage.init(named: "GuardingStar")!, "description" : "The Galactic guards cross the universe in this focus, continuing epic adventures in outer space. They must fight together, protect each other, and unravel the mystery of the star Peter Quill. The old enemy became allies, and the favorite characters in the comics would show up and help the guards.Along with the 'second series of songs' the background music, the Milky Way convoy to the more distant cosmic star domain, while efforts to maintain this new family while not easily won, trying to uncover the mystery of the truth Peter Quel descent. In this journey, the enemies of the past will become allies of today, and the classic comic characters who are loved by fans will come to help our hero.", "ranking" : 7.9],
["name" : "Absurd Accident", "cover" : UIImage.init(named: "Absurd Accident")!, "description" : "Northeast, Yang million and his wife Ma Lilian runs 'Cyclamen hotel'. Yang Baiwan was not for middle-aged patients, but Ma Lilian is a sexy, bold tiger Yang Baiwan, low self-esteem, worried all day. Finally one day, Yang million that Ma Lilian was a cuckold for himself, angrily found a doctor after work, two people planning a revenge on Ma Lilian's plan... That night, the killer rujierzhi, two robbers and a couple of temporary but came to the hotel and a strange combination of circumstances, both involved in the event. The few unrelated people originally interacted with each other, making the already confusing situation even more surprising. Everyone has experienced a fearful experience in order to achieve his goal, and then a series of absurd and funny things happen. At the same time, their fortunes changed...", "ranking" : 7.0]
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = UIScreen.main.bounds
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
CSSearchableIndex.default().deleteAllSearchableItems { (error) in
if error != nil {
print("error--> \(error.debugDescription)")
} else {
print("delete all")
}
}
NotificationCenter.default.addObserver(self, selector: #selector(receivedIdFromSpotlightSearch(sender:)), name: notificationName, object: nil)
}
@objc
func receivedIdFromSpotlightSearch(sender: Notification) -> Void {
let indexPath = IndexPath.init(row: Int(sender.userInfo?["id"] as! String)!, section: 0)
tableView(tableView, didSelectRowAt: indexPath)
}
}
extension ViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell")
if cell == nil {
cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "reuseCell")
}
let dataDic = dataSource[indexPath.row]
cell?.textLabel?.text = dataDic["name"] as? String
cell?.imageView?.image = dataDic["cover"] as? UIImage
let attributSet = CSSearchableItemAttributeSet.init(itemContentType: "test")
attributSet.title = dataDic["name"] as? String
attributSet.contentDescription = dataDic["description"] as? String
let imageData = UIImageJPEGRepresentation(dataDic["cover"] as! UIImage, 0.7)
attributSet.thumbnailData = imageData
let searchItem = CSSearchableItem.init(uniqueIdentifier: String(indexPath.row), domainIdentifier: "Pluto", attributeSet: attributSet)
CSSearchableIndex.default().indexSearchableItems([searchItem]) { (error) in
if error != nil {
print("error--> \(error.debugDescription)")
}
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let detail = DetailViewController.init(data: dataSource[indexPath.row])
navigationController?.pushViewController(detail, animated: true)
}
}
| mit | 2b6ea205c4c330ad5e11560e73711a17 | 62.468085 | 946 | 0.708012 | 4.592764 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.