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
chriscox/material-components-ios
components/AppBar/examples/AppBarDelegateForwardingExample.swift
1
5283
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents // This example builds upon AppBarTypicalUseExample. class AppBarDelegateForwardingExample: UITableViewController { let appBar = MDCAppBar() convenience init() { self.init(style: .plain) } override init(style: UITableViewStyle) { super.init(style: style) self.appBar.navigationBar.tintColor = UIColor.white appBar.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white ] self.addChildViewController(appBar.headerViewController) self.title = "Delegate Forwarding" let color = UIColor(white: 0.1, alpha:1) appBar.headerViewController.headerView.backgroundColor = color appBar.navigationBar.tintColor = UIColor.white } override func viewDidLoad() { super.viewDidLoad() // UITableViewController's tableView.delegate is self by default. We're setting it here for // emphasis. self.tableView.delegate = self appBar.headerViewController.headerView.trackingScrollView = self.tableView appBar.addSubviewsToParent() self.tableView.layoutMargins = UIEdgeInsets.zero self.tableView.separatorInset = UIEdgeInsets.zero } // The following four methods must be forwarded to the tracking scroll view in order to implement // the Flexible Header's behavior. override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidScroll() } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidEndDecelerating() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset) } } // MARK: Typical setup override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Delegate Forwarding (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor( red: CGFloat(0x03) / CGFloat(255), green: CGFloat(0xA9) / CGFloat(255), blue: CGFloat(0xF4) / CGFloat(255), alpha: 1) appBar.headerViewController.headerView.backgroundColor = color appBar.navigationBar.tintColor = UIColor.white } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: Catalog by convention extension AppBarDelegateForwardingExample { class func catalogBreadcrumbs() -> [String] { return ["App Bar", "Delegate Forwarding (Swift)"] } func catalogShouldHideNavigation() -> Bool { return true } } extension AppBarDelegateForwardingExample { override var childViewControllerForStatusBarHidden: UIViewController? { return appBar.headerViewController } override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } } // MARK: - Typical application code (not Material-specific) // MARK: UITableViewDataSource extension AppBarDelegateForwardingExample { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell!.layoutMargins = UIEdgeInsets.zero return cell! } }
apache-2.0
19c4af1464cd9ae719179a8a3506004f
31.611111
99
0.732917
5.314889
false
false
false
false
Jnosh/SwiftBinaryHeapExperiments
BinaryHeap/ValElement.swift
1
1666
// // StructElement.swift // BinaryHeap // // Created by Janosch Hildebrand on 21/09/15. // Copyright © 2015 Janosch Hildebrand. All rights reserved. // import Foundation /// A small value type element public struct ValueElementSmall : Comparable { var value: Int public init(_ value: Int) { self.value = value } } public func ==(lhs: ValueElementSmall, rhs: ValueElementSmall) -> Bool { return lhs.value == rhs.value } public func <(lhs: ValueElementSmall, rhs: ValueElementSmall) -> Bool { return lhs.value < rhs.value } /// A medium value type element public struct ValueElementMedium : Comparable { var value: Int let padding_0 = 0 let padding_1 = 0 let padding_2 = 0 public init(_ value: Int) { self.value = value } } public func ==(lhs: ValueElementMedium, rhs: ValueElementMedium) -> Bool { return lhs.value == rhs.value } public func <(lhs: ValueElementMedium, rhs: ValueElementMedium) -> Bool { return lhs.value < rhs.value } /// A large value type element public struct ValueElementLarge : Comparable { var value: Int let padding_0 = 0 let padding_1 = 0 let padding_2 = 0 let padding_3 = 0 let padding_4 = 0 let padding_5 = 0 let padding_6 = 0 let padding_7 = 0 let padding_8 = 0 let padding_9 = 0 let padding_10 = 0 public init(_ value: Int) { self.value = value } } public func ==(lhs: ValueElementLarge, rhs: ValueElementLarge) -> Bool { return lhs.value == rhs.value } public func <(lhs: ValueElementLarge, rhs: ValueElementLarge) -> Bool { return lhs.value < rhs.value }
mit
083304ed3d2048b0678a4d0907ac603e
20.907895
74
0.641441
3.588362
false
false
false
false
apple/swift
test/Distributed/distributed_func_overloads.swift
2
2341
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ------------------------------------------------------------------------ distributed actor Overloader { func overloaded() {} func overloaded() async {} distributed func overloadedDistA() {} // expected-note{{ambiguous distributed func 'overloadedDistA()' declared here}} distributed func overloadedDistA() async {} // expected-error{{ambiguous distributed func declaration 'overloadedDistA()', cannot overload distributed methods on effect only}} distributed func overloadedDistT() throws {} // expected-note{{ambiguous distributed func 'overloadedDistT()' declared here}} distributed func overloadedDistT() async throws {} // expected-error{{ambiguous distributed func declaration 'overloadedDistT()', cannot overload distributed methods on effect only}} // Throws overloads are not legal anyway, but let's check for them here too: distributed func overloadedDistThrows() {} // expected-note@-1{{ambiguous distributed func 'overloadedDistThrows()' declared here}} // expected-note@-2{{'overloadedDistThrows()' previously declared here}} distributed func overloadedDistThrows() throws {} // expected-error@-1{{ambiguous distributed func declaration 'overloadedDistThrows()', cannot overload distributed methods on effect only}} // expected-error@-2{{invalid redeclaration of 'overloadedDistThrows()'}} distributed func overloadedDistAsync() async {} // expected-note@-1{{ambiguous distributed func 'overloadedDistAsync()' declared here}} // expected-note@-2{{'overloadedDistAsync()' previously declared here}} distributed func overloadedDistAsync() async throws {} // expected-error@-1{{ambiguous distributed func declaration 'overloadedDistAsync()', cannot overload distributed methods on effect only}} // expected-error@-2{{invalid redeclaration of 'overloadedDistAsync()'}} }
apache-2.0
2d71e86a6fecf1d57845c8091a261b7b
57.525
219
0.750534
5.16777
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/PinchDistortion.swift
9
528
public class PinchDistortion: BasicOperation { public var radius:Float = 1.0 { didSet { uniformSettings["radius"] = radius } } public var scale:Float = 0.5 { didSet { uniformSettings["scale"] = scale } } public var center:Position = Position.center { didSet { uniformSettings["center"] = center } } public init() { super.init(fragmentShader:PinchDistortionFragmentShader, numberOfInputs:1) ({radius = 1.0})() ({scale = 0.5})() ({center = Position.center})() } }
mit
978f929b8368b72355d71241c5c7b4c6
39.615385
98
0.623106
4.327869
false
false
false
false
tkremenek/swift
test/refactoring/ConvertAsync/async_attribute_added.swift
1
2550
// RUN: %empty-directory(%t) // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 -enable-experimental-concurrency | %FileCheck -check-prefix=SIMPLE %s func simple(completion: @escaping (String) -> Void) { } // SIMPLE: async_attribute_added.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1 // SIMPLE-NEXT: @available(*, deprecated, message: "Prefer async alternative instead") // SIMPLE-EMPTY: // SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-4]]:1 -> [[# @LINE-4]]:1 // SIMPLE-NEXT: @completionHandlerAsync("simple()", completionHandlerIndex: 0) // SIMPLE-EMPTY: // SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-7]]:53 -> [[# @LINE-7]]:56 // SIMPLE-NEXT: { // SIMPLE-NEXT: Task { // SIMPLE-NEXT: let result = await simple() // SIMPLE-NEXT: completion(result) // SIMPLE-NEXT: } // SIMPLE-NEXT: } // SIMPLE-EMPTY: // SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-15]]:56 -> [[# @LINE-15]]:56 // SIMPLE-EMPTY: // SIMPLE-EMPTY: // SIMPLE-EMPTY: // SIMPLE-NEXT: async_attribute_added.swift [[# @LINE-19]]:56 -> [[# @LINE-19]]:56 // SIMPLE-NEXT: func simple() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=OTHER-ARGS %s func otherArgs(first: Int, second: String, completion: @escaping (String) -> Void) { } // OTHER-ARGS: @completionHandlerAsync("otherArgs(first:second:)", completionHandlerIndex: 2) // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=EMPTY-NAMES %s func emptyNames(first: Int, _ second: String, completion: @escaping (String) -> Void) { } // EMPTY-NAMES: @completionHandlerAsync("emptyNames(first:_:)", completionHandlerIndex: 2) // Not a completion handler named parameter, but should still be converted // during function conversion since it has been attributed @completionHandlerAsync("otherName()", completionHandlerIndex: 0) func otherName(notHandlerName: @escaping (String) -> (Void)) {} func otherName() async -> String {} // RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):5 -enable-experimental-concurrency | %FileCheck -check-prefix=OTHER-CONVERTED %s func otherStillConverted() { otherName { str in print(str) } } // OTHER-CONVERTED: func otherStillConverted() async { // OTHER-CONVERTED-NEXT: let str = await otherName() // OTHER-CONVERTED-NEXT: print(str)
apache-2.0
17b7bf1d55b56ad9dde98c4945d368db
52.125
178
0.705098
3.459973
false
false
false
false
trident10/TDMediaPicker
Example/TDMediaPicker/Themes/Theme1.swift
1
4961
// // Theme1.swift // TDMediaPicker // // Created by abhimanyujindal10 on 07/19/2017. // Copyright (c) 2017 abhimanyujindal10. All rights reserved. // import Foundation import TDMediaPicker import Photos class Theme1: ThemeConfig{ override func getPermissionScreenConfig() -> TDConfigPermissionScreen { let configView = TDConfigViewStandard(backgroundColor: .lightGray) let permissionConfig = TDConfigPermissionScreen(standardView: configView) permissionConfig.settingButton = TDConfigButtonText.init(normalColor: UIColor(rgb: 0xD24D57), normalTextConfig: TDConfigText.init(text: "Open Settings", textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 18)), cornerRadius: 6.0) permissionConfig.cancelButton = TDConfigButtonImage.init(normalImage: UIImage.init(named: "close"), customSize: CGSize.init(width: 20, height: 20)) permissionConfig.caption = TDConfigLabel.init(backgroundColor: .clear, textConfig: TDConfigText.init(text: "Allow TDMedia Picker to access your photos.", textColor: UIColor(rgb: 0xF62459), textFont: UIFont.boldSystemFont(ofSize: 20)), textAlignment: .center, lineBreakMode: .byWordWrapping, minimumFontSize: 2.0) return permissionConfig } override func getNavigationThemeConfig() -> TDConfigViewStandard { return TDConfigViewStandard.init(backgroundColor: .lightGray) } override func getImageSizeForAlbum()->CGSize{ return CGSize(width: 90, height: 90) } override func getNumberOfColumnInPortrait()->Int{ return 5 } override func getNumberOfColumnInLandscape()->Int{ return 10 } override func getAlbumNavBarConfig()->TDConfigNavigationBar{ let configNavBar = TDConfigNavigationBar() configNavBar.backButton = TDConfigButtonText.init(normalColor: .clear, normalTextConfig: TDConfigText.init(text: "Back", textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 18)), cornerRadius: 6.0) configNavBar.otherButton = TDConfigButtonText.init(normalColor: .clear, normalTextConfig: TDConfigText.init(text: "Delete", textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 18)), cornerRadius: 6.0) let nextButton = TDConfigButtonText.init(normalColor: .clear, normalTextConfig: TDConfigText.init(text: "Next", textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 18)), cornerRadius: 6.0) nextButton.disabledTextConfig = TDConfigText.init(text: "Next", textColor: .darkGray, textFont: UIFont.boldSystemFont(ofSize: 18)) configNavBar.nextButton = nextButton configNavBar.screenTitle = TDConfigLabel.init(backgroundColor: nil, textConfig: TDConfigText.init(text: "Albums", textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 18))) configNavBar.navigationBarView = TDConfigViewStandard.init(backgroundColor: .lightGray) return configNavBar } override func getSelectedAlbumAtInitialLoad(albums: [TDAlbum])->TDAlbum?{ for album in albums{ if album.collection.localizedTitle == "Camera Roll"{ return album } } return nil } override func getTextFormatForAlbum(album: TDAlbum, mediaCount: Int)-> TDConfigText{ return TDConfigText.init(text: String(format: "%@\n\n%d",album.collection.localizedTitle!,mediaCount), textColor: .black, textFont: UIFont.systemFont(ofSize: 16)) } override func getMediaHighlightedCellView(mediaCount: Int)->TDConfigView{ return TDConfigViewStandard(backgroundColor: .red) } override func getIsHideCaptionView() -> Bool { return false } override func getMaxNumberOfSelection() -> Int { return 1 } override func getVideoThumbOverlay() -> TDConfigView { let myView: VideoThumbCellView = .fromNib() myView.imageView.image = #imageLiteral(resourceName: "video_thumb") myView.bottomView.backgroundColor = .init(white: 1, alpha: 0.8) return TDConfigViewCustom.init(view: myView) } override func getSelectedThumbnailView() -> TDConfigView { let myView: HightLightedCellView = .fromNib() myView.countLabel.isHidden = true return TDConfigViewCustom.init(view: myView) } override func getPreviewThumbnailAddView() -> TDConfigView { let myView: HightLightedCellView = .fromNib() myView.backgroundColor = .clear myView.countLabel.isHidden = true myView.imageView.image = #imageLiteral(resourceName: "add") return TDConfigViewCustom.init(view: myView) } override func getFetchResultsForAlbumScreen() -> [PHFetchResult<PHAssetCollection>] { let types: [PHAssetCollectionType] = [.smartAlbum, .album] return types.map { return PHAssetCollection.fetchAssetCollections(with: $0, subtype: .any, options: nil) } } }
mit
adebbedd0b41d0331398bea4f79889b1
44.513761
320
0.704495
4.614884
false
true
false
false
CharlesVu/Smart-iPad
MKHome/UK/UK - National Rail/NationalRailViewController.swift
1
5496
// // NationalRailViewController.swift // MKHome // // Created by Charles Vu on 06/06/2019. // Copyright © 2019 charles. All rights reserved. // import Foundation import UIKit import Persistance import HuxleySwift class NationalRailViewViewController: UIViewController { fileprivate let userSettings = UserSettings.sharedInstance fileprivate let appSettings = NationalRail.AppData.sharedInstance @IBOutlet weak var tableView: UITableView? @IBOutlet weak var trainDestinationLabel: UILabel? fileprivate var departures: [Journey: HuxleySwift.Departures] = [:] fileprivate var currentJourneyIndex = -1 override func viewDidLoad() { refreshTrains() Timer.every(1.minutes) { self.refreshTrains() } } override func viewWillAppear(_ animated: Bool) { Timer.every(15.seconds) { self.displayNextTrainJourney() } } func refreshTrains() { if userSettings.rail.getJourneys().count > 0 { for journey in userSettings.rail.getJourneys() { NationalRail.TrainInteractor().getTrains(from: journey.originCRS, to: journey.destinationCRS) { departures in self.departures[journey] = departures if self.currentJourneyIndex == -1 { self.displayNextTrainJourney() } DispatchQueue.main.async { self.tableView?.reloadData() } } } } } func displayNextTrainJourney() { if userSettings.rail.getJourneys().count != 0 { currentJourneyIndex = (currentJourneyIndex + 1) % userSettings.rail.getJourneys().count let journey = userSettings.rail.getJourneys()[currentJourneyIndex] if let source = appSettings.stationMap[journey.originCRS], let destination = appSettings.stationMap[journey.destinationCRS] { let attributedSource = NSMutableAttributedString(string: source.stationName, attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "normalText")!]) let attributedDestination = NSAttributedString(string: destination.stationName, attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "normalText")!]) attributedSource.append(NSAttributedString(string: " → ", attributes: [NSAttributedString.Key.foregroundColor: UIColor(named: "alternativeText")!])) attributedSource.append(attributedDestination) trainDestinationLabel?.attributedText = attributedSource } } self.tableView?.reloadData() } } extension NationalRailViewViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if currentJourneyIndex == -1 { return 0 } let currentJourney = userSettings.rail.getJourneys()[currentJourneyIndex] return departures[currentJourney]?.trainServices.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currentJourney = userSettings.rail.getJourneys()[currentJourneyIndex] let service = departures[currentJourney]!.trainServices[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "TrainCell") as! TrainCell cell.arivalTime?.text = "Leaving at " + service.std! + " (\(Int(service.getJourneyDuration(toStationCRS: currentJourney.destinationCRS) / 60)) min)" if service.etd == "On time" || service.etd == service.std { cell.delay?.text = "On time" cell.delay?.textColor = UIColor(named: "positiveText") } else if service.etd == "Delayed" || service.etd == "Cancelled" { cell.delay?.text = service.etd cell.delay?.textColor = UIColor(named: "errorText") cell.arivalTime?.textColor = UIColor(named: "errorText") } else { cell.delay?.text = "(\(Int(service.delay / 60)) min)" cell.delay?.textColor = UIColor(named: "warningText") } cell.backgroundColor = UIColor.clear if UIDevice.current.userInterfaceIdiom == .pad { cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = .zero cell.separatorInset = .zero } if let platform = service.platform { cell.platform?.text = "Platform \(platform)" cell.platform?.textColor = UIColor(named: "alternativeText") } else { cell.platform?.textColor = UIColor(named: "warningText") cell.platform?.text = "Platform unknown" } cell.operatorImage?.image = UIImage(named: service.operatorCode!, in: nil, compatibleWith: nil) return cell } }
mit
0acca38d6e00dc0ee4dc936db3cec4ea
41.581395
156
0.573821
5.374755
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/TakeOrder/器械信息/View/Cell/MaterialCheckTableViewCell.swift
1
6216
// // MaterialCheckTableViewCell.swift // OMS-WH // // Created by xuech on 2017/10/19. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD protocol MaterialCheckTableViewCellDelegate { func editMetTableViewCell(cell:UITableViewCell,modifiedModel:MedMaterialList) } class MaterialCheckTableViewCell: UITableViewCell { @IBOutlet weak var reqLabel: UILabel! @IBOutlet weak var whLable: UILabel! @IBOutlet weak var materialName: UILabel! @IBOutlet weak var materialCode: UILabel! @IBOutlet weak var materialRule: UILabel! @IBOutlet weak var materialType: UILabel! @IBOutlet weak var stepper: StepperSwift! @IBOutlet weak var inventoryCount: UILabel! @IBOutlet weak var whNameBtn: UIButton! var delegate :MaterialCheckTableViewCellDelegate? fileprivate var modifiedModel : MedMaterialList? // fileprivate var oiWhRelModel : [OIWhRelModel] = [OIWhRelModel]() fileprivate var viewM : MeterialViewModel = MeterialViewModel() override func awakeFromNib() { super.awakeFromNib() } ///高亮提示 func higherLightColor(by inventory:Bool) { if inventory { reqLabel.textColor = .red whLable.textColor = .red materialName.textColor = .red materialCode.textColor = .red materialRule.textColor = .red materialType.textColor = .red inventoryCount.textColor = .red whNameBtn.setTitleColor(.red, for: UIControlState.normal) }else{ reqLabel.textColor = .black whLable.textColor = .black materialName.textColor = .black materialCode.textColor = .black materialRule.textColor = .black materialType.textColor = .black inventoryCount.textColor = .black whNameBtn.setTitleColor(kAppearanceColor, for: UIControlState.normal) } } ///显示cell数据 func configMetailData(medMaterialList:MedMaterialList?,relModel:[OIWhRelModel]) { guard let medList = medMaterialList else { return } modifiedModel = medList materialName.text = "名称:\(medList.medMIName)" materialCode.text = "编码:\(medList.medMICode)" materialRule.text = "规格:\(medList.specification)" materialType.text = "类型:\(medList.categoryByPlatformName)" stepper.value = Double(truncating: medList.reqQty) stepper.addTarget(self, action: #selector(stepperValueChanged), for: .valueChanged) whNameBtn.setTitle(modifiedModel?.wHName ?? "", for: UIControlState.normal) // guard let defaultWarehouse = oiWhRelModel.filter({$0.isDefaultWarehouse == "Y"}).first else { return } // whNameBtn.setTitle(defaultWarehouse.wHName, for: UIControlState.normal) refreshInventory(inventory: medList.inventory) if medList.shouldHighLight { higherLightColor(by: true) }else{ higherLightColor(by: false) } //如果未修改的话直接返回原结果 // modifiedModel?.wHName = defaultWarehouse.wHName // modifiedModel?.estMedMIWarehouse = defaultWarehouse.medMIWarehouse } ///数量的增减 @objc func stepperValueChanged(stepper: StepperSwift) { modifiedModel?.reqQty = NSNumber(value:stepper.value) let inventory = modifiedModel?.inventory ?? 0 if Int(stepper.value) > Int(truncating: inventory) { higherLightColor(by: true) modifiedModel?.shouldHighLight = true }else{ higherLightColor(by: false) modifiedModel?.shouldHighLight = false } delegate?.editMetTableViewCell(cell: self, modifiedModel: modifiedModel!) } @IBAction func whoursEvent(_ sender: UIButton) { guard let oiWhRel = modifiedModel?.oiWhRel else { return } let menuOptionNameArray = oiWhRel.map({$0.wHName}) FTConfiguration.shared.menuWidth = 250 FTPopOverMenu.showForSender(sender: sender, with: menuOptionNameArray, done: { (selectedIndex) in let oiWhRelModel = oiWhRel[selectedIndex] self.modifiedModel?.wHName = oiWhRelModel.wHName self.modifiedModel?.estMedMIWarehouse = oiWhRelModel.medMIWarehouse ///1、显示选中的仓库 self.whNameBtn.setTitle(oiWhRelModel.wHName, for: UIControlState.normal) ///2、根据仓库去请求库存信息 self.queryMedMaterialInventory(with: oiWhRelModel.medMIWarehouse) }) { print("cancel") } } fileprivate func queryMedMaterialInventory(with medMIWarehouse:String) { guard var oIOrgCode = modifiedModel?.oIOrgCode else { return } if oIOrgCode.isBlank { oIOrgCode = modifiedModel?.sOOIOrgCode ?? "" } guard let medMIInternalNo = modifiedModel?.medMIInternalNo else { return } let params = ["oIOrgCode": oIOrgCode, "medMIInternalNo": medMIInternalNo, "medMIWarehouse": medMIWarehouse] let sd = ["jsonArray":[params]] viewM.queryMedMaterialInventory(paramters: sd) { (result, error) in if result.count > 0 { if let inventory = result.first?.inventory { if Int(self.stepper.value) > Int(truncating: inventory) || Int(truncating: inventory) == 0{ SVProgressHUD.showError("库存不足") self.higherLightColor(by: true) self.modifiedModel?.shouldHighLight = true }else{ self.higherLightColor(by: false) self.modifiedModel?.shouldHighLight = false } self.modifiedModel?.inventory = inventory self.delegate?.editMetTableViewCell(cell: self, modifiedModel: self.modifiedModel!) self.refreshInventory(inventory: inventory) } } } } func refreshInventory(inventory:NSNumber){ inventoryCount.text = "库存:\(inventory)" } }
mit
0c2c5aad0f62347c00ebfeefe04bdcc3
39.553333
115
0.636199
4.479381
false
false
false
false
art-divin/mester-client-ios
Mester/UI/cells/StepCell.swift
1
5097
// // StepCell.swift // Mester // // Created by Ruslan Alikhamov on 23/01/15. // Copyright (c) 2015 Ruslan Alikhamov. All rights reserved. // import UIKit class StepCell: UITableViewCell { var succeedCallback: ((AnyObject) -> Void)? var failCallback: ((AnyObject) -> Void)? weak var object: AnyObject? var buttonFail: UIButton = UIButton() var buttonSucceed: UIButton = UIButton() var textLbl: UILabel = UILabel() var statusLbl: UILabel = UILabel() private var swiperView: SwiperView? override func awakeFromNib() { super.awakeFromNib() swiperView = SwiperView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), leftInset: -95, rightInset: -95) let separatorView = UIView() separatorView.backgroundColor = ThemeDefault.colorForTint() self.contentView.addSubview(separatorView) self.contentView.addSubview(swiperView!) separatorView.translatesAutoresizingMaskIntoConstraints = false swiperView!.translatesAutoresizingMaskIntoConstraints = false self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[swiper]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "swiper" : swiperView! ])) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[swiper][sepView(==1)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "swiper" : swiperView!, "sepView" : separatorView ])) self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[sepView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "sepView" : separatorView ])) self.contentView.bringSubviewToFront(swiperView!) textLbl.numberOfLines = 0; textLbl.lineBreakMode = .ByWordWrapping textLbl.translatesAutoresizingMaskIntoConstraints = false swiperView!.topmostView().addSubview(textLbl) swiperView!.topmostView().addSubview(statusLbl) statusLbl.translatesAutoresizingMaskIntoConstraints = false textLbl.translatesAutoresizingMaskIntoConstraints = false var constraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label][statusLbl]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "label" : textLbl, "statusLbl" : statusLbl ]) as [NSLayoutConstraint] constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "label" : textLbl ]) as [NSLayoutConstraint] constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[statusLbl]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "statusLbl" : statusLbl ]) as [NSLayoutConstraint] swiperView!.topmostView().addConstraints(constraints) buttonSucceed.setTitleColor(ThemeDefault.colorForButtonTitle(.Success), forState: .Normal) buttonFail.setTitleColor(ThemeDefault.colorForButtonTitle(.Failure), forState: .Normal) buttonSucceed.backgroundColor = ThemeDefault.colorForButtonBg(.Success) buttonFail.backgroundColor = ThemeDefault.colorForButtonBg(.Failure) swiperView!.addSubview(buttonSucceed); swiperView!.addSubview(buttonFail); buttonSucceed.translatesAutoresizingMaskIntoConstraints = false buttonFail.translatesAutoresizingMaskIntoConstraints = false swiperView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[succ(>=100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "succ" : buttonSucceed ])) swiperView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[fail(>=100)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "fail" : buttonFail ])) swiperView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "button" : buttonFail ])) swiperView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "button" : buttonSucceed ])) swiperView?.leftCallback = { [weak self] in if let callback = self?.succeedCallback { if let object: AnyObject = self?.object { callback(object) } } } swiperView?.rightCallback = { [weak self] in if let callback = self?.failCallback { if let object: AnyObject = self?.object { callback(object) } } } } override func layoutSubviews() { super.layoutSubviews() let frame = self.contentView.bounds swiperView?.frame = CGRectMake(CGRectGetMinX(frame), CGRectGetMinY(frame), CGRectGetWidth(frame), CGRectGetHeight(frame) - 1) } func setButtonVisibility(visible: Bool) { self.buttonFail.hidden = !visible self.buttonSucceed.hidden = !visible self.swiperView?.hidden = !visible; } override func prepareForReuse() { self.succeedCallback = nil self.failCallback = nil self.object = nil self.textLbl.text = "" self.statusLbl.text = "" } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
241f91ef84013e65c629e9fcf1854931
49.97
252
0.758878
4.467134
false
false
false
false
Piwigo/Piwigo-Mobile
piwigoKit/Data Cache/DataController.swift
1
18264
// // DataController.swift // piwigoKit // // Created by Eddy Lelièvre-Berna on 17/02/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // import Foundation import CoreData public class DataController: NSObject { // MARK: - Core Data stack // "Library/Application Support/Piwigo" inside the group container. /// - The shared database and temporary files to upload are stored in the App Group /// container so that they can be used and shared by the app and the extensions. public static var appGroupDirectory: URL = { // We use different App Groups: /// - Development: one chosen by the developer /// - Release: the official group.org.piwigo #if DEBUG let AppGroup = "group.net.lelievre-berna.piwigo" #else let AppGroup = "group.org.piwigo" #endif // Get path of group container let fm = FileManager.default let containerDirectory = fm.containerURL(forSecurityApplicationGroupIdentifier: AppGroup) let piwigoURL = containerDirectory?.appendingPathComponent("Library") .appendingPathComponent("Application Support") .appendingPathComponent("Piwigo") // Create the Piwigo directory in the container if needed if !(fm.fileExists(atPath: piwigoURL?.path ?? "")) { var errorCreatingDirectory: Error? = nil do { if let piwigoURL = piwigoURL { try fm.createDirectory(at: piwigoURL, withIntermediateDirectories: true, attributes: nil) } } catch let errorCreatingDirectory { } if errorCreatingDirectory != nil { fatalError("Unable to create Piwigo directory in App Group container.") } } print("••> AppGroupDirectory: \(piwigoURL!)") return piwigoURL! }() // "Library/Application Support/Piwigo" inside the Data Container of the Sandbox. /// - This is where the incompatible Core Data stores are stored. /// - The contents of this directory are backed up by iTunes and iCloud. /// - This is the directory where the application used to store the Core Data store files /// and files to upload before the creation of extensions. public static var appSupportDirectory: URL = { let fm = FileManager.default let applicationSupportDirectory = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).last let piwigoURL = applicationSupportDirectory?.appendingPathComponent("Piwigo") // Create the Piwigo directory in "Library/Application Support" if needed if !(fm.fileExists(atPath: piwigoURL?.path ?? "")) { var errorCreatingDirectory: Error? = nil do { if let piwigoURL = piwigoURL { try fm.createDirectory(at: piwigoURL, withIntermediateDirectories: true, attributes: nil) } } catch let errorCreatingDirectory { } if errorCreatingDirectory != nil { fatalError("Unable to create \"Piwigo\" directory in \"Library/Application Support\".") } } print("••> AppSupportDirectory: \(piwigoURL!)") return piwigoURL! }() public static var managedObjectContext: NSManagedObjectContext = { let applicationDocumentsDirectory: URL = { // The directory the application used to store the Core Data store file long ago. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() var managedObjectModel: NSManagedObjectModel = { // This resource has the same name as your xcdatamodeld contained in your project let bundle = Bundle.init(for: DataController.self) guard var modelURL = bundle.url(forResource: "DataModel", withExtension: "momd") else { fatalError("Error loading model from bundle") } // Retrieve the model version string (from the .plist file located in the .momd package) // in order to avoid having to update the code each time there is a new model version. // Avoids the warning "Failed to load optimized model at path…" for iOS if #available(iOS 13.0, *) { } else { let versionInfoURL = modelURL.appendingPathComponent("VersionInfo.plist") if let versionInfoNSDictionary = NSDictionary(contentsOf: versionInfoURL), let version = versionInfoNSDictionary.object(forKey: "NSManagedObjectModel_CurrentVersionName") as? String { modelURL.appendPathComponent("\(version).mom") } } // Get the object data model guard let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } return managedObjectModel }() var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) // Should we move the very old or old database to the new folder? let fm = FileManager.default var needMigrate = false, needDeleteOld = false var oldURL = applicationDocumentsDirectory.appendingPathComponent("DataModel.sqlite") if fm.fileExists(atPath: oldURL.path) { needMigrate = true // Should migrate very old store } else { oldURL = appSupportDirectory.appendingPathComponent("DataModel.sqlite") if fm.fileExists(atPath: oldURL.path) { needMigrate = true // Should migrate old store } } // Define options for performing an automatic migration // See https://code.tutsplus.com/tutorials/core-data-from-scratch-migrations--cms-21844 // for migrating to a new data model var failureReason = "There was an error creating or loading the application's saved data." let options = [ NSMigratePersistentStoresAutomaticallyOption: NSNumber(value: true), NSInferMappingModelAutomaticallyOption: NSNumber(value: true) ] let storeURL = appGroupDirectory.appendingPathComponent("DataModel.sqlite") if needMigrate { do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: oldURL, options: options) if let store = coordinator.persistentStore(for: oldURL) { do { try coordinator.migratePersistentStore(store, to: storeURL, options: options, withType: NSSQLiteStoreType) // Delete old Core Data store files deleteOldStoreAtUrl(url: oldURL) deleteOldStoreAtUrl(url: oldURL.deletingPathExtension() .appendingPathExtension("sqlite-shm")) deleteOldStoreAtUrl(url: oldURL.deletingPathExtension() .appendingPathExtension("sqlite-wal")) // Move Upload folder to container if needed moveFilesToUpload() } catch let error { // Log error let error = NSError(domain: "Piwigo", code: 9990, userInfo: [NSLocalizedDescriptionKey : "Failed to move Core Data store."]) print("Unresolved error \(error.localizedDescription)") // Move Incompatible Store moveIncompatibleStore(storeURL: oldURL) // Will inform user at restart CacheVars.couldNotMigrateCoreDataStore = true // Crash! abort() } } } catch { // Log error let error = NSError(domain: "Piwigo", code: 9990, userInfo: [NSLocalizedDescriptionKey : "Failed to migrate Core Data store."]) print("Unresolved error \(error.localizedDescription)") // Move Incompatible Store moveIncompatibleStore(storeURL: oldURL) // Will inform user at restart CacheVars.couldNotMigrateCoreDataStore = true // Crash! abort() } } else { do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { // Log error let error = NSError(domain: "Piwigo", code: 9990, userInfo: [NSLocalizedDescriptionKey : "Failed to migrate Core Data store."]) print("Unresolved error \(error.localizedDescription)") // Move Incompatible Store moveIncompatibleStore(storeURL: storeURL) // Will inform user at restart CacheVars.couldNotMigrateCoreDataStore = true // Crash! abort() } } return coordinator }() // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator if #available(iOS 10.0, *) { managedObjectContext.automaticallyMergesChangesFromParent = true } else { // Fallback on earlier versions } managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy managedObjectContext.shouldDeleteInaccessibleFaults = true // Set unused undoManager to nil for macOS (it is nil by default on iOS) // to reduce resource requirements. managedObjectContext.undoManager = nil return managedObjectContext }() private class func deleteOldStoreAtUrl(url: URL) { let fileCoordinator = NSFileCoordinator(filePresenter: nil) fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil, byAccessor: { (urlForModifying) -> Void in do { try FileManager.default.removeItem(at: urlForModifying) }catch let error { print("Failed to remove item with error: \(error.localizedDescription)") } }) } private class func moveIncompatibleStore(storeURL: URL) { let fm = FileManager.default let applicationIncompatibleStoresDirectory = appSupportDirectory.appendingPathComponent("Incompatible") // Create the Piwigo/Incompatible directory if needed if !fm.fileExists(atPath: applicationIncompatibleStoresDirectory.path) { do { try fm.createDirectory(at: applicationIncompatibleStoresDirectory, withIntermediateDirectories: true, attributes: nil) } catch let error { print("Unable to create directory for corrupt data stores: \(error.localizedDescription)") } } // Rename files with current date let dateFormatter = DateFormatter() dateFormatter.formatterBehavior = .behavior10_4 dateFormatter.dateFormat = "yyyy-MM-dd-HH-mm-ss" let nameForIncompatibleStore = "\(dateFormatter.string(from: Date()))" // Move .sqlite file if fm.fileExists(atPath: storeURL.path) { let corruptURL = applicationIncompatibleStoresDirectory .appendingPathComponent(nameForIncompatibleStore) .appendingPathExtension("sqlite") // Move Corrupt Store do { try fm.moveItem(at: storeURL, to: corruptURL) } catch let error { print("Unable to move corrupt store: \(error.localizedDescription)") } } // Move .sqlite-shm file let shmURL = storeURL.deletingPathExtension().appendingPathExtension("sqlite-shm") if fm.fileExists(atPath: shmURL.path) { let corruptURL = applicationIncompatibleStoresDirectory .appendingPathComponent(nameForIncompatibleStore) .appendingPathExtension("sqlite-shm") // Move Corrupt Store do { try fm.moveItem(at: shmURL, to: corruptURL) } catch let error { print("Unable to move corrupt store: \(error.localizedDescription)") } } // Move .sqlite-shm file let walURL = storeURL.deletingPathExtension().appendingPathExtension("sqlite-wal") if fm.fileExists(atPath: walURL.path) { let corruptURL = applicationIncompatibleStoresDirectory .appendingPathComponent(nameForIncompatibleStore) .appendingPathExtension("sqlite-wal") // Move Corrupt Store do { try fm.moveItem(at: walURL, to: corruptURL) } catch let error { print("Unable to move corrupt store: \(error.localizedDescription)") } } } private class func moveFilesToUpload() { let fm = FileManager.default let oldURL = appSupportDirectory.appendingPathComponent("Uploads") let newURL = appGroupDirectory.appendingPathComponent("Uploads") // Move Uploads directory do { // Get list of files let filesToMove = try fm.contentsOfDirectory(at: oldURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) // Move files for fileToMove in filesToMove { let newFileURL = newURL.appendingPathComponent(fileToMove.lastPathComponent) try fm.moveItem(at: fileToMove, to: newFileURL) } // Delete old Uploads directory try fm.removeItem(at: oldURL) } catch let error { print("Unable to move content of Uploads directory: \(error.localizedDescription)") } } public static var privateManagedObjectContext: NSManagedObjectContext = { var privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) privateManagedObjectContext.parent = managedObjectContext privateManagedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy privateManagedObjectContext.shouldDeleteInaccessibleFaults = true // Set unused undoManager to nil for macOS (it is nil by default on iOS) // to reduce resource requirements. // privateManagedObjectContext.undoManager = nil return privateManagedObjectContext }() // MARK: - Core Data Saving support public class func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } extension NSManagedObjectContext { /// Executes the given `NSBatchDeleteRequest` and directly merges the changes to bring the given managed object context up to date. public func executeAndMergeChanges(using batchDeleteRequest: NSBatchDeleteRequest) throws { batchDeleteRequest.resultType = .resultTypeObjectIDs do { // Execute the request. let deleteResult = try execute(batchDeleteRequest) as? NSBatchDeleteResult // Extract the IDs of the deleted managed objects from the request's result. if let objectIDs = deleteResult?.result as? [NSManagedObjectID] { // Merge the deletions into the app's managed object context. NSManagedObjectContext.mergeChanges( fromRemoteContextSave: [NSDeletedObjectsKey: objectIDs], into: [DataController.managedObjectContext] ) } } catch { // Handle any thrown errors. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } }
mit
2d544bca35ec261852419c1068c689ab
46.041237
295
0.593634
6.088059
false
false
false
false
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind
newsApp 1.2/newsApp/PeriodicosTableViewController.swift
1
3461
// // PeriodicosTableTableViewController.swift // newsApp // // Created by Miguel Gutiérrez Moreno on 22/1/15. // Copyright (c) 2015 MGM. All rights reserved. // /* V 1.1: muestra una lista con los periódicos */ import UIKit class PeriodicosTableViewController: UITableViewController { struct MainStoryboard { struct TableViewCellIdentifiers { // Used for normal items and the add item cell. static let listItemCell = "Cell" } } override func viewDidLoad() { super.viewDidLoad() // para que se desplace la tableView hacia abajo y no aparezca ajustada al Top self.tableView.contentInset = UIEdgeInsetsMake(30, 0, 0, 0); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Periodico.totalPeriodicos() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listItemCell, forIndexPath: indexPath) as UITableViewCell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let periodico = Periodico(rawValue: indexPath.row) { cell.textLabel?.text = periodico.nombre() } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
a054c8e87b6b812f5d631031b97a0c25
33.247525
157
0.687482
5.272866
false
false
false
false
Rapid-SDK/ios
Examples/RapiChat - Chat client/RapiChat shared/Channel.swift
1
778
// // Channel.swift // RapiChat // // Created by Jan on 27/06/2017. // Copyright © 2017 Rapid. All rights reserved. // import Foundation import Rapid struct Channel: Codable { let name: String var lastMessage: Message? enum CodingKeys : String, CodingKey { case name = "id" case lastMessage = "lastMessage" } init(name: String, lastMessage: Message?) { self.name = name self.lastMessage = lastMessage } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) lastMessage = try container.decodeIfPresent(Message.self, forKey: .lastMessage) } }
mit
9466f43f05653ac9b8b80008ac9c7a22
21.2
87
0.619048
4.269231
false
false
false
false
wireapp/wire-ios
Wire-iOS Share Extension/ShareExtensionAnalytics.swift
1
2570
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import WireShareEngine import WireCommonComponents import MobileCoreServices enum AttachmentType: Int, CaseIterable { static func < (lhs: AttachmentType, rhs: AttachmentType) -> Bool { return lhs.rawValue < rhs.rawValue } case walletPass = 1 case video case image case rawFile case url case fileUrl } extension NSItemProvider { var hasGifImage: Bool { return hasItemConformingToTypeIdentifier(kUTTypeGIF as String) } var hasImage: Bool { return hasItemConformingToTypeIdentifier(kUTTypeImage as String) } func hasFile(completion: @escaping (Bool) -> Void) { guard !hasImage && !hasVideo && !hasWalletPass else { return completion(false) } if hasURL { fetchURL { [weak self] url in if (url != nil && !url!.isFileURL) || self?.hasData == false { return completion(false) } completion(true) } } else { completion(hasData) } } private var hasData: Bool { return hasItemConformingToTypeIdentifier(kUTTypeData as String) } var hasURL: Bool { return hasItemConformingToTypeIdentifier(kUTTypeURL as String) && registeredTypeIdentifiers.count == 1 } var hasFileURL: Bool { return hasItemConformingToTypeIdentifier(kUTTypeFileURL as String) } var hasVideo: Bool { guard let uti = registeredTypeIdentifiers.first else { return false } return UTTypeConformsTo(uti as CFString, kUTTypeMovie) } var hasWalletPass: Bool { return hasItemConformingToTypeIdentifier(UnsentFileSendable.passkitUTI) } var hasRawFile: Bool { return hasItemConformingToTypeIdentifier(kUTTypeContent as String) && !hasItemConformingToTypeIdentifier(kUTTypePlainText as String) } }
gpl-3.0
147d9721a2d9db970ada4109df285418
29.963855
140
0.679377
4.858223
false
false
false
false
lcddhr/DouyuTV
DouyuTV/Vender/DDKit/GCD/GCDTimer.swift
2
1286
// // GCDTimer.swift // DouyuTV // // Created by lovelydd on 16/1/15. // Copyright © 2016年 xiaomutou. All rights reserved. // import UIKit class GCDTimer { private var _timer : dispatch_source_t? typealias GCDTimerHandle = (() -> Void) init(){ } private func _createTimer(interval: Double, queue: dispatch_queue_t, block: GCDTimerHandle) -> dispatch_source_t { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (timer != nil) { dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))), UInt64(interval * Double(NSEC_PER_SEC)), (1 * NSEC_PER_SEC) / 10); dispatch_source_set_event_handler(timer, block); dispatch_resume(timer); } return timer; } func start(interval: Double, block: (() ->Void)) { let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) _timer = _createTimer(interval, queue: queue, block: block) } func stop() { if (_timer != nil) { dispatch_source_cancel(_timer!); _timer = nil; } } }
mit
f09a29507e6e4be08815927fab8f1402
22.327273
185
0.551052
3.876133
false
false
false
false
stevehe-campray/BSBDJ
BSBDJ/BSBDJ/publish(发布)/Controllers/BSBPublishViewController.swift
1
16020
// // BSBPublishViewController.swift // BSBDJ // // Created by hejingjin on 16/6/15. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBPublishViewController: UIViewController { var buttonarray :[UIButton] = [] @IBOutlet weak var cancelButton: UIButton! var logvimageview : UIImageView? override func awakeFromNib() { super.awakeFromNib() self.view.insertSubview(cancelButton, atIndex: 1) } override func viewDidLoad() { super.viewDidLoad() // self.awakeFromNib(); let titlearray = ["发视频","发图片","发段子","发声音","审帖","发链接"] let imagenamearray = ["publish-video","publish-picture","publish-text","publish-audio","publish-review","publish-offline"] let screenH :Float = Float(UIScreen.mainScreen().bounds.size.height) let screenW :Float = Float(UIScreen.mainScreen().bounds.size.width) // 中间的6个按钮 let maxCols = 3; let buttonW :Float = 72; let buttonH :Float = buttonW + 30; let buttonStartY : Float = (screenH - 2 * buttonH) * 0.5 let buttonStartX : Float = 25.0 let xMargin : Float = (screenW - 2 * buttonStartX - Float(Int(maxCols)) * buttonW) / Float(Int(maxCols - 1)); // for i in 0 ..< 6{ // XMGVerticalButton *button = [[XMGVerticalButton alloc] init]; let button = BSBVerticalButton(); // 设置内容 button.titleLabel!.font = UIFont.systemFontOfSize(14) button.setTitle(titlearray[i], forState: UIControlState.Normal) button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.setImage(UIImage(named: imagenamearray[i]), forState: UIControlState.Normal) button.titleLabel?.textAlignment = NSTextAlignment.Center // // 设置frame // button.xmg_width = CGFloat(buttonW); // button.xmg_height = CGFloat(buttonH); // let row = i / maxCols; // let col = i % maxCols; // button.xmg_x = CGFloat(buttonStartX + Float(col) * (xMargin + buttonW)); // button.xmg_y = CGFloat((buttonStartY + Float(row) * buttonH)); buttonarray.append(button) self.view.addSubview(button) } self.setbuttonanimation() } func setbuttonanimation() { let screenH :Float = Float(UIScreen.mainScreen().bounds.size.height) let screenW :Float = Float(UIScreen.mainScreen().bounds.size.width) // 中间的6个按钮 let maxCols = 3; let buttonW :Float = 72; let buttonH :Float = buttonW + 30; let buttonStartY : Float = (screenH - 2 * buttonH) * 0.5 let buttonStartX : Float = 25.0 let xMargin : Float = (screenW - 2 * buttonStartX - Float(Int(maxCols)) * buttonW) / Float(Int(maxCols - 1)); let reviewbutton = buttonarray[4]; let reviewanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let reviewbuttonx = CGFloat(buttonStartX + Float(4%3) * (xMargin + buttonW)) let reviewbuttony = CGFloat(buttonStartY + Float(4/3) * buttonH - screenH) let reviewbuttonendy = CGFloat(buttonStartY + Float(1) * buttonH) CGRectMake(reviewbuttonx, reviewbuttony, CGFloat(buttonW), CGFloat(buttonH)) reviewanima.fromValue = NSValue.init(CGRect: CGRectMake(reviewbuttonx, reviewbuttony, CGFloat(buttonW), CGFloat(buttonH))) reviewanima.toValue = NSValue.init(CGRect: CGRectMake(reviewbuttonx, reviewbuttonendy, CGFloat(buttonW), CGFloat(buttonH))) reviewanima.springSpeed = 10.0; reviewanima.springBounciness = 10.0 reviewanima.beginTime = CACurrentMediaTime() + 0.1 reviewbutton.pop_addAnimation(reviewanima, forKey: nil) let audiobutton = buttonarray[3]; let audiobuttonanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let audiobuttonx = CGFloat(buttonStartX + Float(3%3) * (xMargin + buttonW)) let audiobuttony = CGFloat(buttonStartY + Float(3/3) * buttonH - screenH) let audiobuttonendy = CGFloat(buttonStartY + Float(1) * buttonH) audiobuttonanima.fromValue = NSValue.init(CGRect: CGRectMake(audiobuttonx, audiobuttony, CGFloat(buttonW), CGFloat(buttonH))) audiobuttonanima.toValue = NSValue.init(CGRect: CGRectMake(audiobuttonx, audiobuttonendy, CGFloat(buttonW), CGFloat(buttonH))) audiobuttonanima.springSpeed = 10.0; audiobuttonanima.springBounciness = 10.0 audiobuttonanima.beginTime = CACurrentMediaTime() + 0.2 audiobutton.pop_addAnimation(audiobuttonanima, forKey: nil) let offlinebutton = buttonarray[5]; let offlineanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let offlinebuttonx = CGFloat(buttonStartX + Float(5%3) * (xMargin + buttonW)) let offlinebuttony = CGFloat(buttonStartY + Float(5/3) * buttonH - screenH) let offlinebuttonendy = CGFloat(buttonStartY + Float(1) * buttonH) offlineanima.fromValue = NSValue.init(CGRect: CGRectMake(offlinebuttonx, offlinebuttony, CGFloat(buttonW), CGFloat(buttonH))) offlineanima.toValue = NSValue.init(CGRect: CGRectMake(offlinebuttonx, offlinebuttonendy, CGFloat(buttonW), CGFloat(buttonH))) offlineanima.springSpeed = 10.0; offlineanima.springBounciness = 10.0 offlineanima.beginTime = CACurrentMediaTime() + 0.3 offlinebutton.pop_addAnimation(offlineanima, forKey: nil) let picturebutton = buttonarray[1]; let pictureanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let picturebuttonx = CGFloat(buttonStartX + Float(1%3) * (xMargin + buttonW)) let picturebuttony = CGFloat(buttonStartY + Float(1/3) * buttonH - screenH) let picturebuttonendy = CGFloat(buttonStartY + Float(0) * buttonH) pictureanima.fromValue = NSValue.init(CGRect: CGRectMake(picturebuttonx, picturebuttony, CGFloat(buttonW), CGFloat(buttonH))) pictureanima.toValue = NSValue.init(CGRect: CGRectMake(picturebuttonx, picturebuttonendy, CGFloat(buttonW), CGFloat(buttonH))) pictureanima.springSpeed = 10.0; pictureanima.springBounciness = 10.0 pictureanima.beginTime = CACurrentMediaTime() + 0.4 picturebutton.pop_addAnimation(pictureanima, forKey: nil) let videobutton = buttonarray[0]; let videoanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let videobuttonx = CGFloat(buttonStartX + Float(0%3) * (xMargin + buttonW)) let videobuttony = CGFloat(buttonStartY + Float(0/3) * buttonH - screenH) let videobuttonendy = CGFloat(buttonStartY + Float(0) * buttonH) videoanima.fromValue = NSValue.init(CGRect: CGRectMake(videobuttonx, videobuttony, CGFloat(buttonW), CGFloat(buttonH))) videoanima.toValue = NSValue.init(CGRect: CGRectMake(videobuttonx, videobuttonendy, CGFloat(buttonW), CGFloat(buttonH))) videoanima.springSpeed = 10.0; videoanima.springBounciness = 10.0 videoanima.beginTime = CACurrentMediaTime() + 0.5 videobutton.pop_addAnimation(videoanima, forKey: nil) let textbutton = buttonarray[2]; let textbuttonanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let textbuttonx = CGFloat(buttonStartX + Float(2%3) * (xMargin + buttonW)) let textbuttony = CGFloat(buttonStartY + Float(2/3) * buttonH - screenH) let textbuttonendy = CGFloat(buttonStartY + Float(0) * buttonH) textbuttonanima.fromValue = NSValue.init(CGRect: CGRectMake(textbuttonx, textbuttony, CGFloat(buttonW), CGFloat(buttonH))) textbuttonanima.toValue = NSValue.init(CGRect: CGRectMake(textbuttonx, textbuttonendy, CGFloat(buttonW), CGFloat(buttonH))) textbuttonanima.springSpeed = 10.0; textbuttonanima.springBounciness = 10.0 textbuttonanima.beginTime = CACurrentMediaTime() + 0.6 textbutton.pop_addAnimation(textbuttonanima, forKey: nil) let sloganimageview = UIImageView.init(image: UIImage.init(named: "app_slogan")) sloganimageview.xmg_centerY = -60 sloganimageview.xmg_centerX = (UIScreen.mainScreen().bounds.size.width) * 0.5 self.logvimageview = sloganimageview self.view.addSubview(sloganimageview) let sloganimageviewanima = POPSpringAnimation.init(propertyNamed: kPOPLayerPositionY) sloganimageviewanima.fromValue = CGFloat(screenH * 0.2 - screenH * 1.5) sloganimageviewanima.toValue = CGFloat(screenH * 0.2) sloganimageviewanima.beginTime = CACurrentMediaTime() + 0.7 sloganimageviewanima.springBounciness = 10.0 sloganimageviewanima.springSpeed = 10.0 sloganimageview.pop_addAnimation(sloganimageviewanima, forKey: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancell() { let screenH :Float = Float(UIScreen.mainScreen().bounds.size.height) let screenW :Float = Float(UIScreen.mainScreen().bounds.size.width) // 中间的6个按钮 let maxCols = 3; let buttonW :Float = 72; let buttonH :Float = buttonW + 30; let buttonStartY : Float = (screenH - 2 * buttonH) * 0.5 let buttonStartX : Float = 25.0 let xMargin : Float = (screenW - 2 * buttonStartX - Float(Int(maxCols)) * buttonW) / Float(Int(maxCols - 1)); let reviewbutton = buttonarray[4]; let reviewanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let reviewbuttonx = CGFloat(buttonStartX + Float(4%3) * (xMargin + buttonW)) let reviewbuttony = CGFloat(buttonStartY + Float(1) * buttonH) let reviewbuttonendy = CGFloat(screenH * 1.5) CGRectMake(reviewbuttonx, reviewbuttony, CGFloat(buttonW), CGFloat(buttonH)) reviewanima.fromValue = NSValue.init(CGRect: CGRectMake(reviewbuttonx, reviewbuttony, CGFloat(buttonW), CGFloat(buttonH))) reviewanima.toValue = NSValue.init(CGRect: CGRectMake(reviewbuttonx, reviewbuttonendy, CGFloat(buttonW), CGFloat(buttonH))) reviewanima.springSpeed = 10.0; reviewanima.springBounciness = 10.0 reviewanima.beginTime = CACurrentMediaTime() + 0.1 reviewbutton.pop_addAnimation(reviewanima, forKey: nil) let audiobutton = buttonarray[3]; let audiobuttonanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let audiobuttonx = CGFloat(buttonStartX + Float(3%3) * (xMargin + buttonW)) let audiobuttony = CGFloat(buttonStartY + Float(1) * buttonH) let audiobuttonendy = CGFloat(screenH * 1.5) audiobuttonanima.fromValue = NSValue.init(CGRect: CGRectMake(audiobuttonx, audiobuttony, CGFloat(buttonW), CGFloat(buttonH))) audiobuttonanima.toValue = NSValue.init(CGRect: CGRectMake(audiobuttonx, audiobuttonendy, CGFloat(buttonW), CGFloat(buttonH))) audiobuttonanima.springSpeed = 10.0; audiobuttonanima.springBounciness = 10.0 audiobuttonanima.beginTime = CACurrentMediaTime() + 0.2 audiobutton.pop_addAnimation(audiobuttonanima, forKey: nil) let offlinebutton = buttonarray[5]; let offlineanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let offlinebuttonx = CGFloat(buttonStartX + Float(5%3) * (xMargin + buttonW)) let offlinebuttony = CGFloat(buttonStartY + Float(1) * buttonH) let offlinebuttonendy = CGFloat(screenH * 1.5) offlineanima.fromValue = NSValue.init(CGRect: CGRectMake(offlinebuttonx, offlinebuttony, CGFloat(buttonW), CGFloat(buttonH))) offlineanima.toValue = NSValue.init(CGRect: CGRectMake(offlinebuttonx, offlinebuttonendy, CGFloat(buttonW), CGFloat(buttonH))) offlineanima.springSpeed = 10.0; offlineanima.springBounciness = 10.0 offlineanima.beginTime = CACurrentMediaTime() + 0.3 offlinebutton.pop_addAnimation(offlineanima, forKey: nil) let picturebutton = buttonarray[1]; let pictureanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let picturebuttonx = CGFloat(buttonStartX + Float(1%3) * (xMargin + buttonW)) let picturebuttony = CGFloat(buttonStartY + Float(0) * buttonH) let picturebuttonendy = CGFloat(screenH * 1.5) pictureanima.fromValue = NSValue.init(CGRect: CGRectMake(picturebuttonx, picturebuttony, CGFloat(buttonW), CGFloat(buttonH))) pictureanima.toValue = NSValue.init(CGRect: CGRectMake(picturebuttonx, picturebuttonendy, CGFloat(buttonW), CGFloat(buttonH))) pictureanima.springSpeed = 10.0; pictureanima.springBounciness = 10.0 pictureanima.beginTime = CACurrentMediaTime() + 0.4 picturebutton.pop_addAnimation(pictureanima, forKey: nil) let videobutton = buttonarray[0]; let videoanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let videobuttonx = CGFloat(buttonStartX + Float(0%3) * (xMargin + buttonW)) let videobuttony = CGFloat(buttonStartY + Float(0) * buttonH) let videobuttonendy = CGFloat(screenH * 1.5) videoanima.fromValue = NSValue.init(CGRect: CGRectMake(videobuttonx, videobuttony, CGFloat(buttonW), CGFloat(buttonH))) videoanima.toValue = NSValue.init(CGRect: CGRectMake(videobuttonx, videobuttonendy, CGFloat(buttonW), CGFloat(buttonH))) videoanima.springSpeed = 10.0; videoanima.springBounciness = 10.0 videoanima.beginTime = CACurrentMediaTime() + 0.5 videobutton.pop_addAnimation(videoanima, forKey: nil) let textbutton = buttonarray[2]; let textbuttonanima = POPSpringAnimation.init(propertyNamed: kPOPViewFrame) let textbuttonx = CGFloat(buttonStartX + Float(2%3) * (xMargin + buttonW)) let textbuttony = CGFloat(buttonStartY + Float(0) * buttonH) let textbuttonendy = CGFloat(screenH * 1.5) textbuttonanima.fromValue = NSValue.init(CGRect: CGRectMake(textbuttonx, textbuttony, CGFloat(buttonW), CGFloat(buttonH))) textbuttonanima.toValue = NSValue.init(CGRect: CGRectMake(textbuttonx, textbuttonendy, CGFloat(buttonW), CGFloat(buttonH))) textbuttonanima.springSpeed = 10.0; textbuttonanima.springBounciness = 10.0 textbuttonanima.beginTime = CACurrentMediaTime() + 0.6 textbutton.pop_addAnimation(textbuttonanima, forKey: nil) let sloganimageviewanima = POPSpringAnimation.init(propertyNamed: kPOPLayerPositionY) sloganimageviewanima.fromValue = CGFloat(screenH * 0.2) sloganimageviewanima.toValue = CGFloat(screenH * 1.2) sloganimageviewanima.beginTime = CACurrentMediaTime() + 0.65 sloganimageviewanima.springBounciness = 10.0 sloganimageviewanima.springSpeed = 10.0 //闭包代替block sloganimageviewanima.completionBlock = {(animation, finished) in if finished { self.dismissViewControllerAnimated(true, completion: nil) } } self.logvimageview!.pop_addAnimation(sloganimageviewanima, forKey: nil) } }
mit
bf657c99718f4c417e31b473d473583a
49.561905
134
0.656558
4.210151
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/Word.swift
1
2681
/** * Copyright IBM Corporation 2018 * * 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 /** Word. */ public struct Word: Decodable { /// A word from the custom model's words resource. The spelling of the word is used to train the model. public var word: String /// An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. public var soundsLike: [String] /// The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. public var displayAs: String /// A sum of the number of times the word is found across all corpora. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. public var count: Int /// An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. public var source: [String] /// If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. public var error: [WordError]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case word = "word" case soundsLike = "sounds_like" case displayAs = "display_as" case count = "count" case source = "source" case error = "error" } }
mit
86593dc7d272878691bf125c08d0c2ce
52.62
403
0.728833
4.380719
false
false
false
false
seanoshea/computer-science-in-swift
computer-science-in-swift/LinkedList.swift
1
3143
// Copyright (c) 2015-2016 Sean O'Shea. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation class LinkedListNode { var data:Int = 0 var next:LinkedListNode? } class LinkedList: NSObject { var head:LinkedListNode? var length:Int = 0 func add(_ data:Int) { let node = LinkedListNode() node.data = data var current:LinkedListNode if self.head == nil { self.head = node } else { current = self.head! while current.next != nil { current = current.next! } current.next = node } self.length = self.length + 1 } func item(_ index:Int) -> Int? { if index > -1 && index < self.length { var current:LinkedListNode = self.head! var i = 0 while i < index { current = current.next! i = i + 1 } return current.data } return nil } func remove(_ index:Int) -> Int? { if index > -1 && index < self.length { var current:LinkedListNode = self.head! var previous:LinkedListNode = LinkedListNode() var i = 0 if index == 0 { self.head = current.next } else { while i < index { previous = current current = current.next! i = i + 1 } previous.next = current.next } self.length = self.length - 1 return current.data } else { return nil } } func size() -> Int { return self.length } func toArray() -> [Int] { var result = [Int]() for i in 0..<self.length { result.append(self.item(i)!) } return result } func clear() { for i in 0..<self.length { _ = self.remove(i) } self.head = nil self.length = 0 } }
mit
90453a5756823796042dc1760543f1ff
29.221154
80
0.557747
4.622059
false
false
false
false
zmian/xcore.swift
Tests/XcoreTests/Numbers/NumbersTests.swift
1
7882
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import XCTest @testable import Xcore final class NumbersTests: TestCase { func testRunningSum() { let intRunningSum = [1, 1, 1, 1, 1, 1].runningSum() let expected1 = [1, 2, 3, 4, 5, 6] XCTAssertEqual(intRunningSum, expected1) let doubleRunningSum = [1.0, 1, 1, 1, 1, 1].runningSum() let expected2 = [1.0, 2, 3, 4, 5, 6] XCTAssertEqual(doubleRunningSum, expected2) } func testSum() { let intSum = [1, 1, 1, 1, 1, 1].sum() XCTAssertEqual(intSum, 6) let doubleSum = [1.0, 1, 1, 1, 1, 1].sum() XCTAssertEqual(doubleSum, 6.0) } func testSumClosure() { struct Expense { let title: String let amount: Double } let expenses = [ Expense(title: "Laptop", amount: 1200), Expense(title: "Chair", amount: 1000) ] let totalCost = expenses.sum { $0.amount } XCTAssertEqual(totalCost, 2200.0) } func testAverage() { let int = [1, 1, 1, 1, 1, 1].average() XCTAssertEqual(int, 1.0) let double = [1.0, 1, 1, 1, 1, 1].average() XCTAssertEqual(double, 1.0) let float: [Float] = [1.0, 1, 1, 1, 1, 1] XCTAssertEqual(float.average(), 1.0) let float2: [Float] = [1.0, 12.3, 33, 37, 34, 45] XCTAssertEqual(float2.average(), 27.050001) let decimal: [Decimal] = [1.0, 12.3, 33, 37, 34, 45] XCTAssertEqual(decimal.average(), 27.05) } func testMap() { let values = 10.map { $0 * 2 } let expected = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] XCTAssertEqual(values, expected) } func testDoubleInit() { XCTAssertEqual(Double("2.5" as Any), 2.5) XCTAssertEqual(Double(Int(-7) as Any), -7) XCTAssertEqual(Double(UInt(7) as Any), 7) XCTAssertEqual(Double(CGFloat(2.5) as Any), 2.5) XCTAssertEqual(Double(CGFloat(0.07) as Any), 0.07) XCTAssertEqual(Double(Double(2.5) as Any), 2.5) XCTAssertEqual(Double(Double(0.07) as Any), 0.07) XCTAssertEqual(Double(Decimal(0.07) as Any), 0.07) XCTAssertEqual(Double(Decimal(315.36) as Any), 315.36) XCTAssertEqual(Double(Decimal(9.28) as Any), 9.28) XCTAssertEqual(Double(Decimal(0.1736) as Any), 0.1736) XCTAssertEqual(Double(Decimal(0.000001466) as Any), 0.000001466) } func testDouble_formatted() { XCTAssertEqual(Double(1).formatted(fractionDigits: 2), "1.00") XCTAssertEqual(Double(1.09).formatted(fractionDigits: 2), "1.09") XCTAssertEqual(Double(1.9).formatted(fractionDigits: 2), "1.90") XCTAssertEqual(Double(1.1345).formatted(fractionDigits: 2), "1.13") XCTAssertEqual(Double(1.1355).formatted(fractionDigits: 2), "1.14") XCTAssertEqual(Double(1.1355).formatted(fractionDigits: 3), "1.136") XCTAssertEqual(Double(9.28).formatted(fractionDigits: 3), "9.280") XCTAssertEqual(Double(0.1736).formatted(fractionDigits: 4), "0.1736") XCTAssertEqual(Double(0.1736).formatted(fractionDigits: 2), "0.17") XCTAssertEqual(Double(0.000001466).formatted(fractionDigits: 9), "0.000001466") XCTAssertEqual(Double(0.000001466).formatted(fractionDigits: 8), "0.00000147") XCTAssertEqual(Double(0.000001466).formatted(fractionDigits: 3), "0.000") // trunc XCTAssertEqual(Double(1.1355).formatted(.towardZero, fractionDigits: 3), "1.135") } func testAbbreviate() { let values1: [(Double, String)] = [ (0.000001466, "0.000001466"), (0.000001566, "0.000001566"), (0.01466, "0.01466"), (0.241341466, "0.241341466"), (0.1736, "0.1736"), (9.28, "9.28"), (0.07, "0.07"), (315.36, "315.36"), (987, "987"), (1200.0, "1.2K"), (12000.0, "12K"), (120000.0, "120K"), (1200000.0, "1.2M"), (1340.0, "1.3K"), (132456.0, "132.5K"), (132456.80, "132.5K"), (1_116_400_000.00, "1.1B") ] for (input, output) in values1 { XCTAssertEqual(output, input.abbreviate()) } let values2: [(Double, String)] = [ (598, "598"), (987, "987"), (-999, "-999"), // K (1000, "1K"), (-1284, "-1.3K"), (1200, "1.2K"), (1340, "1.3K"), (9940, "9.9K"), (9980, "10K"), (12000, "12K"), (39900, "39.9K"), (99880, "99.9K"), (120_000, "120K"), (132_456, "132.5K"), (399_880, "399.9K"), // M (999_898, "1M"), (999_999, "1M"), (1_200_000, "1.2M"), (1_456_384, "1.5M"), (12_383_474, "12.4M"), (16_000_000, "16M"), (999_000_000, "999M"), (160_000_000, "160M"), // B (9_000_000_000, "9B"), (90_000_000_000, "90B"), (900_000_000_000, "900B"), (999_000_000_000, "999B"), // T (1_000_000_000_000, "1T"), (1_200_000_000_000, "1.2T"), (3_000_000_000_000, "3T"), (9_000_000_000_000, "9T"), (90_000_000_000_000, "90T"), (900_000_000_000_000, "900T"), (999_000_000_000_000, "999T"), // Other (0, "0"), (-10, "-10"), (500, "500"), (999, "999"), (1000, "1K"), (1234, "1.2K"), (9000, "9K"), (10_000, "10K"), (-10_000, "-10K"), (15_235, "15.2K"), (-15_235, "-15.2K"), (99_500, "99.5K"), (-99_500, "-99.5K"), (100_500, "100.5K"), (-100_500, "-100.5K"), (105_000_000, "105M"), (-105_000_000, "-105M"), (140_800_200_000, "140.8B"), (170_400_800_000_000, "170.4T"), (-170_400_800_000_000, "-170.4T"), (-9_223_372_036_854_775_808, "-9,223,372T"), (Double(Int.max), "9,223,372T") ] for (input, output) in values2 { XCTAssertEqual(output, input.abbreviate()) } } func testAbbreviateThreshold() { let values: [(Double, String)] = [ (315.36, "315.36"), (1_000_000, "1,000,000"), (9000, "9,000"), (105_000_000, "105M"), (140_800_200_000, "140.8B"), (170_400_800_000_000, "170.4T"), (-170_400_800_000_000, "-170.4T"), (-9_223_372_036_854_775_808, "-9,223,372T") ] for (input, output) in values { XCTAssertEqual(output, input.abbreviate(threshold: 2_000_000)) } } func testAbbreviateLocale() { // Tr let valuesTr: [(Double, String)] = [ (105_000_000, "105M"), (140_800_200_000, "140,8B"), (170_400_800_000_000, "170,4T"), (-170_400_800_000_000, "-170,4T"), (-9_223_372_036_854_775_808, "-9.223.372T") ] for (input, output) in valuesTr { XCTAssertEqual(output, input.abbreviate(locale: .tr)) } // Fr let valuesFr: [(Double, String)] = [ (105_000_000, "105M"), (140_800_200_000, "140,8B"), (170_400_800_000_000, "170,4T"), (-170_400_800_000_000, "-170,4T"), (-9_223_372_036_854_775_808, "-9 223 372T") ] for (input, output) in valuesFr { XCTAssertEqual(output, input.abbreviate(locale: .fr)) } } }
mit
7a785ec74af032ab98472e4848ba8b5b
31.958159
89
0.483052
3.182626
false
true
false
false
br1sk/brisk-ios
Brisk iOS/Login/LoginCoordinator.swift
1
2234
import UIKit import SafariServices private let kAPIKeyURL = URL(string: "https://openradar.appspot.com/apikey")! private let kOpenRadarUsername = "openradar" final class LoginCoordinator { // MARK: - Properties let source: UIViewController var loginController: LoginViewController? let root = UINavigationController() // MARK: - Init/Deinit init(from source: UIViewController) { self.source = source } // MARK: - Public API func start() { let controller = LoginViewController.newFromStoryboard() controller.delegate = self root.viewControllers = [controller] root.modalPresentationStyle = .formSheet source.present(root, animated: true) loginController = controller } func finish() { source.dismiss(animated: true) } // MARK: - Private fileprivate func showError(_ error: LoginError) { let global = Localizable.Global.self let alert = UIAlertController(title: global.error.localized, message: error.localizedDescription, preferredStyle: .alert) let cancel = UIAlertAction(title: global.tryAgain.localized, style: .cancel) { [weak self] _ in self?.loginController?.dismiss(animated: true, completion: nil) } alert.addAction(cancel) loginController?.present(alert, animated: true, completion: nil) } } // MARK: - LoginViewDelegate Methods extension LoginCoordinator: LoginViewDelegate { func submitTapped(user: User) { guard user.email.isValid else { showError(.invalidEmail) return } // Save to keychain Keychain.set(username: user.email.value, password: user.password, forKey: .radar) // Continue to open radar let openradar = OpenRadarViewController.newFromStoryboard() openradar.delegate = self root.show(openradar, sender: self) } } // MARK: - OpenRadarViewDelegate Method extension LoginCoordinator: OpenRadarViewDelegate { func openSafariTapped() { let safari = SFSafariViewController(url: kAPIKeyURL) root.showDetailViewController(safari, sender: self) } func continueTapped(token: String) { // Save to keychain if token.isEmpty { Keychain.delete(.openRadar) } else { Keychain.set(username: kOpenRadarUsername, password: token, forKey: .openRadar) } finish() } func skipTapped() { finish() } }
mit
cccb62c7caa417ac22c12cb229c5177c
21.34
123
0.735004
3.780034
false
false
false
false
master-nevi/UPnAtom
Source/Parsers/SAXXMLParserElementObservation.swift
1
2729
// // SAXXMLParserElementObservation.swift // // Copyright (c) 2015 David Robles // // 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 public class SAXXMLParserElementObservation { // internal private(set) var didStartParsingElement: ((elementName: String, attributeDict: [NSObject : AnyObject]!) -> Void)? // TODO: Should ideally be a constant, see Github issue #10 let didEndParsingElement: ((elementName: String) -> Void)? let foundInnerText: ((elementName: String, text: String) -> Void)? let elementPath: [String] private(set) var innerText: String? public init(elementPath: [String], didStartParsingElement: ((elementName: String, attributeDict: [NSObject : AnyObject]!) -> Void)?, didEndParsingElement: ((elementName: String) -> Void)?, foundInnerText: ((elementName: String, text: String) -> Void)?) { self.elementPath = elementPath self.didEndParsingElement = didEndParsingElement self.foundInnerText = foundInnerText self.didStartParsingElement = {[unowned self] (elementName: String, attributeDict: [NSObject : AnyObject]!) -> Void in // reset _innerText at the start of the element parse self.innerText = nil if let didStartParsingElement = didStartParsingElement { didStartParsingElement(elementName: elementName, attributeDict: attributeDict) } } } func appendInnerText(innerText: String?) { if self.innerText == nil { self.innerText = "" } if let innerText = innerText { self.innerText! += innerText } } }
mit
41915a974e01c6c4805af1aa5f6d4dce
45.254237
258
0.690729
4.609797
false
false
false
false
Witcast/witcast-ios
WiTcast/ViewController/Search/AppSearchBarController.swift
1
3415
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class AppSearchBarController: SearchBarController { fileprivate var backButton: IconButton! fileprivate var moreButton: IconButton! open override func prepare() { super.prepare() prepareMenuButton() prepareMoreButton() prepareStatusBar() prepareSearchBar() } } extension AppSearchBarController: UITextFieldDelegate { fileprivate func prepareMenuButton() { backButton = IconButton(image: Icon.cm.arrowBack) backButton.tintColor = UIColor.black } fileprivate func prepareMoreButton() { moreButton = IconButton(image: Icon.cm.moreVertical) } fileprivate func prepareStatusBar() { statusBarStyle = .lightContent // Access the statusBar. // statusBar.backgroundColor = Color.green.base } fileprivate func prepareSearchBar() { searchBar.leftViews = [backButton] // searchBar.rightViews = [moreButton] statusBar.backgroundColor = UIColor.white // CustomFunc.UIColorFromRGB(rgbValue: colorMain) searchBar.backgroundColor = UIColor.white // CustomFunc.UIColorFromRGB(rgbValue: colorMain) searchBar.textColor = UIColor.black searchBar.textField.font = UIFont(name: font_regular, size: (searchBar.textField.font?.pointSize)!); searchBar.textField.returnKeyType = .done searchBar.textField.delegate = self backButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { searchBar.endEditing(true) return false } func buttonAction(sender: UIButton!) { _ = navigationController?.popViewController(animated: true); } }
apache-2.0
d4e8abfd9c2557c5faa17a6affbe9bf7
39.176471
108
0.720644
4.942113
false
false
false
false
turingcorp/gattaca
UnitTests/Model/Home/Abstract/TMHomeRequest.swift
1
5688
import XCTest @testable import gattaca class TMHomeRequest:XCTestCase { private var trendingMock:Data? private var session:MSession? private var model:MHome? private var urlResponseOk:URLResponse? private var urlResponseFail:URLResponse? private var requestError:Error? private let kDummyUrl:String = "https://www.google.com" private let kTrendingName:String = "giphyTrending" private let kTrendingExtension:String = "json" private let kErrorDomain:String = "some weird error" private let kIdentifier:String = "lorem ipsum" private let kDelayWait:TimeInterval = 1 private let kWaitExpectation:TimeInterval = 2 private let kStatusCodeOk:Int = 200 private let kStatusCodeFail:Int = 0 private let kMockedItems:Int = 3 override func setUp() { super.setUp() let session:MSession = MSession() self.session = session model = MHome(session:session) requestError = NSError( domain:kErrorDomain, code:0, userInfo:nil) guard let dummyUrl:URL = URL(string:kDummyUrl) else { return } urlResponseOk = HTTPURLResponse( url:dummyUrl, statusCode:kStatusCodeOk, httpVersion:nil, headerFields:nil) urlResponseFail = HTTPURLResponse( url:dummyUrl, statusCode:kStatusCodeFail, httpVersion:nil, headerFields:nil) let bundle:Bundle = Bundle(for:TMHomeRequest.self) model?.coreData = Database(bundle:bundle) guard let url:URL = bundle.url( forResource:kTrendingName, withExtension:kTrendingExtension) else { return } let data:Data do { try data = Data( contentsOf:url, options:Data.ReadingOptions.uncached) } catch { return } trendingMock = data } //MARK: internal func testLoad() { XCTAssertNotNil( trendingMock, "failed loading mockup") XCTAssertNotNil( urlResponseOk, "failed creating url response ok") XCTAssertNotNil( urlResponseFail, "failed creating url response fail") XCTAssertNotNil( requestError, "failed creating error") } func testRequestGifsResponse() { guard let model:MHome = self.model else { return } let items:[MGiphyItem]? = model.requestGifsResponse( data:trendingMock, urlResponse:urlResponseOk, error:nil) XCTAssertNotNil( items, "failed parsing items") guard let parsedItems:[MGiphyItem] = items else { return } XCTAssertEqual( parsedItems.count, kMockedItems, "incorrect number of items") for item:MGiphyItem in parsedItems { let itemIdLength:Int = item.identifier.characters.count XCTAssertGreaterThan( itemIdLength, 0, "failed parsing identifier") } } func testRequestGifsResponseFail() { guard let model:MHome = self.model else { return } let items:[MGiphyItem]? = model.requestGifsResponse( data:trendingMock, urlResponse:urlResponseFail, error:nil) XCTAssertNil( items, "should not parse items") } func testRequestGifsResponseError() { guard let model:MHome = self.model else { return } let items:[MGiphyItem]? = model.requestGifsResponse( data:trendingMock, urlResponse:urlResponseOk, error:requestError) XCTAssertNil( items, "should not parse items") } func testRequestGifsSuccess() { let identifier:String = kIdentifier let item:MGiphyItem = MGiphyItem( identifier:identifier) guard let model:MHome = self.model else { return } model.gif.strategyStand() let successWait:XCTestExpectation = expectation( description:"expectation success") model.requestGifsSuccess(items:[item]) DispatchQueue.main.asyncAfter( deadline:DispatchTime.now() + kDelayWait) { successWait.fulfill() } waitForExpectations(timeout:kWaitExpectation) { (error:Error?) in XCTAssertEqual( model.gif.itemsNotReady.count, 1, "there should be exactly 1 item store") XCTAssertEqual( model.gif.itemsNotReady.first?.identifier, identifier, "stored item doesn't match identifier") } } }
mit
53e2d511ef813c54250a0d4259ab0665
22.89916
67
0.500527
5.705115
false
false
false
false
SirapatBoonyasiwapong/grader
Sources/App/Commands/RedisWorker.swift
2
967
import VaporRedisClient import Redis import RedisClient import Reswifq import Console class RedisWorker { let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } func run() { console.print("Preparing redis client pool...") let client = RedisClientPool(maxElementCount: 10) { () -> RedisClient in self.console.print("Create client") return VaporRedisClient(try! TCPClient(hostname: "redis", port: 6379)) } let queue = Reswifq(client: client) queue.jobMap[String(describing: DemoJob.self)] = DemoJob.self queue.jobMap[String(describing: SubmissionJob.self)] = SubmissionJob.self console.print("Starting worker...") let worker = Worker(queue: queue, maxConcurrentJobs: 4, averagePollingInterval: 0) worker.run() console.print("Finished") } }
mit
7bae119dbd80bfe85b76cd094fd7577e
26.628571
90
0.625646
4.518692
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/View/SettingsLauncher.swift
1
4252
// // SettingsLauncher.swift // TravelApp // // Created by rawat on 23/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class SettingsLauncher: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { let blackView = UIView() let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.backgroundColor = UIColor.white cv.translatesAutoresizingMaskIntoConstraints = false return cv }() let cellId = "cellId" let cellHeight: CGFloat = 50 let settings: [Setting] = { return [ Setting(name: .Settings, imageName: "settings"), Setting(name: .Privacy, imageName: "privacy"), Setting(name: .Feedback, imageName: "feedback"), Setting(name: .Logout, imageName: "logout"), Setting(name: .Cancel, imageName: "cancel") ] }() var homeController: HomeController? func showSettings() { if let window = UIApplication.shared.keyWindow { blackView.backgroundColor = UIColor(white: 0, alpha: 0.5) blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss))) window.addSubview(blackView) window.addSubview(collectionView) let cvHeight: CGFloat = CGFloat(settings.count) * cellHeight let cvY = window.frame.height - cvHeight collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: cvHeight) blackView.frame = window.frame blackView.alpha = 0 UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.blackView.alpha = 1 self.collectionView.frame = CGRect(x: 0, y: cvY, width: self.collectionView.frame.width, height: self.collectionView.frame.height) }, completion: nil) } } func handleDismiss(setting: Setting) { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { self.blackView.alpha = 0 if let window = UIApplication.shared.keyWindow { self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height) } }) { (true) in if setting.name == .Logout { self.homeController?.handleLogout() } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return settings.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SettingCell let setting = settings[indexPath.item] cell.setting = setting return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: cellHeight) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let setting = settings[indexPath.item] handleDismiss(setting: setting) } override init() { super.init() collectionView.dataSource = self collectionView.delegate = self collectionView.register(SettingCell.self, forCellWithReuseIdentifier: cellId) } }
mit
61128615a419f0c83233e9bd46c247b4
38
170
0.642202
5.267658
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/LoadingViewController.swift
3
9386
// // LoadingViewController.swift // GamingStreamsTVApp // // Created by Olivier Boucher on 2015-09-29. import UIKit import Foundation protocol LoadController { var itemCount: Int { get } func getItemAtIndex(index: Int) -> CellItem } //NOTE(Olivier): //Swift doesn't provide any way to abstract a class like Java or C# //This is not a protocol because I don't want to copy this code in each controller class LoadingViewController : UIViewController, LoadController { internal let TOP_BAR_HEIGHT : CGFloat = 100 internal var HEIGHT_RATIO: CGFloat { get { return 1.39705882353 } } internal var ITEMS_INSETS_X : CGFloat { get { return 0 } } internal var NUM_COLUMNS: Int { get { return 5 } } internal let ITEMS_INSETS_Y : CGFloat = 0 internal var collectionView : UICollectionView! internal var topBar : TopBarView! internal var loadingView : LoadingView? internal var errorView : ErrorView? private var reloadLabel : UILabel? override func viewDidLoad() { self.view.backgroundColor = UIColor(white: 0.4, alpha: 1) } /* * displayLoadingView() * * Initializes a loading view in the center of the screen and displays it * */ func displayLoadingView(loading: String = "Loading...") { self.loadingView = LoadingView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width/5, height: self.view.bounds.height/5), text: loading) self.loadingView?.center = self.view.center self.view.addSubview(self.loadingView!) } /* * removeLoadingView() * * Removes the loading view if existant * */ func removeLoadingView() { if self.loadingView != nil { self.loadingView?.removeFromSuperview() self.loadingView = nil } } /* * displayErrorView(title : String) * * Initializes an error view in the center of the screen and displays it * */ func displayErrorView(title : String) { self.errorView = ErrorView(dimension: 450, andTitle: title) self.errorView?.center = self.view.center self.view.addSubview(self.errorView!) self.reloadLabel = UILabel() self.reloadLabel?.text = "Press and hold on your remote to reload the content." self.reloadLabel?.font = self.reloadLabel?.font.fontWithSize(25) self.reloadLabel?.sizeToFit() self.reloadLabel?.center = CGPoint(x: CGRectGetMidX(self.errorView!.frame), y: CGRectGetMaxY(self.errorView!.frame)) self.reloadLabel?.center.y += 10 self.reloadLabel?.textColor = UIColor.whiteColor() self.view.addSubview(self.reloadLabel!) //Gestures configuration let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("handleLongPress:")) longPressRecognizer.cancelsTouchesInView = true self.view.addGestureRecognizer(longPressRecognizer) } /* * removeErrorView() * * Removes the error view if existant * */ func removeErrorView() { if self.errorView != nil { self.errorView?.removeFromSuperview() self.errorView = nil } if self.reloadLabel != nil { self.reloadLabel?.removeFromSuperview() self.reloadLabel = nil } } /* * removeErrorView() * * Removes the error view if existant * */ func configureViews(topBarTitle: String, centerView: UIView? = nil, leftView: UIView? = nil, rightView: UIView? = nil) { //do the top bar first self.topBar = TopBarView(frame: CGRectZero, withMainTitle: topBarTitle, centerView: centerView, leftView: leftView, rightView: rightView) self.topBar.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.topBar) //then do the collection view let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Vertical layout.minimumInteritemSpacing = ITEMS_INSETS_X layout.minimumLineSpacing = 50 self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.collectionView.registerClass(ItemCellView.classForCoder(), forCellWithReuseIdentifier: ItemCellView.CELL_IDENTIFIER) self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.contentInset = UIEdgeInsets(top: TOP_BAR_HEIGHT + ITEMS_INSETS_Y, left: ITEMS_INSETS_X, bottom: ITEMS_INSETS_Y, right: ITEMS_INSETS_X) self.view.addSubview(self.collectionView) self.view.bringSubviewToFront(self.topBar) let viewDict = ["topbar" : topBar, "collection" : collectionView] self.view.addConstraint(NSLayoutConstraint(item: topBar, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: TOP_BAR_HEIGHT)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[topbar]", options: [], metrics: nil, views: viewDict)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[collection]|", options: [], metrics: nil, views: viewDict)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[topbar]|", options: [], metrics: nil, views: viewDict)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[collection]|", options: [], metrics: nil, views: viewDict)) } /* * * Implement this on the child view controller to reload content if there was an error * */ func reloadContent() { Logger.Debug("We are reloading the content now") } /* * handleLongPress(recognizer: UILongPressGestureRecognizer) * * This is so that if the content doesn't load the first time around, we can load it again * */ func handleLongPress(recognizer: UILongPressGestureRecognizer) { if recognizer.state == .Began { self.view.removeGestureRecognizer(recognizer) reloadContent() } } /* * * Implement this on the child view controller to load more content * */ func loadMore() { } internal var itemCount: Int { get { return 0 } } func getItemAtIndex(index: Int) -> CellItem { return TwitchGame(id: 0, viewers: 0, channels: 0, name: "nothing", thumbnails: ["hello" : "world"], logos: ["hello" : "world"]) } } //////////////////////////////////////////// // MARK - UICollectionViewDelegate interface //////////////////////////////////////////// extension LoadingViewController : UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.itemCount - 1 { loadMore() } } } ////////////////////////////////////////////////////// // MARK - UICollectionViewDelegateFlowLayout interface ////////////////////////////////////////////////////// extension LoadingViewController: UICollectionViewDelegateFlowLayout { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width = collectionView.bounds.width / CGFloat(NUM_COLUMNS) - CGFloat(ITEMS_INSETS_X * 2) let height = width * HEIGHT_RATIO + (ItemCellView.LABEL_HEIGHT * 2) //There 2 labels, top & bottom return CGSize(width: width, height: height) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: TOP_BAR_HEIGHT + ITEMS_INSETS_Y, left: ITEMS_INSETS_X, bottom: ITEMS_INSETS_Y, right: ITEMS_INSETS_X) } } ////////////////////////////////////////////// // MARK - UICollectionViewDataSource interface ////////////////////////////////////////////// extension LoadingViewController : UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //The number of sections return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // If the count of games allows the current row to be full return self.itemCount } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell : ItemCellView = collectionView.dequeueReusableCellWithReuseIdentifier(ItemCellView.CELL_IDENTIFIER, forIndexPath: indexPath) as! ItemCellView cell.setRepresentedItem(self.getItemAtIndex(indexPath.row)) return cell } }
mit
d0812ad22541e169cb66cf95d1bea3b4
34.026119
188
0.639356
5.059838
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Test/UnitTest/UTProcess.swift
1
810
/* * @file UTProcess.swift * @brief Unit test for Process classes * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import KiwiLibrary import KiwiEngine import CoconutData import JavaScriptCore import Foundation public func UTProcess(context ctxt: KEContext, console cons: CNFileConsole) -> Bool { return UTSemaphore(context: ctxt, console: cons) } private func UTSemaphore(context ctxt: KEContext, console cons: CNFileConsole) -> Bool { let stmt = "let sem = new Semaphore(0) ; " + "sem.signal() ;\n" + "console.log(\"between semaphore\") ;" + "sem.wait() ;\n" if let res = ctxt.evaluateScript(stmt) { cons.print(string: "Semaphore result = \(res.description)\n") return true } else { cons.print(string: "Semaphore result = null\n") return false } }
lgpl-2.1
074e178b8fd32692e855e30a3ecbf401
24.3125
86
0.690123
3.446809
false
false
false
false
pushuhengyang/dyzb
DYZB/DYZB/Classes/Home首页/Views/DYTurnPictureView.swift
1
4211
// // DYTurnPictureView.swift // DYZB // // Created by xuwenhao on 16/11/16. // Copyright © 2016年 xuwenhao. All rights reserved. // import UIKit class DYTurnPictureView: UIView { @IBOutlet weak var collV: UICollectionView! @IBOutlet weak var pageV: UIPageControl! var turnModes = [DYTurnPicModel]() var timer : Timer? override func awakeFromNib() { super.awakeFromNib(); autoresizingMask = UIViewAutoresizing.init(rawValue: 0); collV.register(UINib.init(nibName: "DYPageTurnCell", bundle: nil), forCellWithReuseIdentifier: "DYPageTurnCell") collV.isPagingEnabled = true } override func layoutSubviews() { let layout = collV.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = self.bounds.size; layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 } func reReshLoadData(dataArry : [DYTurnPicModel]) { self.turnModes = dataArry; collV.reloadData(); pageV.hidesForSinglePage = true pageV.numberOfPages = dataArry.count; pageV.currentPage=0 pageV.currentPageIndicatorTintColor = UIColor.orange; pageV.pageIndicatorTintColor = UIColor.white.withAlphaComponent(0.3) collV.scrollToItem(at: IndexPath.init(item: 0, section: 60), at: .left, animated: false) addCycTimer() // DispatchQueue.main.sync { // collV.scrollToItem(at: IndexPath.init(item: 0, section: 60), at: .left, animated: false) // } } class func dyTurnView() -> DYTurnPictureView { return Bundle.main.loadNibNamed("DYTurnPictureView", owner: nil, options: nil)!.first as! DYTurnPictureView } } extension DYTurnPictureView : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.turnModes.count == 0 ? 0 :1000; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (turnModes.count); } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DYPageTurnCell", for: indexPath) as! DYPageTurnCell let model = turnModes[indexPath.item] cell.imageV.kf.setImage(with: URL.init(string: (model.pic_url)), placeholder: UIImage.init(named: "live_cell_default_phone"), options: nil, progressBlock: nil, completionHandler: nil); return cell; } } extension DYTurnPictureView :UICollectionViewDelegate { //这个继承自scroview func scrollViewDidScroll(_ scrollView: UIScrollView) { let off_x = scrollView.contentOffset.x pageV.currentPage = Int((off_x/SCR_W + 0.5).truncatingRemainder(dividingBy: 6.0)) } } extension DYTurnPictureView { func addCycTimer(){ if timer != nil{ removeTime(); } timer = Timer.init(timeInterval: 3, target: self, selector: #selector(self.turnNext), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .defaultRunLoopMode) } private func removeTime(){ if timer != nil{ timer?.invalidate(); timer = nil } } @objc private func turnNext(){ let off_x = collV.contentOffset.x + self.bounds.width/2 let index = Int(off_x/self.bounds.width) if (index + 10 > numberOfSections(in: collV) * collectionView(collV, numberOfItemsInSection: 0)) || index < 10 { collV.scrollToItem(at: IndexPath.init(item: 0, section: 60), at: .left, animated: false) pageV.currentPage = 0 return } collV.scrollRectToVisible(CGRect.init(x: (CGFloat)(index+1) * self.bounds.width, y: 0, width: self.bounds.width, height: self.bounds.height), animated: true) } }
mit
5245bea81f681aee3dd97484fa9530df
26.25974
192
0.620057
4.513978
false
false
false
false
lfaoro/Cast
Carthage/Checkouts/RxSwift/RxExample/RxExample/Services/ImageService.swift
1
2664
// // ImageService.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif #if os(iOS) import UIKit #elseif os(OSX) import Cocoa #endif protocol ImageService { func imageFromURL(URL: NSURL) -> Observable<Image> } class DefaultImageService: ImageService { static let sharedImageService = DefaultImageService() // Singleton let $: Dependencies = Dependencies.sharedDependencies // 1rst level cache let imageCache = NSCache() // 2nd level cache let imageDataCache = NSCache() private init() { // cost is approx memory usage self.imageDataCache.totalCostLimit = 10 * MB self.imageCache.countLimit = 20 } func decodeImage(imageData: NSData) -> Observable<Image> { return just(imageData) .observeSingleOn($.backgroundWorkScheduler) .map { data in let maybeImage = Image(data: data) if maybeImage == nil { // some error throw apiError("Decoding image error") } let image = maybeImage! return image } .observeSingleOn($.mainScheduler) } func imageFromURL(URL: NSURL) -> Observable<Image> { return deferred { let maybeImage = self.imageDataCache.objectForKey(URL) as? Image let decodedImage: Observable<Image> // best case scenario, it's already decoded an in memory if let image = maybeImage { decodedImage = just(image) } else { let cachedData = self.imageDataCache.objectForKey(URL) as? NSData // does image data cache contain anything if let cachedData = cachedData { decodedImage = self.decodeImage(cachedData) } else { // fetch from network decodedImage = self.$.URLSession.rx_data(NSURLRequest(URL: URL)) .doOn(next: { data in self.imageDataCache.setObject(data, forKey: URL) }) .flatMap(self.decodeImage) } } return decodedImage.doOn(next: { image in self.imageCache.setObject(image, forKey: URL) }) } } }
mit
68159228538e6aae64ac049819bdcf15
27.340426
84
0.526652
5.338677
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/VIPER/Authorization/Assembly/AuthorizationAssemblyImpl.swift
1
1549
import UIKit import Marshroute final class AuthorizationAssemblyImpl: BaseAssembly, AuthorizationAssembly { // MARK: - AuthorizationAssembly func module(routerSeed: RouterSeed) -> (viewController: UIViewController, moduleInput: AuthorizationModuleInput) { registerModuleAsBeingTracked( transitionsHandlerBox: routerSeed.transitionsHandlerBox, transitionId: routerSeed.transitionId ) let interactor = AuthorizationInteractorImpl() let router = AuthorizationRouterIphone( assemblyFactory: assemblyFactory, routerSeed: routerSeed ) let presenter = AuthorizationPresenter( interactor: interactor, router: router ) let viewController = AuthorizationViewController() viewController.addDisposable(presenter) presenter.view = viewController return (viewController, presenter) } // MARK: - Private private func registerModuleAsBeingTracked( transitionsHandlerBox: TransitionsHandlerBox, transitionId: TransitionId) { // debugPrint(transitionUserId) let authorizationModuleRegisteringService = serviceFactory.authorizationModuleRegisteringService() authorizationModuleRegisteringService.registerAuthorizationModuleAsBeingTracked( transitionsHandlerBox: transitionsHandlerBox, transitionId: transitionId ) } }
mit
7b78012446c775a8efe88beb15b72ef6
31.270833
106
0.666236
6.734783
false
false
false
false
avito-tech/Marshroute
Marshroute/Sources/Transitions/TransitionAnimations/ModalNavigation/Presentation/ModalNavigationPresentationAnimationContext.swift
1
2007
import UIKit /// Описание параметров анимаций прямого модального перехода на UINavigationController public struct ModalNavigationPresentationAnimationContext { /// контроллер, на который нужно осуществить прямой модальный переход public let targetViewController: UIViewController /// навигационный контроллер, на который нужно осуществить прямой модальный переход public let targetNavigationController: UINavigationController /// контроллер, с которого нужно осуществить прямой модальный переход public let sourceViewController: UIViewController public init( targetViewController: UIViewController, targetNavigationController: UINavigationController, sourceViewController: UIViewController) { self.targetViewController = targetViewController self.targetNavigationController = targetNavigationController self.sourceViewController = sourceViewController } public init?( modalNavigationPresentationAnimationLaunchingContext: ModalNavigationPresentationAnimationLaunchingContext) { guard let targetViewController = modalNavigationPresentationAnimationLaunchingContext.targetViewController else { return nil } guard let targetNavigationController = modalNavigationPresentationAnimationLaunchingContext.targetNavigationController else { return nil } guard let sourceViewController = modalNavigationPresentationAnimationLaunchingContext.sourceViewController else { return nil } self.targetViewController = targetViewController self.targetNavigationController = targetNavigationController self.sourceViewController = sourceViewController } }
mit
7ffca371098b874be2841adbf95db298
43.25
126
0.765537
6.941176
false
false
false
false
kenada/advent-of-code
tests/2015/Day_7_Tests.swift
1
9991
// // Day_7_Tests.swift // Advent of Code 2015 // // Copyright © 2016 Randy Eckenrode // // 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. // @testable import Advent_of_Code_2015 import XCTest class Day_7_Lexer_Tests: XCTestCase { func testLiteralStore() { Day_7_Lexer_Tests.testParse("1 -> b", expectedResults: .number(1), .assignment, .wire("b")) } func testWireCopy() { Day_7_Lexer_Tests.testParse("a -> b", expectedResults: .wire("a"), .assignment, .wire("b")) } func testNot() { Day_7_Lexer_Tests.testParse("NOT a -> b", expectedResults: .not, .wire("a"), .assignment, .wire("b")) } func testAnd() { Day_7_Lexer_Tests.testParse("1 AND b -> b", expectedResults: .number(1), .and, .wire("b"), .assignment, .wire("b")) } func testOr() { Day_7_Lexer_Tests.testParse("a OR 2 -> b", expectedResults: .wire("a"), .or, .number(2), .assignment, .wire("b")) } func testLeftShift() { Day_7_Lexer_Tests.testParse("c LSHIFT d -> b", expectedResults: .wire("c"), .leftShift, .wire("d"), .assignment, .wire("b")) } func testRightShift() { Day_7_Lexer_Tests.testParse("1 RSHIFT 2 -> q", expectedResults: .number(1), .rightShift, .number(2), .assignment, .wire("q")) } func parseFailure() { Day_7_Lexer_Tests.testParse("fsldfjasldfk333j", expectedResults: .wire("fsldfjasldfk333j")) } static func testParse(_ input: String, expectedResults: Symbol...) { let result = lex(input: input) XCTAssertEqual(result.count, expectedResults.count, "lengths match") for (symbol, expectedSymbol) in zip(result, expectedResults) { XCTAssertEqual(symbol, expectedSymbol, "symbol sequences match") } } } class Day_7_Parser_Tests: XCTestCase { func testLiteral() { Day_7_Parser_Tests.test([.number(1), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .literal(1))) } func testWire() { Day_7_Parser_Tests.test([.wire("a"), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .reference("a"))) } func testAnd() { Day_7_Parser_Tests.test([.number(1), .and, .wire("b"), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .and(.literal(1), .reference("b")))) } func testOr() { Day_7_Parser_Tests.test([.wire("a"), .or, .number(2), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .or(.reference("a"), .literal(2)))) } func testNot() { Day_7_Parser_Tests.test([.not, .wire("a"), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .not(.reference("a")))) } func testLeftShift() { Day_7_Parser_Tests.test([.wire("c"), .leftShift, .wire("d"), .assignment, .wire("b")], expectedResults: .store(wire: "b", expression: .leftShift(.reference("c"), .reference("d")))) } func testRightShift() { Day_7_Parser_Tests.test([.number(1), .rightShift, .number(2), .assignment, .wire("q")], expectedResults: .store(wire: "q", expression: .rightShift(.literal(1), .literal(2)))) } func testInvalidAssignment() { Day_7_Parser_Tests.testParseError(input: .number(1), .assignment, .number(1), expectedException: .invalidAssignment) } func testExpectedAssignment() { Day_7_Parser_Tests.testParseError(input: .number(1), .and, .number(2), expectedException: .expectedAssignment) } func testExpectedOperator() { Day_7_Parser_Tests.testParseError(input: .number(1), expectedException: .expectedOperator) } func testUnexpectedSymbol() { Day_7_Parser_Tests.testParseError(input: .number(1), .and, .number(1), .assignment, .wire("a"), .number(5), expectedException: .unexpectedSymbol) } func testMissingValue() { Day_7_Parser_Tests.testParseError(input: .number(5), .assignment, expectedException: .missingValue) } func testExpectedLiteralOrWire() { Day_7_Parser_Tests.testParseError(input: .assignment, expectedException: .expectedLiteralOrWire) } static func test(_ input: [Symbol], expectedResults: Statement) { let result = try! parse(symbols: input) switch (result, expectedResults) { case let (.store(wire, expression), .store(expectedWire, expectedExpression)): XCTAssertEqual(wire, expectedWire, "wires match") XCTAssertEqual(expression, expectedExpression, "expressions match") } } static func testParseError(input: Symbol..., expectedException: ParseError) { do { _ = try parse(symbols: input) XCTAssert(false, "expecting exception") } catch let exp as ParseError { XCTAssertEqual(exp, expectedException, "expected exception thrown") } catch { XCTAssert(false, "unexception exception not thrown") } } } class Day_7_VM_Tests: XCTestCase { let vm = VirtualMachine() override func setUp() { vm.reset() } func testStore() { let expectedResults: [Wire: UInt16] = [ "x": 123, "y": 456 ] let program: [Statement] = [ .store(wire: "x", expression: .literal(123)), .store(wire: "y", expression: .literal(456)) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testAnd() { let expectedResults: [Wire: UInt16] = [ "x": 1, "y": 3, "z": 1 ] let program: [Statement] = [ .store(wire: "x", expression: .literal(1)), .store(wire: "y", expression: .literal(3)), .store(wire: "z", expression: .and(.reference("x"), .reference("y"))) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testOr() { let expectedResults: [Wire: UInt16] = [ "x": 1, "y": 2, "z": 3 ] let program: [Statement] = [ .store(wire: "x", expression: .literal(1)), .store(wire: "y", expression: .literal(2)), .store(wire: "z", expression: .or(.reference("x"), .reference("y"))) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testNot() { let expectedResults: [Wire: UInt16] = [ "x": 1, "y": 65534, ] let program: [Statement] = [ .store(wire: "x", expression: .literal(1)), .store(wire: "y", expression: .not(.reference("x"))) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testLeftShift() { let expectedResults: [Wire: UInt16] = [ "x": 1, "y": 2, "z": 4 ] let program: [Statement] = [ .store(wire: "x", expression: .literal(1)), .store(wire: "y", expression: .literal(2)), .store(wire: "z", expression: .leftShift(.reference("x"), .reference("y"))) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testRightShift() { let expectedResults: [Wire: UInt16] = [ "x": 4, "y": 2, "z": 1 ] let program: [Statement] = [ .store(wire: "x", expression: .literal(4)), .store(wire: "y", expression: .literal(2)), .store(wire: "z", expression: .rightShift(.reference("x"), .reference("y"))) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } func testSubExpressions() { let expectedResults: [Wire: UInt16] = [ "q": 3 ] let program: [Statement] = [ .store(wire: "q", expression: .and(.not(.and(.reference("x"), .reference("y"))), .or(.reference("x"), .reference("y")))), .store(wire: "x", expression: .literal(5)), .store(wire: "y", expression: .literal(6)) ] Day_7_VM_Tests.test(program, virtualMachine: vm, expectedResults: expectedResults) } static func test<Program: Sequence>( _ program: Program, virtualMachine vm: VirtualMachine, expectedResults: [Wire: UInt16]) where Program.Iterator.Element == Statement { vm.load(program: program) for (wire, expectedValue) in expectedResults { XCTAssertEqual(vm.read(wire: wire), expectedValue, "\(wire) value == expectedResults[\(wire)]") } } }
mit
7a7b7a263e9f93e91dbac76242d6db4b
36.137546
141
0.582282
3.896256
false
true
false
false
iXieYi/Weibo_DemoTest
Weibo_DemoTest/Weibo_DemoTest/VisitorTableViewController.swift
1
2765
// // VisitorTableViewController.swift // Weibo_DemoTest // // Created by 谢毅 on 16/12/11. // Copyright © 2016年 xieyi. All rights reserved. // /// SVProgressHUB import UIKit class VisitorTableViewController: UITableViewController { /// 用户登录标记 private var userLogin = UserAccountViewModel.sharedUserAccount.logon /// 访客视图 //每个控制器有各自不同的访客视图 var visitorView: VisitorView? //定义属性可以为外界控制器所访问 //不能使用懒加载的原因是:在每个子控制器中,都会对visitorView进行判断,如果使用 //懒加载,当判断为空时,访客视图依旧会被创建出来 //lazy var visitorView: VisitorView? = VisitorView() override func viewDidLoad() { super.viewDidLoad() userLogin ?super.loadView():setupVisitorView() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // print(visitorView) } @objc func setupVisitorView(){ visitorView = VisitorView() //设置代理 // visitorView?.delegate = self view = visitorView //添加监听方法 visitorView?.registerButton.addTarget(self, action: "visitorViewDidRegister", forControlEvents: .TouchUpInside) visitorView?.loginButton.addTarget(self, action: "visitorViewDidLogin", forControlEvents: .TouchUpInside) //设置导航栏按钮,plain 是为纯文本提供的样式 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .Plain, target: self, action: "visitorViewDidRegister") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .Plain, target: self, action: "visitorViewDidLogin") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } } //MARK: - 访客视图监听方法 extension VisitorTableViewController{ func visitorViewDidRegister() { print("注册") } func visitorViewDidLogin() { print("登录") let vc = OAuthViewController() let nav = UINavigationController(rootViewController: vc) presentViewController(nav, animated: true, completion: nil) } }
mit
918a21b19b7c0602dd30cd2f068b7857
26.555556
134
0.675
4.69697
false
false
false
false
oceanfive/swift
swift_two/swift_two/Classes/ViewModel/HYAccountViewModel.swift
1
1786
// // HYAccountViewModel.swift // swift_two // // Created by ocean on 16/6/18. // Copyright © 2016年 ocean. All rights reserved. // import UIKit import AFNetworking class HYAccountViewModel: NSObject { //获取accessToken - 使用第三方框架 class func getAccessToken(code: String){ let manager = AFHTTPSessionManager() //MARK: - 如果AFN提示不接受文件类型,那么需要自己手动添加 manager.responseSerializer.acceptableContentTypes?.insert("text/plain") let dict = ["client_id": client_id, "client_secret": client_secret, "grant_type": grant_type, "code": code, "redirect_uri": redirect_uri] manager.POST(accessTokenURLString, parameters: dict, success: { (task, response) -> Void in //保存用户账号信息 HYAccountTool.saveAccount(response! as! [String : AnyObject]) //MARK: - 设置用户登录标记为真 HYLoginViewController.loginFlag = true //切换窗口到新特性窗口 let keyWindow = UIApplication.sharedApplication().keyWindow keyWindow?.rootViewController = HYNewFeatureViewController() //MARK: - 用MJ第三方框架转模型时,如果为nil会崩溃,这时需要添加一个判断,是否为空的判断 /* Optional({ "access_token" = "2.00dBcfVDtOFu4E6c7ef71c44GliulB"; "expires_in" = 157679999; "remind_in" = 157679999; uid = 3216382533; }) */ }) { (errorTask, error) -> Void in print("error---\(error)") } } }
mit
4c02dcdb93af5e8f45a51e6a7120769a
28.5
145
0.552417
4.225464
false
false
false
false
maxkonovalov/MKRingProgressView
Example/ActivityRingsExample/MKRingProgressGroupView.swift
1
3132
/* The MIT License (MIT) Copyright (c) 2015 Max Konovalov 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 MKRingProgressView import UIKit @IBDesignable class RingProgressGroupView: UIView { let ring1 = RingProgressView() let ring2 = RingProgressView() let ring3 = RingProgressView() @IBInspectable var ring1StartColor: UIColor = .red { didSet { ring1.startColor = ring1StartColor } } @IBInspectable var ring1EndColor: UIColor = .blue { didSet { ring1.endColor = ring1EndColor } } @IBInspectable var ring2StartColor: UIColor = .red { didSet { ring2.startColor = ring2StartColor } } @IBInspectable var ring2EndColor: UIColor = .blue { didSet { ring2.endColor = ring2EndColor } } @IBInspectable var ring3StartColor: UIColor = .red { didSet { ring3.startColor = ring3StartColor } } @IBInspectable var ring3EndColor: UIColor = .blue { didSet { ring3.endColor = ring3EndColor } } @IBInspectable var ringWidth: CGFloat = 20 { didSet { ring1.ringWidth = ringWidth ring2.ringWidth = ringWidth ring3.ringWidth = ringWidth setNeedsLayout() } } @IBInspectable var ringSpacing: CGFloat = 2 { didSet { setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { addSubview(ring1) addSubview(ring2) addSubview(ring3) } override func layoutSubviews() { super.layoutSubviews() ring1.frame = bounds ring2.frame = bounds.insetBy(dx: ringWidth + ringSpacing, dy: ringWidth + ringSpacing) ring3.frame = bounds.insetBy(dx: 2 * ringWidth + 2 * ringSpacing, dy: 2 * ringWidth + 2 * ringSpacing) } }
mit
bc5ffc99ed712c564395f4fd7973b2b2
28.271028
110
0.641762
4.599119
false
false
false
false
nalexn/ViewInspector
Sources/ViewInspector/SwiftUI/Section.swift
1
2838
import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension ViewType { struct Section: KnownViewType { public static let typePrefix: String = "Section" } } // MARK: - Content Extraction @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.Section: MultipleViewContent { public static func children(_ content: Content) throws -> LazyGroup<Content> { let view = try Inspector.attribute(label: "content", value: content.view) return try Inspector.viewsInContainer(view: view, medium: content.medium) } } // MARK: - Extraction from SingleViewContent parent @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View: SingleViewContent { func section() throws -> InspectableView<ViewType.Section> { return try .init(try child(), parent: self) } } // MARK: - Extraction from MultipleViewContent parent @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View: MultipleViewContent { func section(_ index: Int) throws -> InspectableView<ViewType.Section> { return try .init(try child(at: index), parent: self, index: index) } } // MARK: - Non Standard Children @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.Section: SupplementaryChildren { static func supplementaryChildren(_ parent: UnwrappedView) throws -> LazyGroup<SupplementaryView> { return .init(count: 2) { index in let medium = parent.content.medium.resettingViewModifiers() if index == 0 { let child = try Inspector.attribute(label: "header", value: parent.content.view) let content = try Inspector.unwrap(content: Content(child, medium: medium)) return try InspectableView<ViewType.ClassifiedView>(content, parent: parent, call: "header()") } else { let child = try Inspector.attribute(label: "footer", value: parent.content.view) let content = try Inspector.unwrap(content: Content(child, medium: medium)) return try InspectableView<ViewType.ClassifiedView>(content, parent: parent, call: "footer()") } } } } // MARK: - Custom Attributes @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View == ViewType.Section { func header() throws -> InspectableView<ViewType.ClassifiedView> { return try View.supplementaryChildren(self).element(at: 0) .asInspectableView(ofType: ViewType.ClassifiedView.self) } func footer() throws -> InspectableView<ViewType.ClassifiedView> { return try View.supplementaryChildren(self).element(at: 1) .asInspectableView(ofType: ViewType.ClassifiedView.self) } }
mit
873e82137179fdbee55a372cdac61255
36.342105
110
0.671952
4.306525
false
false
false
false
lorentey/GlueKit
Tests/GlueKitTests/Bookshelf.swift
1
4314
// // Bookshelf.swift // GlueKit // // Created by Károly Lőrentey on 2016-10-02. // Copyright © 2015–2017 Károly Lőrentey. // import Foundation import GlueKit import XCTest // Let's suppose we're writing an app for maintaining a catalogue for your books. // Here is what the model could look like. private class Author: Hashable { let name: Variable<String> let yearOfBirth: Variable<Int> init(name: String, yearOfBirth: Int) { self.name = .init(name) self.yearOfBirth = .init(yearOfBirth) } var hashValue: Int { return name.value.hashValue } static func == (a: Author, b: Author) -> Bool { return a.name.value == b.name.value && a.yearOfBirth.value == b.yearOfBirth.value } } private class Book: Hashable { let title: Variable<String> let authors: SetVariable<Author> let publicationYear: Variable<Int> let pages: Variable<Int> init(title: String, authors: Set<Author>, publicationYear: Int, pages: Int) { self.title = .init(title) self.authors = SetVariable(authors) self.publicationYear = .init(pages) self.pages = .init(pages) } var hashValue: Int { return title.value.hashValue } static func == (a: Book, b: Book) -> Bool { return (a.title.value == b.title.value && a.authors.value == b.authors.value && a.publicationYear.value == b.publicationYear.value && a.pages.value == b.pages.value) } } private class Bookshelf { let location: Variable<String> let books: ArrayVariable<Book> init(location: String, books: [Book] = []) { self.location = .init(location) self.books = .init(books) } } private struct Fixture { let stephenson = Author(name: "Neal Stephenson", yearOfBirth: 1959) let pratchett = Author(name: "Terry Pratchett", yearOfBirth: 1948) let gaiman = Author(name: "Neil Gaiman", yearOfBirth: 1960) let knuth = Author(name: "Donald E. Knuth", yearOfBirth: 1938) lazy var colourOfMagic: Book = .init(title: "The Colour of Magic", authors: [self.pratchett], publicationYear: 1983, pages: 206) lazy var smallGods: Book = .init(title: "Small Gods", authors: [self.pratchett], publicationYear: 1992, pages: 284) lazy var seveneves: Book = .init(title: "Seveneves", authors: [self.stephenson], publicationYear: 2015, pages: 880) lazy var goodOmens: Book = .init(title: "Good Omens", authors: [self.pratchett, self.gaiman], publicationYear: 1990, pages: 288) lazy var americanGods: Book = .init(title: "American Gods", authors: [self.gaiman], publicationYear: 2001, pages: 465) lazy var cryptonomicon: Book = .init(title: "Cryptonomicon", authors: [self.stephenson], publicationYear: 1999, pages: 918) lazy var anathem: Book = .init(title: "Anathem", authors: [self.stephenson], publicationYear: 2008, pages: 928) lazy var texBook: Book = .init(title: "The TeXBook", authors: [self.knuth], publicationYear: 1984, pages: 483) lazy var taocp1: Book = .init(title: "The Art of Computer Programming vol. 1: Fundamental Algorithms. 3rd ed.", authors: [self.knuth], publicationYear: 1997, pages: 650) lazy var topShelf: Bookshelf = .init(location: "Top", books: [self.colourOfMagic, self.smallGods, self.seveneves, self.goodOmens, self.americanGods]) lazy var bottomShelf: Bookshelf = .init(location: "Bottom", books: [self.cryptonomicon, self.anathem, self.texBook, self.taocp1]) lazy var shelves: ArrayVariable<Bookshelf> = [self.topShelf, self.bottomShelf] } class BookshelfTests: XCTestCase { func testAllTitles() { var f = Fixture() // Let's get an array of the title of each book in the library. let allTitles = f.shelves.flatMap{$0.books}.map{$0.title} XCTAssertEqual(allTitles.value, ["The Colour of Magic", "Small Gods", "Seveneves", "Good Omens", "American Gods", "Cryptonomicon", "Anathem", "The TeXBook", "The Art of Computer Programming vol. 1: Fundamental Algorithms. 3rd ed."]) } func testBooksByStephenson() { var f = Fixture() let booksByStephenson = f.shelves.flatMap{$0.books}.filter { book in book.authors.observableContains(f.stephenson) } XCTAssertEqual(booksByStephenson.value, [f.seveneves, f.cryptonomicon, f.anathem]) } }
mit
6d8848af5ce12b1fd34f588b18a0eee1
40.815534
240
0.677966
3.404743
false
false
false
false
nate-parrott/aamoji
aamoji/AppDelegate.swift
1
2723
// // AppDelegate.swift // aamoji // // Created by Nate Parrott on 5/19/15. // Copyright (c) 2015 Nate Parrott. All rights reserved. // import Cocoa import WebKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationWillFinishLaunching(aNotification: NSNotification) { window.titleVisibility = .Hidden window.titlebarAppearsTransparent = true _updateUI() } func applicationWillTerminate(aNotification: NSNotification) { } let inserter = AamojiInserter() @IBOutlet var button: NSButton! @IBOutlet var headline: NSTextField! @IBOutlet var subtitle: NSTextField! @IBOutlet var postInstallButtons: NSView! @IBOutlet var shortcutsListWindow: NSWindow! @IBOutlet var shortcutsListWebview: WebView! @IBAction func toggleInserted(sender: NSButton) { if let inserted = inserter.inserted { inserter.inserted = !inserted } else { println("ERROR") } _updateUI() delay(0.5, { () -> () in // just in case (seems to be necessary sometimes) self._updateUI() }) } private func _updateUI() { if let inserted = inserter.inserted { button.enabled = true button.title = inserted ? "💔 Remove aamoji shortcuts 💔" : "✨ Add aamoji shortcuts 💫" if inserted { headline.stringValue = "⚡ aamoji is on ⚡" subtitle.stringValue = "You'll need to re-launch your apps before aamoji will work inside them." } else { headline.stringValue = "Type emoji in any app*" subtitle.stringValue = "Prefix the name of an emoji with \"aa\", and it'll autocorrect to the emoji itself." } postInstallButtons.hidden = !inserted } else { button.enabled = false button.title = "🚨 Error 🚨" } } @IBAction func launchNotes(sender: NSButton) { var launchDelay: Double = NSWorkspace.sharedWorkspace().terminateApp("com.apple.Notes") ? 1 : 0 if let notesPath = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier("com.apple.Notes") { delay(launchDelay, { () -> () in NSWorkspace.sharedWorkspace().launchApplication(notesPath) }) } } @IBAction func showShortcutsList(sender: NSButton) { shortcutsListWebview.mainFrame.loadHTMLString(inserter.shortcutListHTML(), baseURL: NSURL(string: "about:blank")) shortcutsListWindow.makeKeyAndOrderFront(sender) } }
mit
8f990ae491b96304d544a4d34b979797
31.95122
124
0.618431
4.67474
false
false
false
false
alexxjk/ProtocolUI.Swift
ProtocolUISwift/ProtocolUISwift/GradientView.swift
1
5912
// // GradientView.swift // ProtocolUISwift // // Created by Alexander Martirosov on 8/21/17. // Copyright © 2017 Alexander Martirosov. All rights reserved. // import UIKit open class GradientView: UIView { // MARK: - Types /// The mode of the gradient. public enum Mode { /// A linear gradient. case linear /// A radial gradient. case radial } /// The direction of the gradient. public enum Direction { /// The gradient is vertical. case vertical /// The gradient is horizontal case horizontal } // MARK: - Properties /// An optional array of `UIColor` objects used to draw the gradient. If the value is `nil`, the `backgroundColor` /// will be drawn instead of a gradient. The default is `nil`. open var colors: [UIColor]? { didSet { updateGradient() } } /// An array of `UIColor` objects used to draw the dimmed gradient. If the value is `nil`, `colors` will be /// converted to grayscale. This will use the same `locations` as `colors`. If length of arrays don't match, bad /// things will happen. You must make sure the number of dimmed colors equals the number of regular colors. /// /// The default is `nil`. open var dimmedColors: [UIColor]? { didSet { updateGradient() } } /// Automatically dim gradient colors when prompted by the system (i.e. when an alert is shown). /// /// The default is `true`. open var automaticallyDims: Bool = true /// An optional array of `CGFloat`s defining the location of each gradient stop. /// /// The gradient stops are specified as values between `0` and `1`. The values must be monotonically increasing. If /// `nil`, the stops are spread uniformly across the range. /// /// Defaults to `nil`. open var locations: [CGFloat]? { didSet { updateGradient() } } /// The mode of the gradient. The default is `.Linear`. @IBInspectable open var mode: Mode = .linear { didSet { setNeedsDisplay() } } /// The direction of the gradient. Only valid for the `Mode.Linear` mode. The default is `.Vertical`. @IBInspectable open var direction: Direction = .vertical { didSet { setNeedsDisplay() } } // MARK: - UIView override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let size = bounds.size // Gradient if let gradient = gradient { let options: CGGradientDrawingOptions = [.drawsAfterEndLocation] if mode == .linear { let startPoint = direction == .vertical ? CGPoint(x: 0.0, y: size.height) : CGPoint.zero let endPoint = direction == .vertical ? CGPoint(x: 0, y: 0) : CGPoint(x: size.width, y: 0) context?.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: options) } else { let center = CGPoint(x: bounds.midX, y: bounds.midY) context?.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: min(size.width, size.height) / 2, options: options) } } } override open func tintColorDidChange() { super.tintColorDidChange() if automaticallyDims { updateGradient() } } override open func didMoveToWindow() { super.didMoveToWindow() contentMode = .redraw } // MARK: - Private fileprivate var gradient: CGGradient? func updateGradient() { gradient = nil setNeedsDisplay() let colors = gradientColors() if let colors = colors { let colorSpace = CGColorSpaceCreateDeviceRGB() let colorSpaceModel = colorSpace.model let gradientColors = colors.map { (color: UIColor) -> AnyObject! in let cgColor = color.cgColor let cgColorSpace = cgColor.colorSpace ?? colorSpace // The color's color space is RGB, simply add it. if cgColorSpace.model == colorSpaceModel { return cgColor as AnyObject! } // Convert to RGB. There may be a more efficient way to do this. var red: CGFloat = 0 var blue: CGFloat = 0 var green: CGFloat = 0 var alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red, green: green, blue: blue, alpha: alpha).cgColor as AnyObject! } as NSArray gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors, locations: locations) } } fileprivate func gradientColors() -> [UIColor]? { if tintAdjustmentMode == .dimmed { if let dimmedColors = dimmedColors { return dimmedColors } if automaticallyDims { if let colors = colors { return colors.map { var hue: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 $0.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: 0, brightness: brightness, alpha: alpha) } } } } return colors } }
mit
620afc15023ce64a8c6e8bd4897a6f2f
31.838889
172
0.541702
5.20793
false
false
false
false
cornerstonecollege/402
Digby/class_2/SwiftExploring2/SwiftExploring2/ViewController.swift
1
1240
// // ViewController.swift // SwiftExploring2 // // Created by Digby Andrews on 2016-06-14. // Copyright © 2016 Digby Andrews. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lblColor: UILabel! @IBOutlet weak var hexLabel: UILabel! @IBAction func colorBtnClicked(sender: AnyObject) { let randRed = arc4random_uniform(255) let randGreen = arc4random_uniform(255) let randBlue = arc4random_uniform(255) lblColor.text = "Red:\(randRed) Green:\(randGreen) Blue:\(randBlue)" hexLabel.text = "#\(String(format: "%x", randRed))\(String(format:"%x", randGreen))\(String(format:"%x",randBlue))" let swiftColor = UIColor(red:CGFloat(randRed)/255.0, green: CGFloat(randGreen)/255.0, blue: CGFloat(randBlue)/255.0, alpha: 1.0) self.view.backgroundColor = swiftColor } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
de0aaa6f28bec6f766acd1a8902d62fe
28.5
136
0.643261
4.089109
false
false
false
false
pgorzelany/ScratchCardView
ScratchCardView/Classes/ScratchCardView.swift
1
5801
// // ScratchCardView.swift // Pods // // Created by Piotr Gorzelany on 08/04/2017. // Copyright © 2017 Piotr Gorzelany. All rights reserved. // import UIKit /// The ScratchCardViewDelegate interface @objc public protocol ScratchCardViewDelegate: class { /// The top view of the scratch card. Covers the content view. /// /// - Parameter scratchCardView: the view that asks for the cover view. /// - Returns: The method should return a cover view for the scratch card func coverView(for scratchCardView: ScratchCardView) -> UIView /// The content view of the scratch card. /// It is initialy covered and is revealed after scratching the view. /// /// - Parameter scratchCardView: The view that asks for the content view. /// - Returns: The method should return a content view for the scratch card func contentView(for scratchCardView: ScratchCardView) -> UIView /// Gets called when scratching starts /// /// - Parameters: /// - view: The scratch card /// - point: The point at which the scratches started. In the scratch card coordinate system @objc optional func scratchCardView(_ view: ScratchCardView, didStartScratchingAt point: CGPoint) /// Called when scratches are in progress /// /// - Parameters: /// - view: The scratch card /// - point: The point to which the scratching finger moved. In the scratch card coordinate system @objc optional func scratchCardView(_ view: ScratchCardView, didScratchTo point: CGPoint) /// Called when current scratches stop (user lifts his finger) /// /// - Parameter view: The scratch card @objc optional func scratchCardViewDidEndScratching(_ view: ScratchCardView) } /// The ScratchCardView open class ScratchCardView: UIView { // MARK: Properties /// The width of the scratch. Default is 30. @IBInspectable public var scratchWidth: CGFloat = 30 { didSet { canvasMaskView.lineWidth = scratchWidth } } /// The percent of total view area that is revealed by the scratches. /// Computing this property requires heavy CPU work, /// consider doing it on a backgroung thread if used frequently. /// /// Returns: a value between 0 and 1 public var scratchPercent: Double { return getScratchPercent() } private var coverViewContainer = UIView() private var contentViewContainer = UIView() private var canvasMaskView = CanvasView() // MARK: Delegate /// The delegate for the ScratchCardView /// /// The delegate is responsible for providing the content and cover views. /// It also gets notified of important events like scratch start or end. public weak var delegate: ScratchCardViewDelegate? { didSet { reloadView() } } // MARK: Lifecycle override init(frame: CGRect) { super.init(frame: frame) configureView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override open func layoutSubviews() { super.layoutSubviews() canvasMaskView.frame = contentViewContainer.bounds } // MARK: Configuration private func configureView() { self.addGestureRecognizers() configureMaskView() contentViewContainer.backgroundColor = UIColor.clear coverViewContainer.backgroundColor = UIColor.clear addSubviewFullscreen(coverViewContainer) addSubviewFullscreen(contentViewContainer) } private func configureMaskView() { canvasMaskView.delegate = self canvasMaskView.backgroundColor = UIColor.clear canvasMaskView.strokeColor = UIColor.black canvasMaskView.lineWidth = scratchWidth contentViewContainer.mask = canvasMaskView } private func addGestureRecognizers() { let panRecognizer = UIPanGestureRecognizer( target: canvasMaskView, action: #selector(canvasMaskView.panGestureRecognized) ) self.addGestureRecognizer(panRecognizer) } // MARK: Private methods private func getScratchPercent() -> Double { // Since the transparency is inverted, the cover view gets transparent if the mask is not transparent // So we need to check how many pixels are NOT transparent in the mask return (1.0 - canvasMaskView.getTransparentPixelsPercent()) } // MARK: Public Methods /// Clears the scratches from the current view public func clear() { canvasMaskView.clear() } /// Clears the scratches and asks the delegate for a new cover and contant views public func reloadView() { clear() (coverViewContainer.subviews + contentViewContainer.subviews).forEach { (subview) in subview.removeFromSuperview() } guard let coverView = delegate?.coverView(for: self), let contentView = delegate?.contentView(for: self) else { return } coverViewContainer.addSubviewFullscreen(coverView) contentViewContainer.addSubviewFullscreen(contentView) } } extension ScratchCardView: CanvasViewDelegate, UITableViewDelegate { func canvasViewDidStartDrawing(_ view: CanvasView, at point: CGPoint) { delegate?.scratchCardView?(self, didStartScratchingAt: point) } func canvasViewDidAddLine(_ view: CanvasView, to point: CGPoint) { delegate?.scratchCardView?(self, didScratchTo: point) } func canvasViewDidEndDrawing(_ view: CanvasView) { delegate?.scratchCardViewDidEndScratching?(self) } }
mit
cf64192c1e783dbeb6d06390352ed590
32.333333
109
0.663621
5.047868
false
false
false
false
natecook1000/swift
test/SILGen/lazy_globals.swift
3
4268
// RUN: %target-swift-emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s // CHECK: sil private @globalinit_[[T:.*]]_func0 : $@convention(c) () -> () { // CHECK: alloc_global @$S12lazy_globals1xSiv // CHECK: [[XADDR:%.*]] = global_addr @$S12lazy_globals1xSivp : $*Int // CHECK: store {{%.*}} to [trivial] [[XADDR]] : $*Int // CHECK: sil hidden [global_init] @$S12lazy_globals1xSivau : $@convention(thin) () -> Builtin.RawPointer { // CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token0 : $*Builtin.Word // CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer // CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func0 : $@convention(c) () -> () // CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $() // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S12lazy_globals1xSivp : $*Int // CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer // CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer // CHECK: } var x: Int = 0 // CHECK: sil private @globalinit_[[T:.*]]_func1 : $@convention(c) () -> () { // CHECK: alloc_global @$S12lazy_globals3FooV3fooSivpZ // CHECK: [[XADDR:%.*]] = global_addr @$S12lazy_globals3FooV3fooSivpZ : $*Int // CHECK: store {{.*}} to [trivial] [[XADDR]] : $*Int // CHECK: return struct Foo { // CHECK: sil hidden [global_init] @$S12lazy_globals3FooV3fooSivau : $@convention(thin) () -> Builtin.RawPointer { // CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token1 : $*Builtin.Word // CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer // CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func1 : $@convention(c) () -> () // CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $() // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S12lazy_globals3FooV3fooSivpZ : $*Int // CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer // CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer static var foo: Int = 22 static var computed: Int { return 33 } static var initialized: Int = 57 } // CHECK: sil private @globalinit_[[T:.*]]_func3 : $@convention(c) () -> () { // CHECK: alloc_global @$S12lazy_globals3BarO3barSivpZ // CHECK: [[XADDR:%.*]] = global_addr @$S12lazy_globals3BarO3barSivpZ : $*Int // CHECK: store {{.*}} to [trivial] [[XADDR]] : $*Int // CHECK: return enum Bar { // CHECK: sil hidden [global_init] @$S12lazy_globals3BarO3barSivau : $@convention(thin) () -> Builtin.RawPointer { // CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token3 : $*Builtin.Word // CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer // CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func3 : $@convention(c) () -> () // CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(c) () -> ()) : $() // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S12lazy_globals3BarO3barSivpZ : $*Int // CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer // CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer static var bar: Int = 33 } // We only emit one initializer function per pattern binding, which initializes // all of the bound variables. func f() -> (Int, Int) { return (1, 2) } // CHECK: sil private @globalinit_[[T]]_func4 : $@convention(c) () -> () { // CHECK: function_ref @$S12lazy_globals1fSi_SityF : $@convention(thin) () -> (Int, Int) // CHECK: sil hidden [global_init] @$S12lazy_globals2a1Sivau : $@convention(thin) () -> Builtin.RawPointer // CHECK: function_ref @globalinit_[[T]]_func4 : $@convention(c) () -> () // CHECK: global_addr @$S12lazy_globals2a1Sivp : $*Int // CHECK: sil hidden [global_init] @$S12lazy_globals2b1Sivau : $@convention(thin) () -> Builtin.RawPointer { // CHECK: function_ref @globalinit_[[T]]_func4 : $@convention(c) () -> () // CHECK: global_addr @$S12lazy_globals2b1Sivp : $*Int var (a1, b1) = f() var computed: Int { return 44 } var initialized: Int = 57
apache-2.0
e70f99d5f7bb65ee83830dd0b64f0fda
51.691358
114
0.619963
3.175595
false
false
false
false
kstaring/swift
test/decl/protocol/req/optional.swift
1
6835
// RUN: %target-parse-verify-swift // ----------------------------------------------------------------------- // Declaring optional requirements // ----------------------------------------------------------------------- @objc class ObjCClass { } @objc protocol P1 { @objc optional func method(_ x: Int) // expected-note {{requirement 'method' declared here}} @objc optional var prop: Int { get } @objc optional subscript (i: Int) -> ObjCClass? { get } } @objc protocol P2 { @objc(objcMethodWithInt:) optional func method(y: Int) // expected-note 1{{requirement 'method(y:)' declared here}} } // ----------------------------------------------------------------------- // Providing witnesses for optional requirements // ----------------------------------------------------------------------- // One does not have provide a witness for an optional requirement class C1 : P1 { } // ... but it's okay to do so. class C2 : P1 { @objc func method(_ x: Int) { } @objc var prop: Int = 0 @objc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C3 : P1 { func method(_ x: Int) { } var prop: Int = 0 subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } class C4 { } extension C4 : P1 { func method(_ x: Int) { } var prop: Int { return 5 } subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // Okay to match via extensions. // ----------------------------------------------------------------------- class C5 : P1 { } extension C5 { func method(_ x: Int) { } var prop: Int { return 5 } subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // Note: @nonobjc suppresses witness match. class C6 { } extension C6 : P1 { @nonobjc func method(_ x: Int) { } @nonobjc var prop: Int { return 5 } @nonobjc subscript (i: Int) -> ObjCClass? { get { return nil } set {} } } // ----------------------------------------------------------------------- // "Near" matches. // ----------------------------------------------------------------------- // Note: warn about selector matches where the Swift names didn't match. @objc class C7 : P1 { // expected-note{{class 'C7' declares conformance to protocol 'P1' here}} @objc(method:) func otherMethod(x: Int) { } // expected-error{{Objective-C method 'method:' provided by method 'otherMethod(x:)' conflicts with optional requirement method 'method' in protocol 'P1'}} // expected-note@-1{{rename method to match requirement 'method'}}{{23-34=method}}{{35-35=_ }} } @objc class C8 : P2 { // expected-note{{class 'C8' declares conformance to protocol 'P2' here}} func objcMethod(int x: Int) { } // expected-error{{Objective-C method 'objcMethodWithInt:' provided by method 'objcMethod(int:)' conflicts with optional requirement method 'method(y:)' in protocol 'P2'}} // expected-note@-1{{add '@nonobjc' to silence this error}}{{3-3=@nonobjc }} // expected-note@-2{{rename method to match requirement 'method(y:)'}}{{8-18=method}}{{19-22=y}}{{none}} } // ----------------------------------------------------------------------- // Using optional requirements // ----------------------------------------------------------------------- // Optional method references in generics. func optionalMethodGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in generics. func optionalPropertyGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in generics. func optionalSubscriptGeneric<T : P1>(_ t: T) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // Optional method references in existentials. func optionalMethodExistential(_ t: P1) { // Infers a value of optional type. var methodRef = t.method // Make sure it's an optional methodRef = .none // ... and that we can call it. methodRef!(5) } // Optional property references in existentials. func optionalPropertyExistential(_ t: P1) { // Infers a value of optional type. var propertyRef = t.prop // Make sure it's an optional propertyRef = .none // ... and that we can use it let i = propertyRef! _ = i as Int } // Optional subscript references in existentials. func optionalSubscriptExistential(_ t: P1) { // Infers a value of optional type. var subscriptRef = t[5] // Make sure it's an optional subscriptRef = .none // ... and that we can use it let i = subscriptRef! _ = i as ObjCClass? } // ----------------------------------------------------------------------- // Restrictions on the application of optional // ----------------------------------------------------------------------- // optional cannot be used on non-protocol declarations optional var optError: Int = 10 // expected-error{{'optional' can only be applied to protocol members}} {{1-10=}} optional struct optErrorStruct { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int // expected-error{{'optional' can only be applied to protocol members}} {{3-12=}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} {{3-12=}} } optional class optErrorClass { // expected-error{{'optional' modifier cannot be applied to this declaration}} {{1-10=}} optional var ivar: Int = 0 // expected-error{{'optional' can only be applied to protocol members}} {{3-12=}} optional func foo() { } // expected-error{{'optional' can only be applied to protocol members}} {{3-12=}} } protocol optErrorProtocol { optional func foo(_ x: Int) // expected-error{{'optional' can only be applied to members of an @objc protocol}} } @objc protocol optObjcAttributeProtocol { optional func foo(_ x: Int) // expected-error{{'optional' requirements are an Objective-C compatibility feature; add '@objc'}}{{3-3=@objc }} optional var bar: Int { get } // expected-error{{'optional' requirements are an Objective-C compatibility feature; add '@objc'}}{{3-3=@objc }} optional associatedtype Assoc // expected-error{{'optional' modifier cannot be applied to this declaration}} {{3-12=}} } @objc protocol optionalInitProto { @objc optional init() // expected-error{{'optional' cannot be applied to an initializer}} }
apache-2.0
74b63141da468a86c903f29d80100421
28.588745
205
0.575274
4.095267
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/WikipediaLookup.swift
1
2963
import Foundation import WMF.WMFLogging import CocoaLumberjackSwift @objc class WikipediaLookup: NSObject { static let allWikipedias: [Wikipedia] = { guard let languagesFileURL = Bundle.wmf.url(forResource: "wikipedia-languages", withExtension: "json") else { return [] } do { let data = try Data(contentsOf: languagesFileURL) return try JSONDecoder().decode([Wikipedia].self, from: data) } catch let error { DDLogError("Error decoding language list \(error)") return [] } }() @objc static let allLanguageLinks: [MWKLanguageLink] = { return allWikipedias.map { (wikipedia) -> MWKLanguageLink in var localizedName = wikipedia.localName if !wikipedia.languageCode.contains("-") { if let iOSLocalizedName = Locale.current.localizedString(forLanguageCode: wikipedia.languageCode) { localizedName = iOSLocalizedName } } else if !Locale.current.isEnglish { if let iOSLocalizedName = Locale.current.localizedString(forIdentifier: wikipedia.languageCode) { localizedName = iOSLocalizedName } } return MWKLanguageLink(languageCode: wikipedia.languageCode, pageTitleText: "", name: wikipedia.languageName, localizedName: localizedName, languageVariantCode: nil, altISOCode: wikipedia.altISOCode) } }() @objc static let allLanguageVariantsByWikipediaLanguageCode: [String:[MWKLanguageLink]] = { guard let languagesFileURL = Bundle.wmf.url(forResource: "wikipedia-language-variants", withExtension: "json") else { return [:] } do { let data = try Data(contentsOf: languagesFileURL) let entries = try JSONDecoder().decode([String : [WikipediaLanguageVariant]].self, from: data) return entries.mapValues { wikipediaLanguageVariants -> [MWKLanguageLink] in wikipediaLanguageVariants.map { wikipediaLanguageVariant in var localizedName = wikipediaLanguageVariant.localName if !Locale.current.isEnglish, let iOSLocalizedName = Locale.current.localizedString(forIdentifier: wikipediaLanguageVariant.languageVariantCode) { localizedName = iOSLocalizedName } return MWKLanguageLink(languageCode: wikipediaLanguageVariant.languageCode, pageTitleText: "", name: wikipediaLanguageVariant.languageName, localizedName: localizedName, languageVariantCode: wikipediaLanguageVariant.languageVariantCode, altISOCode: wikipediaLanguageVariant.altISOCode) } } } catch let error { DDLogError("Error decoding language variant list \(error)") return [:] } }() }
mit
475a54bd23f52609ea9c1558114d4408
48.383333
305
0.633142
5.611742
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/QTitleSwitchComposition.swift
1
4598
// // Quickly // open class QTitleSwitchComposable : QComposable { public typealias Closure = (_ composable: QTitleSwitchComposable) -> Void public var titleStyle: QLabelStyleSheet public var switchStyle: QSwitchStyleSheet public var switchHeight: CGFloat public var switchSpacing: CGFloat public var switchIsOn: Bool public var switchChanged: Closure public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, titleStyle: QLabelStyleSheet, switchStyle: QSwitchStyleSheet, switchHeight: CGFloat = 44, switchSpacing: CGFloat = 4, switchIsOn: Bool = false, switchChanged: @escaping Closure ) { self.titleStyle = titleStyle self.switchStyle = switchStyle self.switchHeight = switchHeight self.switchSpacing = switchSpacing self.switchIsOn = switchIsOn self.switchChanged = switchChanged super.init(edgeInsets: edgeInsets) } } open class QTitleSwitchComposition< Composable: QTitleSwitchComposable > : QComposition< Composable > { public private(set) lazy var titleView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var switchView: QSwitch = { let view = QSwitch(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false view.setContentHuggingPriority( horizontal: UILayoutPriority(rawValue: 252), vertical: UILayoutPriority(rawValue: 252) ) view.onChanged = { [weak self] (_, _) in guard let self = self, let composable = self.composable else { return } composable.switchIsOn = self.switchView.isOn composable.switchChanged(composable) } self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _switchSpacing: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let textSize = composable.titleStyle.size(width: availableWidth) return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(textSize.height, composable.switchHeight) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._switchSpacing != composable.switchSpacing { self._edgeInsets = composable.edgeInsets self._switchSpacing = composable.switchSpacing self._constraints = [ self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.titleView.trailingLayout == self.switchView.leadingLayout.offset(-composable.switchSpacing), self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.switchView.topLayout >= self.contentView.topLayout.offset(composable.edgeInsets.top), self.switchView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.switchView.bottomLayout <= self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.switchView.centerYLayout == self.contentView.centerYLayout ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.titleView.apply(composable.titleStyle) self.switchView.apply(composable.switchStyle) } open override func postLayout(composable: Composable, spec: IQContainerSpec) { self.switchView.setOn(composable.switchIsOn, animated: false) } open func setOn(_ on: Bool, animated: Bool) { if let composable = self.composable { composable.switchIsOn = on } self.switchView.setOn(on, animated: animated) } }
mit
ae8e2d14b2ec9cc50dd2c47ca2d78970
40.423423
124
0.678991
5.143177
false
false
false
false
fireunit/login
Pods/Material/Sources/iOS/ControlView.swift
2
6645
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public class ControlView : MaterialView { /// Will render the view. public var willRenderView: Bool { return 0 < width } /// A preset wrapper around contentInset. public var contentInsetPreset: MaterialEdgeInset { get { return grid.contentInsetPreset } set(value) { grid.contentInsetPreset = value } } /// A wrapper around grid.contentInset. @IBInspectable public var contentInset: UIEdgeInsets { get { return grid.contentInset } set(value) { grid.contentInset = value } } /// A preset wrapper around spacing. public var spacingPreset: MaterialSpacing = .None { didSet { spacing = MaterialSpacingToValue(spacingPreset) } } /// A wrapper around grid.spacing. @IBInspectable public var spacing: CGFloat { get { return grid.spacing } set(value) { grid.spacing = value } } /// ContentView that holds the any desired subviews. public private(set) lazy var contentView: MaterialView = MaterialView() /// Left side UIControls. public var leftControls: Array<UIControl>? { didSet { if let v: Array<UIControl> = oldValue { for b in v { b.removeFromSuperview() } } if let v: Array<UIControl> = leftControls { for b in v { addSubview(b) } } layoutSubviews() } } /// Right side UIControls. public var rightControls: Array<UIControl>? { didSet { if let v: Array<UIControl> = oldValue { for b in v { b.removeFromSuperview() } } if let v: Array<UIControl> = rightControls { for b in v { addSubview(b) } } layoutSubviews() } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) } /** A convenience initializer with parameter settings. - Parameter leftControls: An Array of UIControls that go on the left side. - Parameter rightControls: An Array of UIControls that go on the right side. */ public convenience init?(leftControls: Array<UIControl>? = nil, rightControls: Array<UIControl>? = nil) { self.init(frame: CGRectZero) prepareProperties(leftControls, rightControls: rightControls) } public override func layoutSubviews() { super.layoutSubviews() if willRenderView { layoutIfNeeded() frame.size.height = intrinsicContentSize().height let factor: CGFloat = 24 if let g: Int = Int(width / factor) { let columns: Int = g + 1 grid.views = [] grid.axis.columns = columns contentView.grid.columns = columns // leftControls if let v: Array<UIControl> = leftControls { for c in v { let w: CGFloat = c.intrinsicContentSize().width (c as? UIButton)?.contentEdgeInsets = UIEdgeInsetsZero c.frame.size.height = frame.size.height - contentInset.top - contentInset.bottom let q: Int = Int(w / factor) c.grid.columns = q + 1 contentView.grid.columns -= c.grid.columns addSubview(c) grid.views?.append(c) } } addSubview(contentView) grid.views?.append(contentView) // rightControls if let v: Array<UIControl> = rightControls { for c in v { let w: CGFloat = c.intrinsicContentSize().width (c as? UIButton)?.contentEdgeInsets = UIEdgeInsetsZero c.frame.size.height = frame.size.height - contentInset.top - contentInset.bottom let q: Int = Int(w / factor) c.grid.columns = q + 1 contentView.grid.columns -= c.grid.columns addSubview(c) grid.views?.append(c) } } grid.contentInset = contentInset grid.spacing = spacing grid.reloadLayout() } } } public override func intrinsicContentSize() -> CGSize { return CGSizeMake(width, 36 + contentInset.top + contentInset.bottom) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public override func prepareView() { super.prepareView() prepareContentView() } /** Used to trigger property changes that initializers avoid. - Parameter leftControls: An Array of UIControls that go on the left side. - Parameter rightControls: An Array of UIControls that go on the right side. */ internal func prepareProperties(leftControls: Array<UIControl>?, rightControls: Array<UIControl>?) { self.leftControls = leftControls self.rightControls = rightControls } /// Prepares the contentView. private func prepareContentView() { contentView.backgroundColor = nil addSubview(contentView) } }
mit
6650d632c818af4658fc29d4dcb63374
27.519313
106
0.703687
3.918042
false
false
false
false
ruilin/RLMap
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewTaxiCell.swift
2
2066
@objc(MWMRoutePreviewTaxiCellType) enum RoutePreviewTaxiCellType: Int { case taxi case uber case yandex } @objc(MWMRoutePreviewTaxiCell) final class RoutePreviewTaxiCell: UICollectionViewCell { @IBOutlet private weak var icon: UIImageView! @IBOutlet private weak var title: UILabel! { didSet { title.font = UIFont.bold14() title.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var info: UILabel! { didSet { info.font = UIFont.regular14() info.textColor = UIColor.blackSecondaryText() } } func config(type: RoutePreviewTaxiCellType, title: String, eta: String, price: String, currency: String) { let iconImage = { () -> UIImage in switch type { case .taxi: return #imageLiteral(resourceName: "icTaxiTaxi") case .uber: return #imageLiteral(resourceName: "icTaxiUber") case .yandex: return #imageLiteral(resourceName: "icTaxiYandex") } } let titleString = { () -> String in switch type { case .taxi: fallthrough case .uber: return title case .yandex: return L("yandex_taxi_title") } } let priceString = { () -> String in switch type { case .taxi: fallthrough case .uber: return price case .yandex: let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencyCode = currency formatter.maximumFractionDigits = 0 if let number = UInt(price), let formattedPrice = formatter.string(from: NSNumber(value: number)) { return formattedPrice } else { return "\(currency) \(price)" } } } let timeString = { () -> String in let timeValue = DateComponentsFormatter.etaString(from: TimeInterval(eta)!)! let format = L("taxi_wait").replacingOccurrences(of: "%s", with: "%@") return String(format: format, arguments: [timeValue]) } icon.image = iconImage() self.title.text = titleString() info.text = "~ \(priceString()) • \(timeString())" } }
apache-2.0
5e4821c89c2b233197f76bab521d5538
28.913043
108
0.63905
4.327044
false
false
false
false
sugarAndsugar/ProgressOverlay
ProgressOverlayTestTests/ProgressOverlayTestTests.swift
1
9123
// // ProgressOverlayTestTests.swift // ProgressOverlayTestTests // // Created by xiangkai yin on 16/9/7. // Copyright © 2016年 kuailao_2. All rights reserved. // import XCTest @testable import ProgressOverlayTest class ProgressOverlayTestTests: XCTestCase { var hideExpectation:XCTestExpectation! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testNonAnimatedConvenienceoverlayPresentation() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view let overlay = ProgressOverlay.showOnView(rootView, animated: false) XCTAssertNotNil(overlay, "A overlay should be created.") self.testOverlayIsVisible(overlay, rootView: rootView!) XCTAssertEqual(ProgressOverlay.hideForView(rootView), overlay, "The overlay should be found via the convenience operation.") XCTAssertTrue(ProgressOverlay.hideForView(rootView) != nil, "The overlay should be found and removed.") XCTAssertFalse(ProgressOverlay.hideForView(rootView) == nil, "A subsequent overlay hide operation should fail.") self.testOverlayIsVisible(overlay, rootView: rootView!) } func testOverlayIsVisible(_ overlay:ProgressOverlay,rootView:UIView) { XCTAssertEqual(overlay.superview, rootView, "The overlay should be added to the view.") XCTAssertEqual(overlay.alpha, 1.0, "The overlay should be visible.") XCTAssertFalse(overlay.hidden, "The overlay should be visible.") } func testOverlayIsHidenAndRemoved(_ overlay:ProgressOverlay,rootView:UIView) { XCTAssertFalse(rootView.subviews.contains(overlay), "The overlay should not be part of the view hierarchy.") XCTAssertEqual(overlay.alpha, 0.0, "The overlay should be faded out.") XCTAssertNil(overlay.superview, "The overlay should not have a superview.") } func testAnimatedConvenienceoverlayPresentation() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view let overlay = ProgressOverlay.showOnView(rootView, animated: false) XCTAssertNotNil(overlay, "A overlay should be created.") self.testOverlayIsVisible(overlay, rootView: rootView!) XCTAssertEqual(ProgressOverlay.hideForView(rootView), overlay, "The overlay should be found via the convenience operation.") XCTAssertTrue(ProgressOverlay.hideForView(rootView) != nil, "The overlay should be found and removed.") XCTAssertEqual(overlay.alpha, 1.0, "The overlay should still be visible.") XCTAssertTrue(rootView?.subviews.contains(overlay) == true, "The overlay should still be part of the view hierarchy.") XCTAssertEqual(overlay.superview, rootView, "The overlay should be added to the view.") XCTAssertFalse(ProgressOverlay.hideAllOverlaysForView(rootView, animated: true) == false, "A subsequent overlay hide operation should fail.") self.testOverlayIsHidenAndRemoved(overlay, rootView: rootView!) } func testCompletionBlock() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view self.hideExpectation = expectation(description: "The completionBlock: should have been called.") let overlay = ProgressOverlay.showOnView(rootView, animated: true) overlay.completionBlock = { () in self.hideExpectation.fulfill() } overlay.hideAnimated(true) waitForExpectations(timeout: 5.0) { (error) in } } // MARK: - Delay func testDelayedHide() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view self.hideExpectation = self.expectation(description: "The hudWasHidden: delegate should have been called.") let overlay = ProgressOverlay.showOnView(rootView, animated: true) XCTAssertNotNil(overlay,"A overlay should be created.") overlay.hideAnimated(true, delay: 2) self.testOverlayIsVisible(overlay, rootView: rootView!) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.testOverlayIsHidenAndRemoved(overlay, rootView: rootView!) self.hideExpectation.fulfill() } waitForExpectations(timeout: 5) { (eror) in } } // MARK: - Ruse func testNonAnimatedHudReuse() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view let overlay = ProgressOverlay.init(view:rootView!) // 设置隐藏时 不知道remove ,这样在隐藏后,还可以不用创建就显示 overlay.removeFromSuperViewOnHide = false rootView!.addSubview(overlay) overlay.showAnimated(false) XCTAssertNotNil(overlay,"A overlay should be created.") overlay.hideAnimated(false) overlay.showAnimated(false) testOverlayIsVisible(overlay, rootView: rootView!) overlay.hideAnimated(false) overlay.removeFromSuperview() } func testUnfinishedHidingAnimation() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view self.hideExpectation = self.expectation(description: "The hudWasHidden: delegate should have been called.") let overlay = ProgressOverlay.showOnView(rootView, animated: true) overlay.backgroundView.layer.removeAllAnimations() XCTAssertNotNil(overlay,"A overlay should be created.") overlay.hideAnimated(true, delay: 2) self.testOverlayIsVisible(overlay, rootView: rootView!) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.testOverlayIsHidenAndRemoved(overlay, rootView: rootView!) self.hideExpectation.fulfill() } waitForExpectations(timeout: 5) { (eror) in } } // MARK: - Min show time func testMinShowTime() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view self.hideExpectation = self.expectation(description: "The hudWasHidden: delegate should have been called.") let overlay = ProgressOverlay.init(view:rootView!) overlay.minShowTime = 2 rootView?.addSubview(overlay) overlay.showAnimated(true) XCTAssertNotNil(overlay,"A overlay should be created.") overlay.hideAnimated(true) var checkedAfterOneSecond = false DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.testOverlayIsVisible(overlay, rootView: rootView!) checkedAfterOneSecond = true XCTAssertTrue(checkedAfterOneSecond) self.hideExpectation.fulfill() } waitForExpectations(timeout: 5.0) { (error) in } } // MARK: - Grace time func testGraceTime() { let rootViewController = UIApplication.shared.keyWindow?.rootViewController let rootView = rootViewController?.view self.hideExpectation = self.expectation(description: "The hudWasHidden: delegate should have been called.") let overlay = ProgressOverlay.init(view:rootView!) overlay.graceTime = 2 rootView?.addSubview(overlay) overlay.showAnimated(true) XCTAssertNotNil(overlay,"A overlay should be created.") XCTAssertEqual(overlay.superview, rootView, "The overlay should be added to the view.") XCTAssertEqual(overlay.alpha, 0.0, "The overlay should not be visible.") XCTAssertFalse(overlay.hidden, "The overlay should be visible.") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in XCTAssertEqual(overlay.superview, rootView, "The overlay should be added to the view.") XCTAssertEqual(overlay.alpha, 0.0, "The overlay should not be visible.") XCTAssertFalse(overlay.hidden, "The overlay should be visible.") } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.testOverlayIsVisible(overlay, rootView: rootView!) overlay.hideAnimated(true) self.hideExpectation.fulfill() } waitForExpectations(timeout: 5) { (error) in } } }
bsd-3-clause
0df6633d9bc362cbbb40f80fbf2df24d
40.406393
145
0.72232
4.655031
false
true
false
false
yanoooooo/DecoRecipe
DecoRecipe/DecoRecipe/SearchViewController.swift
1
1981
// // FirstViewController.swift // DecoRecipe // // Created by Yano on 2015/06/01. // Copyright (c) 2015年 Yano. All rights reserved. // import UIKit class SearchViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var myCollectionView: UICollectionView! let datamodel = NailDataUtil.sharedInstance override func viewDidLoad() { super.viewDidLoad() //データをセット(最初だけでいい) datamodel.setPlistData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UICollectionViewDelegate Protocol func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell:CustomCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCell var row: Int = indexPath.row var datanume: String = String(row) cell.title.text = String(datamodel.getNailData("data"+datanume).name) if row > 2{row = 0} cell.image.image = UIImage(named: datamodel.getNailData("data"+datanume).image) cell.backgroundColor = UIColor.whiteColor() return cell } /* Cellが選択された際に呼び出される */ func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var num: String = String(indexPath.row) //選択している番号を保存 datamodel.setSelectedItemId(num) } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3; } }
mit
a290c7c6a69359aa8dbc756507cacf5e
28.246154
131
0.6707
5.04244
false
false
false
false
garthmac/ChemicalVisualizer
ViewController.swift
1
20629
// // ViewController.swift // ChemicalVisualizer Copyright (c) 2015 Garth MacKenzie // // Created by iMac 27 on 2015-12-01. // // import UIKit import SceneKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var geometryLabel: UILabel! @IBOutlet weak var sceneView: SCNView! @IBOutlet weak var topSegControl: UISegmentedControl! @IBOutlet weak var secondSegControl: UISegmentedControl! @IBOutlet weak var thirdSegControl: UISegmentedControl! @IBOutlet weak var bottomSegControl: UISegmentedControl! @IBOutlet weak var helpPickerView: UIPickerView! struct Constants { static let AtomsTitle = "Atoms - Van Der Waals Radius" static let PeriodicTable = "http://periodictable.com/Properties/A/VanDerWaalsRadius.al.html" static let DemoURL = "https://redblockblog.wordpress.com/marketing/" static let ChemsketchURL = "http://www.chemteach.ac.nz/documents/chemed09/misc/chemsketch.pdf" static let ChemSketch_GuideURL = "http://academic.pgcc.edu/psc/ChemSketch_Guide.pdf" static let ShowURLSegue = "Show URL" } var url = "" //MARK: - UIPickerViewDataSource var pickerDataSourceHelp: [UIButton] { // a computed property instead of func get { return (0..<self.hints.count).map { let button = UIButton(frame: CGRect(x: 0, y: 0, width: sceneView.bounds.width, height: 40)) button.titleLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) button.titleLabel!.lineBreakMode = .ByWordWrapping button.setTitle(self.hints[$0], forState: .Normal) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) return button } } set { self.pickerDataSourceHelp = newValue } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } //number of wheels in the picker func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerDataSourceHelp.count } //MARK: - UIPickerViewDelegate func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { if pickerView.tag > 0 { return 45.0 } return 70.0 } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return sceneView.bounds.width } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { //expensive return pickerDataSourceHelp[row] } var selectedHintIndex = 0 func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedHintIndex = row } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Constants.ShowURLSegue { //prepare if let bvc = segue.destinationViewController as? BrowserViewController { bvc.url = url if let nsurl = NSURL(string: url) { bvc.nsurl = nsurl } } } } func unwindFromModalViewController(segue: UIStoryboardSegue?) { dismissViewControllerAnimated(true, completion: nil) } let model = UIDevice.currentDevice().model // Geometry var geometryNode: SCNNode = SCNNode() //if you navigate your scene with the default camera controls (rotation, specifically), you’ll notice an odd effect: you might expect the box to rotate and the lighting to stay in place but, in fact, it’s actually the camera rotating around the scene. // Gestures var currentAngle: Float = 0.0 //once you have more complex models with multiple geometry sources, it’ll be much easier to manage them as a single node – hence the addition of geometryNode. Furthermore, currentAngle will help modify the y-axis rotation of geometryNode exclusively, leaving the rest of your scene nodes untouched...see panGesture // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() helpPickerView.delegate = self helpPickerView.dataSource = self secondSegControl.selectedSegmentIndex = -1 thirdSegControl.selectedSegmentIndex = -1 bottomSegControl.selectedSegmentIndex = -1 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if geometryLabel.text == "Geometry" { sceneSetup() geometryLabel.text = Constants.AtomsTitle geometryNode = Atoms.allAtoms() sceneView.scene!.rootNode.addChildNode(geometryNode) } } // MARK: Scene func sceneSetup() { let scene = SCNScene() let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLightTypeAmbient ambientLightNode.light!.color = UIColor(white: 0.67, alpha: 1.0) //67% white color scene.rootNode.addChildNode(ambientLightNode) //Ambient light is a basic form of lighting that illuminates all objects in a scene evenly, with a constant intensity from all directions, much like cloud-filtered sunlight. It’s a great addition to most scenes when you want a more natural look. Otherwise, objects in shadow would be pure black let omniLightNode = SCNNode() omniLightNode.light = SCNLight() omniLightNode.light!.type = SCNLightTypeOmni omniLightNode.light!.color = UIColor(white: 0.75, alpha: 1.0) omniLightNode.position = SCNVector3Make(0, 50, 50) scene.rootNode.addChildNode(omniLightNode) //omnidirectional light, or point light. It’s similar to ambient light in that it has constant intensity, but differs because it has a direction. The light’s position relative to other objects in your scene determines its direction. Your box node’s default position is (0, 0, 0), so positioning your new light node at (0, 50, 50) means that it’s above and in front...A position of (0, 50, 50) doesn’t mean 50 meters, miles, or light years; it’s simply 50 units //experiment with directional (SCNLightTypeDirectional) and spot (SCNLightTypeSpot) lights let cameraNode = SCNNode() cameraNode.camera = SCNCamera() // cameraNode.camera?.usesOrthographicProjection = true //default projection type of a SCNCamera is perspective cameraNode.position = SCNVector3Make(0, 0, 25) //The only thing you need to define is its position, conveniently set right in front scene.rootNode.addChildNode(cameraNode) let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "doubleTapGesture:") //wikipedia atom doubleTapRecognizer.numberOfTapsRequired = 2 sceneView.addGestureRecognizer(doubleTapRecognizer) let panRecognizer = UIPanGestureRecognizer(target: self, action: "panGesture:") sceneView.addGestureRecognizer(panRecognizer) let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapGesture:") //wikipedia molecule sceneView.addGestureRecognizer(tapRecognizer) sceneView.scene = scene // sceneView.autoenablesDefaultLighting = true // sceneView.allowsCameraControl = true ****used initially to see first node } func panGesture(gesture: UIPanGestureRecognizer) { //Whenever sceneView detects a pan gesture, this function will be called, and it transforms the gesture’s x-axis translation to a y-axis rotation on the geometry node (1 pixel = 1 degree) if geometryLabel.text == Constants.AtomsTitle { let translation = gesture.translationInView(gesture.view!) var newAngle = (Float)(translation.x)*(Float)(M_PI)/180.0 newAngle += currentAngle geometryNode.transform = SCNMatrix4MakeRotation(newAngle, 0, 1, 0) //you modify the transform property of geometryNode by creating a new rotation matrix, but you could also modify its rotation property with a rotation vector. A transformation matrix is better because you can easily expand it to include translation and scale. ***full 3D...http://www.raywenderlich.com/50398/opengl-es-transformations-gestures if (gesture.state == UIGestureRecognizerState.Ended) { currentAngle = newAngle } } else { if (gesture.state == UIGestureRecognizerState.Ended) { url = Constants.PeriodicTable performSegueWithIdentifier(Constants.ShowURLSegue, sender: nil) } } } var tap = UITapGestureRecognizer() func tapStop(gesture: UITapGestureRecognizer, willDisable: Bool) { tap = gesture if willDisable { gesture.enabled = false } else { gesture.enabled = true } } func tapGesture(gesture: UITapGestureRecognizer) { //for molecules (although may still be abble to double tap an atom on rotating molecule) if gesture.numberOfTapsRequired == 1 { let location = gesture.locationInView(gesture.view!) //print(location) let hits = self.sceneView.hitTest(location, options: nil) if let tappedNode = hits.first?.node { let name = tappedNode.parentNode!.name if name != nil { tappedNode.parentNode?.pauseAnimationForKey("spin around") //removeAnimationForKey("spin around") tapStop(gesture, willDisable: true) url = name! performSegueWithIdentifier(Constants.ShowURLSegue, sender: nil) } } } } func doubleTapGesture(gesture: UITapGestureRecognizer) { //for atoms if gesture.numberOfTapsRequired == 2 { let location = gesture.locationInView(gesture.view!) //print(location) let hits = self.sceneView.hitTest(location, options: nil) if let tappedNode = hits.first?.node { let name = tappedNode.geometry!.name if name != nil { url = name! performSegueWithIdentifier(Constants.ShowURLSegue, sender: nil) } } } } // MARK: IBActions @IBAction func segmentValueChanged(sender: UISegmentedControl) { geometryNode.removeFromParentNode() helpPickerView.hidden = true currentAngle = 0.0 var segIndex = 0 if !tap.enabled { tap.enabled = true //restart molecule singleTap } if sender == bottomSegControl { topSegControl.selectedSegmentIndex = -1 secondSegControl.selectedSegmentIndex = -1 thirdSegControl.selectedSegmentIndex = -1 segIndex = topSegControl.numberOfSegments + secondSegControl.numberOfSegments + thirdSegControl.numberOfSegments + sender.selectedSegmentIndex } else if sender == thirdSegControl { topSegControl.selectedSegmentIndex = -1 secondSegControl.selectedSegmentIndex = -1 bottomSegControl.selectedSegmentIndex = -1 segIndex = topSegControl.numberOfSegments + secondSegControl.numberOfSegments + sender.selectedSegmentIndex } else if sender == secondSegControl { topSegControl.selectedSegmentIndex = -1 thirdSegControl.selectedSegmentIndex = -1 bottomSegControl.selectedSegmentIndex = -1 segIndex = topSegControl.numberOfSegments + sender.selectedSegmentIndex } else { //top thirdSegControl.selectedSegmentIndex = -1 secondSegControl.selectedSegmentIndex = -1 bottomSegControl.selectedSegmentIndex = -1 segIndex = sender.selectedSegmentIndex } switch segIndex { case 0: geometryLabel.text = Constants.AtomsTitle // http://periodictable.com/Properties/A/VanDerWaalsRadius.an.html geometryNode = Atoms.allAtoms() case 1: geometryLabel.text = "Terpinen-4-ol (antimicrobial/antifungal\nprimary active ingredient of tea tree oil)\nChemical formula C10H18O\nMolar mass 154.25 g·mol−1" geometryNode = Molecules.teaTreeOilMolecule() // https://en.wikipedia.org/wiki/Terpinen-4-ol case 2: geometryLabel.text = "Benzene (aromatic)\nFormula: C6H6\nMolar mass: 78.11 g/mol\nDensity: 876.50 kg/m³" geometryNode = Molecules.benzeneMolecule() case 3: geometryLabel.text = "Caffeine\nFormula: C8H10N4O2\nMelting point: 235 °C\nMolar mass: 194.19 g/mol\nBoiling point: 178 °C\nDensity: 1.23 g/cm³" geometryNode = Molecules.caffeineMolecule() case 4: geometryLabel.text = "Ethanol\n(ethyl alcohol, drinking alcohol)\nFormula: C2H6O\nMolar mass: 46.06844 g/mol\nBoiling point: 78.37 °C\nDensity: 789.00 kg/m³" geometryNode = Molecules.ethanolMolecule() case 5: geometryLabel.text = "Enprofylline (asthma treatment)\nxanthine derivative\nwhich acts as a bronchodilator\nMolar mass: 194.19 g/mol" geometryNode = Molecules.enprofyllineMolecule() case 6: geometryLabel.text = "Fructose (fruit sugar)\nFormula: C6H12O6\nMelting point: 103 °C\nBoiling point: 440 °C\nDensity: 1.69 g/cm³" geometryNode = Molecules.fructoseMolecule() case 7: geometryLabel.text = "Glyphosate (Roundup)\nN-(phosphonomethyl)glycine\nChemical formula C3H8NO5P\nMolar mass 169.07 g·mol−1\nwhite crystalline powder\nDensity 1.704\nMelting point 184.5 °C" geometryNode = Molecules.glyphosateMolecule() case 8: geometryLabel.text = "Ibuprofen (Advil)\nFormula: C13H18O2\nMolecular mass 206.29 g/mol\nProtein binding 98%\nMetabolism Hepatic\nOnset of action 30 min" geometryNode = Molecules.ibuprofenMolecule() case 9: geometryLabel.text = "Hydrogen peroxide (disinfectant)\nFormula: H2O2\nMolar mass: 34.0147 g/mol\nDensity: 1.45 g/cm³\nMelting point: -0.43 °C\nBoiling point: 150.2 °C" geometryNode = Molecules.hydrogenPeroxideMolecule() case 10: geometryLabel.text = "Isooctane (gasoline)\nFormula (CH₃)₃CCH₂CH(CH₃)₂\non octane rating scale = 100 points\nDensity: 690.00 kg/m³\nBoiling point: 99 °C" geometryNode = Molecules.isooctaneMolecule() case 11: geometryLabel.text = "Methane (natural gas)\nFormula: CH4\nMolar mass: 16.04 g/mol\nBoiling point: -161.5 °C\nDensity: 0.66 kg/m³\nMelting point: -182 °C" geometryNode = Molecules.methaneMolecule() case 12: geometryLabel.text = "Polytetrafluoroethylene (Teflon)\nFormula: (C2F4)n\nsynthetic fluoropolymer\nof tetrafluoroethylene\nMelting point: 326.8 °C\nDensity: 2.20 g/cm³" geometryNode = Molecules.ptfeMolecule() case 13: geometryLabel.text = "Phosphoric acid (mineral acid)\nFormula: H3PO4\nMolar mass: 98 g/mol\nDensity: 1.89 g/cm³\nBoiling point: 158 °C\nMelting point: 42.35 °C" geometryNode = Molecules.phosphoricAcidMolecule() case 14: geometryLabel.text = "Pyrazine (antitumor,antibiotic\nand diuretic) Formula: C4H4N2\nMolar mass: 80.09 g/mol\nDensity: 1.03 g/cm³\nBoiling point: 115 °C\nMelting point: 52 °C" geometryNode = Molecules.pyrazineMolecule() case 15: geometryLabel.text = "Sodium triphosphate (detergent)\nFormula Na5P3O10\nMolar mass: 367.864 g/mol\nMelting point: 622 °C\nDensity: 2.52 g/cm³" geometryNode = Molecules.sodiumTriphosphateMolecule() case 16: geometryLabel.text = "" //no title //4. pan to open Van Der Waals page // Create a 3D text SIMILAR TO A MOLECULE geometryNode = SCNNode() geometryNode.name = Constants.ChemsketchURL //2. single tap let sky = SCNMaterial() sky.diffuse.contents = UIImage(named: "RBGames.png") let red = SCNMaterial() red.diffuse.contents = UIColor.redColor() let blue = SCNMaterial() blue.diffuse.contents = UIColor.blueColor() let myText = SCNText(string: "Ⓒhem 3D", extrusionDepth: 3) myText.name = Constants.ChemSketch_GuideURL //3. double tap after single tap myText.flatness = 0.1 //default 0.6 myText.font = UIFont(name: "Arial", size: 13) //myText.chamferRadius = 1 //half extrusionDepth max myText.materials = [sky, red, blue] //see SCNText help let childNode = SCNNode(geometry: myText) childNode.position = SCNVector3(x: -8, y: 0, z: 0) childNode.orientation = SCNQuaternion(x: 0, y: 0, z: 0.6, w: 0) geometryNode.addChildNode(childNode) //sceneView.scene?.background.contents = "RBGames.png" helpPickerView.hidden = false url = Constants.DemoURL performSegueWithIdentifier(Constants.ShowURLSegue, sender: nil) // if let url = NSURL(string: Constants.DemoURL) { // UIApplication.sharedApplication().openURL(url) //1. opens first // } break // case 16: // geometryLabel.text = "Bacteria\n(Streptomyces cremeus NRRL 3241)\nFormula: C8H6N2O4\nAverage mass: 194.144 Da" //(mouth wash=ZnCl2/shampo=NaCl2) // geometryNode = Molecules.bacteriaMolecule() zopiclone is chloropyridinoxotriazabicyclonona-trienylmethylpiper-azinecarboxylate (C17H17ClN6O3) // case 17: // geometryLabel.text = "Tetrahydrocannabinol (THC), the psychoactive constituent of the cannabis plant" // https://en.wikipedia.org/wiki/Tetrahydrocannabinol // geometryNode = Molecules.ptfeMolecule() cd ~/.wine/drive_c/users/imac27/.wine/drive_c/Program\ Files/ACD2015FREE wine CHEMSK.EXE default: break } if geometryLabel.text != Constants.AtomsTitle { if sceneView.frame.width < sceneView.frame.height { geometryNode.scale = SCNVector3Make(1.2, 1.2, 1.2) } else { let result = geometryLabel.text?.componentsSeparatedByString("\n") if result?.count > 1 { geometryLabel.text = result![0] + " " + result![1] + "," + result![2] } geometryNode.scale = SCNVector3Make(2.4, 2.4, 2.4) } } sceneView.scene!.rootNode.addChildNode(geometryNode) } // MARK: Style override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // MARK: Transition override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) sceneView.stop(nil) if geometryLabel.text != Constants.AtomsTitle { if sceneView.frame.width > sceneView.frame.height { geometryNode.scale = SCNVector3Make(1.2, 1.2, 1.2) } else { geometryNode.scale = SCNVector3Make(2.4, 2.4, 2.4) } } sceneView.play(nil) } let hints = ["HELPful Chem 3D Hints", "Pan opening scene just for fun - VanDerWaalsRadius", "Double Tap any atom on opening scene to view web", "Any wikipedia page viewed is cached for offline use", "While viewing wikipedia in app, links are live", "SwipeLeft (goBack) and Right on multi-traversed pages", "Touch any lower [chemical name] to view 3D molecule", "Swipe background on any chem page for periodic table", "Tap spinning 3D molecule to view wikipedia page...", "Next, Tap the paused molecule to see each element", "Touch DEMO to view web page with developer videos...", "Next, touch ◁Back to Chem 3D to return to app", "Next, tap for ChemSketch info page...and return...", "Next, double tap for ChemSketch_Guide info page...", "Again, swipe background for periodic table"] }
mit
a4d9ad838f3111bf7c953d9467130501
55.787293
468
0.654424
4.169777
false
false
false
false
wordpress-mobile/WordPress-Aztec-iOS
Aztec/Classes/Libxml2/DOM/Logic/CSS/BoldCSSAttributeMatcher.swift
2
523
import Foundation open class BoldCSSAttributeMatcher: CSSAttributeMatcher { public func check(_ cssAttribute: CSSAttribute) -> Bool { guard let value = cssAttribute.value, cssAttribute.type == .fontWeight else { return false } if let weight = FontWeight(rawValue: value) { return weight.isBold() } else if let weight = Int(value) { return FontWeightNumeric.isBold(weight) } return false } }
gpl-2.0
5f68e9284ea16d04724d9fc8b6a066ff
26.526316
61
0.577438
5.127451
false
false
false
false
DevZheng/LeetCode
Array/SearchForARange.swift
1
2001
// // SearchForARange.swift // A // // Created by zyx on 2017/6/27. // Copyright © 2017年 bluelive. All rights reserved. // import Foundation /* Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. */ class SearchForARange { func searchRange(_ nums: [Int], _ target: Int) -> [Int] { if nums.count == 0 { return [-1, -1] } return [searchRange(nums, target, 0, nums.count - 1, true), searchRange(nums, target, 0, nums.count - 1, false)] } func searchRange(_ nums: [Int], _ target: Int, _ start: Int, _ end: Int, _ isLeft: Bool) -> Int { if end < start { return -1 } if end == start { return target == nums[start] ? start : -1 } let mid = (start + end) / 2 if isLeft { if nums[mid] > target { return searchRange(nums, target, start, mid - 1, isLeft); } else if nums[mid] == target { return result(searchRange(nums, target, start, mid - 1, isLeft), mid); } else { return searchRange(nums, target, mid + 1, end, isLeft); } } else { if nums[mid] < target { return searchRange(nums, target, mid + 1, end, isLeft); } else if nums[mid] == target { return result(searchRange(nums, target, mid + 1, end, isLeft), mid); } else { return searchRange(nums, target, start, mid - 1, isLeft); } } } func result(_ num1: Int, _ num2: Int) -> Int { if num1 == -1 { return num2; } return num1; } }
mit
7becf74dcaea8d16d3c18502d3d710df
27.140845
117
0.508509
3.894737
false
false
false
false
ArshAulakh59/DevLab-Test
DevLab-Test/Controllers/FilterViewController.swift
1
3121
// // FilterViewController.swift // DevLab-Test // // Created by Arsh Aulakh on 2017-04-24. // Copyright © 2017 AA. All rights reserved. // import UIKit class FilterViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
4faaeabf4c804188fe639895371b42fb
31.842105
136
0.669551
5.306122
false
false
false
false
cuba/NetworkKit
Source/Network/Dispatcher.swift
1
3926
// // Dispatcher.swift // NetworkKit iOS // // Created by Jacob Sikorski on 2019-03-31. // Copyright © 2019 Jacob Sikorski. All rights reserved. // import Foundation public typealias ResponsePromise<T, E> = Promise<SuccessResponse<T>, ErrorResponse<E>> /// The object that will be making the API call. public protocol Dispatcher { /// Make a promise to send the network call. /// /// - Parameter callback: A callback that constructs the Request object. /// - Returns: A promise to make the network call. func future(from request: Request) -> ResponseFuture<Response<Data?>> } public extension Dispatcher { /// Make a promise to send the network call. /// /// - Parameter callback: A callback that constructs the Request object. /// - Returns: A promise to make the network call. @available(*, deprecated, renamed: "makeRequest(from:)") func make(from callback: @escaping () throws -> Request) -> ResponsePromise<Data?, Data?> { return makeRequest(from: callback) } /// Make a promise to send the request. /// /// - Parameter request: The request to send. /// - Returns: The promise that will send the request. @available(*, deprecated, renamed: "promise(from:)") func make(_ request: Request) -> ResponsePromise<Data?, Data?> { return self.promise(from: request) } /// Make a promise to send the request. /// /// - Parameter request: The request to send. /// - Returns: The promise that will send the request. func promise(from request: Request) -> ResponsePromise<Data?, Data?> { return Promise<SuccessResponse<Data?>, ErrorResponse<Data?>>() { promise in self.future(from: request).response({ response in if let responseError = response.error { let errorResponse = ErrorResponse(data: response.data, httpResponse: response.httpResponse, urlRequest: response.urlRequest, statusCode: response.statusCode, error: responseError) promise.fail(with: errorResponse) } else { let successResponse = SuccessResponse(data: response.data, httpResponse: response.httpResponse, urlRequest: response.urlRequest, statusCode: response.statusCode) promise.succeed(with: successResponse) } }).error({ error in promise.catch(error) }).send() } } /// Make a promise to send the network call. /// /// - Parameter callback: A callback that constructs the Request object. /// - Returns: A promise to make the network call. @available(*, deprecated, renamed: "promise(from:)") func makeRequest(from callback: @escaping () throws -> Request) -> ResponsePromise<Data?, Data?> { return promise(from: callback) } /// Make a promise to send the network call. /// /// - Parameter callback: A callback that constructs the Request object. /// - Returns: A promise to make the network call. func promise(from callback: @escaping () throws -> Request) -> ResponsePromise<Data?, Data?> { return Promise<SuccessResponse<Data?>, ErrorResponse<Data?>>() { promise in let request = try callback() let requestPromise = self.promise(from: request) requestPromise.fulfill(promise) } } /// Make a promise to send the network call. /// /// - Parameter callback: A callback that constructs the Request object. /// - Returns: A promise to make the network call. func future(from callback: @escaping () throws -> Request) -> ResponseFuture<Response<Data?>> { return ResponseFuture<Response<Data?>>() { promise in let request = try callback() let requestPromise = self.future(from: request) requestPromise.fulfill(promise) } } }
mit
dd0ab946dca850abb0cdc073409d0adb
40.315789
199
0.634904
4.717548
false
false
false
false
jdbateman/OnTheMap
OnTheMap/CollectionViewController.swift
1
10070
// // CollectionViewController.swift // OnTheMap // // Created by john bateman on 8/28/15. // Copyright (c) 2015 John Bateman. All rights reserved. // // This file implements the LoginViewController which allows the user to create an account on Udacity, Login to a session on Udacity, or Login to Facebook on the device. import UIKit let reuseIdentifier = "OTMCollectionCellID" class CollectionViewController: UICollectionViewController, UICollectionViewDelegate { @IBOutlet weak var theCollectionView: UICollectionView! var appDelegate: AppDelegate! /* a reference to the studentLocations singleton */ let studentLocations = StudentLocations.sharedInstance() var activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) as UIActivityIndicatorView override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // setup the collectionview datasource & delegate theCollectionView.dataSource = self theCollectionView.delegate = self // Additional bar button items let refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "onRefreshButtonTap") let pinButton = UIBarButtonItem(image: UIImage(named: "pin"), style: .Plain, target: self, action: "onPinButtonTap") navigationItem.setRightBarButtonItems([refreshButton, pinButton], animated: true) // get a reference to the app delegate appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Add a notification observer for updates to student location data from Parse. NSNotificationCenter.defaultCenter().addObserver(self, selector: "onStudentLocationsUpdate", name: studentLocationsUpdateNotificationKey, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Remove observer for the studentLocations update notification. NSNotificationCenter.defaultCenter().removeObserver(self) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource /* return the section count */ override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } /* return the item count */ override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return studentLocations.studentLocations.count } /* return a cell for the requested item */ override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionCell let studentLocation = studentLocations.studentLocations[indexPath.row] // set the cell text var firstName = studentLocation.firstName var lastName = studentLocation.lastName cell.label!.text = firstName + " " + lastName println("cell label = \(cell.label!.text)") return cell } // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // open student's url in Safari browser let studentLocation = studentLocations.studentLocations[indexPath.row] let url = studentLocation.mediaURL showUrlInEmbeddedBrowser(url) } /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ // MARK: button handlers /* The Pin button was selected. */ func onPinButtonTap() { displayInfoPostingViewController() } /* The Refresh button was selected. */ func onRefreshButtonTap() { // refresh the collection of student locations from Parse studentLocations.reset() studentLocations.getStudentLocations(0) { success, errorString in if success == false { if let errorString = errorString { OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: errorString) } else { OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: "Unknown error") } } } } /* logout of Facebook else logout of Udacity session */ @IBAction func onLogoutButtonTap(sender: AnyObject) { startActivityIndicator() // Facebook logout if (FBSDKAccessToken.currentAccessToken() != nil) { // User is logged in with Facebook. Log user out of Facebook. let loginManager = FBSDKLoginManager() loginManager.logOut() if (FBSDKAccessToken.currentAccessToken() == nil) { self.appDelegate.loggedIn = false } self.stopActivityIndicator() self.displayLoginViewController() } else { // Udacity logout RESTClient.sharedInstance().logoutUdacity() {result, error in self.stopActivityIndicator() if error == nil { // successfully logged out self.appDelegate.loggedIn = false self.displayLoginViewController() } else { println("Udacity logout failed") // no display to user } } } } // MARK: helper functions /* Modally present the Login view controller */ func displayLoginViewController() { var storyboard = UIStoryboard (name: "Main", bundle: nil) var controller = storyboard.instantiateViewControllerWithIdentifier("LoginStoryboardID") as! LoginViewController self.presentViewController(controller, animated: true, completion: nil); } /* Modally present the InfoPosting view controller */ func displayInfoPostingViewController() { var storyboard = UIStoryboard (name: "Main", bundle: nil) var controller = storyboard.instantiateViewControllerWithIdentifier("InfoPostingProvideLocationStoryboardID") as! InfoPostingProvideLocationViewController self.presentViewController(controller, animated: true, completion: nil); } /* Received a notification that studentLocations have been updated with new data from Parse. Update the items in the collection view. */ func onStudentLocationsUpdate() { // Provoke the collection view data source protocol methods to be called. self.theCollectionView.reloadData() } /* Display url in external Safari browser. */ func showUrlInExternalWebKitBrowser(url: String) { if let requestUrl = NSURL(string: url) { UIApplication.sharedApplication().openURL(requestUrl) } } /* Display url in an embeded webkit browser in the navigation controller. */ func showUrlInEmbeddedBrowser(url: String) { var storyboard = UIStoryboard (name: "Main", bundle: nil) var controller = storyboard.instantiateViewControllerWithIdentifier("WebViewStoryboardID") as! WebViewController controller.url = url self.navigationController?.pushViewController(controller, animated: true) } /* show activity indicator */ func startActivityIndicator() { activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge view.addSubview(activityIndicator) activityIndicator.startAnimating() } /* hide acitivity indicator */ func stopActivityIndicator() { activityIndicator.stopAnimating() } }
mit
ef41530d93b2177f53843b0fca1469de
38.802372
185
0.681827
6.001192
false
false
false
false
zenangst/Faker
Pod/Tests/Specs/Generators/LoremSpec.swift
1
3923
import Quick import Nimble class LoremSpec: QuickSpec { override func spec() { describe("Lorem") { var lorem: Lorem! beforeEach { let parser = Parser(locale: "en-TEST") lorem = Lorem(parser: parser) } describe("#word") { it("returns the correct text") { let word = lorem.word() expect(word).to(match("^[A-Za-z]+$")) } } describe("#words") { context("without the amount - 3 words by default") { it("returns the expected amount of words") { let word = lorem.words() expect(word).to(match("^[A-Za-z]+ [A-Za-z]+ [A-Za-z]+$")) } } context("with the amount of words") { it("returns the expected amount of words") { let word = lorem.words(amount: 2) expect(word).to(match("^[A-Za-z]+ [A-Za-z]+$")) } } } describe("#character") { it("returns the correct character") { let char = lorem.character() expect(char).to(match("^[A-Za-z]$")) } } describe("#characters") { context("without the amount - 255 chars by default") { it("returns the expected amount of characters") { let chars = lorem.characters() expect(chars).to(match("^[A-Za-z]{255}")) } } context("with the amount of chars") { it("returns the expected amount of characters") { let chars = lorem.characters(amount: 7) expect(chars).to(match("^[A-Za-z]{7}")) } } } describe("#sentence") { context("without the amount - 4 words by default") { it("returns the expected amount of words") { let sentence = lorem.sentence() expect(sentence).to(match("^[A-Z][A-Za-z]+ [A-Za-z]+ [A-Za-z]+ [A-Za-z]+.$")) } } context("with the amount of words") { it("returns the expected amount of words") { let sentence = lorem.sentence(wordsAmount: 2) expect(sentence).to(match("^[A-Z][A-Za-z]+ [A-Za-z]+.$")) } } } describe("#sentences") { context("without the amount - 3 sentences by default") { it("returns the expected amount of sentences") { let sentences = lorem.sentences() expect(sentences).to(match("^[A-Za-z ]+. [A-Za-z ]+. [A-Za-z ]+.$")) } } context("with the amount of sentences") { it("returns the expected amount of sentences") { let sentences = lorem.sentences(amount: 2) expect(sentences).to(match("^[A-Za-z ]+. [A-Za-z ]+.$")) } } } describe("#paragraph") { context("without the amount - 3 sentence by default") { it("returns the expected amount of sentences") { let paragraph = lorem.paragraph() expect(paragraph).to(match("^[A-Za-z ]+. [A-Za-z ]+. [A-Za-z ]+.$")) } } context("with the amount of words") { it("returns the expected amount of sentences") { let sentence = lorem.paragraph(sentencesAmount: 2) expect(sentence).to(match("^[A-Za-z ]+. [A-Za-z ]+.$")) } } } describe("#paragraphs") { context("without the amount - 3 paragraphs by default") { it("returns the expected amount of paragraphs") { let paragraphs = lorem.paragraphs() expect(paragraphs).to(match("^[A-Za-z .]+\\n[A-Za-z .]+\\n[A-Za-z .]+$")) } } context("with the amount of paragraphs") { it("returns the expected amount of paragraphs") { let paragraphs = lorem.paragraphs(amount: 2) expect(paragraphs).to(match("^[A-Za-z .]+\\n[A-Za-z .]+$")) } } } } } }
mit
a19ce79eece9a3174c21540185a15e24
29.889764
89
0.499873
3.950655
false
false
false
false
LeoMobileDeveloper/MDTable
Source/Dispatch.swift
1
3358
// // Dispatch.swift // MDTable // // Created by Leo on 2017/7/24. // Copyright © 2017年 Leo Huang. All rights reserved. // import Foundation import CoreFoundation class Task{ private var _task:(Void)->Void var taskID:String init(_ identifier:String,_ task:@escaping (Void)->Void){ self._task = task self.taskID = identifier } func exccute(){ _task() } } enum TaskExecuteMode { case `default` //Stop execute during scroll case common } /// Dispatch Task to runloop, only one task will be executed in one runloop,use this class to handle perofrm issue public class TaskDispatcher{ public static let common = TaskDispatcher(mode: .common) public static let `default` = TaskDispatcher(mode: .default) enum State{ case running case suspend } var observer:CFRunLoopObserver? var tasks = [String:Task]() var taskKeys = [String]() var state = State.suspend let mode:TaskExecuteMode init(mode:TaskExecuteMode) { self.mode = mode } public func add(_ identifier:String, _ block:@escaping (Void)->Void){ let task = Task(identifier,block) self.add(task) } public func cancelTask(_ taskIdentifier:String){ guard tasks[taskIdentifier] != nil else { return } self.tasks[taskIdentifier] = nil guard let index = self.taskKeys.index(of: taskIdentifier) else{ return } self.taskKeys.remove(at: index) if self.taskKeys.count == 0 && self.state == .running{ invaliate() } } func register(){ let mainRunloop = RunLoop.main.getCFRunLoop() let activities = CFRunLoopActivity.beforeWaiting.rawValue | CFRunLoopActivity.exit.rawValue observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, activities, true, Int.max) { (observer, activity) in self.executeTask() } let runLoopMode = (mode == .common) ? CFRunLoopMode.commonModes : CFRunLoopMode.defaultMode CFRunLoopAddObserver(mainRunloop, observer, runLoopMode) self.state = .running } func add(_ task:Task){ guard tasks[task.taskID] == nil else { return } self.tasks[task.taskID] = task self.taskKeys.append(task.taskID) if self.state == .suspend{ register() } } func reset(){ syncExecuteOnMain{ self.tasks.removeAll() if self.state == .running{ self.invaliate() } } } func executeTask(){ guard let taskID = self.taskKeys.first else{ return } self.taskKeys.remove(at: 0) guard let task = self.tasks[taskID] else{ self.tasks[taskID] = nil return } self.tasks[taskID] = nil task.exccute() if self.taskKeys.count == 0 && self.state == .running{ invaliate() } } func invaliate(){ CFRunLoopRemoveObserver(RunLoop.main.getCFRunLoop(), observer, CFRunLoopMode.commonModes) self.state = .suspend } }
mit
eda8027a2755d6c91aa5452279db0047
29.207207
114
0.566657
4.54336
false
false
false
false
judi0713/TouTiao
TouTiao/Service/EventMonitor.swift
2
753
// // EventMonitor.swift // TouTiao // // Created by plusub on 4/22/16. // Copyright © 2016 tesths. All rights reserved. // import Cocoa open class EventMonitor { fileprivate var monitor: AnyObject? fileprivate let mask: NSEventMask fileprivate let handler: (NSEvent?) -> () public init(mask: NSEventMask, handler: @escaping (NSEvent?) -> ()) { self.mask = mask self.handler = handler } deinit { stop() } open func start() { monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as AnyObject? } open func stop() { if monitor != nil { NSEvent.removeMonitor(monitor!) monitor = nil } } }
mit
2aef02a5cbb57ee9e93274a28bdff2d3
20.485714
99
0.582447
4.224719
false
false
false
false
SamuelFrankSmith/animated-octo-tyrion
testy/testy/MasterViewController.swift
1
2885
// // MasterViewController.swift // testy // // Created by Sam on 1/29/15. // Copyright (c) 2015 no means know. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = NSMutableArray() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insertObject(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] as NSDate (segue.destinationViewController as DetailViewController).detailItem = object } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let object = objects[indexPath.row] as NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeObjectAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
2679526aaf36ef25200c4aa9da90bfae
32.941176
157
0.684229
5.484791
false
false
false
false
schultka/deploy-manager
src/deploy-manager/Branch.swift
1
2887
// // Branch.swift // deploy-manager // // Created by Tobias Schultka on 18.04.15. // Copyright (c) 2015 Tobias Schultka. All rights reserved. // import Foundation let REFS_HEADS = "refs/heads/" let BACKUP_NAME = "backup-" let BACKUP_DATE_FORMAT = "yyyy-MM-dd-HH-mm-ss" // get branches func getBranches() -> [String] { var normalizedBranches: [String] = [] // get all branch names let branchesString = runPathBashs([ "git for-each-ref --format='%(refname)' \(REFS_HEADS)" ]) // split branches string into array var branches = branchesString.componentsSeparatedByString("\n") // filter backup branches for branch: String in branches { // check if branch name has is long enough if (count(branch) <= count(REFS_HEADS)) { continue } // append branch name to array normalizedBranches.append( branch[count(REFS_HEADS)...count(branch) - 1] ) } log(true, "Found \(normalizedBranches.count) branches") return normalizedBranches } // remove local and remote dev branch func removeDevBranch(devBranch: String) { // delete local dev branch if (isPathBashTrue("git show-ref --verify --quiet \"\(REFS_HEADS + devBranch)\"")) { runPathBashs(["git branch --quiet -D \(devBranch)"]) log(true, "Removed local dev branch '\(devBranch)'") } // delete remote dev branch runPathBashs([ "git config push.default current", "git push origin --delete \(devBranch) --quiet" ]) log(true, "Removed remote dev branch '\(devBranch)'") } // create dev branch func createDevBranch(devBranch: String) { // create and checkout dev branch runPathBashs(["git checkout --quiet -b \(devBranch)"]) log(true, "Created and checked out '\(devBranch)'") // push to remote branch runPathBashs([ "git config push.default current", "git push origin \(devBranch) --quiet" ]) log(true, "Pushed '\(devBranch)' to remote") } // remove backup branches func removeBackupBranches(branches: [String], backupCount: Int) { var backupBranches: [String] = [] // filter backup branches for branch: String in branches { // push branch name to backups array if (count(branch) == count(BACKUP_NAME + BACKUP_DATE_FORMAT) && branch[0...count(BACKUP_NAME) - 1] == BACKUP_NAME) { backupBranches.append(branch); } } // delete backup branches var counter = backupBranches.count - backupCount for branch: String in backupBranches { if (counter <= 0) { break } counter-- runPathBashs([" git branch --quiet -D \(branch)"]) log(true, "Removed local branch '\(branch)'") } }
mit
de2caf5782bf92a4cb73b3c02c984d7e
26.235849
88
0.596121
4.083451
false
false
false
false
chenl326/stwitter
stwitter/stwitter/Classes/View/Main/OAuth/CLOAuthViewController.swift
1
3287
// // CLOAuthViewController.swift // stwitter // // Created by sun on 2017/5/27. // Copyright © 2017年 sun. All rights reserved. // import UIKit import SVProgressHUD class CLOAuthViewController: UIViewController { fileprivate lazy var webView = UIWebView() override func loadView() { view = webView view.backgroundColor = UIColor.white title = "登录weibo" navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", fontSize: 14, target: self, action: #selector(close), isBack: true) navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", target: self, action: #selector(autoFill)) } override func viewDidLoad() { super.viewDidLoad() let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(CLAppKey)&redirect_uri=\(CLRedirectURL)" guard let url = URL.init(string: urlStr) else { return } let request = URLRequest.init(url: url) webView.loadRequest(request) webView.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc fileprivate func close() -> () { SVProgressHUD.dismiss() dismiss(animated: true, completion: nil) } @objc fileprivate func autoFill(){ let js = "document.getElementById('userId').value = \(KUsername);" + "document.getElementById('passwd').value = \(KPassword);" webView.stringByEvaluatingJavaScript(from: js) } } extension CLOAuthViewController:UIWebViewDelegate{ /// - Parameters: /// - webView: webView /// - request: request description /// - navigationType: navigationType description /// - Returns: return value description func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.url?.absoluteString.hasPrefix(CLRedirectURL) == false { return true } print("加载请求----\(String(describing: request.url?.absoluteString))") if request.url?.query?.hasPrefix("code=") == false { print("取消授权") close() return false } let code = request.url?.query?.substring(from: "code=".endIndex) print("获取授权ma---\(String(describing: code))") CLNetworkManager.shared.loadAccessToken(code: code!) { (isSuccess) in if isSuccess{ NotificationCenter.default.post(name: NSNotification.Name(rawValue: CLUserLoginSuccessedNotification), object: nil, userInfo: nil) // self.close() }else{ SVProgressHUD.showInfo(withStatus: "网络请求失败") } } return true } func webViewDidStartLoad(_ webView: UIWebView) { SVProgressHUD.show() } func webViewDidFinishLoad(_ webView: UIWebView) { SVProgressHUD.dismiss() } }
apache-2.0
15884a6192cfdcf02442ecc2ba99167a
29.780952
146
0.602104
5.042122
false
false
false
false
CraigZheng/KomicaViewer
KomicaViewer/KomicaViewer/Model/WebViewGuardDog.swift
1
1177
// // WebViewGuardDog.swift // KomicaViewer // // Created by Craig Zheng on 19/08/2016. // Copyright © 2016 Craig. All rights reserved. // import UIKit protocol WebViewGuardDogDelegate: class { func blockedRequest(_ request: URLRequest) } /** Allows only NSURL host that matches home. */ class WebViewGuardDog: NSObject, UIWebViewDelegate { // Home host, any host that does not match this host would be rejected. var home: String? var showWarningOnBlock = false var onBlockMessage = "You cannot navigate away from this page." var delegate: WebViewGuardDogDelegate? // MARK: UIWebViewDelegate func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { var should = true if let home = home { if request.url?.host != home && navigationType == .linkClicked{ should = false delegate?.blockedRequest(request) if showWarningOnBlock && !onBlockMessage.isEmpty { ProgressHUD.showMessage(onBlockMessage) } } } return should } }
mit
ded5c13bd3e2ec4632a4d708452f3e22
29.153846
130
0.645408
4.704
false
false
false
false
googlecreativelab/justaline-ios
Styles.swift
1
1322
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit extension UILabel { override open func awakeFromNib() { let size = font.pointSize font = UIFont.systemFont(ofSize: size) // font = UIFont(name: "CoolSans-Medium", size: size) } } extension UIButton { override open func awakeFromNib() { if let size = titleLabel?.font.pointSize { titleLabel?.font = UIFont.systemFont(ofSize: size) // titleLabel?.font = UIFont(name: "CoolSans-Medium", size: size) } } } extension UITextView { override open func awakeFromNib() { if let size = font?.pointSize { font = UIFont.systemFont(ofSize: size) // font = UIFont(name: "CoolSans-Medium", size: size) } } }
apache-2.0
8b461e8e5994d204520be4841a0e9070
31.243902
76
0.663389
4.210191
false
false
false
false
tadija/AEViewModel
Example/AEViewModelExample/IndexPath+Helpers.swift
1
2198
/** * https://github.com/tadija/AEViewModel * Copyright © 2017-2020 Marko Tadić * Licensed under the MIT license */ import UIKit extension IndexPath { public func next(in tableView: UITableView) -> IndexPath? { var newIndexPath = IndexPath(row: row + 1, section: section) if newIndexPath.row >= tableView.numberOfRows(inSection: section) { let newSection = section + 1 newIndexPath = IndexPath(row: 0, section: newSection) if newSection >= tableView.numberOfSections { return nil } } return newIndexPath } public func previous(in tableView: UITableView) -> IndexPath? { var newIndexPath = IndexPath(row: row - 1, section: section) if newIndexPath.row < 0 { let newSection = section - 1 if newSection < 0 { return nil } let maxRow = tableView.numberOfRows(inSection: newSection) - 1 newIndexPath = IndexPath(row: maxRow, section: newSection) } return newIndexPath } public func next(in collectionView: UICollectionView?) -> IndexPath? { guard let cv = collectionView else { return nil } var newIndexPath = IndexPath(row: row + 1, section: section) if newIndexPath.row >= cv.numberOfItems(inSection: section) { let newSection = section + 1 newIndexPath = IndexPath(item: 0, section: newSection) if newSection >= cv.numberOfSections { return nil } } return newIndexPath } public func previous(in collectionView: UICollectionView?) -> IndexPath? { guard let cv = collectionView else { return nil } var newIndexPath = IndexPath(row: row - 1, section: section) if newIndexPath.row < 0 { let newSection = section - 1 if newSection < 0 { return nil } let maxRow = cv.numberOfItems(inSection: newSection) - 1 newIndexPath = IndexPath(item: maxRow, section: newSection) } return newIndexPath } }
mit
636e1fbfa9da6db20f5c180c02d324cc
31.776119
78
0.579235
5.095128
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/CoreModule/Models/TSModel.swift
1
1420
// // TSModel.swift // TSWeChat // // Created by Hilen on 2/22/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation import ObjectMapper typealias TSModelProtocol = ObjectMapper.Mappable typealias TSMapper = ObjectMapper.Mapper enum GenderType: Int { case female = 0, male } /* 消息内容类型: 0 - 文本 1 - 图片 2 - 语音 3 - 群组提示信息,例如:A 邀请 B,C 加入群聊 4 - 文件 110 - 时间(客户端生成数据) */ enum MessageContentType: String { case Text = "0" case Image = "1" case Voice = "2" case System = "3" case File = "4" case Time = "110" } //服务器返回的是字符串 enum MessageFromType: String { //消息来源类型 case System = "0" // 0是系统 case Personal = "1" // 1是个人 case Group = "2" // 2是群组 case PublicServer = "3" // 服务号 case PublicSubscribe = "4" //订阅号 //消息类型对应的占位图 var placeHolderImage: UIImage { switch (self) { case .Personal: return TSAsset.Icon_avatar.image case .System, .Group, .PublicServer, .PublicSubscribe: return TSAsset.Icon_avatar.image } } } //发送消息的状态 enum MessageSendSuccessType: Int { case success = 0 //消息发送成功 case failed //消息发送失败 case sending //消息正在发送 }
mit
9f23d25294c9a3791e3dd49fd5cf371a
17.014925
62
0.604805
3.201592
false
false
false
false
JGiola/swift
SwiftCompilerSources/Sources/Optimizer/FunctionPasses/EscapeInfoDumper.swift
1
4598
//===--- EscapeInfoDumper.swift - Dumps escape information ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// import SIL /// Dumps the results of escape analysis. /// /// Dumps the EscapeInfo query results for all `alloc_stack` instructions in a function. /// /// This pass is used for testing EscapeInfo. let escapeInfoDumper = FunctionPass(name: "dump-escape-info", { (function: Function, context: PassContext) in print("Escape information for \(function.name):") struct Visitor : EscapeInfoVisitor { var results: Set<String> = Set() mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult { if operand.instruction is ReturnInst { results.insert("return[\(path.projectionPath)]") return .ignore } return .continueWalk } mutating func visitDef(def: Value, path: EscapePath) -> DefResult { guard let arg = def as? FunctionArgument else { return .continueWalkUp } results.insert("arg\(arg.index)[\(path.projectionPath)]") return .walkDown } } for block in function.blocks { for inst in block.instructions { if let allocRef = inst as? AllocRefInst { var walker = EscapeInfo(calleeAnalysis: context.calleeAnalysis, visitor: Visitor()) let escapes = walker.isEscaping(object: allocRef) let results = walker.visitor.results let res: String if escapes { res = "global" } else if results.isEmpty { res = " - " } else { res = Array(results).sorted().joined(separator: ",") } print("\(res): \(allocRef)") } } } print("End function \(function.name)\n") }) /// Dumps the results of address-related escape analysis. /// /// Dumps the EscapeInfo query results for addresses escaping to function calls. /// The `fix_lifetime` instruction is used as marker for addresses and values to query. /// /// This pass is used for testing EscapeInfo. let addressEscapeInfoDumper = FunctionPass(name: "dump-addr-escape-info", { (function: Function, context: PassContext) in print("Address escape information for \(function.name):") var valuesToCheck = [Value]() var applies = [Instruction]() for block in function.blocks { for inst in block.instructions { switch inst { case let fli as FixLifetimeInst: valuesToCheck.append(fli.operand) case is FullApplySite: applies.append(inst) default: break } } } struct Visitor : EscapeInfoVisitor { let apply: Instruction mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult { let user = operand.instruction if user == apply { return .abort } if user is ReturnInst { // Anything which is returned cannot escape to an instruction inside the function. return .ignore } return .continueWalk } } // test `isEscaping(addressesOf:)` for value in valuesToCheck { print("value:\(value)") for apply in applies { let path = AliasAnalysis.getPtrOrAddressPath(for: value) var escapeInfo = EscapeInfo(calleeAnalysis: context.calleeAnalysis, visitor: Visitor(apply: apply)) let escaping = escapeInfo.isEscaping(addressesOf: value, path: path) print(" \(escaping ? "==>" : "- ") \(apply)") } } var eaa = EscapeAliasAnalysis(calleeAnalysis: context.calleeAnalysis) // test `canReferenceSameField` for each pair of `fix_lifetime`. if !valuesToCheck.isEmpty { for lhsIdx in 0..<(valuesToCheck.count - 1) { for rhsIdx in (lhsIdx + 1) ..< valuesToCheck.count { print("pair \(lhsIdx) - \(rhsIdx)") let lhs = valuesToCheck[lhsIdx] let rhs = valuesToCheck[rhsIdx] print(lhs) print(rhs) if eaa.canReferenceSameField( lhs, path: AliasAnalysis.getPtrOrAddressPath(for: lhs), rhs, path: AliasAnalysis.getPtrOrAddressPath(for: rhs)) { print("may alias") } else { print("no alias") } } } } print("End function \(function.name)\n") })
apache-2.0
ef63cfbea2ea1d819bf55c5015cba53f
30.493151
105
0.623749
4.301216
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/TypingIndicatorCell.swift
1
1310
// // TypingIndicatorCell.swift // Avalon-Print // // Created by Roman Mizin on 7/18/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit class TypingIndicatorCell: UICollectionViewCell { static let typingIndicatorHeight: CGFloat = 45 var typingIndicator: TypingBubble = { var typingIndicator = TypingBubble() typingIndicator.typingIndicator.isBounceEnabled = true typingIndicator.typingIndicator.isFadeEnabled = true typingIndicator.isPulseEnabled = true return typingIndicator }() override init(frame: CGRect) { super.init(frame: frame.integral) addSubview(typingIndicator) typingIndicator.frame = CGRect(x: 10, y: 2, width: 72, height: TypingIndicatorCell.typingIndicatorHeight).integral } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() restart() } deinit { typingIndicator.stopAnimating() } func restart() { typingIndicator.backgroundColor = ThemeManager.currentTheme().inputTextViewColor if typingIndicator.isAnimating { typingIndicator.stopAnimating() typingIndicator.startAnimating() } else { typingIndicator.startAnimating() } } }
gpl-3.0
94ca925eef62bf28f49b3c6d3908a674
23.698113
118
0.712758
4.452381
false
false
false
false
radex/SwiftyUserDefaults
Sources/DefaultsKey.swift
2
2512
// // SwiftyUserDefaults // // Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz // // 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 // MARK: - Static keys /// Specialize with value type /// and pass key name to the initializer to create a key. public struct DefaultsKey<ValueType: DefaultsSerializable> { public let _key: String public let defaultValue: ValueType.T? internal var isOptional: Bool public init(_ key: String, defaultValue: ValueType.T) { self._key = key self.defaultValue = defaultValue self.isOptional = false } // Couldn't figure out a way of how to pass a nil/none value from extension, thus this initializer. // Used for creating an optional key (without defaultValue) private init(key: String) { self._key = key self.defaultValue = nil self.isOptional = true } @available(*, unavailable, message: "This key needs a `defaultValue` parameter. If this type does not have a default value, consider using an optional key.") public init(_ key: String) { fatalError() } } public extension DefaultsKey where ValueType: DefaultsSerializable, ValueType: OptionalType, ValueType.Wrapped: DefaultsSerializable { init(_ key: String) { self.init(key: key) } init(_ key: String, defaultValue: ValueType.T) { self._key = key self.defaultValue = defaultValue self.isOptional = true } }
mit
abb3ab5843bbf69e0632d89f0679ab7f
35.897059
161
0.713432
4.570128
false
false
false
false
abonz/Swift
JSONParse/JSONParse/ViewController.swift
32
3365
// // ViewController.swift // JSONParse // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit class ViewController: UIViewController { @IBOutlet weak var image: UIImageView! @IBOutlet weak var tittle: UILabel! @IBOutlet weak var myDescription: UITextView! var dataJSON = NSMutableData() override func viewDidLoad() { super.viewDidLoad() var stringURL:NSString = "https://itunes.apple.com/es/rss/topfreeapplications/limit=10/json" //building NSURL var url = NSURL(string: stringURL as String) //building NSURLRequest var request = NSURLRequest(URL: url!) //connection var connection: NSURLConnection? = NSURLConnection(request: request, delegate: self) if (connection != nil){ println("Connecting...") dataJSON = NSMutableData() } else{ println("Connection failed") } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func connection(connection: NSURLConnection!, didFailWithError error: NSError!){ println("Error: \(error)") } func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!){ println("Received response: \(response)") //restore data dataJSON.length = 0 } func connection(connection: NSURLConnection!, didReceiveData data:NSData!){ self.dataJSON.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!){ var error: NSError? if var dic = NSJSONSerialization.JSONObjectWithData(dataJSON, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary{ //A partir del JSON obtenemos la primera entrada var top1: AnyObject = ((dic["feed"] as! NSDictionary) ["entry"]! as! NSArray) [2] var imgJson: AnyObject = (top1["im:image"] as! NSArray) [2] var url = NSURL(string: imgJson.objectForKey("label") as! String) var data = NSData(contentsOfURL: url!) var img = UIImage(data: data!) image.image = img //get tittle and description var tit = (top1["title"] as! NSDictionary) ["label"] as! NSString var desc = (top1["summary"] as! NSDictionary) ["label"] as! NSString tittle.text = tit as String myDescription.text = desc as String } } }
gpl-3.0
260cde791e70bf6304623741965d2c59
36.808989
151
0.643982
4.793447
false
false
false
false
emilstahl/swift
test/expr/cast/dictionary_coerce.swift
24
749
// RUN: %target-parse-verify-swift class C : Hashable { var x = 0 var hashValue: Int { return x } } func == (x: C, y: C) -> Bool { return true } class D : C {} // Test dictionary upcasts var dictCC = Dictionary<C, C>() var dictCD = Dictionary<C, D>() var dictDC = Dictionary<D, C>() var dictDD = Dictionary<D, D>() dictCC = dictCD dictCC = dictDC dictCC = dictDD dictCD = dictDD dictCD = dictCC // expected-error{{cannot assign value of type 'Dictionary<C, C>' to type 'Dictionary<C, D>'}} dictDC = dictDD dictDC = dictCD // expected-error{{cannot assign value of type 'Dictionary<C, D>' to type 'Dictionary<D, C>'}} dictDD = dictCC // expected-error{{cannot assign value of type 'Dictionary<C, C>' to type 'Dictionary<D, D>'}}
apache-2.0
b471aba20868ce8c2d2c69662204c160
21.029412
110
0.659546
3.069672
false
false
false
false
schluchter/berlin-transport
berlin-transport/berlin-trnsprt/BTConnectionResultListVC.swift
1
1875
// // BTConnectionResultListVC.swift // berlin-transport // // Created by Thomas Schluchter on 11/17/14. // Copyright (c) 2014 Thomas Schluchter. All rights reserved. // import Foundation import UIKit class BTConnectionResultListViewController: UITableViewController { var connections: [BTConnection]? var selectedConnection: BTConnection! override func viewDidLoad() { } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showConnectionMap" { let destVC = segue.destinationViewController as! BTConnectionMapVC destVC.connection = self.selectedConnection } } } extension BTConnectionResultListViewController: UITableViewDelegate { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let connections = self.connections { self.selectedConnection = connections[indexPath.row] as BTConnection self.performSegueWithIdentifier("showConnectionMap", sender: self) } else { NSException(name: "No connections found", reason: nil, userInfo: nil).raise() } } } extension BTConnectionResultListViewController: UITableViewDataSource { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return connections!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("IndividualConnection", forIndexPath: indexPath) as! UITableViewCell let connection = connections![indexPath.row] cell.textLabel?.text = "\(connection.startDate)" cell.detailTextLabel?.text = "\(connection.travelTime)s" return cell } }
mit
1c5fc5d421c3aeeb8fe114e7b9ae6feb
35.784314
131
0.714133
5.266854
false
false
false
false
adrfer/swift
stdlib/private/SwiftPrivate/ShardedAtomicCounter.swift
2
2572
//===----------------------------------------------------------------------===// // // 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 SwiftShims public func _stdlib_getHardwareConcurrency() -> Int { // This is effectively a re-export of this shims function // for consumers of the unstable library (like unittest) to // use. return _swift_stdlib_getHardwareConcurrency() } /// An atomic counter for contended applications. /// /// This is a struct to prevent extra retains/releases. You are required to /// call `deinit()` to release the owned memory. public struct _stdlib_ShardedAtomicCounter { // Using an array causes retains/releases, which create contention on the // reference count. // FIXME: guard every element against false sharing. var _shardsPtr: UnsafeMutablePointer<Int> var _shardsCount: Int public init() { let hardwareConcurrency = _stdlib_getHardwareConcurrency() let count = max(8, hardwareConcurrency * hardwareConcurrency) let shards = UnsafeMutablePointer<Int>.alloc(count) for i in 0..<count { (shards + i).initialize(0) } self._shardsPtr = shards self._shardsCount = count } public func `deinit`() { self._shardsPtr.destroy(self._shardsCount) self._shardsPtr.dealloc(self._shardsCount) } public func add(operand: Int, randomInt: Int) { let shardIndex = Int(UInt(bitPattern: randomInt) % UInt(self._shardsCount)) _swift_stdlib_atomicFetchAddInt( object: self._shardsPtr + shardIndex, operand: operand) } // FIXME: non-atomic as a whole! public func getSum() -> Int { var result = 0 let shards = self._shardsPtr let count = self._shardsCount for i in 0..<count { result += _swift_stdlib_atomicLoadInt(object: shards + i) } return result } public struct PRNG { var _state: Int public init() { _state = Int(Int32(bitPattern: rand32())) } public mutating func randomInt() -> Int { var result = 0 for _ in 0..<Int._sizeInBits { result = (result << 1) | (_state & 1) _state = (_state >> 1) ^ (-(_state & 1) & Int(bitPattern: 0xD0000001)) } return result } } }
apache-2.0
d2c568df7f3bc308b96fb938ad2cff55
29.987952
80
0.629082
4.182114
false
false
false
false
rvanmelle/LeetSwift
Problems.playground/Pages/Add Linked Lists.xcplaygroundpage/Contents.swift
1
1502
//: Playground - noun: a place where people can play /* 2. Add Two Numbers https://leetcode.com/problems/add-two-numbers/#/description You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 */ import UIKit import Foundation import XCTest extension ListNode { public var asInteger : Int? { return (description as NSString).integerValue } var reversed : ListNode { return description.asReversedIntegerList! } } extension String { var asReversedIntegerList: ListNode? { let chars : [Character] = Array(characters) let charsReversed = chars.reversed() let intsReversed = charsReversed.map { (ch) -> Int in return (ch.description as NSString).integerValue } return ListNode(intsReversed) } } func addTwoNumbers(_ l1: ListNode, _ l2: ListNode) -> ListNode? { let sum = l1.reversed.asInteger! + l2.reversed.asInteger! return sum.description.asReversedIntegerList } let x1 : ListNode = ListNode([2,4,3])! let x2 : ListNode = ListNode([5,6,4])! let result = addTwoNumbers(x1, x2) if let result = result { XCTAssert(result.asInteger == 708) } else { XCTAssert(false) }
mit
2ea49d6117d39a5e3ea1d9b10b75d785
25.821429
220
0.680426
3.881137
false
false
false
false
ichu501/animated-tab-bar
RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift
1
9019
// AnimationTabBarController.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class RAMAnimatedTabBarItem: UITabBarItem { @IBOutlet weak var animation: RAMItemAnimation! @IBInspectable var textColor: UIColor = UIColor.blackColor() func playAnimation(icon: UIImageView, textLabel: UILabel) { assert(animation != nil, "add animation in UITabBarItem") if animation != nil { animation.playAnimation(icon, textLabel: textLabel) } } func deselectAnimation(icon: UIImageView, textLabel: UILabel) { if animation != nil { animation.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor) } } func selectedState(icon: UIImageView, textLabel: UILabel) { if animation != nil { animation.selectedState(icon, textLabel: textLabel) } } } class RAMAnimatedTabBarController: UITabBarController { var iconsView: [(icon: UIImageView, textLabel: UILabel)] = Array() // MARK: life circle override func viewDidLoad() { super.viewDidLoad() let containers = createViewContainers() createCustomIcons(containers) } // MARK: create methods func createCustomIcons(containers : NSDictionary) { if let items = tabBar.items { let itemsCount = tabBar.items!.count as Int - 1 var index = 0 for item in self.tabBar.items as! [RAMAnimatedTabBarItem] { assert(item.image != nil, "add image icon in UITabBarItem") var container : UIView = containers["container\(itemsCount-index)"] as! UIView container.tag = index var icon = UIImageView(image: item.image) icon.setTranslatesAutoresizingMaskIntoConstraints(false) icon.tintColor = UIColor.clearColor() // text var textLabel = UILabel() textLabel.text = item.title textLabel.backgroundColor = UIColor.clearColor() textLabel.textColor = item.textColor textLabel.font = UIFont.systemFontOfSize(10) textLabel.textAlignment = NSTextAlignment.Center textLabel.setTranslatesAutoresizingMaskIntoConstraints(false) container.addSubview(icon) createConstraints(icon, container: container, size: item.image!.size, yOffset: -5) container.addSubview(textLabel) let textLabelWidth = tabBar.frame.size.width / CGFloat(tabBar.items!.count) - 5.0 createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16) let iconsAndLabels = (icon:icon, textLabel:textLabel) iconsView.append(iconsAndLabels) if 0 == index { // selected first elemet item.selectedState(icon, textLabel: textLabel) } item.image = nil item.title = "" index++ } } } func createConstraints(view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) { var constX = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: container, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) container.addConstraint(constX) var constY = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: container, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: yOffset) container.addConstraint(constY) var constW = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: size.width) view.addConstraint(constW) var constH = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: size.height) view.addConstraint(constH) } func createViewContainers() -> NSDictionary { var containersDict = NSMutableDictionary() let itemsCount : Int = tabBar.items!.count as Int - 1 for index in 0...itemsCount { var viewContainer = createViewContainer() containersDict.setValue(viewContainer, forKey: "container\(index)") } var keys = containersDict.allKeys var formatString = "H:|-(0)-[container0]" for index in 1...itemsCount { formatString += "-(0)-[container\(index)(==container0)]" } formatString += "-(0)-|" var constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:NSLayoutFormatOptions.DirectionRightToLeft, metrics: nil, views: containersDict as [NSObject : AnyObject]) view.addConstraints(constranints) return containersDict } func createViewContainer() -> UIView { var viewContainer = UIView(); viewContainer.backgroundColor = UIColor.clearColor() // for test viewContainer.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(viewContainer) // add gesture var tapGesture = UITapGestureRecognizer(target: self, action: "tapHandler:") tapGesture.numberOfTouchesRequired = 1 viewContainer.addGestureRecognizer(tapGesture) // add constrains var constY = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) view.addConstraint(constY) var constH = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tabBar.frame.size.height) viewContainer.addConstraint(constH) return viewContainer } // MARK: actions func tapHandler(gesture:UIGestureRecognizer) { let items = tabBar.items as! [RAMAnimatedTabBarItem] let currentIndex = gesture.view!.tag if selectedIndex != currentIndex { var animationItem : RAMAnimatedTabBarItem = items[currentIndex] var icon = iconsView[currentIndex].icon var textLabel = iconsView[currentIndex].textLabel animationItem.playAnimation(icon, textLabel: textLabel) let deselelectIcon = iconsView[selectedIndex].icon let deselelectTextLabel = iconsView[selectedIndex].textLabel let deselectItem = items[selectedIndex] deselectItem.deselectAnimation(deselelectIcon, textLabel: deselelectTextLabel) selectedIndex = gesture.view!.tag } } }
mit
da8f2a2cd0255b8d493c1b78206e03e6
37.054852
129
0.609935
5.729987
false
false
false
false
LeeShiYoung/DouYu
DouYuAPP/DouYuAPP/Classes/Room/Controller/Yo_RoomNormalViewController.swift
1
1698
// // Yo_RoomNormalViewController.swift // DouYuAPP // // Created by shying li on 2017/4/10. // Copyright © 2017年 李世洋. All rights reserved. // import UIKit import FDFullscreenPopGesture class Yo_RoomNormalViewController: GenericViewController<Yo_RoomNormalContentView> { override func viewDidLoad() { super.viewDidLoad() fd_prefersNavigationBarHidden = true roomNormalViewModel.loadLiveUrl { (liveUrl) in contentView.roomNormalconfigurePlayer(liveString: liveUrl) contentView.player?.prepareToPlay() } contentView.portraitLiveControlView.delegate = roomNormalViewModel contentView.landscapeLiveControlView.delegate = roomNormalViewModel } fileprivate lazy var roomNormalViewModel: Yo_RoomNormalViewModel = {[weak self] in let roomNormalViewModel = Yo_RoomNormalViewModel() roomNormalViewModel.delegate = self return roomNormalViewModel; }() override func viewDidDisappear(_ animated: Bool) { super.viewWillDisappear(animated) contentView.player?.shutdown() } } extension Yo_RoomNormalViewController: Yo_RoomNormalViewModelDelegate { func roomNormalViewModelFullScreen(controlView: UIView, Orientation: UIInterfaceOrientation) { switch Orientation { case .landscapeRight: fd_interactivePopDisabled = true // 设置横屏UI contentView.landscapeUI() case .portrait: // 设置竖屏 fd_interactivePopDisabled = false contentView.portraitUI() default: break } } }
apache-2.0
b48badd39f148947c872adce3fdde2e4
28.350877
98
0.661686
5.147692
false
false
false
false
gdoublezero00/SocketConnectorForSwift
SocketConnector/AppDelegate.swift
1
6139
// // AppDelegate.swift // SocketConnector // // Created by tornado on 10/10/14. // Copyright (c) 2014 self. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "self.SocketConnector" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SocketConnector", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SocketConnector.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
8bcccbaf70f89edfc68ffc801cde46da
54.306306
290
0.717706
5.813447
false
false
false
false
spoonik/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/AnimatedPropertiesInterfaceController.swift
14
3422
// // AnimatedPropertiesInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/13. // Copyright © 2015年 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class AnimatedPropertiesInterfaceController: WKInterfaceController { @IBOutlet weak var image: WKInterfaceImage! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } // ========================================================================= // MARK: - Actions @IBAction func scaleBtnTapped() { self.animateWithDuration(0.5) { () -> Void in self.image.setWidth(100) self.image.setHeight(160) } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * double_t(NSEC_PER_SEC))) let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_after(when, queue) { () -> Void in dispatch_async(dispatch_get_main_queue(), { self.animateWithDuration(0.5, animations: { () -> Void in self.image.setWidth(50) self.image.setHeight(80) }) }) } } @IBAction func fadeBtnTapped() { self.animateWithDuration(0.5) { () -> Void in self.image.setAlpha(0.0) } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * double_t(NSEC_PER_SEC))) let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_after(when, queue) { () -> Void in dispatch_async(dispatch_get_main_queue(), { self.animateWithDuration(0.5, animations: { () -> Void in self.image.setAlpha(1.0) }) }) } } @IBAction func moveBtnTapped() { self.animateWithDuration(0.5) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Right) } let when1 = dispatch_time(DISPATCH_TIME_NOW, Int64(0.8 * double_t(NSEC_PER_SEC))) let queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_after(when1, queue1) { () -> Void in dispatch_async(dispatch_get_main_queue(), { self.animateWithDuration(0.2) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Left) } }) } let when2 = dispatch_time(DISPATCH_TIME_NOW, Int64(1.2 * double_t(NSEC_PER_SEC))) let queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_after(when2, queue2) { () -> Void in dispatch_async(dispatch_get_main_queue(), { self.animateWithDuration(0.5) { () -> Void in self.image.setHorizontalAlignment(WKInterfaceObjectHorizontalAlignment.Center) } }) } } }
mit
81977e00bc875a9846a47d41d803c8af
32.851485
98
0.570927
4.528477
false
false
false
false
EZ-NET/CodePiece
XcodeSourceEditorExtension/CodePieceUrl.swift
1
954
// // CodePieceUrl.swift // XcodeSourceEditorExtension // // Created by Tomohiro Kumagai on 2020/02/21. // Copyright © 2020 Tomohiro Kumagai. All rights reserved. // import Foundation struct CodePieceUrlScheme { var method: String var language: String? = nil var code: String? = nil } extension URL { init?(_ url: CodePieceUrlScheme) { var components = URLComponents() #if DEBUG components.scheme = "codepiece-beta" #else components.scheme = "codepiece" #endif components.host = "open" var queryItems: [URLQueryItem] { var items = [URLQueryItem]() if let language = url.language { items.append(.init(name: "language", value: language)) } if let code = url.code { items.append(.init(name: "code", value: code)) } return items } components.queryItems = queryItems guard let instance = components.url else { return nil } self = instance } }
gpl-3.0
f38335636cf3d6a0ed9f1f3c37ea64d1
15.431034
59
0.64638
3.52963
false
false
false
false
swifth/SwifthDB
Pod/Classes/OrderBy.swift
2
1618
// // Filter.swift // SwiftyDB // // Created by Øyvind Grimnes on 17/01/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation /** An instance of the Filter class is used to filter query results All filters are automatically converted into SQLite statements when querying the database. To make filtering easier, and backwards compatibility, it is possible to instantiate a filter object as a dictionary literal **Example:** Return any objects with the name 'Ghost' ``` let filter: Filter = ["name": "Ghost"] let filter = Filter.equal("name", value: "Ghost") ``` */ public enum OrderDirection: String { case Asc = "asc" case Desc = "desc" } struct OrderTuple { let filedName : String let orderDirection : OrderDirection func statement() -> String { switch orderDirection { case .Asc: return "\(filedName) \(orderDirection.rawValue)" case .Desc: return "\(filedName) \(orderDirection.rawValue)" } } } public class OrderBy { private var orderFileds: [OrderTuple] = [] /** Initialize a new, empty Filter object */ public init() {} public func appendOrderBy(filedName: String, direction: OrderDirection) -> OrderBy { let ot = OrderTuple(filedName: filedName, orderDirection: direction) orderFileds.append(ot) return self } func statement() -> String { let statement = "orderby " + self.orderFileds.map {$0.statement()}.joinWithSeparator(" , ") return statement } }
apache-2.0
2e48aa76f3a75474fd0c53c8fa4368a8
22.42029
124
0.631807
4.320856
false
false
false
false
ejeinc/MetalScope
Sources/Rotation.swift
1
3258
// // Rotation.swift // MetalScope // // Created by Jun Tanaka on 2017/01/17. // Copyright © 2017 eje Inc. All rights reserved. // import GLKit public struct Rotation { public var matrix: GLKMatrix3 public init(matrix: GLKMatrix3 = GLKMatrix3Identity) { self.matrix = matrix } } extension Rotation { public static let identity = Rotation() } extension Rotation { public init(_ glkMatrix3: GLKMatrix3) { self.init(matrix: glkMatrix3) } public var glkMatrix3: GLKMatrix3 { get { return matrix } set(value) { matrix = value } } } extension Rotation { public init(_ glkQuaternion: GLKQuaternion) { self.init(GLKMatrix3MakeWithQuaternion(glkQuaternion)) } public var glkQuartenion: GLKQuaternion { get { return GLKQuaternionMakeWithMatrix3(glkMatrix3) } set(value) { glkMatrix3 = GLKMatrix3MakeWithQuaternion(value) } } } extension Rotation { public init(radians: Float, aroundVector vector: GLKVector3) { self.init(GLKMatrix3MakeRotation(radians, vector.x, vector.y, vector.z)) } public init(x: Float) { self.init(GLKMatrix3MakeXRotation(x)) } public init(y: Float) { self.init(GLKMatrix3MakeYRotation(y)) } public init(z: Float) { self.init(GLKMatrix3MakeZRotation(z)) } } extension Rotation { public mutating func rotate(byRadians radians: Float, aroundAxis axis: GLKVector3) { glkMatrix3 = GLKMatrix3RotateWithVector3(glkMatrix3, radians, axis) } public mutating func rotate(byX radians: Float) { glkMatrix3 = GLKMatrix3RotateX(glkMatrix3, radians) } public mutating func rotate(byY radians: Float) { glkMatrix3 = GLKMatrix3RotateY(glkMatrix3, radians) } public mutating func rotate(byZ radians: Float) { glkMatrix3 = GLKMatrix3RotateZ(glkMatrix3, radians) } public mutating func invert() { glkQuartenion = GLKQuaternionInvert(glkQuartenion) } public mutating func normalize() { glkQuartenion = GLKQuaternionNormalize(glkQuartenion) } } extension Rotation { public func rotated(byRadians radians: Float, aroundAxis axis: GLKVector3) -> Rotation { var r = self r.rotate(byRadians: radians, aroundAxis: axis) return r } public func rotated(byX x: Float) -> Rotation { var r = self r.rotate(byX: x) return r } public func rotated(byY y: Float) -> Rotation { var r = self r.rotate(byY: y) return r } public func rotated(byZ z: Float) -> Rotation { var r = self r.rotate(byZ: z) return r } public func inverted() -> Rotation { var r = self r.invert() return r } public func normalized() -> Rotation { var r = self r.normalize() return r } } public func * (lhs: Rotation, rhs: Rotation) -> Rotation { return Rotation(GLKMatrix3Multiply(lhs.glkMatrix3, rhs.glkMatrix3)) } public func * (lhs: Rotation, rhs: GLKVector3) -> GLKVector3 { return GLKMatrix3MultiplyVector3(lhs.glkMatrix3, rhs) }
mit
8f1bb87554a5b23f0ee0e2881a982de7
22.099291
92
0.624808
3.800467
false
false
false
false
NijiDigital/NetworkStack
Example/SimpleDemo/Pods/OHHTTPStubs/Sources/OHHTTPStubsSwift/OHHTTPStubsSwift.swift
2
17214
/*********************************************************************************** * * Copyright (c) 2012 Olivier Halligon * * 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. * ***********************************************************************************/ /** * Swift Helpers */ import Foundation #if SWIFT_PACKAGE import OHHTTPStubs #endif #if !swift(>=3.0) extension HTTPStubs { private class func stubRequests(passingTest: HTTPStubsTestBlock, withStubResponse: HTTPStubsResponseBlock) -> HTTPStubsDescriptor { return stubRequestsPassingTest(passingTest, withStubResponse: withStubResponse) } } extension NSURLRequest { var httpMethod: String? { return HTTPMethod } var url: NSURL? { return URL } } extension NSURLComponents { private convenience init?(url: NSURL, resolvingAgainstBaseURL: Bool) { self.init(URL: url, resolvingAgainstBaseURL: resolvingAgainstBaseURL) } } private typealias URLRequest = NSURLRequest extension URLRequest { private func value(forHTTPHeaderField key: String) -> String? { return valueForHTTPHeaderField(key) } } extension String { private func contains(string: String) -> Bool { return rangeOfString(string) != nil } } #else extension URLRequest { public var ohhttpStubs_httpBody: Data? { return (self as NSURLRequest).ohhttpStubs_HTTPBody() } } #endif // MARK: Syntaxic Sugar for OHHTTPStubs /** * Helper to return a `HTTPStubsResponse` given a fixture path, status code and optional headers. * * - Parameter filePath: the path of the file fixture to use for the response * - Parameter status: the status code to use for the response * - Parameter headers: the HTTP headers to use for the response * * - Returns: The `HTTPStubsResponse` instance that will stub with the given status code * & headers, and use the file content as the response body. */ #if swift(>=3.0) public func fixture(filePath: String, status: Int32 = 200, headers: [AnyHashable: Any]?) -> HTTPStubsResponse { return HTTPStubsResponse(fileAtPath: filePath, statusCode: status, headers: headers) } #else public func fixture(filePath: String, status: Int32 = 200, headers: [NSObject: AnyObject]?) -> HTTPStubsResponse { return HTTPStubsResponse(fileAtPath: filePath, statusCode: status, headers: headers) } #endif /** * Helper to call the stubbing function in a more concise way? * * - Parameter condition: the matcher block that determine if the request will be stubbed * - Parameter response: the stub reponse to use if the request is stubbed * * - Returns: The opaque `HTTPStubsDescriptor` that uniquely identifies the stub * and can be later used to remove it with `removeStub:` */ #if swift(>=3.0) @discardableResult public func stub(condition: @escaping HTTPStubsTestBlock, response: @escaping HTTPStubsResponseBlock) -> HTTPStubsDescriptor { return HTTPStubs.stubRequests(passingTest: condition, withStubResponse: response) } #else public func stub(condition: HTTPStubsTestBlock, response: HTTPStubsResponseBlock) -> HTTPStubsDescriptor { return HTTPStubs.stubRequests(passingTest: condition, withStubResponse: response) } #endif // MARK: Create HTTPStubsTestBlock matchers /** * Matcher testing that the `NSURLRequest` is using the **GET** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the GET method */ public func isMethodGET() -> HTTPStubsTestBlock { return { $0.httpMethod == "GET" } } /** * Matcher testing that the `NSURLRequest` is using the **POST** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the POST method */ public func isMethodPOST() -> HTTPStubsTestBlock { return { $0.httpMethod == "POST" } } /** * Matcher testing that the `NSURLRequest` is using the **PUT** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the PUT method */ public func isMethodPUT() -> HTTPStubsTestBlock { return { $0.httpMethod == "PUT" } } /** * Matcher testing that the `NSURLRequest` is using the **PATCH** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the PATCH method */ public func isMethodPATCH() -> HTTPStubsTestBlock { return { $0.httpMethod == "PATCH" } } /** * Matcher testing that the `NSURLRequest` is using the **DELETE** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the DELETE method */ public func isMethodDELETE() -> HTTPStubsTestBlock { return { $0.httpMethod == "DELETE" } } /** * Matcher testing that the `NSURLRequest` is using the **HEAD** `HTTPMethod` * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * is using the HEAD method */ public func isMethodHEAD() -> HTTPStubsTestBlock { return { $0.httpMethod == "HEAD" } } /** * Matcher for testing an `NSURLRequest`'s **absolute url string**. * * e.g. the absolute url string is `https://api.example.com/signin?user=foo&password=123#anchor` in `https://api.example.com/signin?user=foo&password=123#anchor` * * - Parameter url: The absolute url string to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * has the given absolute url */ public func isAbsoluteURLString(_ url: String) -> HTTPStubsTestBlock { return { req in req.url?.absoluteString == url } } /** * Matcher for testing an `NSURLRequest`'s **scheme**. * * e.g. the scheme part is `https` in `https://api.example.com/signin` * * - Parameter scheme: The scheme to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * has the given scheme */ public func isScheme(_ scheme: String) -> HTTPStubsTestBlock { precondition(!scheme.contains("://"), "The scheme part of an URL never contains '://'. Only use strings like 'https' for this value, and not things like 'https://'") precondition(!scheme.contains("/"), "The scheme part of an URL never contains any slash. Only use strings like 'https' for this value, and not things like 'https://api.example.com/'") return { req in req.url?.scheme == scheme } } /** * Matcher for testing an `NSURLRequest`'s **host**. * * e.g. the host part is `api.example.com` in `https://api.example.com/signin`. * * - Parameter host: The host to match (e.g. 'api.example.com') * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * has the given host */ public func isHost(_ host: String) -> HTTPStubsTestBlock { precondition(!host.contains("/"), "The host part of an URL never contains any slash. Only use strings like 'api.example.com' for this value, and not things like 'https://api.example.com/'") return { req in req.url?.host == host } } /** * Matcher for testing an `NSURLRequest`'s **path**. * * e.g. the path is `/signin` in `https://api.example.com/signin`. * * - Parameter path: The path to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request * has exactly the given path * * - Note: URL paths are usually absolute and thus starts with a '/' (which you * should include in the `path` parameter unless you're testing relative URLs) */ public func isPath(_ path: String) -> HTTPStubsTestBlock { return { req in req.url?.path == path } } private func getPath(_ req: URLRequest) -> String? { #if swift(>=3.0) return req.url?.path // In Swift 3, path is non-optional #else return req.url?.path #endif } /** * Matcher for testing the start of an `NSURLRequest`'s **path**. * * - Parameter path: The path to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request's * path starts with the given string * * - Note: URL paths are usually absolute and thus starts with a '/' (which you * should include in the `path` parameter unless you're testing relative URLs) */ public func pathStartsWith(_ path: String) -> HTTPStubsTestBlock { return { req in getPath(req)?.hasPrefix(path) ?? false } } /** * Matcher for testing the end of an `NSURLRequest`'s **path**. * * - Parameter path: The path to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request's * path ends with the given string */ public func pathEndsWith(_ path: String) -> HTTPStubsTestBlock { return { req in getPath(req)?.hasSuffix(path) ?? false } } /** * Matcher for testing if the path of an `NSURLRequest` matches a RegEx. * * - Parameter regex: The Regular Expression we want the path to match * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request's * path matches the given regular expression * * - Note: URL paths are usually absolute and thus starts with a '/' */ public func pathMatches(_ regex: NSRegularExpression) -> HTTPStubsTestBlock { return { req in guard let path = getPath(req) else { return false } let range = NSRange(location: 0, length: path.utf16.count) #if swift(>=3.0) return regex.firstMatch(in: path, options: [], range: range) != nil #else return regex.firstMatchInString(path, options: [], range: range) != nil #endif } } /** * Matcher for testing if the path of an `NSURLRequest` matches a RegEx. * * - Parameter regexString: The Regular Expression string we want the path to match * - Parameter options: The Regular Expression options to use. * Defaults to no option. Common option includes e.g. `.caseInsensitive`. * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request's * path matches the given regular expression * * - Note: This is a convenience function building an NSRegularExpression * and calling pathMatches(…) with it */ #if swift(>=3.0) public func pathMatches(_ regexString: String, options: NSRegularExpression.Options = []) -> HTTPStubsTestBlock { guard let regex = try? NSRegularExpression(pattern: regexString, options: options) else { return { _ in false } } return pathMatches(regex) } #else public func pathMatches(_ regexString: String, options: NSRegularExpressionOptions = []) -> HTTPStubsTestBlock { guard let regex = try? NSRegularExpression(pattern: regexString, options: options) else { return { _ in false } } return pathMatches(regex) } #endif /** * Matcher for testing an `NSURLRequest`'s **path extension**. * * - Parameter ext: The file extension to match (without the dot) * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds only if the request path * ends with the given extension */ public func isExtension(_ ext: String) -> HTTPStubsTestBlock { return { req in req.url?.pathExtension == ext } } /** * Matcher for testing an `NSURLRequest`'s **query parameters**. * * - Parameter params: The dictionary of query parameters to check the presence for * * - Returns: a matcher (HTTPStubsTestBlock) that succeeds if the request contains * the given query parameters with the given value. * * - Note: There is a difference between: * (1) using `[q:""]`, which matches a query parameter "?q=" with an empty value, and * (2) using `[q:nil]`, which matches a query parameter "?q" without a value at all */ @available(iOS 8.0, OSX 10.10, *) public func containsQueryParams(_ params: [String:String?]) -> HTTPStubsTestBlock { return { req in if let url = req.url { let comps = NSURLComponents(url: url, resolvingAgainstBaseURL: true) if let queryItems = comps?.queryItems { for (k,v) in params { if queryItems.filter({ qi in qi.name == k && qi.value == v }).count == 0 { return false } } return true } } return false } } /** * Matcher testing that the `NSURLRequest` headers contain a specific key * - Parameter name: the name of the key to search for in the `NSURLRequest`'s **allHTTPHeaderFields** property * * - Returns: a matcher that returns true if the `NSURLRequest`'s headers contain a value for the key name */ public func hasHeaderNamed(_ name: String) -> HTTPStubsTestBlock { return { (req: URLRequest) -> Bool in return req.value(forHTTPHeaderField: name) != nil } } /** * Matcher testing that the `NSURLRequest` headers contain a specific key and the key's value is equal to the parameter value * - Parameter name: the name of the key to search for in the `NSURLRequest`'s **allHTTPHeaderFields** property * - Parameter value: the value to compare against the header's value * * - Returns: a matcher that returns true if the `NSURLRequest`'s headers contain a value for the key name and it's value * is equal to the parameter value */ public func hasHeaderNamed(_ name: String, value: String) -> HTTPStubsTestBlock { return { (req: URLRequest) -> Bool in return req.value(forHTTPHeaderField: name) == value } } /** * Matcher testing that the `NSURLRequest` body contain exactly specific data bytes * - Parameter body: the Data bytes to expect * * - Returns: a matcher that returns true if the `NSURLRequest`'s body is exactly the same as the parameter value */ #if swift(>=3.0) public func hasBody(_ body: Data) -> HTTPStubsTestBlock { return { req in (req as NSURLRequest).ohhttpStubs_HTTPBody() == body } } #else public func hasBody(_ body: NSData) -> HTTPStubsTestBlock { return { req in req.OHOHHTTPStubs_HTTPBody() == body } } #endif /** * Matcher testing that the `NSURLRequest` body contains a JSON object with the same keys and values * - Parameter jsonObject: the JSON object to expect * * - Returns: a matcher that returns true if the `NSURLRequest`'s body contains a JSON object with the same keys and values as the parameter value */ #if swift(>=3.0) public func hasJsonBody(_ jsonObject: [AnyHashable : Any]) -> HTTPStubsTestBlock { return { req in guard let httpBody = req.ohhttpStubs_httpBody, let jsonBody = (try? JSONSerialization.jsonObject(with: httpBody, options: [])) as? [AnyHashable : Any] else { return false } return NSDictionary(dictionary: jsonBody).isEqual(to: jsonObject) } } #endif // MARK: Operators on HTTPStubsTestBlock /** * Combine different `HTTPStubsTestBlock` matchers with an 'OR' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`HTTPStubsTestBlock`) that succeeds if either of the given matchers succeeds */ #if swift(>=3.0) public func || (lhs: @escaping HTTPStubsTestBlock, rhs: @escaping HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in lhs(req) || rhs(req) } } #else public func || (lhs: HTTPStubsTestBlock, rhs: HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in lhs(req) || rhs(req) } } #endif /** * Combine different `HTTPStubsTestBlock` matchers with an 'AND' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`HTTPStubsTestBlock`) that only succeeds if both of the given matchers succeeds */ #if swift(>=3.0) public func && (lhs: @escaping HTTPStubsTestBlock, rhs: @escaping HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in lhs(req) && rhs(req) } } #else public func && (lhs: HTTPStubsTestBlock, rhs: HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in lhs(req) && rhs(req) } } #endif /** * Create the opposite of a given `HTTPStubsTestBlock` matcher. * * - Parameter expr: the matcher to negate * * - Returns: a matcher (HTTPStubsTestBlock) that only succeeds if the expr matcher fails */ #if swift(>=3.0) public prefix func ! (expr: @escaping HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in !expr(req) } } #else public prefix func ! (expr: HTTPStubsTestBlock) -> HTTPStubsTestBlock { return { req in !expr(req) } } #endif
apache-2.0
34fcb7c7236b8d17a0449ed54bfb578b
34.783784
191
0.689345
4.18173
false
true
false
false
openHPI/xikolo-ios
Common/Data/RelationshipKeyPathsObserver.swift
1
4490
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData public final class RelationshipKeyPathsObserver<Object: NSManagedObject>: NSObject { private let keyPaths: Set<RelationshipKeyPath> public init?(for entityType: Object.Type, managedObjectContext: NSManagedObjectContext, keyPaths: Set<String>) { guard !keyPaths.isEmpty else { return nil } let relationships = entityType.entity().relationshipsByName self.keyPaths = Set(keyPaths.compactMap { keyPath in return RelationshipKeyPath(keyPath: keyPath, relationships: relationships) }) super.init() NotificationCenter.default.addObserver(self, selector: #selector(contextDidChangeNotification(notification:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: managedObjectContext) } @objc private func contextDidChangeNotification(notification: NSNotification) { guard let managedObjectContext = notification.object as? NSManagedObjectContext else { return } guard let updatedObjects = notification.userInfo?[NSRefreshedObjectsKey] as? Set<NSManagedObject> else { return } updatedObjects.forEach { object in guard let changedRelationshipKeyPath = object.changedKeyPath(from: self.keyPaths, refreshed: true) else { return } let firstKeyPath = changedRelationshipKeyPath.relationshipKeyPaths.first ?? "" var inverseRelationshipKeyPaths: [String] = changedRelationshipKeyPath.inverseRelationshipKeyPaths.reversed() let lastInverseRelationshipKeyPath = inverseRelationshipKeyPaths.popLast() ?? "" var objects: Set<NSManagedObject> = [object] objects = objects.objects(whenFollowingKeyPaths: inverseRelationshipKeyPaths) managedObjectContext.performAndWait { for object in objects { guard let value = object.value(forKey: lastInverseRelationshipKeyPath) else { continue } if let toManyObjects = value as? Set<NSManagedObject> { toManyObjects.forEach { $0.setValue(object, forKeyPath: firstKeyPath) } } else if let toOneObject = value as? NSManagedObject { toOneObject.setValue(object, forKeyPath: firstKeyPath) } else { assertionFailure("Invalid relationship observed for keyPath: \(lastInverseRelationshipKeyPath)") return } } } } } } private extension NSManagedObject { /// Matches the given key paths to the current changes of this `NSManagedObject`. /// - Parameter keyPaths: The key paths to match the changes for. /// - Returns: The matching relationship key path if found. Otherwise, `nil`. func changedKeyPath(from keyPaths: Set<RelationshipKeyPath>, refreshed: Bool) -> RelationshipKeyPath? { return keyPaths.first { keyPath -> Bool in guard keyPath.destinationEntityName == entity.name || keyPath.destinationEntityName == entity.superentity?.name else { return false } return refreshed || changedValues().keys.contains(keyPath.destinationPropertyName) } } } private extension Set where Element: NSManagedObject { /// Follow the given key paths to get from one set of object to a another /// - Parameter keyPaths: The key paths to follow /// - Returns: The objects when following the given key paths func objects(whenFollowingKeyPaths keyPaths: [String]) -> Set<NSManagedObject> { var objects: Set<NSManagedObject> = self for keyPath in keyPaths { let values = objects.compactMap { object in object.value(forKey: keyPath) } objects.removeAll() for value in values { if let toManyObjects = value as? Set<NSManagedObject> { objects.formUnion(toManyObjects) } else if let toOneObject = value as? NSManagedObject { objects.insert(toOneObject) } else { assertionFailure("Invalid relationship when following keyPaths: \(keyPaths) at '\(keyPath)'") } } } return objects } }
gpl-3.0
7389927de89085f5c2ddcf05a73c27c0
43.009804
145
0.6409
5.696701
false
false
false
false
hayasilin/App-Like-Twitter
SwifferApp/ComposeViewController.swift
1
2544
// // ComposeViewController.swift // SwifferApp // // Created by Kareem Khattab on 11/8/14. // Copyright (c) 2014 Kareem Khattab. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate{ @IBOutlet var sweetTextView: UITextView! = UITextView() @IBOutlet var charRemainingLabel: UILabel! = UILabel() required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() sweetTextView.layer.borderColor = UIColor.blackColor().CGColor sweetTextView.layer.borderWidth = 0.5 sweetTextView.layer.cornerRadius = 5 sweetTextView.delegate = self //Open the keyboard when user hits the TextView sweetTextView.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendSweet(sender: AnyObject) { var sweet:PFObject = PFObject(className: "Sweets") sweet["content"] = sweetTextView.text sweet["sweeter"] = PFUser.currentUser() sweet.saveInBackgroundWithTarget(nil , selector: nil) var push:PFPush = PFPush() push.setChannel("Reload") var data:NSDictionary = ["alert":"", "badge":"0", "content-available":"1","sound":""] push.setData(data) push.sendPushInBackgroundWithTarget(nil, selector: nil) self.navigationController?.popToRootViewControllerAnimated(true) } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{ var newLength:Int = (textView.text as NSString).length + (text as NSString).length - range.length var remainingChar:Int = 140 - newLength charRemainingLabel.text = "\(remainingChar)" return (newLength > 140) ? false : true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
7c3f0dc1f7c7a431916a3caea9cd51b9
28.241379
109
0.623821
5.191837
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/ScatterChartRenderer.swift
6
11469
// // 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.CGBase import UIKit.UIFont @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) -> Float; func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Float; 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 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) { 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; } var y = CGFloat(set.yValForXIndex(xIndex)) * _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: 0.0, 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); } }
gpl-2.0
7d373b195be40557098ae9a4d1acb14c
37.361204
260
0.549394
5.863497
false
false
false
false
eBardX/XestiMonitors
Examples/XestiMonitorsDemo-tvOS/XestiMonitorsDemo/Formatters.swift
1
7520
// // Formatters.swift // XestiMonitorsDemo-tvOS // // Created by J. G. Pusey on 2018-01-11. // // © 2018 J. G. Pusey (see LICENSE.md) // import CoreLocation import Foundation import UIKit import XestiMonitors public func formatAccessibilityElement(_ element: Any) -> String { if let accElem = element as? UIAccessibilityElement, let label = accElem.accessibilityLabel { return label } return "\(element)" } public func formatAssistiveTechnology(_ value: String) -> String { if UIAccessibilityNotificationSwitchControlIdentifier == value { return "Switch Control" } if UIAccessibilityNotificationVoiceOverIdentifier == value { return "VoiceOver" } return value } public func formatAuthorizationStatus(_ value: CLAuthorizationStatus) -> String { switch value { case .authorizedAlways: return "Authorized always" case .authorizedWhenInUse: return "Authorized when in use" case .denied: return "Denied" case .notDetermined: return "Not determined" case .restricted: return "Restricted" } } public func formatBool(_ value: Bool) -> String { return value ? "True" : "False" } public func formatDate(_ value: Date) -> String { return dateFormatter.string(from: value) } public func formatDecimal(_ value: Double, minimumFractionDigits: Int = 0, maximumFractionDigits: Int = 3) -> String { return formatDecimal(NSNumber(value: value), minimumFractionDigits: minimumFractionDigits, maximumFractionDigits: maximumFractionDigits) } public func formatDecimal(_ value: NSNumber, minimumFractionDigits: Int = 0, maximumFractionDigits: Int = 3) -> String { decimalFormatter.maximumFractionDigits = maximumFractionDigits decimalFormatter.minimumFractionDigits = minimumFractionDigits return decimalFormatter.string(from: value) ?? "\(value)" } public func formatFloor(_ value: CLFloor?) -> String { if let level = value?.level { if level > 0 { return "GL+\(formatInteger(level))" } if level < 0 { return "GL-\(formatInteger(abs(level)))" } return "Ground level" } else { return "N/A" } } public func formatFocusHeading(_ value: UIFocusHeading) -> String { var headings: [String] = [] if value.contains(.down) { headings.append("Down") } if value.contains(.left) { headings.append("Left") } if value.contains(.next) { headings.append("Next") } if value.contains(.previous) { headings.append("Previous") } if value.contains(.right) { headings.append("Right") } if value.contains(.up) { headings.append("Up") } if headings.isEmpty { return "Unknown" } return headings.joined(separator: ", ") } @available(tvOS 10.0, *) public func formatFocusItem(_ item: UIFocusItem) -> String { if let object = item as? NSObject { return String(format: "%1$@:%2$p", NSStringFromClass(type(of: item)), object) } else { return NSStringFromClass(type(of: item)) } } public func formatHeadingComponentValues(_ x: CLHeadingComponentValue, _ y: CLHeadingComponentValue, _ z: CLHeadingComponentValue) -> String { return "\(formatDecimal(x)), \(formatDecimal(y)), \(formatDecimal(z))" } public func formatInteger(_ value: Int) -> String { return formatInteger(NSNumber(value: value)) } public func formatInteger(_ value: NSNumber) -> String { return integerFormatter.string(from: value) ?? "\(value)" } public func formatLocationAccuracy(_ value: CLLocationAccuracy) -> String { guard value >= 0 else { return "Invalid" } return "\(formatDecimal(value)) m" } public func formatLocationCoordinate2D(_ value: CLLocationCoordinate2D) -> String { guard CLLocationCoordinate2DIsValid(value) else { return "Invalid" } return "\(formatLatitude(value.latitude)) \(formatLongitude(value.longitude))" } public func formatLocationDistance(_ value: CLLocationDistance) -> String { return "\(formatDecimal(value)) m" } public func formatPercentage(_ value: Float) -> String { return formatPercentage(NSNumber(value: value)) } public func formatPercentage(_ value: NSNumber) -> String { return percentageFormatter.string(from: value) ?? "\(value.floatValue * 100.0)%" } public func formatRect(_ value: CGRect) -> String { return "\(value)" // for now ... } public func formatTimeInterval(_ value: TimeInterval) -> String { return timeIntervalFormatter.string(from: value) ?? "\(value)" } // MARK: - private var dateFormatter: DateFormatter = { var formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium return formatter }() private var decimalFormatter: NumberFormatter = { var formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true return formatter }() private var integerFormatter: NumberFormatter = { var formatter = NumberFormatter() formatter.maximumFractionDigits = 0 formatter.minimumFractionDigits = 0 formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true return formatter }() private var percentageFormatter: NumberFormatter = { var formatter = NumberFormatter() formatter.maximumFractionDigits = 1 formatter.minimumFractionDigits = 0 formatter.numberStyle = .percent formatter.usesGroupingSeparator = true return formatter }() private var timeIntervalFormatter: DateComponentsFormatter = { var formatter = DateComponentsFormatter() formatter.allowedUnits = [.day, .hour, .minute, .second] formatter.unitsStyle = .positional formatter.zeroFormattingBehavior = .pad return formatter }() private func formatLatitude(_ value: CLLocationDegrees) -> String { return formatLocationDegrees(value, directions: (pos: "N", neg: "S")) } private func formatLongitude(_ value: CLLocationDegrees) -> String { return formatLocationDegrees(value, directions: (pos: "E", neg: "W")) } private func formatLocationDegrees(_ value: CLLocationDegrees, directions: (pos: String, neg: String)) -> String { let rawDegrees = value.degrees let degrees = formatInteger(abs(rawDegrees)) let minutes = formatInteger(value.minutes) let seconds = formatDecimal(value.seconds, maximumFractionDigits: 1) let direction = rawDegrees > 0 ? directions.pos : rawDegrees < 0 ? directions.neg : "" return "\(degrees)° \(minutes)′ \(seconds)″ \(direction)" } private extension CLLocationDegrees { var degrees: Int { return Int(rounded(.towardZero)) } var minutes: Int { return Int((abs(self) * 60).modulo(60).rounded(.towardZero)) } var seconds: Double { return (abs(self) * 3_600).modulo(60) } private func modulo(_ mod: CLLocationDegrees) -> CLLocationDegrees { return self - (mod * (self / mod).rounded(.towardZero)) } }
mit
2c3b8e957397e0c642555b831f81a031
25.364912
86
0.637211
4.618316
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/Extensions/UIView+Extension.swift
1
832
import UIKit extension UIView { @nonobjc var parent: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } var recursiveSubviews: [UIView] { var subviews = self.subviews.compactMap({$0}) subviews.forEach { subviews.append(contentsOf: $0.recursiveSubviews) } return subviews } @discardableResult static func fromNib<T: UIView>() -> T? { guard let view = Bundle.main.loadNibNamed(String(describing: T.self), owner: self, options: nil)?.first as? T else { return nil } return view } }
gpl-3.0
34e35bd6c8b6c7afa704f47af6950557
28.714286
137
0.609375
5.104294
false
false
false
false
achappell/dungeonsanddragonscharactersheet
DungeonsDragonsCCTests/CreateCharacter/CreateCharacterAbilityScoreViewControllerTests.swift
1
12347
// // CreateCharacterAbilityScoreViewControllerTests.swift // DungeonsDragonsCC // // Created by Amanda Chappell on 3/4/16. // Copyright © 2016 AmplifiedProjects. All rights reserved. // import XCTest import UIKit import MagicalRecord @testable import DungeonsDragonsCC class CreateCharacterAbilityMock: CreateCharacterAbilityScoreViewController { var didCallRegisterForKeyboardNotifications = false var didCallKeyboardWasShown = false var didCallKeyboardWillBeHidden = false internal override func registerForKeyboardNotifications() { didCallRegisterForKeyboardNotifications = true super.registerForKeyboardNotifications() } internal override func keyboardWasShown(_ aNotification: Notification) { didCallKeyboardWasShown = true super.keyboardWasShown(aNotification) } internal override func keyboardWillBeHidden(_ aNotification: Notification) { didCallKeyboardWillBeHidden = true super.keyboardWillBeHidden(aNotification) } } class CreateCharacterAbilityScoreViewControllerTests: XCTestCase { var viewController: CreateCharacterAbilityScoreViewController! var viewControllerMock: CreateCharacterAbilityMock! var expectation: XCTestExpectation! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. viewController = UIStoryboard.storyboard(.CreateCharacter).instantiateViewController() as CreateCharacterAbilityScoreViewController viewController.performSelector(onMainThread: #selector(UIViewController.loadView), with: nil, waitUntilDone: true) viewControllerMock = CreateCharacterAbilityMock() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() viewController = nil } func testMakeViewController() { let viewController = CreateCharacterAbilityScoreViewController(nibName: nil, bundle: nil) XCTAssertNotNil(viewController, "View Controller failed initialization") } func testSholudRegisterForNotificationsOnViewDidLoad() { let createMock = CreateCharacterAbilityMock() createMock.viewDidLoad() XCTAssertTrue(createMock.didCallRegisterForKeyboardNotifications, "View Controller failed to register for notifications") } func testRegisterForNotificationsProperly() { viewControllerMock.scrollView = UIScrollView() viewControllerMock.registerForKeyboardNotifications() NotificationCenter.default.post(name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.post(name: NSNotification.Name.UIKeyboardWillHide, object: nil) XCTAssertTrue(viewControllerMock.didCallKeyboardWasShown, "View Controller did not call keyBoardWasShown:") XCTAssertTrue(viewControllerMock.didCallKeyboardWillBeHidden, "View Controller did not call keyBroadWillBeHidden:") } func testShouldGoToNextInRightScenario() { viewController.strengthTextField.text = "12" viewController.dexterityTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertTrue(viewController.shouldAllowNextNavigation(), "View Controller did not allow next when it should have") } func testShouldNotGoToNextWithNoData() { XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller allowed next when it should not have") } func testShouldNotGotToNextWithoutDexterity() { viewController.strengthTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Dexterity") } func testShouldNotGotToNextWithoutStrength() { viewController.dexterityTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Strength") } func testShouldNotGotToNextWithoutConstitution() { viewController.strengthTextField.text = "12" viewController.dexterityTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Constitution") } func testShouldNotGotToNextWithoutWisdom() { viewController.strengthTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.dexterityTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Wisdom") } func testShouldNotGotToNextWithoutIntelligence() { viewController.strengthTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.dexterityTextField.text = "12" viewController.charismaTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Intelligence") } func testShouldNotGotToNextWithoutCharisma() { viewController.strengthTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.dexterityTextField.text = "12" XCTAssertFalse(viewController.shouldAllowNextNavigation(), "View Controller did not allow without Charisma") } func testCreateCharacterWithValidInfo() { MagicalRecord.setupCoreDataStack() viewController.strengthTextField.text = "12" viewController.dexterityTextField.text = "12" viewController.constitutionTextField.text = "12" viewController.wisdomTextField.text = "12" viewController.intelligenceTextField.text = "12" viewController.charismaTextField.text = "12" let character = viewController.createCharacter() XCTAssertNotNil(character, "Character was not created correctly") XCTAssertEqual(character.baseAbilityScores.count, 6, "There should be 6 ability scores on the character now") } func testSetActiveFieldOnResponder() { viewController.textFieldDidBeginEditing(viewController.strengthTextField) XCTAssertEqual(viewController.activeField, viewController.strengthTextField) } func testDexAfterStr() { XCTAssertEqual(viewController.nextTextField(viewController.strengthTextField), viewController.dexterityTextField) } func testConAfterDex() { XCTAssertEqual(viewController.nextTextField(viewController.dexterityTextField), viewController.constitutionTextField) } func testIntAfterCon() { XCTAssertEqual(viewController.nextTextField(viewController.constitutionTextField), viewController.intelligenceTextField) } func testWisAfterInt() { XCTAssertEqual(viewController.nextTextField(viewController.intelligenceTextField), viewController.wisdomTextField) } func testChaAfterWis() { XCTAssertEqual(viewController.nextTextField(viewController.wisdomTextField), viewController.charismaTextField) } func testNothingAfterCha() { XCTAssertNil(viewController.nextTextField(viewController.charismaTextField)) } func testNextBarButtonEnabled() { class TestViewController: CreateCharacterAbilityScoreViewController { override func shouldAllowNextNavigation() -> Bool { return true } } let testViewController = TestViewController() testViewController.charismaTextField = UITextField() testViewController.strengthTextField = UITextField() testViewController.dexterityTextField = UITextField() testViewController.constitutionTextField = UITextField() testViewController.intelligenceTextField = UITextField() testViewController.wisdomTextField = UITextField() testViewController.nextBarButtonItem = UIBarButtonItem() testViewController.nextBarButtonItem.isEnabled = false XCTAssertTrue(testViewController.textFieldShouldReturn(testViewController.charismaTextField)) XCTAssertTrue(testViewController.nextBarButtonItem.isEnabled) XCTAssertFalse(testViewController.charismaTextField.isFirstResponder) } func testFirstResponderSwitch() { let expectation = self.expectation(description: "Should become responder") class TestTextField: UITextField { var viewController: CreateCharacterAbilityScoreViewController? var expectation: XCTestExpectation? override func becomeFirstResponder() -> Bool { expectation!.fulfill() XCTAssertTrue(viewController?.dexterityTextField == self) return true } } let testViewController = CreateCharacterAbilityScoreViewController() let dexterity = TestTextField() dexterity.viewController = testViewController dexterity.expectation = expectation testViewController.charismaTextField = UITextField() testViewController.strengthTextField = UITextField() testViewController.dexterityTextField = dexterity testViewController.constitutionTextField = UITextField() testViewController.intelligenceTextField = UITextField() testViewController.wisdomTextField = UITextField() testViewController.nextBarButtonItem = UIBarButtonItem() testViewController.nextBarButtonItem.isEnabled = false XCTAssertTrue(testViewController.textFieldShouldReturn(testViewController.strengthTextField)) waitForExpectations(timeout: 1) { (error) in XCTAssertNil(error) } } func testFirstResponderRelease() { let expectation = self.expectation(description: "Should resign responder") class TestViewController: CreateCharacterAbilityScoreViewController { override func shouldAllowNextNavigation() -> Bool { return true } } class TestTextField: UITextField { var viewController: CreateCharacterAbilityScoreViewController? var expectation: XCTestExpectation? override func resignFirstResponder() -> Bool { XCTAssertTrue(viewController?.charismaTextField == self) expectation!.fulfill() return true } } let testViewController = TestViewController() let charisma = TestTextField() charisma.viewController = testViewController charisma.expectation = expectation testViewController.charismaTextField = charisma testViewController.strengthTextField = UITextField() testViewController.dexterityTextField = UITextField() testViewController.constitutionTextField = UITextField() testViewController.intelligenceTextField = UITextField() testViewController.wisdomTextField = UITextField() testViewController.nextBarButtonItem = UIBarButtonItem() testViewController.nextBarButtonItem.isEnabled = false XCTAssertTrue(testViewController.textFieldShouldReturn(testViewController.charismaTextField)) waitForExpectations(timeout: 1) { (error) in XCTAssertNil(error) } } }
mit
38e9558e8a190d45dcf68d5dda1421c8
39.478689
139
0.731735
5.684162
false
true
false
false
jondwillis/Swinject
Swinject/ResolutionPool.swift
1
1358
// // ResolutionPool.swift // Swinject // // Created by Yoichi Tagaya on 7/28/15. // Copyright (c) 2015 Swinject Contributors. All rights reserved. // import Foundation internal struct ResolutionPool { private static let MaxDepth = 200 private var pool = [ServiceKey: Any]() private var depth: Int = 0 internal subscript(key: ServiceKey) -> Any? { get { return pool[key] } set { pool[key] = newValue } } internal mutating func incrementDepth() { depth++ if depth > ResolutionPool.MaxDepth { // Raises an exception to tell the problem to programmers. (Usually just crashes the program.) // No error is thrown intentionally to avoid 'try' every time to resolve a service. let e = NSException( name: "SwinjectInfiniteRecursiveCall", reason: "Infinite recursive call for circular dependency has been detected. " + "To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.", userInfo: nil) e.raise() } } internal mutating func decrementDepth() { assert(depth > 0, "The depth cannot be negative.") depth-- if depth == 0 { pool = [:] } } }
mit
f60c028c8fed9014cf04f4ccf56db9aa
29.177778
124
0.582474
4.798587
false
false
false
false
apple/swift-argument-parser
Sources/ArgumentParser/Parsing/Name.swift
1
3020
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// enum Name { /// A name (usually multi-character) prefixed with `--` (2 dashes) or equivalent. case long(String) /// A single character name prefixed with `-` (1 dash) or equivalent. /// /// Usually supports mixing multiple short names with a single dash, i.e. `-ab` is equivalent to `-a -b`. case short(Character, allowingJoined: Bool = false) /// A name (usually multi-character) prefixed with `-` (1 dash). case longWithSingleDash(String) } extension Name { init(_ baseName: Substring) { assert(baseName.first == "-", "Attempted to create name for unprefixed argument") if baseName.hasPrefix("--") { self = .long(String(baseName.dropFirst(2))) } else if baseName.count == 2 { // single character "-x" style self = .short(baseName.last!) } else { // long name with single dash self = .longWithSingleDash(String(baseName.dropFirst())) } } } // short argument names based on the synopsisString // this will put the single - options before the -- options extension Name: Comparable { static func < (lhs: Name, rhs: Name) -> Bool { return lhs.synopsisString < rhs.synopsisString } } extension Name: Hashable { } extension Name { enum Case: Equatable { case long case short case longWithSingleDash } var `case`: Case { switch self { case .short: return .short case .longWithSingleDash: return .longWithSingleDash case .long: return .long } } } extension Name { var synopsisString: String { switch self { case .long(let n): return "--\(n)" case .short(let n, _): return "-\(n)" case .longWithSingleDash(let n): return "-\(n)" } } var valueString: String { switch self { case .long(let n): return n case .short(let n, _): return String(n) case .longWithSingleDash(let n): return n } } var allowsJoined: Bool { switch self { case .short(_, let allowingJoined): return allowingJoined default: return false } } /// The instance to match against user input -- this always has /// `allowingJoined` as `false`, since that's the way input is parsed. var nameToMatch: Name { switch self { case .long, .longWithSingleDash: return self case .short(let c, _): return .short(c) } } } extension BidirectionalCollection where Element == Name { var preferredName: Name? { first { $0.case != .short } ?? first } var partitioned: [Name] { filter { $0.case == .short } + filter { $0.case != .short } } }
apache-2.0
2e3a99cb79f46cae3b96a6d5eedd091b
25.26087
107
0.603642
4.097693
false
false
false
false
mohamede1945/quran-ios
Quran/GaplessAudioPlayer.swift
2
4704
// // GaplessAudioPlayer.swift // Quran // // Created by Mohamed Afifi on 5/16/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import AVFoundation import Foundation import MediaPlayer import QueuePlayer import UIKit private class GaplessPlayerItem: AVPlayerItem { let sura: Int init(URL: URL, sura: Int) { self.sura = sura super.init(asset: AVAsset(url: URL), automaticallyLoadedAssetKeys: nil) } fileprivate override var description: String { return super.description + " sura: \(sura)" } } class GaplessAudioPlayer: DefaultAudioPlayer { weak var delegate: AudioPlayerDelegate? let player = QueuePlayer() let timingRetriever: QariTimingRetriever fileprivate var ayahsDictionary: [AVPlayerItem: [AyahNumber]] = [:] init(timingRetriever: QariTimingRetriever) { self.timingRetriever = timingRetriever } func play(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) { let (items, info) = playerItemsForQari(qari, startAyah: startAyah, endAyah: endAyah) timingRetriever.retrieveTiming(for: qari, suras: items.map { $0.sura }) .then(on: .main) { timings -> Void in var mutableTimings = timings if let timeArray = mutableTimings[startAyah.sura] { mutableTimings[startAyah.sura] = Array(timeArray.dropFirst(startAyah.ayah - 1)) } var times: [AVPlayerItem: [Double]] = [:] var ayahs: [AVPlayerItem: [AyahNumber]] = [:] for item in items { var array = unwrap(mutableTimings[item.sura]) if array.last?.ayah == AyahNumber(sura: item.sura, ayah: 999) { array = Array(array.dropLast()) } times[item] = array.enumerated().map { $0 == 0 && $1.ayah.ayah == 1 ? 0 : $1.seconds } ayahs[item] = array.map { $0.ayah } } self.ayahsDictionary = ayahs let startSuraTimes = unwrap(mutableTimings[startAyah.sura]) let startTime = startAyah.ayah == 1 ? 0 : startSuraTimes[0].seconds self.player.onPlaybackEnded = self.onPlaybackEnded() self.player.onPlaybackRateChanged = self.onPlaybackRateChanged() self.player.onPlaybackStartingTimeFrame = { [weak self] (item: AVPlayerItem, timeIndex: Int) in guard let item = item as? GaplessPlayerItem, let ayahs = self?.ayahsDictionary[item] else { return } self?.delegate?.playingAyah(ayahs[timeIndex]) } self.player.play(startTimeInSeconds: startTime, items: items, info: info, boundaries: times) }.cauterize(tag: "QariTimingRetriever.retrieveTiming(for:suras:)") } } extension GaplessAudioPlayer { fileprivate func playerItemsForQari(_ qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> ([GaplessPlayerItem], [PlayerItemInfo]) { let files = filesToPlay(qari: qari, startAyah: startAyah, endAyah: endAyah) let items = files.map { GaplessPlayerItem(URL: $0, sura: $1) } let info = files.map { PlayerItemInfo( title: Quran.nameForSura($1), artist: qari.name, artwork: UIImage(named: qari.imageName) .flatMap { MPMediaItemArtwork(image: $0) }) } return (items, info) } fileprivate func filesToPlay(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> [(URL, Int)] { guard case AudioType.gapless = qari.audioType else { fatalError("Unsupported qari type gapped. Only gapless qaris can be played here.") } // loop over the files var files: [(URL, Int)] = [] for sura in startAyah.sura...endAyah.sura { let fileName = sura.as3DigitString() let localURL = qari.localFolder().appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension) files.append(localURL, sura) } return files } }
gpl-3.0
9e23374e0452f243ef21ded976513d42
38.529412
142
0.62415
4.421053
false
false
false
false
kevinvanderlugt/Exercism-Solutions
swift/linked-list/LinkedList.swift
2
1247
// // LinkedList.swift // exercism-test-runner // // Created by Kevin VanderLugt on 4/22/15. // Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved. // import Foundation class Node<T> { var next, previous: Node? var value: T init(value: T, next: Node?, previous: Node?) { self.next = next self.previous = previous self.value = value } } class Deque<T> { var first, last: Node<T>? init() { } func push(value: T) { let node = Node(value: value, next: nil, previous: last) if let last = last { last.next = node } if first == nil { first = node } last = node } func pop() -> T? { let poppedNode = last last?.previous?.next = nil last = last?.previous return poppedNode?.value } func shift() -> T? { if let node = first { first = node.next return node.value } return nil } func unshift(value: T) { let node = Node(value: value, next: first, previous: nil) if let first = first { first.previous = node } first = node if last == nil { last = node } } }
mit
133e16067e42d3f54d12eae17db16d89
20.517241
65
0.511628
3.790274
false
false
false
false
mono0926/LicensePlist
Sources/LicensePlistCore/Entity/SwiftPackage.swift
1
6033
// // SwiftPackage.swift // LicensePlistCore // // Created by Matthias Buchetics on 20.09.19. // import Foundation public struct SwiftPackage: Equatable { let package: String let repositoryURL: String let revision: String? let version: String? let packageDefinitionVersion: Int } struct SwiftPackageV1: Decodable { struct State: Decodable { let branch: String? let revision: String? let version: String? } let package: String let repositoryURL: String let state: State } struct ResolvedPackagesV1: Decodable { struct Pins: Decodable { let pins: [SwiftPackageV1] } let object: Pins let version: Int } struct SwiftPackageV2: Decodable { struct State: Decodable { let branch: String? let revision: String? let version: String? } let identity: String let location: String let state: State } struct ResolvedPackagesV2: Decodable { let pins: [SwiftPackageV2] let version: Int } extension SwiftPackage { static func loadPackages(_ content: String) -> [SwiftPackage] { guard let data = content.data(using: .utf8) else { return [] } if let resolvedPackagesV1 = try? JSONDecoder().decode(ResolvedPackagesV1.self, from: data) { return resolvedPackagesV1.object.pins.map { SwiftPackage(package: $0.package, repositoryURL: $0.repositoryURL, revision: $0.state.revision, version: $0.state.version, packageDefinitionVersion: 1) } } else if let resolvedPackagesV2 = try? JSONDecoder().decode(ResolvedPackagesV2.self, from: data) { return resolvedPackagesV2.pins.map { SwiftPackage(package: $0.identity, repositoryURL: $0.location, revision: $0.state.revision, version: $0.state.version, packageDefinitionVersion: 2) } } else { return [] } } func toGitHub(renames: [String: String]) -> GitHub? { guard repositoryURL.contains("github.com") else { return nil } let urlParts = repositoryURL .replacingOccurrences(of: "https://", with: "") .replacingOccurrences(of: "http://", with: "") .deletingSuffix("/") .components(separatedBy: "/") let name = urlParts.last?.deletingSuffix(".git") ?? "" let owner: String if urlParts.count >= 3 { // http/https owner = urlParts[urlParts.count - 2] } else { // ssh owner = urlParts.first?.components(separatedBy: ":").last ?? "" } return GitHub(name: name, nameSpecified: renames[name] ?? getDefaultName(for: owner, and: name), owner: owner, version: version) } private func getDefaultName(for owner: String, and name: String) -> String { guard packageDefinitionVersion != 1 else { return package } // In SPM v1 the Package.resolved JSON always contains the correct name, no need for anything else. guard let version = version else { return fallbackName(using: name) } guard let packageDefinitionURL = URL(string: "https://raw.githubusercontent.com/\(owner)/\(name)/\(version)/Package.swift") else { return fallbackName(using: name) } guard let packageDefinition = try? String(contentsOf: packageDefinitionURL) else { return fallbackName(using: name) } return parseName(from: packageDefinition) ?? fallbackName(using: name) } private func fallbackName(using githubName: String) -> String { packageDefinitionVersion == 1 ? package : githubName } func parseName(from packageDefinition: String) -> String? { // Step 1 - Trim the beginning of the Package Description to where the Package object is starting to be defined -> return as a one-liner without spaces let startingPoint = packageDefinition .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) .components(separatedBy: "let package = Package").element(at: 1) guard !startingPoint.isEmpty else { return nil } // Step 2 - Assemble Reduced Package Description // This removes all nested square brackets and everything written after the closing round bracket of the Package definition var nestingRoundBracketsCounter = 0 var nestingSquareBracketsCounter = 0 var reducedPackageDescription = "" parsing: for character in startingPoint { switch character { case "(": nestingRoundBracketsCounter += 1 reducedPackageDescription.append(nestingSquareBracketsCounter == 0 ? "\(character)" : "") case ")": nestingRoundBracketsCounter -= 1 reducedPackageDescription.append(nestingSquareBracketsCounter == 0 ? "\(character)" : "") if nestingRoundBracketsCounter < 1 { break parsing } case "[": nestingSquareBracketsCounter += 1 case "]": nestingSquareBracketsCounter -= 1 default: reducedPackageDescription.append(nestingSquareBracketsCounter == 0 ? "\(character)" : "") } } // Step 3 - Retrieve name from the reduced Package Description // We can now be confident that we only have the top level description which has exactly one name. let name = reducedPackageDescription .replacingOccurrences(of: "name\\s?:\\s?\"", with: "name:\"", options: .regularExpression) .components(separatedBy: "name:\"") .element(at: 1) .components(separatedBy: "\"") .element(at: 0) return name.isEmpty ? nil : name } } extension Array where Element == String { func element(at index: Int) -> String { guard (0 ..< count).contains(index) else { return "" } return String(self[index]) } }
mit
8efad6a0e4794ba6dd75621073eec0ec
34.910714
173
0.618598
4.742925
false
false
false
false
shajrawi/swift
stdlib/public/core/Character.swift
1
8507
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster that approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. Strings are collections of `Character` instances, so /// the number of visible characters is generally the most natural way to /// count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Length: \(greeting.count)") /// // Prints "Length: 8" /// /// Because each character in a string can be made up of one or more Unicode /// scalar values, the number of characters in a string may not match the /// length of the Unicode scalar value representation or the length of the /// string in a particular binary representation. /// /// print("Unicode scalar value count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode scalar value count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode scalar values /// that are grouped together as an *extended grapheme cluster*. The way these /// scalar values are grouped is defined by a canonical, localized, or /// otherwise tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator scalar values that correspond to that country's ISO 3166-1 /// alpha-2 code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a string literal, these two /// scalar values are combined into a single grapheme cluster, represented by /// a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value @_fixed_layout public struct Character { @usableFromInline internal var _str: String @inlinable @inline(__always) internal init(unchecked str: String) { self._str = str _invariantCheck() } } extension Character { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant(_str.count == 1) _internalInvariant(_str._guts.isFastUTF8) _internalInvariant(_str._guts._object.isPreferredRepresentation) } #endif // INTERNAL_CHECKS_ENABLED } extension Character { /// A view of a character's contents as a collection of UTF-8 code units. See /// String.UTF8View for more information public typealias UTF8View = String.UTF8View /// A UTF-8 encoding of `self`. @inlinable public var utf8: UTF8View { return _str.utf8 } /// A view of a character's contents as a collection of UTF-16 code units. See /// String.UTF16View for more information public typealias UTF16View = String.UTF16View /// A UTF-16 encoding of `self`. @inlinable public var utf16: UTF16View { return _str.utf16 } public typealias UnicodeScalarView = String.UnicodeScalarView @inlinable public var unicodeScalars: UnicodeScalarView { return _str.unicodeScalars } } extension Character : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral { /// Creates a character containing the given Unicode scalar value. /// /// - Parameter content: The Unicode scalar value to convert into a character. @inlinable @inline(__always) public init(_ content: Unicode.Scalar) { self.init(unchecked: String(content)) } @inlinable @inline(__always) @_effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self.init(Unicode.Scalar(_builtinUnicodeScalarLiteral: value)) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @inlinable @inline(__always) @_effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self.init(unchecked: String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } /// Creates a character with the specified value. /// /// Do not call this initalizer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. @inlinable @inline(__always) public init(extendedGraphemeClusterLiteral value: Character) { self.init(unchecked: value._str) } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. @inlinable @inline(__always) public init(_ s: String) { _precondition(!s.isEmpty, "Can't form a Character from an empty String") _debugPrecondition(s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") if _fastPath(s._guts._object.isPreferredRepresentation) { self.init(unchecked: s) return } self.init(unchecked: String._copying(s)) } } extension Character : CustomStringConvertible { @inlinable public var description: String { return _str } } extension Character : LosslessStringConvertible { } extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. public var debugDescription: String { return _str.debugDescription } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. @inlinable @inline(__always) public init(_ c: Character) { self.init(c._str._guts) } } extension Character : Equatable { @inlinable @inline(__always) @_effects(readonly) public static func == (lhs: Character, rhs: Character) -> Bool { return lhs._str == rhs._str } } extension Character : Comparable { @inlinable @inline(__always) @_effects(readonly) public static func < (lhs: Character, rhs: Character) -> Bool { return lhs._str < rhs._str } } extension Character: Hashable { // not @inlinable (performance) /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @_effects(releasenone) public func hash(into hasher: inout Hasher) { _str.hash(into: &hasher) } } extension Character { @usableFromInline // @testable internal var _isSmall: Bool { return _str._guts.isSmall } }
apache-2.0
1a472e44e23be16a30a8334e2c810f00
33.262097
96
0.692009
4.291414
false
false
false
false
codefellows/sea-b23-iOS
PushPopnLock/PushPopnLock/ViewController.swift
1
1381
// // ViewController.swift // PushPopnLock // // Created by Bradley Johnson on 10/9/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var countLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.title = "Home" println(self.navigationController?.viewControllers.count) // self.navigationItem.titleView = UIView(frame: CGRect(x: 20, y: 20, width: 50, height: 50)) // self.navigationItem.titleView?.backgroundColor = UIColor.purpleColor() var barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Camera, target: self, action: "cameraPressed") self.navigationItem.rightBarButtonItem = barButton // Do any additional setup after loading the view, typically from a nib. } @IBAction func buttonPressed(sender: AnyObject) { let newVC = self.storyboard?.instantiateViewControllerWithIdentifier("BUTTON_VC") as ViewController newVC.view.backgroundColor = UIColor.redColor() newVC.countLabel.text = "sdofijsdoifj" self.navigationController?.pushViewController(newVC, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
cf211c0f88ac059565790f4216569987
34.410256
129
0.700941
4.795139
false
false
false
false
beni55/ReactiveCocoa
ReactiveCocoaTests/Swift/ObjectiveCBridgingSpec.swift
2
5779
// // ObjectiveCBridgingSpec.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2015-01-23. // Copyright (c) 2015 GitHub. All rights reserved. // import Result import Nimble import Quick import ReactiveCocoa import XCTest class ObjectiveCBridgingSpec: QuickSpec { override func spec() { describe("RACSignal.toSignalProducer") { it("should subscribe once per start()") { var subscriptions = 0 let racSignal = RACSignal.createSignal { subscriber in subscriber.sendNext(subscriptions++) subscriber.sendCompleted() return nil } let producer = racSignal.toSignalProducer().map { $0 as! Int } expect((producer.single())?.value).to(equal(0)) expect((producer.single())?.value).to(equal(1)) expect((producer.single())?.value).to(equal(2)) } it("should forward errors") { let error = TestError.Default as NSError let racSignal = RACSignal.error(error) let producer = racSignal.toSignalProducer() let result = producer.last() expect(result?.error).to(equal(error)) } } describe("toRACSignal") { describe("on a Signal") { it("should forward events") { let (signal, sink) = Signal<NSNumber, NoError>.pipe() let racSignal = toRACSignal(signal) var lastValue: NSNumber? var didComplete = false racSignal.subscribeNext({ number in lastValue = number as? NSNumber }, completed: { didComplete = true }) expect(lastValue).to(beNil()) for number in [1, 2, 3] { sendNext(sink, number) expect(lastValue).to(equal(number)) } expect(didComplete).to(beFalse()) sendCompleted(sink) expect(didComplete).to(beTrue()) } it("should convert errors to NSError") { let (signal, sink) = Signal<AnyObject, TestError>.pipe() let racSignal = toRACSignal(signal) let expectedError = TestError.Error2 var error: NSError? racSignal.subscribeError { error = $0 return } sendError(sink, expectedError) expect(error).to(equal(expectedError as NSError)) } } describe("on a SignalProducer") { it("should start once per subscription") { var subscriptions = 0 let producer = SignalProducer<NSNumber, NoError>.attempt { return .Success(subscriptions++) } let racSignal = toRACSignal(producer) expect(racSignal.first() as? NSNumber).to(equal(0)) expect(racSignal.first() as? NSNumber).to(equal(1)) expect(racSignal.first() as? NSNumber).to(equal(2)) } it("should convert errors to NSError") { let producer = SignalProducer<AnyObject, TestError>(error: .Error1) let racSignal = toRACSignal(producer).materialize() let event = racSignal.first() as? RACEvent expect(event?.error).to(equal(TestError.Error1 as NSError)) } } } describe("RACCommand.toAction") { var command: RACCommand! var results: [Int] = [] var enabledSubject: RACSubject! var enabled = false var action: Action<AnyObject?, AnyObject?, NSError>! beforeEach { enabledSubject = RACSubject() results = [] command = RACCommand(enabled: enabledSubject) { (input: AnyObject?) -> RACSignal! in let inputNumber = input as! Int return RACSignal.`return`(inputNumber + 1) } expect(command).notTo(beNil()) command.enabled.subscribeNext { enabled = $0 as! Bool } expect(enabled).to(beTruthy()) command.executionSignals.flatten().subscribeNext { results.append($0 as! Int) } expect(results).to(equal([])) action = command.toAction() } it("should reflect the enabledness of the command") { expect(action.enabled.value).to(beTruthy()) enabledSubject.sendNext(false) expect(enabled).toEventually(beFalsy()) expect(action.enabled.value).to(beFalsy()) } it("should execute the command once per start()") { let producer = action.apply(0) expect(results).to(equal([])) producer.start() expect(results).toEventually(equal([ 1 ])) producer.start() expect(results).toEventually(equal([ 1, 1 ])) let otherProducer = action.apply(2) expect(results).to(equal([ 1, 1 ])) otherProducer.start() expect(results).toEventually(equal([ 1, 1, 3 ])) producer.start() expect(results).toEventually(equal([ 1, 1, 3, 1 ])) } } describe("toRACCommand") { var action: Action<AnyObject?, NSString, TestError>! var results: [NSString] = [] var enabledProperty: MutableProperty<Bool>! var command: RACCommand! var enabled = false beforeEach { results = [] enabledProperty = MutableProperty(true) action = Action(enabledIf: enabledProperty) { input in let inputNumber = input as! Int return SignalProducer(value: "\(inputNumber + 1)") } expect(action.enabled.value).to(beTruthy()) action.values.observe(next: { results.append($0) }) command = toRACCommand(action) expect(command).notTo(beNil()) command.enabled.subscribeNext { enabled = $0 as! Bool } expect(enabled).to(beTruthy()) } it("should reflect the enabledness of the action") { enabledProperty.value = false expect(enabled).toEventually(beFalsy()) enabledProperty.value = true expect(enabled).toEventually(beTruthy()) } it("should apply and start a signal once per execution") { let signal = command.execute(0) do { try signal.asynchronouslyWaitUntilCompleted() expect(results).to(equal([ "1" ])) try signal.asynchronouslyWaitUntilCompleted() expect(results).to(equal([ "1" ])) try command.execute(2).asynchronouslyWaitUntilCompleted() expect(results).to(equal([ "1", "3" ])) } catch { XCTFail("Failed to wait for completion") } } } } }
mit
a64f7bfe4c16b8752150dc9ef3bbb72f
24.45815
88
0.656169
3.704487
false
false
false
false
QuarkX/Quark
Sources/Mustache/Configuration/Configuration.swift
2
11015
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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. /** Configuration exposes properties that affect both the parsing and the rendering of Mustache templates. ### What can be configured Configuration covers: - **Content type**: HTML templates escape rendered strings, while Text templates do not. Text templates are HTML-escaped as a whole when included in HTML templates. - **Context stack**: values stored in a Configuration's context are readily available to templates. - **Tag delimiters**: default Mustache delimiters are `{{` and `}}`. These are configurable. ### Usage You setup a configuration *before* loading templates: // Template loaded later will not HTML-escape the rendered strings: Mustache.DefaultConfiguration.contentType = .Text // A text template let template = try! Template(string: "...") ### Configuration levels There are three levels of configuration: `Mustache.DefaultConfiguration` is a global variable that applies by default: Mustache.DefaultConfiguration.contentType = .Text // A text template let template = try! Template(named: "Document") `TemplateRepository.configuration` only applies to templates loaded from the template repository: let repository = TemplateRepository(directoryPath: "/path/to/templates") repository.configuration.contentType = .Text // A text template let template = try! repository.template(named: "Document") Templates can also be configured individually. See the documentation of each Configuration method for more details. */ public struct Configuration { // ========================================================================= // MARK: - Factory Configuration /** Returns a factory configuration. Its contentType is HTML, baseContext empty, tag delimiters `{{` and `}}`. For example: // Make sure the template repository uses factory configuration, // regardless of changes made to `Mustache.DefaultConfiguration`: let repository = TemplateRepository(directoryPath: "/path/to/templates") repository.configuration = Configuration() */ public init() { contentType = .HTML baseContext = Context() tagDelimiterPair = ("{{", "}}") } // ========================================================================= // MARK: - Content Type /** The content type of strings rendered by templates built with this configuration. It affects the HTML-escaping of your data: - The `.HTML` content type has templates render HTML. This is the default behavior. HTML template escape the input of variable tags such as `{{name}}`. Use triple mustache tags `{{{content}}}` in order to avoid the HTML-escaping. - The `.Text` content type has templates render text. They do not HTML-escape their input: `{{name}}` and `{{{name}}}` have identical, non-escaped, renderings. GRMustache safely keeps track of the content type of templates: should a HTML template embed a text template, the content of the text template would be HTML-escaped, as a whole. Setting the contentType of a configuration affects the contentType of all templates loaded afterwards: // Globally, with Mustache.DefaultConfiguration: Mustache.DefaultConfiguration.contentType = .Text let textTemplate = try! Template(named: "Script") // Locally, using a TemplateRepository: let repository = TemplateRepository(bundle: NSBundle.mainBundle()) repository.configuration.contentType = .HTML let HTMLTemplate = try! repository.template(named: "HTMLDocument") In order to set the content type of an individual templates, use pragma tags right in the content of your templates: - `{{% CONTENT_TYPE:TEXT }}` turns a template into a text template. - `{{% CONTENT_TYPE:HTML }}` turns a template into a HTML template. For example: {{! This template renders a bash script. }} {{% CONTENT_TYPE:TEXT }} export LANG={{ENV.LANG}} ... These pragmas must be found early in the template (before any value tag). Should several pragmas be found in a template content, the last one wins. */ public var contentType: ContentType // ========================================================================= // MARK: - Context Stack /** The base context for templates rendering. All templates built with this configuration can access values stored in the base context. The default base context is empty. You can set it to some custom context, or extend it with the `extendBaseContext` and `registerInBaseContext` methods. // Globally, with Mustache.DefaultConfiguration: Mustache.DefaultConfiguration.baseContext = Context(Box(["foo": "bar"])) // "bar" let template1 = try! Template(string: "{{foo}}") try! template1.render() // Locally, using a TemplateRepository: let repository = TemplateRepository(bundle: NSBundle.mainBundle()) repository.configuration.baseContext = Context(Box(["foo": "bar"])) // "bar" let template2 = try! repository.template(string: "{{foo}}") try! template2.render() The base context can also be set for individual templates: let template3 = try! Template(string: "{{foo}}") template3.baseContext = Context(Box(["foo": "bar"])) // "bar" try! template3.render() See also: - extendBaseContext - registerInBaseContext */ public var baseContext: Context /** Extends the base context with the provided boxed value. All templates built with this configuration can access its keys. // Globally, with Mustache.DefaultConfiguration: Mustache.DefaultConfiguration.extendBaseContext(Box(["foo": "bar"])) // "bar" let template1 = try! Template(string: "{{foo}}") try! template1.render() // Locally, using a TemplateRepository: let repository = TemplateRepository(bundle: NSBundle.mainBundle()) repository.configuration.extendBaseContext(Box(["foo": "bar"])) // "bar" let template2 = try! repository.template(string: "{{foo}}") try! template2.render() The base context can also be extended for individual templates: let template3 = try! Template(string: "{{foo}}") template3.extendBaseContext(Box(["foo": "bar"])) // "bar" try! template3.render() - parameter box: The box pushed on the top of the context stack. See also: - baseContext - registerInBaseContext */ public mutating func extendBaseContext(box: MustacheBox) { baseContext = baseContext.extendedContext(box) } /** Registers a key in the base context. All renderings will be able to access the provided box through this key. Registered keys are looked up first when evaluating Mustache tags. // Globally, with Mustache.DefaultConfiguration: Mustache.DefaultConfiguration.registerInBaseContext("foo", Box("bar")) // Renders "bar" let template1 = try! Template(string: "{{foo}}") try! template1.render() // Renders "bar" again, because the registered key "foo" has priority. try! template1.render(Box(["foo": "qux"])) // Locally, using a TemplateRepository: let repository = TemplateRepository(bundle: NSBundle.mainBundle()) repository.configuration.registerInBaseContext("foo", Box("bar")) // "bar" let template2 = try! repository.template(string: "{{foo}}") try! template2.render() Keys can also be registered in the base context of individual templates: let template3 = try! Template(string: "{{foo}}") template3.registerInBaseContext("foo", Box("bar")) // "bar" try! template3.render() - parameter key: An identifier. - parameter box: The box registered for *key*. See also: - baseContext - extendBaseContext */ public mutating func registerInBaseContext(key: String, _ box: MustacheBox) { baseContext = baseContext.context(withRegisteredKey: key, box: box) } // ========================================================================= // MARK: - Tag delimiters /** The delimiters for Mustache tags. All templates built with this configuration are parsed using those delimiters. The default value is `("{{", "}}")`. Setting the tagDelimiterPair of a configuration affects all templates loaded afterwards: // Globally, with Mustache.DefaultConfiguration: Mustache.DefaultConfiguration.tagDelimiterPair = ("<%", "%>") let template1 = try! Template(string: "<% name %>) // Locally, using a TemplateRepository: let repository = TemplateRepository() repository.configuration.tagDelimiterPair = ("[[", "]]") let HTMLTemplate = try! repository.template(string: "[[ name ]]") You can also change the delimiters right in your templates using a "Set Delimiter tag": `{{=[[ ]]=}}` changes delimiters to `[[` and `]]`. */ public var tagDelimiterPair: TagDelimiterPair } // ============================================================================= // MARK: - Default Configuration /** The default configuration that is used unless specified otherwise by a `TemplateRepository`. See also: - TemplateRepository */ public var DefaultConfiguration = Configuration()
mit
97ac2c4516a86dd983814df7a392e1df
31.976048
81
0.636826
5.144325
false
true
false
false
davidbutz/ChristmasFamDuels
iOS/Boat Aware/createLeagueViewController.swift
1
4043
// // createLeagueViewController.swift // Christmas Fam Duels // // Created by Dave Butz on 10/28/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import UIKit class createLeagueViewController: FormViewController { typealias JSONArray = Array<AnyObject> typealias JSONDictionary = Dictionary<String, AnyObject> @IBOutlet weak var txtLeagueName: UITextField! @IBAction func onClickCreate(sender: AnyObject) { let leaguename = txtLeagueName.text; if(leaguename!.isEmpty){ displayAlert("League Name is required.", fn: {self.doNothing()}); return; } LoadingOverlay.shared.showOverlay(self.view); LoadingOverlay.shared.setCaption("Creating League..."); let api = APICalls(); let appvar = ApplicationVariables.applicationvariables; let JSONObject: [String : AnyObject] = [ "login_token" : appvar.logintoken ] api.apicallout("/api/setup/league/create/" + appvar.userid + "/" + leaguename!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! + "/" + appvar.logintoken , iptype: "localIPAddress", method: "GET", JSONObject: JSONObject, callback: { (response) -> () in dispatch_async(dispatch_get_main_queue()) { LoadingOverlay.shared.hideOverlayView(); }; let JSONResponse = response as! JSONDictionary; if(JSONResponse["success"] as! Bool){ let leagueID = JSONResponse["leagueID"] as! String; let leagueName = JSONResponse["leagueName"] as! String; let leagueOwnerID = JSONResponse["leagueOwnerID"] as! String; //store these deep. let leaguevar = LeagueVariables.leaguevariables; leaguevar.leagueID = leagueID; leaguevar.leagueName = leagueName; leaguevar.leagueOwnerID = leagueOwnerID; leaguevar.roleID = 1; //move them along to invitations... dispatch_async(dispatch_get_main_queue()) { let inviteFriends = self.storyboard?.instantiateViewControllerWithIdentifier("Invite Friends"); self.presentViewController(inviteFriends!, animated: true, completion: nil); } } }); } override func viewDidLoad() { super.viewDidLoad() txtLeagueName.resignFirstResponder(); // Do any additional setup after loading the view. definesPresentationContext = true; } func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField == txtLeagueName) { onClickCreate(textField); } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func displayAlert(userMessage:String, fn:()->Void){ let myAlert = UIAlertController(title:"Alert",message: userMessage,preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction(title:"Ok",style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in fn()}); myAlert.addAction(okAction); dispatch_async(dispatch_get_main_queue()) { self.presentViewController(myAlert, animated: true, completion: nil); }; } func doNothing(){ } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait; } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
24380de082fe7075538c75a13c9696b7
38.627451
309
0.635824
5.29751
false
false
false
false
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/extensions/UIButtonExtensions.swift
1
3044
// // UIButtonExtensions.swift // BaseVCKit // // Created by frank on 2017. 5. 31.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit fileprivate let intervalImageBetweenText: CGFloat = 6 public extension UIButton { // MARK: - Configure Helper static func configure( image: UIImage?, title: String?, titleColor: UIColor = .white, fontSize: CGFloat = 14, fontWeight: UIFont.Weight = UIFont.Weight.light , bgColor: UIColor = .clear, cornerRadius: CGFloat = 0) -> UIButton { let btn = UIButton(type: .custom) btn.setImage(image, for: .normal) btn.setTitle(title, for: UIControl.State.normal) btn.titleLabel!.font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight) btn.setRoundCorner(radius: cornerRadius) btn.setStatesTitleColor(withNormalColor: titleColor) btn.setStatesBackground(withNormalColor: bgColor) if let _ = image, let _ = title { btn.imageEdgeInsets.right = intervalImageBetweenText/2 btn.titleEdgeInsets.left = intervalImageBetweenText/2 } return btn } // MARK: - Background color func setStatesBackground(withNormalColor color: UIColor) { self.setBackground(color: color, state: .normal) self.setBackground(color: color.withRecursiveAlphaComponent(0.7), state: .highlighted) self.setBackground(color: color, state: .disabled) } func setBackground(color: UIColor, state: UIControl.State) { self.setBackgroundImage(image(withColor: color), for: state) } private func image(withColor color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } // MARK: - Title color func setStatesTitleColor(withNormalColor color: UIColor) { self.setTitleColor(color, for: .normal) self.setTitleColor(color, for: .highlighted) self.setTitleColor(color.withRecursiveAlphaComponent(0.3), for: .disabled) } // MARK: - Min Bounds /** * Should set image and title before call 'minSize' */ var minSize: CGSize { guard let _ = title(for: .normal) else { return CGSize(width: 21, height: 21) // icon only } let marginH: CGFloat = 8 var w: CGFloat = marginH*2 if let img = image(for: .normal) { w += intervalImageBetweenText w += img.size.width } w += self.titleLabel!.intrinsicContentSize.width return CGSize(width: w, height: 30) } // MARK: - Size func widthWithoutEllipsis(paddingH: CGFloat) -> CGFloat { return titleLabel!.intrinsicContentSize.width + paddingH*2 } }
mit
2f6e648f1c09cf3bd419b4fd8882de63
29.108911
94
0.637619
4.426492
false
false
false
false
modocache/swift
stdlib/public/core/BridgeObjectiveC.swift
3
20713
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) /// A Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each element of the source container. public protocol _ObjectiveCBridgeable { associatedtype _ObjectiveCType : AnyObject /// Convert `self` to Objective-C. func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. @discardableResult static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) -> Bool /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for unconditional bridging when /// interoperating with Objective-C code, either in the body of an /// Objective-C thunk or when calling Objective-C code, and may /// defer complete checking until later. For example, when bridging /// from `NSArray` to `Array<Element>`, we can defer the checking /// for the individual elements of the array. /// /// \param source The Objective-C object from which we are /// bridging. This optional value will only be `nil` in cases where /// an Objective-C method has returned a `nil` despite being marked /// as `_Nonnull`/`nonnull`. In most such cases, bridging will /// generally force the value immediately. However, this gives /// bridging the flexibility to substitute a default value to cope /// with historical decisions, e.g., an existing Objective-C method /// that returns `nil` to for "empty result" rather than (say) an /// empty array. In such cases, when `nil` does occur, the /// implementation of `Swift.Array`'s conformance to /// `_ObjectiveCBridgeable` will produce an empty array rather than /// dynamically failing. static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self } //===--- Bridging for metatypes -------------------------------------------===// /// A stand-in for a value of metatype type. /// /// The language and runtime do not yet support protocol conformances for /// structural types like metatypes. However, we can use a struct that contains /// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table /// will be ABI-compatible with one that directly provided conformance to the /// metatype type itself. @_fixed_layout public struct _BridgeableMetatype: _ObjectiveCBridgeable { internal var value: AnyObject.Type public typealias _ObjectiveCType = AnyObject public func _bridgeToObjectiveC() -> AnyObject { return value } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) { result = _BridgeableMetatype(value: source as! AnyObject.Type) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) -> Bool { if let type = source as? AnyObject.Type { result = _BridgeableMetatype(value: type) return true } result = nil return false } public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> _BridgeableMetatype { var result: _BridgeableMetatype? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } //===--- Bridging facilities written in Objective-C -----------------------===// // Functions that must discover and possibly use an arbitrary type's // conformance to a given protocol. See ../runtime/Metadata.cpp for // implementations. //===----------------------------------------------------------------------===// /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// /// COMPILER_INTRINSIC public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, to: AnyObject.self) } return _bridgeAnythingNonVerbatimToObjectiveC(x) } /// COMPILER_INTRINSIC @_silgen_name("_swift_bridgeAnythingNonVerbatimToObjectiveC") public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: T) -> AnyObject /// Convert a purportedly-nonnull `id` value from Objective-C into an Any. /// /// Since Objective-C APIs sometimes get their nullability annotations wrong, /// this includes a failsafe against nil `AnyObject`s, wrapping them up as /// a nil `AnyObject?`-inside-an-`Any`. /// /// COMPILER_INTRINSIC public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any { if let nonnullObject = possiblyNullObject { return nonnullObject // AnyObject-in-Any } return possiblyNullObject // AnyObject?-in-Any } /// Convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, trap; /// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`; /// - otherwise, trap. public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as! T } var result: T? _bridgeNonVerbatimFromObjectiveC(x, T.self, &result) return result! } /// Convert `x` from its Objective-C representation to its Swift /// representation. @_silgen_name("_forceBridgeFromObjectiveC_bridgeable") public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, the result is empty; /// + otherwise, returns the result of /// `T._conditionallyBridgeFromObjectiveC(x)`; /// - otherwise, the result is empty. public func _conditionallyBridgeFromObjectiveC<T>( _ x: AnyObject, _: T.Type ) -> T? { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as? T } var result: T? _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result) return result } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. @_silgen_name("_conditionallyBridgeFromObjectiveC_bridgeable") public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveC") func _bridgeNonVerbatimFromObjectiveC<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) /// Helper stub to upcast to Any and store the result to an inout Any? /// on the C++ runtime's behalf. // COMPILER_INTRINSIC @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCToAny") public func _bridgeNonVerbatimFromObjectiveCToAny( _ x: AnyObject, _ result: inout Any? ) { result = x as Any } /// Helper stub to upcast to Optional on the C++ runtime's behalf. // COMPILER_INTRINSIC @_silgen_name("_swift_bridgeNonVerbatimBoxedValue") public func _bridgeNonVerbatimBoxedValue<NativeType>( _ x: UnsafePointer<NativeType>, _ result: inout NativeType? ) { result = x.pointee } /// Runtime optional to conditionally perform a bridge from an object to a value /// type. /// /// - parameter result: Will be set to the resulting value if bridging succeeds, and /// unchanged otherwise. /// /// - Returns: `true` to indicate success, `false` to indicate failure. @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCConditional") func _bridgeNonVerbatimFromObjectiveCConditional<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) -> Bool /// Determines if values of a given type can be converted to an Objective-C /// representation. /// /// - If `T` is a class type, returns `true`; /// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`. public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool { if _fastPath(_isClassOrObjCExistential(T.self)) { return true } return _isBridgedNonVerbatimToObjectiveC(T.self) } @_silgen_name("_swift_isBridgedNonVerbatimToObjectiveC") func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool /// A type that's bridged "verbatim" does not conform to /// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an /// `AnyObject`. When this function returns true, the storage of an /// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`. public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool { return _isClassOrObjCExistential(T.self) } /// Retrieve the Objective-C type to which the given type is bridged. public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? { if _fastPath(_isClassOrObjCExistential(T.self)) { return T.self } return _getBridgedNonVerbatimObjectiveCType(T.self) } @_silgen_name("_swift_getBridgedNonVerbatimObjectiveCType") func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type? // -- Pointer argument bridging @_transparent internal var _nilNativeObject: AnyObject? { return nil } /// A mutable pointer-to-ObjC-pointer argument. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - `nil`, which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike `UnsafeMutablePointer<Pointee>`, /// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that /// does not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. @_fixed_layout public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */> : Equatable, _Pointer { public let _rawValue: Builtin.RawPointer @_transparent public // COMPILER_INTRINSIC init(_ _rawValue: Builtin.RawPointer) { self._rawValue = _rawValue } /// Access the `Pointee` instance referenced by `self`. /// /// - Precondition: the pointee has been initialized with an instance of type /// `Pointee`. public var pointee: Pointee { /// Retrieve the value the pointer points to. @_transparent get { // We can do a strong load normally. return unsafeBitCast(self, to: UnsafeMutablePointer<Pointee>.self).pointee } /// Set the value the pointer points to, copying over the previous value. /// /// AutoreleasingUnsafeMutablePointers are assumed to reference a /// value with __autoreleasing ownership semantics, like 'NSFoo**' /// in ARC. This autoreleases the argument before trivially /// storing it to the referenced memory. @_transparent nonmutating set { // Autorelease the object reference. typealias OptionalAnyObject = AnyObject? let newAnyObject = unsafeBitCast(newValue, to: OptionalAnyObject.self) Builtin.retain(newAnyObject) Builtin.autorelease(newAnyObject) // Trivially assign it as an OpaquePointer; the pointer references an // autoreleasing slot, so retains/releases of the original value are // unneeded. typealias OptionalUnmanaged = Unmanaged<AnyObject>? UnsafeMutablePointer<Pointee>(_rawValue).withMemoryRebound( to: OptionalUnmanaged.self, capacity: 1) { if let newAnyObject = newAnyObject { $0.pointee = Unmanaged.passUnretained(newAnyObject) } else { $0.pointee = nil } } } } /// Access the `i`th element of the raw array pointed to by /// `self`. /// /// - Precondition: `self != nil`. public subscript(i: Int) -> Pointee { @_transparent get { // We can do a strong load normally. return (UnsafePointer<Pointee>(self) + i).pointee } } /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init<U>(_ from: UnsafeMutablePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from an UnsafeMutablePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init?<U>(_ from: UnsafeMutablePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Explicit construction from a UnsafePointer. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent init<U>(_ from: UnsafePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from a UnsafePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent init?<U>(_ from: UnsafePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension UnsafeMutableRawPointer { /// Convert from `AutoreleasingUnsafeMutablePointer`. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Convert other `AutoreleasingUnsafeMutablePointer`. /// /// Returns nil if `other` is nil. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension UnsafeRawPointer { /// Convert other `AutoreleasingUnsafeMutablePointer`. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Convert other `AutoreleasingUnsafeMutablePointer`. /// /// Returns nil if `other` is nil. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } @_transparent public func == <Pointee>( lhs: AutoreleasingUnsafeMutablePointer<Pointee>, rhs: AutoreleasingUnsafeMutablePointer<Pointee> ) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } @_fixed_layout internal struct _CocoaFastEnumerationStackBuf { // Clang uses 16 pointers. So do we. internal var _item0: UnsafeRawPointer? internal var _item1: UnsafeRawPointer? internal var _item2: UnsafeRawPointer? internal var _item3: UnsafeRawPointer? internal var _item4: UnsafeRawPointer? internal var _item5: UnsafeRawPointer? internal var _item6: UnsafeRawPointer? internal var _item7: UnsafeRawPointer? internal var _item8: UnsafeRawPointer? internal var _item9: UnsafeRawPointer? internal var _item10: UnsafeRawPointer? internal var _item11: UnsafeRawPointer? internal var _item12: UnsafeRawPointer? internal var _item13: UnsafeRawPointer? internal var _item14: UnsafeRawPointer? internal var _item15: UnsafeRawPointer? @_transparent internal var count: Int { return 16 } internal init() { _item0 = nil _item1 = _item0 _item2 = _item0 _item3 = _item0 _item4 = _item0 _item5 = _item0 _item6 = _item0 _item7 = _item0 _item8 = _item0 _item9 = _item0 _item10 = _item0 _item11 = _item0 _item12 = _item0 _item13 = _item0 _item14 = _item0 _item15 = _item0 _sanityCheck(MemoryLayout.size(ofValue: self) >= MemoryLayout<Optional<UnsafeRawPointer>>.size * count) } } extension AutoreleasingUnsafeMutablePointer { @available(*, unavailable, renamed: "Pointee") public typealias Memory = Pointee @available(*, unavailable, renamed: "pointee") public var memory: Pointee { Builtin.unreachable() } @available(*, unavailable, message: "Removed in Swift 3. Please use nil literal instead.") public init() { Builtin.unreachable() } } /// Get the ObjC type encoding for a type as a pointer to a C string. /// /// This is used by the Foundation overlays. The compiler will error if the /// passed-in type is generic or not representable in Objective-C @_transparent public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> { // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is // only supported by the compiler for concrete types that are representable // in ObjC. return UnsafePointer(Builtin.getObjCTypeEncoding(type)) } #endif
apache-2.0
70c64b12c91ecd2772622e8490201f38
33.811765
92
0.696085
4.398598
false
false
false
false
jopamer/swift
test/Interpreter/imported_objc_generics_extension.swift
1
833
// RUN: %empty-directory(%t) // // RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test // XFAIL: interpret // REQUIRES: objc_interop import Foundation import StdlibUnittest import ObjCClasses var ImportedObjCGenericExtension = TestSuite("ImportedObjCGenericExtension") @objc extension Container { @objc func returnSelf() -> Self { return self } } ImportedObjCGenericExtension.test("ExtensionFromSwift") { let gc = Container<NSString>(object: "") expectTrue(gc.returnSelf() === gc) let gc2: Unmanaged<AnyObject>! = gc.perform(#selector(Container<NSString>.returnSelf)) expectTrue(gc2!.takeUnretainedValue() === gc) } runAllTests()
apache-2.0
72c0945aecfcc38d6f32639b1d65bc64
26.766667
91
0.726291
3.621739
false
true
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/Align.swift
6
9264
// // Align.swift // Cartography // // Created by Robert Böhnke on 17/02/15. // Copyright (c) 2015 Robert Böhnke. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif private func makeEqual<P: RelativeEquality, T: LayoutProxy>(by attribute: (T) -> P, items: [T]) -> [NSLayoutConstraint] { if let first = items.first { if let first = first as? AutoresizingMaskLayoutProxy { first.translatesAutoresizingMaskIntoConstraints = false } let rest = items.dropFirst() return rest.reduce([]) { acc, current in if let current = current as? AutoresizingMaskLayoutProxy { current.translatesAutoresizingMaskIntoConstraints = false } return acc + [ attribute(first) == attribute(current) ] } } else { return [] } } /// Aligns multiple items by their top edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(top items: [SupportsTopLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.top }, items: items.map(AnyTopLayoutProxy.init)) } /// Aligns multiple items by their top edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(top first: SupportsTopLayoutProxy, _ rest: SupportsTopLayoutProxy...) -> [NSLayoutConstraint] { return align(top: [first] + rest) } /// Aligns multiple items by their right edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(right items: [SupportsRightLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.right }, items: items.map(AnyRightLayoutProxy.init)) } /// Aligns multiple items by their right edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(right first: SupportsRightLayoutProxy, _ rest: SupportsRightLayoutProxy...) -> [NSLayoutConstraint] { return align(right: [first] + rest) } /// Aligns multiple items by their bottom edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(bottom items: [SupportsBottomLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.bottom }, items: items.map(AnyBottomLayoutProxy.init)) } /// Aligns multiple items by their bottom edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(bottom first: SupportsBottomLayoutProxy, _ rest: SupportsBottomLayoutProxy...) -> [NSLayoutConstraint] { return align(bottom: [first] + rest) } /// Aligns multiple items by their left edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(left items: [SupportsLeftLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.left }, items: items.map(AnyLeftLayoutProxy.init)) } /// Aligns multiple items by their left edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(left first: SupportsLeftLayoutProxy, _ rest: SupportsLeftLayoutProxy...) -> [NSLayoutConstraint] { return align(left: [first] + rest) } /// Aligns multiple items by their leading edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(leading items: [SupportsLeadingLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.leading }, items: items.map(AnyLeadingLayoutProxy.init)) } /// Aligns multiple items by their leading edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(leading first: SupportsLeadingLayoutProxy, _ rest: SupportsLeadingLayoutProxy...) -> [NSLayoutConstraint] { return align(leading: [first] + rest) } /// Aligns multiple items by their trailing edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(trailing items: [SupportsTrailingLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.trailing }, items: items.map(AnyTrailingLayoutProxy.init)) } /// Aligns multiple vies by their trailing edge. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(trailing first: SupportsTrailingLayoutProxy, _ rest: SupportsTrailingLayoutProxy...) -> [NSLayoutConstraint] { return align(trailing: [first] + rest) } /// Aligns multiple items by their horizontal center. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(centerX items: [SupportsCenterXLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.centerX }, items: items.map(AnyCenterXLayoutProxy.init)) } /// Aligns multiple items by their horizontal center. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(centerX first: SupportsCenterXLayoutProxy, _ rest: SupportsCenterXLayoutProxy...) -> [NSLayoutConstraint] { return align(centerX: [first] + rest) } /// Aligns multiple items by their vertical center. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(centerY items: [SupportsCenterYLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.centerY }, items: items.map(AnyCenterYLayoutProxy.init)) } /// Aligns multiple items by their vertical center. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(centerY first: SupportsCenterYLayoutProxy, _ rest: SupportsCenterYLayoutProxy...) -> [NSLayoutConstraint] { return align(centerY: [first] + rest) } /// Aligns multiple items by their baseline. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - parameter items: an array of items to align /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(baseline items: [SupportsBaselineLayoutProxy]) -> [NSLayoutConstraint] { return makeEqual(by: { $0.baseline }, items: items.map(AnyBaselineLayoutProxy.init)) } /// Aligns multiple items by their baseline. /// /// All items passed to this function will have /// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`. /// /// - returns: An array of `NSLayoutConstraint` instances. /// @discardableResult public func align(baseline first: SupportsBaselineLayoutProxy, _ rest: SupportsBaselineLayoutProxy...) -> [NSLayoutConstraint] { return align(baseline: [first] + rest) }
mit
a54aa5311186f9f5f2b3a092e739ed9f
36.196787
147
0.725545
4.551351
false
false
false
false