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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/Icon.swift | 1 | 6644 | /*
* 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 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
public struct Icon {
/// An internal reference to the icons bundle.
private static var internalBundle: Bundle?
/**
A public reference to the icons bundle, that aims to detect
the correct bundle to use.
*/
public static var bundle: Bundle {
if nil == Icon.internalBundle {
Icon.internalBundle = Bundle(for: View.self)
let url = Icon.internalBundle!.resourceURL!
let b = Bundle(url: url.appendingPathComponent("io.cosmicmind.material.icons.bundle"))
if let v = b {
Icon.internalBundle = v
}
}
return Icon.internalBundle!
}
/// Get the icon by the file name.
public static func icon(_ name: String) -> UIImage? {
return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
}
/// Google icons.
public static let add = Icon.icon("ic_add_white")
public static let addCircle = Icon.icon("ic_add_circle_white")
public static let addCircleOutline = Icon.icon("ic_add_circle_outline_white")
public static let arrowBack = Icon.icon("ic_arrow_back_white")
public static let arrowDownward = Icon.icon("ic_arrow_downward_white")
public static let audio = Icon.icon("ic_audiotrack_white")
public static let bell = Icon.icon("cm_bell_white")
public static let check = Icon.icon("ic_check_white")
public static let clear = Icon.icon("ic_close_white")
public static let close = Icon.icon("ic_close_white")
public static let edit = Icon.icon("ic_edit_white")
public static let email = Icon.icon("ic_email_white")
public static let favorite = Icon.icon("ic_favorite_white")
public static let favoriteBorder = Icon.icon("ic_favorite_border_white")
public static let history = Icon.icon("ic_history_white")
public static let home = Icon.icon("ic_home_white")
public static let image = Icon.icon("ic_image_white")
public static let menu = Icon.icon("ic_menu_white")
public static let moreHorizontal = Icon.icon("ic_more_horiz_white")
public static let moreVertical = Icon.icon("ic_more_vert_white")
public static let movie = Icon.icon("ic_movie_white")
public static let pen = Icon.icon("ic_edit_white")
public static let place = Icon.icon("ic_place_white")
public static let phone = Icon.icon("ic_phone_white")
public static let photoCamera = Icon.icon("ic_photo_camera_white")
public static let photoLibrary = Icon.icon("ic_photo_library_white")
public static let search = Icon.icon("ic_search_white")
public static let settings = Icon.icon("ic_settings_white")
public static let share = Icon.icon("ic_share_white")
public static let star = Icon.icon("ic_star_white")
public static let starBorder = Icon.icon("ic_star_border_white")
public static let starHalf = Icon.icon("ic_star_half_white")
public static let videocam = Icon.icon("ic_videocam_white")
public static let visibility = Icon.icon("ic_visibility_white")
/// CosmicMind icons.
public struct cm {
public static let add = Icon.icon("cm_add_white")
public static let arrowBack = Icon.icon("cm_arrow_back_white")
public static let arrowDownward = Icon.icon("cm_arrow_downward_white")
public static let audio = Icon.icon("cm_audio_white")
public static let audioLibrary = Icon.icon("cm_audio_library_white")
public static let bell = Icon.icon("cm_bell_white")
public static let check = Icon.icon("cm_check_white")
public static let clear = Icon.icon("cm_close_white")
public static let close = Icon.icon("cm_close_white")
public static let edit = Icon.icon("cm_pen_white")
public static let image = Icon.icon("cm_image_white")
public static let menu = Icon.icon("cm_menu_white")
public static let microphone = Icon.icon("cm_microphone_white")
public static let moreHorizontal = Icon.icon("cm_more_horiz_white")
public static let moreVertical = Icon.icon("cm_more_vert_white")
public static let movie = Icon.icon("cm_movie_white")
public static let pause = Icon.icon("cm_pause_white")
public static let pen = Icon.icon("cm_pen_white")
public static let photoCamera = Icon.icon("cm_photo_camera_white")
public static let photoLibrary = Icon.icon("cm_photo_library_white")
public static let play = Icon.icon("cm_play_white")
public static let search = Icon.icon("cm_search_white")
public static let settings = Icon.icon("cm_settings_white")
public static let share = Icon.icon("cm_share_white")
public static let shuffle = Icon.icon("cm_shuffle_white")
public static let skipBackward = Icon.icon("cm_skip_backward_white")
public static let skipForward = Icon.icon("cm_skip_forward_white")
public static let star = Icon.icon("cm_star_white")
public static let videocam = Icon.icon("cm_videocam_white")
public static let volumeHigh = Icon.icon("cm_volume_high_white")
public static let volumeMedium = Icon.icon("cm_volume_medium_white")
public static let volumeOff = Icon.icon("cm_volume_off_white")
}
}
| gpl-3.0 | b981de84b61e7efbb639010b1051dafe | 50.503876 | 104 | 0.718543 | 3.836028 | false | false | false | false |
velvetroom/columbus | Source/Model/Store/MStore+Products.swift | 1 | 1575 | import Foundation
import StoreKit
extension MStore
{
//MARK: private
private func received(product:SKProduct)
{
let identifier:String = product.productIdentifier
guard
let perk:MStorePerkProtocol = perksMap[identifier],
let price:String = factoryPrice(product:product)
else
{
return
}
received(
product:product,
perk:perk,
price:price)
}
private func received(
product:SKProduct,
perk:MStorePerkProtocol,
price:String)
{
var perk:MStorePerkProtocol = perk
guard
let _:DPerk = settings?.perksMap[perk.perkType]
else
{
perk.statusNew(
product:product,
price:price)
return
}
perk.statusPurchased(
product:product,
price:price)
}
private func factoryPrice(product:SKProduct) -> String?
{
priceFormatter.locale = product.priceLocale
let priceNumber:NSDecimalNumber = product.price
let price:String? = priceFormatter.string(from:priceNumber)
return price
}
//MARK: internal
func received(products:[SKProduct])
{
for product:SKProduct in products
{
received(product:product)
}
changeStatus(statusType:MStoreStatusReady.self)
}
}
| mit | 06887ddacb18143008adcda848d567bd | 20.575342 | 67 | 0.52 | 5.320946 | false | false | false | false |
Pursuit92/antlr4 | runtime/Swift/Antlr4/org/antlr/v4/runtime/atn/PredictionContextCache.swift | 3 | 1420 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/** Used to cache {@link org.antlr.v4.runtime.atn.PredictionContext} objects. Its used for the shared
* context cash associated with contexts in DFA states. This cache
* can be used for both lexers and parsers.
*/
public final class PredictionContextCache {
//internal final var
var cache: HashMap<PredictionContext, PredictionContext> =
HashMap<PredictionContext, PredictionContext>()
public init() {
}
/** Add a context to the cache and return it. If the context already exists,
* return that one instead and do not add a new context to the cache.
* Protect shared cache from unsafe thread access.
*/
@discardableResult
public func add(_ ctx: PredictionContext) -> PredictionContext {
if ctx === PredictionContext.EMPTY {
return PredictionContext.EMPTY
}
let existing: PredictionContext? = cache[ctx]
if existing != nil {
// print(name+" reuses "+existing);
return existing!
}
cache[ctx] = ctx
return ctx
}
public func get(_ ctx: PredictionContext) -> PredictionContext? {
return cache[ctx]
}
public func size() -> Int {
return cache.count
}
}
| bsd-3-clause | 15b5793e54fd569f04642fa1af8b75f7 | 32.023256 | 101 | 0.658451 | 4.536741 | false | false | false | false |
raulriera/HuntingKit | HuntingKit/Post.swift | 1 | 3110 | //
// Post.swift
// HuntingKit
//
// Created by Raúl Riera on 19/04/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import Foundation
public struct Post: Model {
public let id: Int
public let name: String
public let tagline: String
public let user: User
public let featured: Bool
public let stats: PostStats?
public let discussionURL: NSURL?
public let redirectURL: NSURL?
public let imagesURL: ImagesURL
public let makerInside: Bool
public let makers: [User]
public let votes: [Vote]
public let comments: [Comment]?
public init?(dictionary: NSDictionary) {
if let id = dictionary["id"] as? Int,
let userDictionary = dictionary["user"] as? NSDictionary,
let user = User(dictionary: userDictionary),
let imagesURLDictionary = dictionary["screenshot_url"] as? NSDictionary,
let name = dictionary["name"] as? String,
let tagline = dictionary["tagline"] as? String,
let featured = dictionary["featured"] as? Bool,
let discussionURL = dictionary["discussion_url"] as? String,
let redirectURL = dictionary["redirect_url"] as? String,
let makerInside = dictionary["maker_inside"] as? Bool {
self.id = id
self.name = name
self.tagline = tagline
self.user = user
self.featured = featured
self.discussionURL = NSURL(string: discussionURL)
self.redirectURL = NSURL(string: redirectURL)
self.stats = PostStats(dictionary: dictionary)
imagesURL = ImagesURL(dictionary: imagesURLDictionary)
self.makerInside = makerInside
if let makers = dictionary["makers"] as? [NSDictionary] {
self.makers = initEach(makers)
} else {
makers = [User]()
}
if let votes = dictionary["votes"] as? [NSDictionary] {
self.votes = initEach(votes)
} else {
self.votes = [Vote]()
}
if let comments = dictionary["comments"] as? [NSDictionary] {
self.comments = initEach(comments)
} else {
self.comments = .None
}
} else {
return nil
}
}
}
public struct PostStats {
public let votes: Int
public let comments: Int
public let createdAt: NSDate?
public init?(dictionary: NSDictionary) {
if
let votes = dictionary["votes_count"] as? Int,
let comments = dictionary["comments_count"] as? Int,
let createdAt = dictionary["created_at"] as? String {
self.votes = votes
self.comments = comments
self.createdAt = formatter.dateFromString(createdAt)
} else {
return nil
}
}
} | mit | d00433a652979d91f41646b7d5488be7 | 33.555556 | 84 | 0.53715 | 4.9744 | false | false | false | false |
ben-ng/swift | validation-test/Sema/type_checker_crashers_fixed/rdar28023899.swift | 1 | 228 | // RUN: %target-swift-frontend %s -typecheck
// REQUIRES: asserts
class B : Equatable {
static func == (lhs: B, rhs: B) -> Bool { return true }
}
class C : B {
static var v: C { return C() }
}
let c: C! = nil
_ = c == .v
| apache-2.0 | 9392d7c4fa3668718068867cfadf6e35 | 16.538462 | 57 | 0.565789 | 2.746988 | false | false | false | false |
norio-nomura/PlayNow | PlayNow/AppDelegate.swift | 1 | 3341 | //
// AppDelegate.swift
// PlayNow
//
// Created by 野村 憲男 on 9/5/15.
//
// Copyright (c) 2015 Norio Nomura
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let url = CommandLine.arguments.dropFirst().first.map { URL(fileURLWithPath: $0) }
var executed = false
func applicationDidFinishLaunching(_ notification: Notification) {
// Document said "Service requests can arrive immediately after you register the object."
// But it does not as I tested.
NSApplication.shared().servicesProvider = self
// So,
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(NSEC_PER_SEC) / Double(NSEC_PER_SEC)) {
[unowned self] in
if !self.executed {
do {
try Playground(fileURL: self.url).update()
} catch let error as Playground.Error {
NSLog("#PlayNow: \(error)")
NSAlert(error: error.NSError).runModal()
} catch let error as NSError {
NSLog("#PlayNow: \(error)")
NSAlert(error: error).runModal()
}
}
NSApplication.shared().terminate(self)
}
}
/// Service Provider handler
/// - SeeAlso: [Services Implementation Guide](https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Conceptual/SysServices/introduction.html)
func executeInPlayground(_ pasteboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer<NSString?>) {
let contents = pasteboard.string(forType: NSPasteboardTypeString)
do {
// When called from Services, avoid added Page regarding unused.
try Playground(fileURL: url, contentsSwift: contents).update().checkMakeUsedIfFromServices()
} catch let error as Playground.Error {
NSLog("#PlayNow: \(error)")
NSAlert(error: error.NSError).runModal()
} catch let error as NSError {
NSLog("#PlayNow: \(error)")
NSAlert(error: error).runModal()
}
executed = true
}
}
| mit | 2d7b0435ce75b2543e6bc6633aadbaf9 | 40.6625 | 163 | 0.654665 | 4.72766 | false | false | false | false |
UncleJoke/Spiral | Spiral/ZenButton.swift | 1 | 1775 | //
// ZenButton.swift
// Spiral
//
// Created by 杨萧玉 on 15/6/4.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import SpriteKit
class ZenButton: SKSpriteNode {
init() {
super.init(texture: SKTexture(imageNamed: "ZenBtn"), color: UIColor.clearColor(), size: mainButtonSize)
normalTexture = texture?.textureByGeneratingNormalMapWithSmoothness(0.2, contrast: 2.5)
lightingBitMask = playerLightCategory | killerLightCategory | scoreLightCategory | shieldLightCategory | reaperLightCategory
userInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
userInteractionEnabled = false
if !Data.sharedData.gameOver {
return
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { () -> Void in
Data.sharedData.currentMode = .Zen
Data.sharedData.gameOver = false
let gvc = UIApplication.sharedApplication().keyWindow?.rootViewController as! GameViewController
gvc.startRecordWithHandler { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if self.scene is MainScene {
gvc.addGestureRecognizers()
let scene = ZenModeScene(size: self.scene!.size)
let flip = SKTransition.flipHorizontalWithDuration(1)
flip.pausesIncomingScene = false
self.scene?.view?.presentScene(scene, transition: flip)
}
})
}
}
}
}
| mit | 68c6f6142d11fbbd9b415d96b2ea9fcc | 38.133333 | 132 | 0.60477 | 4.905292 | false | false | false | false |
syedabsar/ios-nytimes-mostpopular | NYTimes_MostPopularArticles/ViewControllers/MasterViewController.swift | 1 | 12015 | //
// MasterViewController.swift
// NY Times Most Popular Articles
//
// Created by Syed Absar Karim on 8/4/17.
// Copyright © 2017 Syed Absar Karim. All rights reserved.
//
import UIKit
import AZDropdownMenu
import SwiftSpinner
class MasterViewController: UITableViewController, UISearchBarDelegate {
// MARK: - Properties
var detailViewController: DetailViewController? = nil
var mostViewedItemsList : [MostViewedResults]? = Array<MostViewedResults>()
var filteredSearchResultList : [MostViewedResults]? = nil
var currentOffset = 0
var totalResults = 0
var searchMode = false
let operationsManager = OperationsManager()
let searchBar = UISearchBar()
var menu : AZDropdownMenu?
var sections : [SectionsResults]? = nil
var defaultSection = "all-sections"
var defaultTimePeriod = TimePeriod.Week { didSet {
refreshControl?.attributedTitle = NSAttributedString(string: self.getFetchingMessage())
} }
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure Split Controller
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
// Configure Search Bar
searchBar.showsCancelButton = true
searchBar.returnKeyType = UIReturnKeyType.done
searchBar.delegate = self
// Configure Refresh Control
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(MasterViewController.refresh), for: UIControlEvents.valueChanged)
refreshControl?.attributedTitle = NSAttributedString(string: self.getFetchingMessage())
// Configure Table View
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 150
// Load Web Service Items
self.loadLatestItems()
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - ViewController Methods
func showError(message:String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func resetResults() {
self.mostViewedItemsList?.removeAll()
self.currentOffset = 0
}
func loadLatestItems() {
SwiftSpinner.useContainerView(self.view)
SwiftSpinner.show(self.getFetchingMessage())
operationsManager.getMostViewed(
section: self.defaultSection,
timePeriod: self.defaultTimePeriod,
offset: self.currentOffset) { (responseModel, error) in
if error != nil {
self.showError(message: (error?.localizedDescription)!)
SwiftSpinner.hide()
return
}
self.totalResults = (responseModel?.num_results)!
self.mostViewedItemsList?.append(contentsOf: (responseModel?.results)!)
self.tableView.reloadData()
self.tableView.scrollToRow(at: IndexPath(row: self.currentOffset, section: 0), at: .bottom, animated: false)
self.loadSectionsList()
}
}
func loadSectionsList() {
if self.sections != nil {
SwiftSpinner.hide()
} else {
operationsManager.getSectionsList(completionHandler: { (array, error) in
SwiftSpinner.hide()
if error != nil {
self.showError(message: (error?.localizedDescription)!)
return
}
self.sections = array
let sectionNamesArray = self.sections?.map({ (section: SectionsResults) -> String in
section.name!
})
self.menu = AZDropdownMenu(titles: sectionNamesArray!)
self.menu?.cellTapHandler = { indexPath in
self.defaultSection = (sectionNamesArray?[indexPath.row])!.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!
self.resetResults()
self.loadLatestItems()
}
})
}
}
func refresh(sender:AnyObject) {
self.currentOffset = 0
// Code to refresh table view
operationsManager.getMostViewed(section: "all-sections", timePeriod: self.defaultTimePeriod, offset: 0) { (responseModel, error) in
self.refreshControl?.endRefreshing()
if error != nil {
self.showError(message: (error?.localizedDescription)!)
return
}
self.mostViewedItemsList = responseModel?.results
self.tableView.reloadData()
}
}
func showTimePeriodFilters() {
let alert = UIAlertController(title: "See most popular items for",
message: nil,
preferredStyle: UIAlertControllerStyle.actionSheet)
for timePeriod in EnumUtils.iterateEnum(TimePeriod.self) {
let timePeriodAction = UIAlertAction(title: self.getDisplayNameForTimePeriod(timePeriod: timePeriod),
style: .default, handler: { action in
self.defaultTimePeriod = timePeriod
self.loadLatestItems()
})
alert.addAction(timePeriodAction)
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
private func getDisplayNameForTimePeriod(timePeriod: TimePeriod) -> String {
var displayName = timePeriod.getDisplayName()
if self.defaultTimePeriod == timePeriod {
displayName = "✓ " + displayName
}
return displayName
}
private func getFetchingMessage() -> String {
return "Fetching this \(self.defaultTimePeriod.getDisplayName())'s most viewed in \(self.defaultSection)"
}
// MARK: - Button Actions
@IBAction func didTapLeftButtonItem(_ sender: Any) {
if (self.menu?.isDescendant(of: self.view) == true) {
self.menu?.hideMenu()
} else {
self.menu?.showMenuFromView(self.view)
}
}
@IBAction func didTapMoreButtonItem(_ sender: Any) {
self.showTimePeriodFilters()
}
@IBAction func didTapSearchButtonItem(_ sender: Any) {
if self.searchMode == true {
searchBarCancelButtonClicked(self.searchBar)
return
}
self.filteredSearchResultList = self.mostViewedItemsList
self.searchMode = true
self.tableView.tableHeaderView = searchBar
searchBar.sizeToFit()
searchBar.becomeFirstResponder()
}
// MARK: - Search Bar
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.searchMode = false
searchBar.resignFirstResponder()
self.tableView.tableHeaderView = nil
self.tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.filteredSearchResultList = BusinessLogicHelper.filterBySearchKeywords(searchKeyword: searchText, resultsArray: self.mostViewedItemsList!)
self.tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
if tableView.indexPathForSelectedRow != nil {
let object = self.mostViewedItemsList?[(tableView.indexPathForSelectedRow?.row)!]
controller.detailItem = object
} else if (self.mostViewedItemsList?.count)! > 0 {
//The first news shows by default no item selected and orientation is landscape.
controller.detailItem = self.mostViewedItemsList?.first
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.searchMode && self.filteredSearchResultList != nil {
return (self.filteredSearchResultList?.count)!
}
if self.searchMode == false && self.mostViewedItemsList != nil {
return (self.mostViewedItemsList?.count)!
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.MasterViewController.SummaryCellIdentifier, for: indexPath) as! MasterSummaryTableViewCell
//Populate object information to cell
let object = self.searchMode ? self.filteredSearchResultList?[indexPath.row] : self.mostViewedItemsList?[indexPath.row]
cell.titleLabel!.text = object?.title
cell.byLineLabel.text = object?.byline
cell.publishDateLabel.text = "🗓 "+(object?.published_date!)!
cell.thumbnailView?.image = UIImage(named: Constants.MasterViewController.PlaceholderImageName)
cell.thumbnailView?.layer.cornerRadius = 20
operationsManager.downloadImage(object: object!) { (image, error) in
DispatchQueue.main.async() { () -> Void in
cell.thumbnailView?.image = image
}
}
cell.layoutIfNeeded()
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let offsetNumber = indexPath.row + 1;
if (offsetNumber % 20 == 0 && offsetNumber > self.currentOffset && (self.mostViewedItemsList?.count)! <= self.totalResults) {
self.currentOffset = offsetNumber
self.loadLatestItems()
}
}
}
| mit | 7789b55c86f6e0a055cc8e6bfa98253d | 33.01983 | 166 | 0.586477 | 5.872372 | false | false | false | false |
daniel-barros/Comedores-UGR | Comedores UGR/MenuTableViewController.swift | 1 | 12828 | //
// MenuTableViewController.swift
// Comedores UGR
//
// Created by Daniel Barros López on 3/9/16.
/*
MIT License
Copyright (c) 2016 Daniel Barros
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
import UIKit
import EventKitUI
import SafariServices
class MenuTableViewController: UITableViewController {
let fetcher = WeekMenuFetcher()
var weekMenu = [DayMenu]()
var error: FetcherError?
var lastTimeTableViewReloaded: Date?
/// `false` when there's a saved menu or the vc has already fetched since viewDidLoad().
var isFetchingForFirstTime = true
fileprivate let lastUpdateRowHeight: CGFloat = 46.45
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
weekMenu = fetcher.savedMenu ?? []
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 150
if weekMenu.isEmpty == false {
tableView.contentOffset.y = lastUpdateRowHeight // Hides "last update" row
isFetchingForFirstTime = false
}
refreshControl = UIRefreshControl()
refreshControl!.addTarget(self, action: #selector(fetchData), for: .valueChanged)
updateSeparatorsInset(for: tableView.frame.size)
if fetcher.needsToUpdateMenu {
if isFetchingForFirstTime {
refreshControl!.layoutIfNeeded()
refreshControl!.beginRefreshing()
tableView.contentOffset.y = -tableView.contentInset.top
}
fetchData()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func appDidBecomeActive(_ notification: Notification) {
// Menu was updated externally and changes need to be reflected in UI
if let savedMenu = fetcher.savedMenu, savedMenu != weekMenu {
self.error = nil
weekMenu = savedMenu
tableView.reloadData()
} else {
// This makes sure that only the date for today's menu is highlighted
if let lastReload = lastTimeTableViewReloaded, Calendar.current.isDateInToday(lastReload) == false {
tableView.reloadData()
}
// Menu needs to be updated
if fetcher.needsToUpdateMenu {
fetchData()
}
}
}
func fetchData() {
if fetcher.isFetching == false {
fetcher.fetchMenu(completionHandler: { menu in
self.error = nil
let menuChanged = self.weekMenu != menu
self.weekMenu = menu
self.lastTimeTableViewReloaded = Date()
self.isFetchingForFirstTime = false
mainQueue {
if menuChanged {
self.tableView.reloadData()
} else {
self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row
}
UIView.animate(withDuration: 0.5) {
if self.refreshControl!.isRefreshing {
self.refreshControl!.endRefreshing()
}
}
}
}, errorHandler: { error in
self.error = error
self.lastTimeTableViewReloaded = Date()
self.isFetchingForFirstTime = false
mainQueue {
if self.weekMenu.isEmpty {
self.tableView.reloadData()
} else {
self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none) // Updates "last updated" row showing error message temporarily
delay(1) {
self.error = nil // Next time first cell is loaded it will show last update date instead of error message
}
}
UIView.animate(withDuration: 0.5) {
if self.refreshControl!.isRefreshing {
self.refreshControl!.endRefreshing()
}
}
}
})
}
}
@IBAction func prepareForUnwind(_ segue: UIStoryboardSegue) {
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateSeparatorsInset(for: size)
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if weekMenu.isEmpty {
return isFetchingForFirstTime ? 0 : 1
}
return weekMenu.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if weekMenu.isEmpty == false {
// First row shows error message if any (eventually dismissed, see fetchData()), or last update date
if indexPath.row == 0 {
if let error = error {
let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell
cell.configure(with: error)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LastUpdateCell", for: indexPath) as! LastUpdateTableViewCell
cell.configure(with: fetcher.lastUpdate)
return cell
}
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuTableViewCell
cell.configure(with: weekMenu[indexPath.row - 1])
return cell
}
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "ErrorCell", for: indexPath) as! ErrorTableViewCell
cell.configure(with: error)
return cell
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.row == 0 { return false }
if self.weekMenu[indexPath.row - 1].isClosedMenu { return false }
return true
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if weekMenu.isEmpty || indexPath.row == 0 {
return nil
}
let menu = self.weekMenu[indexPath.row - 1]
let calendarAction = addToCalendarRowAction(for: menu)
if let allergensRowAction = allergensInfoRowAction(for: menu) {
return [calendarAction, allergensRowAction]
} else {
return [calendarAction]
}
}
// MARK: - UIScrollViewDelegate
// Avoids "last update" row scrolling down to first dish row
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if lastUpdateRowIsVisible {
self.tableView.scrollToRow(at: IndexPath(row: 1, section: 0), at: .top, animated: true)
}
}
}
// MARK: Helpers
private extension MenuTableViewController {
func addToCalendarRowAction(for menu: DayMenu) -> UITableViewRowAction {
let rowAction = UITableViewRowAction(style: .normal,
title: NSLocalizedString("Add to\nCalendar"),
handler: { action, indexPath in
switch EventManager.authorizationStatus {
case .authorized: self.presentEventEditViewController(for: menu)
case .denied: self.presentAlertController(title: NSLocalizedString("Access Denied"), message: NSLocalizedString("Please go to the app's settings and allow us to access your calendars."), showsGoToSettings: true)
case .notDetermined: self.requestEventAccessPermission(for: menu)
case .restricted: self.presentAlertController(title: NSLocalizedString("Access Restricted"), message: NSLocalizedString("Access to calendars is restricted, possibly due to parental controls being in place."), showsGoToSettings: false)
}
})
rowAction.backgroundColor = .customAlternateRedColor
return rowAction
}
func allergensInfoRowAction(for menu: DayMenu) -> UITableViewRowAction? {
if let _ = menu.allergens {
// TODO: Implement
return nil
} else {
return nil
}
}
func presentEventEditViewController(for menu: DayMenu) {
let eventVC = EKEventEditViewController()
let eventStore = EKEventStore()
eventVC.eventStore = eventStore
eventVC.editViewDelegate = self
eventVC.event = EventManager.createEvent(in: eventStore, for: menu)
self.present(eventVC, animated: true, completion: nil)
}
func presentAlertController(title: String, message: String, showsGoToSettings: Bool) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel"), style: .cancel, handler: { action in
self.dismiss(animated: true, completion: nil)
self.tableView.isEditing = false
})
alertController.addAction(cancelAction)
if showsGoToSettings {
let settingsAction = UIAlertAction(title: NSLocalizedString("Go to Settings"), style: .default, handler: { action in
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
})
alertController.addAction(settingsAction)
alertController.preferredAction = settingsAction
}
self.present(alertController, animated: true, completion: nil)
}
func requestEventAccessPermission(for menu: DayMenu) {
EventManager.requestAccessPermission { granted in
mainQueue {
if granted {
self.presentEventEditViewController(for: menu)
} else {
self.tableView.isEditing = false
}
}
}
}
var lastUpdateRowIsVisible: Bool {
let offset = navigationController!.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height
return weekMenu.isEmpty == false && tableView.contentOffset.y < lastUpdateRowHeight - offset
}
/// Updates the table view's separators left inset according to the given size.
func updateSeparatorsInset(for size: CGSize) {
tableView.separatorInset.left = size.width * 0.2 - 60
}
}
// MARK: - EKEventEditViewDelegate
extension MenuTableViewController: EKEventEditViewDelegate {
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
if let event = controller.event, action == .saved {
EventManager.saveDefaultInfo(from: event)
}
dismiss(animated: true, completion: nil)
self.tableView.isEditing = false
}
}
| mit | e7b8758d1c0579d55b4dc3602093f06e | 37.289552 | 246 | 0.613783 | 5.538428 | false | false | false | false |
NathanE73/Blackboard | Sources/BlackboardFramework/Storyboards/BlackboardTableViewCell.swift | 1 | 2331 | //
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// 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
struct BlackboardTableViewCell {
var name: String
var enumName: String
var dequeueFuncName: String
var identifier: String
var className: String
var parameterName: String
}
extension BlackboardTableViewCell {
init?(_ tableViewCell: StoryboardTableViewCell) {
guard let reuseIdentifier = tableViewCell.reuseIdentifier else {
return nil
}
name = Naming.name(from: reuseIdentifier)
.removingSuffix("Cell")
enumName = (name.isEmpty
? Naming.name(from: reuseIdentifier)
: name)
.firstCharacterLowercased
dequeueFuncName = "dequeue\(name)Cell"
identifier = reuseIdentifier
if let customClass = tableViewCell.customClass {
className = customClass
parameterName = (customClass
.removingSuffix("Cell")
.removingSuffix("TableView")
+ "Cell")
.firstCharacterLowercased
} else {
className = "UITableViewCell"
parameterName = "cell"
}
}
}
| mit | 1c61f1668be89acddf4edf70f56a1be1 | 31.830986 | 80 | 0.659803 | 5.203125 | false | false | false | false |
RobotRebels/ios-common | ToboxCommon/Helpers/Utils.swift | 1 | 1148 | //
// Utils.swift
// ToboxCommon
//
// Created by Ilya Lunkin on 24/10/2016.
// Copyright © 2016 Tobox. All rights reserved.
//
import Foundation
public func kFormat<T: NSNumber>(val: T, number: UInt = 0) -> String {
let fVal = Float(val) ?? 0
if fVal > 999.0 && fVal < 999999.0 {
return String(format: "%.\(number)f", (fVal / 1000.0)) + "K"
} else if fVal > 999999.0 {
return String(format: "%.\(number)f", (fVal / 1000000.0)) + "M"
}
return String(val)
}
public func localizedCountriesISOCodes() -> [String: String] {
let locale = NSLocale.systemLocale()
var resultDict = Dictionary<String, String>()
for ISOCode in NSLocale.ISOCountryCodes() {
let localizedName = locale.displayNameForKey(NSLocaleCountryCode, value: ISOCode) ?? "RU"
resultDict[localizedName] = ISOCode
}
return resultDict
}
// analogue to obj-c's @synchronized
public func synchronized(lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
public func synchronized(lock: AnyObject, @autoclosure autoclosure: () -> ()) {
objc_sync_enter(lock)
autoclosure()
objc_sync_exit(lock)
}
| mit | 40fa3259d50cad52921b4a89786f5824 | 26.309524 | 93 | 0.666957 | 3.334302 | false | false | false | false |
oneSwiftSprite/Swiftris | Swiftris/Shape.swift | 1 | 6026 | //
// Shape.swift
// Swiftris
//
// Created by Adriana Gustavson on 1/19/15.
// Copyright (c) 2015 Adriana Gustavson. All rights reserved.
//
import SpriteKit
let NumOrientations: UInt32 = 4
enum Orientation: Int, Printable {
case Zero = 0, Ninety, OneEighty, TwoSeventy
var description: String {
switch self {
case .Zero:
return "0"
case .Ninety:
return "90"
case .OneEighty:
return "180"
case .TwoSeventy:
return "270"
}
}
static func random() -> Orientation {
return Orientation(rawValue:Int(arc4random_uniform(NumOrientations)))!
}
// #1
static func rotate(orientation: Orientation, clockwise: Bool) -> Orientation {
var rotated = orientation.rawValue + (clockwise ? 1 : -1)
if rotated > Orientation.TwoSeventy.rawValue {
rotated = Orientation.Zero.rawValue
} else if rotated < 0 {
rotated + Orientation.TwoSeventy.rawValue
}
return Orientation(rawValue:rotated)!
}
}
// The number of total shape varieties
let NumShapeTypes: UInt32 = 7
// Shape indexes
let FirstBlockIdx: Int = 0
let SecondBlockIdx: Int = 1
let ThirdBlockIdx: Int = 2
let FourthBlockIdx: Int = 3
class Shape: Hashable, Printable {
//the color of the shape
let color:BlockColor
//the blocks comprising the shape
var blocks = Array<Block>()
//the current orientation of the shape
var orientation: Orientation
//the column and row representing the shape's anchor point
var column, row: Int
//required overrides
// #1
//subclasses must override this property
var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] {
return [:]
}
// #2
//subclasses must override this property
var bottomBlocksForOrientations: [Orientation: Array<Block>] {
return [:]
}
// #3
var bottomBlocks:Array<Block> {
if let bottomBlocks = bottomBlocksForOrientations[orientation] {
return bottomBlocks
}
return []
}
// Hashable
var hashValue: Int {
// #4
return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue }
}
//Printable
var description: String {
return "\(color) block facing \(orientation): \(blocks[FirstBlockIdx]), \(blocks[SecondBlockIdx]), \(blocks[ThirdBlockIdx]), \(blocks[FourthBlockIdx])"
}
init(column:Int, row:Int, color: BlockColor, orientation:Orientation) {
self.color = color
self.column = column
self.row = row
self.orientation = orientation
initializeBlocks()
}
// #5
convenience init(column:Int, row:Int) {
self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random())
}
//--
// #1
final func initializeBlocks() {
// #2
if let blockRowColumnTranslations = blockRowColumnPositions[orientation] {
for i in 0..<blockRowColumnTranslations.count {
let blockRow = row + blockRowColumnTranslations[i].rowDiff
let blockColumn = column + blockRowColumnTranslations[i].columnDiff
let newBlock = Block(column: blockColumn, row: blockRow, color: color)
blocks.append(newBlock)
}
}
}
final func rotateBlocks(orientation: Orientation) {
if let blockRowColumnTranslation: Array<(columnDiff: Int, rowDiff: Int)> = blockRowColumnPositions[orientation] {
// #1
for(idx, (columnDiff: Int, rowDiff: Int)) in enumerate(blockRowColumnTranslation) {
blocks[idx].column = column + columnDiff
blocks[idx].row = row + rowDiff
}
}
}
// #1 (playing by the rules)
final func rotateClockwise() {
let newOrientation = Orientation.rotate(orientation, clockwise: true)
rotateBlocks (newOrientation)
orientation = newOrientation
}
final func rotateCounterClockwise() {
let newOrientation = Orientation.rotate(orientation, clockwise: false)
rotateBlocks(newOrientation)
orientation = newOrientation
}
final func lowerShapeByOneRow() {
shiftBy(0, rows: 1)
}
final func raiseShapeByOneRow() {
shiftBy(0, rows:-1)
}
final func shiftRightByOneColumn() {
shiftBy(1, rows:0)
}
final func shiftLeftByOneColumn() {
shiftBy(-1, rows:0)
}
// #2
final func shiftBy(columns: Int, rows: Int) {
self.column += columns
self.row += rows
for block in blocks {
block.column += columns
block.row += rows
}
}
// #3
final func moveTo(column: Int, row: Int) {
self.column = column
self.row = row
rotateBlocks(orientation)
}
final class func random(startingColumn: Int, startingRow: Int) -> Shape {
switch Int(arc4random_uniform(NumShapeTypes)) {
// #4
case 0:
return SquareShape (column: startingColumn, row: startingRow)
case 1:
return TShape (column: startingColumn, row: startingRow)
case 2:
return LineShape (column: startingColumn, row: startingRow)
case 3:
return LShape (column: startingColumn, row: startingRow)
case 4:
return JShape (column: startingColumn, row: startingRow)
case 5:
return SShape (column: startingColumn, row: startingRow)
default:
return ZShape (column: startingColumn, row: startingRow)
}
}
}
func ==(lhs: Shape, rhs: Shape) -> Bool {
return lhs.row == rhs.row && lhs.column == rhs.column
}
| mit | 860095d1ed2944836946cc16596ad907 | 23.007968 | 159 | 0.583804 | 4.664087 | false | false | false | false |
amujic5/iVictim | iVictim/Common/Extensions/View.swift | 1 | 1483 | //
// View.swift
// Tvm
//
// Created by Azzaro Mujic on 25/04/16.
// Copyright © 2016 Infinum. All rights reserved.
//
import UIKit
extension UIView {
var isOnMainWindow: Bool {
if let windowFrame = UIApplication.shared.keyWindow?.frame {
return windowFrame.contains(frame)
} else {
return false
}
}
@IBInspectable var borderWidth2: CGFloat {
get {
return layer.borderWidth
}
set(borderWidth) {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor2: UIColor {
get {
return UIColor(cgColor: layer.borderColor ?? UIColor.clear.cgColor)
}
set(borderColor) {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var cornerRadius2: CGFloat {
get {
return layer.cornerRadius
}
set(cornerRadius) {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
static func initViewWithOwner<T: UIView>(owner: AnyObject) -> T {
let wrapedView = Bundle.main.loadNibNamed(String(describing: T.self), owner: owner, options: nil)![0]
guard let view = wrapedView as? T else {
fatalError("Couldn’t instantiate view from nib with identifier \(String(describing: T.self))")
}
return view
}
}
| gpl-3.0 | b3d8617914219b1859c65e325156a3b9 | 23.262295 | 109 | 0.558784 | 4.728435 | false | false | false | false |
slash-hq/slash | Sources/SlackWebClient.swift | 1 | 6449 | //
// slash
//
// Copyright © 2016 slash Corp. All rights reserved.
//
import Foundation
enum SlackWebClientError: Error {
case error(String)
}
class SlackWebClient {
private let token: String
init(authenticatedBy token: String) {
self.token = token
}
func rtm() throws -> SlackTeam {
return processStartRTMresponse(try self.rpc(forMethod: "rtm.start"))
}
func history(for channel: String) throws -> [SlackMessage] {
var method = "channels.history"
if let firstCharacter = channel.first {
switch firstCharacter {
//TODO - This mapping is rather naive. There should be separated methods for: groups and ims.
case "C": method = "channels.history"
case "G": method = "groups.history"
case "D": method = "im.history"
default: break
}
}
let response = try self.rpc(forMethod: method, withParams: ["channel": channel])
guard let messages = response["messages"] as? Array<Any> else {
throw SlackWebClientError.error("No messages array in the response \(response).")
}
return messages.map { item in
guard let dictionary = item as? Dictionary<String, Any> else {
return SlackMessage(ts: "", channel: "", user: "", text: "", reactions: [])
}
return SlackMessage(ts: (dictionary["ts"] as? String) ?? "",
channel: channel,
user: (dictionary["user"] as? String) ?? "",
text: (dictionary["text"] as? String) ?? "",
reactions: (dictionary["reactions"] as? [[String: Any]])?.map({ item in
return SlackMessageReaction(
name: item["name"] as? String ?? "",
count: item["count"] as? Int ?? 0,
users: item["users"] as? [String] ?? []
)
}) ?? []
)
}
}
private func rpc(forMethod rpcMethod: String, withParams params: [String: String] = [:]) throws -> Dictionary<String, Any> {
var queryParams = [String: String]()
queryParams["token"] = token
params.forEach { queryParams[$0.key] = $0.value }
let urlString = ("https://slack.com/api/\(rpcMethod)?") + queryParams.map({ $0 + "=" + $1}).joined(separator: "&")
guard let url = URL(string: urlString) else {
throw SlackWebClientError.error("Could not create URL object.")
}
let (theData, _) = try URLSession.shared.synchronousDataTask(with: URLRequest(url: url))
guard let data = theData else {
throw SlackWebClientError.error("Error receiving data.")
}
let object = try JSONSerialization.jsonObject(with:data)
guard let dict = object as? Dictionary<String, Any> else {
throw SlackWebClientError.error("\(rpcMethod)'s response is not a dictionary.")
}
guard (dict["ok"] as? Bool) == true else {
throw SlackWebClientError.error("result not ok \(dict).")
}
return dict
}
private func processStartRTMresponse(_ object: Any) -> SlackTeam {
return SlackTeam(
selfId : object ← "self" ← "id",
name : object ← "team" ← "name",
users: (object ←← "users").map(
{ SlackUser(id: $0 ← "id", name: $0 ← "name", color: $0 ← "color", presence: ($0 ← "presence") == "active" ? .active : .away) }
),
channels: (object ←← "channels").map({
SlackChannel(
id: $0 ← "id",
name: $0 ← "name",
members: ($0 ←← "members").map({ ($0 as? String) ?? "" }),
topic: $0 ← "topic",
general: $0 ← "is_general",
isMember: $0 ← "is_member"
)}
),
groups: (object ←← "groups").map(
{ SlackGroup(id: $0 ← "id", name: $0 ← "name",
members: ($0 ←← "members").map({ ($0 as? String) ?? "" }),
topic: $0 ← "topic")}
),
ims: (object ←← "ims").map({ SlackIM(id: $0 ← "id", user: $0 ← "user") }),
wssUrl: object ← "url"
)
}
}
precedencegroup LookupSeparatorPrecedence { associativity: left }
infix operator ← : LookupSeparatorPrecedence
infix operator ←← : LookupSeparatorPrecedence
func ← (left: Any, right: String) -> [String: Any] {
if let dict = left as? [String: Any] {
return (dict[right] as? [String: Any]) ?? [String: Any]()
}
return [String: Any]()
}
func ←← (left: Any, right: String) -> [Any] {
if let dict = left as? [String: Any] {
return (dict[right] as? [Any]) ?? [Any]()
}
return [Any]()
}
func ← (left: Any, right: String) -> String? {
if let dict = left as? [String: Any] {
return (dict[right] as? String)
}
return nil
}
func ← (left: Any, right: String) -> String {
if let dict = left as? [String: Any] {
return (dict[right] as? String) ?? ""
}
return ""
}
func ← (left: Any, right: String) -> Bool? {
if let dict = left as? [String: Any] {
return (dict[right] as? Bool)
}
return nil
}
func ← (left: Any, right: String) -> Bool {
if let dict = left as? [String: Any] {
return (dict[right] as? Bool) ?? false
}
return false
}
func ← (left: [String: Any], right: String) -> [String: Any] {
return (left[right] as? [String: Any]) ?? [String: Any]()
}
func ← (left: [String: Any], right: String) -> Int? {
return (left[right] as? Int) ?? nil
}
func ← (left: [String: Any], right: String) -> Int {
return (left[right] as? Int) ?? 0
}
func ← (left: [String: Any], right: String) -> String? {
return (left[right] as? String) ?? nil
}
func ← (left: [String: Any], right: String) -> String {
return (left[right] as? String) ?? ""
}
func ← (left: [String: Any], right: String) -> Bool? {
return (left[right] as? Bool)
}
func ← (left: [String: Any], right: String) -> Bool {
return (left[right] as? Bool) ?? false
}
| apache-2.0 | 7e43be1f07146f73ecd1114072949a57 | 31.243655 | 143 | 0.513854 | 3.920988 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Settings/AASettingsSessionsController.swift | 4 | 3059 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
open class AASettingsSessionsController: AAContentTableController {
fileprivate var sessionsCell: AAManagedArrayRows<ARApiAuthSession, AACommonCell>?
public init() {
super.init(style: AAContentTableStyle.settingsGrouped)
navigationItem.title = AALocalized("PrivacyAllSessions")
content = ACAllEvents_Settings.privacy()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func tableDidLoad() {
section { (s) -> () in
s.footerText = AALocalized("PrivacyTerminateHint")
s.danger("PrivacyTerminate") { (r) -> () in
r.selectAction = { () -> Bool in
self.confirmDangerSheetUser("PrivacyTerminateAlert", tapYes: { [unowned self] () -> () in
// Terminating all sessions and reload list
self.executeSafe(Actor.terminateAllSessionsCommand(), successBlock: { (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
return true
}
}
}
section { (s) -> () in
self.sessionsCell = s.arrays() { (r: AAManagedArrayRows<ARApiAuthSession, AACommonCell>) -> () in
r.bindData = { (c: AACommonCell, d: ARApiAuthSession) -> () in
if d.getAuthHolder().ordinal() != ARApiAuthHolder.thisdevice().ordinal() {
c.style = .normal
c.setContent(d.getDeviceTitle())
} else {
c.style = .hint
c.setContent("(Current) \(d.getDeviceTitle())")
}
}
r.selectAction = { (d) -> Bool in
if d.getAuthHolder().ordinal() != ARApiAuthHolder.thisdevice().ordinal() {
self.confirmDangerSheetUser("PrivacyTerminateAlertSingle", tapYes: { [unowned self] () -> () in
// Terminating session and reload list
self.executeSafe(Actor.terminateSessionCommand(withId: d.getId()), successBlock: { [unowned self] (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
}
return true
}
}
}
// Request sessions load
loadSessions()
}
fileprivate func loadSessions() {
execute(Actor.loadSessionsCommand(), successBlock: { [unowned self] (val) -> Void in
self.sessionsCell!.data = (val as! JavaUtilList).toArray().toSwiftArray()
self.managedTable.tableView.reloadData()
}, failureBlock: nil)
}
}
| agpl-3.0 | 9dc2c5b525a5868d9810719b242def09 | 37.2375 | 142 | 0.495587 | 5.184746 | false | false | false | false |
wanliming11/MurlocAlgorithms | Last/LeetCode/String/43._Multiply_Strings/43. Multiply Strings/main.swift | 1 | 4413 | //
// main.swift
// 43. Multiply Strings
//
// Created by FlyingPuPu on 08/02/2017.
// Copyright (c) 2017 FPP. All rights reserved.
//
import Foundation
/*
43. Multiply Strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
*/
/*
Thinking:
需要模拟单个位上的乘法,主要要储存进位和余数
例如 18 * 8
-------
18
8
64 --> 个位 (6, 4) //进6, 余4 a(个位)*b(个位)
8 -> 十位 8+6 (1,4) //进1,余4,a(十位) * b(个位) a(个位) * b(十位)
我们从个位开始计算,每次计算的结果丢入到一个栈结构中,
例如 18 * 12
例如首先计算18* 2, 先是8*2,产生了1的进位,6的余数,6进入栈,1记录
然后1*2, 2+之前的进位,产生3, 0的进位,3的余数,3进入栈,一次循环结束。
第二次循环,从栈的index = 1 开始,注意这里计算位置要反向计算
18*1 , 先是8*1,产生0的进位,8的余数,8丢进栈的1位置,1有值,则为3+8 = 11,
1 放入栈,产生了1 的进位,放到当前存储进位的位置
然后1*1, 产生了0的进位,1的余数,加上进位,就变成2, 放入到栈中。
单个过程就是:
计算->存储进位->pushStack->返回进位->合并存储进位
下一次
//Error: 如果要频繁的遍历字符,也许转换为C字符串更高效。
*/
func multiply(_ num1: String, _ num2: String) -> String {
let length1 = num1.lengthOfBytes(using: .ascii)
let length2 = num2.lengthOfBytes(using: .ascii)
guard length1 > 0, length2 > 0 else {
return ""
}
var calcResultStack: [Int] = [Int]() //存储结构
var bit: Int = 0 //存储进位
//计算是从个位开始,所以是反向计算
print("0000+ \(CFAbsoluteTimeGetCurrent())")
let num1Scalar = num1.cString(using: .ascii)
let num2Scalar = num2.cString(using: .ascii)
print("1111+ \(CFAbsoluteTimeGetCurrent())")
//把计算结果push到 stack 结构中去,然后返回结果产生的进位
func push(_ left: Int, _ index: Int) -> Int {
var appendValue = left //应该合并进的数
var bitValue = 0 //产生的进位
if calcResultStack.count > index {
appendValue += calcResultStack[index]
calcResultStack[index] = appendValue % 10
bitValue = appendValue / 10
} else {
//Error: 不能直接存进去,因为也可能超过10
calcResultStack.append(appendValue % 10)
bitValue = appendValue / 10
}
return bitValue
}
//根据输入值,计算出进位,返回(应该入栈的结果,进位)
let zeroValue = ("0" as UnicodeScalar).value //获取0的 unicode值
func calc(_ left: Int, _ right: Int) -> (Int, Int) {
let l = left - Int(zeroValue)
let r = right - Int(zeroValue)
let value = l * r
return (Int(value % 10), Int(value / 10))
}
print("2222+ \(CFAbsoluteTimeGetCurrent())")
for i in stride(from: length1 - 1, through: 0, by: -1) {
let v = Int(num1Scalar![i])
for i2 in stride(from: length2 - 1, through: 0, by: -1) {
let v2 = Int(num2Scalar![i2])
var (result, add) = calc(v, v2) //add 是下一次计算需要的进位
result += bit //先加上之前的进位
let pushAdd = push(result, length1 - 1 - i + length2 - 1 - i2) //计算出入栈产生的下一次进位
bit = add + pushAdd
}
if (bit != 0) {
//一次内循环结束,如果还有进位,则需要进位
calcResultStack.append(bit)
bit = 0
}
}
print("3333+ \(CFAbsoluteTimeGetCurrent())")
let reversedStack = calcResultStack.map {
String($0)
}.reversed()
var retString: String = ""
var start = false
for value in reversedStack {
if value != "0", !start {
start = true
}
if start {
retString.append(value)
}
}
if retString.isEmpty {
retString = "0"
}
return retString
}
print(multiply("7", "871")) | mit | 45e44997d4c02074f01cb5a981d765fd | 26.395349 | 106 | 0.595528 | 2.842317 | false | false | false | false |
FuzzyHobbit/bitcoin-swift | BitcoinSwift/PeerController.swift | 1 | 5212 | //
// PeerController.swift
// BitcoinSwift
//
// Created by Kevin Greene on 8/17/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public protocol PeerControllerDelegate: class {
func blockChainSyncComplete()
}
// TODO: Clean this up. This is ugly and hacked right now. I just threw something together to
// demo header sync'ing with the dlheader.swift script.
public class PeerController {
private let hostname: String
private let port: UInt16
private let network: Message.Network
private let queue: NSOperationQueue
private let blockChainStore: BlockChainStore
private var connection: PeerConnection?
private weak var delegate: PeerControllerDelegate?
private var peerVersion: VersionMessage?
private var headersDownloaded = 0
public init(hostname: String,
port: UInt16,
network: Message.Network,
blockChainStore: BlockChainStore,
queue: NSOperationQueue = NSOperationQueue.mainQueue(),
delegate: PeerControllerDelegate? = nil) {
self.hostname = hostname
self.port = port
self.network = network
self.blockChainStore = blockChainStore
self.queue = queue
self.delegate = delegate
}
public func start() {
precondition(connection == nil)
queue.addOperationWithBlock {
self.headersDownloaded = 0
self.connection = PeerConnection(hostname: self.hostname,
port: self.port,
network: self.network,
delegate: self,
delegateQueue: self.queue)
self.connection!.connectWithVersionMessage(self.createVersion())
}
}
private func createVersion() -> VersionMessage {
let senderPeerAddress = PeerAddress(services: PeerServices.NodeNetwork,
IP: IPAddress.IPV4(0x00000000),
port: 0)
let receiverPeerAddress = PeerAddress(services: PeerServices.NodeNetwork,
IP: IPAddress.IPV4(0x00000000),
port: 0)
return VersionMessage(protocolVersion: 70002,
services: PeerServices.NodeNetwork,
date: NSDate(),
senderAddress: senderPeerAddress,
receiverAddress: receiverPeerAddress,
nonce: 0x5e9e17ca3e515405,
userAgent: "/BitcoinSwift:0.0.1/",
blockStartHeight: 0,
announceRelayedTransactions: false)
}
private var genesisBlockHash: SHA256Hash {
let bytes: [UInt8] = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68,
0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93,
0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1,
0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f]
return SHA256Hash(bytes: bytes)
}
}
extension PeerController: PeerConnectionDelegate {
public func peerConnection(peerConnection: PeerConnection,
didConnectWithPeerVersion peerVersion: VersionMessage) {
queue.addOperationWithBlock {
self.peerVersion = peerVersion
let getHeadersMessage = GetHeadersMessage(protocolVersion: 70002,
blockLocatorHashes: [self.genesisBlockHash])
self.connection?.sendMessageWithPayload(getHeadersMessage)
}
}
public func peerConnection(peerConnection: PeerConnection,
didDisconnectWithError error: NSError?) {
Logger.info("Connection failed")
}
public func peerConnection(peerConnection: PeerConnection,
didReceiveMessage message: PeerConnectionMessage) {
switch message {
case .InventoryMessage(let inventoryMessage):
Logger.info("Inventory Message")
for inventoryVector in inventoryMessage.inventoryVectors {
Logger.info(" " + inventoryVector.description)
}
case .HeadersMessage(let headersMessage):
queue.addOperationWithBlock {
self.headersDownloaded += headersMessage.headers.count
// If there are still more headers to sync, request more.
if headersMessage.headers.count == 2000 {
let percentComplete = Double(self.headersDownloaded) /
Double(self.peerVersion!.blockStartHeight) * 100
Logger.info("Received \(headersMessage.headers.count) block headers - " +
"\(Int(percentComplete))% complete")
let lastHeaderHash = headersMessage.headers.last!.hash
let getHeadersMessage = GetHeadersMessage(protocolVersion: 70002,
blockLocatorHashes: [lastHeaderHash])
self.connection?.sendMessageWithPayload(getHeadersMessage)
} else {
Logger.info("Header sync complete")
if let delegate = self.delegate {
delegate.blockChainSyncComplete()
}
}
}
default:
break
}
}
}
| apache-2.0 | cebf668aa2594754a70e0f4fa4255251 | 37.895522 | 93 | 0.608596 | 4.926276 | false | false | false | false |
klaus01/Centipede | CentipedeExample/ViewController.swift | 1 | 2463 | //
// ViewController.swift
// CentipedeExample
//
// Created by kelei on 16/10/27.
// Copyright © 2016年 kelei. All rights reserved.
//
import UIKit
import Centipede
class ViewController: UIViewController {
private var leftTableView: UITableView!
private var rightTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let cellReuseIdentifier = "CELL"
leftTableView = UITableView()
leftTableView.frame = CGRect(x: 0, y: 0, width: view.center.x, height: view.bounds.height)
leftTableView.showsVerticalScrollIndicator = false
leftTableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
leftTableView.ce_scrollViewDidScroll { [weak self] (scrollView) in
self?.rightTableView.contentOffset = scrollView.contentOffset
}.ce_numberOfSections_in { (tableView) -> Int in
return 4
}.ce_tableView_numberOfRowsInSection { (tableView, section) -> Int in
return 8
}.ce_tableView_cellForRowAt { (tableView, indexPath) -> UITableViewCell in
return tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
}.ce_tableView_willDisplay { (tableView, cell, indexPath) in
cell.textLabel?.text = "\(indexPath.section) - \(indexPath.row)"
}
view.addSubview(leftTableView)
rightTableView = UITableView()
rightTableView.frame = leftTableView.frame
rightTableView.frame.origin.x = view.center.x
rightTableView.showsVerticalScrollIndicator = false
rightTableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
rightTableView.ce_numberOfSections_in { (tableView) -> Int in
return 8
}.ce_tableView_numberOfRowsInSection { (tableView, section) -> Int in
return 4
}.ce_tableView_cellForRowAt { (tableView, indexPath) -> UITableViewCell in
return tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
}.ce_tableView_willDisplay { (tableView, cell, indexPath) in
cell.textLabel?.text = "\(indexPath.section) - \(indexPath.row)"
}.ce_scrollViewDidScroll { [weak self] (scrollView) in
self?.leftTableView.contentOffset = scrollView.contentOffset
}
view.addSubview(rightTableView)
}
}
| mit | e411269166262c84620f1279d53649b7 | 41.413793 | 101 | 0.67561 | 5.030675 | false | false | false | false |
Jean-Daniel/PhoneNumberKit | PhoneNumberKit/UI/TextField.swift | 1 | 9590 | //
// TextField.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 07/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
/// Custom text field that formats phone numbers
open class PhoneNumberTextField: UITextField, UITextFieldDelegate {
public let phoneNumberKit = PhoneNumberKit()
/// Override setText so number will be automatically formatted when setting text by code
override open var text: String? {
set {
if isPartialFormatterEnabled && newValue != nil {
let formattedNumber = partialFormatter.formatPartial(newValue! as String)
super.text = formattedNumber
} else {
super.text = newValue
}
}
get {
return super.text
}
}
/// allows text to be set without formatting
open func setTextUnformatted(newValue: String?) {
super.text = newValue
}
/// Override region to set a custom region. Automatically uses the default region code.
open var defaultRegion = PhoneNumberKit.defaultRegionCode() {
didSet {
partialFormatter.defaultRegion = defaultRegion
}
}
public var withPrefix: Bool = true {
didSet {
partialFormatter.withPrefix = withPrefix
if withPrefix == false {
self.keyboardType = UIKeyboardType.numberPad
} else {
self.keyboardType = UIKeyboardType.phonePad
}
}
}
public var isPartialFormatterEnabled = true
public var maxDigits: Int? {
didSet {
partialFormatter.maxDigits = maxDigits
}
}
let partialFormatter: PartialFormatter
let nonNumericSet: NSCharacterSet = {
var mutableSet = NSMutableCharacterSet.decimalDigit().inverted
mutableSet.remove(charactersIn: PhoneNumberConstants.plusChars)
return mutableSet as NSCharacterSet
}()
weak private var _delegate: UITextFieldDelegate?
override open var delegate: UITextFieldDelegate? {
get {
return _delegate
}
set {
self._delegate = newValue
}
}
// MARK: Status
public var currentRegion: String {
get {
return partialFormatter.currentRegion
}
}
public var nationalNumber: String {
get {
let rawNumber = self.text ?? String()
return partialFormatter.nationalNumber(from: rawNumber)
}
}
public var isValidNumber: Bool {
get {
let rawNumber = self.text ?? String()
do {
_ = try phoneNumberKit.parse(rawNumber, withRegion: currentRegion)
return true
} catch {
return false
}
}
}
// MARK: Lifecycle
/**
Init with frame
- parameter frame: UITextfield F
- returns: UITextfield
*/
override public init(frame: CGRect) {
self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix)
super.init(frame:frame)
self.setup()
}
/**
Init with coder
- parameter aDecoder: decoder
- returns: UITextfield
*/
required public init(coder aDecoder: NSCoder) {
self.partialFormatter = PartialFormatter(phoneNumberKit: phoneNumberKit, defaultRegion: defaultRegion, withPrefix: withPrefix)
super.init(coder: aDecoder)!
self.setup()
}
func setup() {
self.autocorrectionType = .no
self.keyboardType = UIKeyboardType.phonePad
super.delegate = self
}
// MARK: Phone number formatting
/**
* To keep the cursor position, we find the character immediately after the cursor and count the number of times it repeats in the remaining string as this will remain constant in every kind of editing.
*/
internal struct CursorPosition {
let numberAfterCursor: String
let repetitionCountFromEnd: Int
}
internal func extractCursorPosition() -> CursorPosition? {
var repetitionCountFromEnd = 0
// Check that there is text in the UITextField
guard let text = text, let selectedTextRange = selectedTextRange else {
return nil
}
let textAsNSString = text as NSString
let cursorEnd = offset(from: beginningOfDocument, to: selectedTextRange.end)
// Look for the next valid number after the cursor, when found return a CursorPosition struct
for i in cursorEnd ..< textAsNSString.length {
let cursorRange = NSMakeRange(i, 1)
let candidateNumberAfterCursor: NSString = textAsNSString.substring(with: cursorRange) as NSString
if (candidateNumberAfterCursor.rangeOfCharacter(from: nonNumericSet as CharacterSet).location == NSNotFound) {
for j in cursorRange.location ..< textAsNSString.length {
let candidateCharacter = textAsNSString.substring(with: NSMakeRange(j, 1))
if candidateCharacter == candidateNumberAfterCursor as String {
repetitionCountFromEnd += 1
}
}
return CursorPosition(numberAfterCursor: candidateNumberAfterCursor as String, repetitionCountFromEnd: repetitionCountFromEnd)
}
}
return nil
}
// Finds position of previous cursor in new formatted text
internal func selectionRangeForNumberReplacement(textField: UITextField, formattedText: String) -> NSRange? {
let textAsNSString = formattedText as NSString
var countFromEnd = 0
guard let cursorPosition = extractCursorPosition() else {
return nil
}
for i in stride(from: (textAsNSString.length - 1), through: 0, by: -1) {
let candidateRange = NSMakeRange(i, 1)
let candidateCharacter = textAsNSString.substring(with: candidateRange)
if candidateCharacter == cursorPosition.numberAfterCursor {
countFromEnd += 1
if countFromEnd == cursorPosition.repetitionCountFromEnd {
return candidateRange
}
}
}
return nil
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// This allows for the case when a user autocompletes a phone number:
if range == NSRange(location: 0, length: 0) && string == " " {
return true
}
guard let text = text else {
return false
}
// allow delegate to intervene
guard _delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true else {
return false
}
guard isPartialFormatterEnabled else {
return true
}
let textAsNSString = text as NSString
let changedRange = textAsNSString.substring(with: range) as NSString
let modifiedTextField = textAsNSString.replacingCharacters(in: range, with: string)
let filteredCharacters = modifiedTextField.filter {
return String($0).rangeOfCharacter(from: (textField as! PhoneNumberTextField).nonNumericSet as CharacterSet) == nil
}
let rawNumberString = String(filteredCharacters)
let formattedNationalNumber = partialFormatter.formatPartial(rawNumberString as String)
var selectedTextRange: NSRange?
let nonNumericRange = (changedRange.rangeOfCharacter(from: nonNumericSet as CharacterSet).location != NSNotFound)
if (range.length == 1 && string.isEmpty && nonNumericRange) {
selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: modifiedTextField)
textField.text = modifiedTextField
} else {
selectedTextRange = selectionRangeForNumberReplacement(textField: textField, formattedText: formattedNationalNumber)
textField.text = formattedNationalNumber
}
sendActions(for: .editingChanged)
if let selectedTextRange = selectedTextRange, let selectionRangePosition = textField.position(from: beginningOfDocument, offset: selectedTextRange.location) {
let selectionRange = textField.textRange(from: selectionRangePosition, to: selectionRangePosition)
textField.selectedTextRange = selectionRange
}
return false
}
// MARK: UITextfield Delegate
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldBeginEditing?(textField) ?? true
}
open func textFieldDidBeginEditing(_ textField: UITextField) {
_delegate?.textFieldDidBeginEditing?(textField)
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldEndEditing?(textField) ?? true
}
open func textFieldDidEndEditing(_ textField: UITextField) {
_delegate?.textFieldDidEndEditing?(textField)
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldClear?(textField) ?? true
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldReturn?(textField) ?? true
}
}
#endif
| mit | 4d25a5eeac833e39a4c019957fc84738 | 33.617329 | 207 | 0.642924 | 5.495129 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.CurrentTransport.swift | 1 | 2041 | import Foundation
public extension AnyCharacteristic {
static func currentTransport(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read],
description: String? = "Current Transport",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.currentTransport(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func currentTransport(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read],
description: String? = "Current Transport",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Bool> {
GenericCharacteristic<Bool>(
type: .currentTransport,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 79200a6ace56cda2842f32652ad25455 | 32.459016 | 66 | 0.580108 | 5.546196 | false | false | false | false |
GabrielGhe/SwiftProjects | App8TableView/App8TableView/ViewController.swift | 1 | 1564 | //
// ViewController.swift
// App8TableView
//
// Created by Gabriel on 2014-06-30.
// Copyright (c) 2014 Gabriel. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView : UITableView
var itemCount = 10
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//How many rows
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return itemCount
}
//display cell at indexPath
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell:UITableViewCell = UITableViewCell(style: .Subtitle, reuseIdentifier: "MyTestCell")
cell.text = "Row #\(indexPath.row)"
cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"
cell.accessoryType = .Checkmark
return cell
}
//Style cell
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.backgroundColor = self.colorForIndex(indexPath.row);
}
func colorForIndex(row: Int) -> UIColor{
var val:Float = (Float(row) / Float(itemCount - 1)) * 0.6
return UIColor(red: 1.0, green: val, blue: 0.0, alpha: 1.0)
}
}
| mit | fdcc9a12e0eaed2a9af158bb66262316 | 30.28 | 128 | 0.659847 | 4.965079 | false | false | false | false |
wess/Appendix | Sources/shared/URLRequest+Appendix.swift | 1 | 567 | //
// URLRequest+Appendix.swift
// Appendix
//
// Created by Wess Cope on 1/25/19.
//
import Foundation
extension URLRequest {
public enum Method:String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
init(_ urlString:String, method:URLRequest.Method = .get) {
self.init(url: URL(string: urlString)!)
self.httpMethod = method.rawValue
}
}
| mit | 86ad25124af0b8fecd622acaf071805b | 18.551724 | 61 | 0.594356 | 3.436364 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationsViewController+JetpackPrompt.swift | 1 | 2296 | extension NotificationsViewController {
var blogForJetpackPrompt: Blog? {
return Blog.lastUsed(in: managedObjectContext())
}
func promptForJetpackCredentials() {
guard let blog = blogForJetpackPrompt else {
return
}
if let controller = jetpackLoginViewController {
controller.blog = blog
controller.updateMessageAndButton()
configureControllerCompletion(controller, withBlog: blog)
} else {
let controller = JetpackLoginViewController(blog: blog)
controller.promptType = .notifications
addChild(controller)
tableView.addSubview(withFadeAnimation: controller.view)
controller.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
controller.view.topAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.topAnchor),
controller.view.leadingAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.leadingAnchor),
controller.view.trailingAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.trailingAnchor),
controller.view.bottomAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.bottomAnchor)
])
configureControllerCompletion(controller, withBlog: blog)
jetpackLoginViewController = controller
controller.didMove(toParent: self)
}
}
fileprivate func configureControllerCompletion(_ controller: JetpackLoginViewController, withBlog blog: Blog) {
controller.completionBlock = { [weak self, weak controller] in
if AccountHelper.isDotcomAvailable() {
self?.activityIndicator.stopAnimating()
WPAppAnalytics.track(.signedInToJetpack, withProperties: ["source": "notifications"], with: blog)
controller?.view.removeFromSuperview()
controller?.removeFromParent()
self?.jetpackLoginViewController = nil
self?.configureJetpackBanner()
self?.tableView.reloadData()
} else {
self?.activityIndicator.stopAnimating()
controller?.updateMessageAndButton()
}
}
}
}
| gpl-2.0 | 78b1994f2ab538c7c42e682995da78c1 | 43.153846 | 115 | 0.654617 | 6.273224 | false | true | false | false |
cwoloszynski/XCGLogger | Sources/XCGLogger/Destinations/BaseDestination.swift | 1 | 6578 | //
// BaseDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright © 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
import Dispatch
// MARK: - BaseDestination
/// A base class destination that doesn't actually output the log anywhere and is intented to be subclassed
open class BaseDestination: DestinationProtocol, CustomDebugStringConvertible {
// MARK: - Properties
/// Logger that owns the destination object
open var owner: XCGLogger?
/// Identifier for the destination (should be unique)
open var identifier: String
/// Log level for this destination
open var outputLevel: XCGLogger.Level = .debug
/// Flag whether or not we've logged the app details to this destination
open var haveLoggedAppDetails: Bool = false
/// Array of log formatters to apply to messages before they're output
open var formatters: [LogFormatterProtocol]? = nil
/// Array of log filters to apply to messages before they're output
open var filters: [FilterProtocol]? = nil
/// Option: whether or not to output the log identifier
open var showLogIdentifier: Bool = false
/// Option: whether or not to output the function name that generated the log
open var showFunctionName: Bool = true
/// Option: whether or not to output the thread's name the log was created on
open var showThreadName: Bool = false
/// Option: whether or not to output the fileName that generated the log
open var showFileName: Bool = true
/// Option: whether or not to output the line number where the log was generated
open var showLineNumber: Bool = true
/// Option: whether or not to output the log level of the log
open var showLevel: Bool = true
/// Option: whether or not to output the date the log was created
open var showDate: Bool = true
/// Option: override descriptions of log levels
open var levelDescriptions: [XCGLogger.Level: String] = [:]
// MARK: - CustomDebugStringConvertible
open var debugDescription: String {
get {
return "\(extractTypeName(self)): \(identifier) - Level: \(outputLevel) showLogIdentifier: \(showLogIdentifier) showFunctionName: \(showFunctionName) showThreadName: \(showThreadName) showLevel: \(showLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber) showDate: \(showDate)"
}
}
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, identifier: String = "") {
self.owner = owner
self.identifier = identifier
}
// MARK: - Methods to Process Log Details
/// Process the log details.
///
/// - Parameters:
/// - logDetails: Structure with all of the details for the log to process.
///
/// - Returns: Nothing
///
open func process(logDetails: LogDetails) {
guard let owner = owner else { return }
var extendedDetails: String = ""
if showDate {
extendedDetails += "\((owner.dateFormatter != nil) ? owner.dateFormatter!.string(from: logDetails.date) : logDetails.date.description) "
}
if showLevel {
extendedDetails += "[\(levelDescriptions[logDetails.level] ?? owner.levelDescriptions[logDetails.level] ?? logDetails.level.description)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
#if !os(Linux)
if showThreadName {
if Thread.isMainThread {
extendedDetails += "[main] "
}
else {
if let threadName = Thread.current.name, !threadName.isEmpty {
extendedDetails += "[\(threadName)] "
}
else if let queueName = DispatchQueue.currentQueueLabel, !queueName.isEmpty {
extendedDetails += "[\(queueName)] "
}
else {
extendedDetails += String(format: "[%p] ", Thread.current)
}
}
}
#endif
if showFileName {
let lastPath = URL(fileURLWithPath: logDetails.fileName).lastPathComponent
extendedDetails += "[\(lastPath)\((showLineNumber ? ":" + String(logDetails.lineNumber) : ""))] "
}
else if showLineNumber {
extendedDetails += "[\(logDetails.lineNumber)] "
}
if showFunctionName {
extendedDetails += "\(logDetails.functionName) "
}
output(logDetails: logDetails, message: "\(extendedDetails)> \(logDetails.message)")
}
/// Process the log details (internal use, same as process(logDetails:) but omits function/file/line info).
///
/// - Parameters:
/// - logDetails: Structure with all of the details for the log to process.
///
/// - Returns: Nothing
///
open func processInternal(logDetails: LogDetails) {
guard let owner = owner else { return }
var extendedDetails: String = ""
if showDate {
extendedDetails += "\((owner.dateFormatter != nil) ? owner.dateFormatter!.string(from: logDetails.date) : logDetails.date.description) "
}
if showLevel {
extendedDetails += "[\(logDetails.level)] "
}
if showLogIdentifier {
extendedDetails += "[\(owner.identifier)] "
}
output(logDetails: logDetails, message: "\(extendedDetails)> \(logDetails.message)")
}
// MARK: - Misc methods
/// Check if the destination's log level is equal to or lower than the specified level.
///
/// - Parameters:
/// - level: The log level to check.
///
/// - Returns:
/// - true: Log destination is at the log level specified or lower.
/// - false: Log destination is at a higher log level.
///
open func isEnabledFor(level: XCGLogger.Level) -> Bool {
return level >= self.outputLevel
}
// MARK: - Methods that must be overriden in subclasses
/// Output the log to the destination.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open func output(logDetails: LogDetails, message: String) {
// Do something with the text in an overridden version of this method
precondition(false, "Must override this")
}
}
| mit | 00285afd6865138da9b61f81be35f1cc | 34.551351 | 306 | 0.624297 | 4.900894 | false | false | false | false |
migue1s/habitica-ios | HabitRPG/UI/Intro/IntroViewController.swift | 2 | 4471 | //
// IntroViewController.swift
// Habitica
//
// Created by Phillip Thelen on 31/12/2016.
// Copyright © 2016 Phillip Thelen. All rights reserved.
//
import UIKit
import EAIntroView
class IntroViewController: UIViewController, EAIntroDelegate {
var intro: EAIntroView?
//swiftlint:disable:next function_body_length
override func viewDidLoad() {
let titleposition = (self.view.frame.size.height / 2) - (self.view.frame.size.height / 16)
let page1 = EAIntroPage()
page1.title = "Welcome to Habitica".localized
page1.titlePositionY = titleposition
page1.titleFont = UIFont.boldSystemFont(ofSize: 20.0)
let userCount = "2,000,000"
page1.desc = "Join over \(userCount) people having fun while getting things done. Create an avatar and track your real-life tasks.".localized
page1.descPositionY = titleposition - 24
page1.descFont = UIFont.systemFont(ofSize: 14.0)
page1.titleIconView = UIImageView(image: #imageLiteral(resourceName: "IntroPage1"))
page1.titleIconPositionY = titleposition - 90
weak var weakPage1 = page1
page1.onPageDidLoad = {
weakPage1?.titleIconView.alpha = 0
}
page1.onPageDidDisappear = {
weakPage1?.titleIconView.alpha = 0
}
page1.onPageDidAppear = {
UIView .animate(withDuration: 0.8, animations: {
weakPage1?.titleIconView.alpha = 1
})
}
let page2 = EAIntroPage()
page2.title = "Game Progress = Life Progress".localized
page2.titlePositionY = titleposition
page2.titleFont = UIFont.boldSystemFont(ofSize: 20.0)
page2.desc = "Unlock features in the game by checking off your real-life tasks. Earn armor, pets, and more to reward you for meeting your goals!".localized
page2.descPositionY = titleposition - 24
page2.descFont = UIFont.systemFont(ofSize: 14.0)
page2.titleIconView = UIImageView(image: #imageLiteral(resourceName: "IntroPage2"))
page2.titleIconPositionY = titleposition - 220
weak var weakPage2 = page2
page2.onPageDidLoad = {
weakPage2?.titleIconView.alpha = 0
}
page2.onPageDidDisappear = {
weakPage2?.titleIconView.alpha = 0
}
page2.onPageDidAppear = {
UIView .animate(withDuration: 0.8, animations: {
weakPage2?.titleIconView.alpha = 1
})
}
let page3 = EAIntroPage()
page3.titlePositionY = titleposition
page3.titleFont = UIFont.boldSystemFont(ofSize: 20.0)
page3.title = "Get Social and Fight Monsters".localized
page3.desc = "Keep your goals on track with help from your friends. Support each other in life and in battle as you improve together!".localized
page3.descPositionY = titleposition - 24
page3.descFont = UIFont.systemFont(ofSize: 14.0)
page3.titleIconView = UIImageView(image: #imageLiteral(resourceName: "IntroPage3"))
page3.titleIconPositionY = titleposition - 230
weak var weakPage3 = page3
page3.onPageDidLoad = {
weakPage3?.titleIconView.alpha = 0
}
page3.onPageDidDisappear = {
weakPage3?.titleIconView.alpha = 0
}
page3.onPageDidAppear = {
UIView .animate(withDuration: 0.8, animations: {
weakPage3?.titleIconView.alpha = 1
})
}
self.intro = EAIntroView(frame: self.view.frame, andPages: [page1, page2, page3])
self.intro?.bgImage = #imageLiteral(resourceName: "IntroBackground")
self.intro?.delegate = self
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.intro?.show(in: self.view)
}
func introDidFinish(_ introView: EAIntroView!, wasSkipped: Bool) {
self.performSegue(withIdentifier: "LoginSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "LoginSegue" {
if let navigationController = segue.destination as? UINavigationController {
if let loginViewController = navigationController.topViewController as? LoginTableViewController {
loginViewController.isRootViewController = true
}
}
}
}
}
| gpl-3.0 | 4640b05ecf101bb7e19a15749c543a30 | 38.210526 | 163 | 0.64094 | 4.48345 | false | false | false | false |
TabletopAssistant/DiceKit | DiceKit/FrequencyDistribution.swift | 1 | 10329 | //
// FrequencyDistribution.swift
// DiceKit
//
// Created by Brentley Jones on 7/24/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
public protocol FrequencyDistributionOutcomeType: InvertibleMultiplicativeType, Hashable {
/// The number that will be used when determining how many times to perform another
/// expression when multiplied by `self`.
var multiplierEquivalent: Int { get }
}
extension Int: InvertibleMultiplicativeType, FrequencyDistributionOutcomeType {
public static let additiveIdentity: Int = 0
public static let multiplicativeIdentity: Int = 1
public var multiplierEquivalent: Int {
return self
}
}
extension Double: InvertibleMultiplicativeType {
public static let additiveIdentity: Double = 0.0
public static let multiplicativeIdentity: Double = 1.0
public var multiplierEquivalent: Double {
return self
}
}
public struct FrequencyDistribution<OutcomeType: FrequencyDistributionOutcomeType>: Equatable {
public typealias Outcome = OutcomeType
public typealias Frequency = Double
public typealias FrequenciesPerOutcome = [Outcome: Frequency]
// TODO: Change to stored properties when allowed by Swift
public static var additiveIdentity: FrequencyDistribution {
return FrequencyDistribution(FrequenciesPerOutcome())
}
public static var multiplicativeIdentity: FrequencyDistribution {
return FrequencyDistribution([Outcome.additiveIdentity: Frequency.multiplicativeIdentity])
}
public let frequenciesPerOutcome: FrequenciesPerOutcome
let orderedOutcomes: [Outcome]
internal init(_ frequenciesPerOutcome: FrequenciesPerOutcome, delta: Double) {
self.frequenciesPerOutcome = frequenciesPerOutcome.filterValues { abs($0) > delta }
self.orderedOutcomes = self.frequenciesPerOutcome.map { $0.0 }.sort()
}
public init(_ frequenciesPerOutcome: FrequenciesPerOutcome) {
self.init(frequenciesPerOutcome, delta: 0.0)
}
}
// MARK: - CustomStringConvertible
extension FrequencyDistribution: CustomStringConvertible {
public var description: String {
let sortedFrequenciesPerOutcome = frequenciesPerOutcome.sort {
$0.0 < $1.0
}
let stringifiedFrequenciesPerOutcome: [String] = sortedFrequenciesPerOutcome.map {
"\($0.0): \($0.1)"
}
let innerDesc = stringifiedFrequenciesPerOutcome.joinWithSeparator(", ")
let desc = "[\(innerDesc)]"
return desc
}
}
// MARK: - Equatable
public func == <V>(lhs: FrequencyDistribution<V>, rhs: FrequencyDistribution<V>) -> Bool {
return lhs.frequenciesPerOutcome == rhs.frequenciesPerOutcome
}
// MARK: - Indexable
extension FrequencyDistribution: Indexable {
public typealias Index = FrequencyDistributionIndex<Outcome>
public typealias _Element = (Outcome, Frequency) // This is needed to prevent ambigious Indexable conformance...
/// Returns the `Index` for the given value, or `nil` if the value is not
/// present in the frequency distribution.
public func indexForOutcome(outcome: Outcome) -> Index? {
guard frequenciesPerOutcome[outcome] != nil else {
return nil
}
let index = orderedOutcomes.indexOf(outcome)! // This won't crash because we already know the value exists. This isn't used in the guard, because checking if it exists is O(1), while this is O(n)
return FrequencyDistributionIndex(index: index, orderedOutcomes: orderedOutcomes)
}
public var startIndex: Index {
return FrequencyDistributionIndex.startIndex(orderedOutcomes)
}
public var endIndex: Index {
return FrequencyDistributionIndex.endIndex(orderedOutcomes)
}
public subscript(index: Index) -> (Outcome, Frequency) {
let outcome = index.value!
let frequency = frequenciesPerOutcome[outcome]!
return (outcome, frequency)
}
}
// MARK: - CollectionType
extension FrequencyDistribution: CollectionType {
// Protocol defaults cover implmentation after conforming to `Indexable`
}
// MARK: - Operations
extension FrequencyDistribution {
// MARK: Foundational Operations
public func mapOutcomes(@noescape transform: (Outcome) -> Outcome) -> FrequencyDistribution {
let newFrequenciesPerOutcome = frequenciesPerOutcome.mapKeys ({ $1 + $2 }) {
(baseOutcome, _) in transform(baseOutcome)
}
return FrequencyDistribution(newFrequenciesPerOutcome)
}
public func mapFrequencies(@noescape transform: (Frequency) -> Frequency) -> FrequencyDistribution {
let newFrequenciesPerOutcome = frequenciesPerOutcome.mapValues {
(_, frequency) in transform(frequency)
}
return FrequencyDistribution(newFrequenciesPerOutcome)
}
// MARK: Primitive Operations
public subscript(outcome: Outcome) -> Frequency? {
get {
return frequenciesPerOutcome[outcome]
}
}
public func approximatelyEqual(x: FrequencyDistribution, delta: Frequency) -> Bool {
guard frequenciesPerOutcome.count == x.frequenciesPerOutcome.count else {
return false
}
for (outcome, frequency) in frequenciesPerOutcome {
guard let otherFrequency = x.frequenciesPerOutcome[outcome] else {
return false
}
let diff = abs(frequency - otherFrequency)
if diff > delta {
return false
}
}
return true
}
public func negateOutcomes() -> FrequencyDistribution {
return mapOutcomes { -$0 }
}
public func shiftOutcomes(outcome: Outcome) -> FrequencyDistribution {
return mapOutcomes { $0 + outcome }
}
public func scaleFrequencies(frequency: Frequency) -> FrequencyDistribution {
return mapFrequencies { $0 * frequency }
}
public func normalizeFrequencies() -> FrequencyDistribution {
let frequencies: Frequency = frequenciesPerOutcome.reduce(0) {
let (_, value) = $1
return $0 + value
}
return mapFrequencies { $0 / frequencies }
}
public func minimumOutcome() -> Outcome? {
return orderedOutcomes.first
}
public func maximumOutcome() -> Outcome? {
return orderedOutcomes.last
}
public func filterZeroFrequencies(delta: Frequency) -> FrequencyDistribution {
let newFrequenciesPerOutcome = frequenciesPerOutcome
return FrequencyDistribution(newFrequenciesPerOutcome, delta: delta)
}
// MARK: Advanced Operations
public func add(x: FrequencyDistribution) -> FrequencyDistribution {
var newFrequenciesPerOutcome = frequenciesPerOutcome
for (outcome, frequency) in x.frequenciesPerOutcome {
let exisitingFrequency = newFrequenciesPerOutcome[outcome] ?? 0
let newFrequency = exisitingFrequency + frequency
newFrequenciesPerOutcome[outcome] = newFrequency
}
return FrequencyDistribution(newFrequenciesPerOutcome)
}
public func subtract(x: FrequencyDistribution) -> FrequencyDistribution {
var newFrequenciesPerOutcome = frequenciesPerOutcome
for (outcome, frequency) in x.frequenciesPerOutcome {
let exisitingFrequency = newFrequenciesPerOutcome[outcome] ?? 0
let newFrequency = exisitingFrequency - frequency
newFrequenciesPerOutcome[outcome] = newFrequency
}
return FrequencyDistribution(newFrequenciesPerOutcome)
}
public func multiply(x: FrequencyDistribution) -> FrequencyDistribution {
return frequenciesPerOutcome.reduce(.additiveIdentity) {
let (outcome, frequency) = $1
let addend = x.shiftOutcomes(outcome).scaleFrequencies(frequency)
return $0.add(addend)
}
}
/// This is a special case of `power(x: FrequencyDistribution)`,
/// for when `x` is `FrequencyDistribution([x: 1])`.
public func power(x: Outcome) -> FrequencyDistribution {
let power = x.multiplierEquivalent
guard power != 0 else { return .multiplicativeIdentity }
// Crappy implementation. Currently O(n). Can be O(log(n)).
var freqDist = self
for _ in 1..<abs(power) {
freqDist = freqDist.multiply(self)
}
// if (power < 0) {
// return FrequencyDistribution.multiplicativeIdentity.divide(freqDist)
// } else {
return freqDist
// }
}
public func power(x: FrequencyDistribution) -> FrequencyDistribution {
return frequenciesPerOutcome.reduce(.additiveIdentity) {
let (outcome, frequency) = $1
let addend = x.power(outcome).normalizeFrequencies().scaleFrequencies(frequency)
return $0.add(addend)
}
}
}
// TODO: Remove the need for ForwardIndexType
extension FrequencyDistribution where OutcomeType: ForwardIndexType {
public func divide(y: FrequencyDistribution) -> FrequencyDistribution {
guard let initialK = orderedOutcomes.first, lastK = orderedOutcomes.last else {
return .additiveIdentity
}
guard let firstY = y.orderedOutcomes.first, lastY = y.orderedOutcomes.last, firstYFrequency = y[firstY] where firstYFrequency != 0.0 else {
fatalError("Invalid divide operation. The divisor expression must not be empty, and its first frequency must not be zero.")
}
var xFrequencies: FrequenciesPerOutcome = [:]
for k in initialK...(lastK + lastY) {
var p: Frequency = 0.0
for (n, frequency) in xFrequencies {
p += frequency * (y[k - n] ?? 0)
}
xFrequencies[k - firstY] = ((frequenciesPerOutcome[k] ?? 0) - p) / firstYFrequency
}
let delta = ProbabilityMassConfig.probabilityEqualityDelta
return FrequencyDistribution(xFrequencies).filterZeroFrequencies(delta)
}
}
| apache-2.0 | 963a972e85948305ad12b7d94874e011 | 33.198675 | 203 | 0.659179 | 5.197786 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Extensions/UIFontDescriptor+Extensions.swift | 1 | 4424 | //
// UIFontDescriptor+Extensions.swift
// EclipseSoundscapes
//
// Created by Arlindo on 7/15/18.
// Copyright © 2018 Arlindo Goncalves. All rights reserved.
//
import UIKit
extension UIFontDescriptor {
@nonobjc static var fontSizeTable: [UIFont.TextStyle : [UIContentSizeCategory : CGFloat]] = {
return [
.headline: [
.accessibilityExtraExtraExtraLarge: 25,
.accessibilityExtraExtraLarge: 25,
.accessibilityExtraLarge: 25,
.accessibilityLarge: 25,
.accessibilityMedium: 25,
.extraExtraExtraLarge: 25,
.extraExtraLarge: 23,
.extraLarge: 21,
.large: 19,
.medium: 18,
.small: 17,
.extraSmall: 16],
.subheadline: [
.accessibilityExtraExtraExtraLarge: 21,
.accessibilityExtraExtraLarge: 21,
.accessibilityExtraLarge: 21,
.accessibilityLarge: 21,
.accessibilityMedium: 21,
.extraExtraExtraLarge: 21,
.extraExtraLarge: 19,
.extraLarge: 17,
.large: 15,
.medium: 14,
.small: 13,
.extraSmall: 12],
.body: [
.accessibilityExtraExtraExtraLarge: 53,
.accessibilityExtraExtraLarge: 47,
.accessibilityExtraLarge: 40,
.accessibilityLarge: 33,
.accessibilityMedium: 28,
.extraExtraExtraLarge: 23,
.extraExtraLarge: 21,
.extraLarge: 19,
.large: 17,
.medium: 16,
.small: 15,
.extraSmall: 14],
.caption1: [
.accessibilityExtraExtraExtraLarge: 18,
.accessibilityExtraExtraLarge: 18,
.accessibilityExtraLarge: 18,
.accessibilityLarge: 18,
.accessibilityMedium: 18,
.extraExtraExtraLarge: 18,
.extraExtraLarge: 16,
.extraLarge: 14,
.large: 12,
.medium: 11,
.small: 11,
.extraSmall: 11],
.caption2: [
.accessibilityExtraExtraExtraLarge: 17,
.accessibilityExtraExtraLarge: 17,
.accessibilityExtraLarge: 17,
.accessibilityLarge: 17,
.accessibilityMedium: 17,
.extraExtraExtraLarge: 17,
.extraExtraLarge: 15,
.extraLarge: 13,
.large: 11,
.medium: 11,
.small: 11,
.extraSmall: 11],
.footnote: [
.accessibilityExtraExtraExtraLarge: 19,
.accessibilityExtraExtraLarge: 19,
.accessibilityExtraLarge: 19,
.accessibilityLarge: 19,
.accessibilityMedium: 19,
.extraExtraExtraLarge: 19,
.extraExtraLarge: 17,
.extraLarge: 15,
.large: 13,
.medium: 12,
.small: 12,
.extraSmall: 12]
]
}()
class func currentPreferredSize(textStyle: UIFont.TextStyle = .body, scale: CGFloat = 1.0) -> CGFloat {
let contentSize = UIApplication.shared.preferredContentSizeCategory
guard let style = fontSizeTable[textStyle], let fontSize = style[contentSize] else { return 17 }
return fontSize * scale
}
class func preferredFontDescriptor(fontName: Futura = .condensedMedium, textStyle: UIFont.TextStyle = .body, scale: CGFloat = 1.0) -> UIFontDescriptor {
var name : String!
switch fontName {
case .condensedMedium:
name = "Futura-CondensedMedium"
case .extraBold:
name = "Futura-CondensedExtraBold"
case .meduium :
name = "Futura-Medium"
case .italic:
name = "Futura-MediumItalic"
case .bold :
if #available(iOS 10.0, *) {
name = "Futura-Bold"
} else {
name = "Futura-CondensedMedium"
}
}
return UIFontDescriptor(name: name, size: currentPreferredSize(textStyle: textStyle, scale: scale))
}
}
| gpl-3.0 | 32a19e1a111b589947600efd52bd4e59 | 34.95935 | 156 | 0.508026 | 5.648787 | false | false | false | false |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Charts/BarChartView.swift | 3 | 11653 | //
// BarChartView.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
/// Chart that draws bars.
public class BarChartView: BarLineChartViewBase, BarChartRendererDelegate
{
/// flag that enables or disables the highlighting arrow
private var _drawHighlightArrowEnabled = false
/// if set to true, all values are drawn above their bars, instead of below their top
private var _drawValueAboveBarEnabled = true
/// if set to true, all values of a stack are drawn individually, and not just their sum
private var _drawValuesForWholeStackEnabled = true
/// if set to true, a grey area is darawn behind each bar that indicates the maximum value
private var _drawBarShadowEnabled = false
internal override func initialize()
{
super.initialize();
renderer = BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler);
_xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self);
_chartXMin = -0.5;
}
internal override func calcMinMax()
{
super.calcMinMax();
if (_data === nil)
{
return;
}
var barData = _data as! BarChartData;
// increase deltax by 1 because the bars have a width of 1
_deltaX += 0.5;
// extend xDelta to make space for multiple datasets (if ther are one)
_deltaX *= CGFloat(_data.dataSetCount);
var maxEntry = 0;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var set = barData.getDataSetByIndex(i);
if (maxEntry < set!.entryCount)
{
maxEntry = set!.entryCount;
}
}
var groupSpace = barData.groupSpace;
_deltaX += CGFloat(maxEntry) * groupSpace;
_chartXMax = Float(_deltaX) - _chartXMin;
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
public override func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.");
return nil;
}
_leftAxisTransformer.pixelToValue(&pt);
if (pt.x < CGFloat(_chartXMin) || pt.x > CGFloat(_chartXMax))
{
return nil;
}
return getHighlight(xPosition: pt.x, yPosition: pt.y);
}
/// Returns the correct Highlight object (including xIndex and dataSet-index) for the specified touch position.
internal func getHighlight(#xPosition: CGFloat, yPosition: CGFloat) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
return nil;
}
var barData = _data as! BarChartData!;
var setCount = barData.dataSetCount;
var valCount = barData.xValCount;
var dataSetIndex = 0;
var xIndex = 0;
if (!barData.isGrouped)
{ // only one dataset exists
xIndex = Int(round(xPosition));
// check bounds
if (xIndex < 0)
{
xIndex = 0;
}
else if (xIndex >= valCount)
{
xIndex = valCount - 1;
}
}
else
{ // if this bardata is grouped into more datasets
// calculate how often the group-space appears
var steps = Int(xPosition / (CGFloat(setCount) + CGFloat(barData.groupSpace)));
var groupSpaceSum = barData.groupSpace * CGFloat(steps);
var baseNoSpace = xPosition - groupSpaceSum;
dataSetIndex = Int(baseNoSpace) % setCount;
xIndex = Int(baseNoSpace) / setCount;
// check bounds
if (xIndex < 0)
{
xIndex = 0;
dataSetIndex = 0;
}
else if (xIndex >= valCount)
{
xIndex = valCount - 1;
dataSetIndex = setCount - 1;
}
// check bounds
if (dataSetIndex < 0)
{
dataSetIndex = 0;
}
else if (dataSetIndex >= setCount)
{
dataSetIndex = setCount - 1;
}
}
var dataSet = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!;
if (!dataSet.isStacked)
{
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex);
}
else
{
return getStackedHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, yValue: Float(yPosition));
}
}
/// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected.
internal func getStackedHighlight(#xIndex: Int, dataSetIndex: Int, yValue: Float) -> ChartHighlight!
{
var dataSet = _data.getDataSetByIndex(dataSetIndex);
var entry = dataSet.entryForXIndex(xIndex) as! BarChartDataEntry!;
if (entry !== nil)
{
var stackIndex = entry.getClosestIndexAbove(yValue);
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex);
}
else
{
return nil;
}
}
/// Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
public func getBarBounds(e: BarChartDataEntry) -> CGRect!
{
var set = _data.getDataSetForEntry(e) as! BarChartDataSet!;
if (set === nil)
{
return nil;
}
var barspace = set.barSpace;
var y = CGFloat(e.value);
var x = CGFloat(e.xIndex);
var barWidth: CGFloat = 0.5;
var spaceHalf = barspace / 2.0;
var left = x - barWidth + spaceHalf;
var right = x + barWidth - spaceHalf;
var top = y >= 0.0 ? y : 0.0;
var bottom = y <= 0.0 ? y : 0.0;
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top);
getTransformer(set.axisDependency).rectValueToPixel(&bounds);
return bounds;
}
public override var lowestVisibleXIndex: Int
{
var step = CGFloat(_data.dataSetCount);
var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace;
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom);
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt);
return Int(((pt.x <= 0.0) ? 0.0 : pt.x / div) + 1.0);
}
public override var highestVisibleXIndex: Int
{
var step = CGFloat(_data.dataSetCount);
var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace;
var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom);
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt);
return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div));
}
// MARK: Accessors
/// flag that enables or disables the highlighting arrow
public var drawHighlightArrowEnabled: Bool
{
get { return _drawHighlightArrowEnabled; }
set
{
_drawHighlightArrowEnabled = newValue;
setNeedsDisplay();
}
}
/// if set to true, all values are drawn above their bars, instead of below their top
public var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled; }
set
{
_drawValueAboveBarEnabled = newValue;
setNeedsDisplay();
}
}
/// if set to true, all values of a stack are drawn individually, and not just their sum
public var drawValuesForWholeStackEnabled: Bool
{
get { return _drawValuesForWholeStackEnabled; }
set
{
_drawValuesForWholeStackEnabled = newValue;
setNeedsDisplay();
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
public var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled; }
set
{
_drawBarShadowEnabled = newValue;
setNeedsDisplay();
}
}
/// returns true if drawing the highlighting arrow is enabled, false if not
public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; }
/// returns true if drawing values above bars is enabled, false if not
public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; }
/// returns true if all values of a stack are drawn, and not just their sum
public var isDrawValuesForWholeStackEnabled: Bool { return drawValuesForWholeStackEnabled; }
/// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not
public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; }
// MARK: - BarChartRendererDelegate
public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData!
{
return _data as! BarChartData!;
}
public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
{
return getTransformer(which);
}
public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int
{
return maxVisibleValueCount;
}
public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter!
{
return valueFormatter;
}
public func barChartRendererChartYMax(renderer: BarChartRenderer) -> Float
{
return chartYMax;
}
public func barChartRendererChartYMin(renderer: BarChartRenderer) -> Float
{
return chartYMin;
}
public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Float
{
return chartXMax;
}
public func barChartRendererChartXMin(renderer: BarChartRenderer) -> Float
{
return chartXMin;
}
public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool
{
return drawHighlightArrowEnabled;
}
public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool
{
return drawValueAboveBarEnabled;
}
public func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool
{
return drawValuesForWholeStackEnabled;
}
public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool
{
return drawBarShadowEnabled;
}
public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool
{
return getAxis(axis).isInverted;
}
} | gpl-2.0 | 2707da4662cf3e087242cdc15fec5a4d | 31.016484 | 150 | 0.594439 | 5.347866 | false | false | false | false |
congncif/SiFUtilities | Example/Pods/Boardy/Boardy/Core/BoardType/InteractableBoard.swift | 1 | 2286 | //
// InteractableBoard.swift
// Boardy
//
// Created by FOLY on 10/24/20.
//
import Foundation
public protocol BoardCommandModel {
var identifier: BoardID { get }
var data: Any? { get }
}
public protocol InteractableBoard: ActivatableBoard {
func interact(command: Any?)
}
extension InteractableBoard {
public func interact(command: BoardCommandModel) {
#if DEBUG
print("\(String(describing: self)) \n⚠️ Has called \(#function) with \(command)")
#endif
}
}
public protocol GuaranteedCommandBoard: InteractableBoard {
associatedtype CommandType
func interact(guaranteedCommand: CommandType)
}
extension GuaranteedCommandBoard {
public func interact(command: Any?) {
guard let commandData = command as? CommandType else {
#if DEBUG
assertionFailure("\(String(describing: self)) \n⚠️ Received command \(command) while expected type is \(CommandType.self)")
#endif
return
}
interact(guaranteedCommand: commandData)
}
}
// MARK: - BoardCommand with Input
public struct BoardCommand<Input>: BoardCommandModel {
public let identifier: BoardID
public let input: Input
public var data: Any? { input }
public init(identifier: BoardID, input: Input) {
self.identifier = identifier
self.input = input
}
}
extension BoardCommand {
public func withIdentifier(_ identifier: BoardID) -> BoardCommand {
BoardCommand(identifier: identifier, input: input)
}
}
extension BoardCommand {
public static func target<Input>(_ id: BoardID, _ input: Input) -> BoardCommand<Input> {
BoardCommand<Input>(identifier: id, input: input)
}
}
extension BoardCommand where Input == Void {
public init(identifier: BoardID) {
self.init(identifier: identifier, input: ())
}
public static func target(_ id: BoardID) -> BoardCommand<Input> {
BoardCommand<Input>(identifier: id)
}
}
extension BoardCommand where Input: ExpressibleByNilLiteral {
public init(identifier: BoardID) {
self.init(identifier: identifier, input: nil)
}
public static func target(_ id: BoardID) -> BoardCommand<Input> {
BoardCommand<Input>(identifier: id)
}
}
| mit | f5e008781e277d83b0dd9efd92505012 | 24.595506 | 135 | 0.666813 | 4.218519 | false | false | false | false |
anzfactory/QiitaCollection | QiitaCollection/EntryEntity.swift | 1 | 1655 | //
// EntryEntity.swift
// QiitaCollection
//
// Created by ANZ on 2015/02/07.
// Copyright (c) 2015年 anz. All rights reserved.
//
import SwiftyJSON
struct EntryEntity: EntityProtocol {
let id: String
let title: String
let body: String
let htmlBody: String
let urlString: String
let updateDate: String
let postUser: UserEntity
var tags: [TagEntity]
init (data: JSON) {
id = data["id"].string!
title = data["title"].string!
body = data["body"].string!
htmlBody = data["rendered_body"].string!
urlString = data["url"].string!
updateDate = data["updated_at"].string!
tags = [TagEntity]()
for tagObject: JSON in data["tags"].array! {
let tag: TagEntity = TagEntity(data: tagObject)
tags.append(tag)
}
postUser = UserEntity(data: data["user"].dictionary!)
}
var shortUpdateDate: String {
get { return updateDate.componentsSeparatedByString("T")[0] }
}
var beginning: String {
get {
let str: NSString = NSString(string: body)
let result = body.substringToIndex(advance(body.startIndex, min(50, str.length)))
return body.substringToIndex(advance(body.startIndex, min(50, str.length)))
.stringByReplacingOccurrencesOfString("\n", withString: " ", options: nil, range: nil) + "…"
}
}
func toTagList() -> [String] {
var ids: [String] = [String]()
for tag in self.tags {
ids.append(tag.id)
}
return ids
}
}
| mit | 00a62c522113a806f1b7c392c7f024b4 | 26.065574 | 108 | 0.565718 | 4.211735 | false | false | false | false |
hughbe/swift | test/IDE/print_clang_decls.swift | 2 | 8207 | // RUN: %empty-directory(%t)
// XFAIL: linux
// This file deliberately does not use %clang-importer-sdk for most RUN lines.
// Instead, it generates custom overlay modules itself, and uses -I %t when it
// wants to use them.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=TAG_DECLS_AND_TYPEDEFS -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=FOUNDATION -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes.bits -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=CTYPESBITS -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=nullability -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=CHECK-NULLABILITY -strict-whitespace < %t.printed.txt
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct1 {{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: /*!
// TAG_DECLS_AND_TYPEDEFS-NEXT: @keyword Foo2
// TAG_DECLS_AND_TYPEDEFS-NEXT: */
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStruct2 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}typealias FooStructTypedef1 = FooStruct2{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStructTypedef2 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct3 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct4 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct5 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct6 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// Skip through unavailable typedefs when importing types.
// TAG_DECLS_AND_TYPEDEFS: @available(*, unavailable, message: "use double")
// TAG_DECLS_AND_TYPEDEFS-NEXT: typealias real_t = Double
// TAG_DECLS_AND_TYPEDEFS-NEXT: func realSin(_ value: Double) -> Double
// NEGATIVE-NOT: typealias FooStructTypedef2
// FOUNDATION-LABEL: {{^}}/// Aaa. NSArray. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}class NSArray : NSObject {{{$}}
// FOUNDATION-NEXT: subscript(idx: Int) -> Any { get }
// FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingMode. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}enum NSRuncingMode : UInt {{{$}}
// FOUNDATION-NEXT: {{^}} init?(rawValue: UInt){{$}}
// FOUNDATION-NEXT: {{^}} var rawValue: UInt { get }{{$}}
// FOUNDATION-NEXT: {{^}} case mince{{$}}
// FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "mince"){{$}}
// FOUNDATION-NEXT: {{^}} static var Mince: NSRuncingMode { get }{{$}}
// FOUNDATION-NEXT: {{^}} case quince{{$}}
// FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "quince"){{$}}
// FOUNDATION-NEXT: {{^}} static var Quince: NSRuncingMode { get }{{$}}
// FOUNDATION-NEXT: {{^}}}{{$}}
// FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingOptions. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}struct NSRuncingOptions : OptionSet {{{$}}
// FOUNDATION-NEXT: {{^}} init(rawValue: UInt){{$}}
// FOUNDATION-NEXT: {{^}} let rawValue: UInt{{$}}
// FOUNDATION-NEXT: {{^}} typealias RawValue = UInt
// FOUNDATION-NEXT: {{^}} typealias Element = NSRuncingOptions
// FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}}
// FOUNDATION-NEXT: {{^}} static var none: NSRuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}}
// FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "none"){{$}}
// FOUNDATION-NEXT: {{^}} static var None: NSRuncingOptions { get }
// FOUNDATION-NEXT: {{^}} static var enableMince: NSRuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableMince"){{$}}
// FOUNDATION-NEXT: {{^}} static var EnableMince: NSRuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} static var enableQuince: NSRuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableQuince"){{$}}
// FOUNDATION-NEXT: {{^}} static var EnableQuince: NSRuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}}}{{$}}
// FOUNDATION-LABEL: {{^}}/// Unavailable Global Functions{{$}}
// FOUNDATION-NEXT: @available(*, unavailable, message: "Zone-based memory management is unavailable")
// FOUNDATION-NEXT: NSSetZoneName(_ zone: NSZone, _ name: String)
// CTYPESBITS-NOT: FooStruct1
// CTYPESBITS: {{^}}typealias DWORD = Int32{{$}}
// CTYPESBITS-NEXT: {{^}}var MY_INT: Int32 { get }{{$}}
// CTYPESBITS-NOT: FooStruct1
// CHECK-NULLABILITY: func getId1() -> Any?
// CHECK-NULLABILITY: var global_id: AnyObject?
// CHECK-NULLABILITY: class SomeClass {
// CHECK-NULLABILITY: class func methodA(_ obj: SomeClass?) -> Any{{$}}
// CHECK-NULLABILITY: func methodA(_ obj: SomeClass?) -> Any{{$}}
// CHECK-NULLABILITY: class func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}}
// CHECK-NULLABILITY: func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}}
// CHECK-NULLABILITY: func methodC() -> Any?
// CHECK-NULLABILITY: var property: Any?
// CHECK-NULLABILITY: func stringMethod() -> String{{$}}
// CHECK-NULLABILITY: func optArrayMethod() -> [Any]?
// CHECK-NULLABILITY: }
// CHECK-NULLABILITY: func compare_classes(_ sc1: SomeClass, _ sc2: SomeClass, _ sc3: SomeClass!)
| apache-2.0 | 493865013b356f03edae006a83e61aac | 56.795775 | 215 | 0.639089 | 3.273634 | false | false | false | false |
nessBautista/iOSBackup | iOSNotebook/Pods/RxSwift/RxSwift/Traits/Completable.swift | 17 | 10965 | //
// Completable.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing 0 elements
public enum CompletableTrait { }
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
case .completed:
onCompleted?()
}
}
}
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> Completable {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> Completable {
return PrimitiveSequence(raw: Observable.never())
}
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> Completable {
return Completable(raw: Observable.empty())
}
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onError: ((Swift.Error) throws -> Void)? = nil,
onCompleted: (() throws -> Void)? = nil,
onSubscribe: (() -> ())? = nil,
onSubscribed: (() -> ())? = nil,
onDispose: (() -> ())? = nil)
-> Completable {
return Completable(raw: primitiveSequence.source.do(
onError: onError,
onCompleted: onCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat(_ second: Completable) -> Completable {
return Completable.concat(primitiveSequence, second)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Sequence>(_ sequence: S) -> Completable
where S.Iterator.Element == Completable {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<C: Collection>(_ collection: C) -> Completable
where C.Iterator.Element == Completable {
let source = Observable.concat(collection.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Completable ...) -> Completable {
let source = Observable.concat(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<C: Collection>(_ sources: C) -> Completable
where C.Iterator.Element == Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [Completable]) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: Completable...) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
}
| cc0-1.0 | 10136fd2d996fca6a81b3475748d4f43 | 41.332046 | 220 | 0.661073 | 5.291506 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/iOS/Extensions/UIScreen+AspectRatio.swift | 1 | 823 |
import Foundation
extension UIScreen {
var aspectRatio: String {
let numbers = [bounds.width, bounds.height]
// Normalize the input vector to that the maximum is 1.0,
// and compute rational approximations of all components:
let maximum = numbers.max()!
let rats = numbers.map({($0/maximum).rationalApproximation})
// Multiply all rational numbers by the LCM of the denominators:
let commonDenominator = lcm(rats.map({$0.denominator}))
let numerators = rats.map({$0.numerator * commonDenominator / $0.denominator})
// Divide the numerators by the GCD of all numerators:
let commonNumerator = gcd(numerators)
return numerators.map({ String($0 / commonNumerator) }).joined(separator: ":")
}
}
| gpl-3.0 | f6ce87c95aa5f156c4fa9822c7d7ccb0 | 33.291667 | 86 | 0.63548 | 4.472826 | false | false | false | false |
squarefrog/TraktTopTen | TraktTopTen/Controllers/ViewController.swift | 1 | 3233 | //
// ViewController.swift
// TraktTopTen
//
// Created by Paul Williamson on 04/04/2015.
// Copyright (c) 2015 Paul Williamson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var dataSource: CollectionViewDataSource?
var delegate: CollectionViewDelegateFlowLayout?
var activityIndicator: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Top Ten Movies"
setupCollectionView()
fetchAndDisplayTopMovies()
showActivityIndicatorView()
}
func showActivityIndicatorView() {
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
activityIndicator?.startAnimating()
activityIndicator?.color = UIColor.applicationLightGrayColour()
activityIndicator?.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(activityIndicator!)
let centerX = NSLayoutConstraint(
item: activityIndicator!,
attribute: .CenterX,
relatedBy: .Equal,
toItem: self.view,
attribute: .CenterX,
multiplier: 1.0,
constant: 0.0)
let centerY = NSLayoutConstraint(
item: activityIndicator!,
attribute: .CenterY,
relatedBy: .Equal,
toItem: self.view,
attribute: .CenterY,
multiplier: 1.0,
constant: 0.0)
self.view.addConstraints([centerX, centerY])
}
func setupCollectionView() {
delegate = CollectionViewDelegateFlowLayout()
collectionView.delegate = delegate!
dataSource = CollectionViewDataSource(collectionView: collectionView)
collectionView.dataSource = dataSource!
collectionView.backgroundColor = UIColor.applicationBackgroundColour()
}
func fetchAndDisplayTopMovies() {
let application = UIApplication.sharedApplication()
application.networkActivityIndicatorVisible = true
TraktAPIManager().fetchTopMovies { (data, errorString) -> Void in
application.networkActivityIndicatorVisible = false
dispatch_async(dispatch_get_main_queue()) {
if let unwrappedData: NSData = data {
let array = MediaItemFactory().createMediaItems(unwrappedData)
self.dataSource?.updateData(array)
self.activityIndicator?.removeFromSuperview()
} else if let error = errorString {
print("\(error)")
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let indexPath = collectionView.indexPathsForSelectedItems()?.first else {
return
}
if let mediaItem = dataSource?.mediaItemForIndexPath(indexPath) {
let viewController = segue.destinationViewController as! DetailViewController
viewController.mediaItem = mediaItem
}
}
}
| mit | 765c2193b5a50a5277e21c514a7bc1f2 | 32.329897 | 89 | 0.621404 | 6.32681 | false | false | false | false |
notohiro/NowCastMapView | Example/Example/ViewController.swift | 1 | 4771 | //
// ViewController.swift
// Example
//
// Created by Hiroshi Noto on 1/26/16.
// Copyright © 2016 Hiroshi Noto. All rights reserved.
//
import UIKit
import MapKit
import NowCastMapView
class ViewController: UIViewController {
struct Constants {
static let numberOfForecastBars = 12
static let numberOfPastBars = 12
}
// MARK: - IBOutlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var indexLabel: UILabel!
// MARK: - NowCastMapView Variables
let baseTimeModel = BaseTimeModel()
var baseTime: BaseTime? {
didSet {
if oldValue == baseTime { return }
if let baseTime = baseTime {
print("baseTime updated: \(baseTime)")
renderers.removeAll()
mapView.removeOverlays(mapView.overlays)
let overlay = Overlay()
for index in -Constants.numberOfPastBars...Constants.numberOfForecastBars {
let renderer = OverlayRenderer(overlay: overlay, baseTime: baseTime, index: index)
renderers[index] = renderer
}
OperationQueue.main.addOperation {
self.mapView.add(overlay, level: .aboveRoads)
self.mapView.setNeedsDisplay()
}
rainLevelsModel = RainLevelsModel(baseTime: baseTime, delegate: self)
}
}
}
var index: Int = 0 {
didSet {
if index == oldValue { return }
indexLabel.text = "\(index)"
let overlays = mapView.overlays
mapView.removeOverlays(overlays)
mapView.addOverlays(overlays)
}
}
var rainLevelsModel: RainLevelsModel?
// MARK: - Other Variables
var renderers = [Int: OverlayRenderer]()
var annotation: MKPointAnnotation? {
didSet {
if let annotation = annotation {
let request = RainLevelsModel.Request(coordinate: annotation.coordinate, range: 0...0)
do {
let task = try rainLevelsModel?.rainLevels(with: request)
task?.resume()
} catch let error {
print(error)
}
}
}
}
// MARK: - Application Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialize mapView
mapView.delegate = self
// register notification
baseTimeModel.delegate = self
baseTimeModel.fetch()
baseTimeModel.fetchInterval = 3
slider.maximumValue = Float(Constants.numberOfForecastBars)
slider.minimumValue = -Float(Constants.numberOfPastBars)
indexLabel.text = "\(index)"
}
// MARK: - IBAction
@IBAction private func handleLongPressGesture(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
// remove existing annotations
mapView.removeAnnotations(mapView.annotations)
// add annotation
let touchedPoint = sender.location(in: mapView)
let touchCoordinate = mapView.convert(touchedPoint, toCoordinateFrom: mapView)
let anno = MKPointAnnotation()
anno.coordinate = touchCoordinate
annotation = anno
mapView.addAnnotation(anno)
}
}
@IBAction private func sliderValueChanged(_ sender: UISlider) {
index = Int(floor(sender.value))
sender.value = Float(index)
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
// MARK: - BaseTimeModelDelegate
extension ViewController: BaseTimeModelDelegate {
public func baseTimeModel(_ model: BaseTimeModel, fetched baseTime: BaseTime?) {
self.baseTime = baseTime
}
}
// MARK: - BaseTimeModelDelegate
extension ViewController: RainLevelsModelDelegate {
func rainLevelsModel(_ model: RainLevelsModel, task: RainLevelsModel.Task, result: RainLevelsModel.Result) {
switch result {
case let .succeeded(request: _, result: result):
guard let level = result.levels[0]?.rawValue else { return }
let message = "level = " + String(level)
let alertController = UIAlertController(title: "RainLevels", message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
OperationQueue.main.addOperation {
self.present(alertController, animated: true, completion: nil)
}
case let .failed(request: _, error: error):
print(error)
let message = "failed"
let alertController = UIAlertController(title: "RainLevels", message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
OperationQueue.main.addOperation {
self.present(alertController, animated: true, completion: nil)
}
}
}
}
// MARK: - MKMapViewDelegate
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
return renderers[index]!
}
}
| mit | e4df566e85e6fbd13cd56961da55c520 | 25.5 | 132 | 0.721593 | 4.097938 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ApplePlatform/Graphic/CGColor.swift | 1 | 4634 | //
// CGColor.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreGraphics)
extension Color {
public var cgColor: CGColor? {
return colorSpace.cgColorSpace.flatMap { CGColor(colorSpace: $0, components: color.map { CGFloat($0) } + [CGFloat(opacity)]) }
}
}
protocol CGColorConvertibleProtocol {
var cgColor: CGColor? { get }
}
extension Color: CGColorConvertibleProtocol {
}
extension AnyColor {
public init?(cgColor: CGColor) {
guard let colorSpace = cgColor.colorSpace.flatMap(AnyColorSpace.init) else { return nil }
guard let components = cgColor.components, components.count == colorSpace.numberOfComponents + 1 else { return nil }
guard let opacity = components.last else { return nil }
self.init(colorSpace: colorSpace, components: components.dropLast().lazy.map(Double.init), opacity: Double(opacity))
}
}
extension AnyColor {
public var cgColor: CGColor? {
if let base = self.base as? CGColorConvertibleProtocol {
return base.cgColor
}
return nil
}
}
#if canImport(UIKit)
extension CGColor {
public class var clear: CGColor { return UIColor.clear.cgColor }
public class var black: CGColor { return UIColor.black.cgColor }
public class var blue: CGColor { return UIColor.blue.cgColor }
public class var brown: CGColor { return UIColor.brown.cgColor }
public class var cyan: CGColor { return UIColor.cyan.cgColor }
public class var darkGray: CGColor { return UIColor.darkGray.cgColor }
public class var gray: CGColor { return UIColor.gray.cgColor }
public class var green: CGColor { return UIColor.green.cgColor }
public class var lightGray: CGColor { return UIColor.lightGray.cgColor }
public class var magenta: CGColor { return UIColor.magenta.cgColor }
public class var orange: CGColor { return UIColor.orange.cgColor }
public class var purple: CGColor { return UIColor.purple.cgColor }
public class var red: CGColor { return UIColor.red.cgColor }
public class var white: CGColor { return UIColor.white.cgColor }
public class var yellow: CGColor { return UIColor.yellow.cgColor }
}
#elseif canImport(AppKit)
extension CGColor {
public class var clear: CGColor { return NSColor.clear.cgColor }
public class var black: CGColor { return NSColor.black.cgColor }
public class var blue: CGColor { return NSColor.blue.cgColor }
public class var brown: CGColor { return NSColor.brown.cgColor }
public class var cyan: CGColor { return NSColor.cyan.cgColor }
public class var darkGray: CGColor { return NSColor.darkGray.cgColor }
public class var gray: CGColor { return NSColor.gray.cgColor }
public class var green: CGColor { return NSColor.green.cgColor }
public class var lightGray: CGColor { return NSColor.lightGray.cgColor }
public class var magenta: CGColor { return NSColor.magenta.cgColor }
public class var orange: CGColor { return NSColor.orange.cgColor }
public class var purple: CGColor { return NSColor.purple.cgColor }
public class var red: CGColor { return NSColor.red.cgColor }
public class var white: CGColor { return NSColor.white.cgColor }
public class var yellow: CGColor { return NSColor.yellow.cgColor }
}
#endif
#endif
| mit | 01ed37460563bd768e50add131a2152b | 31.865248 | 134 | 0.697238 | 4.610945 | false | false | false | false |
zhuhaow/NEKit | src/RawSocket/NWTCPSocket.swift | 2 | 9774 | import Foundation
import NetworkExtension
import CocoaLumberjackSwift
/// The TCP socket build upon `NWTCPConnection`.
///
/// - warning: This class is not thread-safe.
public class NWTCPSocket: NSObject, RawTCPSocketProtocol {
private var connection: NWTCPConnection?
private var writePending = false
private var closeAfterWriting = false
private var cancelled = false
private var scanner: StreamScanner!
private var scanning: Bool = false
private var readDataPrefix: Data?
// MARK: RawTCPSocketProtocol implementation
/// The `RawTCPSocketDelegate` instance.
weak open var delegate: RawTCPSocketDelegate?
/// If the socket is connected.
public var isConnected: Bool {
return connection != nil && connection!.state == .connected
}
/// The source address.
///
/// - note: Always returns `nil`.
public var sourceIPAddress: IPAddress? {
return nil
}
/// The source port.
///
/// - note: Always returns `nil`.
public var sourcePort: Port? {
return nil
}
/// The destination address.
///
/// - note: Always returns `nil`.
public var destinationIPAddress: IPAddress? {
return nil
}
/// The destination port.
///
/// - note: Always returns `nil`.
public var destinationPort: Port? {
return nil
}
/**
Connect to remote host.
- parameter host: Remote host.
- parameter port: Remote port.
- parameter enableTLS: Should TLS be enabled.
- parameter tlsSettings: The settings of TLS.
- throws: Never throws.
*/
public func connectTo(host: String, port: Int, enableTLS: Bool, tlsSettings: [AnyHashable: Any]?) throws {
let endpoint = NWHostEndpoint(hostname: host, port: "\(port)")
let tlsParameters = NWTLSParameters()
if let tlsSettings = tlsSettings as? [String: AnyObject] {
tlsParameters.setValuesForKeys(tlsSettings)
}
guard let connection = RawSocketFactory.TunnelProvider?.createTCPConnection(to: endpoint, enableTLS: enableTLS, tlsParameters: tlsParameters, delegate: nil) else {
// This should only happen when the extension is already stopped and `RawSocketFactory.TunnelProvider` is set to `nil`.
return
}
self.connection = connection
connection.addObserver(self, forKeyPath: "state", options: [.initial, .new], context: nil)
}
/**
Disconnect the socket.
The socket will disconnect elegantly after any queued writing data are successfully sent.
*/
public func disconnect() {
cancelled = true
if connection == nil || connection!.state == .cancelled {
delegate?.didDisconnectWith(socket: self)
} else {
closeAfterWriting = true
checkStatus()
}
}
/**
Disconnect the socket immediately.
*/
public func forceDisconnect() {
cancelled = true
if connection == nil || connection!.state == .cancelled {
delegate?.didDisconnectWith(socket: self)
} else {
cancel()
}
}
/**
Send data to remote.
- parameter data: Data to send.
- warning: This should only be called after the last write is finished, i.e., `delegate?.didWriteData()` is called.
*/
public func write(data: Data) {
guard !cancelled else {
return
}
guard data.count > 0 else {
QueueFactory.getQueue().async {
self.delegate?.didWrite(data: data, by: self)
}
return
}
send(data: data)
}
/**
Read data from the socket.
- warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called.
*/
public func readData() {
guard !cancelled else {
return
}
connection!.readMinimumLength(1, maximumLength: Opt.MAXNWTCPSocketReadDataSize) { data, error in
guard error == nil else {
DDLogError("NWTCPSocket got an error when reading data: \(String(describing: error))")
self.queueCall {
self.disconnect()
}
return
}
self.readCallback(data: data)
}
}
/**
Read specific length of data from the socket.
- parameter length: The length of the data to read.
- warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called.
*/
public func readDataTo(length: Int) {
guard !cancelled else {
return
}
connection!.readLength(length) { data, error in
guard error == nil else {
DDLogError("NWTCPSocket got an error when reading data: \(String(describing: error))")
self.queueCall {
self.disconnect()
}
return
}
self.readCallback(data: data)
}
}
/**
Read data until a specific pattern (including the pattern).
- parameter data: The pattern.
- warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called.
*/
public func readDataTo(data: Data) {
readDataTo(data: data, maxLength: 0)
}
// Actually, this method is available as `- (void)readToPattern:(id)arg1 maximumLength:(unsigned int)arg2 completionHandler:(id /* block */)arg3;`
// which is sadly not available in public header for some reason I don't know.
// I don't want to do it myself since This method is not trival to implement and I don't like reinventing the wheel.
// Here is only the most naive version, which may not be the optimal if using with large data blocks.
/**
Read data until a specific pattern (including the pattern).
- parameter data: The pattern.
- parameter maxLength: The max length of data to scan for the pattern.
- warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called.
*/
public func readDataTo(data: Data, maxLength: Int) {
guard !cancelled else {
return
}
var maxLength = maxLength
if maxLength == 0 {
maxLength = Opt.MAXNWTCPScanLength
}
scanner = StreamScanner(pattern: data, maximumLength: maxLength)
scanning = true
readData()
}
private func queueCall(_ block: @escaping () -> Void) {
QueueFactory.getQueue().async(execute: block)
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == "state" else {
return
}
switch connection!.state {
case .connected:
queueCall {
self.delegate?.didConnectWith(socket: self)
}
case .disconnected:
cancelled = true
cancel()
case .cancelled:
cancelled = true
queueCall {
let delegate = self.delegate
self.delegate = nil
delegate?.didDisconnectWith(socket: self)
}
default:
break
}
}
private func readCallback(data: Data?) {
guard !cancelled else {
return
}
queueCall {
guard let data = self.consumeReadData(data) else {
// remote read is closed, but this is okay, nothing need to be done, if this socket is read again, then error occurs.
return
}
if self.scanning {
guard let (match, rest) = self.scanner.addAndScan(data) else {
self.readData()
return
}
self.scanner = nil
self.scanning = false
guard let matchData = match else {
// do not find match in the given length, stop now
return
}
self.readDataPrefix = rest
self.delegate?.didRead(data: matchData, from: self)
} else {
self.delegate?.didRead(data: data, from: self)
}
}
}
private func send(data: Data) {
writePending = true
self.connection!.write(data) { error in
self.queueCall {
self.writePending = false
guard error == nil else {
DDLogError("NWTCPSocket got an error when writing data: \(String(describing: error))")
self.disconnect()
return
}
self.delegate?.didWrite(data: data, by: self)
self.checkStatus()
}
}
}
private func consumeReadData(_ data: Data?) -> Data? {
defer {
readDataPrefix = nil
}
if readDataPrefix == nil {
return data
}
if data == nil {
return readDataPrefix
}
var wholeData = readDataPrefix!
wholeData.append(data!)
return wholeData
}
private func cancel() {
connection?.cancel()
}
private func checkStatus() {
if closeAfterWriting && !writePending {
cancel()
}
}
deinit {
guard let connection = connection else {
return
}
connection.removeObserver(self, forKeyPath: "state")
}
}
| bsd-3-clause | 41d86360775d9b924121aeabd05f697c | 28.618182 | 171 | 0.565889 | 4.891892 | false | false | false | false |
hsiun/yoyo | ufile/ios/demo/ufile sdk demo/ufile sdk demo/MultipartTableCell.swift | 1 | 1745 | //
// MultipartTableCell.swift
// ufile sdk demo
//
// Created by wu shauk on 12/16/15.
// Copyright © 2015 ucloud. All rights reserved.
//
import UIKit
class MultipartTableCell: UITableViewCell {
var session: MultipartSession?
var partNumber: Int = 0
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var downloadBtn: UIButton!
func setSession(session: MultipartSession, partNumber: Int) {
self.session = session
self.partNumber = partNumber
self.progressBar.setProgress(0, animated: false)
self.downloadBtn.enabled = true
}
@IBAction func startDownload(sender: AnyObject) {
let contentType = "application/jpeg"
let auth = self.session!.ufileSDK.calcKey("PUT", key: self.session!.key, contentMd5: nil, contentType: contentType)
self.session!.ufileSDK.ufileSDK?.multipartUploadPart(self.session!.key, uploadId: self.session!.uploadId, partNumber: self.partNumber, contentType: contentType, data: (self.session!.getDataForPart(UInt(self.partNumber)))!, authorization: auth,
progress: { (progress:NSProgress) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.progressBar.setProgress(Float(progress.fractionCompleted), animated: true)
})
},
success: { (result: [NSObject : AnyObject]) -> Void in
self.downloadBtn.enabled = false
self.session!.addEtag(UInt(self.partNumber), etag: result[kUFileRespETag] as! NSString as String)
},
failure: { (err: NSError) -> Void in
self.progressBar.backgroundColor = UIColor.redColor()
})
}
}
| apache-2.0 | 3da103c608dbcd09c02da7ea0e0965a6 | 39.55814 | 251 | 0.642775 | 4.349127 | false | false | false | false |
domenicosolazzo/practice-swift | Notifications/Scheduling Local Notifications/Scheduling Local Notifications/AppDelegate.swift | 1 | 2143 | //
// AppDelegate.swift
// Scheduling Local Notifications
//
// Created by Domenico Solazzo on 15/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/* First ask the user if we are
allowed to perform local notifications */
let settings = UIUserNotificationSettings(types: .alert,
categories: nil)
application.registerUserNotificationSettings(settings)
return true
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types == nil{
/* The user did not allow us to send notifications */
return
}
let notification = UILocalNotification()
// This is a property of type NSDate that dictates to iOS
// when the instance of the local notification has to be fired. This is required.
notification.fireDate = Date(timeIntervalSinceNow: 8)
// The time zone in which the given fire-date is specified
notification.timeZone = Calendar.current.timeZone
// The text that has to be displayed to the user when
// your notification is displayed on screen
notification.alertBody = "A new item has been downloaded"
notification.hasAction = true
// It represents the action that the user can take on your local notification
notification.alertAction = "View"
// The badge number for your app icon
notification.applicationIconBadgeNumber += 1
// More additional information about the local notification
notification.userInfo = [
"Key 1": "Value1",
"Key 2": "Value2"
]
/* Schedule the notification */
application.scheduleLocalNotification(notification)
}
}
| mit | 9c269b617dacc21570c417f385c0214d | 32.484375 | 144 | 0.644424 | 5.887363 | false | false | false | false |
samodom/TestableMapKit | TestableMapKit/MKRouteStep/MKRouteStep.swift | 1 | 2390 | //
// MKRouteStep.swift
// TestableMapKit
//
// Created by Sam Odom on 12/26/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import MapKit
public class MKRouteStep: MapKit.MKRouteStep {
/*!
Mutable override of `polyline` property.
*/
public override var polyline: MKPolyline! {
get {
if polylineOverride != nil {
return polylineOverride!
}
else {
return super.polyline
}
}
set {
polylineOverride = newValue
}
}
/*!
Mutable override of `instructions` property.
*/
public override var instructions: String! {
get {
if instructionsOverride != nil {
return instructionsOverride!
}
else {
return super.instructions
}
}
set {
instructionsOverride = newValue
}
}
/*!
Mutable override of `notice` property.
*/
public override var notice: String! {
get {
if noticeOverride != nil {
return noticeOverride!
}
else {
return super.notice
}
}
set {
noticeOverride = newValue
}
}
/*!
Mutable override of `distance` property.
*/
public override var distance: CLLocationDistance {
get {
if distanceOverride != nil {
return distanceOverride!
}
else {
return super.distance
}
}
set {
distanceOverride = newValue
}
}
/*!
Mutable override of `transportType` property.
*/
public override var transportType: MKDirectionsTransportType {
get {
if transportTypeOverride != nil {
return transportTypeOverride!
}
else {
return super.transportType
}
}
set {
transportTypeOverride = newValue
}
}
private var polylineOverride: MKPolyline?
private var instructionsOverride: String?
private var noticeOverride: String?
private var distanceOverride: CLLocationDistance?
private var transportTypeOverride: MKDirectionsTransportType?
}
| mit | 6044879c427110f9d63f96dd240ad653 | 21.761905 | 66 | 0.512971 | 5.663507 | false | false | false | false |
hjw6160602/JourneyNotes | JourneyNotes/Classes/Common/Category/UIView+AutoLayout.swift | 1 | 14355 | //
// UIView+AutoLayout.swift
// XMGWeibo
//
// Created by 李南江 on 15/9/1.
// Copyright © 2015年 xiaomage. All rights reserved.
//
import UIKit
/**
对齐类型枚举,设置控件相对于父视图的位置
- TopLeft: 左上
- TopRight: 右上
- TopCenter: 中上
- BottomLeft: 左下
- BottomRight: 右下
- BottomCenter: 中下
- CenterLeft: 左中
- CenterRight: 右中
- Center: 中中
*/
public enum XMG_AlignType {
case topLeft
case topRight
case topCenter
case bottomLeft
case bottomRight
case bottomCenter
case centerLeft
case centerRight
case center
fileprivate func layoutAttributes(_ isInner: Bool, isVertical: Bool) -> XMG_LayoutAttributes {
let attributes = XMG_LayoutAttributes()
switch self {
case .topLeft:
_ = attributes.horizontals(.left, to: .left).verticals(.top, to: .top)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.bottom, to: .top)
} else {
return attributes.horizontals(.right, to: .left)
}
case .topRight:
_ = attributes.horizontals(.right, to: .right).verticals(.top, to: .top)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.bottom, to: .top)
} else {
return attributes.horizontals(.left, to: .right)
}
case .bottomLeft:
_ = attributes.horizontals(.left, to: .left).verticals(.bottom, to: .bottom)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.top, to: .bottom)
} else {
return attributes.horizontals(.right, to: .left)
}
case .bottomRight:
_ = attributes.horizontals(.right, to: .right).verticals(.bottom, to: .bottom)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.top, to: .bottom)
} else {
return attributes.horizontals(.left, to: .right)
}
// 仅内部 & 垂直参照需要
case .topCenter:
_ = attributes.horizontals(.centerX, to: .centerX).verticals(.top, to: .top)
return isInner ? attributes : attributes.verticals(.bottom, to: .top)
// 仅内部 & 垂直参照需要
case .bottomCenter:
_ = attributes.horizontals(.centerX, to: .centerX).verticals(.bottom, to: .bottom)
return isInner ? attributes : attributes.verticals(.top, to: .bottom)
// 仅内部 & 水平参照需要
case .centerLeft:
_ = attributes.horizontals(.left, to: .left).verticals(.centerY, to: .centerY)
return isInner ? attributes : attributes.horizontals(.right, to: .left)
// 仅内部 & 水平参照需要
case .centerRight:
_ = attributes.horizontals(.right, to: .right).verticals(.centerY, to: .centerY)
return isInner ? attributes : attributes.horizontals(.left, to: .right)
// 仅内部参照需要
case .center:
return XMG_LayoutAttributes(horizontal: .centerX, referHorizontal: .centerX, vertical: .centerY, referVertical: .centerY)
}
}
}
extension UIView {
/**
填充子视图
:param: referView 参考视图
:param: insets 间距
:returns: 约束数组
*/
public func xmg_Fill(_ referView: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(insets.left)-[subView]-\(insets.right)-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: nil, views: ["subView" : self])
cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(insets.top)-[subView]-\(insets.bottom)-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: nil, views: ["subView" : self])
superview?.addConstraints(cons)
return cons
}
/**
参照参考视图内部对齐
:param: type 对齐方式
:param: referView 参考视图
:param: size 视图大小,如果是 nil 则不设置大小
:param: offset 偏移量,默认是 CGPoint(x: 0, y: 0)
:returns: 约束数组
*/
public func xmg_AlignInner(type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPoint.zero) -> [NSLayoutConstraint] {
return xmg_AlignLayout(referView, attributes: type.layoutAttributes(true, isVertical: true), size: size, offset: offset)
}
/**
参照参考视图垂直对齐
:param: type 对齐方式
:param: referView 参考视图
:param: size 视图大小,如果是 nil 则不设置大小
:param: offset 偏移量,默认是 CGPoint(x: 0, y: 0)
:returns: 约束数组
*/
public func xmg_AlignVertical(type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPoint.zero) -> [NSLayoutConstraint] {
return xmg_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: true), size: size, offset: offset)
}
/**
参照参考视图水平对齐
:param: type 对齐方式
:param: referView 参考视图
:param: size 视图大小,如果是 nil 则不设置大小
:param: offset 偏移量,默认是 CGPoint(x: 0, y: 0)
:returns: 约束数组
*/
public func xmg_AlignHorizontal(type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPoint.zero) -> [NSLayoutConstraint] {
return xmg_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: false), size: size, offset: offset)
}
/**
在当前视图内部水平平铺控件
:param: views 子视图数组
:param: insets 间距
:returns: 约束数组
*/
public func xmg_HorizontalTile(_ views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] {
assert(!views.isEmpty, "views should not be empty")
var cons = [NSLayoutConstraint]()
let firstView = views[0]
_ = firstView.xmg_AlignInner(type: XMG_AlignType.topLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top))
cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -insets.bottom))
// 添加后续视图的约束
var preView = firstView
for i in 1..<views.count {
let subView = views[i]
cons += subView.xmg_sizeConstraints(firstView)
_ = subView.xmg_AlignHorizontal(type: XMG_AlignType.topRight, referView: preView, size: nil, offset: CGPoint(x: insets.right, y: 0))
preView = subView
}
let lastView = views.last!
cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -insets.right))
addConstraints(cons)
return cons
}
/**
在当前视图内部垂直平铺控件
:param: views 子视图数组
:param: insets 间距
:returns: 约束数组
*/
public func xmg_VerticalTile(_ views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] {
assert(!views.isEmpty, "views should not be empty")
var cons = [NSLayoutConstraint]()
let firstView = views[0]
_ = firstView.xmg_AlignInner(type: XMG_AlignType.topLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top))
cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -insets.right))
// 添加后续视图的约束
var preView = firstView
for i in 1..<views.count {
let subView = views[i]
cons += subView.xmg_sizeConstraints(firstView)
_ = subView.xmg_AlignVertical(type: XMG_AlignType.bottomLeft, referView: preView, size: nil, offset: CGPoint(x: 0, y: insets.bottom))
preView = subView
}
let lastView = views.last!
cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -insets.bottom))
addConstraints(cons)
return cons
}
/**
从约束数组中查找指定 attribute 的约束
:param: constraintsList 约束数组
:param: attribute 约束属性
:returns: 对应的约束
*/
public func xmg_Constraint(_ constraintsList: [NSLayoutConstraint], attribute: NSLayoutAttribute) -> NSLayoutConstraint? {
for constraint in constraintsList {
if constraint.firstItem as! NSObject == self && constraint.firstAttribute == attribute {
return constraint
}
}
return nil
}
// MARK: - 私有函数
/**
参照参考视图对齐布局
:param: referView 参考视图
:param: attributes 参照属性
:param: size 视图大小,如果是 nil 则不设置大小
:param: offset 偏移量,默认是 CGPoint(x: 0, y: 0)
:returns: 约束数组
*/
fileprivate func xmg_AlignLayout(_ referView: UIView, attributes: XMG_LayoutAttributes, size: CGSize?, offset: CGPoint) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += xmg_positionConstraints(referView, attributes: attributes, offset: offset)
if size != nil {
cons += xmg_sizeConstraints(size!)
}
superview?.addConstraints(cons)
return cons
}
/**
尺寸约束数组
:param: size 视图大小
:returns: 约束数组
*/
fileprivate func xmg_sizeConstraints(_ size: CGSize) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: size.width))
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: size.height))
return cons
}
/**
尺寸约束数组
:param: referView 参考视图,与参考视图大小一致
:returns: 约束数组
*/
fileprivate func xmg_sizeConstraints(_ referView: UIView) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: referView, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0))
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: referView, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: 0))
return cons
}
/**
位置约束数组
:param: referView 参考视图
:param: attributes 参照属性
:param: offset 偏移量
:returns: 约束数组
*/
fileprivate func xmg_positionConstraints(_ referView: UIView, attributes: XMG_LayoutAttributes, offset: CGPoint) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: attributes.horizontal, relatedBy: NSLayoutRelation.equal, toItem: referView, attribute: attributes.referHorizontal, multiplier: 1.0, constant: offset.x))
cons.append(NSLayoutConstraint(item: self, attribute: attributes.vertical, relatedBy: NSLayoutRelation.equal, toItem: referView, attribute: attributes.referVertical, multiplier: 1.0, constant: offset.y))
return cons
}
}
/// 布局属性
private final class XMG_LayoutAttributes {
var horizontal: NSLayoutAttribute
var referHorizontal: NSLayoutAttribute
var vertical: NSLayoutAttribute
var referVertical: NSLayoutAttribute
init() {
horizontal = NSLayoutAttribute.left
referHorizontal = NSLayoutAttribute.left
vertical = NSLayoutAttribute.top
referVertical = NSLayoutAttribute.top
}
init(horizontal: NSLayoutAttribute, referHorizontal: NSLayoutAttribute, vertical: NSLayoutAttribute, referVertical: NSLayoutAttribute) {
self.horizontal = horizontal
self.referHorizontal = referHorizontal
self.vertical = vertical
self.referVertical = referVertical
}
fileprivate func horizontals(_ from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self {
horizontal = from
referHorizontal = to
return self
}
fileprivate func verticals(_ from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self {
vertical = from
referVertical = to
return self
}
}
| mit | 7515c6ac254c8551ae9414a65dfd8018 | 34.978667 | 222 | 0.606359 | 4.601637 | false | false | false | false |
ManuelAurora/RxQuickbooksService | Example/Pods/Action/Sources/Action/Action.swift | 2 | 4366 | import Foundation
import RxSwift
import RxCocoa
/// Typealias for compatibility with UIButton's rx.action property.
public typealias CocoaAction = Action<Void, Void>
/// Possible errors from invoking execute()
public enum ActionError: Error {
case notEnabled
case underlyingError(Error)
}
/**
Represents a value that accepts a workFactory which takes some Observable<Input> as its input
and produces an Observable<Element> as its output.
When this excuted via execute() or inputs subject, it passes its parameter to this closure and subscribes to the work.
*/
public final class Action<Input, Element> {
public typealias WorkFactory = (Input) -> Observable<Element>
public let _enabledIf: Observable<Bool>
public let workFactory: WorkFactory
/// Inputs that triggers execution of action.
/// This subject also includes inputs as aguments of execute().
/// All inputs are always appear in this subject even if the action is not enabled.
/// Thus, inputs count equals elements count + errors count.
public let inputs = InputSubject<Input>()
/// Errors aggrevated from invocations of execute().
/// Delivered on whatever scheduler they were sent from.
public let errors: Observable<ActionError>
/// Whether or not we're currently executing.
/// Delivered on whatever scheduler they were sent from.
public let elements: Observable<Element>
/// Whether or not we're currently executing.
public let executing: Observable<Bool>
/// Observables returned by the workFactory.
/// Useful for sending results back from work being completed
/// e.g. response from a network call.
public let executionObservables: Observable<Observable<Element>>
/// Whether or not we're enabled. Note that this is a *computed* sequence
/// property based on enabledIf initializer and if we're currently executing.
/// Always observed on MainScheduler.
public let enabled: Observable<Bool>
private let disposeBag = DisposeBag()
public init(
enabledIf: Observable<Bool> = Observable.just(true),
workFactory: @escaping WorkFactory) {
self._enabledIf = enabledIf
self.workFactory = workFactory
let enabledSubject = BehaviorSubject<Bool>(value: false)
enabled = enabledSubject.asObservable()
let errorsSubject = PublishSubject<ActionError>()
errors = errorsSubject.asObservable()
executionObservables = inputs
.withLatestFrom(enabled) { $0 }
.flatMap { input, enabled -> Observable<Observable<Element>> in
if enabled {
return Observable.of(workFactory(input)
.do(onError: { errorsSubject.onNext(.underlyingError($0)) })
.shareReplay(1))
} else {
errorsSubject.onNext(.notEnabled)
return Observable.empty()
}
}
.share()
elements = executionObservables
.flatMap { $0.catchError { _ in Observable.empty() } }
executing = executionObservables.flatMap {
execution -> Observable<Bool> in
let execution = execution
.flatMap { _ in Observable<Bool>.empty() }
.catchError { _ in Observable.empty()}
return Observable.concat([Observable.just(true),
execution,
Observable.just(false)])
}
.startWith(false)
.shareReplay(1)
Observable
.combineLatest(executing, enabledIf) { !$0 && $1 }
.bind(to: enabledSubject)
.disposed(by: disposeBag)
}
@discardableResult
public func execute(_ value: Input) -> Observable<Element> {
defer {
inputs.onNext(value)
}
let subject = ReplaySubject<Element>.createUnbounded()
let work = executionObservables
.map { $0.catchError { throw ActionError.underlyingError($0) } }
let error = errors
.map { Observable<Element>.error($0) }
work.amb(error)
.take(1)
.flatMap { $0 }
.subscribe(subject)
.disposed(by: disposeBag)
return subject.asObservable()
}
}
| mit | 84b62641b045184f85e7e3cc0f62ea2d | 33.650794 | 118 | 0.623683 | 5.070848 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/EtherClient/EtherServiceRequest.swift | 1 | 1084 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import APIKit
import JSONRPCKit
struct EtherServiceRequest<Batch: JSONRPCKit.Batch>: APIKit.Request {
let batch: Batch
let server: RPCServer
typealias Response = Batch.Responses
var timeoutInterval: Double
init(
for server: RPCServer,
batch: Batch,
timeoutInterval: Double = 30.0
) {
self.server = server
self.batch = batch
self.timeoutInterval = timeoutInterval
}
var baseURL: URL {
return server.rpcURL
}
var method: HTTPMethod {
return .post
}
var path: String {
return "/"
}
var parameters: Any? {
return batch.requestObject
}
func intercept(urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
urlRequest.timeoutInterval = timeoutInterval
return urlRequest
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
return try batch.responses(from: object)
}
}
| gpl-3.0 | 75039a5ccd1d15f3c0177e0beff2daf3 | 21.122449 | 86 | 0.641144 | 4.927273 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardIssuing/Sources/FeatureCardIssuingData/NetworkClients/TransactionClient.swift | 1 | 2282 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import FeatureCardIssuingDomain
import Foundation
import NetworkKit
public final class TransactionClient: TransactionClientAPI {
// MARK: - Types
private enum Path: String {
case transactions
}
// MARK: - Properties
private let networkAdapter: NetworkAdapterAPI
private let requestBuilder: RequestBuilder
// MARK: - Setup
public init(
networkAdapter: NetworkAdapterAPI,
requestBuilder: RequestBuilder
) {
self.networkAdapter = networkAdapter
self.requestBuilder = requestBuilder
}
// MARK: - API
func fetchTransactions(
_ params: TransactionsParams?
) -> AnyPublisher<[Card.Transaction], NabuNetworkError> {
let request = requestBuilder.get(
path: [Path.transactions.rawValue],
parameters: params?.urlQueryItems,
authenticated: true
)!
return networkAdapter
.perform(request: request, responseType: [Card.Transaction].self)
.eraseToAnyPublisher()
}
}
extension TransactionsParams {
var urlQueryItems: [URLQueryItem] {
let formatter = ISO8601DateFormatter()
formatter.formatOptions.formUnion([.withFractionalSeconds])
var params: [URLQueryItem] = []
params.append(.init(name: CodingKeys.cardId.rawValue, value: cardId))
params.append(.init(
name: CodingKeys.types.rawValue,
value: try? types?
.map(\.rawValue)
.encodeToString(encoding: .utf8)
))
params.append(.init(name: CodingKeys.toId.rawValue, value: toId))
params.append(.init(name: CodingKeys.fromId.rawValue, value: fromId))
if let limit = limit {
params.append(.init(name: CodingKeys.limit.rawValue, value: "\(limit)"))
}
if let fromDate = from {
params.append(.init(name: CodingKeys.from.rawValue, value: formatter.string(from: fromDate)))
}
if let toDate = to {
params.append(.init(name: CodingKeys.to.rawValue, value: formatter.string(from: toDate)))
}
return params.filter(\.value.isNotNilOrEmpty)
}
}
| lgpl-3.0 | c857a7c13247e532e3e0051fa1f386e5 | 27.5125 | 105 | 0.635686 | 4.915948 | false | false | false | false |
izeni-team/retrolux | Retrolux/Part.swift | 1 | 1486 | //
// Part.swift
// Retrolux
//
// Created by Bryan Henderson on 1/26/17.
// Copyright © 2017 Bryan. All rights reserved.
//
import UIKit
public struct Part: MultipartEncodeable {
private var mimeType: String?
private var filename: String?
private var name: String?
private var data: Data?
public init(name: String, filename: String, mimeType: String) {
self.name = name
self.filename = filename
self.mimeType = mimeType
}
public init(name: String, mimeType: String) {
self.name = name
self.mimeType = mimeType
}
public init(name: String) {
self.name = name
}
public init(_ data: Data) {
self.data = data
}
public init(_ string: String) {
self.data = string.data(using: .utf8)!
}
public static func encode(with arg: BuilderArg, using encoder: MultipartFormData) {
if let creation = arg.creation as? Part, let starting = arg.starting as? Part {
if let filename = creation.filename, let mimeType = creation.mimeType {
encoder.append(starting.data!, withName: creation.name!, fileName: filename, mimeType: mimeType)
} else if let mimeType = creation.mimeType {
encoder.append(starting.data!, withName: creation.name!, mimeType: mimeType)
} else {
encoder.append(starting.data!, withName: creation.name!)
}
}
}
}
| mit | adcb852b094497b992d8d97ae3cd2a36 | 28.117647 | 112 | 0.601347 | 4.31686 | false | false | false | false |
CUIndependent/iOS-app | CUIApp/AppDelegate.swift | 1 | 6144 | //
// AppDelegate.swift
// CUIApp
//
// Created by Michael on 2/16/15.
// Copyright (c) 2015 cuindependent. 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 "com.cuindependent.CUIApp" 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("CUIApp", 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("CUIApp.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(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// 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 | 8b42d9ae8c125aaa13bea97b0dd2434a | 54.351351 | 290 | 0.716146 | 5.742056 | false | false | false | false |
naokits/bluemix-swift-demo-ios | Pods/BMSCore/Source/Network Requests/BMSClient.swift | 2 | 3065 | /*
* Copyright 2016 IBM Corp.
* 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.
*/
/**
A singleton that serves as an entry point to Bluemix client-server communication.
*/
public class BMSClient {
// MARK: Constants
/// The southern United States Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_US_SOUTH = ".ng.bluemix.net"
/// The United Kingdom Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_UK = ".eu-gb.bluemix.net"
/// The Sydney Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_SYDNEY = ".au-syd.bluemix.net"
// MARK: Properties (API)
/// This singleton should be used for all `BMSClient` activity
public static let sharedInstance = BMSClient()
/// Specifies the base backend URL
public private(set) var bluemixAppRoute: String?
// Specifies the bluemix region
public private(set) var bluemixRegion: String?
/// Specifies the backend application id
public private(set) var bluemixAppGUID: String?
/// Specifies the default timeout (in seconds) for all BMS network requests.
public var defaultRequestTimeout: Double = 20.0
public var authorizationManager: AuthorizationManager
// MARK: Initializers
/**
The required intializer for the `BMSClient` class.
Sets the base URL for the authorization server.
- Note: The `backendAppRoute` and `backendAppGUID` parameters are not required to use the `BMSAnalytics` framework.
- parameter backendAppRoute: The base URL for the authorization server
- parameter backendAppGUID: The GUID of the Bluemix application
- parameter bluemixRegion: The region where your Bluemix application is hosted. Use one of the `BMSClient.REGION` constants.
*/
public func initializeWithBluemixAppRoute(bluemixAppRoute: String?, bluemixAppGUID: String?, bluemixRegion: String) {
self.bluemixAppRoute = bluemixAppRoute
self.bluemixAppGUID = bluemixAppGUID
self.bluemixRegion = bluemixRegion
}
private init() {
self.authorizationManager = BaseAuthorizationManager()
} // Prevent users from using BMSClient() initializer - They must use BMSClient.sharedInstance
}
| mit | c4b6f51e2b49f3c793e44833a0e88aeb | 37.910256 | 141 | 0.692916 | 4.794629 | false | false | false | false |
o15a3d4l11s2/cs193p | Calculator/Calculator/CalculatorViewController.swift | 1 | 4090 | //
// CalculatorViewController.swift
// Calculator
//
// Created by Dimitar Topalov on 9/12/15.
// Copyright (c) 2015 Dimitar Topalov. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var history: UILabel!
var userIsInTheMiddleOfTypingANumber = false
var operandStack = Array<Double>()
var displayValue: Double? {
get {
if let displayText = display.text {
if let displayNumber = NSNumberFormatter().numberFromString(displayText)?.doubleValue {
return displayNumber
}
}
return nil
}
set {
display.text = newValue != nil ? "\(newValue)" : "0"
userIsInTheMiddleOfTypingANumber = false
}
}
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
@IBAction func appendComma() {
if userIsInTheMiddleOfTypingANumber {
if (display.text!.rangeOfString(".") == nil) {
display.text = display.text! + "."
}
} else {
display.text = "0."
userIsInTheMiddleOfTypingANumber = true
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
history.text = history.text! + " \(operation) "
switch (operation) {
case "×": performOperation { $0 * $1 }
case "÷": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "−": performOperation { $1 - $0 }
case "√": performOperation { sqrt($0) }
case "sin": performOperation { sin($0) }
case "cos": performOperation { cos($0) }
case "π": performOperation { M_PI }
default: break
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
if ((displayValue) != nil) {
operandStack.append(displayValue!)
history.text = history.text! + " \(displayValue!) "
}
}
@IBAction func clear() {
operandStack.removeAll()
display.text = "0"
history.text = " "
userIsInTheMiddleOfTypingANumber = false
}
@IBAction func backspace() {
if userIsInTheMiddleOfTypingANumber {
if count(display.text!) == 1 || (count(display.text!) == 2 && display.text!.rangeOfString("-") != nil) {
display.text = "0"
userIsInTheMiddleOfTypingANumber = false
} else {
display.text = dropLast(display.text!)
}
}
}
@IBAction func changeSign() {
if userIsInTheMiddleOfTypingANumber {
if display.text!.rangeOfString("-") != nil {
display.text = dropFirst(display.text!)
} else {
display.text = "-\(display.text!)"
}
} else {
performOperation { -($0) }
}
}
private func performOperation(operation: () -> Double) {
displayValue = operation()
enter()
}
private func performOperation(operation: (Double) -> Double) {
if operandStack.count >= 1 {
history.text = history.text! + "= "
displayValue = operation(operandStack.removeLast())
enter()
}
}
private func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
history.text = history.text! + "= "
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
}
| mit | 7e432a9a84bac8f9f7abb38ece280837 | 28.80292 | 116 | 0.533186 | 5.135849 | false | false | false | false |
jjjjaren/jCode | jCode/Classes/Utilities/LogUtility.swift | 1 | 2115 | //
// LogUtility.swift
// ResearchKit-Demo-1
//
// Created by Jaren Hamblin on 8/16/16.
// Copyright © 2016 Jaren Hamblin. All rights reserved.
//
import Foundation
open class LogUtility: ILogUtility {
public weak var delegate: LogUtilityDelegate?
public static let shared: ILogUtility = LogUtility()
public static let defaultDateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
fileprivate let useBackgroundThread: Bool = true
fileprivate let dateFormatter = DateFormatter()
public init(dateFormat: String = LogUtility.defaultDateFormat) {
dateFormatter.dateFormat = dateFormat
}
// MARK: - Private Interface
open func log(_ level: LogLevel, message: [Any?], file: String, line: Int, column: Int, function: String) {
let shouldLog = delegate?.shouldLog(level: level) ?? true
guard shouldLog else { return }
let thread = Thread.isMainThread ? "Main" : "Background"
let queue = useBackgroundThread ? DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) : DispatchQueue.main
queue.sync {
let date = Date()
let dateString = self.dateFormatter.string(from: date)
var components = [String]()
components.append("\(dateString)")
components.append("[\(level.rawValue)]")
components.append("[\(thread)]")
let fileName = file.components(separatedBy: "/").last ?? ""
components.append("[\(fileName):\(line)] \(function)")
let logDetails = components.joined(separator: " ")
let logMessage = message.flatMap{$0}.map { "\($0)" }.joined(separator: " ")
delegate?.didLog(level: level, message: logMessage, file: fileName, line: line, column: column, function: function, date: date)
// Write to console
if type(of: logMessage) != NSNull.self {
let finalLog = logDetails + " > " + logMessage
print(finalLog)
}
}
}
}
public let log: ILogUtility = LogUtility.shared
| mit | 49815563b94f4951ee66af16a3e78270 | 33.655738 | 139 | 0.608798 | 4.615721 | false | false | false | false |
bengottlieb/marcel | Source/Marcel/Data+Mime.swift | 1 | 12016 | //
// Data+Mime.swift
// Marcel
//
// Created by Ben Gottlieb on 8/31/17.
// Copyright © 2017 Stand Alone, inc. All rights reserved.
//
import Foundation
extension Data {
struct Components {
let data: Data
var ranges: [Range<Data.Index>]
var count: Int { return self.ranges.count }
static let empty = Components(data: Data(), ranges: [])
subscript(_ index: Int) -> String {
let range = self.ranges[index]
var data = self.data[range]
if data.contains(string: "?utf-8?") { data = data.convertFromMangledUTF8() }
return String(data: data, encoding: .utf8) ?? String(data: data, encoding: .ascii) ?? ""
}
func index(of string: String) -> Int? {
for i in 0..<self.count {
if self[i] == string { return i }
}
return nil
}
subscript(_ range: Range<Int>) -> [String] {
var results: [String] = []
for i in range.lowerBound..<range.upperBound {
results.append(self[i])
}
return results
}
var all: [String] {
return self[0..<self.count]
}
var string: String {
return self.all.joined(separator: "\n")
}
subscript(_ range: Range<Int>) -> Data {
let lower = self.ranges[range.lowerBound].lowerBound
let upper = self.ranges[range.upperBound - 1].upperBound
return self.data[lower..<upper]
// var result = Data()
//
// for i in range.lowerBound..<range.upperBound {
// let chunk = self.ranges[i]
// result.append(self.data[chunk])
// }
//
// return result
}
subscript(_ range: Range<Int>) -> Components {
return Components(data: self.data, ranges: Array(self.ranges[range]))
}
func separated(by boundary: String) -> [Components] {
var results: [Components] = []
var start = 0
let fullBoundary = "--" + boundary
for i in 0..<self.count {
let line = self[i]
if line.hasPrefix(fullBoundary) {
if i > start { results.append(self[start..<i]) }
start = i + 1
}
}
return results
}
}
var mimeContentStart: Int? {
if count <= 4 { return nil }
return withUnsafeBytes { raw in
let upper = self.count - 4
for i in 0...upper {
let byte1 = raw[byte: i]
let byte2 = raw[byte: i + 1]
if byte1 == 10 && byte2 == 10 { return i }
if byte1 == 13 && byte2 == 13 { return i }
let byte3 = raw[byte: i + 2]
let byte4 = raw[byte: i + 3]
if byte1 == 13 && byte2 == 10 && byte3 == 13 && byte4 == 10 { return i }
}
return nil
}
}
func separated(by sep: String) -> [Data] {
return withUnsafeBytes { raw in
var results: [Data] = []
let sepBytes = Data(bytes: [UInt8](sep.utf8), count: sep.count)
let first = sepBytes.first
let upper = self.count - sepBytes.count
var last: Int?
for i in 0...upper {
let byte = raw[byte: i]
if byte == first, self[i..<(i + sep.count)] == sepBytes {
if let prev = last {
let chunk = self[prev..<i]
last = i + sep.count
results.append(chunk)
} else {
last = i + sep.count
}
}
}
if let prev = last {
let chunk = self[prev...]
results.append(chunk)
}
return results
}
}
func components() -> Components? {
var ranges: [Range<Data.Index>] = []
var i = 0
let count = self.count
var checkThese = ["\n", "\r"]
if self.contains(string: "\r\n") { checkThese = ["\r\n"] }
while i < count {
let index = self.firstIndex(of: checkThese, startingAt: i) ?? count
ranges.append(i..<index)
i = index + 1
if i < self.count, self[i - 1] != 10, self[i] == 10 { i += 1}
}
if ranges.count < 2 { return nil }
return Components(data: self, ranges: ranges)
}
func contains(string: String) -> Bool { return self.firstIndex(of: [string]) != nil }
func firstIndex(of strings: [String], startingAt: Int = 0) -> Int? {
precondition(strings.count > 0)
let byteArrays = strings.map { [UInt8]($0.utf8) }
if self.count < byteArrays.first!.count { return nil }
return withUnsafeBytes { raw in
for i in startingAt..<(self.count - byteArrays.first!.count) {
for bytes in byteArrays {
if raw[byte: i] == bytes[0] {
var valid = true
for j in 1..<bytes.count {
if raw[byte: i + j] != bytes[j] {
valid = false
break
}
}
if valid { return i }
}
}
}
return nil
}
}
var usesCRLF: Bool {
return withUnsafeBytes { raw in
let length = self.count
let cr = UInt8(firstCharacterOf: "\r")
let newline = UInt8(firstCharacterOf: "\n")
for i in 0..<(length - 1) {
let byte = raw[byte: i]
if byte == cr {
return raw[byte: i + 1] == newline
} else if byte == newline {
return false
}
}
return false
}
}
func unwrapFoldedHeadersAndStripOutCarriageReturns() -> Data {
return withUnsafeBytes { raw in
let length = self.count
let output = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
var count = 0, i = 0
let space = UInt8(firstCharacterOf: " ")
let tab = UInt8(firstCharacterOf: "\t")
let newline = UInt8(firstCharacterOf: "\n")
while i < length {
if raw[byte: i] == newline, (raw[byte: i + 1] == space || raw[byte: i + 1] == tab) {
i += 2
} else {
output[count] = raw[byte: i]
count += 1
}
i += 1
}
return Data(bytes: output, count: count)
}
}
func unwrapTabs() -> Data {
return withUnsafeBytes { raw in
var count = 0, i = 0
let length = self.count
let output = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
let newline = UInt8(firstCharacterOf: "\n")
let cr = UInt8(firstCharacterOf: "\r")
let space = UInt8(firstCharacterOf: " ")
let tab = UInt8(firstCharacterOf: "\t")
while i < length {
var isNewline = false
if raw[byte: i] == cr { //if it's a newline, check for CRLF and either remove the CR or replace it with an LF
// if i == length - 1 { break }
// if raw[byte: i + 1] == newline { i += 1 }
isNewline = true
} else if raw[byte: i] == newline {
isNewline = true
}
output[count] = raw[byte: i]
count += 1
i += 1
if i < length, isNewline, raw[byte: i] == space || raw[byte: i] == tab {
count -= 1
i += 1
}
}
return Data(bytes: output, count: count)
}
}
func unwrap7BitLineBreaks() -> Data {
return withUnsafeBytes { raw in
var count = 0, i = 0
let length = self.count
let output = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
let newline = UInt8(firstCharacterOf: "\n")
let equals = UInt8(firstCharacterOf: "=")
let cr = UInt8(firstCharacterOf: "\r")
let questionMark = UInt8(firstCharacterOf: "?")
while i < length {
if raw[byte: i] == cr || raw[byte: i] == newline { //if it's a newline, check for CRLF and either remove the CR or replace it with an LF
if i > 1 && raw[byte: i - 1] == equals && raw[byte: i - 2] != equals && raw[byte: i - 2] != questionMark {
count -= 1
i += 1
continue
}
}
output[count] = raw[byte: i]
count += 1
i += 1
}
return Data(bytes: output, count: count)
}
}
func convertFromMangledUTF8() -> Data {
/*
if we look at three bytes, and ignore any runs longer than 2, then we miss stuff like References=20=2F=20A=20Case, which should be "References / A Case", but the =20A is throwing it for a loop
if we look at only two bytes, then we catch that, but we miss URL parameters such as &ct=1507640404515657
we're going to look at the next 8 characters. If they're all digits, we'll assume this is some sort of parameter and not convert it.
*/
return self.convertCheckingByteRuns(maxLength: 8)
}
func convertCheckingByteRuns(maxLength: Int) -> Data {
return withUnsafeBytes { raw in
var count = 0, i = 0
let length = self.count
let output = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
let sentinel = UInt8(firstCharacterOf: "=")
let newline = UInt8(firstCharacterOf: "\n")
let cr = UInt8(firstCharacterOf: "\r")
let questionMark = UInt8(firstCharacterOf: "?")
let space = UInt8(firstCharacterOf: " ")
let tab = UInt8(firstCharacterOf: "\t")
var lastWasSentinel = false
let backSlash = UInt8(firstCharacterOf: "\\")
let u = UInt8(firstCharacterOf: "u")
let three = UInt8(firstCharacterOf: "3")
let d = UInt8(firstCharacterOf: "d")
let D = UInt8(firstCharacterOf: "D")
let equals = UInt8(firstCharacterOf: "=")
while i < length {
let pointingToNewline = raw[byte: i] == newline || raw[byte: i] == cr
if raw[byte: i] == backSlash, raw[byte: i + 1] == u, let bytes = raw.nextHexCharacters(from: i + 2, length: length), let chr = UInt32(hexBytes: bytes), let scalar = UnicodeScalar(chr) {
i += bytes.count + 2
let repl = String(Character(scalar)).utf8
for byte in repl {
output[count] = byte
count += 1
}
continue
} else if i < (length - 1), raw[byte: i] == sentinel, i > 0, (raw[byte: i - 1] != questionMark || raw[byte: i + 1] != newline) { //currently at an = character
if lastWasSentinel {
lastWasSentinel = false
output[count] = raw[byte: i]
count += 1
i += 1
continue
} else {
lastWasSentinel = true
}
} else if lastWasSentinel { //last character was an =
lastWasSentinel = false
if pointingToNewline, i < (length - 1), i > 1, raw[byte: i - 2] != sentinel { //newline. Might be a hard wrap
count -= 1
while (raw[byte: i] == newline || raw[byte: i] == cr), i < length {
i += 1
}
continue
} else if raw[byte: i] == three && (raw[byte: i + 1] == d || raw[byte: i + 1] == D) {
output[count - 1] = equals
i += 2
continue
} else if let bytes = raw.nextHexCharacters(from: i, limitedTo: maxLength, length: length), bytes.count >= 2, bytes.count < 6, let escaped = UInt8(bytes: Array(bytes[0..<2])) {
var translated = [escaped]
var additionalOffset = 2
while (i + additionalOffset + 2) < length {
if raw[byte: i + additionalOffset] != sentinel { break }
if raw[byte: i + additionalOffset + 1] == newline {
additionalOffset += 2
continue
}
guard let nextBytes = raw.nextHexCharacters(from: i + additionalOffset + 1, limitedTo: 2, length: length), nextBytes.count == 2, let escaped = UInt8(bytes: nextBytes) else { break }
translated.append(escaped)
additionalOffset += nextBytes.count + 1
}
count -= 1
for byte in translated {
output[count] = byte
count += 1
}
i += additionalOffset
continue
}
} else if pointingToNewline, i < (length - 1), (raw[byte: i + 1] == space || raw[byte: i + 1] == tab) {
i += 2
continue
}
output[count] = raw[byte: i]
count += 1
i += 1
// if String(data: Data(bytes: output, count: count), encoding: .utf8) == nil {
// print("Bad string")
// return Data(bytes: output, count: count)
// }
}
return Data(bytes: output, count: count)
}
}
}
extension UnsafeRawBufferPointer {
subscript(byte byte: Int) -> UInt8 {
load(fromByteOffset: byte, as: UInt8.self)
}
func nextHexCharacters(from startIndex: Int, limitedTo: Int = 4, length: Int) -> [UInt8]? {
var results: [UInt8] = []
var index = startIndex
let max = Swift.min(startIndex + limitedTo, length)
while index < max {
guard let chr = UInt8(asciiChar: self[index]) else { break }
results.append(chr)
index += 1
}
return results
}
}
| mit | 9439b2fc63e4117fa94348c6f5ddae44 | 28.666667 | 201 | 0.571119 | 3.338427 | false | false | false | false |
fuzza/SwiftyJanet | Tests/SwiftyJanetTests/JanetTestsSendDeferred.swift | 1 | 2356 | import SwiftyJanet
import RxSwift
import RxTest
import Nimble
import XCTest
class JanetTestsSendDeferred: JanetTestCase<String> {
func test_success_runsOnSubscribeAndCompletes() {
// Act
sendDeferred(action: "test_action")
// Assert
observer.verifySuccessSequenceCompleted(action: "test_action")
}
func test_failure_runsOnSubscribeAndCompletes() {
// Act
sendDeferred(action: "test_action")
// Assert
observer.verifySuccessSequenceCompleted(action: "test_action")
}
func test_skipsOtherActions() {
// Arrange
service.sendStub = { callback, holder in
callback?.stubStart("another_action")
callback?.stubProgress(22, 18.4)
callback?.stubSuccessSequence(holder: holder)
}
// Act
sendDeferred(action: "test_action")
// Assert
observer.verifySuccessSequenceCompleted(action: "test_action")
}
func test_retrievesModifiedAction() {
// Arrange
service.sendStub = { callback, holder in
callback?.stubSuccess(holder: holder, modified: "modified_action")
}
// Act
sendDeferred(action: "test_action")
// Assert
observer.verifySuccessSequenceCompleted(action: "modified_action")
}
func test_assertsIfServiceNotFound() {
let pipe = janet.createPipe(of: Double.self)
expect(pipe.sendDeferred(4.44).subscribe().disposed(by:self.bag))
.to(throwAssertion())
}
func test_subscribesOnDefaultScheduler() {
// Arrange
let pipe = self.providePipe(janet: janet, scheduler: scheduler)
// Act
pipe.sendDeferred("test_action").subscribe(observer).disposed(by:self.bag)
scheduler.start()
// Asser
observer.verifySuccessSequenceCompleted(action: "test_action", time: 1)
}
func test_mirrorsEventsToPipeline() {
// Arrange
let pipelineObserver = scheduler.createObserver(ActionState<String>.self)
actionPipe.observe().subscribe(pipelineObserver).disposed(by: bag)
// Act
sendDeferred(action: "mirror_action")
// Assert
observer.verifySuccessSequenceCompleted(action: "mirror_action")
pipelineObserver.verifySuccessSequence(action: "mirror_action")
}
// MARK: Private helpers
private func sendDeferred(action: String) {
actionPipe.sendDeferred(action).subscribe(observer).disposed(by: bag)
}
}
| mit | 38ee111578a7f2d987cca30ec8e2af9f | 25.47191 | 78 | 0.690577 | 4.126095 | false | true | false | false |
vanshg/MacAssistant | Pods/SwiftProtobuf/Sources/SwiftProtobuf/HashVisitor.swift | 3 | 10115 | // Sources/SwiftProtobuf/HashVisitor.swift - Hashing support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Hashing is basically a serialization problem, so we can leverage the
/// generated traversal methods for that.
///
// -----------------------------------------------------------------------------
import Foundation
private let i_2166136261 = Int(bitPattern: 2166136261)
private let i_16777619 = Int(16777619)
/// Computes the hash of a message by visiting its fields recursively.
///
/// Note that because this visits every field, it has the potential to be slow
/// for large or deeply nested messages. Users who need to use such messages as
/// dictionary keys or set members can use a wrapper struct around the message
/// and use a custom Hashable implementation that looks at the subset of the
/// message fields they want to include.
internal struct HashVisitor: Visitor {
#if swift(>=4.2)
internal private(set) var hasher: Hasher
#else // swift(>=4.2)
// Roughly based on FNV hash: http://tools.ietf.org/html/draft-eastlake-fnv-03
private(set) var hashValue = i_2166136261
private mutating func mix(_ hash: Int) {
hashValue = (hashValue ^ hash) &* i_16777619
}
private mutating func mixMap<K, V: Hashable>(map: Dictionary<K,V>) {
var mapHash = 0
for (k, v) in map {
// Note: This calculation cannot depend on the order of the items.
mapHash = mapHash &+ (k.hashValue ^ v.hashValue)
}
mix(mapHash)
}
#endif // swift(>=4.2)
#if swift(>=4.2)
init(_ hasher: Hasher) {
self.hasher = hasher
}
#else
init() {}
#endif
mutating func visitUnknown(bytes: Data) throws {
#if swift(>=4.2)
hasher.combine(bytes)
#else
mix(bytes.hashValue)
#endif
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularEnumField<E: Enum>(value: E,
fieldNumber: Int) {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) {
#if swift(>=4.2)
hasher.combine(fieldNumber)
value.hash(into: &hasher)
#else
mix(fieldNumber)
mix(value.hashValue)
#endif
}
mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
for v in value {
v.hash(into: &hasher)
}
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
for v in value {
v.hash(into: &hasher)
}
#else
mix(fieldNumber)
for v in value {
mix(v.hashValue)
}
#endif
}
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mixMap(map: value)
#endif
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws where ValueType.RawValue == Int {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mixMap(map: value)
#endif
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
#if swift(>=4.2)
hasher.combine(fieldNumber)
hasher.combine(value)
#else
mix(fieldNumber)
mixMap(map: value)
#endif
}
}
| mit | e53c9f13a5172aeb79864502ec43dde5 | 23.791667 | 92 | 0.620564 | 3.96978 | false | false | false | false |
el-hoshino/NotAutoLayout | Playground.playground/Sources/ReplyView.swift | 1 | 1747 | import UIKit
import NotAutoLayout
private let padding: CGFloat = 5
public class ReplyView: UIView {
private let replyView: UITextView
private let replyPlaceholderText = "Reply to me!"
public var contents: String? {
get {
return self.replyView.text
}
set {
self.setReply(with: newValue)
}
}
public override init(frame: CGRect) {
self.replyView = UITextView()
super.init(frame: frame)
self.setupReplyView()
}
public convenience init() {
self.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
self.placeReplyView()
}
}
extension ReplyView {
private func setupReplyView() {
let view = self.replyView
view.isEditable = false
view.isSelectable = false
view.clipsToBounds = true
view.textContainerInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
view.font = .systemFont(ofSize: UIFont.systemFontSize)
view.textColor = .darkGray
view.backgroundColor = UIColor(red: 224.0 / 255.0, green: 231.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
self.setReply(with: nil)
self.addSubview(view)
}
}
extension ReplyView {
private func placeReplyView() {
self.nal.layout(self.replyView, by: { $0
.setFrame(by: { $0.frame })
.addingProcess(by: { (frame, parameters) in
parameters.targetView.layer.cornerRadius = (frame.height / 2).cgValue
})
})
}
}
extension ReplyView {
private func setReply(with text: String?) {
switch text {
case let reply?:
self.replyView.text = reply
case nil:
self.replyView.text = self.replyPlaceholderText
}
}
}
| apache-2.0 | 0b8fc621df2fe900271cfa98de40bbb2 | 17.585106 | 105 | 0.682313 | 3.327619 | false | false | false | false |
CatchChat/Yep | Yep/Services/YepAudioService.swift | 1 | 11240 | //
// YepAudioService.swift
// Yep
//
// Created by kevinzhow on 15/3/31.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import AVFoundation
import AudioToolbox
import YepKit
import Proposer
extension AVPlayer {
var yep_playing: Bool {
if (rate != 0 && error == nil) {
return true
}
return false
}
}
final class YepAudioService: NSObject {
static let sharedManager = YepAudioService()
var shouldIgnoreStart = false
let queue = dispatch_queue_create("YepAudioService", DISPATCH_QUEUE_SERIAL)
var audioFileURL: NSURL?
var audioRecorder: AVAudioRecorder?
var audioPlayer: AVAudioPlayer?
var onlineAudioPlayer: AVPlayer?
var audioPlayCurrentTime: NSTimeInterval {
if let audioPlayer = audioPlayer {
return audioPlayer.currentTime
}
return 0
}
var aduioOnlinePlayCurrentTime: CMTime {
if let onlineAudioPlayerItem = onlineAudioPlayer?.currentItem {
return onlineAudioPlayerItem.currentTime()
}
return CMTime()
}
func prepareAudioRecorderWithFileURL(fileURL: NSURL, audioRecorderDelegate: AVAudioRecorderDelegate) {
audioFileURL = fileURL
let settings: [String: AnyObject] = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
AVEncoderBitRateKey : 64000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100.0
]
do {
let audioRecorder = try AVAudioRecorder(URL: fileURL, settings: settings)
audioRecorder.delegate = audioRecorderDelegate
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord() // creates/overwrites the file at soundFileURL
self.audioRecorder = audioRecorder
} catch let error {
self.audioRecorder = nil
println("create AVAudioRecorder error: \(error)")
}
}
var recordTimeoutAction: (() -> Void)?
var checkRecordTimeoutTimer: NSTimer?
func startCheckRecordTimeoutTimer() {
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(YepAudioService.checkRecordTimeout(_:)), userInfo: nil, repeats: true)
checkRecordTimeoutTimer = timer
timer.fire()
}
func checkRecordTimeout(timer: NSTimer) {
if audioRecorder?.currentTime > YepConfig.AudioRecord.longestDuration {
endRecord()
recordTimeoutAction?()
recordTimeoutAction = nil
}
}
func beginRecordWithFileURL(fileURL: NSURL, audioRecorderDelegate: AVAudioRecorderDelegate) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord)
} catch let error {
println("beginRecordWithFileURL setCategory failed: \(error)")
}
//dispatch_async(queue) {
do {
//AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker,error: nil)
//AVAudioSession.sharedInstance().setActive(true, error: nil)
proposeToAccess(.Microphone, agreed: {
self.prepareAudioRecorderWithFileURL(fileURL, audioRecorderDelegate: audioRecorderDelegate)
if let audioRecorder = self.audioRecorder {
if (audioRecorder.recording){
audioRecorder.stop()
} else {
if !self.shouldIgnoreStart {
audioRecorder.record()
println("audio record did begin")
}
}
}
}, rejected: {
if let
appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
viewController = appDelegate.window?.rootViewController {
viewController.alertCanNotAccessMicrophone()
}
})
}
}
func endRecord() {
if let audioRecorder = self.audioRecorder {
if audioRecorder.recording {
audioRecorder.stop()
}
}
dispatch_async(queue) {
//AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker,error: nil)
let _ = try? AVAudioSession.sharedInstance().setActive(false, withOptions: AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation)
}
self.checkRecordTimeoutTimer?.invalidate()
self.checkRecordTimeoutTimer = nil
}
// MARK: Audio Player
enum PlayingItem {
case MessageType(Message)
case FeedAudioType(FeedAudio)
}
var playingItem: PlayingItem?
var playingMessage: Message? {
guard let playingItem = playingItem else { return nil }
if case .MessageType(let message) = playingItem {
return message
}
return nil
}
var playingFeedAudio: FeedAudio? {
guard let playingItem = playingItem else { return nil }
if case .FeedAudioType(let feedAUdio) = playingItem {
return feedAUdio
}
return nil
}
var playbackTimer: NSTimer? {
didSet {
if let oldPlaybackTimer = oldValue {
oldPlaybackTimer.invalidate()
}
}
}
func playAudioWithMessage(message: Message, beginFromTime time: NSTimeInterval, delegate: AVAudioPlayerDelegate, success: () -> Void) {
if AVAudioSession.sharedInstance().category == AVAudioSessionCategoryRecord {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error {
println("playAudioWithMessage setCategory failed: \(error)")
}
}
if let audioFileURL = message.audioFileURL {
do {
let audioPlayer = try AVAudioPlayer(contentsOfURL: audioFileURL)
self.audioPlayer = audioPlayer
audioPlayer.delegate = delegate
audioPlayer.prepareToPlay()
audioPlayer.currentTime = time
if audioPlayer.play() {
println("do play audio")
playingItem = .MessageType(message)
UIDevice.currentDevice().proximityMonitoringEnabled = true
if !message.mediaPlayed {
if let realm = message.realm {
let _ = try? realm.write {
message.mediaPlayed = true
}
}
}
success()
}
} catch let error {
println("play audio error: \(error)")
}
} else {
println("please wait for download") // TODO: Download audio message, check first
}
}
func playAudioWithFeedAudio(feedAudio: FeedAudio, beginFromTime time: NSTimeInterval, delegate: AVAudioPlayerDelegate, success: () -> Void) {
if AVAudioSession.sharedInstance().category == AVAudioSessionCategoryRecord {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error {
println("playAudioWithMessage setCategory failed: \(error)")
}
}
if let audioFileURL = feedAudio.audioFileURL {
do {
let audioPlayer = try AVAudioPlayer(contentsOfURL: audioFileURL)
self.audioPlayer = audioPlayer
audioPlayer.delegate = delegate
audioPlayer.prepareToPlay()
audioPlayer.currentTime = time
if audioPlayer.play() {
println("do play audio")
playingItem = .FeedAudioType(feedAudio)
success()
}
} catch let error {
println("play audio error: \(error)")
}
} else {
println("please wait for download") // TODO: Download feed audio, check first
}
}
func playOnlineAudioWithFeedAudio(feedAudio: FeedAudio, beginFromTime time: NSTimeInterval, delegate: AVAudioPlayerDelegate, success: () -> Void) {
guard let URL = NSURL(string: feedAudio.URLString) else {
return
}
if AVAudioSession.sharedInstance().category == AVAudioSessionCategoryRecord {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error {
println("playAudioWithMessage setCategory failed: \(error)")
}
}
let playerItem = AVPlayerItem(URL: URL)
let player = AVPlayer(playerItem: playerItem)
player.rate = 1.0
let time = CMTime(seconds: time, preferredTimescale: 1)
playerItem.seekToTime(time)
player.play()
playingItem = .FeedAudioType(feedAudio)
success()
println("playOnlineAudioWithFeedAudio")
self.onlineAudioPlayer = player
}
func tryNotifyOthersOnDeactivation() {
// playback 会导致从音乐 App 进来的时候停止音乐,所以需要重置回去
dispatch_async(queue) {
let _ = try? AVAudioSession.sharedInstance().setActive(false, withOptions: AVAudioSessionSetActiveOptions.NotifyOthersOnDeactivation)
}
}
func resetToDefault() {
tryNotifyOthersOnDeactivation()
// hack, wait for all observers of AVPlayerItemDidPlayToEndTimeNotification
// to handle feedAudioDidFinishPlaying (check playingFeedAudio need playingItem)
doInNextRunLoop { [weak self] in
self?.playingItem = nil
}
}
// MARK: Proximity
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YepAudioService.proximityStateChanged), name: UIDeviceProximityStateDidChangeNotification, object: UIDevice.currentDevice())
}
func proximityStateChanged() {
if UIDevice.currentDevice().proximityState {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch let error {
println("proximityStateChanged setCategory failed: \(error)")
}
} else {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error {
println("proximityStateChanged setCategory failed: \(error)")
}
}
}
}
| mit | f540c24cadde9d438a7ec408fe5d2c0f | 30.169916 | 207 | 0.592136 | 5.911252 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/EditorStickerContentView.swift | 1 | 10724 | //
// EditorStickerContentView.swift
// HXPHPicker
//
// Created by Slience on 2021/7/20.
//
import UIKit
#if canImport(Kingfisher)
import Kingfisher
#endif
struct EditorStickerText {
let image: UIImage
let text: String
let textColor: UIColor
let showBackgroud: Bool
}
struct EditorStickerItem {
let image: UIImage
let imageData: Data?
let text: EditorStickerText?
let music: VideoEditorMusic?
var frame: CGRect {
var width = UIScreen.main.bounds.width - 80
if music != nil {
let height: CGFloat = 60
width = UIScreen.main.bounds.width - 40
return CGRect(origin: .zero, size: CGSize(width: width, height: height))
}
if text != nil {
width = UIScreen.main.bounds.width - 30
}
let height = width
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
let imageWidth = image.width
var imageHeight = image.height
if imageWidth > width {
imageHeight = width / imageWidth * imageHeight
}
if imageHeight > height {
itemWidth = height / image.height * imageWidth
itemHeight = height
}else {
if imageWidth > width {
itemWidth = width
}else {
itemWidth = imageWidth
}
itemHeight = imageHeight
}
return CGRect(x: 0, y: 0, width: itemWidth, height: itemHeight)
}
init(image: UIImage,
imageData: Data?,
text: EditorStickerText?,
music: VideoEditorMusic? = nil,
videoSize: CGSize? = nil) {
self.image = image
self.imageData = imageData
self.text = text
self.music = music
}
}
extension EditorStickerText: Codable {
enum CodingKeys: CodingKey {
case image
case text
case textColor
case showBackgroud
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let imageData = try container.decode(Data.self, forKey: .image)
image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(imageData) as! UIImage
text = try container.decode(String.self, forKey: .text)
let colorData = try container.decode(Data.self, forKey: .textColor)
textColor = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(colorData) as! UIColor
showBackgroud = try container.decode(Bool.self, forKey: .showBackgroud)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 11.0, *) {
let imageData = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(imageData, forKey: .image)
let colorData = try NSKeyedArchiver.archivedData(withRootObject: textColor, requiringSecureCoding: false)
try container.encode(colorData, forKey: .textColor)
} else {
let imageData = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(imageData, forKey: .image)
let colorData = NSKeyedArchiver.archivedData(withRootObject: textColor)
try container.encode(colorData, forKey: .textColor)
}
try container.encode(text, forKey: .text)
try container.encode(showBackgroud, forKey: .showBackgroud)
}
}
extension EditorStickerItem: Codable {
enum CodingKeys: CodingKey {
case image
case imageData
case text
case music
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let imageData = try container.decode(Data.self, forKey: .image)
var image = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(imageData) as! UIImage
if let data = try container.decodeIfPresent(Data.self, forKey: .imageData) {
self.imageData = data
#if canImport(Kingfisher)
if data.kf.imageFormat == .GIF {
if let gifImage = DefaultImageProcessor.default.process(item: .data(imageData), options: .init([])) {
image = gifImage
}
}
#endif
}else {
self.imageData = nil
}
self.image = image
text = try container.decodeIfPresent(EditorStickerText.self, forKey: .text)
music = try container.decodeIfPresent(VideoEditorMusic.self, forKey: .music)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 11.0, *) {
let imageData = try NSKeyedArchiver.archivedData(withRootObject: image, requiringSecureCoding: false)
try container.encode(imageData, forKey: .image)
} else {
let imageData = NSKeyedArchiver.archivedData(withRootObject: image)
try container.encode(imageData, forKey: .image)
}
if let data = imageData {
try container.encodeIfPresent(data, forKey: .imageData)
}else {
#if canImport(Kingfisher)
if let data = image.kf.gifRepresentation() {
try container.encodeIfPresent(data, forKey: .imageData)
}
#endif
}
try container.encodeIfPresent(text, forKey: .text)
try container.encodeIfPresent(music, forKey: .music)
}
}
class EditorStickerContentView: UIView {
lazy var animationView: VideoEditorMusicAnimationView = {
let view = VideoEditorMusicAnimationView(hexColor: "#ffffff")
view.startAnimation()
return view
}()
lazy var textLayer: CATextLayer = {
let textLayer = CATextLayer()
let fontSize: CGFloat = 25
let font = UIFont.boldSystemFont(ofSize: fontSize)
textLayer.font = font
textLayer.fontSize = fontSize
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.truncationMode = .end
textLayer.contentsScale = UIScreen.main.scale
textLayer.alignmentMode = .left
textLayer.isWrapped = true
return textLayer
}()
lazy var imageView: ImageView = {
let view = ImageView()
if let imageData = item.imageData {
view.setImageData(imageData)
}else {
view.image = item.image
}
return view
}()
var scale: CGFloat = 1
var item: EditorStickerItem
weak var timer: Timer?
init(item: EditorStickerItem) {
self.item = item
super.init(frame: item.frame)
if item.music != nil {
addSubview(animationView)
layer.addSublayer(textLayer)
CATransaction.begin()
CATransaction.setDisableActions(true)
if let player = PhotoManager.shared.audioPlayer {
textLayer.string = item.music?.lyric(atTime: player.currentTime)?.lyric
}else {
textLayer.string = item.music?.lyric(atTime: 0)?.lyric
}
CATransaction.commit()
updateText()
startTimer()
}else {
if item.text != nil {
imageView.layer.shadowColor = UIColor.black.withAlphaComponent(0.8).cgColor
}
addSubview(imageView)
}
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
func startTimer() {
invalidateTimer()
let timer = Timer.scheduledTimer(
withTimeInterval: 0.5,
repeats: true, block: { [weak self] timer in
if let player = PhotoManager.shared.audioPlayer {
let lyric = self?.item.music?.lyric(atTime: player.currentTime)
if let str = self?.textLayer.string as? String,
let lyricStr = lyric?.lyric,
str == lyricStr {
return
}
CATransaction.begin()
CATransaction.setDisableActions(true)
self?.textLayer.string = lyric?.lyric
self?.updateText()
CATransaction.commit()
}else {
timer.invalidate()
self?.timer = nil
}
})
self.timer = timer
}
func invalidateTimer() {
self.timer?.invalidate()
self.timer = nil
}
func update(item: EditorStickerItem) {
self.item = item
if !frame.equalTo(item.frame) {
frame = item.frame
}
if imageView.image != item.image {
imageView.image = item.image
}
}
func updateText() {
if var height = (textLayer.string as? String)?.height(
ofFont: textLayer.font as! UIFont, maxWidth: width * scale
) {
height = min(100, height)
if textLayer.frame.height != height {
textLayer.frame = CGRect(origin: .zero, size: CGSize(width: width * scale, height: height))
}
}
animationView.frame = CGRect(x: 2, y: -23, width: 20, height: 15)
}
override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
gestureRecognizer.delegate = self
super.addGestureRecognizer(gestureRecognizer)
}
override func layoutSubviews() {
super.layoutSubviews()
if item.music != nil {
updateText()
}else {
imageView.frame = bounds
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// deinit {
// print("deinit: \(self)")
// }
}
extension EditorStickerContentView: UIGestureRecognizerDelegate {
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
if otherGestureRecognizer.delegate is PhotoEditorViewController ||
otherGestureRecognizer.delegate is VideoEditorViewController {
return false
}
if otherGestureRecognizer is UITapGestureRecognizer || gestureRecognizer is UITapGestureRecognizer {
return true
}
if let view = gestureRecognizer.view, view == self,
let otherView = otherGestureRecognizer.view, otherView == self {
return true
}
return false
}
}
| mit | f4488db1966daf31f19fb4e1993068b3 | 34.866221 | 117 | 0.596512 | 5.099382 | false | false | false | false |
darina/omim | iphone/Maps/UI/Downloader/SearchMapsDataSource.swift | 5 | 1715 | class SearchMapsDataSource {
typealias SearchCallback = (Bool) -> Void
fileprivate var searchResults: [MapSearchResult] = []
fileprivate var searchId = 0
fileprivate var onUpdate: SearchCallback?
}
extension SearchMapsDataSource: IDownloaderDataSource {
var isEmpty: Bool {
searchResults.isEmpty
}
var title: String {
""
}
var isRoot: Bool {
true
}
var isSearching: Bool {
true
}
func numberOfSections() -> Int {
1
}
func parentAttributes() -> MapNodeAttributes {
return Storage.shared().attributesForRoot()
}
func numberOfItems(in section: Int) -> Int {
searchResults.count
}
func item(at indexPath: IndexPath) -> MapNodeAttributes {
Storage.shared().attributes(forCountry: searchResults[indexPath.item].countryId)
}
func matchedName(at indexPath: IndexPath) -> String? {
searchResults[indexPath.item].matchedName
}
func title(for section: Int) -> String {
L("downloader_search_results")
}
func indexTitles() -> [String]? {
nil
}
func dataSourceFor(_ childId: String) -> IDownloaderDataSource {
AvailableMapsDataSource(childId)
}
func reload(_ completion: () -> Void) {
completion()
}
func search(_ query: String, locale: String, update: @escaping SearchCallback) {
searchId += 1
onUpdate = update
FrameworkHelper.search(inDownloader: query, inputLocale: locale) { [weak self, searchId] (results, finished) in
if searchId != self?.searchId {
return
}
self?.searchResults = results
if results.count > 0 || finished {
self?.onUpdate?(finished)
}
}
}
func cancelSearch() {
searchResults = []
onUpdate = nil
}
}
| apache-2.0 | c9da38cc4ebec14cca8fdb17a1904a92 | 20.4375 | 115 | 0.658892 | 4.255583 | false | false | false | false |
codefellows/sea-b19-ios | Projects/Week5 Region Monitoring Demo/mapkitdemo/ViewController.swift | 1 | 7825 | //
// ViewController.swift
// mapkitdemo
//
// Created by Bradley Johnson on 8/18/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController,UITextFieldDelegate,MKMapViewDelegate,CLLocationManagerDelegate {
@IBOutlet weak var mapVIew: MKMapView!
@IBOutlet weak var latFIeld: UITextField!
@IBOutlet weak var longField: UITextField!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
switch CLLocationManager.authorizationStatus() as CLAuthorizationStatus {
case .Authorized:
println("authorized, great!")
//this status is for always requesting
self.mapVIew.showsUserLocation = true
//self.locationManager.startUpdatingLocation()
case .NotDetermined:
println("must be firsh launch")
self.locationManager.requestAlwaysAuthorization()
case .Restricted:
println("youre out of luck, sorry bro")
case .AuthorizedWhenInUse:
println("authorized for when in use")
//when were authorized, show user location and start updating locations
self.mapVIew.showsUserLocation = true
//this one is for the high power, standard location services
//self.locationManager.startUpdatingLocation()
//this is the significant location monitoring, will only fire when location changes > 500 meters
case .Denied:
println("fire an alertview, pleading with the user about turning it on")
}
//creating a region at the start
// var location = CLLocationCoordinate2D(latitude: 47.6, longitude: -122.3)
// self.mapVIew.region = MKCoordinateRegionMakeWithDistance(location, 1000, 1000)
self.latFIeld.delegate = self
self.longField.delegate = self
var ground = CLLocationCoordinate2D(latitude: 40.6892, longitude: -74.0444)
var eye = CLLocationCoordinate2D(latitude: 40.6892, longitude: -74.0442)
var camera = MKMapCamera(lookingAtCenterCoordinate: ground, fromEyeCoordinate: eye, eyeAltitude: 50)
self.mapVIew.camera = camera
//setup our longpress gesture recognizer
var longPress = UILongPressGestureRecognizer(target: self, action: "mapPressed:")
self.mapVIew.addGestureRecognizer(longPress)
self.mapVIew.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
func mapPressed(sender : UILongPressGestureRecognizer) {
switch sender.state {
case .Began:
println("Began")
//figuring out where they touched on the mapview
var touchPoint = sender.locationInView(self.mapVIew)
var touchCoordinate = self.mapVIew.convertPoint(touchPoint, toCoordinateFromView: self.mapVIew)
//setting up our pin
var annotation = MKPointAnnotation()
annotation.coordinate = touchCoordinate
annotation.title = "Add Reminder"
self.mapVIew.addAnnotation(annotation)
case .Changed:
println("Changed")
case .Ended:
println("Ended")
default:
println("default")
}
}
func mapPanned(sender : UIPanGestureRecognizer) {
switch sender.state {
case .Changed:
var point = sender.translationInView(self.view)
println(point)
default:
println("default")
}
}
//MARK: CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .Authorized:
println("they said yes")
self.mapVIew.showsUserLocation = true
//self.locationManager.startUpdatingLocation()
case .Denied:
println("this is terrible")
case .AuthorizedWhenInUse:
println("they said yes, when in use")
self.mapVIew.showsUserLocation = true
default:
println("auth did change, default")
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("location did update")
if let location = locations.last as? CLLocation {
println(location.coordinate.latitude)
println(location.coordinate.longitude)
}
}
//MARK: MKMapViewDelegate
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
//very similar to tableview cell for row at index path
//first we will try to dequeue an old one
if let annotV = mapVIew.dequeueReusableAnnotationViewWithIdentifier("Pin") as? MKPinAnnotationView {
//if we didnt get one back, create a new one with identifier
self.setupAnnotationView(annotV)
return annotV
}
else {
var annotV = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin")
self.setupAnnotationView(annotV)
return annotV
}
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
//tells us which annotation was clicked
var annotation = view.annotation
var geoRegion = CLCircularRegion(center: annotation.coordinate, radius: 200, identifier: "Reminder")
self.locationManager.startMonitoringForRegion(geoRegion)
println(annotation.coordinate.latitude)
println(annotation.coordinate.longitude)
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
println("did enter region")
var notification = UILocalNotification()
notification.alertBody = "Hey you entered a region!"
notification.alertAction = "Click here!"
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
println("did exit region")
}
func setupAnnotationView(annotationView : MKPinAnnotationView) {
annotationView.animatesDrop = true
annotationView.canShowCallout = true
var rightButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton
annotationView.rightCalloutAccessoryView = rightButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func goPressed(sender: AnyObject) {
var latString = NSString(string: self.latFIeld.text)
var lat = latString.doubleValue
var longString = NSString(string: self.longField.text)
var long = longString.doubleValue
var newLocation = CLLocationCoordinate2D(latitude: lat, longitude: long)
var region = MKCoordinateRegionMakeWithDistance(newLocation, 1000, 1000)
self.mapVIew.setRegion(region, animated: true)
}
}
| gpl-2.0 | c7cba1339da42711bf4da3afc9774369 | 33.933036 | 130 | 0.628754 | 5.703353 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/UploadWidget/CropView/CLDCropView.swift | 1 | 36277 | //
// CLDCropView.swift
//
// Copyright (c) 2020 Cloudinary (http://cloudinary.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
public extension CGFloat {
static var ulpOfOne: CGFloat { CGFloat(Float.ulpOfOne) }
}
/**
Preset values of the most common aspect ratios that can be used to quickly configure
the crop view controller.
*/
@objc
public enum CLDCropViewControllerAspectRatioPreset : Int {
case original
case square
case rect3x2
case rect5x3
case rect4x3
case rect5x4
case rect7x5
case rect16x9
case custom
}
/**
When the user taps down to resize the box, this state is used
to determine where they tapped and how to manipulate the box
*/
@objc
public enum CLDCropViewOverlayEdge : Int {
case none
case topLeft
case top
case topRight
case right
case bottomRight
case bottom
case bottomLeft
case left
}
// =====================================================================================================================
@objc
public protocol CLDCropViewDelegate : NSObjectProtocol {
@objc optional func cropView(_ cropView: CLDCropView, didChangeResettable state: Bool)
}
// =====================================================================================================================
@objc
@objcMembers
public class CLDCropView: UIView {
// MARK: - Constants
internal struct Constants {
internal static let padding : CGFloat = CGFloat(14.0) // kTOCropViewPadding
internal static let timerDuration : TimeInterval = TimeInterval(0.8) // kTOCropTimerDuration
internal static let minimumBoxSize : CGFloat = CGFloat(42.0) // kTOCropViewMinimumBoxSize
internal static let circularPathRadius : CGFloat = CGFloat(300.0) // kTOCropViewCircularPathRadius
internal static let maximumZoomScale : CGFloat = CGFloat(15.0) // kTOMaximumZoomScale
}
// MARK: - Types
internal class Calculator {
internal class CropBox {}
internal class ImageCrop {}
internal class AspectRatio {}
}
// MARK: - Properties
/**
A delegate object that receives notifications from the crop view
*/
public weak var delegate: CLDCropViewDelegate?
/**
If false, the user cannot resize the crop box frame using a pan gesture from a corner.
Default value is true.
*/
public var cropBoxResizeEnabled: Bool {
get { _cropBoxResizeEnabled }
set {
_cropBoxResizeEnabled = newValue
gridPanGestureRecognizer.isEnabled = newValue
}
}
/**
Inset the workable region of the crop view in case in order to make space for accessory views
*/
public var cropRegionInsets: UIEdgeInsets
/**
When performing manual content layout (such as during screen rotation), disable any internal layout
*/
public var internalLayoutDisabled: Bool
/**
A width x height ratio that the crop box will be rescaled to (eg 4:3 is {4.0f, 3.0f})
Setting it to CGSizeZero will reset the aspect ratio to the image's own ratio.
*/
public var aspectRatio: CGSize {
get { _aspectRatio }
set { setAspectRatio(newValue, animated: false) }
}
/**
When the cropping box is locked to its current aspect ratio (But can still be resized)
*/
public var aspectRatioLockEnabled: Bool
/**
If true, a custom aspect ratio is set, and the aspectRatioLockEnabled is set to YES,
the crop box will swap it's dimensions depending on portrait or landscape sized images.
This value also controls whether the dimensions can swap when the image is rotated.
Default is true.
*/
public var aspectRatioLockDimensionSwapEnabled: Bool
/**
When the user taps 'reset', whether the aspect ratio will also be reset as well
Default is true.
*/
public var resetAspectRatioEnabled: Bool
/**
The rotation angle of the crop view (Will always be negative as it rotates in a counter-clockwise direction)
*/
public var angle: Int {
get { _angle }
set {
// The initial layout would not have been performed yet.
// Save the value and it will be applied when it has
var newAngle = newValue
if (newValue % 90 != 0) { newAngle = 0 }
if !initialSetupPerformed {
restoreAngle = newAngle
return
}
// Negative values are allowed, so rotate clockwise or counter clockwise depending on direction
if (newAngle >= 0) {
while ( labs(angle) != labs(newAngle)) { rotateImageNinetyDegreesAnimated(false, clockwise: true ) }
} else {
while (-labs(angle) != -labs(newAngle)) { rotateImageNinetyDegreesAnimated(false, clockwise: false) }
}
}
}
/**
In relation to the coordinate space of the image, the frame that the crop view is focusing on
*/
public var imageCropFrame: CGRect {
get {
return Calculator.ImageCrop.computeFrame(given: imageSize, scrollView: scrollView, cropBox: cropBoxFrame)
}
set {
guard initialSetupPerformed else { restoreImageCropFrame = newValue; return }
let adjutsments = Calculator.ImageCrop.computeAdjutsments(for: self,
scrollView: scrollView,
content: contentBounds,
newValue: newValue)
cropBoxFrame = adjutsments.cropFrame
applyCropFrameAdjutsments(to: scrollView, originPoint: newValue.origin, minimumScale: adjutsments.minimumZoomScale, adjustedZoom: adjutsments.adjustedZoomScale)
}
}
/**
Paddings of the crop rectangle.
Default to 14.0
*/
public var cropViewPadding: CGFloat
/**
Delay before crop frame is adjusted according new crop area.
Default to 0.8
*/
public var cropAdjustingDelay: TimeInterval
/**
The minimum croping aspect ratio. If set, user is prevented from setting cropping
rectangle to lower aspect ratio than defined by the parameter.
*/
public var minimumAspectRatio: CGFloat
/**
The maximum scale that user can apply to image by pinching to zoom. Small values
are only recomended with aspectRatioLockEnabled set to true.
Default to 15.0
*/
public var maximumZoomScale: CGFloat
/**
Always show the cropping grid lines, even when the user isn't interacting.
This also disables the fading animation.
(Default is NO)
*/
public var alwaysShowCroppingGrid: Bool {
get { _alwaysShowCroppingGrid }
set {
if _alwaysShowCroppingGrid == newValue { return }
_alwaysShowCroppingGrid = newValue
gridOverlayView.setGridlines(hidden: !newValue, animted: true)
}
}
/**
Permanently hides the translucency effect covering the outside bounds of the
crop box.
Default is NO
*/
public var translucencyAlwaysHidden: Bool {
get { _translucencyAlwaysHidden }
set {
guard _translucencyAlwaysHidden != newValue else { return }
_translucencyAlwaysHidden = newValue
translucencyView.isHidden = newValue
}
}
/**
The image that the crop view is displaying. This cannot be changed once the crop view is instantiated.
*/
public internal(set) var image : UIImage
/* Views */
/**
The main image view, placed within the scroll view
*/
internal var backgroundImageView: UIImageView!
/**
A view which contains the background image view, to separate its transforms from the scroll view.
*/
internal var backgroundContainerView: UIView!
/**
A container view that clips the a copy of the image so it appears over the dimming view
*/
public private(set) var foregroundContainerView: UIView!
/**
A copy of the background image view, placed over the dimming views
*/
internal var foregroundImageView: UIImageView!
/**
The scroll view in charge of panning/zooming the image.
*/
internal private(set) var scrollView: CLDCropScrollView!
/**
The scroll view in charge of panning/zooming the image.
*/
private var scrollViewDelegate: CLDCropScrollViewController!
/**
A semi-transparent grey view, overlaid on top of the background image
*/
private var overlayView: UIView!
/**
A blur view that is made visible when the user isn't interacting with the crop view
*/
internal var translucencyView: UIVisualEffectView!
/**
The dark blur visual effect applied to the visual effect view.
*/
private var translucencyEffect: UIBlurEffect!
/**
A grid view overlaid on top of the foreground image view's container.
*/
public private(set) var gridOverlayView: CLDCropOverlayView!
/* Gesture Recognizers */
/**
The gesture recognizer in charge of controlling the resizing of the crop view
*/
private var gridPanGestureRecognizer: UIPanGestureRecognizer!
/* Crop box handling */
/**
No by default, when setting initialCroppedImageFrame this will be set to YES, and set back to NO after first application - so it's only done once
*/
private var applyInitialCroppedImageFrame: Bool
/**
The edge region that the user tapped on, to resize the cropping region
*/
internal var tappedEdge: CLDCropViewOverlayEdge
/**
When resizing, this is the original frame of the crop box.
*/
internal var cropOriginFrame : CGRect
/**
The initial touch point of the pan gesture recognizer
*/
internal var panOriginPoint : CGPoint
/**
The frame of the cropping box in the coordinate space of the crop view
*/
public internal(set) var cropBoxFrame: CGRect {
get { _cropBoxFrame }
set {
if _cropBoxFrame.equalTo(newValue) { return }
guard newValue.isValidBoxSize else { return }
// Clamp the cropping region to the inset boundaries of the screen
_cropBoxFrame = Calculator.CropBox.clampFrame(given: contentBounds, cropBox: newValue,
minimumBoxSize: Constants.minimumBoxSize)
applyDidSetCropBoxFrame(to: _cropBoxFrame)
}
}
/**
A manager for the crop view UI
*/
fileprivate var cropUIManager: CLDCropViewUIManager!
/**
The timer used to reset the view after the user stops interacting with it
*/
internal var resetTimer: Timer?
/**
Used to denote the active state of the user manipulating the content
default is NO. setting is not animated.
*/
private var isEditing: Bool {
get { _isEditing }
set {
setEditing(newValue, resetCropBox: false, animated: false)
}
}
internal func startEditing() {
cancelResetTimer()
setEditing(true, resetCropBox: false, animated: true)
}
internal func setEditing(_ editing: Bool, resetCropBox: Bool, animated: Bool) {
if _isEditing == editing { return }
_isEditing = editing
// Toggle the visiblity of the gridlines when not editing
var hidden = !editing
if (alwaysShowCroppingGrid) { hidden = false } // Override this if the user requires
gridOverlayView.setGridlines(hidden: hidden, animted: animated)
if resetCropBox {
moveCroppedContentToCenterAnimated(animated)
captureStateForImageRotation()
cropBoxLastEditedAngle = angle
}
switch animated {
case false:
toggleTranslucencyViewVisible(!editing)
case true:
let duration = editing ? 0.05 : 0.35
let delay = editing ? 0.00 : 0.35
UIView.animateKeyframes(withDuration: duration, delay: delay, options: [], animations: {
self.toggleTranslucencyViewVisible(!editing)
}, completion: nil)
}
}
/**
At times during animation, disable matching the forground image view to the background
*/
internal var disableForgroundMatching: Bool
/* Pre-screen-rotation state information */
private var rotationContentOffset: CGPoint
private var rotationContentSize : CGSize
private var rotationBoundFrame : CGRect
/* View State information */
/**
Give the current screen real-estate, the frame that the scroll view is allowed to use
*/
internal var contentBounds: CGRect {
return Calculator.bounds(for: self.bounds, padding: cropViewPadding, cropRegion: cropRegionInsets)
}
/**
Given the current rotation of the image, the size of the image
*/
internal var imageSize: CGSize {
if (angle == -90 || angle == -270 || angle == 90 || angle == 270 )
{
return CGSize(width: image.size.height, height: image.size.width )
}
else
{
return CGSize(width: image.size.width , height: image.size.height)
}
}
/**
True if an aspect ratio was explicitly applied to this crop view
*/
internal var hasAspectRatio: Bool {
return aspectRatio.width > CGFloat.ulpOfOne && aspectRatio.height > CGFloat.ulpOfOne
}
/* 90-degree rotation state data */
/**
When performing 90-degree rotations, remember what our last manual size was to use that as a base
*/
internal var cropBoxLastEditedSize: CGSize
/**
Remember which angle we were at when we saved the editing size
*/
internal var cropBoxLastEditedAngle: Int
/**
Remember the zoom size when we last edited
*/
internal var cropBoxLastEditedZoomScale: CGFloat
/**
Remember the minimum size when we last edited.
*/
internal var cropBoxLastEditedMinZoomScale: CGFloat
/**
Disallow any input while the rotation animation is playing
*/
internal var rotateAnimationInProgress: Bool
/* Reset state data */
/**
Save the original crop box size so we can tell when the content has been edited
*/
private var originalCropBoxSize: CGSize
/**
Save the original content offset so we can tell if it's been scrolled.
*/
private var originalContentOffset: CGPoint
/**
Whether the user has manipulated the crop view to the point where it can be reset
*/
public internal(set) var isResettable: Bool {
get{ _isResettableFlag }
set{
guard newValue != _isResettableFlag else { return }
_isResettableFlag = newValue
delegate?.cropView?(self, didChangeResettable: _isResettableFlag)
}
}
/**
In iOS 9, a new dynamic blur effect became available.
*/
public internal(set) var dynamicBlurEffect: Bool
// MARK: - ======================================================================================
/**
If restoring to a previous crop setting, these properties hang onto the
values until the view is configured for the first time.
*/
private var restoreAngle : Int
private var restoreImageCropFrame: CGRect
/**
Set to YES once `performInitialLayout` is called.
This lets pending properties get queued until the view has been properly set up in its parent.
*/
private var initialSetupPerformed: Bool
// MARK: - Private properties ======================================================================================
private var _cropBoxFrame : CGRect
private var _cropBoxResizeEnabled : Bool
private var _simpleRenderMode : Bool
private var _imageCropFrame : CGRect
private var _isEditing : Bool
private var _isResettableFlag : Bool
private var _aspectRatio : CGSize
private var _croppingViewsHidden : Bool
private var _gridOverlayHidden : Bool
private var _alwaysShowCroppingGrid : Bool
private var _translucencyAlwaysHidden: Bool
var _angle : Int
// MARK: - Initialized ======================================================================================
/**
Create a new instance of the crop view with the specified image and cropping
*/
public init(image: UIImage) {
self.image = image
self.aspectRatioLockDimensionSwapEnabled = true
self.resetAspectRatioEnabled = true
self.cropViewPadding = Constants.padding
self.cropAdjustingDelay = Constants.timerDuration
self.cropBoxLastEditedSize = CGSize.zero
self.cropBoxLastEditedAngle = 0
self.cropBoxLastEditedZoomScale = 0.0
self.cropBoxLastEditedMinZoomScale = 0.0
self.rotateAnimationInProgress = false
self.cropRegionInsets = .zero
self.minimumAspectRatio = CGFloat(0.0)
self.internalLayoutDisabled = false
self.aspectRatioLockEnabled = false
self.tappedEdge = .none
self.cropOriginFrame = CGRect.zero
self.panOriginPoint = CGPoint.zero
self._angle = 0
self._isEditing = false
self._cropBoxFrame = .zero
self._aspectRatio = .zero
self._imageCropFrame = .zero
self._isResettableFlag = false
self._simpleRenderMode = false
self._cropBoxResizeEnabled = false
self._alwaysShowCroppingGrid = false
self._translucencyAlwaysHidden = false
self._gridOverlayHidden = false
self._croppingViewsHidden = false
self.disableForgroundMatching = false
self.rotationContentOffset = .zero
self.rotationContentSize = .zero
self.rotationBoundFrame = .zero
self.originalCropBoxSize = .zero
self.originalContentOffset = .zero
self.initialSetupPerformed = false
self.maximumZoomScale = Constants.maximumZoomScale
self.applyInitialCroppedImageFrame = false
self.dynamicBlurEffect = false
self.restoreAngle = 0
self.restoreImageCropFrame = .zero
super.init(frame: .zero)
// UI manager
self.cropUIManager = CLDCropViewUIManager(cropView: self)
// The pan controller to recognize gestures meant to resize the grid view
self.gridPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(gridPanGestureRecognized(_:)))
self.cropBoxResizeEnabled = true
self.alwaysShowCroppingGrid = false
self.translucencyAlwaysHidden = false
// View properties
self.autoresizingMask = [.flexibleHeight , .flexibleWidth]
self.backgroundColor = UIColor(white: 0.12, alpha: 1.0)
self.cropBoxFrame = CGRect.zero
self._isEditing = false
self._cropBoxResizeEnabled = true
self._aspectRatio = CGSize.zero
self.resetAspectRatioEnabled = true
self.cropAdjustingDelay = Constants.timerDuration
self.cropViewPadding = Constants.padding
/* Dynamic animation blurring is only possible on iOS 9, however since the API was available on iOS 8,
we'll need to manually check the system version to ensure that it's available. */
self.dynamicBlurEffect = UIDevice.current.systemVersion.compare("9.0", options: .numeric) != .orderedAscending
// Scroll View
self.scrollViewDelegate = CLDCropScrollViewController(cropView: self)
self.scrollView = CLDCropScrollView(frame: bounds)
self.scrollView.delegate = self.scrollViewDelegate
self.addSubview(self.scrollView)
// Disable smart inset behavior in iOS 11
if #available(iOS 11.0, *) {
self.scrollView.contentInsetAdjustmentBehavior = .never
}
self.scrollView.touchesBegan = { [weak self] in self?.startEditing() }
self.scrollView.touchesEnded = { [weak self] in self?.startResetTimer() }
// Background Image View
self.backgroundImageView = UIImageView(image: self.image)
self.backgroundImageView.layer.minificationFilter = CALayerContentsFilter.trilinear
// Background container view
self.backgroundContainerView = UIView(frame: self.backgroundImageView.frame)
self.backgroundContainerView.addSubview(self.backgroundImageView)
self.scrollView.addSubview(self.backgroundContainerView)
// Grey transparent overlay view
self.overlayView = UIView(frame: bounds)
self.overlayView.autoresizingMask = [.flexibleHeight , .flexibleWidth]
self.overlayView.backgroundColor = self.backgroundColor?.withAlphaComponent(0.35)
self.overlayView.isHidden = false
self.overlayView.isUserInteractionEnabled = false
self.addSubview(self.overlayView)
// Translucency View
self.translucencyEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
self.translucencyView = UIVisualEffectView(effect: self.translucencyEffect)
self.translucencyView.frame = self.bounds
self.translucencyView.isHidden = self.translucencyAlwaysHidden
self.translucencyView.isUserInteractionEnabled = false
self.translucencyView.autoresizingMask = [.flexibleHeight , .flexibleWidth]
self.addSubview(self.translucencyView)
// The forground container that holds the foreground image view
self.foregroundContainerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
self.foregroundContainerView.clipsToBounds = true
self.foregroundContainerView.isUserInteractionEnabled = false
self.addSubview(self.foregroundContainerView)
self.foregroundImageView = UIImageView(image: self.image)
self.foregroundImageView.layer.minificationFilter = CALayerContentsFilter.trilinear
self.foregroundContainerView.addSubview(self.foregroundImageView)
// Disable colour inversion for the image views
if #available(iOS 11.0, *) {
self.foregroundImageView.accessibilityIgnoresInvertColors = true
self.backgroundImageView.accessibilityIgnoresInvertColors = true
}
// The white grid overlay view
self.gridOverlayView = CLDCropOverlayView(frame: self.foregroundContainerView.frame)
self.gridOverlayView.isUserInteractionEnabled = false
self.gridOverlayView.isGridHidden = true
self.addSubview(self.gridOverlayView)
self.gridPanGestureRecognizer.delegate = self
self.scrollView.panGestureRecognizer.require(toFail: self.gridPanGestureRecognizer)
self.addGestureRecognizer(self.gridPanGestureRecognizer)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Layout
/**
Performs the initial set up, including laying out the image and applying any restore properties.
This should be called once the crop view has been added to a parent that is in its final layout frame.
*/
public func performInitialSetup() {
// Calling this more than once is potentially destructive
if initialSetupPerformed {
return
}
// Disable from calling again
initialSetupPerformed = true
// Perform the initial layout of the image
layoutInitialImage()
// -- State Restoration --
// If the angle value was previously set before this point, apply it now
if (restoreAngle != 0) {
angle = restoreAngle
restoreAngle = 0
cropBoxLastEditedAngle = angle
}
// If an image crop frame was also specified before creation, apply it now
if !restoreImageCropFrame.isEmpty {
imageCropFrame = restoreImageCropFrame
restoreImageCropFrame = .zero
}
// Save the current layout state for later
captureStateForImageRotation()
// Check if we performed any resetabble modifications
checkForCanReset()
}
private func layoutInitialImage() {
let scaledImageSize = cropUIManager.manualLayout_initialImageAndGetScaledImageSize()
// Save the current state for use with 90-degree rotations
cropBoxLastEditedAngle = 0
captureStateForImageRotation()
//save the size for checking if we're in a resettable state
originalCropBoxSize = resetAspectRatioEnabled ? scaledImageSize : cropBoxFrame.size
originalContentOffset = scrollView.contentOffset
checkForCanReset()
matchForegroundToBackground()
}
internal func matchForegroundToBackground() {
if disableForgroundMatching { return }
// We can't simply match the frames since if the images are rotated, the frame property becomes unusable
if let view = backgroundContainerView.superview {
foregroundImageView.frame = view.convert(backgroundContainerView.frame, to: foregroundContainerView)
}
}
private func updateCropBoxFrame(withGesture point: CGPoint) {
cropBoxFrame = Calculator.CropBox.calculateFrame(given: point, in: self)
checkForCanReset()
}
private func toggleTranslucencyViewVisible(_ visible: Bool) {
if dynamicBlurEffect == false {
translucencyView.alpha = visible ? 1.0 : 0.0
} else {
translucencyView.effect = visible ? translucencyEffect : nil
}
}
// MARK: - Gesture Recognizer - ====================================================================================
@objc private func gridPanGestureRecognized(_ recognizer: UIPanGestureRecognizer) {
let point = recognizer.location(in: self)
switch recognizer.state {
case .began:
startEditing()
panOriginPoint = point
cropOriginFrame = cropBoxFrame
tappedEdge = Calculator.overlayEdge(for: panOriginPoint, cropBoxFrame: cropBoxFrame)
break
case .ended:
startResetTimer()
break
default:
break
}
updateCropBoxFrame(withGesture: point)
}
// MARK: - Timer ====================================================================================
internal func startResetTimer() {
if let _ = resetTimer {} else {
resetTimer = Timer.scheduledTimer(timeInterval: cropAdjustingDelay, target: self, selector: #selector(timerTriggered), userInfo: nil, repeats: false)
}
}
@objc private func timerTriggered() {
setEditing(false, resetCropBox: true, animated: true)
resetTimer?.invalidate()
resetTimer = nil
}
internal func cancelResetTimer() {
resetTimer?.invalidate()
resetTimer = nil
}
// MARK: - =========================================================================================================
/**
Changes the aspect ratio of the crop box to match the one specified
- parameter aspectRatio The aspect ratio (For example 16:9 is 16.0f/9.0f). 'CGSizeZero' will reset it to the image's own ratio
- parameter animated Whether the locking effect is animated
*/
public func setAspectRatio(_ newValue: CGSize, animated: Bool) {
_aspectRatio = newValue
let adjustments = Calculator.AspectRatio.postChangeAdjustments(given: newValue, animated: animated, in: self)
cropBoxLastEditedSize = adjustments.cropBoxFrame.size
cropBoxLastEditedAngle = angle
let translateBlock : () -> Void = {
self.scrollView.contentOffset = adjustments.scrollOffset
self.cropBoxFrame = adjustments.cropBoxFrame
if (adjustments.ShouldZoomOut) {
self.scrollView.zoomScale = self.scrollView.minimumZoomScale
}
self.moveCroppedContentToCenterAnimated(false)
self.checkForCanReset()
}
switch animated {
case false:
translateBlock()
case true :
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.7, options: [.beginFromCurrentState],
animations: translateBlock, completion: nil)
}
}
public func lockAspectRatio(to aspectRatio: CGSize) {
if aspectRatioLockEnabled {
_aspectRatio = aspectRatio
}
}
/**
Rotates the entire canvas to a 90-degree angle. The default rotation is counterclockwise.
- parameter animated Whether the transition is animated
*/
public func rotateImageNinetyDegreesAnimated(_ animated: Bool) {
rotateImageNinetyDegreesAnimated(animated, clockwise: false)
}
/**
Rotates the entire canvas to a 90-degree angle
- parameter animated Whether the transition is animated
- parameter clockwise Whether the rotation is clockwise. Passing 'NO' means counterclockwise
*/
public func rotateImageNinetyDegreesAnimated(_ animated: Bool, clockwise: Bool) {
cropUIManager.manualLayout_rotateImageNinetyDegreesAnimated(animated, clockwise: clockwise)
}
/**
When triggered, the crop view will perform a relayout to ensure the crop box
fills the entire crop view region
*/
public func moveCroppedContentToCenterAnimated(_ animated: Bool) {
cropUIManager.manualLayout_moveCroppedContentToCenterAnimated(animated)
}
// MARK: -- Editing Mode
internal func captureStateForImageRotation() {
cropBoxLastEditedSize = cropBoxFrame.size
cropBoxLastEditedZoomScale = scrollView.zoomScale
cropBoxLastEditedMinZoomScale = scrollView.minimumZoomScale
}
// MARK: -- Resettable State
internal func checkForCanReset() {
var resettable = false
if angle != 0 { // Image has been rotated
resettable = true
}
else if scrollView.zoomScale > scrollView.minimumZoomScale + CGFloat.ulpOfOne { // Image has been zoomed in
resettable = true
}
else if
Int(floor(cropBoxFrame.width )) != Int(floor(originalCropBoxSize.width )) ||
Int(floor(cropBoxFrame.height)) != Int(floor(originalCropBoxSize.height)) // Crop box has been changed
{
resettable = true
}
else if
Int(floor(scrollView.contentOffset.x)) != Int(floor(originalContentOffset.x)) ||
Int(floor(scrollView.contentOffset.y)) != Int(floor(originalContentOffset.y))
{
resettable = true
}
isResettable = resettable
}
// MARK: -- fileprivate methods
fileprivate func applyCropFrameAdjutsments(to scrollView: UIScrollView, originPoint: CGPoint, minimumScale: CGFloat, adjustedZoom scale: CGFloat) {
let scaledOffset = CGPoint(x: originPoint.x * minimumScale,
y: originPoint.y * minimumScale)
// Zoom into the scroll view to the appropriate size
scrollView.zoomScale = scrollView.minimumZoomScale * scale
scrollView.contentOffset = CGPoint(x: (scaledOffset.x * scale) - scrollView.contentInset.left,
y: (scaledOffset.y * scale) - scrollView.contentInset.top)
}
fileprivate func applyDidSetCropBoxFrame(to rectangle: CGRect) {
// Set the clipping view to match the new rect
foregroundContainerView.frame = rectangle
// Set the new overlay view to match the same region
gridOverlayView.frame = rectangle
Calculator.CropBox.updateScrollView(scrollView, given: backgroundContainerView.bounds.size,
boundingRect: self.bounds, newCropBox: rectangle)
// Re-align the background content to match
matchForegroundToBackground()
}
}
// MARK: - UIGestureRecognizerDelegate
extension CLDCropView : UIGestureRecognizerDelegate {
public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer != gridPanGestureRecognizer {
return true
}
let tapPoint = gestureRecognizer.location(in: self)
let rectangle = gridOverlayView.frame
let innerRectangle = rectangle.insetBy(dx: 22.0, dy: 22.0)
let outerRectangle = rectangle.insetBy(dx: -22.0, dy: -22.0)
if innerRectangle.contains(tapPoint) || !outerRectangle.contains(tapPoint) {
return false
}
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gridPanGestureRecognizer.state == .changed {
return false
}
return true
}
}
// MARK: - General extensions
fileprivate extension CGRect {
var isValidBoxSize : Bool {
// Upon init, sometimes the box size is still 0 (or NaN), which can result in CALayer issues
let threashold = CGFloat.ulpOfOne
if (width < threashold || height < threashold) { return false }
if (width.isNaN || height.isNaN ) { return false }
return true
}
}
| mit | 5a24d430188835d9d06c412a83b94863 | 34.705709 | 172 | 0.614522 | 5.295912 | false | false | false | false |
xu6148152/binea_project_for_ios | ListerforAppleWatchiOSandOSX/Swift/ListerKit/DirectoryMonitor.swift | 1 | 3232 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
`DirectoryMonitor` is used to monitor the contents of the provided directory by using a GCD dispatch source.
*/
import Foundation
/// A protocol that allows delegates of `DirectoryMonitor` to respond to changes in a directory.
protocol DirectoryMonitorDelegate: class {
func directoryMonitorDidObserveChange(directoryMonitor: DirectoryMonitor)
}
class DirectoryMonitor {
// MARK: Properties
/// The `DirectoryMonitor`'s delegate who is responsible for responding to `DirectoryMonitor` updates.
weak var delegate: DirectoryMonitorDelegate?
/// A file descriptor for the monitored directory.
var monitoredDirectoryFileDescriptor: CInt = -1
/// A dispatch queue used for sending file changes in the directory.
let directoryMonitorQueue = dispatch_queue_create("com.example.apple-samplecode.lister.directorymonitor", DISPATCH_QUEUE_CONCURRENT)
/// A dispatch source to monitor a file descriptor created from the directory.
var directoryMonitorSource: dispatch_source_t?
/// URL for the directory being monitored.
var URL: NSURL
// MARK: Initializers
init(URL: NSURL) {
self.URL = URL
}
// MARK: Monitoring
func startMonitoring() {
// Listen for changes to the directory (if we are not already).
if directoryMonitorSource == nil && monitoredDirectoryFileDescriptor == -1 {
// Open the directory referenced by URL for monitoring only.
monitoredDirectoryFileDescriptor = open(URL.path!, O_EVTONLY)
// Define a dispatch source monitoring the directory for additions, deletions, and renamings.
directoryMonitorSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(monitoredDirectoryFileDescriptor), DISPATCH_VNODE_WRITE, directoryMonitorQueue)
// Define the block to call when a file change is detected.
dispatch_source_set_event_handler(directoryMonitorSource!) {
// Call out to the `DirectoryMonitorDelegate` so that it can react appropriately to the change.
self.delegate?.directoryMonitorDidObserveChange(self)
return
}
// Define a cancel handler to ensure the directory is closed when the source is cancelled.
dispatch_source_set_cancel_handler(directoryMonitorSource!) {
close(self.monitoredDirectoryFileDescriptor)
self.monitoredDirectoryFileDescriptor = -1
self.directoryMonitorSource = nil
}
// Start monitoring the directory via the source.
dispatch_resume(directoryMonitorSource)
}
}
func stopMonitoring() {
// Stop listening for changes to the directory, if the source has been created.
if directoryMonitorSource != nil {
// Stop monitoring the directory via the source.
dispatch_source_cancel(directoryMonitorSource)
}
}
}
| mit | 9e4af7a0607b78db36cc2ed3282c5b98 | 39.886076 | 172 | 0.66192 | 5.465313 | false | false | false | false |
SuPair/firefox-ios | Push/PushClient.swift | 1 | 7104 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Alamofire
import Deferred
import Shared
import SwiftyJSON
//public struct PushRemoteError {
// static let MissingNecessaryCryptoKeys: Int32 = 101
// static let InvalidURLEndpoint: Int32 = 102
// static let ExpiredURLEndpoint: Int32 = 103
// static let DataPayloadTooLarge: Int32 = 104
// static let EndpointBecameUnavailable: Int32 = 105
// static let InvalidSubscription: Int32 = 106
// static let RouterTypeIsInvalid: Int32 = 108
// static let InvalidAuthentication: Int32 = 109
// static let InvalidCryptoKeysSpecified: Int32 = 110
// static let MissingRequiredHeader: Int32 = 111
// static let InvalidTTLHeaderValue: Int32 = 112
// static let UnknownError: Int32 = 999
//}
public let PushClientErrorDomain = "org.mozilla.push.error"
private let PushClientUnknownError = NSError(domain: PushClientErrorDomain, code: 999,
userInfo: [NSLocalizedDescriptionKey: "Invalid server response"])
private let log = Logger.browserLogger
/// Bug 1364403 – This is to be put into the push registration
private let apsEnvironment: [String: Any] = [
"mutable-content": 1,
"alert": [
"title": " ",
"body": " "
],
]
public struct PushRemoteError {
let code: Int
let errno: Int
let error: String
let message: String?
public static func from(json: JSON) -> PushRemoteError? {
guard let code = json["code"].int,
let errno = json["errno"].int,
let error = json["error"].string else {
return nil
}
let message = json["message"].string
return PushRemoteError(code: code, errno: errno, error: error, message: message)
}
}
public enum PushClientError: MaybeErrorType {
case Remote(PushRemoteError)
case Local(Error)
public var description: String {
switch self {
case let .Remote(error):
let errorString = error.error
let messageString = error.message ?? ""
return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>"
case let .Local(error):
return "<FxAClientError.Local Error \"\(error.localizedDescription)\">"
}
}
}
public class PushClient {
let endpointURL: NSURL
let experimentalMode: Bool
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.fxaUserAgent
let configuration = URLSessionConfiguration.ephemeral
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = ua
configuration.httpAdditionalHeaders = defaultHeaders
return SessionManager(configuration: configuration)
}()
public init(endpointURL: NSURL, experimentalMode: Bool = false) {
self.endpointURL = endpointURL
self.experimentalMode = experimentalMode
}
}
public extension PushClient {
public func register(_ apnsToken: String) -> Deferred<Maybe<PushRegistration>> {
// POST /v1/{type}/{app_id}/registration
let registerURL = endpointURL.appendingPathComponent("registration")!
var mutableURLRequest = URLRequest(url: registerURL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters: [String: Any]
if experimentalMode {
parameters = [
"token": apnsToken,
"aps": apsEnvironment,
]
} else {
parameters = ["token": apnsToken]
}
mutableURLRequest.httpBody = JSON(parameters).stringify()?.utf8EncodedData
if experimentalMode {
log.info("curl -X POST \(registerURL.absoluteString) --data '\(JSON(parameters).stringify()!)'")
}
return send(request: mutableURLRequest) >>== { json in
guard let response = PushRegistration.from(json: json) else {
return deferMaybe(PushClientError.Local(PushClientUnknownError))
}
return deferMaybe(response)
}
}
public func updateUAID(_ apnsToken: String, withRegistration creds: PushRegistration) -> Deferred<Maybe<PushRegistration>> {
// PUT /v1/{type}/{app_id}/registration/{uaid}
let registerURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)")!
var mutableURLRequest = URLRequest(url: registerURL)
mutableURLRequest.httpMethod = HTTPMethod.put.rawValue
mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization")
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = ["token": apnsToken]
mutableURLRequest.httpBody = JSON(parameters).stringify()?.utf8EncodedData
return send(request: mutableURLRequest) >>== { json in
return deferMaybe(creds)
}
}
public func unregister(_ creds: PushRegistration) -> Success {
// DELETE /v1/{type}/{app_id}/registration/{uaid}
let unregisterURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)")
var mutableURLRequest = URLRequest(url: unregisterURL!)
mutableURLRequest.httpMethod = HTTPMethod.delete.rawValue
mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization")
return send(request: mutableURLRequest) >>> succeed
}
}
/// Utilities
extension PushClient {
fileprivate func send(request: URLRequest) -> Deferred<Maybe<JSON>> {
log.info("\(request.httpMethod!) \(request.url?.absoluteString ?? "nil")")
let deferred = Deferred<Maybe<JSON>>()
alamofire.request(request)
.validate(contentType: ["application/json"])
.responseJSON { response in
// Don't cancel requests just because our client is deallocated.
withExtendedLifetime(self.alamofire) {
let result = response.result
if let error = result.error {
return deferred.fill(Maybe(failure: PushClientError.Local(error)))
}
guard let data = response.data else {
return deferred.fill(Maybe(failure: PushClientError.Local(PushClientUnknownError)))
}
let json = JSON(data: data)
if let remoteError = PushRemoteError.from(json: json) {
return deferred.fill(Maybe(failure: PushClientError.Remote(remoteError)))
}
deferred.fill(Maybe(success: json))
}
}
return deferred
}
}
| mpl-2.0 | ca20bba306d850ceb3d83ca232aafa82 | 36.973262 | 128 | 0.635263 | 5.093974 | false | false | false | false |
karryoberes/PopUpMenu | Pod/Classes/PopUpViewController.swift | 1 | 13449 | //
// PopUpViewController.swift
// Pods
//
// Created by Oberes, Karry Raia C. on 10/13/15.
//
//
import UIKit
@objc protocol PopUpViewDelegate {
optional func handleButton1Pressed()
optional func handleButton2Pressed()
optional func handleButton3Pressed()
optional func handleButton4Pressed()
optional func handleButton5Pressed()
optional func handleButton6Pressed()
optional func handleButton7Pressed()
optional func handleButton8Pressed()
optional func handleButton9Pressed()
optional func handleButton10Pressed()
optional func handleButton11Pressed()
optional func handleButton12Pressed()
optional func handleButton13Pressed()
optional func handleButton14Pressed()
optional func handleButton15Pressed()
}
/// Sets the current instance to its self
private struct PrivateInstance {
static var currentInstance: PopUpViewController!
}
public class PopUpViewController: UIViewController {
var menuView: UIView!
var menuButton: UIButton!
var delegate: PopUpViewDelegate?
var buttonTitles = NSMutableArray()
var buttonNormalIcons = NSMutableArray()
var buttonHighlightedIcons = NSMutableArray()
var btnHeight:CGFloat = 40
/// Color for the Title Label of the menu in PopUp View Controller (PopUp Menu)
public var buttonTitleColor: UIColor!
/// Color for the Title Label of the menu when highlighted in PopUp View Controller (PopUp Menu)
public var buttonSelectedTitleColor: UIColor!
/// Background color for the button in PopUp View Controller (PopUp Menu)
public var buttonBackgroundColor: UIColor!
/// Color for the separator of menus in PopUp View Controller (PopUp Menu)
public var separatorColor: UIColor!
/// Font for the Title Label of the menu in PopUp View Controller (PopUp Menu
public var buttonFont: UIFont!
/// Background image for the button in PopUp View Controller (PopUp Menu)
public var backgroundImage: String!
/// Background image for the button when highlighted in PopUp View Controller (PopUp Menu)
public var backgroundHighlightedImage: String!
var returnToNormalWhenSelected = true
// MARK: INITIALIZE POPUP MENU PROPERTIES
/**
Initializes a view controller with the provided specifications from the PopUp Button.
:param: menuButtonTitles The list of the titles for the PopUp View Controller (PopUp Menu), in an Array of String
:param: menuButtonNormalIcons The list of the image names for the PopUp View Controller (PopUp Menu) for Normal State
:param: menuButtonHighlightedIcons The list of the image names for the PopUp View Controller (PopUp Menu) for Highlighted State
:param: menuBGImage The background image for the menus inside the PopUp View Controller (PopUp Menu) for Normal State
:param: menuHBGImage The background image for the menus inside the PopUp View Controller (PopUp Menu) for Highlighted State
:returns: A custom PopUp Menu.
*/
convenience init(menuButtonTitles: NSArray!, menuButtonNormalIcons: NSArray!, menuButtonHighlightedIcons: NSArray!, menuBGImage: String!, menuHBGImage: String!) {
self.init()
if let titles = menuButtonTitles {
buttonTitles.addObjectsFromArray(titles as [AnyObject])
}
if let iconsN = menuButtonNormalIcons {
buttonNormalIcons.addObjectsFromArray(iconsN as [AnyObject])
}
if let iconsH = menuButtonHighlightedIcons {
buttonHighlightedIcons.addObjectsFromArray(iconsH as [AnyObject])
}
backgroundImage = menuBGImage
backgroundHighlightedImage = menuHBGImage
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
Initializes the view's frame and properties of the PopUp Menu.
Adds a gesture recognizer that once the user taps oustide the view, it will dismiss the presented view.
*/
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.frame = UIScreen.mainScreen().bounds
UIApplication.sharedApplication().keyWindow?.addSubview(self.view)
self.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.4)
self.view.alpha = 0.0
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:"hide"))
}
/// Once the view will appear it calls the createMenuView.
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.createMenuView()
}
/// Once the view appeared it sets the current instance to its self.
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
PrivateInstance.currentInstance = self
}
// MARK: CREATE VIEW FOR POPUP MENU
/**
This function is set to create the view for the PopUp Menu.
Sets the button's frame and its properties and adds it into the view.
Initializes the view's frame and its properties.
*/
func createMenuView() {
menuView = UIView()
var btnArray = NSMutableArray()
for (index, title) in enumerate(buttonTitles) {
menuButton = UIButton(frame: CGRectMake(0, 0, 0, btnHeight))
menuButton.tag = index+1
menuButton.backgroundColor = buttonBackgroundColor
if (!backgroundImage.isEmpty && !backgroundHighlightedImage.isEmpty) {
menuButton.setBackgroundImage(UIImage(named: backgroundImage), forState: .Normal)
menuButton.setBackgroundImage(UIImage(named: backgroundHighlightedImage), forState: .Highlighted)
}
if (buttonNormalIcons.count >= 1 && buttonHighlightedIcons.count >= 1) {
menuButton.setImage(UIImage(named: buttonNormalIcons[index] as! String), forState: .Normal)
menuButton.setImage(UIImage(named: buttonHighlightedIcons[index] as! String), forState: .Highlighted)
menuButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
}
menuButton.setTitle(title as! NSString as String, forState: .Normal)
menuButton.titleLabel?.font = buttonFont
menuButton.setTitleColor(buttonTitleColor, forState: UIControlState.Normal)
menuButton.setTitleColor(buttonSelectedTitleColor, forState: .Highlighted)
let selector = "handleButton\(index+1)Pressed"
menuButton.addTarget(self, action: Selector(selector), forControlEvents: .TouchUpInside)
btnArray.addObject(menuButton)
}
menuView.frame = CGRectMake(20, 0, self.view.frame.width - 90, btnHeight * CGFloat(btnArray.count))
menuView.center = self.view.center
var bYOrigin :CGFloat = 0.0
for (index,button) in enumerate(btnArray) {
if var btn = button as? UIButton {
btn.frame = CGRectMake(0, bYOrigin, menuView.frame.size.width, btnHeight)
bYOrigin += btnHeight
btn.titleLabel?.adjustsFontSizeToFitWidth = true
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 100)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 200, bottom: 0, right: 0)
menuView.addSubview(btn)
}
}
var sYOrigin :CGFloat = btnHeight + 0.5
for button in btnArray {
var separatorView = UIView(frame: CGRectMake(0, sYOrigin, menuView.frame.width, 0.7))
sYOrigin += btnHeight + 0.5
separatorView.backgroundColor = separatorColor
menuView.addSubview(separatorView)
}
menuView.layer.cornerRadius = 7.0
menuView.clipsToBounds = true
menuView.backgroundColor = UIColor.clearColor()
menuView.alpha = 0.0
self.view.addSubview(menuView)
}
// MARK: SHOW VIEW WHEN MENU BUTTON IS SELECTED
/// This function is used and called to present the view with animation and dim view background.
func show() {
self.view.alpha = 1.0
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.menuView.alpha = 1.0
})
}
// MARK: HIDE VIEW WHEN SUB MENU BUTTON IS SELECTED
/// This function is used and called to dismiss the view with animation and return to its normal view background.
func hide() {
if returnToNormalWhenSelected {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.alpha = 0.0
PrivateInstance.currentInstance = nil
})
}
}
// MARK: SUB MENU BUTTON DELEGATE
///Hides the view and call the handleButton1Pressed delegate when the 1st menu button is pressed.
public func handleButton1Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton1Pressed!()
}
}
///Hides the view and call the handleButton2Pressed delegate when the 2nd menu button is pressed.
public func handleButton2Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton2Pressed!()
}
}
///Hides the view and call the handleButton3Pressed delegate when the 3rd menu button is pressed.
public func handleButton3Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton3Pressed!()
}
}
///Hides the view and call the handleButton4Pressed delegate when the 4th menu button is pressed.
public func handleButton4Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton4Pressed!()
}
}
///Hides the view and call the handleButton5Pressed delegate when the 5th menu button is pressed.
public func handleButton5Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton5Pressed!()
}
}
///Hides the view and call the handleButton6Pressed delegate when the 6th menu button is pressed.
public func handleButton6Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton6Pressed!()
}
}
///Hides the view and call the handleButton7Pressed delegate when the 7th menu button is pressed.
public func handleButton7Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton7Pressed!()
}
}
///Call the handleButton8Pressed delegate when the 8th menu button is pressed.
public func handleButton8Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton8Pressed!()
}
}
///Hides the view and call the handleButton9Pressed delegate when the 9th menu button is pressed.
public func handleButton9Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton9Pressed!()
}
}
///Hides the view and call the handleButton10Pressed delegate when the 10th menu button is pressed.
public func handleButton10Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton10Pressed!()
}
}
///Hides the view and call the handleButton11Pressed delegate when the 11th menu button is pressed.
public func handleButton11Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton11Pressed!()
}
}
///Hides the view and call the handleButton12Pressed delegate when the 12th menu button is pressed.
public func handleButton12Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton12Pressed!()
}
}
///Hides the view and call the handleButton13Pressed delegate when the 13th menu button is pressed.
public func handleButton13Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton13Pressed!()
}
}
///Hides the view and call the handleButton14Pressed delegate when the 14th menu button is pressed.
public func handleButton14Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton14Pressed!()
}
}
///Hides the view and calls the handleButton15Pressed delegate when the 15th menu button is pressed.
public func handleButton15Pressed() {
if self.delegate != nil {
hide()
self.delegate!.handleButton15Pressed!()
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 24aa39c9c10f2aea26e3556162471052 | 36.151934 | 166 | 0.642278 | 5.154849 | false | false | false | false |
drewag/Swiftlier | Sources/Swiftlier/Model/Observable/Observable.swift | 1 | 7078 | //
// Observable.swift
// Swiftlier
//
// Created by Andrew J Wagner on 7/17/14.
// Copyright (c) 2014 Drewag LLC. 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.
/**
Options for observing an observable
*/
public struct ObservationOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let initial = ObservationOptions(rawValue: 1 << 0)
public static let onlyOnce = ObservationOptions(rawValue: 1 << 1)
}
/**
Store a value that can be observed by external objects
*/
public final class Observable<T> {
public typealias NewValueHandler = (_ newValue: T) -> ()
public typealias ChangeValueHandler = (_ oldValue: T?, _ newValue: T) -> ()
typealias Handlers = (new: NewValueHandler?, change: ChangeValueHandler?)
typealias HandlerSpec = (options: ObservationOptions, handlers: Handlers)
// MARK: Properties
/**
The current value
*/
public var current : T {
didSet {
var handlersToCall: [Handlers] = []
for observerIndex in Array((0..<self.observers.count).reversed()) {
let observer = self.observers[observerIndex].observer
var handlers = self.observers[observerIndex].handlers
if observer.value != nil {
for handlerIndex in Array((0..<handlers.count).reversed()) {
let handlerSpec = handlers[handlerIndex]
handlersToCall.append(handlerSpec.handlers)
if handlerSpec.options.contains(.onlyOnce) {
handlers.remove(at: handlerIndex)
}
}
if handlers.count == 0 {
self.observers.remove(at: observerIndex)
}
else {
self.observers[observerIndex] = (observer: observer, handlers: handlers)
}
}
else {
if let index = self.indexOfObserver(observer) {
self.observers.remove(at: index)
}
}
}
for handlers in handlersToCall {
handlers.change?(oldValue, self.current)
handlers.new?(self.current)
}
}
}
/**
Whether there is at least 1 current observer
*/
public var hasObserver: Bool {
return observers.count > 0
}
// MARK: Initializers
public init(_ value: T, onHasObserversChanged: ((Bool) -> ())? = nil) {
self.current = value
self.onHasObserverChanged = onHasObserversChanged
}
// MARK: Methods
/**
Add handler for when the value has changed
- parameter observer: observing object to be referenced later to remove the hundler
- parameter handler: callback to be called when value is changed
*/
public func addNewValueObserver(_ observer: AnyObject, handler: @escaping NewValueHandler) {
self.addNewValueObserver(observer, options: [], handler: handler)
}
public func addChangedValueObserver(_ observer: AnyObject, handler: @escaping ChangeValueHandler) {
self.addChangeObserver(observer, options: [], handler: handler)
}
/**
Add handler for when the value has changed
- parameter observer: observing object to be referenced later to remove the hundler
- parameter options: observation options
- parameter handler: callback to be called when value is changed
*/
public func addNewValueObserver(_ observer: AnyObject, options: ObservationOptions, handler: @escaping NewValueHandler) {
let handlers: Handlers = (new: handler, change: nil)
self.addObserver(observer, options: options, handlers: handlers)
}
public func addChangeObserver(_ observer: AnyObject, options: ObservationOptions, handler: @escaping ChangeValueHandler) {
let handlers: Handlers = (new: nil, change: handler)
self.addObserver(observer, options: options, handlers: handlers)
}
/**
Remove all handlers for the given observer
- parameter observer: the observer to remove handlers from
*/
public func removeObserver(_ observer: AnyObject) {
if let index = self.indexOfObserver(observer) {
self.observers.remove(at: index)
if self.observers.count == 0 {
self.onHasObserverChanged?(false)
}
}
}
// MARK: Private Properties
fileprivate var observers: [(observer: WeakWrapper<AnyObject>, handlers: [HandlerSpec])] = []
fileprivate var onHasObserverChanged: ((Bool) -> ())?
}
private extension Observable {
func indexOfObserver(_ observer: AnyObject) -> Int? {
var index: Int = 0
for (possibleObserver, _) in self.observers {
if possibleObserver.value === observer {
return index
}
index += 1
}
return nil
}
func addObserver(_ observer: AnyObject, options: ObservationOptions, handlers: Handlers) {
if let index = self.indexOfObserver(observer) {
// since the observer exists, add the handler to the existing array
self.observers[index].handlers.append((options: options, handlers: handlers))
}
else {
// since the observer does not already exist, add a new tuple with the
// observer and an array with the handler
let oldCount = self.observers.count
self.observers.append((observer: WeakWrapper(observer), handlers: [(options: options, handlers: handlers)]))
if oldCount == 0 {
self.onHasObserverChanged?(true)
}
}
if options.contains(.initial) {
handlers.change?(nil, self.current)
handlers.new?(self.current)
}
}
}
| mit | 514d171d4827ecfe5929f3e7ac1e0dce | 35.864583 | 126 | 0.620514 | 4.973999 | false | false | false | false |
dogsfield/Comrade | Comrade/Comrade/Sources/BatteryUsage/BatteryUsageDataCollector.swift | 1 | 2313 | //
// BatteryUsageDataCollector.swift
// Comrade
//
// Copyright © 2017 Michal Miedlarz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public class BatteryUsageDataCollector: NSObject, DataCollector
{
public let timeInterval: TimeInterval
public let device: UIDevice
public weak var delegate: DataCollectorDelegate?
private var timer: Timer?
init(timeInterval: TimeInterval, device: UIDevice = UIDevice.current)
{
self.timeInterval = timeInterval
self.device = device
}
//MARK: DataCollector protocol implementation
public func isRunning() -> Bool
{
return timer != nil
}
public func stop()
{
clearTimer()
}
public func start()
{
clearTimer()
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(collectBatteryData), userInfo: nil, repeats: true)
}
//MARK: Utils
func collectBatteryData()
{
let chunk = BatteryUsageDataChunk(level: device.batteryLevel, state: device.batteryState)
delegate?.dataCollector(sender: self, handleChunk: chunk, error: nil)
}
private func clearTimer()
{
timer?.invalidate()
timer = nil
}
}
| mit | d36e520a4db57dd319123fa2db10b485 | 32.507246 | 149 | 0.696367 | 4.578218 | false | false | false | false |
cacawai/Tap2Read | tap2read/tap2read/CategoryBarCell.swift | 1 | 1134 | //
// CategoryBarCell.swift
// tap2read
//
// Created by 徐新元 on 14/05/2017.
// Copyright © 2017 Last4 Team. All rights reserved.
//
import UIKit
class CategoryBarCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var emojiLabel: UILabel!
func setHighlighted(isHighlighted: Bool) {
if isHighlighted {
self.layer.borderColor = UIColor.orange.cgColor
self.layer.borderWidth = 2
}else {
self.layer.borderColor = UIColor.darkGray.cgColor
self.layer.borderWidth = 1
}
}
func loadData(category: CategoryModel?) {
if category != nil {
let emojiText = category?.titleWithLanguage(language: ConfigMgr.sharedInstance.currentLanguage())
// if emojiText != nil {
emojiLabel.text = emojiText
emojiLabel.isHidden = false
// imageView.isHidden = true
// }else{
imageView.sd_setImage(with: category?.getImageFileUrl())
// imageView.isHidden = false
// }
}
}
}
| mit | 64606beb16227409dad6a4afc25dcf71 | 27.897436 | 109 | 0.591837 | 4.63786 | false | false | false | false |
robertofrontado/RxSocialConnect-iOS | RxSocialConnectExample/RxSocialConnectExample/Pods/OAuthSwift/Sources/Dictionary+OAuthSwift.swift | 9 | 2123 | //
// Dictionary+OAuthSwift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
extension Dictionary {
func join(_ other: Dictionary) -> Dictionary {
var joinedDictionary = Dictionary()
for (key, value) in self {
joinedDictionary.updateValue(value, forKey: key)
}
for (key, value) in other {
joinedDictionary.updateValue(value, forKey: key)
}
return joinedDictionary
}
func filter(_ predicate: (_ key: Key, _ value: Value) -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for (key, value) in self {
if predicate(key, value) {
filteredDictionary.updateValue(value, forKey: key)
}
}
return filteredDictionary
}
var urlEncodedQuery: String {
var parts = [String]()
for (key, value) in self {
let keyString = "\(key)".urlEncodedString
let valueString = "\(value)".urlEncodedString
let query = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joined(separator: "&")
}
mutating func merge<K, V>(_ dictionaries: Dictionary<K, V>...) {
for dict in dictionaries {
for (key, value) in dict {
self.updateValue(value as! Value, forKey: key as! Key)
}
}
}
func map<K: Hashable, V> (_ transform: (Key, Value) -> (K, V)) -> Dictionary<K, V> {
var results: Dictionary<K, V> = [:]
for k in self.keys {
if let value = self[ k ] {
let (u, w) = transform(k, value)
results.updateValue(w, forKey: u)
}
}
return results
}
}
func +=<K, V> (left: inout [K : V], right: [K : V]) { left.merge(right) }
func +<K, V> (left: [K : V], right: [K : V]) -> [K : V] { return left.join(right) }
func +=<K, V> (left: inout [K : V]?, right: [K : V]) {
if let _ = left { left?.merge(right) } else { left = right }
}
| apache-2.0 | b3ccc6d8236d95461070e0fe11500635 | 26.934211 | 88 | 0.531324 | 3.960821 | false | false | false | false |
jngd/advanced-ios10-training | T6E02/T6E02/ViewController.swift | 1 | 2698 | //
// ViewController.swift
// T6E02
//
// Created by jngd on 18/10/16.
// Copyright © 2016 jngd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/***** Vars ******/
var filePath : NSString = ""
var image : CIImage = CIImage()
/***** Methods *****/
override func viewDidLoad() {
super.viewDidLoad()
filePath = Bundle.main.path(forResource: "photo-peace", ofType: "jpg")! as NSString
let fileNameAndPath = NSURL.fileURL(withPath: filePath as String) as NSURL
image = CIImage(contentsOf:fileNameAndPath as URL)!
let context = CIContext(options: nil)
let options : Dictionary<String, AnyObject> = [CIDetectorAccuracy:
CIDetectorAccuracyHigh as AnyObject]
let detector = CIDetector(ofType: CIDetectorTypeFace, context:
context, options: options)
let features: NSArray = detector!.features(in: image) as NSArray
let imageView = UIImageView(image: UIImage(named: "photo-peace.jpg"))
self.view.addSubview(imageView)
let vistAux = UIView(frame: imageView.frame)
for faceFeature in features {
let smile = (faceFeature as AnyObject).hasSmile
let rightEyeBlinking = (faceFeature as AnyObject).rightEyeClosed
let leftEyeBlinking = (faceFeature as AnyObject).leftEyeClosed
// Create Rectangle in mouth
let mouthPosition = (faceFeature as AnyObject).mouthPosition
let mouthRect = CGRect(origin: mouthPosition!, size: CGSize(width: 100, height: 10))
let mouthView = UIView(frame: mouthRect)
mouthView.backgroundColor = smile! ? UIColor.blue : UIColor.red
vistAux.addSubview(mouthView)
let rightEyePosition = (faceFeature as AnyObject).rightEyePosition
let rEyeRect = CGRect(origin: rightEyePosition!, size: CGSize(width: 50, height: 10))
let rEyeView = UIView(frame: rEyeRect)
rEyeView.backgroundColor = rightEyeBlinking! ? UIColor.yellow : UIColor.cyan
vistAux.addSubview(rEyeView)
let leftEyePosition = (faceFeature as AnyObject).leftEyePosition
let lEyeRect = CGRect(origin: leftEyePosition!, size: CGSize(width: 50, height: 10))
let lEyeView = UIView(frame: lEyeRect)
lEyeView.backgroundColor = leftEyeBlinking! ? UIColor.green : UIColor.brown
vistAux.addSubview(lEyeView)
let faceRect = (faceFeature as AnyObject).bounds
let faceView = UIView(frame: faceRect!)
faceView.layer.borderWidth = 2
faceView.layer.borderColor = UIColor.red.cgColor
let faceWidth:CGFloat = faceRect!.size.width
vistAux.addSubview(faceView)
}
self.view.addSubview(vistAux)
vistAux.transform = CGAffineTransform(scaleX: 1, y: -1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 0cf7fff7147d22b8a67701ef7c15bdb3 | 33.576923 | 88 | 0.736745 | 3.740638 | false | false | false | false |
Touchwonders/Transition | Tests/TransitionTests/TestObjects/TestInteractionController.swift | 1 | 3577 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import TransitionPlus
class TestInteractionController : TransitionInteractionController {
var gestureRecognizer: UIGestureRecognizer = UIPanGestureRecognizer()
weak public var interactiveElementProvider: InteractiveTransitionElementProvider? = nil
var transitionOperation: TransitionOperation = .none
public func operationForInteractiveTransition() -> TransitionOperation {
return transitionOperation
}
var completionPosition: UIViewAnimatingPosition = .end
public func completionPosition(in transitionOperationContext: TransitionOperationContext, fractionComplete: CGFloat) -> UIViewAnimatingPosition {
return completionPosition
}
var progress: TransitionProgress = .fractionComplete(0.0)
public func progress(in transitionOperationContext: TransitionOperationContext) -> TransitionProgress {
return progress
}
/// For deriving stepped progress, you might need to reset the GestureRecognizer's
/// property that was used to calculate the progress.
/// For instance: taking a pan gesture's translation for calculating the progress,
/// and setting it to CGPoint.zero afterwards to reset it for the next call.
/// Expect `progress(in:)` to be called only once every time the gestureRecognizer updates,
/// followed by a single call to resetProgressIfNeeded().
/// The reset step is explicitly separated to avoid unexpected behaviour
/// if the gestureRecognizer is inspected inbetween the `progress(in:)` call and `resetProgressIfNeeded()`.
public func resetProgressIfNeeded(in transitionOperationContext: TransitionOperationContext) {
}
/// interactionStarted() and interactionEnded() can be used to do context-specific setup and cleanup
/// for calculating the progress.
/// Note that the interaction can start as an interruption of a running animation,
/// the interruption being recognized by a different gestureRecognizer (a long-press)
/// than this TransitionInteractionController's gestureRecognizer.
public func interactionStarted(in transitionOperationContext: TransitionOperationContext, gestureRecognizer: UIGestureRecognizer) {
}
public func interactionEnded(in transitionOperationContext: TransitionOperationContext) {
}
}
| mit | a9793cea5a88b92d73bcaf83e15cfff5 | 44.278481 | 149 | 0.740006 | 5.43617 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewModel/RegisterDomainDetailsServiceProxy.swift | 1 | 9795 | import Foundation
import CoreData
/// Protocol for cart response, empty because there are no external details.
protocol CartResponseProtocol {}
extension CartResponse: CartResponseProtocol {}
/// A proxy for being able to use dependency injection for RegisterDomainDetailsViewModel
/// especially for unittest mocking purposes
protocol RegisterDomainDetailsServiceProxyProtocol {
func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void)
func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void)
func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void)
func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void)
func purchaseDomainUsingCredits(
siteID: Int,
domainSuggestion: DomainSuggestion,
domainContactInformation: [String: String],
privacyProtectionEnabled: Bool,
success: @escaping (String) -> Void,
failure: @escaping (Error) -> Void)
func createTemporaryDomainShoppingCart(
siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void)
func createPersistentDomainShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void)
func redeemCartUsingCredits(cart: CartResponseProtocol,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void)
func setPrimaryDomain(
siteID: Int,
domain: String,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void)
}
class RegisterDomainDetailsServiceProxy: RegisterDomainDetailsServiceProxyProtocol {
private lazy var context = {
ContextManager.sharedInstance().mainContext
}()
private lazy var restApi: WordPressComRestApi = {
let account = try? WPAccount.lookupDefaultWordPressComAccount(in: context)
return account?.wordPressComRestApi ?? WordPressComRestApi.defaultApi(oAuthToken: "")
}()
private lazy var domainService = {
DomainsService(managedObjectContext: context, remote: domainsServiceRemote)
}()
private lazy var domainsServiceRemote = {
DomainsServiceRemote(wordPressComRestApi: restApi)
}()
private lazy var transactionsServiceRemote = {
TransactionsServiceRemote(wordPressComRestApi: restApi)
}()
func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.validateDomainContactInformation(
contactInformation: contactInformation,
domainNames: domainNames,
success: success,
failure: failure
)
}
func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.getDomainContactInformation(success: success,
failure: failure)
}
func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void) {
transactionsServiceRemote.getSupportedCountries(success: success,
failure: failure)
}
func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void) {
domainsServiceRemote.getStates(for: countryCode,
success: success,
failure: failure)
}
/// Convenience method to perform a full domain purchase.
///
func purchaseDomainUsingCredits(
siteID: Int,
domainSuggestion: DomainSuggestion,
domainContactInformation: [String: String],
privacyProtectionEnabled: Bool,
success: @escaping (String) -> Void,
failure: @escaping (Error) -> Void) {
let domainName = domainSuggestion.domainName
createTemporaryDomainShoppingCart(
siteID: siteID,
domainSuggestion: domainSuggestion,
privacyProtectionEnabled: privacyProtectionEnabled,
success: { cart in
self.redeemCartUsingCredits(
cart: cart,
domainContactInformation: domainContactInformation,
success: {
self.recordDomainPurchase(
siteID: siteID,
domain: domainName,
isPrimaryDomain: false)
success(domainName)
},
failure: failure)
}, failure: failure)
}
/// Records that a domain purchase took place.
///
func recordDomainPurchase(
siteID: Int,
domain: String,
isPrimaryDomain: Bool) {
let domain = Domain(
domainName: domain,
isPrimaryDomain: isPrimaryDomain,
domainType: .registered)
domainService.create(domain, forSite: siteID)
if let blog = try? Blog.lookup(withID: siteID, in: context) {
blog.hasDomainCredit = false
}
}
func createTemporaryDomainShoppingCart(
siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void) {
transactionsServiceRemote.createTemporaryDomainShoppingCart(siteID: siteID,
domainSuggestion: domainSuggestion,
privacyProtectionEnabled: privacyProtectionEnabled,
success: success,
failure: failure)
}
func createPersistentDomainShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void) {
transactionsServiceRemote.createPersistentDomainShoppingCart(siteID: siteID,
domainSuggestion: domainSuggestion,
privacyProtectionEnabled: privacyProtectionEnabled,
success: success,
failure: failure)
}
func redeemCartUsingCredits(cart: CartResponseProtocol,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
guard let cartResponse = cart as? CartResponse else {
fatalError()
}
transactionsServiceRemote.redeemCartUsingCredits(cart: cartResponse,
domainContactInformation: domainContactInformation,
success: success,
failure: failure)
}
func setPrimaryDomain(siteID: Int,
domain: String,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
if let blog = try? Blog.lookup(withID: siteID, in: context),
let domains = blog.domains as? Set<ManagedDomain>,
let newPrimaryDomain = domains.first(where: { $0.domainName == domain }) {
for existingPrimaryDomain in domains.filter({ $0.isPrimary }) {
existingPrimaryDomain.isPrimary = false
}
newPrimaryDomain.isPrimary = true
ContextManager.shared.save(context)
}
domainsServiceRemote.setPrimaryDomainForSite(siteID: siteID,
domain: domain,
success: success,
failure: failure)
}
}
| gpl-2.0 | bbd03f9d90d2e2cb497e5690f8055b91 | 41.402597 | 120 | 0.531802 | 6.461082 | false | false | false | false |
tattn/TTEventKit | TTEventKit/Example/ViewController.swift | 1 | 2187 | //
// ViewController.swift
// Example
//
// Copyright (c) 2014年 tattn. All rights reserved.
//
import UIKit
import EventKit
import TTEventKit
class ViewController: UIViewController, CalendarDelegate {
@IBOutlet weak var calendarView: CalendarView!
@IBOutlet weak var header: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
calendarView.delegate = self
let year = calendarView.current.year
let month = calendarView.current.month
changedMonth(year, month: month)
EventStore.requestAccess() { (granted, error) in
if !granted {
dispatch_async(dispatch_get_main_queue()) {
let alert = UIAlertView(title: "Error", message: "カレンダーへのアクセスを許可してください。", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "OK")
alert.show()
}
}
}
let ev = EventStore.getEvents(Month(year: 2017, month: 1))
if ev != nil {
for e in ev {
print("Title \(e.title)")
print("startDate: \(e.startDate)")
print("endDate: \(e.endDate)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func tappedAddButton(sender: UIBarButtonItem) {
let event = EventStore.create()
event.title = "元旦"
event.startDate = Month(year: 2017, month: 1).nsdate
event.endDate = event.startDate
event.notes = "メモ"
EventUI.showEditView(event)
}
//=================================
// Calendar Delegate
//=================================
func changedMonth(year: Int, month: Int) {
let monthEn = ["January", "Febrary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
header.title = "\(year) \(monthEn[month - 1])"
}
func selectedDay(dayView: CalendarDayView) {
}
}
| mit | 31649ddba4f3d38bc23ea5bc8b4a63e9 | 26.025316 | 157 | 0.532553 | 4.733925 | false | false | false | false |
PDF417/pdf417-ios | Samples/DirectAPI-sample-Swift/DirectAPI-sample-Swift/ViewController.swift | 1 | 3643 | //
// ViewController.swift
// DirectAPI-sample-Swift
//
// Created by Jura Skrlec on 10/05/2018.
// Copyright © 2018 Microblink. All rights reserved.
//
import UIKit
import Pdf417Mobi
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MBBScanningRecognizerRunnerDelegate {
var recognizerRunner: MBBRecognizerRunner?
var barcodeRecognizer: MBBBarcodeRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
setupRecognizerRunner()
}
@IBAction func openImagePicker(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.cameraDevice = .rear
// Displays a control that allows the user to choose only photos
imagePicker.mediaTypes = [kUTTypeImage as String]
// Hides the controls for moving & scaling pictures, or for trimming movies.
imagePicker.allowsEditing = false
// Shows default camera control overlay over camera preview.
imagePicker.showsCameraControls = true
// set delegate
imagePicker.delegate = self
present(imagePicker, animated: true) {() -> Void in }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String
if CFStringCompare(mediaType as CFString?, kUTTypeImage, CFStringCompareFlags(rawValue: 9)) == .compareEqualTo {
let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
processImageRunner(originalImage)
}
picker.dismiss(animated: true, completion: nil)
}
func setupRecognizerRunner() {
var recognizers = [MBBRecognizer]()
barcodeRecognizer = MBBBarcodeRecognizer()
barcodeRecognizer?.scanPdf417 = true
recognizers.append(barcodeRecognizer!)
let recognizerCollection = MBBRecognizerCollection(recognizers: recognizers)
recognizerRunner = MBBRecognizerRunner(recognizerCollection: recognizerCollection)
recognizerRunner?.scanningRecognizerRunnerDelegate = self
}
func processImageRunner(_ originalImage: UIImage?) {
var image: MBBImage? = nil
if let anImage = originalImage {
image = MBBImage(uiImage: anImage)
}
image?.cameraFrame = true
image?.orientation = .left
let _serialQueue = DispatchQueue(label: "com.microblink.DirectAPI-sample-swift")
_serialQueue.async(execute: {() -> Void in
self.recognizerRunner?.processImage(image!)
})
}
func recognizerRunner(_ recognizerRunner: MBBRecognizerRunner, didFinishScanningWith state: MBBRecognizerResultState) {
DispatchQueue.main.async(execute: {() -> Void in
let title = "PDF417"
// Save the string representation of the code
let message = self.barcodeRecognizer?.result.stringData!
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
self.dismiss(animated: true) {() -> Void in }
})
alertController.addAction(okAction)
self.present(alertController, animated: true) {() -> Void in }
})
}
}
| apache-2.0 | 4652945b0dad2c2768fa07a6c6561304 | 38.586957 | 144 | 0.66749 | 5.309038 | false | false | false | false |
coderLL/DYTV | DYTV/DYTV/Classes/Tools/NetworkTools.swift | 1 | 968 | //
// NetworkTools.swift
// DYTV
//
// Created by coderLL on 16/10/1.
// Copyright © 2016年 coderLL. All rights reserved.
//
import UIKit
import Alamofire
// MARK:- 方法枚举类型
enum MethodType {
case get
case post
}
// MARK:- 网络请求工具类
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback: @escaping (_ result : Any) -> ()) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error)
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| mit | 65d703995d4cc718809725764e6cd865 | 23.916667 | 157 | 0.574136 | 4.191589 | false | false | false | false |
ziligy/SnapLocation | SnapLocation/JGTapButton.swift | 1 | 7788 | //
// JGTapButton.swift
//
// Created by Jeff on 8/20/15.
// Copyright © 2015 Jeff Greenberg. All rights reserved.
//
import UIKit
enum TapButtonShape {
case Round
case Rectangle
}
enum TapButtonStyle {
case Raised
case Flat
}
@IBDesignable
public class JGTapButton: UIButton {
// MARK: Inspectables
// select round or rectangle button shape
@IBInspectable public var round: Bool = true {
didSet {
buttonShape = (round ? .Round : .Rectangle)
}
}
// select raised or flat style
@IBInspectable public var raised: Bool = true {
didSet {
buttonStyle = (raised ? .Raised : .Flat)
}
}
// set title caption for button
@IBInspectable public var title: String = "JGTapButton" {
didSet {
buttonTitle = title
}
}
// optional button image
@IBInspectable public var image: UIImage=UIImage() {
didSet {
iconImageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))
iconImageView.image = self.image
}
}
// main background button color
@IBInspectable public var mainColor: UIColor = UIColor.redColor() {
didSet {
buttonColor = mainColor
}
}
// title font size
@IBInspectable public var fontsize: CGFloat = 22.0 {
didSet {
titleFontSize = fontsize
}
}
@IBInspectable public var fontColor: UIColor = UIColor.whiteColor()
// MARK: Private variables
private var buttonShape = TapButtonShape.Round
private var buttonStyle = TapButtonStyle.Flat
private var buttonTitle = ""
private var buttonColor = UIColor.redColor()
private var titleFontSize: CGFloat = 22.0
private var tapButtonFrame = CGRectMake(0, 0, 100, 100)
// outline shape of button from draw
private var outlinePath = UIBezierPath()
// variables for glow animation
private let tapGlowView = UIView()
private let tapGlowBackgroundView = UIView()
private var tapGlowColor = UIColor(white: 0.9, alpha: 1)
private var tapGlowBackgroundColor = UIColor(white: 0.95, alpha: 1)
private var tapGlowMask: CAShapeLayer? {
get {
let maskLayer = CAShapeLayer()
maskLayer.path = outlinePath.CGPath
return maskLayer
}
}
// optional image for
private var iconImageView = UIImageView(frame: CGRectMake(0, 0, 40, 40))
// MARK: Initialize
func initMaster() {
self.backgroundColor = UIColor.clearColor()
self.addSubview(iconImageView)
}
override init(frame: CGRect) {
super.init(frame: frame)
initMaster()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initMaster()
}
override public func prepareForInterfaceBuilder() {
invalidateIntrinsicContentSize()
self.backgroundColor = UIColor.clearColor()
}
// MARK: Layout
override public func layoutSubviews() {
super.layoutSubviews()
iconImageView.layer.mask = tapGlowMask
tapGlowBackgroundView.layer.mask = tapGlowMask
}
// override intrinsic size for uibutton
public override func intrinsicContentSize() -> CGSize {
return bounds.size
}
// MARK: draw
override public func drawRect(rect: CGRect) {
outlinePath = drawTapButton(buttonShape, buttonTitle: buttonTitle, fontsize: titleFontSize)
tapGlowSetup()
}
private func tapGlowSetup() {
tapGlowBackgroundView.backgroundColor = tapGlowBackgroundColor
tapGlowBackgroundView.frame = bounds
layer.addSublayer(tapGlowBackgroundView.layer)
tapGlowBackgroundView.layer.addSublayer(tapGlowView.layer)
tapGlowBackgroundView.alpha = 0
}
private func drawTapButton(buttonShape: TapButtonShape, buttonTitle: String, fontsize: CGFloat) -> UIBezierPath {
var bezierPath: UIBezierPath!
if buttonStyle == .Raised {
tapButtonFrame = CGRectMake(1, 1, CGRectGetWidth(self.bounds) - 2, CGRectGetHeight(self.bounds) - 2)
} else {
tapButtonFrame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))
}
let context = UIGraphicsGetCurrentContext()
if buttonShape == .Round {
bezierPath = UIBezierPath(ovalInRect: tapButtonFrame)
} else {
bezierPath = UIBezierPath(rect: tapButtonFrame)
}
buttonColor.setFill()
bezierPath.fill()
let shadow = UIColor.blackColor().CGColor
let shadowOffset = CGSizeMake(3.1, 3.1)
let shadowBlurRadius: CGFloat = 7
if buttonStyle == .Raised {
CGContextSaveGState(context)
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow)
fontColor.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
CGContextRestoreGState(context)
}
// MARK: Title Text
if image == "" || iconImageView.image == nil {
let buttonTitleTextContent = NSString(string: buttonTitle)
CGContextSaveGState(context)
if buttonStyle == .Raised {
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow)
}
let buttonTitleStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
buttonTitleStyle.alignment = NSTextAlignment.Center
let buttonTitleFontAttributes = [NSFontAttributeName: UIFont(name: "AppleSDGothicNeo-Regular", size: fontsize)!, NSForegroundColorAttributeName: fontColor, NSParagraphStyleAttributeName: buttonTitleStyle]
let buttonTitleTextHeight: CGFloat = buttonTitleTextContent.boundingRectWithSize(CGSizeMake(tapButtonFrame.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: buttonTitleFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, tapButtonFrame);
buttonTitleTextContent.drawInRect(CGRectMake(tapButtonFrame.minX, tapButtonFrame.minY + (tapButtonFrame.height - buttonTitleTextHeight) / 2, tapButtonFrame.width, buttonTitleTextHeight), withAttributes: buttonTitleFontAttributes)
CGContextRestoreGState(context)
CGContextRestoreGState(context)
}
return bezierPath
}
// MARK: Tap events
override public func beginTrackingWithTouch(touch: UITouch,
withEvent event: UIEvent?) -> Bool {
UIView.animateWithDuration(0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: nil)
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override public func endTrackingWithTouch(touch: UITouch?,
withEvent event: UIEvent?) {
super.endTrackingWithTouch(touch, withEvent: event)
UIView.animateWithDuration(0.1, animations: {
self.tapGlowBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animateWithDuration(0.6 , animations: {
self.tapGlowBackgroundView.alpha = 0
}, completion: nil)
})
}
}
| mit | 21432b153ee65bd9b905c8382ff01045 | 31.177686 | 265 | 0.620907 | 5.479944 | false | false | false | false |
dmitryrybakov/19test | 19test/ComicDetailsViewController/ComicsPageViewController.swift | 1 | 3117 | //
// ComicsPageViewController.swift
// 19test
//
// Created by Dmitry on 12.05.16.
// Copyright © 2016 Dmitry Rybakov. All rights reserved.
//
import Foundation
class ComicsPageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
var model:Array<MarvelComic>? = []
var startPageIndex:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
if let modelObject = self.model {
if self.startPageIndex >= modelObject.count {
self.startPageIndex = 0
}
self.setViewControllers([self.viewControllerAtIndex(startPageIndex)],
direction: UIPageViewControllerNavigationDirection.Forward,
animated: true,
completion: nil)
}
self.dataSource = self
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! ComicDetailsViewController).pageIndex
if index == 0 || index == NSNotFound {
return nil
}
index -= 1
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var retValue:UIViewController? = nil
if let modelObject = self.model {
var index = (viewController as! ComicDetailsViewController).pageIndex
if index != NSNotFound {
index += 1
if index < modelObject.count {
retValue = self.viewControllerAtIndex(index)
}
}
}
return retValue
}
func viewControllerAtIndex(index: Int) -> UIViewController {
let comicDetails = self.storyboard?.instantiateViewControllerWithIdentifier("ComicDetailsViewController") as! ComicDetailsViewController
comicDetails.pageIndex = index
if let modelObject = self.model {
if index < modelObject.count {
let comicObject = modelObject[index]
let imageURL = comicObject.getImageURLWithSize(MarvelImageSize.portrait_uncanny)
if let URLString = imageURL {
comicDetails.imageURL = URLString
}
comicDetails.comicTitle = comicObject.title
}
}
return comicDetails
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
if let modelObject = self.model {
return modelObject.count
}
return 0
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.startPageIndex
}
}
| artistic-2.0 | 0b0163605e3db37016e003764b4a5463 | 32.148936 | 161 | 0.599487 | 6.359184 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Nodes/Effects/Filters/Moog Ladder/AKMoogLadder.swift | 1 | 5255 | //
// AKMoogLadder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Moog Ladder is an new digital implementation of the Moog ladder filter based
/// on the work of Antti Huovilainen, described in the paper "Non-Linear Digital
/// Implementation of the Moog Ladder Filter" (Proceedings of DaFX04, Univ of
/// Napoli). This implementation is probably a more accurate digital
/// representation of the original analogue filter.
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Filter cutoff frequency.
/// - parameter resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
///
public class AKMoogLadder: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKMoogLadderAudioUnit?
internal var token: AUParameterObserverToken?
private var cutoffFrequencyParameter: AUParameter?
private var resonanceParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Filter cutoff frequency.
public var cutoffFrequency: Double = 1000 {
willSet {
if cutoffFrequency != newValue {
if internalAU!.isSetUp() {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
public var resonance: Double = 0.5 {
willSet {
if resonance != newValue {
if internalAU!.isSetUp() {
resonanceParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.resonance = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Filter cutoff frequency.
/// - parameter resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 1000,
resonance: Double = 0.5) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x6d676c64 /*'mgld'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKMoogLadderAudioUnit.self,
asComponentDescription: description,
name: "Local AKMoogLadder",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKMoogLadderAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter
resonanceParameter = tree.valueForKey("resonance") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.cutoffFrequencyParameter!.address {
self.cutoffFrequency = Double(value)
} else if address == self.resonanceParameter!.address {
self.resonance = Double(value)
}
}
}
internalAU?.cutoffFrequency = Float(cutoffFrequency)
internalAU?.resonance = Float(resonance)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | fc24f684598284c39beee7e5cef46ff4 | 35.241379 | 190 | 0.63254 | 5.451245 | false | false | false | false |
adow/AWebImage | AWebImageDemo/AppDelegate.swift | 1 | 3482 | //
// AppDelegate.swift
// AWebImage
//
// Created by 秦 道平 on 16/6/1.
// Copyright © 2016年 秦 道平. All rights reserved.
//
import UIKit
import AWebImage
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UINavigationBar.appearance().tintColor = UIColor.lightGray
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage.aw_imageWithColor(UIColor.white),
for: UIBarMetrics.default)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.lightGray,]
// self.testImageProcess()
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:.
}
}
extension AppDelegate {
// func testImageProcess() {
// let inputImage = UIImage(named: "test2")!
// let process = AWebCropImageProcess(targetWidth: 750.0, targetHeight: 187.5)
// let outputImage = process.make(fromInputImage: inputImage)
// debugPrint(outputImage)
// }
}
extension UIImage {
/// 用颜色来创建一个图片
class func aw_imageWithColor(_ color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mit | 4aa49dc1f8e04a038f1ef7ca04aed25e | 43.766234 | 285 | 0.710183 | 5.327666 | false | false | false | false |
johnoppenheimer/epiquote-ios | EpiquoteSwift/views/ContextCollectionViewCell.swift | 1 | 1314 | //
// ContextCollectionViewCell.swift
// EpiquoteSwift
//
// Created by Maxime Cattet on 17/11/2016.
//
//
import UIKit
import PureLayout
class ContextCollectionViewCell: UICollectionViewCell {
lazy var textLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12.0)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = UIColor.darkGray
self.contentView.addSubview(label)
return label
}()
lazy var colorBlockView: UIView = {
let view = UIView()
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 5)
self.textLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: 5)
self.textLabel.autoPinEdge(toSuperviewEdge: .left, withInset: 10)
self.textLabel.autoPinEdge(toSuperviewEdge: .right, withInset: 10)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .left)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .top)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .bottom)
self.colorBlockView.autoSetDimension(.width, toSize: 5)
}
}
| mit | 4d0b05076523425c60ab1b16eb355811 | 30.285714 | 74 | 0.665906 | 4.726619 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Sources/iOS+tvOS/Extensions/BlueprintLayout+iOS+tvOS.swift | 1 | 930 | import UIKit
extension BlueprintLayout {
open override func layoutAttributesForSupplementaryView(ofKind elementKind: String,
at indexPath: IndexPath) -> LayoutAttributes? {
if indexPathIsOutOfBounds(indexPath, for: cachedSupplementaryAttributesBySection) {
return nil
}
let sectionAttributes = cachedSupplementaryAttributesBySection[indexPath.section]
var layoutAttributesResult: LayoutAttributes? = nil
switch elementKind {
case CollectionView.collectionViewHeaderType:
layoutAttributesResult = sectionAttributes.filter({ $0.representedElementCategory == .supplementaryView }).first
case CollectionView.collectionViewFooterType:
layoutAttributesResult = sectionAttributes.filter({ $0.representedElementCategory == .supplementaryView }).last
default:
return nil
}
return layoutAttributesResult
}
}
| mit | b7943bdf675c3ccdc1795641d5a39bcd | 37.75 | 118 | 0.730108 | 6.241611 | false | false | false | false |
wangchong321/tucao | WCWeiBo/WCWeiBo/Classes/Tools/SQLiteManager.swift | 1 | 9366 | //
// SQLiteManager.swift
// 01-SQLite演练
//
// Created by apple on 15/5/26.
// Copyright (c) 2015年 heima. All rights reserved.
//
import Foundation
class SQLiteManager {
// swift 创建数据库上下文变量
var db: COpaquePointer = nil
// swift 调用打开数据库的方法传递参数的类型设定
private func test() {
var db: COpaquePointer = nil
var fileName = "111".cStringUsingEncoding(NSUTF8StringEncoding)!
sqlite3_open(fileName, &db)
}
// 1> 私有静态成员
static private let instance = SQLiteManager()
// 2> 公共的类函数,作为全局访问点
class func sharedSQLManager() -> SQLiteManager {
return instance
}
/// 打开数据库
func openDB(dbName: String) -> Bool {
// 数据库文件可以保存在沙盒的 document / cache 目录中
var filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
filePath = filePath.stringByAppendingPathComponent(dbName)
// 转换成 C 语言格式的字符串
let path = filePath.cStringUsingEncoding(NSUTF8StringEncoding)!
/**
参数:
1. 文件路径:完整的 C 语言格式的路径字符串 Int8, Char, Byte, char *
2. 数据库句柄,数据库指针地址,后续通过句柄操作数据库
如果数据库已经存在,就会直接打开
如果数据库不存在,会新建之后再打开
*/
if sqlite3_open(path, &db) != SQLITE_OK {
println("打开数据失败")
return false
}
println("打开数据库成功 \(filePath)")
// 创建数据表
let result = createTable()
let tip = result ? "创表成功" : "创表失败"
println(tip)
return result
}
/// 开启事务
func beginTransction() -> Bool {
return execSQL("BEGIN TRANSACTION;")
}
/// 提交事务
func commitTransction() -> Bool {
return execSQL("COMMIT TRANSACTION;")
}
/// 回滚事务
func rollbackTransction() -> Bool {
return execSQL("ROLLBACK TRANSACTION;")
}
/// 批量更新
func execUpdate(sql: String, params: CVarArgType...) -> Bool {
// INSERT INTO T_Person (name, age, height) VALUES (?, ?, ?);
let cSQL = sql.cStringUsingEncoding(NSUTF8StringEncoding)!
// 1. 准备语句
var stmt: COpaquePointer = nil
// 准备批量更新语句的结果
var result = true
if sqlite3_prepare_v2(db, cSQL, -1, &stmt, nil) == SQLITE_OK {
// 语句已经编译完成,可以绑定参数,需要针对不同的数据类型
// 2. 判断参数的属性
// ** bind 函数的第二个参数,是对应的 ? 参数的索引
// 索引值是从 `1` 开始
var index: Int32 = 1
for obj in params {
if obj is Int {
sqlite3_bind_int64(stmt, index, sqlite3_int64(obj as! Int))
} else if obj is Double {
sqlite3_bind_double(stmt, index, obj as! Double)
} else if obj is String {
// println("String \(obj)")
// 将 obj 转换成 c 语言的 char *
let cStr = (obj as! String).cStringUsingEncoding(NSUTF8StringEncoding)!
/**
3. c 语言字符串的地址 char *
4. 字符串长度,可以传入 -1
5. 是对字符串的引用方式,SQLITE_TRANSIENT 让 SQLite copy 字符串,以保证字符串的内容正确
之所以有的时候,打断点跟踪执行是正确的,是因为程序在断电的地方为了方便程序员调试
会记录当前所有变量的值
*/
sqlite3_bind_text(stmt, index, cStr, -1, SQLITE_TRANSIENT)
} else if obj is NSNull {
sqlite3_bind_null(stmt, index)
}
index++
}
// 3. 执行语句 - 需要注意更新记录返回的结果是 `DONE`
if sqlite3_step(stmt) != SQLITE_DONE {
println("插入数据错误!")
result = false
}
// 4. 复位语句
if sqlite3_reset(stmt) != SQLITE_OK {
println("复位语句错误")
result = false
}
}
// 5. 释放语句
sqlite3_finalize(stmt)
// 6. 返回结果
return result
}
/// 执行 SQL,返回?数组
func execRecordSet(sql: String) -> [[String: AnyObject]]? {
// 转换成 C 语言的字符串
let cSQL = sql.cStringUsingEncoding(NSUTF8StringEncoding)!
// 1. 准备 SQL,预先编译 SQL
/**
参数
1. 数据库句柄
2. SQL
3. 以字节为单位的 SQL 语句的长度,使用 -1 可以自动计算
4. 编译后的语句句柄,后续 step 操作都依赖这个句柄,需要释放
5. 未使用的指针,nil
*/
var stmt: COpaquePointer = nil
// 定义结果数组
var list: [[String: AnyObject]]?
if sqlite3_prepare_v2(db, cSQL, -1, &stmt, nil) == SQLITE_OK {
// 2. 如果准备 OK,sqlite3_step 逐行取出记录,while
// 如果取到一行,就执行
// 实例化结果字典数组
list = [[String: AnyObject]]()
while sqlite3_step(stmt) == SQLITE_ROW {
list!.append(recordDict(stmt))
}
}
// 3. 释放语句句柄
sqlite3_finalize(stmt)
return list
}
/// 从指令中提取一条完整的记录字典
private func recordDict(stmt: COpaquePointer) -> [String: AnyObject] {
// 3. 一行数据,包含了指定查询的所有字段,name, age, height
// 1> 获得当前行的列数
let colCount = sqlite3_column_count(stmt)
// 2> 希望知道所有列的信息 -> 遍历所有列
// 创建一个字典,记录当前行的所有信息
var recordDict = [String: AnyObject]()
// 遍历列获取详细信息
for i in 0..<colCount {
// 获取到对应的列名
let cname = sqlite3_column_name(stmt, i)
// 转换名称
let colName = String(CString: cname, encoding: NSUTF8StringEncoding)!
// 获取到列的字段类型
let colType = sqlite3_column_type(stmt, i)
// 根据类型来获取不同类型的结果
switch colType {
case SQLITE_INTEGER:
let iNum = Int(sqlite3_column_int64(stmt, i))
recordDict[colName] = iNum
case SQLITE_FLOAT:
let dNum = sqlite3_column_double(stmt, i)
recordDict[colName] = dNum
case SQLITE3_TEXT:
let cStr = UnsafePointer<Int8>(sqlite3_column_text(stmt, i))
let str = String(CString: cStr, encoding: NSUTF8StringEncoding)
recordDict[colName] = str
case SQLITE_NULL:
recordDict[colName] = NSNull()
default:
println("不支持的数据类型")
}
}
// 返回完整字典
return recordDict
}
/// 执行 SQL 语句
func execSQL(sql: String) -> Bool {
let cSQL = sql.cStringUsingEncoding(NSUTF8StringEncoding)!
/**
参数
1. 数据库句柄
2. C 语言的 SQL 语句 (evaluated)
3. 回调 nil
4. 回调函数的第一个参数 nil
5. 错误信息 nil
*/
return sqlite3_exec(db, cSQL, nil, nil, nil) == SQLITE_OK
}
/**
创建数据表:只需要执行一次
目的:就是创建数据表,以便保存数据
提示:SQL可以从 navicat 中粘贴
1> 替换 "
2> IF NOT EXISTS
3> 在末尾添加 \n
创表的动作,就是执行一条 SQL 语句
*/
private func createTable() -> Bool {
// 1. 从文件读取 SQL
let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
let data = NSData(contentsOfFile: path)!
// 将二进制数据转换成 sql 字符串
let sql = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
println(sql)
// 2. 执行 SQL
return execSQL(sql)
}
/**
typedef void (*sqlite3_destructor_type)(void*);
#define SQLITE_STATIC ((sqlite3_destructor_type)0)
#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
*/
private let SQLITE_TRANSIENT = sqlite3_destructor_type(COpaquePointer(bitPattern: -1))
}
| mit | 1b4556ccb507589bfcfcb03618a9b9c1 | 29.264591 | 160 | 0.501929 | 4.074384 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/TimestreamWrite/TimestreamWrite_Shapes.swift | 1 | 34973 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension TimestreamWrite {
// MARK: Enums
public enum DimensionValueType: String, CustomStringConvertible, Codable {
case varchar = "VARCHAR"
public var description: String { return self.rawValue }
}
public enum MeasureValueType: String, CustomStringConvertible, Codable {
case bigint = "BIGINT"
case boolean = "BOOLEAN"
case double = "DOUBLE"
case varchar = "VARCHAR"
public var description: String { return self.rawValue }
}
public enum TableStatus: String, CustomStringConvertible, Codable {
case active = "ACTIVE"
case deleting = "DELETING"
public var description: String { return self.rawValue }
}
public enum TimeUnit: String, CustomStringConvertible, Codable {
case microseconds = "MICROSECONDS"
case milliseconds = "MILLISECONDS"
case nanoseconds = "NANOSECONDS"
case seconds = "SECONDS"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct CreateDatabaseRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String
/// The KMS key for the database. If the KMS key is not specified, the database will be encrypted with a Timestream managed KMS key located in your account. Refer to AWS managed KMS keys for more info.
public let kmsKeyId: String?
/// A list of key-value pairs to label the table.
public let tags: [Tag]?
public init(databaseName: String, kmsKeyId: String? = nil, tags: [Tag]? = nil) {
self.databaseName = databaseName
self.kmsKeyId = kmsKeyId
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 2048)
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1)
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
try self.validate(self.tags, name: "tags", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case kmsKeyId = "KmsKeyId"
case tags = "Tags"
}
}
public struct CreateDatabaseResponse: AWSDecodableShape {
/// The newly created Timestream database.
public let database: Database?
public init(database: Database? = nil) {
self.database = database
}
private enum CodingKeys: String, CodingKey {
case database = "Database"
}
}
public struct CreateTableRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String
/// The duration for which your time series data must be stored in the memory store and the magnetic store.
public let retentionProperties: RetentionProperties?
/// The name of the Timestream table.
public let tableName: String
/// A list of key-value pairs to label the table.
public let tags: [Tag]?
public init(databaseName: String, retentionProperties: RetentionProperties? = nil, tableName: String, tags: [Tag]? = nil) {
self.databaseName = databaseName
self.retentionProperties = retentionProperties
self.tableName = tableName
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.retentionProperties?.validate(name: "\(name).retentionProperties")
try self.validate(self.tableName, name: "tableName", parent: name, max: 64)
try self.validate(self.tableName, name: "tableName", parent: name, min: 3)
try self.validate(self.tableName, name: "tableName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
try self.validate(self.tags, name: "tags", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case retentionProperties = "RetentionProperties"
case tableName = "TableName"
case tags = "Tags"
}
}
public struct CreateTableResponse: AWSDecodableShape {
/// The newly created Timestream table.
public let table: Table?
public init(table: Table? = nil) {
self.table = table
}
private enum CodingKeys: String, CodingKey {
case table = "Table"
}
}
public struct Database: AWSDecodableShape {
/// The Amazon Resource Name that uniquely identifies this database.
public let arn: String?
/// The time when the database was created, calculated from the Unix epoch time.
public let creationTime: Date?
/// The name of the Timestream database.
public let databaseName: String?
/// The identifier of the KMS key used to encrypt the data stored in the database.
public let kmsKeyId: String?
/// The last time that this database was updated.
public let lastUpdatedTime: Date?
/// The total number of tables found within a Timestream database.
public let tableCount: Int64?
public init(arn: String? = nil, creationTime: Date? = nil, databaseName: String? = nil, kmsKeyId: String? = nil, lastUpdatedTime: Date? = nil, tableCount: Int64? = nil) {
self.arn = arn
self.creationTime = creationTime
self.databaseName = databaseName
self.kmsKeyId = kmsKeyId
self.lastUpdatedTime = lastUpdatedTime
self.tableCount = tableCount
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case creationTime = "CreationTime"
case databaseName = "DatabaseName"
case kmsKeyId = "KmsKeyId"
case lastUpdatedTime = "LastUpdatedTime"
case tableCount = "TableCount"
}
}
public struct DeleteDatabaseRequest: AWSEncodableShape {
/// The name of the Timestream database to be deleted.
public let databaseName: String
public init(databaseName: String) {
self.databaseName = databaseName
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
}
}
public struct DeleteTableRequest: AWSEncodableShape {
/// The name of the database where the Timestream database is to be deleted.
public let databaseName: String
/// The name of the Timestream table to be deleted.
public let tableName: String
public init(databaseName: String, tableName: String) {
self.databaseName = databaseName
self.tableName = tableName
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.validate(self.tableName, name: "tableName", parent: name, max: 64)
try self.validate(self.tableName, name: "tableName", parent: name, min: 3)
try self.validate(self.tableName, name: "tableName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case tableName = "TableName"
}
}
public struct DescribeDatabaseRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String
public init(databaseName: String) {
self.databaseName = databaseName
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
}
}
public struct DescribeDatabaseResponse: AWSDecodableShape {
/// The name of the Timestream table.
public let database: Database?
public init(database: Database? = nil) {
self.database = database
}
private enum CodingKeys: String, CodingKey {
case database = "Database"
}
}
public struct DescribeEndpointsRequest: AWSEncodableShape {
public init() {}
}
public struct DescribeEndpointsResponse: AWSDecodableShape {
/// An Endpoints object is returned when a DescribeEndpoints request is made.
public let endpoints: [Endpoint]
public init(endpoints: [Endpoint]) {
self.endpoints = endpoints
}
private enum CodingKeys: String, CodingKey {
case endpoints = "Endpoints"
}
}
public struct DescribeTableRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String
/// The name of the Timestream table.
public let tableName: String
public init(databaseName: String, tableName: String) {
self.databaseName = databaseName
self.tableName = tableName
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.validate(self.tableName, name: "tableName", parent: name, max: 64)
try self.validate(self.tableName, name: "tableName", parent: name, min: 3)
try self.validate(self.tableName, name: "tableName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case tableName = "TableName"
}
}
public struct DescribeTableResponse: AWSDecodableShape {
/// The Timestream table.
public let table: Table?
public init(table: Table? = nil) {
self.table = table
}
private enum CodingKeys: String, CodingKey {
case table = "Table"
}
}
public struct Dimension: AWSEncodableShape {
/// The data type of the dimension for the time series data point.
public let dimensionValueType: DimensionValueType?
/// Dimension represents the meta data attributes of the time series. For example, the name and availability zone of an EC2 instance or the name of the manufacturer of a wind turbine are dimensions. Dimension names can only contain alphanumeric characters and underscores. Dimension names cannot end with an underscore.
public let name: String
/// The value of the dimension.
public let value: String
public init(dimensionValueType: DimensionValueType? = nil, name: String, value: String) {
self.dimensionValueType = dimensionValueType
self.name = name
self.value = value
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 256)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.value, name: "value", parent: name, max: 2048)
try self.validate(self.value, name: "value", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case dimensionValueType = "DimensionValueType"
case name = "Name"
case value = "Value"
}
}
public struct Endpoint: AWSDecodableShape {
/// An endpoint address.
public let address: String
/// The TTL for the endpoint, in minutes.
public let cachePeriodInMinutes: Int64
public init(address: String, cachePeriodInMinutes: Int64) {
self.address = address
self.cachePeriodInMinutes = cachePeriodInMinutes
}
private enum CodingKeys: String, CodingKey {
case address = "Address"
case cachePeriodInMinutes = "CachePeriodInMinutes"
}
}
public struct ListDatabasesRequest: AWSEncodableShape {
/// The total number of items to return in the output. If the total number of items available is more than the value specified, a NextToken is provided in the output. To resume pagination, provide the NextToken value as argument of a subsequent API invocation.
public let maxResults: Int?
/// The pagination token. To resume pagination, provide the NextToken value as argument of a subsequent API invocation.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 20)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListDatabasesResponse: AWSDecodableShape {
/// A list of database names.
public let databases: [Database]?
/// The pagination token. This parameter is returned when the response is truncated.
public let nextToken: String?
public init(databases: [Database]? = nil, nextToken: String? = nil) {
self.databases = databases
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case databases = "Databases"
case nextToken = "NextToken"
}
}
public struct ListTablesRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String?
/// The total number of items to return in the output. If the total number of items available is more than the value specified, a NextToken is provided in the output. To resume pagination, provide the NextToken value as argument of a subsequent API invocation.
public let maxResults: Int?
/// The pagination token. To resume pagination, provide the NextToken value as argument of a subsequent API invocation.
public let nextToken: String?
public init(databaseName: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.databaseName = databaseName
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 20)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListTablesResponse: AWSDecodableShape {
/// A token to specify where to start paginating. This is the NextToken from a previously truncated response.
public let nextToken: String?
/// A list of tables.
public let tables: [Table]?
public init(nextToken: String? = nil, tables: [Table]? = nil) {
self.nextToken = nextToken
self.tables = tables
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case tables = "Tables"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
/// The Timestream resource with tags to be listed. This value is an Amazon Resource Name (ARN).
public let resourceARN: String
public init(resourceARN: String) {
self.resourceARN = resourceARN
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// The tags currently associated with the Timestream resource.
public let tags: [Tag]?
public init(tags: [Tag]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct Record: AWSEncodableShape {
/// Contains the list of dimensions for time series data points.
public let dimensions: [Dimension]?
/// Measure represents the data attribute of the time series. For example, the CPU utilization of an EC2 instance or the RPM of a wind turbine are measures.
public let measureName: String?
/// Contains the measure value for the time series data point.
public let measureValue: String?
/// Contains the data type of the measure value for the time series data point.
public let measureValueType: MeasureValueType?
/// Contains the time at which the measure value for the data point was collected.
public let time: String?
/// The granularity of the timestamp unit. It indicates if the time value is in seconds, milliseconds, nanoseconds or other supported values.
public let timeUnit: TimeUnit?
public init(dimensions: [Dimension]? = nil, measureName: String? = nil, measureValue: String? = nil, measureValueType: MeasureValueType? = nil, time: String? = nil, timeUnit: TimeUnit? = nil) {
self.dimensions = dimensions
self.measureName = measureName
self.measureValue = measureValue
self.measureValueType = measureValueType
self.time = time
self.timeUnit = timeUnit
}
public func validate(name: String) throws {
try self.dimensions?.forEach {
try $0.validate(name: "\(name).dimensions[]")
}
try self.validate(self.dimensions, name: "dimensions", parent: name, max: 128)
try self.validate(self.measureName, name: "measureName", parent: name, max: 256)
try self.validate(self.measureName, name: "measureName", parent: name, min: 1)
try self.validate(self.measureValue, name: "measureValue", parent: name, max: 2048)
try self.validate(self.measureValue, name: "measureValue", parent: name, min: 1)
try self.validate(self.time, name: "time", parent: name, max: 256)
try self.validate(self.time, name: "time", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case dimensions = "Dimensions"
case measureName = "MeasureName"
case measureValue = "MeasureValue"
case measureValueType = "MeasureValueType"
case time = "Time"
case timeUnit = "TimeUnit"
}
}
public struct RetentionProperties: AWSEncodableShape & AWSDecodableShape {
/// The duration for which data must be stored in the magnetic store.
public let magneticStoreRetentionPeriodInDays: Int64
/// The duration for which data must be stored in the memory store.
public let memoryStoreRetentionPeriodInHours: Int64
public init(magneticStoreRetentionPeriodInDays: Int64, memoryStoreRetentionPeriodInHours: Int64) {
self.magneticStoreRetentionPeriodInDays = magneticStoreRetentionPeriodInDays
self.memoryStoreRetentionPeriodInHours = memoryStoreRetentionPeriodInHours
}
public func validate(name: String) throws {
try self.validate(self.magneticStoreRetentionPeriodInDays, name: "magneticStoreRetentionPeriodInDays", parent: name, max: 73000)
try self.validate(self.magneticStoreRetentionPeriodInDays, name: "magneticStoreRetentionPeriodInDays", parent: name, min: 1)
try self.validate(self.memoryStoreRetentionPeriodInHours, name: "memoryStoreRetentionPeriodInHours", parent: name, max: 8766)
try self.validate(self.memoryStoreRetentionPeriodInHours, name: "memoryStoreRetentionPeriodInHours", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case magneticStoreRetentionPeriodInDays = "MagneticStoreRetentionPeriodInDays"
case memoryStoreRetentionPeriodInHours = "MemoryStoreRetentionPeriodInHours"
}
}
public struct Table: AWSDecodableShape {
/// The Amazon Resource Name that uniquely identifies this table.
public let arn: String?
/// The time when the Timestream table was created.
public let creationTime: Date?
/// The name of the Timestream database that contains this table.
public let databaseName: String?
/// The time when the Timestream table was last updated.
public let lastUpdatedTime: Date?
/// The retention duration for the memory store and magnetic store.
public let retentionProperties: RetentionProperties?
/// The name of the Timestream table.
public let tableName: String?
/// The current state of the table: DELETING - The table is being deleted. ACTIVE - The table is ready for use.
public let tableStatus: TableStatus?
public init(arn: String? = nil, creationTime: Date? = nil, databaseName: String? = nil, lastUpdatedTime: Date? = nil, retentionProperties: RetentionProperties? = nil, tableName: String? = nil, tableStatus: TableStatus? = nil) {
self.arn = arn
self.creationTime = creationTime
self.databaseName = databaseName
self.lastUpdatedTime = lastUpdatedTime
self.retentionProperties = retentionProperties
self.tableName = tableName
self.tableStatus = tableStatus
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case creationTime = "CreationTime"
case databaseName = "DatabaseName"
case lastUpdatedTime = "LastUpdatedTime"
case retentionProperties = "RetentionProperties"
case tableName = "TableName"
case tableStatus = "TableStatus"
}
}
public struct Tag: AWSEncodableShape & AWSDecodableShape {
/// The key of the tag. Tag keys are case sensitive.
public let key: String
/// The value of the tag. Tag values are case-sensitive and can be null.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
public func validate(name: String) throws {
try self.validate(self.key, name: "key", parent: name, max: 128)
try self.validate(self.key, name: "key", parent: name, min: 1)
try self.validate(self.value, name: "value", parent: name, max: 256)
try self.validate(self.value, name: "value", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case key = "Key"
case value = "Value"
}
}
public struct TagResourceRequest: AWSEncodableShape {
/// Identifies the Timestream resource to which tags should be added. This value is an Amazon Resource Name (ARN).
public let resourceARN: String
/// The tags to be assigned to the Timestream resource.
public let tags: [Tag]
public init(resourceARN: String, tags: [Tag]) {
self.resourceARN = resourceARN
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
try self.tags.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
try self.validate(self.tags, name: "tags", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
case tags = "Tags"
}
}
public struct TagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UntagResourceRequest: AWSEncodableShape {
/// The Timestream resource that the tags will be removed from. This value is an Amazon Resource Name (ARN).
public let resourceARN: String
/// A list of tags keys. Existing tags of the resource whose keys are members of this list will be removed from the Timestream resource.
public let tagKeys: [String]
public init(resourceARN: String, tagKeys: [String]) {
self.resourceARN = resourceARN
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
}
try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 200)
try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
case tagKeys = "TagKeys"
}
}
public struct UntagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateDatabaseRequest: AWSEncodableShape {
/// The name of the database.
public let databaseName: String
/// The identifier of the new KMS key (KmsKeyId) to be used to encrypt the data stored in the database. If the KmsKeyId currently registered with the database is the same as the KmsKeyId in the request, there will not be any update. You can specify the KmsKeyId using any of the following: Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab Key ARN: arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab Alias name: alias/ExampleAlias Alias ARN: arn:aws:kms:us-east-1:111122223333:alias/ExampleAlias
public let kmsKeyId: String
public init(databaseName: String, kmsKeyId: String) {
self.databaseName = databaseName
self.kmsKeyId = kmsKeyId
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 2048)
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case kmsKeyId = "KmsKeyId"
}
}
public struct UpdateDatabaseResponse: AWSDecodableShape {
public let database: Database?
public init(database: Database? = nil) {
self.database = database
}
private enum CodingKeys: String, CodingKey {
case database = "Database"
}
}
public struct UpdateTableRequest: AWSEncodableShape {
/// The name of the Timestream database.
public let databaseName: String
/// The retention duration of the memory store and the magnetic store.
public let retentionProperties: RetentionProperties
/// The name of the Timesream table.
public let tableName: String
public init(databaseName: String, retentionProperties: RetentionProperties, tableName: String) {
self.databaseName = databaseName
self.retentionProperties = retentionProperties
self.tableName = tableName
}
public func validate(name: String) throws {
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.retentionProperties.validate(name: "\(name).retentionProperties")
try self.validate(self.tableName, name: "tableName", parent: name, max: 64)
try self.validate(self.tableName, name: "tableName", parent: name, min: 3)
try self.validate(self.tableName, name: "tableName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case databaseName = "DatabaseName"
case retentionProperties = "RetentionProperties"
case tableName = "TableName"
}
}
public struct UpdateTableResponse: AWSDecodableShape {
/// The updated Timestream table.
public let table: Table?
public init(table: Table? = nil) {
self.table = table
}
private enum CodingKeys: String, CodingKey {
case table = "Table"
}
}
public struct WriteRecordsRequest: AWSEncodableShape {
/// A record containing the common measure and dimension attributes shared across all the records in the request. The measure and dimension attributes specified in here will be merged with the measure and dimension attributes in the records object when the data is written into Timestream.
public let commonAttributes: Record?
/// The name of the Timestream database.
public let databaseName: String
/// An array of records containing the unique dimension and measure attributes for each time series data point.
public let records: [Record]
/// The name of the Timesream table.
public let tableName: String
public init(commonAttributes: Record? = nil, databaseName: String, records: [Record], tableName: String) {
self.commonAttributes = commonAttributes
self.databaseName = databaseName
self.records = records
self.tableName = tableName
}
public func validate(name: String) throws {
try self.commonAttributes?.validate(name: "\(name).commonAttributes")
try self.validate(self.databaseName, name: "databaseName", parent: name, max: 64)
try self.validate(self.databaseName, name: "databaseName", parent: name, min: 3)
try self.validate(self.databaseName, name: "databaseName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try self.records.forEach {
try $0.validate(name: "\(name).records[]")
}
try self.validate(self.records, name: "records", parent: name, max: 100)
try self.validate(self.records, name: "records", parent: name, min: 1)
try self.validate(self.tableName, name: "tableName", parent: name, max: 64)
try self.validate(self.tableName, name: "tableName", parent: name, min: 3)
try self.validate(self.tableName, name: "tableName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case commonAttributes = "CommonAttributes"
case databaseName = "DatabaseName"
case records = "Records"
case tableName = "TableName"
}
}
}
| apache-2.0 | dacdc3318d6cb6df7cc06d92c9442bf8 | 43.102144 | 536 | 0.629714 | 4.801345 | false | false | false | false |
jpush/jchat-swift | JChat/Src/ChatRoomModule/ViewController/JCChatRoomInfoTableViewController.swift | 1 | 9512 | //
// JCChatRoomInfoTableViewController.swift
// JChat
//
// Created by Allan on 2019/4/23.
// Copyright © 2019 HXHG. All rights reserved.
//
import UIKit
class JCChatRoomInfoTableViewController: UITableViewController {
open var chatRoom: JMSGChatRoom?
open var isFromSearch: Bool = false
var isOwner: Bool?
var chatRoomOwner: JMSGUser?
var isManager: Bool?
var managerList: [JMSGUser]?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "聊天室信息"
view.backgroundColor = UIColor(netHex: 0xe8edf3)
self.tableView.register(JCChatRoomInfoCell.self, forCellReuseIdentifier: "ChatRoomInfoCell")
self.tableView.register(JCButtonCell.self, forCellReuseIdentifier: "JCButtonCell")
self.tableView.separatorStyle = .none
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.requestData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
// MARK: Request
func requestData() {
//获取房主信息
self.chatRoom?.getOwnerInfo({ (result, error) in
if let user = result as? JMSGUser {
self.chatRoomOwner = user
if user.uid == JMSGUser.myInfo().uid {
self.isOwner = true;
}else{
self.isOwner = false;
}
self.tableView.reloadData()
}else{
print("获取房主信息失败")
}
})
//获取管理员列表
self.chatRoom?.chatRoomAdminList({ (result, error) in
if let users = result as? [JMSGUser]{
self.managerList = users
for user in users {
if (user.uid == JMSGUser.myInfo().uid){
self.isManager = true
break
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
if error != nil{
let err = error! as NSError
printLog("error:\(err.localizedDescription)")
}
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 2{
return 1
}
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 2 {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "JCButtonCell", for: indexPath)
if let btnCell = cell2 as? JCButtonCell {
btnCell.delegate = self
if isFromSearch{
btnCell.button.setTitle("进入聊天室", for: .normal)
}else{
btnCell.button.setTitle("退出聊天室", for: .normal)
}
}
return cell2;
}
let cell = tableView.dequeueReusableCell(withIdentifier: "ChatRoomInfoCell", for: indexPath)
let section0Title = ["聊天室名称","聊天室介绍"]
let section1Title = ["房主","管理员"]
// let section2Title = ["黑名单","禁言"]
if(indexPath.section == 0){
cell.textLabel?.text = section0Title[indexPath.row]
if(indexPath.row == 0){
cell.detailTextLabel?.text = self.chatRoom?.name
}else{
cell.detailTextLabel?.text = self.chatRoom?.desc
}
}else if(indexPath.section == 1 ){
cell.textLabel?.text = section1Title[indexPath.row]
if(indexPath.row == 0){
cell.detailTextLabel?.text = self.chatRoomOwner?.displayName()
}else{
// 管理员头像展示,最多5个
if let infoCell = cell as? JCChatRoomInfoCell {
infoCell.bindImages(users: self.managerList)
}
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
do {
if(indexPath.row == 0){
let nameVC = JCChatRoomNameInfoViewController.init(nibName: "JCChatRoomNameInfoViewController", bundle: nil)
nameVC.roomName = self.chatRoom?.name
self.navigationController?.pushViewController(nameVC, animated: true)
}else{
let introduceVC = JCChatRoomIntroduceViewController.init(nibName: "JCChatRoomIntroduceViewController", bundle: nil)
introduceVC.introduceText = self.chatRoom?.desc
self.navigationController?.pushViewController(introduceVC, animated: true)
}
}
break;
case 1:
do {
if(indexPath.row == 0 ){
//:权限房主是否存在
if(self.chatRoomOwner == nil){
MBProgressHUD_JChat.show(text: "获取房主信息失败", view: self.view)
print("获取房主信息失败")
}else{
let vc = JCUserInfoViewController()
vc.user = self.chatRoomOwner
navigationController?.pushViewController(vc, animated: true)
}
}else{
let roomMangerList = JCChatRoomManagerListViewController.init()
roomMangerList.chatRoom = self.chatRoom?.copy() as? JMSGChatRoom
roomMangerList.isOwner = self.isOwner
self.navigationController?.pushViewController(roomMangerList, animated: true)
}
}
break;
default:
break;
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
if section == 0 {
return 0
}
return 10
}
func logoutChatRoom(){
let alert = UIAlertController.init(title: "退出聊天室", message: "是否确认退出该聊天室?", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction.init(title: "确定", style: UIAlertAction.Style.default) { (UIAlertAction) in
JMSGChatRoom.leaveChatRoom(withRoomId: self.chatRoom!.roomID, completionHandler: { (result, error) in
if error == nil {
self.navigationController?.popToRootViewController(animated: true)
}else{
let err = error! as NSError
MBProgressHUD_JChat.show(text: err.localizedDescription, view: self.view)
printLog("退出聊天室失败,\(err.localizedDescription)")
}
} )
}
alert.addAction(okAction)
let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
func enterChatRoom() {
MBProgressHUD_JChat.show(text: "loading···", view: self.view)
let con = JMSGConversation.chatRoomConversation(withRoomId: self.chatRoom!.roomID)
if con == nil {
//获取聊天室
let room = self.chatRoom!
JMSGChatRoom.enterChatRoom(withRoomId: self.chatRoom!.roomID) { (result, error) in
MBProgressHUD_JChat.hide(forView: self.view, animated: true)
if let con1 = result as? JMSGConversation {
let vc = JCChatRoomChatViewController(conversation: con1, room: room)
self.navigationController?.pushViewController(vc, animated: true)
}else{
printLog("\(String(describing: error))")
if let error = error as NSError? {
if error.code == 851003 {//member has in the chatroom
JMSGConversation.createChatRoomConversation(withRoomId: room.roomID) { (result, error) in
if let con = result as? JMSGConversation {
let vc = JCChatRoomChatViewController(conversation: con, room: room)
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
}
};
}else{
let vc = JCChatRoomChatViewController(conversation: con!, room: self.chatRoom!)
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
extension JCChatRoomInfoTableViewController: JCButtonCellDelegate {
func buttonCell(clickButton button: UIButton) {
if isFromSearch{
self.enterChatRoom()
}else{
self.logoutChatRoom()
}
}
}
| mit | ecf595cc92b25db15d01b8cf8b8c925a | 37.907563 | 135 | 0.546436 | 5.013535 | false | false | false | false |
iDustPan/LoveFreshBee | LoveFreshBee/LoveFreshBee/XPMainTabController.swift | 1 | 2174 | //
// XPMainTabController.swift
// LoveFreshBee
//
// Created by 徐攀 on 16/6/18.
// Copyright © 2016年 cn.xupan.www. All rights reserved.
//
import UIKit
class XPMainTabController: UITabBarController {
// 用来存放tabBar上的按钮
var tabBarButtonArr = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = UIColor.darkGrayColor()
addChildViewControllers()
}
private func addChildViewControllers() {
addChildViewController("Home", title: "首页", image: "v2_home", tag: 0)
addChildViewController("FlashMarket", title: "闪电超市", image: "v2_order", tag: 1)
addChildViewController("ShoppingCard", title: "购物车", image: "shopCart", tag: 2)
addChildViewController("Mine", title: "我的", image: "v2_my", tag: 3)
}
private func addChildViewController(storyboardName: String, title: String, image: String, tag: Int) {
let storyBoard = UIStoryboard(name: storyboardName, bundle: NSBundle.mainBundle())
let viewController = storyBoard.instantiateInitialViewController()!
viewController.childViewControllers[0].title = title
viewController.tabBarItem.image = UIImage(named: image)
viewController.tabBarItem.selectedImage = UIImage(named: image + "_r")?.imageWithRenderingMode(.AlwaysOriginal)
viewController.tabBarItem.tag = tag
addChildViewController(viewController)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for tabBarSubView in tabBar.subviews {
if tabBarSubView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
tabBarButtonArr.append(tabBarSubView)
}
}
}
// MARK: - UITabBarDelegate
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
let btn = tabBarButtonArr[item.tag] as! UIView
let animationView = btn.subviews.first!
XPAnimationManager.manager.addAnimation(.bounces, toView: animationView, duration: 0.5)
}
}
| mit | 3de2187ff987cbef113df0651fdbb383 | 33.33871 | 119 | 0.653828 | 4.916859 | false | false | false | false |
hisui/ReactiveSwift | ReactiveSwift/combinators.swift | 1 | 7486 | // Copyright (c) 2014 segfault.jp. All rights reserved.
import Foundation
public extension Stream {
public func delay(delay: Double) -> Stream<A> {
return flatMap { Streams.`repeat`($0, delay).take(1) }
}
public func sample<B>(tick: Stream<B>) -> Stream<(A?, B)> {
return race(tick, self).innerBind {
var last: A? = nil
return {
switch $0 {
case .Left (let e): return .pure((last, e))
case .Right(let e):
last = e
return .done()
}
}
}
}
public func sample(interval: Double) -> Stream<A?> {
return sample(Streams.`repeat`((), interval) ).map { $0.0 }
}
public func throttle(interval: Double) -> Stream<A> {
return outerBind {{ .timeout(interval, $0) }}
}
public func takeWhile(predicate: A -> Bool) -> Stream<A> { return takeWhile { predicate } }
public func skipWhile(predicate: A -> Bool) -> Stream<A> { return skipWhile { predicate } }
public func take(n: UInt) -> Stream<A> {
return n > 0 ? takeWhile { counter( n ) } : .done()
}
public func skip(n: UInt) -> Stream<A> {
return n > 0 ? skipWhile { counter(n+1) } : self
}
public func fold<B>(initial: B, _ f: (B, A) -> B) -> Stream<B> {
return fold(initial) { f }
}
public func fold<B>(initial: B, _ f: () -> (B, A) -> B) -> Stream<B> {
return unpack(pack().innerBind {
var a = initial
let g = f()
return {
switch $0 {
case .Done:
return .args(.Next(a), .Done)
case .Fail(let x):
return .pure(.Fail(x))
case .Next(let e):
a = g(a, e)
return .done()
}
}
})
}
public func recover(aux: NSError -> Stream<A>) -> Stream<A> {
return unpack(pack().flatMap { e in
switch e {
case .Fail(let x):
return aux(x).pack()
default:
return .pure(e)
}
})
}
public func barrier(that: Stream<Stream<A>>) -> Stream<A> {
return race(self, that).merge {
var count = 0
return { $0.fold(
{ o in count == 0 ? .pure(o): .done() },
{ o in
++count
return o.onClose { count -= 1 }
})
}
}
}
public func fails(error: NSError) -> Stream<A> {
return unpack(pack().map { e in
switch e {
case .Fail: return e
case .Next: return e
case .Done: return .Fail(error)
}
})
}
public func takeWhile(predicate: () -> A -> Bool) -> Stream<A> {
return switchIf(predicate,
during: { .pure(.Next($0)) },
follow: { .args(.Next($0), .Done) })
}
public func skipWhile(predicate: () -> A -> Bool) -> Stream<A> {
return switchIf(predicate,
during: { _ in .done() },
follow: { e in .pure(.Next(e)) })
}
public func nullify<B>() -> Stream<B> { return filter { _ in false }.map { _ in undefined() } }
public func parMap<B>(f: A -> B) -> Stream<B> {
return merge {{ e in Streams.exec([.Isolated]) { f(e) } }}
}
public func continueBy(f: () -> Stream<A>) -> Stream<A> {
return unpack(pack().flatMap { e in
switch e {
case .Done: return f().pack()
default:
return .pure(e)
}
})
}
public func closeBy<X>(s: Stream<X>) -> Stream<A> {
let cut = NSError(domain: "Stream#closeBy", code: 0, userInfo: nil)
return mix([self, s.flatMap { _ in .fail(cut) }])
.recover { e in
e == cut ? .done(): .fail(e)
}
}
public func fill<B>(e: B) -> Stream<B> { return map { _ in e } }
}
private func counter<X>(var n: UInt) -> (X -> Bool) { return { _ in --n == 0 } }
public extension Streams {
public class func timeout<A>(delay: Double, _ value: A) -> Stream<A> {
return `repeat`(value, delay).take(1)
}
}
public func flatten<A>(s: Stream<Stream<A>>) -> Stream<A> { return s.flatMap { $0 } }
public func mix<A>(a: [Stream<A>]) -> Stream<A> { return merge(.list(a)) }
public func seq<A>(a: [Stream<A>]) -> Stream<[A]> {
return a.reduce(.pure([])) { zip($0, $1).map { $0.0 + [$0.1] } }
}
public func concat<A>(a: [Stream<A>]) -> Stream<A> { return flatten(.list(a)) }
public func race<A, B>(a: Stream<A>, _ b: Stream<B>) -> Stream<Either<A, B>>
{
return mix([a.map { .Left($0) }, b.map { .Right($0) }])
}
public func distinct<A: Equatable>(s: Stream<A>) -> Stream<A> {
return s.innerBind {
var last: A? = nil
return { e in
if (last != e) {
last = e
return .pure(e)
}
else {
return .done()
}
}
}
}
// TODO HList
public func combineLatest<A, B>(a: Stream<A>, _ b: Stream<B>) -> Stream<(A, B)> {
return race(a, b).innerBind {
var lhs: A? = nil
var rhs: B? = nil
return {
switch $0 {
case .Left (let e): lhs = e
case .Right(let e): rhs = e
}
if let l = lhs,
r = rhs {
return .pure((l, r))
}
else {
return .done()
}
}
}
}
// TODO done, HList
public func zip<A, B>(a: Stream<A>, _ b: Stream<B>) -> Stream<(A, B)> {
// let exit = NSError()
return race(a /* .fails(exit) */, b /* .fails(exit) */).innerBind {
let queue = ArrayDeque<Either<A, B>>()
return { e in
switch ((queue.head, e)) {
case let ((.Some(.Left(l)), .Right(r))):
queue.shift()
return .pure((l, r))
case let ((.Some(.Right(r)), .Left(l))):
queue.shift()
return .pure((l, r))
default:
queue.push(e)
return .done()
}
}
}
// .recover { $0 === exit ? Streams.done(): Streams.fail($0) }
}
public func compact<A>(s: Stream<A?>) -> Stream<A> {
return s.flatMap { $0.map(Streams.pure) ?? .done() }
}
public func + <A>(a: Stream<A>, b: Stream<A>) -> Stream<A> { return concat([a, b]) }
extension Channel {
public func autoclose() -> Channel<A> {
return AutoClosing(self)
}
public func publish() -> Stream<A> {
return PublishSource(autoclose())
}
}
private class AutoClosing<A>: Channel<A> {
var origin: Channel<A>?
init(_ origin: Channel<A>) { self.origin = origin }
deinit { origin?.close() }
override func subscribe(f: Packet<A> -> ()) {
origin?.subscribe(f)
}
override func close() {
origin?.close()
origin = nil
}
}
private class PublishSource<A>: ForeignSource<A> {
private var channel: Channel<A>!
required init(_ channel: Channel<A>) {
super.init()
self.channel = channel
self.channel.subscribe(emit)
}
}
| mit | 461252963e2183cd3884fb10dc417d9e | 26.221818 | 99 | 0.457254 | 3.704107 | false | false | false | false |
alblue/swift-corelibs-foundation | Foundation/URLSession/libcurl/MultiHandle.swift | 6 | 18995 | //
// 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
//
// -----------------------------------------------------------------------------
///
/// libcurl *multi handle* wrapper.
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
extension URLSession {
/// Minimal wrapper around [curl multi interface](https://curl.haxx.se/libcurl/c/libcurl-multi.html).
///
/// The the *multi handle* manages the sockets for easy handles
/// (`_EasyHandle`), and this implementation uses
/// libdispatch to listen for sockets being read / write ready.
///
/// Using `DispatchSource` allows this implementation to be
/// non-blocking and all code to run on the same thread /
/// `DispatchQueue` -- thus keeping is simple.
///
/// - SeeAlso: _EasyHandle
internal final class _MultiHandle {
let rawHandle = CFURLSessionMultiHandleInit()
let queue: DispatchQueue
let group = DispatchGroup()
fileprivate var easyHandles: [_EasyHandle] = []
fileprivate var timeoutSource: _TimeoutSource? = nil
init(configuration: URLSession._Configuration, workQueue: DispatchQueue) {
queue = DispatchQueue(label: "MultiHandle.isolation", target: workQueue)
setupCallbacks()
configure(with: configuration)
}
deinit {
// C.f.: <https://curl.haxx.se/libcurl/c/curl_multi_cleanup.html>
easyHandles.forEach {
try! CFURLSessionMultiHandleRemoveHandle(rawHandle, $0.rawHandle).asError()
}
try! CFURLSessionMultiHandleDeinit(rawHandle).asError()
}
}
}
extension URLSession._MultiHandle {
func configure(with configuration: URLSession._Configuration) {
try! CFURLSession_multi_setopt_l(rawHandle, CFURLSessionMultiOptionMAX_HOST_CONNECTIONS, configuration.httpMaximumConnectionsPerHost).asError()
try! CFURLSession_multi_setopt_l(rawHandle, CFURLSessionMultiOptionPIPELINING, configuration.httpShouldUsePipelining ? 3 : 2).asError()
//TODO: We may want to set
// CFURLSessionMultiOptionMAXCONNECTS
// CFURLSessionMultiOptionMAX_TOTAL_CONNECTIONS
}
}
fileprivate extension URLSession._MultiHandle {
static func from(callbackUserData userdata: UnsafeMutableRawPointer?) -> URLSession._MultiHandle? {
guard let userdata = userdata else { return nil }
return Unmanaged<URLSession._MultiHandle>.fromOpaque(userdata).takeUnretainedValue()
}
}
fileprivate extension URLSession._MultiHandle {
/// Forward the libcurl callbacks into Swift methods
func setupCallbacks() {
// Socket
try! CFURLSession_multi_setopt_ptr(rawHandle, CFURLSessionMultiOptionSOCKETDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_multi_setopt_sf(rawHandle, CFURLSessionMultiOptionSOCKETFUNCTION) { (easyHandle: CFURLSessionEasyHandle, socket: CFURLSession_socket_t, what: Int32, userdata: UnsafeMutableRawPointer?, socketptr: UnsafeMutableRawPointer?) -> Int32 in
guard let handle = URLSession._MultiHandle.from(callbackUserData: userdata) else { fatalError() }
return handle.register(socket: socket, for: easyHandle, what: what, socketSourcePtr: socketptr)
}.asError()
// Timeout:
try! CFURLSession_multi_setopt_ptr(rawHandle, CFURLSessionMultiOptionTIMERDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_multi_setopt_tf(rawHandle, CFURLSessionMultiOptionTIMERFUNCTION) { (_, timeout: Int, userdata: UnsafeMutableRawPointer?) -> Int32 in
guard let handle = URLSession._MultiHandle.from(callbackUserData: userdata) else { fatalError() }
handle.updateTimeoutTimer(to: timeout)
return 0
}.asError()
}
/// <https://curl.haxx.se/libcurl/c/CURLMOPT_SOCKETFUNCTION.html> and
/// <https://curl.haxx.se/libcurl/c/curl_multi_socket_action.html>
func register(socket: CFURLSession_socket_t, for easyHandle: CFURLSessionEasyHandle, what: Int32, socketSourcePtr: UnsafeMutableRawPointer?) -> Int32 {
// We get this callback whenever we need to register or unregister a
// given socket with libdispatch.
// The `action` / `what` defines if we should register or unregister
// that we're interested in read and/or write readiness. We will do so
// through libdispatch (DispatchSource) and store the source(s) inside
// a `SocketSources` which we in turn store inside libcurl's multi handle
// by means of curl_multi_assign() -- we retain the object fist.
let action = _SocketRegisterAction(rawValue: CFURLSessionPoll(value: what))
var socketSources = _SocketSources.from(socketSourcePtr: socketSourcePtr)
if socketSources == nil && action.needsSource {
let s = _SocketSources()
let p = Unmanaged.passRetained(s).toOpaque()
CFURLSessionMultiHandleAssign(rawHandle, socket, UnsafeMutableRawPointer(p))
socketSources = s
} else if socketSources != nil && action == .unregister {
// We need to release the stored pointer:
if let opaque = socketSourcePtr {
Unmanaged<_SocketSources>.fromOpaque(opaque).release()
}
socketSources = nil
}
if let ss = socketSources {
let handler = DispatchWorkItem { [weak self] in
self?.performAction(for: socket)
}
ss.createSources(with: action, fileDescriptor: Int(socket), queue: queue, handler: handler)
}
return 0
}
/// What read / write ready event to register / unregister.
///
/// This re-maps `CFURLSessionPoll` / `CURL_POLL`.
enum _SocketRegisterAction {
case none
case registerRead
case registerWrite
case registerReadAndWrite
case unregister
}
}
internal extension URLSession._MultiHandle {
/// Add an easy handle -- start its transfer.
func add(_ handle: _EasyHandle) {
// If this is the first handle being added, we need to `kick` the
// underlying multi handle by calling `timeoutTimerFired` as
// described in
// <https://curl.haxx.se/libcurl/c/curl_multi_socket_action.html>.
// That will initiate the registration for timeout timer and socket
// readiness.
let needsTimeout = self.easyHandles.isEmpty
self.easyHandles.append(handle)
try! CFURLSessionMultiHandleAddHandle(self.rawHandle, handle.rawHandle).asError()
if needsTimeout {
self.timeoutTimerFired()
}
}
/// Remove an easy handle -- stop its transfer.
func remove(_ handle: _EasyHandle) {
guard let idx = self.easyHandles.index(of: handle) else {
fatalError("Handle not in list.")
}
self.easyHandles.remove(at: idx)
try! CFURLSessionMultiHandleRemoveHandle(self.rawHandle, handle.rawHandle).asError()
}
}
fileprivate extension URLSession._MultiHandle {
/// This gets called when we should ask curl to perform action on a socket.
func performAction(for socket: CFURLSession_socket_t) {
try! readAndWriteAvailableData(on: socket)
}
/// This gets called when our timeout timer fires.
///
/// libcurl relies on us calling curl_multi_socket_action() every now and then.
func timeoutTimerFired() {
try! readAndWriteAvailableData(on: CFURLSessionSocketTimeout)
}
/// reads/writes available data given an action
func readAndWriteAvailableData(on socket: CFURLSession_socket_t) throws {
var runningHandlesCount = Int32(0)
try CFURLSessionMultiHandleAction(rawHandle, socket, 0, &runningHandlesCount).asError()
//TODO: Do we remove the timeout timer here if / when runningHandles == 0 ?
readMessages()
}
/// Check the status of all individual transfers.
///
/// libcurl refers to this as “read multi stack informationals”.
/// Check for transfers that completed.
func readMessages() {
// We pop the messages one by one in a loop:
repeat {
// count will contain the messages left in the queue
var count = Int32(0)
let info = CFURLSessionMultiHandleInfoRead(rawHandle, &count)
guard let handle = info.easyHandle else { break }
let code = info.resultCode
completedTransfer(forEasyHandle: handle, easyCode: code)
} while true
}
/// Transfer completed.
func completedTransfer(forEasyHandle handle: CFURLSessionEasyHandle, easyCode: CFURLSessionEasyCode) {
// Look up the matching wrapper:
guard let idx = easyHandles.index(where: { $0.rawHandle == handle }) else {
fatalError("Tansfer completed for easy handle, but it is not in the list of added handles.")
}
let easyHandle = easyHandles[idx]
// Find the NSURLError code
var error: NSError?
if let errorCode = easyHandle.urlErrorCode(for: easyCode) {
let errorDescription = easyHandle.errorBuffer[0] != 0 ?
String(cString: easyHandle.errorBuffer) :
CFURLSessionCreateErrorDescription(easyCode.value)._swiftObject
error = NSError(domain: NSURLErrorDomain, code: errorCode, userInfo: [
NSLocalizedDescriptionKey: errorDescription
])
}
completedTransfer(forEasyHandle: easyHandle, error: error)
}
/// Transfer completed.
func completedTransfer(forEasyHandle handle: _EasyHandle, error: NSError?) {
handle.completedTransfer(withError: error)
}
}
fileprivate extension _EasyHandle {
/// An error code within the `NSURLErrorDomain` based on the error of the
/// easy handle.
/// - Note: The error value is set only on failure. You can't use it to
/// determine *if* something failed or not, only *why* it failed.
func urlErrorCode(for easyCode: CFURLSessionEasyCode) -> Int? {
switch (easyCode, CInt(connectFailureErrno)) {
case (CFURLSessionEasyCodeOK, _):
return nil
case (_, ECONNREFUSED):
return NSURLErrorCannotConnectToHost
case (CFURLSessionEasyCodeUNSUPPORTED_PROTOCOL, _):
return NSURLErrorUnsupportedURL
case (CFURLSessionEasyCodeURL_MALFORMAT, _):
return NSURLErrorBadURL
case (CFURLSessionEasyCodeCOULDNT_RESOLVE_HOST, _):
// Oddly, this appears to happen for malformed URLs, too.
return NSURLErrorCannotFindHost
case (CFURLSessionEasyCodeRECV_ERROR, ECONNRESET):
return NSURLErrorNetworkConnectionLost
case (CFURLSessionEasyCodeSEND_ERROR, ECONNRESET):
return NSURLErrorNetworkConnectionLost
case (CFURLSessionEasyCodeGOT_NOTHING, _):
return NSURLErrorBadServerResponse
case (CFURLSessionEasyCodeABORTED_BY_CALLBACK, _):
return NSURLErrorUnknown // Or NSURLErrorCancelled if we're in such a state
case (CFURLSessionEasyCodeCOULDNT_CONNECT, ETIMEDOUT):
return NSURLErrorTimedOut
case (CFURLSessionEasyCodeOPERATION_TIMEDOUT, _):
return NSURLErrorTimedOut
default:
//TODO: Need to map to one of the NSURLError... constants
return NSURLErrorUnknown
}
}
}
fileprivate extension URLSession._MultiHandle._SocketRegisterAction {
init(rawValue: CFURLSessionPoll) {
switch rawValue {
case CFURLSessionPollNone:
self = .none
case CFURLSessionPollIn:
self = .registerRead
case CFURLSessionPollOut:
self = .registerWrite
case CFURLSessionPollInOut:
self = .registerReadAndWrite
case CFURLSessionPollRemove:
self = .unregister
default:
fatalError("Invalid CFURLSessionPoll value.")
}
}
}
extension CFURLSessionPoll : Equatable {
public static func ==(lhs: CFURLSessionPoll, rhs: CFURLSessionPoll) -> Bool {
return lhs.value == rhs.value
}
}
fileprivate extension URLSession._MultiHandle._SocketRegisterAction {
/// Should a libdispatch source be registered for **read** readiness?
var needsReadSource: Bool {
switch self {
case .none: return false
case .registerRead: return true
case .registerWrite: return false
case .registerReadAndWrite: return true
case .unregister: return false
}
}
/// Should a libdispatch source be registered for **write** readiness?
var needsWriteSource: Bool {
switch self {
case .none: return false
case .registerRead: return false
case .registerWrite: return true
case .registerReadAndWrite: return true
case .unregister: return false
}
}
/// Should either a **read** or a **write** readiness libdispatch source be
/// registered?
var needsSource: Bool {
return needsReadSource || needsWriteSource
}
}
/// A helper class that wraps a libdispatch timer.
///
/// Used to implement the timeout of `URLSession.MultiHandle` and `URLSession.EasyHandle`
class _TimeoutSource {
let rawSource: DispatchSource
let milliseconds: Int
let queue: DispatchQueue //needed to restart the timer for EasyHandles
let handler: DispatchWorkItem //needed to restart the timer for EasyHandles
init(queue: DispatchQueue, milliseconds: Int, handler: DispatchWorkItem) {
self.queue = queue
self.handler = handler
self.milliseconds = milliseconds
self.rawSource = DispatchSource.makeTimerSource(queue: queue) as! DispatchSource
let delay = UInt64(max(1, milliseconds - 1))
let start = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(delay))
rawSource.schedule(deadline: start, repeating: .milliseconds(Int(delay)), leeway: (milliseconds == 1) ? .microseconds(Int(1)) : .milliseconds(Int(1)))
rawSource.setEventHandler(handler: handler)
rawSource.resume()
}
deinit {
rawSource.cancel()
}
}
fileprivate extension URLSession._MultiHandle {
/// <https://curl.haxx.se/libcurl/c/CURLMOPT_TIMERFUNCTION.html>
func updateTimeoutTimer(to value: Int) {
updateTimeoutTimer(to: _Timeout(timeout: value))
}
func updateTimeoutTimer(to timeout: _Timeout) {
// Set up a timeout timer based on the given value:
switch timeout {
case .none:
timeoutSource = nil
case .immediate:
timeoutSource = nil
timeoutTimerFired()
case .milliseconds(let milliseconds):
if (timeoutSource == nil) || timeoutSource!.milliseconds != milliseconds {
//TODO: Could simply change the existing timer by using DispatchSourceTimer again.
let block = DispatchWorkItem { [weak self] in
self?.timeoutTimerFired()
}
timeoutSource = _TimeoutSource(queue: queue, milliseconds: milliseconds, handler: block)
}
}
}
enum _Timeout {
case milliseconds(Int)
case none
case immediate
}
}
fileprivate extension URLSession._MultiHandle._Timeout {
init(timeout: Int) {
switch timeout {
case -1:
self = .none
case 0:
self = .immediate
default:
self = .milliseconds(timeout)
}
}
}
/// Read and write libdispatch sources for a specific socket.
///
/// A simple helper that combines two sources -- both being optional.
///
/// This info is stored into the socket using `curl_multi_assign()`.
///
/// - SeeAlso: URLSession.MultiHandle.SocketRegisterAction
fileprivate class _SocketSources {
var readSource: DispatchSource?
var writeSource: DispatchSource?
func createReadSource(fileDescriptor fd: Int, queue: DispatchQueue, handler: DispatchWorkItem) {
guard readSource == nil else { return }
let s = DispatchSource.makeReadSource(fileDescriptor: Int32(fd), queue: queue)
s.setEventHandler(handler: handler)
readSource = s as? DispatchSource
s.resume()
}
func createWriteSource(fileDescriptor fd: Int, queue: DispatchQueue, handler: DispatchWorkItem) {
guard writeSource == nil else { return }
let s = DispatchSource.makeWriteSource(fileDescriptor: Int32(fd), queue: queue)
s.setEventHandler(handler: handler)
writeSource = s as? DispatchSource
s.resume()
}
func tearDown() {
if let s = readSource {
s.cancel()
}
readSource = nil
if let s = writeSource {
s.cancel()
}
writeSource = nil
}
}
extension _SocketSources {
/// Create a read and/or write source as specified by the action.
func createSources(with action: URLSession._MultiHandle._SocketRegisterAction, fileDescriptor fd: Int, queue: DispatchQueue, handler: DispatchWorkItem) {
if action.needsReadSource {
createReadSource(fileDescriptor: fd, queue: queue, handler: handler)
}
if action.needsWriteSource {
createWriteSource(fileDescriptor: fd, queue: queue, handler: handler)
}
}
}
extension _SocketSources {
/// Unwraps the `SocketSources`
///
/// A `SocketSources` is stored into the multi handle's socket using
/// `curl_multi_assign()`. This helper unwraps it from the returned
/// `UnsafeMutablePointer<Void>`.
static func from(socketSourcePtr ptr: UnsafeMutableRawPointer?) -> _SocketSources? {
guard let ptr = ptr else { return nil }
return Unmanaged<_SocketSources>.fromOpaque(ptr).takeUnretainedValue()
}
}
extension CFURLSessionMultiCode : Equatable {
public static func ==(lhs: CFURLSessionMultiCode, rhs: CFURLSessionMultiCode) -> Bool {
return lhs.value == rhs.value
}
}
extension CFURLSessionMultiCode : Error {
public var _domain: String { return "libcurl.Multi" }
public var _code: Int { return Int(self.value) }
}
internal extension CFURLSessionMultiCode {
func asError() throws {
if self == CFURLSessionMultiCodeOK { return }
throw self
}
}
| apache-2.0 | 52a6217e666e0de79d5d3b06a6fa3be9 | 40.465066 | 259 | 0.65431 | 4.776408 | false | false | false | false |
Meeca/IQKeyboardManager | IQKeybordManagerSwift/Constants/IQKeyboardManagerConstants.swift | 19 | 7348 | //
// IQKeyboardManagerConstants.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// 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: Debugging
///----------------
/**
Set `-DIQKEYBOARDMANAGER_DEBUG` flag in 'other swift flag' to enable debugging.
*/
///-----------------------------------
/// MARK: IQAutoToolbarManageBehaviour
///-----------------------------------
/**
`IQAutoToolbarBySubviews`
Creates Toolbar according to subview's hirarchy of Textfield's in view.
`IQAutoToolbarByTag`
Creates Toolbar according to tag property of TextField's.
`IQAutoToolbarByPosition`
Creates Toolbar according to the y,x position of textField in it's superview coordinate.
*/
enum IQAutoToolbarManageBehaviour {
case BySubviews
case ByTag
case ByPosition
}
/*
/---------------------------------------------------------------------------------------------------\
\---------------------------------------------------------------------------------------------------/
| iOS NSNotification Mechanism |
/---------------------------------------------------------------------------------------------------\
\---------------------------------------------------------------------------------------------------/
1) Begin Editing:- When TextField begin editing.
2) End Editing:- When TextField end editing.
3) Switch TextField:- When Keyboard Switch from a TextField to another TextField.
3) Orientation Change:- When Device Orientation Change.
----------------------------------------------------------------------------------------------------------------------------------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
----------------------------------------------------------------------------------------------------------------------------------------------
=============
UITextField
=============
Begin Editing Begin Editing
-------------------------------------------- ---------------------------------- ---------------------------------
|UITextFieldTextDidBeginEditingNotification| --------> | UIKeyboardWillShowNotification | --------> | UIKeyboardDidShowNotification |
-------------------------------------------- ---------------------------------- ---------------------------------
^ Switch TextField ^ Switch TextField
| |
| |
| Switch TextField | Orientation Change
| |
| |
| |
-------------------------------------------- | ---------------------------------- ---------------------------------
| UITextFieldTextDidEndEditingNotification | <-------- | UIKeyboardWillHideNotification | --------> | UIKeyboardDidHideNotification |
-------------------------------------------- ---------------------------------- ---------------------------------
| End Editing ^
| |
|--------------------End Editing-------------------------------------------------------------|
----------------------------------------------------------------------------------------------------------------------------------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
----------------------------------------------------------------------------------------------------------------------------------------------
=============
UITextView
=============
|-------------------Switch TextView--------------------------------------------------------------|
| |------------------Begin Editing-------------------------------------------------------------| |
| | | |
v | Begin Editing Switch TextView v |
-------------------------------------------- ---------------------------------- ---------------------------------
| UITextViewTextDidBeginEditingNotification| <-------- | UIKeyboardWillShowNotification | --------> | UIKeyboardDidShowNotification |
-------------------------------------------- ---------------------------------- ---------------------------------
^
|
|------------------------Switch TextView--------|
| | Orientation Change
| |
| |
| |
-------------------------------------------- | ---------------------------------- ---------------------------------
| UITextViewTextDidEndEditingNotification | <-------- | UIKeyboardWillHideNotification | | UIKeyboardDidHideNotification |
-------------------------------------------- ---------------------------------- ---------------------------------
| End Editing ^
| |
|--------------------End Editing-------------------------------------------------------------|
----------------------------------------------------------------------------------------------------------------------------------------------
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
----------------------------------------------------------------------------------------------------------------------------------------------
*/
| mit | 631198cd4231154aa481c05a1b9f7b9b | 56.40625 | 142 | 0.300354 | 7.429727 | false | false | false | false |
tjw/swift | stdlib/public/core/StringUnicodeScalarView.swift | 1 | 23924 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
extension String {
/// A view of a string's contents as a collection of Unicode scalar values.
///
/// You can access a string's view of Unicode scalar values by using its
/// `unicodeScalars` property. Unicode scalar values are the 21-bit codes
/// that are the basic unit of Unicode. Each scalar value is represented by
/// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.unicodeScalars {
/// print(v.value)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 128144
///
/// Some characters that are visible in a string are made up of more than one
/// Unicode scalar value. In that case, a string's `unicodeScalars` view
/// contains more elements than the string itself.
///
/// let flag = "🇵🇷"
/// for c in flag {
/// print(c)
/// }
/// // 🇵🇷
///
/// for v in flag.unicodeScalars {
/// print(v.value)
/// }
/// // 127477
/// // 127479
///
/// You can convert a `String.UnicodeScalarView` instance back into a string
/// using the `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.unicodeScalars.index(where: { $0.value >= 128 }) {
/// let asciiPrefix = String(favemoji.unicodeScalars[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
@_fixed_layout // FIXME(sil-serialize-all)
public struct UnicodeScalarView :
BidirectionalCollection,
CustomStringConvertible,
CustomDebugStringConvertible
{
@usableFromInline
internal var _guts: _StringGuts
/// The offset of this view's `_guts` from the start of an original string,
/// in UTF-16 code units. This is here to support legacy Swift 3-style
/// slicing where `s.unicodeScalars[i..<j]` produces a
/// `String.UnicodeScalarView`. The offset should be subtracted from the
/// `encodedOffset` of view indices before it is passed to `_guts`.
///
/// Note: This should be removed when Swift 3 semantics are no longer
/// supported.
@usableFromInline // FIXME(sil-serialize-all)
internal var _coreOffset: Int
@inlinable // FIXME(sil-serialize-all)
internal init(_ _guts: _StringGuts, coreOffset: Int = 0) {
self._guts = _guts
self._coreOffset = coreOffset
}
public typealias Index = String.Index
/// Translates a `_guts` index into a `UnicodeScalarIndex` using this
/// view's `_coreOffset`.
@inlinable // FIXME(sil-serialize-all)
internal func _fromCoreIndex(_ i: Int) -> Index {
return Index(encodedOffset: i + _coreOffset)
}
/// Translates a `UnicodeScalarIndex` into a `_guts` index using this
/// view's `_coreOffset`.
@inlinable // FIXME(sil-serialize-all)
internal func _toCoreIndex(_ i: Index) -> Int {
return i.encodedOffset - _coreOffset
}
/// The position of the first Unicode scalar value if the string is
/// nonempty.
///
/// If the string is empty, `startIndex` is equal to `endIndex`.
@inlinable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _fromCoreIndex(_guts.startIndex)
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`.
@inlinable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _fromCoreIndex(_guts.endIndex)
}
/// Returns the next consecutive location after `i`.
///
/// - Precondition: The next location exists.
@inlinable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
let offset = _toCoreIndex(i)
let length: Int = _visitGuts(_guts, args: offset,
ascii: { _ -> Int in return 1 },
utf16: { utf16, offset in
return utf16.unicodeScalarWidth(startingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalarWidth(startingAt: offset) }
)
return _fromCoreIndex(offset + length)
}
/// Returns the previous consecutive location before `i`.
///
/// - Precondition: The previous location exists.
@inlinable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
let offset = _toCoreIndex(i)
let length: Int = _visitGuts(_guts, args: offset,
ascii: { _ -> Int in return 1 },
utf16: { utf16, offset in
return utf16.unicodeScalarWidth(endingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalarWidth(endingAt: offset) }
)
return _fromCoreIndex(offset - length)
}
/// Accesses the Unicode scalar value at the given position.
///
/// The following example searches a string's Unicode scalars view for a
/// capital letter and then prints the character and Unicode scalar value
/// at the found index:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.unicodeScalars.index(where: { "A"..."Z" ~= $0 }) {
/// print("First capital letter: \(greeting.unicodeScalars[i])")
/// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)")
/// }
/// // Prints "First capital letter: H"
/// // Prints "Unicode scalar value: 72"
///
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
@inlinable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Unicode.Scalar {
let offset = position.encodedOffset
return _guts.unicodeScalar(startingAt: offset)
}
/// An iterator over the Unicode scalars that make up a `UnicodeScalarView`
/// collection.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator : IteratorProtocol {
@usableFromInline // FIXME(sil-serialize-all)
internal var _guts: _StringGuts
// FIXME(TODO: JIRA): the below is absurdly wasteful.
// UnicodeScalarView.Iterator should be able to be passed in-registers.
@usableFromInline // FIXME(sil-serialize-all)
internal var _asciiIterator: _UnmanagedASCIIString.UnicodeScalarIterator?
@usableFromInline // FIXME(sil-serialize-all)
internal var _utf16Iterator: _UnmanagedUTF16String.UnicodeScalarIterator?
@usableFromInline // FIXME(sil-serialize-all)
internal var _opaqueIterator: _UnmanagedOpaqueString.UnicodeScalarIterator?
@usableFromInline
internal var _smallIterator: _SmallUTF8String.UnicodeScalarIterator?
@inlinable // FIXME(sil-serialize-all)
internal init(_ guts: _StringGuts) {
if _slowPath(guts._isOpaque) {
self.init(_opaque: guts)
return
}
self.init(_concrete: guts)
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal init(_concrete guts: _StringGuts) {
_sanityCheck(!guts._isOpaque)
self._guts = guts
defer { _fixLifetime(self) }
if _guts.isASCII {
self._asciiIterator =
_guts._unmanagedASCIIView.makeUnicodeScalarIterator()
} else {
self._utf16Iterator =
_guts._unmanagedUTF16View.makeUnicodeScalarIterator()
}
}
@usableFromInline // @opaque
init(_opaque _guts: _StringGuts) {
_sanityCheck(_guts._isOpaque)
defer { _fixLifetime(self) }
self._guts = _guts
// TODO: Replace the whole iterator scheme with a sensible solution.
if self._guts._isSmall {
self._smallIterator =
_guts._smallUTF8String.makeUnicodeScalarIterator()
} else {
self._opaqueIterator = _guts._asOpaque().makeUnicodeScalarIterator()
}
}
/// Advances to the next element and returns it, or `nil` if no next
/// element exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Unicode.Scalar? {
if _slowPath(_opaqueIterator != nil) {
return _opaqueIterator!.next()
}
if _asciiIterator != nil {
return _asciiIterator!.next()
}
if _guts._isSmall {
return _smallIterator!.next()
}
return _utf16Iterator!.next()
}
}
/// Returns an iterator over the Unicode scalars that make up this view.
///
/// - Returns: An iterator over this collection's `Unicode.Scalar` elements.
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(_guts)
}
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return String(_guts)
}
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "StringUnicodeScalarView(\(self.description.debugDescription))"
}
}
/// Creates a string corresponding to the given collection of Unicode
/// scalars.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `unicodeScalars` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.unicodeScalars.index(of: " ") {
/// let adjective = String(picnicGuest.unicodeScalars[..<i])
/// print(adjective)
/// }
/// // Prints "Deserving"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.unicodeScalars` view.
///
/// - Parameter unicodeScalars: A collection of Unicode scalar values.
@inlinable // FIXME(sil-serialize-all)
public init(_ unicodeScalars: UnicodeScalarView) {
self.init(unicodeScalars._guts)
}
/// The index type for a string's `unicodeScalars` view.
public typealias UnicodeScalarIndex = UnicodeScalarView.Index
}
extension _StringGuts {
@inlinable
internal func unicodeScalar(startingAt offset: Int) -> Unicode.Scalar {
return _visitGuts(self, args: offset,
ascii: { ascii, offset in
let u = ascii.codeUnit(atCheckedOffset: offset)
return Unicode.Scalar(_unchecked: UInt32(u)) },
utf16: { utf16, offset in
return utf16.unicodeScalar(startingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalar(startingAt: offset) })
}
@inlinable
internal func unicodeScalar(endingAt offset: Int) -> Unicode.Scalar {
return _visitGuts(self, args: offset,
ascii: { ascii, offset in
let u = ascii.codeUnit(atCheckedOffset: offset &- 1)
return Unicode.Scalar(_unchecked: UInt32(u)) },
utf16: { utf16, offset in
return utf16.unicodeScalar(endingAt: offset) },
opaque: { opaque, offset in
return opaque.unicodeScalar(endingAt: offset) })
}
}
extension String.UnicodeScalarView : _SwiftStringView {
@inlinable // FIXME(sil-serialize-all)
internal var _persistentContent : String { return String(_guts) }
@inlinable // FIXME(sil-serialize-all)
var _wholeString : String {
return String(_guts)
}
@inlinable // FIXME(sil-serialize-all)
var _encodedOffsetRange : Range<Int> {
return 0..<_guts.count
}
}
extension String {
/// The string's value represented as a collection of Unicode scalar values.
@inlinable // FIXME(sil-serialize-all)
public var unicodeScalars: UnicodeScalarView {
get {
return UnicodeScalarView(_guts)
}
set {
_guts = newValue._guts
}
}
}
extension String.UnicodeScalarView : RangeReplaceableCollection {
/// Creates an empty view instance.
@inlinable // FIXME(sil-serialize-all)
public init() {
self = String.UnicodeScalarView(_StringGuts())
}
/// Reserves enough space in the view's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because a Unicode scalar value can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding to a Unicode scalar view after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*), where *n* is the capacity being reserved.
@inlinable // FIXME(sil-serialize-all)
public mutating func reserveCapacity(_ n: Int) {
_guts.reserveCapacity(n)
}
/// Appends the given Unicode scalar to the view.
///
/// - Parameter c: The character to append to the string.
@inlinable // FIXME(sil-serialize-all)
public mutating func append(_ c: Unicode.Scalar) {
if _fastPath(_guts.isASCII && c.value <= 0x7f) {
_guts.withMutableASCIIStorage(unusedCapacity: 1) { storage in
unowned(unsafe) let s = storage._value
s.end.pointee = UInt8(c.value)
s.count += 1
}
} else {
let width = UTF16.width(c)
_guts.withMutableUTF16Storage(unusedCapacity: width) { storage in
unowned(unsafe) let s = storage._value
_sanityCheck(s.count + width <= s.capacity)
if _fastPath(width == 1) {
s.end.pointee = UTF16.CodeUnit(c.value)
} else {
_sanityCheck(width == 2)
s.end[0] = UTF16.leadSurrogate(c)
s.end[1] = UTF16.trailSurrogate(c)
}
s.count += width
}
}
}
/// Appends the Unicode scalar values in the given sequence to the view.
///
/// - Parameter newElements: A sequence of Unicode scalar values.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting view.
@inlinable // FIXME(sil-serialize-all)
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Unicode.Scalar {
// FIXME: Keep ASCII storage if possible
_guts.reserveUnusedCapacity(newElements.underestimatedCount)
var it = newElements.makeIterator()
var next = it.next()
while let n = next {
_guts.withMutableUTF16Storage(unusedCapacity: UTF16.width(n)) { storage in
var p = storage._value.end
let limit = storage._value.capacityEnd
while let n = next {
let w = UTF16.width(n)
guard p + w <= limit else { break }
if w == 1 {
p.pointee = UTF16.CodeUnit(n.value)
} else {
_sanityCheck(w == 2)
p[0] = UTF16.leadSurrogate(n)
p[1] = UTF16.trailSurrogate(n)
}
p += w
next = it.next()
}
storage._value.count = p - storage._value.start
}
}
}
/// Replaces the elements within the specified bounds with the given Unicode
/// scalar values.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - bounds: The range of elements to replace. The bounds of the range
/// must be valid indices of the view.
/// - newElements: The new Unicode scalar values to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the view and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes elements at the end of the string, the complexity is O(*n*),
/// where *n* is equal to `bounds.count`.
@inlinable // FIXME(sil-serialize-all)
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Unicode.Scalar {
let rawSubRange: Range<Int> = _toCoreIndex(bounds.lowerBound) ..<
_toCoreIndex(bounds.upperBound)
let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 }
_guts.replaceSubrange(rawSubRange, with: lazyUTF16)
}
}
// Index conversions
extension String.UnicodeScalarIndex {
/// Creates an index in the given Unicode scalars view that corresponds
/// exactly to the specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `unicodeScalars` view:
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.index(of: 32)!
/// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)!
///
/// print(String(cafe.unicodeScalars[..<scalarIndex]))
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `unicodeScalars`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair results in `nil`.
///
/// - Parameters:
/// - sourcePosition: A position in the `utf16` view of a string. `utf16Index`
/// must be an element of `String(unicodeScalars).utf16.indices`.
/// - unicodeScalars: The `UnicodeScalarView` in which to find the new
/// position.
@inlinable // FIXME(sil-serialize-all)
public init?(
_ sourcePosition: String.UTF16Index,
within unicodeScalars: String.UnicodeScalarView
) {
if !unicodeScalars._isOnUnicodeScalarBoundary(sourcePosition) { return nil }
self = sourcePosition
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.unicodeScalars.index(of: "🍵")
/// let j = i.samePosition(in: cafe)!
/// print(cafe[j...])
/// // Prints "🍵"
///
/// - Parameter characters: The string to use for the index conversion.
/// This index must be a valid index of at least one view of `characters`.
/// - Returns: The position in `characters` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `characters`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
@inlinable // FIXME(sil-serialize-all)
public func samePosition(in characters: String) -> String.Index? {
return String.Index(self, within: characters)
}
}
extension String.UnicodeScalarView {
@inlinable // FIXME(sil-serialize-all)
internal func _isOnUnicodeScalarBoundary(_ i: Index) -> Bool {
if _fastPath(_guts.isASCII) { return true }
if i == startIndex || i == endIndex {
return true
}
if i._transcodedOffset != 0 { return false }
let i2 = _toCoreIndex(i)
if _fastPath(!UTF16.isTrailSurrogate(_guts[i2])) { return true }
return i2 == 0 || !UTF16.isLeadSurrogate(_guts[i2 &- 1])
}
// NOTE: Don't make this function inlineable. Grapheme cluster
// segmentation uses a completely different algorithm in Unicode 9.0.
@inlinable // FIXME(sil-serialize-all)
internal func _isOnGraphemeClusterBoundary(_ i: Index) -> Bool {
if i == startIndex || i == endIndex {
return true
}
if !_isOnUnicodeScalarBoundary(i) { return false }
let str = String(_guts)
return i == str.index(before: str.index(after: i))
}
}
// Reflection
extension String.UnicodeScalarView : CustomReflectable {
/// Returns a mirror that reflects the Unicode scalars view of a string.
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UnicodeScalarView : CustomPlaygroundQuickLookable {
@inlinable // FIXME(sil-serialize-all)
@available(*, deprecated, message: "UnicodeScalarView.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
// backward compatibility for index interchange.
extension String.UnicodeScalarView {
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(after i: Index?) -> Index {
return index(after: i!)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(_ i: Index?, offsetBy n: Int) -> Index {
return index(i!, offsetBy: n)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public func distance(from i: Index?, to j: Index?) -> Int {
return distance(from: i!, to: j!)
}
@inlinable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public subscript(i: Index?) -> Unicode.Scalar {
return self[i!]
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.unicodeScalars[
/// someString.unicodeScalars.startIndex
/// ..< someString.unicodeScalars.endIndex]
///
/// was deduced to be of type `String.UnicodeScalarView`. Provide a
/// more-specific Swift-3-only `subscript` overload that continues to produce
/// `String.UnicodeScalarView`.
extension String.UnicodeScalarView {
public typealias SubSequence = Substring.UnicodeScalarView
@inlinable // FIXME(sil-serialize-all)
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence {
return String.UnicodeScalarView.SubSequence(self, _bounds: r)
}
/// Accesses the Unicode scalar values in the given range.
///
/// The example below uses this subscript to access the scalar values up
/// to, but not including, the first comma (`","`) in the string.
///
/// let str = "All this happened, more or less."
/// let i = str.unicodeScalars.index(of: ",")!
/// let substring = str.unicodeScalars[str.unicodeScalars.startIndex ..< i]
/// print(String(substring))
/// // Prints "All this happened"
///
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
@inlinable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView {
let rawSubRange: Range<Int> =
_toCoreIndex(r.lowerBound)..<_toCoreIndex(r.upperBound)
return String.UnicodeScalarView(
_guts._extractSlice(rawSubRange),
coreOffset: r.lowerBound.encodedOffset)
}
@inlinable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(bounds: ClosedRange<Index>) -> String.UnicodeScalarView {
return self[bounds.relative(to: self)]
}
}
| apache-2.0 | 5be8a6348128f24d04a1a36be672f904 | 35.755385 | 125 | 0.639237 | 4.229244 | false | false | false | false |
turingcorp/gattaca | gattaca/View/Abstract/Basic/ViewParentGesture.swift | 1 | 3449 | import UIKit
extension ViewParent:UIGestureRecognizerDelegate
{
//MARK: selectors
func actionPanRecognized(sender panGesture:UIPanGestureRecognizer)
{
let location:CGPoint = panGesture.location(in:self)
let xPos:CGFloat = location.x
switch panGesture.state
{
case UIGestureRecognizerState.began,
UIGestureRecognizerState.possible:
if xPos < kMaxXPanning
{
self.panningX = xPos
}
break
case UIGestureRecognizerState.changed:
if let panningX:CGFloat = self.panningX
{
var deltaX:CGFloat = xPos - panningX
if deltaX > kMaxXDelta
{
panRecognizer.isEnabled = false
}
else
{
if deltaX < 0
{
deltaX = 0
}
guard
let topView:ViewMain = subviews.last as? ViewMain
else
{
return
}
topView.layoutLeft.constant = deltaX
}
}
break
case UIGestureRecognizerState.cancelled,
UIGestureRecognizerState.ended,
UIGestureRecognizerState.failed:
if let panningX:CGFloat = self.panningX
{
let deltaX:CGFloat = xPos - panningX
if deltaX > kMinXDelta
{
gesturePop()
}
else
{
gestureRestore()
}
}
panningX = nil
break
}
}
//MARK: private
private func gesturePop()
{
panRecognizer.isEnabled = true
controller.pop(horizontal:ControllerParent.Horizontal.right)
}
private func gestureRestore()
{
panRecognizer.isEnabled = true
guard
let topView:ViewProtocol = subviews.last as? ViewProtocol
else
{
return
}
topView.layoutLeft.constant = 0
UIView.animate(withDuration:kAnimationDuration)
{
self.layoutIfNeeded()
}
}
//MARK: internal
func factoryGesture()
{
let panRecognizer:UIPanGestureRecognizer = UIPanGestureRecognizer(
target:self,
action:#selector(actionPanRecognized(sender:)))
panRecognizer.delegate = self
self.panRecognizer = panRecognizer
addGestureRecognizer(panRecognizer)
}
//MARK: gestureRecognizerDelegate
override func gestureRecognizerShouldBegin(
_ gestureRecognizer:UIGestureRecognizer) -> Bool
{
guard
let view:ViewProtocol = subviews.last as? ViewProtocol
else
{
return false
}
let panBack:Bool = view.panBack
return panBack
}
}
| mit | 0115f81f6b1e798c47242ae74f3c86eb | 23.635714 | 74 | 0.447086 | 7.353945 | false | false | false | false |
apple/swift | test/PrintAsObjC/mixed-framework.swift | 3 | 1903 | // RUN: %empty-directory(%t.framework)
// RUN: %empty-directory(%t.framework/Headers)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module -parse-as-library %s -typecheck -emit-objc-header-path %t.framework/Headers/mixed.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=FRAMEWORK %s < %t.framework/Headers/mixed.h
// RUN: %check-in-clang -Watimport-in-framework-header -F %S/Inputs/ %t.framework/Headers/mixed.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t.framework/Headers/mixed-header.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=HEADER %s < %t.framework/Headers/mixed-header.h
// RUN: %check-in-clang -Watimport-in-framework-header -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t.framework/Headers/mixed-header.h
// REQUIRES: objc_interop
// CHECK: #pragma clang diagnostic push
// CHECK-LABEL: #if __has_feature(objc_modules)
// CHECK-NEXT: #if __has_warning("-Watimport-in-framework-header")
// CHECK-NEXT: #pragma clang diagnostic ignored "-Watimport-in-framework-header"
// CHECK-NEXT: #endif
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: #endif
// FRAMEWORK-LABEL: #import <Mixed/Mixed.h>
// HEADER-NOT: __ObjC
// HEADER: #import "{{.*}}Mixed.h"
// HEADER-NOT: __ObjC
import Foundation
// CHECK-LABEL: @interface Dummy : NSNumber
public class Dummy: NSNumber {
// CHECK: - (CIntAlias)getIntAlias SWIFT_WARN_UNUSED_RESULT;
@objc public func getIntAlias() -> CIntAlias {
let result: CInt = 0
return result
}
// FRAMEWORK: @property (nonatomic, readonly) NSInteger extraData;
// HEADER: @property (nonatomic) NSInteger extraData;
@objc public internal(set) var extraData: Int = 0
} // CHECK: @end
// CHECK: #pragma clang diagnostic pop
| apache-2.0 | ebc311f5735b4a4575312ef62b8f722f | 44.309524 | 215 | 0.72412 | 3.209106 | false | false | false | false |
lorentey/swift | test/Constraints/casts.swift | 2 | 5361 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
class B {
init() {}
}
class D : B {
override init() { super.init() }
}
var seven : Double = 7
var pair : (Int, Double) = (1, 2)
var closure : (Int, Int) -> Int = { $0 + $1 }
var d_as_b : B = D()
var b_as_d = B() as! D
var bad_b_as_d : D = B() // expected-error{{cannot convert value of type 'B' to specified type 'D'}}
var d = D()
var b = B()
var d_as_b_2 : B = d
var b_as_d_2 = b as! D
var b_is_d:Bool = B() is D
// FIXME: Poor diagnostic below.
var bad_d_is_b:Bool = D() is B // expected-warning{{always true}}
func base_class_archetype_casts<T : B>(_ t: T) {
var _ : B = t
_ = B() as! T
var _ : T = B() // expected-error{{cannot convert value of type 'B' to specified type 'T'}}
let b = B()
_ = b as! T
var _:Bool = B() is T
var _:Bool = b is T
var _:Bool = t is B // expected-warning{{always true}}
_ = t as! D
}
protocol P1 { func p1() }
protocol P2 { func p2() }
struct S1 : P1 {
func p1() {}
}
class C1 : P1 {
func p1() {}
}
class D1 : C1 {}
struct S2 : P2 {
func p2() {}
}
struct S3 {}
struct S12 : P1, P2 {
func p1() {}
func p2() {}
}
func protocol_archetype_casts<T : P1>(_ t: T, p1: P1, p2: P2, p12: P1 & P2) {
// Coercions.
var _ : P1 = t
var _ : P2 = t // expected-error{{value of type 'T' does not conform to specified type 'P2'}}
// Checked unconditional casts.
_ = p1 as! T
_ = p2 as! T
_ = p12 as! T
_ = t as! S1
_ = t as! S12
_ = t as! C1
_ = t as! D1
_ = t as! S2
_ = S1() as! T
_ = S12() as! T
_ = C1() as! T
_ = D1() as! T
_ = S2() as! T
// Type queries.
var _:Bool = p1 is T
var _:Bool = p2 is T
var _:Bool = p12 is T
var _:Bool = t is S1
var _:Bool = t is S12
var _:Bool = t is C1
var _:Bool = t is D1
var _:Bool = t is S2
}
func protocol_concrete_casts(_ p1: P1, p2: P2, p12: P1 & P2) {
// Checked unconditional casts.
_ = p1 as! S1
_ = p1 as! C1
_ = p1 as! D1
_ = p1 as! S12
_ = p1 as! P1 & P2
_ = p2 as! S1 // expected-warning {{cast from 'P2' to unrelated type 'S1' always fails}}
_ = p12 as! S1
_ = p12 as! S2
_ = p12 as! S12
_ = p12 as! S3
// Type queries.
var _:Bool = p1 is S1
var _:Bool = p1 is C1
var _:Bool = p1 is D1
var _:Bool = p1 is S12
var _:Bool = p1 is P1 & P2
var _:Bool = p2 is S1 // expected-warning {{cast from 'P2' to unrelated type 'S1' always fails}}
var _:Bool = p12 is S1
var _:Bool = p12 is S2
var _:Bool = p12 is S12
var _:Bool = p12 is S3
}
func conditional_cast(_ b: B) -> D? {
return b as? D
}
@objc protocol ObjCProto1 {}
@objc protocol ObjCProto2 {}
protocol NonObjCProto : class {}
@objc class ObjCClass {}
class NonObjCClass {}
func objc_protocol_casts(_ op1: ObjCProto1, opn: NonObjCProto) {
_ = ObjCClass() as! ObjCProto1
_ = ObjCClass() as! ObjCProto2
_ = ObjCClass() as! ObjCProto1 & ObjCProto2
_ = ObjCClass() as! NonObjCProto
_ = ObjCClass() as! ObjCProto1 & NonObjCProto
_ = op1 as! ObjCProto1 & ObjCProto2
_ = op1 as! ObjCProto2
_ = op1 as! ObjCProto1 & NonObjCProto
_ = opn as! ObjCProto1
_ = NonObjCClass() as! ObjCProto1
}
func dynamic_lookup_cast(_ dl: AnyObject) {
_ = dl as! ObjCProto1
_ = dl as! ObjCProto2
_ = dl as! ObjCProto1 & ObjCProto2
}
// Cast to subclass with generic parameter inference
class C2<T> : B { }
class C3<T> : C2<[T]> {
func f(_ x: T) { }
}
var c2i : C2<[Int]> = C3()
var c3iOpt = c2i as? C3
c3iOpt?.f(5)
var b1 = c2i is C3
var c2f: C2<Float>? = b as? C2
var c2f2: C2<[Float]>? = b as! C3
// <rdar://problem/15633178>
var f: (Float) -> Float = { $0 as Float }
var f2: (B) -> Bool = { $0 is D }
func metatype_casts<T, U>(_ b: B.Type, t:T.Type, u: U.Type) {
_ = b is D.Type
_ = T.self is U.Type
_ = type(of: T.self) is U.Type.Type
_ = type(of: b) is D.Type // expected-warning{{always fails}}
_ = b is D.Type.Type // expected-warning{{always fails}}
}
// <rdar://problem/17017851>
func forcedDowncastToOptional(_ b: B) {
var dOpt: D? = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}}
// expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{22-23=?}}
// expected-note@-2{{add parentheses around the cast to silence this warning}}{{18-18=(}}{{25-25=)}}
dOpt = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}}
// expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{14-15=?}}
// expected-note@-2{{add parentheses around the cast to silence this warning}}{{10-10=(}}{{17-17=)}}
dOpt = (b as! D)
_ = dOpt
}
_ = b1 as Int // expected-error {{cannot convert value of type 'Bool' to type 'Int' in coercion}}
_ = seven as Int // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}}
func rdar29894174(v: B?) {
let _ = [v].compactMap { $0 as? D }
}
// When re-typechecking a solution with an 'is' cast applied,
// we would fail to produce a diagnostic.
func process(p: Any?) {
compare(p is String)
// expected-error@-1 {{missing argument for parameter #2 in call}} {{22-22=, <#Bool#>}}
}
func compare<T>(_: T, _: T) {} // expected-note {{'compare' declared here}}
func compare<T>(_: T?, _: T?) {}
_ = nil? as? Int?? // expected-error {{nil literal cannot be the source of a conditional cast}}
| apache-2.0 | 2fb6075cc5163ee1072a5fe770ff83f2 | 22.933036 | 118 | 0.586271 | 2.742199 | false | false | false | false |
phimage/CallbackURLKit | Sources/CallbackURLKit.swift | 1 | 6026 | //
// CallbackURLKit.swift
// CallbackURLKit
/*
The MIT License (MIT)
Copyright (c) 2017 Eric Marchand (phimage)
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
// action ie. url path
public typealias Action = String
// block which handle action and optionally respond to callback
public typealias ActionHandler = (Parameters, @escaping SuccessCallback, @escaping FailureCallback, @escaping CancelCallback) -> Void
// Simple dictionary for parameters
public typealias Parameters = [String: String]
// Callback for response
public typealias SuccessCallback = (Parameters?) -> Void
public typealias FailureCallback = (FailureCallbackError) -> Void
public typealias CancelCallback = () -> Void
// MARK: global functions
// Perform an action on client application
// - Parameter action: The action to perform.
// - Parameter urlScheme: The urlScheme for application to apply action.
// - Parameter parameters: Optional parameters for the action.
// - Parameter onSuccess: callback for success.
// - Parameter onFailure: callback for failure.
// - Parameter onCancel: callback for cancel.
//
// Throws: CallbackURLKitError
public func perform(action: Action, urlScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
try Manager.perform(action: action, urlScheme: urlScheme, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
public func register(action: Action, actionHandler: @escaping ActionHandler) {
Manager.shared[action] = actionHandler
}
// MARK: - Error
public let ErrorDomain = "CallbackURLKit.error"
public enum ErrorCode: Int {
case notSupportedAction = 1 // "(action) not supported by (appName)"
case missingParameter = 2 // when handling an action, could return an error to show that parameters are missing
case missingErrorCode = 3
}
// Implement this protocol to custom the error into Client
public protocol FailureCallbackError: Error {
var code: Int {get}
var message: String {get}
}
extension FailureCallbackError {
public var XCUErrorParameters: Parameters {
return [kXCUErrorCode: "\(self.code)", kXCUErrorMessage: self.message]
}
public var XCUErrorQuery: String {
return XCUErrorParameters.queryString
}
}
extension NSError: FailureCallbackError {
public var message: String { return localizedDescription }
}
extension FailureCallbackError {
public static func error(code: ErrorCode, failureReason: String) -> NSError {
return error(code: code.rawValue, failureReason: failureReason)
}
public static func error(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: ErrorDomain, code: code, userInfo: userInfo)
}
}
// Framework errors
public enum CallbackURLKitError: Error {
// It's seems that application with specified scheme has not installed
case appWithSchemeNotInstalled(scheme: String)
// Failed to create NSURL for request
case failedToCreateRequestURL(components: URLComponents)
// You specify a callback but no manager.callbackURLScheme defined
case callbackURLSchemeNotDefined
}
// MARK: - x-callback-url
let kXCUPrefix = "x-"
let kXCUHost = "x-callback-url"
// Parameters
// The friendly name of the source app calling the action. If the action in the target app requires user interface elements, it may be necessary to identify to the user the app requesting the action.
let kXCUSource = "x-source"
// If the action in the target method is intended to return a result to the source app, the x-callback parameter should be included and provide a URL to open to return to the source app. On completion of the action, the target app will open this URL, possibly with additional parameters tacked on to return a result to the source app. If x-success is not provided, it is assumed that the user will stay in the target app on successful completion of the action.
let kXCUSuccess = "x-success"
// URL to open if the requested action generates an error in the target app. This URL will be open with at least the parameters “errorCode=code&errorMessage=message”. If x-error is not present, and a error occurs, it is assumed the target app will report the failure to the user and remain in the target app.
let kXCUError = "x-error"
let kXCUErrorCode = "errorCode"
let kXCUErrorMessage = "errorMessage"
// URL to open if the requested action is cancelled by the user. In the case where the target app offer the user the option to “cancel” the requested action, without a success or error result, this the the URL that should be opened to return the user to the source app.
let kXCUCancel = "x-cancel"
// MARK: - framework strings
let kResponse = "response"
let kResponseType = "responseType"
let kRequestID = "requestID"
let protocolKeys = [kResponse, kResponseType, kRequestID]
| mit | d44a8c6c9b0327bedf91a6d864ac33a4 | 46.385827 | 460 | 0.760552 | 4.507865 | false | false | false | false |
wookay/Look | samples/LookSample/Pods/C4/C4/Core/C4Rect.swift | 3 | 10676 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Foundation
import CoreGraphics
/// A structure that contains the location and dimensions of a rectangle.
public struct C4Rect : Equatable, CustomStringConvertible {
/// The origin (top-left) of the rect.
public var origin: C4Point
/// The size (width / height) of the rect.
public var size: C4Size
/// The width of the rect.
public var width : Double {
get {
return size.width
} set {
size.width = newValue
}
}
/// The height of the rect.
public var height : Double {
get {
return size.height
} set {
size.height = newValue
}
}
/// Initializes a new C4Rect with the origin {0,0} and the size {0,0}
///
/// ````
/// let r = C4Rect()
/// ````
public init() {
self.init(0,0,0,0)
}
/// Initializes a new C4Rect with the origin {x,y} and the size {w,h}
///
/// ````
/// let r = C4Rect(0.0,0.0,10.0,10.0)
/// ````
public init(_ x: Double, _ y: Double, _ w: Double, _ h: Double) {
origin = C4Point(x, y)
size = C4Size(w, h)
}
/// Initializes a new C4Rect with the origin {x,y} and the size {w,h}, converting values from Int to Double
///
/// ````
/// let r = C4Rect(0,0,10,10)
/// ````
public init(_ x: Int, _ y: Int, _ w: Int, _ h: Int) {
origin = C4Point(x, y)
size = C4Size(w, h)
}
/// Initializes a new C4Rect with the origin {o.x,o.y} and the size {s.w,s.h}
///
/// ````
/// let p = C4Point()
/// let s = C4Size()
/// let r = C4Rect(p,s)
/// ````
public init(_ o: C4Point, _ s: C4Size) {
origin = o
size = s
}
/// Initializes a C4Rect from a CGRect
public init(_ rect: CGRect) {
origin = C4Point(rect.origin)
size = C4Size(rect.size)
}
/// Returns a rectangle that contains all of the specified coordinates in an array.
///
/// ````
/// let pts = [C4Point(), C4Point(0,5), C4Point(10,10), C4Point(9,8)]
/// let r = C4Rect(pts) //-> {{0.0, 0.0}, {10.0, 10.0}}
/// ````
///
/// - parameter points: An array of C4Point coordinates
public init(_ points:[C4Point]) {
let count = points.count
assert(count >= 2, "To create a Polygon you need to specify an array of at least 2 points")
var cgPoints = [CGPoint]()
for i in 0..<count {
cgPoints.append(CGPoint(points[i]))
}
let r = CGRectMakeFromPoints(cgPoints)
let f = C4Rect(r)
self.init(f.origin,f.size)
}
/// Returns a rectangle that contains the specified coordinates in a tuple.
///
/// ````
/// let pts = (C4Point(), C4Point(0,5))
/// let r = C4Rect(pts)
/// ````
///
/// - parameter points: An tuple of C4Point coordinates
public init(_ points: (C4Point, C4Point)) {
let r = CGRectMakeFromPoints([CGPoint(points.0),CGPoint(points.1)])
let f = C4Rect(r)
self.init(f.origin,f.size)
}
//MARK: - Comparing
/// Returns whether two rectangles intersect.
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(5,5,10,10)
/// let r3 = C4Rect(10,10,10,10)
/// r1.intersects(r2) //-> true
/// r1.intersects(r3) //-> false
/// ````
///
/// - parameter rect1: The first rectangle to examine.
/// - parameter rect2: The second rectangle to examine.
///
/// - returns: true if the two specified rectangles intersect; otherwise, false.
public func intersects(r: C4Rect) -> Bool {
return CGRectIntersectsRect(CGRect(self), CGRect(r))
}
//MARK: - Center & Max
/// The center point of the receiver.
///
/// ````
/// let r = C4Rect(0,0,10,10)
/// r.center //-> {5,5}
/// ````
public var center: C4Point {
get {
return C4Point(origin.x + size.width/2, origin.y + size.height/2)
}
set {
origin.x = newValue.x - size.width/2
origin.y = newValue.y - size.height/2
}
}
/// The bottom-right point of the receiver.
///
/// ````
/// let r = C4Rect(5,5,10,10)
/// r.max //-> {15,15}
/// ````
public var max: C4Point {
get {
return C4Point(origin.x + size.width, origin.y + size.height)
}
}
/// Checks to see if the receiver has zero size and position
///
/// ````
/// let r = C4Point()
/// r.isZero() //-> true
/// ````
///
/// - returns: true if origin = {0,0} and size = {0,0}
public func isZero() -> Bool {
return origin.isZero() && size.isZero()
}
//MARK: - Membership
/// Returns whether a rectangle contains a specified point.
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(5,5,10,10)
/// let p = C4Rect(2,2,2,2)
/// r1.contains(p) //-> true
/// r2.contains(p) //-> false
/// ````
///
/// - parameter rect: The rectangle to examine.
/// - parameter point: The point to examine.
///
/// - returns: true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false.
public func contains(point: C4Point) -> Bool {
return CGRectContainsPoint(CGRect(self), CGPoint(point))
}
/// Returns whether the first rectangle contains the second rectangle.
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(5,5,10,10)
/// let r3 = C4Rect(2,2,2,2)
/// r1.contains(r2) //-> false
/// r1.contains(r3) //-> true
/// ````
///
/// - parameter rect1: The rectangle to examine for containment of the rectangle passed in rect2.
/// - parameter rect2: The rectangle to examine for being contained in the rectangle passed in rect1.
/// - parameter true: if the rectangle specified by rect2 is contained in the rectangle passed in rect1; otherwise, false.
public func contains(rect: C4Rect) -> Bool {
return CGRectContainsRect(CGRect(self), CGRect(rect))
}
/// A string representation of the rect.
///
/// - returns: A string formatted to look like {{x,y},{w,h}}
public var description : String {
get {
return "{\(origin),\(size)}"
}
}
}
//MARK: - Comparing
/// Checks to see if two C4Rects share identical origin and size
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(0,0,10,10.5)
/// println(r1 == r2) //-> false
/// ````
///
/// - returns: A bool, `true` if the rects are identical, otherwise `false`.
public func == (lhs: C4Rect, rhs: C4Rect) -> Bool {
return lhs.origin == rhs.origin && lhs.size == rhs.size
}
//MARK: - Manipulating
/// Returns the intersection of two rectangles.
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(5,5,10,10)
/// intersection(r1,r2) //-> {5,5,5,5}
/// ````
///
/// - parameter rect1: The first source rectangle.
/// - parameter rect2: The second source rectangle.
///
/// - returns: A rectangle that represents the intersection of the two specified rectangles.
public func intersection(rect1: C4Rect, rect2: C4Rect) -> C4Rect {
return C4Rect(CGRectIntersection(CGRect(rect1), CGRect(rect2)))
}
/// Returns the smallest rectangle that contains the two source rectangles.
///
/// ````
/// let r1 = C4Rect(0,0,10,10)
/// let r2 = C4Rect(5,5,10,10)
/// intersection(r1,r2) //-> {0,0,15,15}
/// ````
///
/// - parameter r1: The first source rectangle.
/// - parameter r2: The second source rectangle.
///
/// - returns: The smallest rectangle that completely contains both of the source rectangles.
public func union(rect1: C4Rect, rect2: C4Rect) -> C4Rect {
return C4Rect(CGRectUnion(CGRect(rect1), CGRect(rect2)))
}
/// Returns the smallest rectangle that results from converting the source rectangle values to integers.
///
/// ````
/// let r1 = C4Rect(0.1,0.1,10.6,10.6)
/// let r2 = C4Rect(5,5,10,10)
/// intersection(r1,r2) //-> {5,5,5,5}
/// ````
///
/// - parameter rect: The source rectangle.
///
/// - returns: A rectangle with the smallest integer values for its origin and size that contains the source rectangle.
public func integral(r: C4Rect) -> C4Rect {
return C4Rect(CGRectIntegral(CGRect(r)))
}
/// Returns a rectangle with a positive width and height.
///
/// ````
/// let r = C4Rect(0.1,0.1,10.6,10.6)
/// integral(r) //-> {0,0,11,11}
/// ````
///
/// - parameter rect: The source rectangle.
///
/// - returns: A rectangle that represents the source rectangle, but with positive width and height values.
public func standardize(r: C4Rect) -> C4Rect {
return C4Rect(CGRectStandardize(CGRect(r)))
}
/// Returns a rectangle that is smaller or larger than the source rectangle, with the same center point.
///
/// ````
/// let r = C4Rect(0,0,10,10)
/// inset(r, 1, 1) //-> {1,1,8,8}
/// ````
///
/// - parameter rect: The source C4Rect structure.
/// - parameter dx: The x-coordinate value to use for adjusting the source rectangle.
/// - parameter dy: The y-coordinate value to use for adjusting the source rectangle.
///
/// - returns: A rectangle.
public func inset(r: C4Rect, dx: Double, dy: Double) -> C4Rect {
return C4Rect(CGRectInset(CGRect(r), CGFloat(dx), CGFloat(dy)))
}
// MARK: - Casting to CGRect
public extension CGRect {
/// Initializes a CGRect from a C4Rect
public init(_ rect: C4Rect) {
origin = CGPoint(rect.origin)
size = CGSize(rect.size)
}
} | mit | e13e397fc41988ee4745eda4a8c2850c | 30.307918 | 126 | 0.588759 | 3.465909 | false | false | false | false |
ulrikdamm/Sqlable | SqlableTests/SqlableConstraintTests.swift | 1 | 2270 | //
// SqlableConstraintTests.swift
// Sqlable
//
// Created by Ulrik Damm on 15/12/2015.
// Copyright © 2015 Ufd.dk. All rights reserved.
//
import XCTest
@testable import Sqlable
struct Table {
let id : Int?
let value1 : Int
let value2 : Int
}
extension Table : Sqlable {
static let id = Column("id", .integer, PrimaryKey(autoincrement: true))
static let value1 = Column("value_1", .integer)
static let value2 = Column("value_2", .integer)
static let tableLayout = [id, value1, value2]
static let tableConstraints : [TableConstraint] = [Unique(value1, value2)]
func valueForColumn(_ column : Column) -> SqlValue? {
switch column {
case Table.id: return id
case Table.value1: return value1
case Table.value2: return value2
case _: return nil
}
}
init(row : ReadRow) throws {
id = try row.get(Table.id)
value1 = try row.get(Table.value1)
value2 = try row.get(Table.value2)
}
}
class SqliteConstraintsTests: XCTestCase {
let path = documentsPath() + "/test.sqlite"
var db : SqliteDatabase!
override func setUp() {
_ = try? SqliteDatabase.deleteDatabase(at: path)
db = try! SqliteDatabase(filepath: path)
try! db.createTable(Table.self)
}
func testUniqueConstraintNoViolation() {
do {
try Table(id: nil, value1: 1, value2: 2).insert().run(db)
try Table(id: nil, value1: 1, value2: 1).insert().run(db)
} catch let error {
XCTAssert(false, "Failed with error: \(error)")
}
}
func testUniqueConstraintViolation() {
var didFail = false
do {
try Table(id: nil, value1: 1, value2: 2).insert().run(db)
try Table(id: nil, value1: 1, value2: 2).insert().run(db)
} catch SqlError.sqliteConstraintViolation(_) {
didFail = true
} catch let error {
XCTAssert(false, "Failed with error: \(error)")
}
XCTAssert(didFail)
XCTAssertEqual(try! Table.count().run(db), 1)
}
func testConstraintViolationRollback() {
do {
try db.transaction { db in
try Table(id: nil, value1: 1, value2: 2).insert().run(db)
try Table(id: nil, value1: 1, value2: 2).insert().run(db)
}
} catch SqlError.sqliteConstraintViolation(_) {
// Expected
} catch let error {
XCTAssert(false, "Failed with error: \(error)")
}
XCTAssert(try! Table.count().run(db) == 0)
}
}
| mit | 70b06bc0f89bc5bd2dea7c4015dcfd31 | 23.663043 | 75 | 0.667254 | 2.997358 | false | true | false | false |
croberts22/Cardinal | Cardinal/Classes/Logger.swift | 1 | 5286 | //
// Logger.swift
// Cardinal
//
// Created by Corey Roberts on 3/13/19.
//
import Foundation
public class Log {
public class func log(_ severity: LoggerLevel = .debug, category: LoggerCategory = .none, file: String = #file, function: String = #function, lineNumber: Int = #line, closure: () -> String?) {
if let string = closure() {
// Logger.log(asynchronous: false,
// category: category,
// flag: severity,
// file: function,
// function: function,
// lineNumber: lineNumber,
// string: string)
}
}
// MARK: - Verbose Logging Methods
public class func verbose(_ category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line, closure: () -> String?) {
log(.verbose, category: category, file: file, function: function, lineNumber: lineNumber, closure: closure)
}
public class func verbose(_ category: LoggerCategory = .none, _ string: String, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.verbose, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
public class func verbose(_ string: String, category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.verbose, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
// MARK: - Debug Logging Methods
public class func debug(_ category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line, closure: () -> String?) {
log(.debug, category: category, file: file, function: function, lineNumber: lineNumber, closure: closure)
}
public class func debug(_ category: LoggerCategory = .none, _ string: String, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.debug, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
public class func debug(_ string: String, category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.debug, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
// MARK: - Info Logging Methods
public class func info(_ category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line, closure: () -> String?) {
log(.info, category: category, file: file, function: function, lineNumber: lineNumber, closure: closure)
}
public class func info(_ category: LoggerCategory = .none, _ string: String, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.info, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
public class func info(_ string: String, category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.info, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
// MARK: - Warning Logging Methods
public class func warning(_ category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line, closure: () -> String?) {
log(.warning, category: category, file: file, function: function, lineNumber: lineNumber, closure: closure)
}
public class func warning(_ category: LoggerCategory = .none, _ string: String, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.warning, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
public class func warning(_ string: String, category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.warning, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
// MARK: - Error Logging Methods
public class func error(_ category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line, closure: () -> String?) {
log(.error, category: category, file: file, function: function, lineNumber: lineNumber, closure: closure)
}
public class func error(_ category: LoggerCategory = .none, _ string: String, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.error, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
public class func error(_ string: String, category: LoggerCategory = .none, function: String = #function, file: String = #file, lineNumber: Int = #line) {
log(.error, category: category, file: file, function: function, lineNumber: lineNumber, closure: {string})
}
}
| mit | d62be611e7c86530792f973617b26d86 | 51.336634 | 196 | 0.637344 | 4.301058 | false | false | false | false |
cpoutfitters/cpoutfitters | CPOutfitters/LoginViewController.swift | 1 | 3939 | //
// LoginViewController.swift
// CPOutfitters
//
// Created by Aditya Purandare on 08/03/16.
// Copyright © 2016 SnazzyLLama. All rights reserved.
//
import UIKit
import ParseUI
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var backgroundImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
// if (PFUser.currentUser() == nil) {
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! UIViewController
//// self.presentViewController(viewController, animated: true, completion: nil)
// })
// }
}
override func viewWillAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogin(sender: AnyObject) {
let email = emailTextField.text
let password = passwordTextField.text
if (email!.characters.count < 5) {
let alert = UIAlertController(title: "Invalid", message: "Please enter a valid email address", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
} else if (password!.characters.count < 8) {
let alert = UIAlertController(title: "Invalid", message: "Password must be greater than 8 characters", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
emailTextField.enabled = false
passwordTextField.enabled = false
// Send a request to login
PFUser.logInWithUsernameInBackground(email!.lowercaseString, password: password!, block: { (user: PFUser?, error: NSError?) -> Void in
// Stop the spinner
spinner.stopAnimating()
if let error = error {
let alert = UIAlertController(title: "Login error", message: "Invalid username/password combination", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: { () -> Void in
self.emailTextField.enabled = true
self.passwordTextField.enabled = true
})
} else {
NSNotificationCenter.defaultCenter().postNotificationName(userDidLoginNotification, object: nil)
}
})
}
}
func dismissKeyboard() {
view.endEditing(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.
}
*/
}
| apache-2.0 | 6b8e88d24cd0358e3d856c32d42fc8f7 | 40.020833 | 165 | 0.617826 | 5.454294 | false | false | false | false |
maor-eini/Chop-Chop | chopchop/chopchop/LoginInputController.swift | 1 | 1574 | //
// LoginInputController.swift
// chopchop
//
// Created by Maor Eini on 13/02/2017.
// Copyright © 2017 Maor Eini. All rights reserved.
//
import UIKit
class LoginInputController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
self.nameTextField.delegate = self
self.emailTextField.delegate = self
self.passwordTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
@IBAction func textFieldReturn(_ sender: UITextField) {
self.view.endEditing(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 | 84aaa3375106fa6046c4d766eef774ba | 26.596491 | 106 | 0.668786 | 5.314189 | false | false | false | false |
neoneye/SwiftyFORM | Example/Other/OptionsViewController.swift | 1 | 3182 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class OptionsViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "Options"
builder.toolbarMode = .none
builder += SectionHeaderTitleFormItem().title("Options")
builder += adoptBitcoin
builder += exploreSpace
builder += worldPeace
builder += stopGlobalWarming
builder += SectionFormItem()
builder += randomizeButton
}
lazy var adoptBitcoin: OptionPickerFormItem = {
let instance = OptionPickerFormItem()
instance.title("Adopt Bitcoin?").placeholder("required")
instance.append([
"Strongly disagree",
"Disagree",
"Neutral",
"Agree",
"Strongly agree"
])
instance.selectOptionWithTitle("Neutral")
instance.valueDidChange = { (selected: OptionRowModel?) in
print("adopt bitcoin: \(String(describing: selected))")
}
return instance
}()
lazy var exploreSpace: OptionPickerFormItem = {
let instance = OptionPickerFormItem()
instance.title("Explore Space?").placeholder("required")
instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree")
instance.selectOptionWithTitle("Neutral")
instance.valueDidChange = { (selected: OptionRowModel?) in
print("explore space: \(String(describing: selected))")
}
return instance
}()
lazy var worldPeace: OptionPickerFormItem = {
let instance = OptionPickerFormItem()
instance.title("World Peace?").placeholder("required")
instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree")
instance.selectOptionWithTitle("Neutral")
instance.valueDidChange = { (selected: OptionRowModel?) in
print("world peace: \(String(describing: selected))")
}
return instance
}()
lazy var stopGlobalWarming: OptionPickerFormItem = {
let instance = OptionPickerFormItem()
instance.title("Stop Global Warming?").placeholder("required")
instance.append("Strongly disagree", identifier: "strongly_disagree")
instance.append("Disagree", identifier: "disagree")
instance.append("Neutral", identifier: "neutral")
instance.append("Agree", identifier: "agree")
instance.append("Strongly agree", identifier: "strongly_agree")
instance.selectOptionWithIdentifier("neutral")
instance.valueDidChange = { (selected: OptionRowModel?) in
print("stop global warming: \(String(describing: selected))")
}
return instance
}()
lazy var randomizeButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title = "Randomize"
instance.action = { [weak self] in
self?.randomize()
}
return instance
}()
func assignRandomOption(_ optionField: OptionPickerFormItem) {
var selected: OptionRowModel? = nil
let options = optionField.options
if options.count > 0 {
let i = Int.random(in: 0..<options.count)
if i < options.count {
selected = options[i]
}
}
optionField.selected = selected
}
func randomize() {
assignRandomOption(adoptBitcoin)
assignRandomOption(exploreSpace)
assignRandomOption(worldPeace)
assignRandomOption(stopGlobalWarming)
}
}
| mit | dcecc3b86957b7e58d94e3f82711e60e | 31.141414 | 116 | 0.732872 | 3.833735 | false | false | false | false |
proudcat/code-labs | swift/concentration/concentration/Concentration.swift | 1 | 1988 | //
// Concentration.swift
// concentration
//
// Created by koala on 2019/11/7.
// Copyright © 2019 goooku. All rights reserved.
//
import Foundation
struct Concentration
{
private(set) var cards = [Card]()
private var indexOfOneAndOnlyFaceUpCard : Int? {
get{
var foundIndex: Int?
for index in cards.indices{
if cards[index].isFaceUp{
if foundIndex == nil{
foundIndex = index
}else{
foundIndex = nil
}
}
}
return foundIndex
}
set {
for index in cards.indices{
cards[index].isFaceUp = (index == newValue)
}
}
}
init(numberOfPairsOfCards: Int) {
assert(numberOfPairsOfCards > 0,"Concentration.init(numberOfPairsOfCards:\(numberOfPairsOfCards)):numberOfPairsOfCards should bigger than zero")
for _ in 1...numberOfPairsOfCards{
let card = Card()
cards += [card,card]
}
shuffleCards()
}
mutating func shuffleCards(){
for _ in cards.indices{
cards.swapAt(cards.count.arc4random, cards.count.arc4random)
}
}
mutating func chooseCard(at index:Int){
assert(cards.indices.contains(index),"Concentration.chooseCard(at:\(index)):chosen index not in the card")
if !cards[index].isMatched {
if let matchIndex = indexOfOneAndOnlyFaceUpCard, matchIndex != index {
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
}
cards[index].isFaceUp = true
}else{
indexOfOneAndOnlyFaceUpCard = index
}
}else{
}
}
}
| mit | 394cc75aeaa578059545f1bd38ec331f | 26.219178 | 152 | 0.506291 | 5.005038 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/Event.swift | 1 | 12337 | import Foundation
/// An event happening at a certain time and location, such as a concert, lecture, or festival.
///
/// * Ticketing information may be added via the offers property.
/// * Repeated events may be structured as separate Event objects.
public class Event: Thing {
/// The subject matter of the content.
public var about: Thing?
/// An actor - in tv, radio, movie, video games etc. - or in an event.
///
/// Actors can be associated with individual items or with a series, episode, clip.
public var actors: [Person]?
/// The overall rating, based on a collection of reviews or ratings, of the item.
public var aggregateRating: AggregateRating?
/// A person or organization attending the event.
public var attendees: [OrganizationOrPerson]?
/// An intended audience
///
/// ## Example
/// A group for whom something was created.
///
/// ## Supersedes
/// _serviceAudience_
public var audience: Audience?
/// The person or organization who wrote a composition, or who is the composer of a work performed at some event.
public var composer: OrganizationOrPerson?
/// A secondary contributor to the CreativeWork or Event.
public var contributor: OrganizationOrPerson?
/// A director of an event.
///
/// Directors can be associated with individual items or with a series, episode, clip.
public var directors: [Person]?
/// The time admission will commence.
public var doorTime: DateTime?
/// The duration of the item (movie, audio recording, event, etc.) in ISO 8601 date format.
public var duration: Duration?
/// The end date and time of the item (in ISO 8601 date format).
public var endDate: DateOnlyOrDateTime?
/// An eventStatus of an event represents its status; particularly useful when an event is cancelled or rescheduled.
public var eventStatus: EventStatus?
/// A person or organization that supports (sponsors) something through some kind of financial contribution.
public var funder: OrganizationOrPerson?
/// The language of the content or performance or used in an action.
///
/// Please use one of the language codes from the IETF BCP 47 standard.
/// ## See Also
/// _availableLanguage_
public var inLanguage: LanguageOrText?
/// A flag to signal that the publication is accessible for free.
/// ## Supersedes
/// _free_
public var isAccessibleForFree: Bool?
/// The location of for example where the event is happening, an organization is located, or where an action takes
/// place.
public var location: PlaceOrPostalAddressOrText?
/// The total number of individuals that may attend an event or venue.
public var maximumAttendeeCapacity: Int?
/// An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, perform a
/// service, or give away tickets to an event.
public var offers: [Offer]?
/// An organizer of an Event.
public var organizer: OrganizationOrPerson?
/// A performer at the event—for example, a presenter, musician, musical group or actor.
public var performers: [OrganizationOrPerson]?
/// Used in conjunction with eventStatus for rescheduled or cancelled events.
///
/// This property contains the previously scheduled start date. For rescheduled events, the startDate property
/// should be used for the newly scheduled start date. In the (rare) case of an event that has been postponed and
/// rescheduled multiple times, this field may be repeated.
public var previousStartDate: DateOnly?
/// The `CreativeWork` that captured all or part of this Event.
/// ## Inverse Property
/// _recordedAt_
public var recordedIn: CreativeWork?
/// The number of attendee places for an event that remain unallocated.
public var remainingAttendeeCapacity: Int?
/// A review of the item.
/// ## Supersedes
/// _reviews_
public var reviews: [Review]?
/// A person or organization that supports a thing through a pledge, promise, or financial contribution.
///
/// ## For Example
/// A sponsor of a Medical Study or a corporate sponsor of an event.
public var sponsor: OrganizationOrPerson?
/// The start date and time of the item (in ISO 8601 date format).
public var startDate: DateOnlyOrDateTime?
/// An Event that is part of this event.
///
/// ## For Example
/// A conference event includes many presentations, each of which is a subEvent of the conference.
///
/// ## Supersedes
/// _subEvents_
/// ## Inverse Property
/// _superEvent_
public var subEvents: [Event]?
/// An event that this event is a part of.
///
/// ## For Example
/// A collection of individual music performances might each have a music festival as their superEvent.
///
/// ## Inverse Property
/// _subEvent_
public var superEvent: Event?
/// Organization or person who adapts a creative work to different languages, regional differences and technical
/// requirements of a target market, or that translates during some event.
public var translator: OrganizationOrPerson?
/// The typical expected age range.
///
/// ## For Example
/// * '7-9'
/// * '11-'
public var typicalAgeRange: String?
/// A work featured in some event.
///
/// ## For Example
/// Exhibited in an ExhibitionEvent.
public var workFeatured: CreativeWork?
/// A work performed in some event, for example a play performed in a TheaterEvent.
public var workPerformed: CreativeWork?
internal enum EventCodingKeys: String, CodingKey {
case about
case actors = "actor"
case aggregateRating
case attendees = "attendee"
case audience
case composer
case contributor
case directors = "director"
case doorTime
case duration
case endDate
case eventStatus
case funder
case inLanguage
case isAccessibleForFree
case location
case maximumAttendeeCapacity
case offers
case organizer
case performers = "performer"
case previousStartDate
case recordedIn
case remainingAttendeeCapacity
case reviews = "review"
case sponsor
case startDate
case subEvents = "subEvent"
case superEvent
case translator
case typicalAgeRange
case workFeatured
case workPerformed
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: EventCodingKeys.self)
about = try container.decodeIfPresent(Thing.self, forKey: .about)
actors = try container.decodeIfPresent([Person].self, forKey: .actors)
aggregateRating = try container.decodeIfPresent(AggregateRating.self, forKey: .aggregateRating)
attendees = try container.decodeIfPresent([OrganizationOrPerson].self, forKey: .attendees)
audience = try container.decodeIfPresent(Audience.self, forKey: .audience)
composer = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .composer)
contributor = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .contributor)
directors = try container.decodeIfPresent([Person].self, forKey: .directors)
doorTime = try container.decodeIfPresent(DateTime.self, forKey: .doorTime)
duration = try container.decodeIfPresent(Duration.self, forKey: .duration)
eventStatus = try container.decodeIfPresent(EventStatus.self, forKey: .eventStatus)
funder = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .funder)
inLanguage = try container.decodeIfPresent(LanguageOrText.self, forKey: .inLanguage)
isAccessibleForFree = try container.decodeIfPresent(Bool.self, forKey: .isAccessibleForFree)
location = try container.decodeIfPresent(PlaceOrPostalAddressOrText.self, forKey: .location)
maximumAttendeeCapacity = try container.decodeIfPresent(Int.self, forKey: .maximumAttendeeCapacity)
offers = try container.decodeIfPresent([Offer].self, forKey: .offers)
organizer = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .organizer)
performers = try container.decodeIfPresent([OrganizationOrPerson].self, forKey: .performers)
previousStartDate = try container.decodeIfPresent(DateOnly.self, forKey: .previousStartDate)
recordedIn = try container.decodeIfPresent(CreativeWork.self, forKey: .recordedIn)
remainingAttendeeCapacity = try container.decodeIfPresent(Int.self, forKey: .remainingAttendeeCapacity)
reviews = try container.decodeIfPresent([Review].self, forKey: .reviews)
sponsor = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .sponsor)
startDate = try container.decodeIfPresent(DateOnlyOrDateTime.self, forKey: .startDate)
subEvents = try container.decodeIfPresent([Event].self, forKey: .subEvents)
superEvent = try container.decodeIfPresent(Event.self, forKey: .superEvent)
translator = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .translator)
typicalAgeRange = try container.decodeIfPresent(String.self, forKey: .typicalAgeRange)
workFeatured = try container.decodeIfPresent(CreativeWork.self, forKey: .workFeatured)
workPerformed = try container.decodeIfPresent(CreativeWork.self, forKey: .workPerformed)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: EventCodingKeys.self)
try container.encodeIfPresent(about, forKey: .about)
try container.encodeIfPresent(actors, forKey: .actors)
try container.encodeIfPresent(aggregateRating, forKey: .aggregateRating)
try container.encodeIfPresent(attendees, forKey: .attendees)
try container.encodeIfPresent(audience, forKey: .audience)
try container.encodeIfPresent(composer, forKey: .composer)
try container.encodeIfPresent(contributor, forKey: .contributor)
try container.encodeIfPresent(directors, forKey: .directors)
try container.encodeIfPresent(doorTime, forKey: .doorTime)
try container.encodeIfPresent(duration, forKey: .duration)
try container.encodeIfPresent(eventStatus, forKey: .eventStatus)
try container.encodeIfPresent(funder, forKey: .funder)
try container.encodeIfPresent(inLanguage, forKey: .inLanguage)
try container.encodeIfPresent(isAccessibleForFree, forKey: .isAccessibleForFree)
try container.encodeIfPresent(location, forKey: .location)
try container.encodeIfPresent(maximumAttendeeCapacity, forKey: .maximumAttendeeCapacity)
try container.encodeIfPresent(offers, forKey: .offers)
try container.encodeIfPresent(organizer, forKey: .organizer)
try container.encodeIfPresent(performers, forKey: .performers)
try container.encodeIfPresent(previousStartDate, forKey: .previousStartDate)
try container.encodeIfPresent(recordedIn, forKey: .recordedIn)
try container.encodeIfPresent(remainingAttendeeCapacity, forKey: .remainingAttendeeCapacity)
try container.encodeIfPresent(reviews, forKey: .reviews)
try container.encodeIfPresent(sponsor, forKey: .sponsor)
try container.encodeIfPresent(startDate, forKey: .startDate)
try container.encodeIfPresent(subEvents, forKey: .subEvents)
try container.encodeIfPresent(superEvent, forKey: .superEvent)
try container.encodeIfPresent(translator, forKey: .translator)
try container.encodeIfPresent(typicalAgeRange, forKey: .typicalAgeRange)
try container.encodeIfPresent(workFeatured, forKey: .workFeatured)
try container.encodeIfPresent(workPerformed, forKey: .workPerformed)
try super.encode(to: encoder)
}
}
| mit | a4c724dcad8418fa156e977bb88fce00 | 44.677778 | 120 | 0.695532 | 4.86317 | false | false | false | false |
gnachman/iTerm2 | iTermFileProvider/FileProviderFetcher.swift | 2 | 2772 | //
// FileProviderFetcher.swift
// FileProvider
//
// Created by George Nachman on 6/10/22.
//
import Foundation
import FileProvider
import FileProviderService
actor FileProviderFetcher {
private let temporaryDirectoryURL: URL
private let domain: NSFileProviderDomain
private let remoteService: RemoteService
struct FetchRequest: CustomDebugStringConvertible {
let itemIdentifier: NSFileProviderItemIdentifier
let requestedVersion: NSFileProviderItemVersion?
let request: NSFileProviderRequest
var debugDescription: String {
return "<FetchRequest \(itemIdentifier.rawValue)>"
}
}
init(domain: NSFileProviderDomain, remoteService: RemoteService) {
self.domain = domain
self.remoteService = remoteService
guard let manager = NSFileProviderManager(for: domain) else {
print("Failed to create manager for domain \(domain)")
fatalError()
}
temporaryDirectoryURL = try! manager.temporaryDirectoryURL()
}
func fetchContents(_ request: FetchRequest,
progress: Progress) async throws -> URL {
return try await logging("Fetch \(request)") {
let path = request.itemIdentifier.rawValue
let destination = makeTemporaryURL("fetch")
log("Destination will be \(destination)")
_ = try await Task {
FileManager.default.createFile(atPath: destination.path, contents: nil)
let handle = try FileHandle(forWritingTo: destination)
let stream = await remoteService.fetch(path)
log("Beginning collecting chunks")
for await update in stream {
switch update {
case .failure(let error):
log("Error during fetch: \(error)")
throw error
case .success(let data):
log("Received \(data.count) bytes")
try handle.write(contentsOf: data)
progress.completedUnitCount += Int64(data.count)
log("Completed unit count is now \(progress.completedUnitCount)")
}
log("Continue for await loop")
}
try handle.close()
}.value
return destination
}
}
private func makeTemporaryURL(_ purpose: String, _ ext: String? = nil) -> URL {
var parts = [purpose, "-", UUID().uuidString]
if let ext = ext {
parts.append("." + ext)
}
let filename = parts.joined(separator: "")
return temporaryDirectoryURL.appendingPathComponent(filename)
}
}
| gpl-2.0 | c3741651e51fb7a15134372844adb887 | 35.96 | 89 | 0.586941 | 5.622718 | false | false | false | false |
StanZabroda/Hydra | Hydra/HRFriendAudioCell.swift | 1 | 2949 | //
// HRFriendAudioCell.swift
// Hydra
//
// Created by Evgeny Evgrafov on 9/22/15.
// Copyright © 2015 Evgeny Evgrafov. All rights reserved.
//
import UIKit
class HRFriendAudioCell: UITableViewCell {
var audioAristLabel : UILabel
var audioTitleLabel : UILabel
var audioDurationTime : UILabel!
var progressView : UIProgressView!
var downloadButton : UIButton!
var allMusicController : HRFriendAudioController!
var audioModel : HRAudioItemModel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
self.audioTitleLabel = UILabel()
self.audioTitleLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 15)
self.audioTitleLabel.textColor = UIColor.blackColor()
self.audioAristLabel = UILabel()
self.audioAristLabel.font = UIFont(name: "HelveticaNeue-Light", size: 13)
self.audioAristLabel.textColor = UIColor.grayColor()
self.progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default)
self.progressView.tintColor = UIColor.blackColor()
self.progressView.hidden = true
self.downloadButton = UIButton(type: UIButtonType.System)
self.downloadButton.setImage(UIImage(named: "downloadButton"), forState: UIControlState.Normal)
self.downloadButton.tintColor = UIColor.blackColor()
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
self.downloadButton.addTarget(self, action: "startDownload", forControlEvents: UIControlEvents.TouchUpInside)
self.contentView.addSubview(self.audioAristLabel)
self.contentView.addSubview(self.audioTitleLabel)
self.contentView.addSubview(self.progressView)
self.contentView.addSubview(self.downloadButton)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//audioTitleLabel
self.audioTitleLabel.frame = CGRectMake(self.separatorInset.left, 10, screenSizeWidth-70, 20)
self.audioAristLabel.frame = CGRectMake(self.separatorInset.left, 40, screenSizeWidth-70, 20)
self.progressView.frame = CGRectMake(0, self.contentView.frame.height-2, self.contentView.frame.width, 2)
self.downloadButton.frame = CGRectMake(self.contentView.frame.width-65, 5, 60, 60)
}
override func prepareForReuse() {
super.prepareForReuse()
self.progressView.hidden = true
//self.avatar.image = nil
}
func startDownload() {
self.downloadButton.hidden = true
self.allMusicController.downloadAudio(self.audioModel, progressView: self.progressView)
}
}
| mit | e17402b02b447e3af6522f1373f541cf | 35.395062 | 117 | 0.666893 | 4.921536 | false | false | false | false |
fgengine/quickly | Quickly/Wireframe/QAppWireframe.swift | 1 | 4874 | //
// Quickly
//
open class QAppWireframe< ContextType: IQContext > : IQWireframe, IQWireframeDeeplinkable, IQContextable {
public private(set) var context: ContextType
public private(set) var window: QWindow
public var viewController: QMainViewController
public var backgroundViewController: IQViewController? {
set(value) { self.viewController.backgroundViewController = value }
get { return self.viewController.backgroundViewController }
}
public var contentViewController: IQViewController? {
set(value) { self.viewController.contentViewController = value }
get { return self.viewController.contentViewController }
}
public var modalContainerViewController: IQModalContainerViewController? {
set(value) { self.viewController.modalContainerViewController = value }
get { return self.viewController.modalContainerViewController }
}
public var dialogContainerViewController: IQDialogContainerViewController? {
set(value) { self.viewController.dialogContainerViewController = value }
get { return self.viewController.dialogContainerViewController }
}
public var pushContainerViewController: IQPushContainerViewController? {
set(value) { self.viewController.pushContainerViewController = value }
get { return self.viewController.pushContainerViewController }
}
private var _wireframe: AnyObject?
public init(
context: ContextType
) {
self.context = context
self.viewController = QMainViewController()
self.window = QWindow(self.viewController)
self.setup()
}
open func setup() {
}
open func launch(_ options: [UIApplication.LaunchOptionsKey : Any]?) {
if self.window.isKeyWindow == false {
self.window.makeKeyAndVisible()
}
}
open func open(_ url: URL) -> Bool {
guard let deeplinkable = self._wireframe as? IQWireframeDeeplinkable else { return false }
return deeplinkable.open(url)
}
}
// MARK: Public
public extension QAppWireframe {
func set< WireframeType: IQWireframe >(wireframe: WireframeType) {
if self._wireframe !== wireframe {
self._wireframe = wireframe
self.viewController.contentViewController = wireframe.viewController
}
}
func wireframe< WireframeType: IQWireframe >() -> WireframeType? {
return self._wireframe as? WireframeType
}
}
// MARK: IQWireframeDefaultRouter
extension QAppWireframe : IQWireframeDefaultRouter {
public func present(notificationView: QDisplayView, alignment: QMainViewController.NotificationAlignment, duration: TimeInterval) {
self.viewController.present(notificationView: notificationView, alignment: alignment, duration: duration)
}
public func present(viewController: UIViewController, animated: Bool, completion: (() -> Swift.Void)?) {
guard let rootViewController = self.window.rootViewController else { return }
rootViewController.present(viewController, animated: animated, completion: completion)
}
public func dismiss(viewController: UIViewController, animated: Bool, completion: (() -> Swift.Void)?) {
viewController.dismiss(animated: animated, completion: completion)
}
public func present(viewController: IQModalViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.modalContainerViewController?.present(viewController: viewController, animated: animated, completion: completion)
}
public func dismiss(viewController: IQModalViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.modalContainerViewController?.dismiss(viewController: viewController, animated: animated, completion: completion)
}
public func present(viewController: IQDialogViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.dialogContainerViewController?.present(viewController: viewController, animated: animated, completion: completion)
}
public func dismiss(viewController: IQDialogViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.dialogContainerViewController?.dismiss(viewController: viewController, animated: animated, completion: completion)
}
public func present(viewController: IQPushViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.pushContainerViewController?.present(viewController: viewController, animated: animated, completion: completion)
}
public func dismiss(viewController: IQPushViewController, animated: Bool, completion: (() -> Swift.Void)?) {
self.pushContainerViewController?.dismiss(viewController: viewController, animated: animated, completion: completion)
}
}
| mit | c3d377b691ed0eeabcfeb5ea6627bee1 | 41.017241 | 135 | 0.713377 | 5.379691 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.