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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BenYeh16/SoundMapiOS
|
SoundMap/MapPopupViewController.swift
|
1
|
4161
|
//
// MapPopupViewController.swift
// SoundMap
//
// Created by 胡采思 on 14/06/2017.
// Copyright © 2017 cnl4. All rights reserved.
//
import UIKit
import AVFoundation
class MapPopupViewController: UIViewController {
@IBOutlet weak var soundTitleLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var mapPopupView: UIView!
@IBOutlet weak var audioCurrent: UILabel!
@IBOutlet weak var playButton: UIButton!
var player:AVAudioPlayer = AVAudioPlayer();
var remotePlayer:AVPlayer = AVPlayer();
var isPaused:BooleanLiteralType = false;
var timer: Timer!
// Sound info
@IBOutlet weak var soundTitle: UILabel!
@IBOutlet weak var soundDescript: UILabel!
@IBOutlet weak var owner: UILabel!
@IBOutlet weak var ownerImage: UIImageView!
var tmpOwner: String?
var tmpDescript: String?
var tmpTitle: String?
var tmpImage: UIImage?
var soundURL: String?
override func viewDidLoad() {
super.viewDidLoad()
// Set design attributes
mapPopupView.layer.cornerRadius = 10
mapPopupView.layer.masksToBounds = true
soundTitleLabel.font = UIFont.boldSystemFont(ofSize: 20.0)
// Set image to circle
//profileImage.frame = CGRect(x: 85, y: 124, width: 150, height: 150) ; // set as you want
profileImage.layer.cornerRadius = profileImage.frame.height / 2
profileImage.layer.masksToBounds = true
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor(red: 86/255, green: 86/255, blue: 1/255, alpha: 1).cgColor
// Set data
soundTitle.text = tmpTitle
soundDescript.text = tmpDescript
owner.text = tmpOwner
ownerImage.image = tmpImage
// Look for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MapPopupViewController.dismissPopup))
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
// Initialize audio
self.isPaused = false;
do {
let playerItem = AVPlayerItem(url: URL(string: soundURL!)!)
try self.remotePlayer = AVPlayer(playerItem: playerItem)
self.remotePlayer.volume = 1.0
} catch {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Close popup
func dismissPopup() {
//remotePlayer.pause()
dismiss(animated: true, completion: nil)
}
/****** Audio ******/
@IBAction func playAudioPressed(_ sender: Any) {
if ( self.isPaused == false ) {
remotePlayer.play()
playButton.setImage(UIImage(named: "music-pause2"), for: .normal)
self.isPaused = true
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
} else {
remotePlayer.pause()
playButton.setImage(UIImage(named: "music-play2"), for: .normal)
self.isPaused = false
timer.invalidate()
}
}
/*@IBAction func slide(_ sender: Any) {
player.currentTime = TimeInterval(audioSlider.value)
}*/
func stringFromTimeInterval(interval: TimeInterval) -> String {
let interval = Int(interval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
func stringFromFloatCMTime(time: Double) -> String {
let intTime = Int(time)
let seconds = intTime % 60
let minutes = ( intTime / 60 ) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
func updateTime(_ timer: Timer) {
let currentTimeInSeconds = CMTimeGetSeconds((remotePlayer.currentItem?.currentTime())!)
audioCurrent.text = stringFromFloatCMTime(time: currentTimeInSeconds)
}
}
|
gpl-3.0
|
3236b930e91da23407b1b29ee3736b3b
| 31.708661 | 134 | 0.630958 | 4.590055 | false | false | false | false |
Lightstreamer/Lightstreamer-example-MPNStockList-client-ios
|
Shared/DetailViewController.swift
|
1
|
26679
|
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/
//
// DetailViewController.swift
// StockList Demo for iOS
//
// Copyright (c) Lightstreamer Srl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import LightstreamerClient
class DetailViewController: UIViewController, SubscriptionDelegate, MPNSubscriptionDelegate, ChartViewDelegate {
let lockQueue = DispatchQueue(label: "lightstreamer.DetailViewController")
var detailView: DetailView?
var chartController: ChartViewController?
var priceMpnSubscription: MPNSubscription?
var subscription: Subscription?
var itemData: [String : String]?
var itemUpdated: [AnyHashable : Any]?
// MARK: -
// MARK: Properties
private(set) var item: String?
// MARK: -
// MARK: Notifications from notification center
// MARK: -
// MARK: Internals
// MARK: -
// MARK: Initialization
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Single-item data structures: they store fields data and
// which fields have been updated
itemData = [:]
itemUpdated = [:]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Single-item data structures: they store fields data and
// which fields have been updated
itemData = [:]
itemUpdated = [:]
}
// MARK: -
// MARK: Methods of UIViewController
override func loadView() {
let niblets = Bundle.main.loadNibNamed(DEVICE_XIB("DetailView"), owner: self, options: nil)
detailView = niblets?.last as? DetailView
view = detailView
// Add chart
chartController = ChartViewController(delegate: self)
chartController?.view.backgroundColor = UIColor.white
chartController?.view.frame = CGRect(x: 0.0, y: 0.0, width: detailView?.chartBackgroundView?.frame.size.width ?? 0.0, height: detailView?.chartBackgroundView?.frame.size.height ?? 0.0)
if let view = chartController?.view {
detailView?.chartBackgroundView?.addSubview(view)
}
// Initially disable MPN controls
disableMPNControls()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Reset size of chart
chartController?.view.frame = CGRect(x: 0.0, y: 0.0, width: detailView?.chartBackgroundView?.frame.size.width ?? 0.0, height: detailView?.chartBackgroundView?.frame.size.height ?? 0.0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We use the notification center to know when the app
// has been successfully registered for MPN and when
// the MPN subscription cache has been updated
NotificationCenter.default.addObserver(self, selector: #selector(appDidRegisterForMPN), name: NOTIFICATION_MPN_ENABLED, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidUpdateMPNSubscriptionCache), name: NOTIFICATION_MPN_UPDATED, object: nil)
// Check if registration for MPN has already been completed
if Connector.shared().mpnEnabled {
enableMPNControls()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Unregister from control center notifications
NotificationCenter.default.removeObserver(self, name: NOTIFICATION_MPN_UPDATED, object: nil)
NotificationCenter.default.removeObserver(self, name: NOTIFICATION_MPN_ENABLED, object: nil)
// Unsubscribe the table
if subscription != nil {
print("DetailViewController: unsubscribing previous table...")
Connector.shared().unsubscribe(subscription!)
subscription = nil
}
}
// MARK: -
// MARK: Communication with StockList View Controller
@objc func changeItem(_ item: String?) {
// This method is always called from the main thread
// Set current item and clear the data
lockQueue.sync {
self.item = item
itemData?.removeAll()
itemUpdated?.removeAll()
}
// Update the view
updateView()
// Reset the chart
chartController?.clearChart()
// Check MPN status and update view
updateViewForMPNStatus()
// If needed, unsubscribe previous table
if subscription != nil {
print("DetailViewController: unsubscribing previous table...")
Connector.shared().unsubscribe(subscription!)
subscription = nil
}
// Subscribe new single-item table
if let item = item {
print("DetailViewController: subscribing table...")
// The LSLightstreamerClient will reconnect and resubscribe automatically
subscription = Subscription(subscriptionMode: .MERGE, items: [item], fields: DETAIL_FIELDS)
subscription?.dataAdapter = DATA_ADAPTER
subscription?.requestedSnapshot = .yes
subscription?.addDelegate(self)
Connector.shared().subscribe(subscription!)
}
}
@objc func updateViewForMPNStatus() {
// This method is always called from the main thread
// Clear thresholds on the chart
detailView?.mpnSwitch?.isOn = false
chartController?.clearThresholds()
// Early bail
if self.item == nil {
return
}
// Early bail
if !Connector.shared().mpnEnabled {
return
}
// Update view according to cached MPN subscriptions
let mpnSubscriptions = Connector.shared().mpnSubscriptions()
for mpnSubscription in mpnSubscriptions {
let builder = MPNBuilder(notificationFormat: mpnSubscription.notificationFormat!)!
let item = builder.customData!["item"] as? String
if self.item != item {
continue
}
let threshold = builder.customData!["threshold"] as? String
if let threshold = threshold {
// MPN subscription is a threshold, we show it
// only if it has not yet triggered
if mpnSubscription.status != .TRIGGERED {
let chartThreshold = chartController?.addThreshold(Float(threshold) ?? 0.0)
chartThreshold?.mpnSubscription = mpnSubscription
}
} else {
// MPN subscription is main price subscription
priceMpnSubscription = mpnSubscription
detailView?.mpnSwitch?.isOn = true
}
}
}
// MARK: -
// MARK: User interfaction
@IBAction func mpnSwitchDidChange() {
// Get and keep current item
var item: String? = nil
lockQueue.sync {
item = self.item
}
if detailView?.mpnSwitch?.isOn ?? false {
if priceMpnSubscription != nil {
// Delete the MPN subscription
Connector.shared().unsubscribeMPN(priceMpnSubscription!)
priceMpnSubscription = nil
}
// Prepare the notification format, with a custom data
// to match the item against the MPN list
let builder = MPNBuilder()
builder.body("Stock ${stock_name} is now ${last_price}")
builder.sound("Default")
builder.badge(with: "AUTO")
builder.customData(
[
"item": item ?? "",
"stock_name": "${stock_name}",
"last_price": "${last_price}",
"pct_change": "${pct_change}",
"time": "${time}",
"open_price": "${open_price}"
])
builder.category("STOCK_PRICE_CATEGORY")
// Prepare the MPN subscription
priceMpnSubscription = MPNSubscription(subscriptionMode: .MERGE, item: item!, fields: DETAIL_FIELDS)
priceMpnSubscription?.dataAdapter = DATA_ADAPTER
priceMpnSubscription?.notificationFormat = builder.build()
priceMpnSubscription?.addDelegate(self)
Connector.shared().subscribeMPN(priceMpnSubscription!)
} else {
if priceMpnSubscription != nil {
// Delete the MPN subscription
Connector.shared().unsubscribeMPN(priceMpnSubscription!)
priceMpnSubscription = nil
}
}
}
// MARK: -
// MARK: Methods of SubscriptionDelegate
func subscription(_ subscription: Subscription, didClearSnapshotForItemName itemName: String?, itemPos: UInt) {}
func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forCommandSecondLevelItemWithKey key: String) {}
func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?, forCommandSecondLevelItemWithKey key: String) {}
func subscription(_ subscription: Subscription, didEndSnapshotForItemName itemName: String?, itemPos: UInt) {}
func subscription(_ subscription: Subscription, didLoseUpdates lostUpdates: UInt, forItemName itemName: String?, itemPos: UInt) {}
func subscriptionDidRemoveDelegate(_ subscription: Subscription) {}
func subscriptionDidAddDelegate(_ subscription: Subscription) {}
func subscriptionDidSubscribe(_ subscription: Subscription) {}
func subscription(_ subscription: Subscription, didFailWithErrorCode code: Int, message: String?) {}
func subscriptionDidUnsubscribe(_ subscription: Subscription) {}
func subscription(_ subscription: Subscription, didReceiveRealFrequency frequency: RealMaxFrequency?) {}
func subscription(_ subscription: Subscription, didUpdateItem itemUpdate: ItemUpdate) {
// This method is always called from a background thread
let itemName = itemUpdate.itemName
lockQueue.sync {
// Check if it is a late update of the previous table
if item != itemName {
return
}
var previousLastPrice = 0.0
for fieldName in DETAIL_FIELDS {
// Save previous last price to choose blick color later
if fieldName == "last_price" {
previousLastPrice = toDouble(itemData?[fieldName])
}
// Store the updated field in the item's data structures
let value = itemUpdate.value(withFieldName: fieldName)
if value != "" {
itemData?[fieldName] = value
} else {
itemData?[fieldName] = nil
}
if itemUpdate.isValueChanged(withFieldName: fieldName) {
itemUpdated?[fieldName] = NSNumber(value: true)
}
}
let currentLastPrice = Double(itemUpdate.value(withFieldName: "last_price") ?? "0")!
if currentLastPrice >= previousLastPrice {
itemData?["color"] = "green"
} else {
itemData?["color"] = "orange"
}
}
DispatchQueue.main.async(execute: { [self] in
// Forward the update to the chart
chartController?.itemDidUpdate(itemUpdate)
// Update the view
updateView()
})
}
// MARK: -
// MARK: methods of MPNSubscriptionDelegate
func mpnSubscriptionDidAddDelegate(_ subscription: MPNSubscription) {}
func mpnSubscriptionDidRemoveDelegate(_ subscription: MPNSubscription) {}
func mpnSubscriptionDidUnsubscribe(_ subscription: MPNSubscription) {}
func mpnSubscription(_ subscription: MPNSubscription, didFailUnsubscriptionWithErrorCode code: Int, message: String?) {}
func mpnSubscriptionDidTrigger(_ subscription: MPNSubscription) {}
func mpnSubscription(_ subscription: MPNSubscription, didChangeStatus status: MPNSubscription.Status, timestamp: Int64) {}
func mpnSubscription(_ subscription: MPNSubscription, didChangeProperty property: String) {}
func mpnSubscription(_ subscription: MPNSubscription, didFailModificationWithErrorCode code: Int, message: String?, property: String) {}
func mpnSubscriptionDidSubscribe(_ subscription: MPNSubscription) {
// This method is always called from a background thread
print("DetailViewController: activation of MPN subscription succeeded")
}
func mpnSubscription(_ subscription: MPNSubscription, didFailSubscriptionWithErrorCode code: Int, message: String?) {
// This method is always called from a background thread
print(String(format: "DetailViewController: error while activating MPN subscription: %ld - %@", code, message ?? ""))
// Show error alert
let mpnSubscription = subscription
DispatchQueue.main.async(execute: { [self] in
UIAlertView(title: "Error while activating MPN subscription", message: "An error occurred and the MPN subscription could not be activated.", delegate: nil, cancelButtonTitle: "Cancel", otherButtonTitles: "").show()
let builder = MPNBuilder(notificationFormat: mpnSubscription.notificationFormat!)!
if let ts = builder.customData!["threshold"] as? String {
// It's the subscription of a threshold, remove it if still present
let threshold = chartController?.findThreshold(toFloat(ts))
if let threshold = threshold {
chartController?.remove(threshold)
}
} else {
// It's the main price subscription, reset the switch
priceMpnSubscription = nil
detailView?.mpnSwitch?.isOn = false
}
})
}
// MARK: -
// MARK: ChartViewDelegate methods
func chart(_ chartControllter: ChartViewController?, didAdd threshold: ChartThreshold?) {
// This method is always called from the main thread
var lastPrice: Float = 0.0
lockQueue.sync {
lastPrice = toFloat(itemData?["last_price"])
}
if (threshold?.value ?? 0.0) > lastPrice {
// The threshold is higher than current price,
// ask confirm with the appropriate alert view
if let value = threshold?.value {
let alert = UIAlertController(
title: "Add alert on threshold",
message: String(format: "Confirm adding a notification alert when %@ rises above %.2f", title ?? "", value),
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(
title: "Proceed",
style: UIAlertAction.Style.default,
handler: { _ in
self.addOrUpdateMPNSubscription(for: threshold, greaterThan: true)
}))
alert.addAction(UIAlertAction(
title: "Cancel",
style: UIAlertAction.Style.cancel,
handler: { _ in
self.chartController?.remove(threshold)
}))
self.present(alert, animated: true, completion: nil)
}
} else if (threshold?.value ?? 0.0) < lastPrice {
// The threshold is lower than current price,
// ask confirm with the appropriate alert view
if let value = threshold?.value {
let alert = UIAlertController(
title: "Add alert on threshold",
message: String(format: "Confirm adding a notification alert when %@ drops below %.2f", title ?? "", value),
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(
title: "Proceed",
style: UIAlertAction.Style.default,
handler: { _ in
self.addOrUpdateMPNSubscription(for: threshold, greaterThan: false)
}))
alert.addAction(UIAlertAction(
title: "Cancel",
style: UIAlertAction.Style.cancel,
handler: { _ in
self.chartController?.remove(threshold)
}))
self.present(alert, animated: true, completion: nil)
}
} else {
// The threshold matches current price,
// show the appropriate alert view
UIAlertView(title: "Invalid threshold", message: "Threshold must be higher or lower than current price", delegate: nil, cancelButtonTitle: "Cancel", otherButtonTitles: "").show()
// Cleanup
chartController?.remove(threshold)
}
}
func chart(_ chartControllter: ChartViewController?, didChange threshold: ChartThreshold?) {
// This method is always called from the main thread
var lastPrice: Float = 0.0
lockQueue.sync {
lastPrice = toFloat(itemData?["last_price"])
}
// No need to ask confirm, just proceed
addOrUpdateMPNSubscription(for: threshold, greaterThan: (threshold?.value ?? 0.0) > lastPrice)
}
func chart(_ chartControllter: ChartViewController?, didRemove threshold: ChartThreshold?) {
// This method is always called from the main thread
// No need to ask confirm, just proceed
deleteMPNSubscription(for: threshold)
}
// MARK: -
// MARK: Properties
// MARK: -
// MARK: Notifications from notification center
@objc func appDidRegisterForMPN() {
DispatchQueue.main.async(execute: { [self] in
enableMPNControls()
})
}
@objc func appDidUpdateMPNSubscriptionCache() {
DispatchQueue.main.async(execute: { [self] in
updateViewForMPNStatus()
})
}
// MARK: -
// MARK: Internals
func disableMPNControls() {
// Disable UI controls related to MPN
detailView?.chartBackgroundView?.isUserInteractionEnabled = false
detailView?.chartTipLabel?.isHidden = true
detailView?.switchTipLabel?.isEnabled = false
detailView?.mpnSwitch?.isEnabled = false
}
func enableMPNControls() {
// Enable UI controls related to MPN
detailView?.chartBackgroundView?.isUserInteractionEnabled = true
detailView?.chartTipLabel?.isHidden = false
detailView?.switchTipLabel?.isEnabled = true
detailView?.mpnSwitch?.isEnabled = true
}
func updateView() {
// This method is always called on the main thread
lockQueue.sync {
// Take current item status from item's data structures
// and update the view appropriately
let colorName = itemData?["color"]
var color: UIColor? = nil
if colorName == "green" {
color = GREEN_COLOR
} else if colorName == "orange" {
color = ORANGE_COLOR
} else {
color = UIColor.white
}
title = itemData?["stock_name"]
detailView?.lastLabel?.text = itemData?["last_price"]
if (itemUpdated?["last_price"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.lastLabel, with: color)
itemUpdated?["last_price"] = NSNumber(value: false)
}
detailView?.timeLabel?.text = itemData?["time"]
if (itemUpdated?["time"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.timeLabel, with: color)
itemUpdated?["time"] = NSNumber(value: false)
}
let pctChange = toDouble(itemData?["pct_change"])
if pctChange > 0.0 {
detailView?.dirImage?.image = UIImage(named: "Arrow-up")
} else if pctChange < 0.0 {
detailView?.dirImage?.image = UIImage(named: "Arrow-down")
} else {
detailView?.dirImage?.image = nil
}
detailView?.changeLabel?.text = (itemData?["pct_change"] ?? "") + "%"
detailView?.changeLabel?.textColor = (toDouble(itemData?["pct_change"]) >= 0.0) ? DARK_GREEN_COLOR : RED_COLOR
if (itemUpdated?["pct_change"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flashImage(detailView?.dirImage, with: color)
SpecialEffects.flash(detailView?.changeLabel, with: color)
itemUpdated?["pct_change"] = NSNumber(value: false)
}
detailView?.minLabel?.text = itemData?["min"]
if (itemUpdated?["min"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.minLabel, with: color)
itemUpdated?["min"] = NSNumber(value: false)
}
detailView?.maxLabel?.text = itemData?["max"]
if (itemUpdated?["max"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.maxLabel, with: color)
itemUpdated?["max"] = NSNumber(value: false)
}
detailView?.bidLabel?.text = itemData?["bid"]
if (itemUpdated?["bid"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.bidLabel, with: color)
itemUpdated?["bid"] = NSNumber(value: false)
}
detailView?.askLabel?.text = itemData?["ask"]
if (itemUpdated?["ask"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.askLabel, with: color)
itemUpdated?["ask"] = NSNumber(value: false)
}
detailView?.bidSizeLabel?.text = itemData?["bid_quantity"]
if (itemUpdated?["bid_quantity"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.bidSizeLabel, with: color)
itemUpdated?["bid_quantity"] = NSNumber(value: false)
}
detailView?.askSizeLabel?.text = itemData?["ask_quantity"]
if (itemUpdated?["ask_quantity"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.askSizeLabel, with: color)
itemUpdated?["ask_quantity"] = NSNumber(value: false)
}
detailView?.openLabel?.text = itemData?["open_price"]
if (itemUpdated?["open_price"] as? NSNumber)?.boolValue ?? false {
SpecialEffects.flash(detailView?.openLabel, with: color)
itemUpdated?["open_price"] = NSNumber(value: false)
}
}
}
func addOrUpdateMPNSubscription(for threshold: ChartThreshold?, greaterThan: Bool) {
// This method is always called from the main thread
// Get and keep current item
var item: String? = nil
lockQueue.sync {
item = self.item
}
// Prepare the notification format, with a custom data
// to match the item and threshold against the MPN list
let builder = MPNBuilder()
if let value = threshold?.value {
builder.body(String(format: greaterThan ? "Stock ${stock_name} rised above %.2f" : "Stock ${stock_name} dropped below %.2f", value))
}
builder.sound("Default")
builder.badge(with: "AUTO")
if let value = threshold?.value {
builder.customData(
[
"item": item ?? "",
"stock_name": "${stock_name}",
"last_price": "${last_price}",
"pct_change": "${pct_change}",
"time": "${time}",
"open_price": "${open_price}",
"threshold": String(format: "%.2f", value),
"subID": "${LS_MPN_subscription_ID}"
])
}
builder.category("STOCK_PRICE_CATEGORY")
var trigger: String? = nil
if let value = threshold?.value {
trigger = String(format: "Double.parseDouble(${last_price}) %@ %.2f", (greaterThan ? ">" : "<"), value)
}
print("DetailViewController: subscribing MPN with trigger expression: \(trigger ?? "")")
// Prepare the MPN subscription
let mpnSubscription = MPNSubscription(subscriptionMode: .MERGE, item: item!, fields: DETAIL_FIELDS)
mpnSubscription.dataAdapter = DATA_ADAPTER
mpnSubscription.notificationFormat = builder.build()
mpnSubscription.triggerExpression = trigger
mpnSubscription.addDelegate(self)
// Delete the existing MPN subscription, if present
if ((threshold?.mpnSubscription) != nil) {
Connector.shared().unsubscribeMPN((threshold?.mpnSubscription)!)
}
// Activate the new MPN subscription
Connector.shared().subscribeMPN(mpnSubscription)
threshold?.mpnSubscription = mpnSubscription
}
func deleteMPNSubscription(for threshold: ChartThreshold?) {
// This method is always called from the main thread
// Delete the existing MPN subscription, if present
if ((threshold?.mpnSubscription) != nil) {
Connector.shared().unsubscribeMPN((threshold?.mpnSubscription)!)
}
}
func toDouble(_ s: String?) -> Double {
Double(s ?? "0") ?? 0
}
func toFloat(_ s: String?) -> Float {
Float(s ?? "0") ?? 0
}
}
// MARK: -
// MARK: DetailViewController extension
// MARK: -
// MARK: DetailViewController implementation
|
apache-2.0
|
ae9c57218ae3dfe00efbd4ebbede0a46
| 38.641902 | 226 | 0.593426 | 5.097249 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Dining/Networking + Cache/DiningAPI.swift
|
1
|
6307
|
//
// DiningAPI.swift
// PennMobile
//
// Created by Josh Doman on 8/5/17.
// Copyright © 2017 PennLabs. All rights reserved.
//
import SwiftyJSON
import Foundation
class DiningAPI: Requestable {
static let instance = DiningAPI()
let diningUrl = "https://pennmobile.org/api/dining/venues/"
let diningMenuUrl = "https://pennmobile.org/api/dining/daily_menu/"
// TODO: Broken API, need to fetch locally
let diningInsightsUrl = "https://pennmobile.org/api/dining/"
func fetchDiningHours() async -> Result<[DiningVenue], NetworkingError> {
guard let (data, _) = try? await URLSession.shared.data(from: URL(string: diningUrl)!) else {
return .failure(.serverError)
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let diningVenues = try? decoder.decode([DiningVenue].self, from: data) {
self.saveToCache(diningVenues)
return .success(diningVenues)
} else {
return .failure(.parsingError)
}
}
func fetchDiningMenu(for id: Int, at date: Date = Date(), _ completion: @escaping (_ result: Result<DiningMenuAPIResponse, NetworkingError>) -> Void) {
return completion(.failure(.parsingError))
}
}
// Dining Data Storage
extension DiningAPI {
// MARK: - Get Methods
func getVenues() -> [DiningVenue] {
if Storage.fileExists(DiningVenue.directory, in: .caches) {
return Storage.retrieve(DiningVenue.directory, from: .caches, as: [DiningVenue].self)
} else {
return []
}
}
func getSectionedVenues() -> [VenueType: [DiningVenue]] {
var venuesDict = [VenueType: [DiningVenue]]()
for type in VenueType.allCases {
venuesDict[type] = getVenues().filter({ $0.venueType == type })
}
return venuesDict
}
func getVenues<T: Collection>(with ids: T) -> [DiningVenue] where T.Element == Int {
return getVenues().filter({ ids.contains($0.id) })
}
func getMenus() -> [Int: DiningMenuAPIResponse] {
if Storage.fileExists(DiningMenuAPIResponse.directory, in: .caches) {
return Storage.retrieve(DiningMenuAPIResponse.directory, from: .caches, as: [Int: DiningMenuAPIResponse].self)
} else {
return [:]
}
}
// MARK: - Cache Methods
func saveToCache(_ venues: [DiningVenue]) {
Storage.store(venues, to: .caches, as: DiningVenue.directory)
}
func saveToCache(id: Int, _ menu: DiningMenuAPIResponse) {
if Storage.fileExists(DiningMenuAPIResponse.directory, in: .caches) {
var menus = Storage.retrieve(DiningMenuAPIResponse.directory, from: .caches, as: [Int: DiningMenuAPIResponse].self)
menus[id] = menu
Storage.store(menus, to: .caches, as: DiningMenuAPIResponse.directory)
} else {
Storage.store([id: menu], to: .caches, as: DiningMenuAPIResponse.directory)
}
}
}
// MARK: Dining Balance
extension DiningAPI {
func getDiningBalance(diningToken: String) async -> Result<DiningBalance, NetworkingError> {
let url = URL(string: "https://prod.campusexpress.upenn.edu/api/v1/dining/currentBalance")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(diningToken, forHTTPHeaderField: "x-authorization")
guard let (data, response) = try? await URLSession.shared.data(for: request), let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
return .failure(.serverError)
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let balance = try? decoder.decode(DiningBalance.self, from: data) {
return .success(balance)
} else {
return .failure(.parsingError)
}
}
}
// MARK: Past Dining Balances
extension DiningAPI {
func getPastDiningBalances(diningToken: String, startDate: String) async -> Result<[DiningBalance], NetworkingError> {
var url = URL(string: "https://prod.campusexpress.upenn.edu/api/v1/dining/pastBalances")!
let formatter = Date.dayOfMonthFormatter
let endDate = formatter.string(from: Calendar.current.date(byAdding: .day, value: -1, to: Date().localTime)!)
url.appendQueryItem(name: "start_date", value: startDate)
url.appendQueryItem(name: "end_date", value: endDate)
UserDefaults.standard.setNextAnalyticsStartDate(formatter.string(from: Date()))
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(diningToken, forHTTPHeaderField: "x-authorization")
guard let (data, response) = try? await URLSession.shared.data(for: request), let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
return .failure(.serverError)
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let decodedBalances = try? decoder.decode(PastDiningBalances.self, from: data) {
return .success(decodedBalances.balanceList)
} else {
return .failure(.parsingError)
}
}
}
// MARK: Current Dining Plan Start Date
extension DiningAPI {
func getDiningPlanStartDate(diningToken: String) async -> Result<Date, NetworkingError> {
let url = URL(string: "https://prod.campusexpress.upenn.edu/api/v1/dining/currentPlan")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(diningToken, forHTTPHeaderField: "x-authorization")
guard let (data, response) = try? await URLSession.shared.data(for: request), let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
return .failure(.serverError)
}
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
if let plan = try? decoder.decode(DiningPlan.self, from: data) {
return .success(plan.start_date)
} else {
return .failure(.parsingError)
}
}
}
|
mit
|
45b5a662abf5883a30768c500ee650a1
| 39.165605 | 172 | 0.650967 | 4.257934 | false | false | false | false |
gpolitis/jitsi-meet
|
ios/sdk/src/picture-in-picture/DragGestureController.swift
|
1
|
4274
|
/*
* Copyright @ 2017-present Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
final class DragGestureController {
var insets: UIEdgeInsets = UIEdgeInsets.zero
private var frameBeforeDragging: CGRect = CGRect.zero
private weak var view: UIView?
private lazy var panGesture: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,
action: #selector(handlePan(gesture:)))
}()
func startDragListener(inView view: UIView) {
self.view = view
view.addGestureRecognizer(panGesture)
panGesture.isEnabled = true
}
func stopDragListener() {
panGesture.isEnabled = false
view?.removeGestureRecognizer(panGesture)
view = nil
}
@objc private func handlePan(gesture: UIPanGestureRecognizer) {
guard let view = self.view else { return }
let translation = gesture.translation(in: view.superview)
let velocity = gesture.velocity(in: view.superview)
var frame = frameBeforeDragging
switch gesture.state {
case .began:
frameBeforeDragging = view.frame
case .changed:
frame.origin.x = floor(frame.origin.x + translation.x)
frame.origin.y = floor(frame.origin.y + translation.y)
view.frame = frame
case .ended:
let currentPos = view.frame.origin
let finalPos = calculateFinalPosition()
let distance = CGPoint(x: currentPos.x - finalPos.x,
y: currentPos.y - finalPos.y)
let distanceMagnitude = magnitude(vector: distance)
let velocityMagnitude = magnitude(vector: velocity)
let animationDuration = 0.5
let initialSpringVelocity =
velocityMagnitude / distanceMagnitude / CGFloat(animationDuration)
frame.origin = CGPoint(x: finalPos.x, y: finalPos.y)
UIView.animate(withDuration: animationDuration,
delay: 0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: initialSpringVelocity,
options: .curveLinear,
animations: {
view.frame = frame
}, completion: nil)
default:
break
}
}
private func calculateFinalPosition() -> CGPoint {
guard
let view = self.view,
let bounds = view.superview?.frame
else { return CGPoint.zero }
let currentSize = view.frame.size
let adjustedBounds = bounds.inset(by: insets)
let threshold: CGFloat = 20.0
let velocity = panGesture.velocity(in: view.superview)
let location = panGesture.location(in: view.superview)
let goLeft: Bool
if abs(velocity.x) > threshold {
goLeft = velocity.x < -threshold
} else {
goLeft = location.x < bounds.midX
}
let goUp: Bool
if abs(velocity.y) > threshold {
goUp = velocity.y < -threshold
} else {
goUp = location.y < bounds.midY
}
let finalPosX: CGFloat =
goLeft
? adjustedBounds.origin.x
: bounds.size.width - insets.right - currentSize.width
let finalPosY: CGFloat =
goUp
? adjustedBounds.origin.y
: bounds.size.height - insets.bottom - currentSize.height
return CGPoint(x: finalPosX, y: finalPosY)
}
private func magnitude(vector: CGPoint) -> CGFloat {
return sqrt(pow(vector.x, 2) + pow(vector.y, 2))
}
}
|
apache-2.0
|
4792349f7480bac299c029f745a64cb0
| 32.653543 | 82 | 0.594525 | 4.873432 | false | false | false | false |
rafattouqir/RRNotificationBar
|
RRNotificationBar/RRNotificationBar.swift
|
1
|
12688
|
//
// RRNotificationBar.swift
// RRNotificationBar
//
// Created by RAFAT TOUQIR RAFSUN on 2/6/17.
// Copyright © 2017 RAFAT TOUQIR RAFSUN. All rights reserved.
//
import UIKit
open class RRNotificationBar:NSObject{
lazy var rrNotificationView:RRNotificationView = {
let notificationView = RRNotificationView()
notificationView.translatesAutoresizingMaskIntoConstraints = false
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(notificationViewDidTapped))
notificationView.addGestureRecognizer(tapGesture)
return notificationView
}()
var topConstraint:NSLayoutConstraint = NSLayoutConstraint()
lazy var window:UIWindow = {
let window = UIWindow(frame:UIScreen.main.bounds)
//Need to assign placeholder rootViewController due to iOS's device rotation call back doesn't work (for Autolayout) without rootview controller
window.rootViewController = UIViewController()
window.windowLevel = UIWindowLevelStatusBar
window.isHidden = false
return window
}()
enum NotificationVisibility{
case showing,hiding,hidden
}
public var padding:CGFloat = 8
let height:CGFloat = 60
public var notificationViewCornerRadius:CGFloat = 12
var notificationVisibility:NotificationVisibility = .hidden
public var animationDuration:Double = 0.7
public var dismissDelay:Double = 2.0
var tapBlock:(()->())?
public override init() {
super.init()
// guard let rrNotificationView = rrNotificationView else { return }
rrNotificationView.viewHolder.layer.cornerRadius = notificationViewCornerRadius
rrNotificationView.viewHolder.clipsToBounds = true
rrNotificationView.buttonClose.addTarget(self, action: #selector(dismissed), for: .touchUpInside)
window.addSubview(rrNotificationView)
window.addConstraintsWithFormat(format: "H:|-\(padding)-[v0]-\(padding)-|", views: rrNotificationView)
topConstraint = NSLayoutConstraint(item: rrNotificationView, attribute: .top, relatedBy: .equal, toItem:window , attribute: .top, multiplier: 1.0, constant: -(self.height))
window.addConstraint(topConstraint)
self.window.layoutIfNeeded()
}
func dismissed(){
hide()
}
func notificationViewDidTapped(gesture:UITapGestureRecognizer){
//Exclude the dismiss button, otherwise execute notification bar tap
guard let view = gesture.view,let filteredView = view.hitTest(gesture.location(in: view),with:nil),
filteredView !== rrNotificationView.buttonClose else { return }
self.tapBlock?()
self.hide()
}
/**
Shows a notification just like `iOS 10`.
- Parameter title: The string to show notification title.
- Parameter message: The string to show notification message.
- Parameter time: The string to show notification time, default is `now`.
- Parameter onTap: On tap block which will be triggered when user has tapped on the notification bar.
*/
public func show(title:String = "",message:String = "",time:String = "",onTap:(()->())? = nil) {
// guard let rrNotificationView = rrNotificationView else { return }
rrNotificationView.labelTitle.text = title
rrNotificationView.labelSubTitle.text = message
rrNotificationView.labelTime.text = time.isEmpty ? "now" : time
tapBlock = onTap
UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: [.curveEaseOut,.allowUserInteraction], animations: { [unowned self] in
self.notificationVisibility = .showing
self.topConstraint.constant = 0 + self.padding
self.window.layoutIfNeeded()
self.rrNotificationView.layoutIfNeeded()
}, completion: { isCompleted in
DispatchQueue.main.asyncAfter(deadline: .now() + self.dismissDelay, execute: { //[unowned self] in
guard let strongSelf = Optional(self) else { return }
if strongSelf.notificationVisibility != .hiding || strongSelf.notificationVisibility != .hidden{
strongSelf.hide()
}
})
})
}
public func hide() {
UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.0, options: [.curveEaseIn,.allowUserInteraction], animations: { [weak self] in
guard let strongSelf = self
else { return }
strongSelf.notificationVisibility = .hiding
strongSelf.topConstraint.constant = -(strongSelf.rrNotificationView.bounds.height + (2*strongSelf.padding))
strongSelf.window.layoutIfNeeded()
strongSelf.rrNotificationView.layoutIfNeeded()
}, completion: { isCompleted in
self.notificationVisibility = .hidden
self.rrNotificationView.removeFromSuperview()
self.window.isHidden = true
})
}
}
//MARK: - RRNotificationView is the view that is shown in RRNotificationBar
class RRNotificationView:UIView{
let imageViewWidth:CGFloat = 30
let buttonCloseHeight:CGFloat = 20
var isDropShadowEnabled = true
let viewHolder:UIView = {
let view = UIView()
return view
}()
let viewHolderTop:UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
let view = UIVisualEffectView(effect: blurEffect)
view.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
return view
}()
let viewHolderBottom:UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
let view = UIVisualEffectView(effect: blurEffect)
return view
}()
lazy var imageView:UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = .lightGray
if let lastIcon = getAppIconName{
let icon = UIImage(named: lastIcon)
imageView.image = icon
}
imageView.layer.cornerRadius = self.imageViewWidth * 0.2
imageView.clipsToBounds = true
return imageView
}()
let labelApp:UILabel = {
let label = UILabel()
label.text = getAppName
label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight)
return label
}()
let labelTime:UILabel = {
let label = UILabel()
label.text = ""
// label.backgroundColor = .green
label.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightUltraLight)
return label
}()
let labelTitle:UILabel = {
let label = UILabel()
label.text = ""
label.numberOfLines = 1
// label.backgroundColor = .yellow
label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium)
return label
}()
let labelSubTitle:UILabel = {
let label = UILabel()
label.text = ""
label.numberOfLines = 2
// label.backgroundColor = .green
label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular)
return label
}()
class DarkView:UIView{
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height/2
}
}
class var getAppName:String?{
return Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
}
class var getAppIconName:String?{
if let iconsDictionary = Bundle.main.infoDictionary?["CFBundleIcons"] as? NSDictionary,let primaryIconsDictionary = iconsDictionary["CFBundlePrimaryIcon"] as? NSDictionary,let iconFiles = primaryIconsDictionary["CFBundleIconFiles"] as? NSArray,let lastIcon = iconFiles.lastObject as? String{
return lastIcon
}else{
return nil
}
}
let buttonClose:UIButton = {
let button = UIButton()
// button.backgroundColor = .red
let darkView = DarkView()
darkView.isUserInteractionEnabled = false
darkView.backgroundColor = .lightGray
button.addSubview(darkView)
button.addConstraint(NSLayoutConstraint(item: darkView, attribute: .width, relatedBy: .equal, toItem: button, attribute: .width, multiplier: 0.1, constant: 0))
button.addConstraint(NSLayoutConstraint(item: darkView, attribute: .centerX, relatedBy: .equal, toItem: button, attribute: .centerX, multiplier: 1.0, constant: 0))
// button.addConstraintsWithFormat(format: "H:[v0(30)]", views: darkView)
button.addConstraintsWithFormat(format: "V:|-8-[v0]-8-|", views: darkView)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override func layoutSubviews() {
super.layoutSubviews()
if isDropShadowEnabled{
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
}
}
func addDefaultShadowConfig(){
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.4
layer.shadowRadius = 8
layer.shadowOffset = .zero
}
func setupViews(){
if isDropShadowEnabled{
addDefaultShadowConfig()
}
viewHolder.addSubview(viewHolderTop)
viewHolderTop.addSubview(imageView)
viewHolderTop.addSubview(labelApp)
viewHolderTop.addSubview(labelTime)
viewHolderTop.addConstraintsWithFormat(format: "H:|-8-[v0(\(imageViewWidth))]-8-[v1]-(>=8)-[v2]-8-|", views: imageView,labelApp,labelTime,options:[.alignAllCenterY])
viewHolderTop.addConstraintsWithFormat(format: "V:|-8-[v0(\(imageViewWidth))]-(8)-|", views: imageView)
viewHolder.addSubview(viewHolderBottom)
viewHolderBottom.addSubview(labelTitle)
viewHolderBottom.addSubview(labelSubTitle)
viewHolderBottom.addSubview(buttonClose)
viewHolderBottom.addConstraintsWithFormat(format: "H:|-8-[v0]-8-|", views: labelTitle)
viewHolderBottom.addConstraintsWithFormat(format: "V:|-4-[v0]-4-[v1]-0-[v2(\(buttonCloseHeight))]-0-|", views: labelTitle,labelSubTitle,buttonClose,options:[.alignAllLeading,.alignAllTrailing])
viewHolder.addConstraintsWithFormat(format: "H:|-0-[v0]-0-|", views: viewHolderTop)
viewHolder.addConstraintsWithFormat(format: "V:|-0-[v0]-0-[v1]-0-|", views: viewHolderTop,viewHolderBottom,options:[.alignAllLeading,.alignAllTrailing])
addSubview(viewHolder)
viewHolder.boundInside(superView: self)
}
}
//MARK:- VFL Extensions
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView... , options: NSLayoutFormatOptions = NSLayoutFormatOptions()) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: nil, views: viewsDictionary))
}
func boundInside(superView: UIView,inset:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)){
self.translatesAutoresizingMaskIntoConstraints = false
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(inset.left)-[subview]-\(inset.right)-|", options: NSLayoutFormatOptions.directionLeadingToTrailing, metrics:nil, views:["subview":self]))
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(inset.top)-[subview]-\(inset.bottom)-|", options: NSLayoutFormatOptions.directionLeadingToTrailing, metrics:nil, views:["subview":self]))
}
}
|
mit
|
f7b4e27363402f07c3a9b9d0556ff0fd
| 36.314706 | 299 | 0.639316 | 5.119855 | false | false | false | false |
Trevi-Swift/Trevi-lime
|
Sources/ServeStatic.swift
|
1
|
1744
|
//
// ServeStatic.swift
// Trevi
//
// Created by SeungHyun Lee on 2015. 12. 27..
// Copyright © 2015 Trevi Community. All rights reserved.
//
import Foundation
import Trevi
/**
A Middleware for serving static files in server like .css, .js, .html, etc.
*/
public class ServeStatic: Middleware {
public var name: MiddlewareName
private let basePath: String
public init (path: String) {
name = .ServeStatic
if let last = path.characters.last where last == "/" {
basePath = path[path.startIndex ..< path.endIndex.advancedBy(-1)]
} else {
basePath = path
}
}
public func handle(req: Request, res: Response, next: NextCallback?) {
var entirePath = req.url
let type: String! = req.url.componentsSeparatedByString(".").last!
guard let mType = type else {
return next!()
}
let resultType = Mime.mimeType(mType)
guard resultType.length() > 0 else {
return next!()
}
#if os(Linux)
entirePath = "\(basePath)/\(req.url)"
#else
if let bundlePath = NSBundle.mainBundle().pathForResource(NSURL(fileURLWithPath: req.url).lastPathComponent!, ofType: nil) {
entirePath = bundlePath
}
let file = FileSystem.ReadStream(path: entirePath)
let buf = NSMutableData()
file?.onClose() { handle in
return res.send(buf)
}
file?.readStart() { error, data in
buf.appendData(data)
}
#endif
next!()
}
}
|
apache-2.0
|
a4f0ebf0fa2a0bcd758e0707643b5739
| 24.632353 | 136 | 0.527252 | 4.749319 | false | false | false | false |
vapor/vapor
|
Sources/Vapor/Cache/Application+Cache.swift
|
1
|
1604
|
extension Application {
/// Controls application's configured caches.
///
/// app.caches.use(.memory)
///
public var caches: Caches {
.init(application: self)
}
/// Current application cache. See `Request.cache` for caching in request handlers.
public var cache: Cache {
guard let makeCache = self.caches.storage.makeCache else {
fatalError("No cache configured. Configure with app.caches.use(...)")
}
return makeCache(self)
}
public struct Caches {
public struct Provider {
let run: (Application) -> ()
public init(_ run: @escaping (Application) -> ()) {
self.run = run
}
}
final class Storage {
var makeCache: ((Application) -> Cache)?
init() { }
}
struct Key: StorageKey {
typealias Value = Storage
}
public let application: Application
public func use(_ provider: Provider) {
provider.run(self.application)
}
public func use(_ makeCache: @escaping (Application) -> (Cache)) {
self.storage.makeCache = makeCache
}
func initialize() {
self.application.storage[Key.self] = .init()
self.use(.memory)
}
var storage: Storage {
guard let storage = self.application.storage[Key.self] else {
fatalError("Caches not configured. Configure with app.caches.initialize()")
}
return storage
}
}
}
|
mit
|
bb3753eba623c7d91b3bb37c7d3c52f0
| 26.655172 | 91 | 0.537406 | 4.920245 | false | true | false | false |
coppercash/Anna
|
Demos/Easy/Easy/AppDelegate.swift
|
1
|
2358
|
//
// AppDelegate.swift
// Easy
//
// Created by William on 2018/6/24.
// Copyright © 2018 coppercash. All rights reserved.
//
import UIKit
import Anna
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate, Analyzable, Delegate {
var window: UIWindow?
lazy var analyzer :Analyzing = {
let
manager = Manager(
moduleURL: Bundle.main.url(
forResource: "analytics",
withExtension: "bundle"
)!
)
manager.delegate = self
return RootAnalyzer(
manager: manager
)
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
return true
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// MARK: - Analytics
func
manager(
_ manager :Manager,
didSend result :Any
) {
print(result)
}
func
manager(
_ manager: Manager,
didCatch error: Error
) {
print(error)
}
func
log(_ string: String) {
print(string)
}
}
|
mit
|
75a52372ffaa19b09ba874c2e4c47d95
| 32.197183 | 189 | 0.669071 | 5.967089 | false | false | false | false |
Shedward/SwiftyNotificationCenter
|
SwiftyNotificationCenter/Classes/NotificationObserver.swift
|
1
|
2909
|
//
// NotificationObserver.swift
// Pods
//
// Created by Vladislav Maltsev on 04.12.16.
// Copyright (c) 2016 Vladislav Maltsev.
//
// 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
private var SwiftyNotificationDisposeBagKey = "SwiftyNotificationDisposeBagKey"
public typealias NotificationDisposeBag = [Any]
public class NotificationObserver<EventType: ObservableEvent> {
private weak var notificationCenter: NotificationCenter?
internal init(notificationCenter: NotificationCenter, object: Any? = nil) {
self.notificationCenter = notificationCenter
notificationCenter.addObserver(self,
selector: #selector(notificationDidReceived(notification:)),
name: EventType.notificationName(),
object: object)
}
deinit {
notificationCenter?.removeObserver(self)
}
public func disposeWith(object: Any) {
let associatedObject = objc_getAssociatedObject(object, &SwiftyNotificationDisposeBagKey)
let disposeBag = associatedObject as? NSMutableArray ?? NSMutableArray()
disposeBag.add(self)
objc_setAssociatedObject(object, &SwiftyNotificationDisposeBagKey, disposeBag, .OBJC_ASSOCIATION_RETAIN)
}
public func disposeWith(disposeBag: inout NotificationDisposeBag) {
disposeBag.append(self)
}
@objc private func notificationDidReceived(notification: Notification) {
guard let userInfo = notification.userInfo else { return }
let event = EventType.fromUserInfo(userInfo)
process(event: event)
}
internal func process(event: EventType) {
fatalError("SwiftyNotification: Abstract NotificationObserver can not process events.")
}
}
|
mit
|
49687c0f848738b9c816487f6d29bc0b
| 39.402778 | 112 | 0.701959 | 5.130511 | false | false | false | false |
ello/ello-ios
|
Specs/Controllers/Omnibar/OmnibarViewControllerSpec.swift
|
1
|
21680
|
////
/// OmnibarViewControllerSpec.swift
//
@testable import Ello
import Quick
import Nimble
class OmnibarMockScreen: OmnibarScreenProtocol {
var chosenCategory: Ello.Category?
var communityPickerEditability: OmnibarScreen.CommunityPickerEditability = .editable
weak var delegate: OmnibarScreenDelegate?
var isEditing: Bool = false
var isComment: Bool = false
var isArtistInviteSubmission: Bool = true
var isInteractionEnabled: Bool = true
var title: String = ""
var submitTitle: String = ""
var buyButtonURL: URL?
var regions = [OmnibarRegion]()
var canGoBack = false
var didReportError = false
var didReset = false
var didKeyboardWillShow = false
var didKeyboardWillHide = false
func reportError(_ title: String, error: NSError) {
didReportError = true
}
func reportError(_ title: String, errorMessage: String) {
didReportError = true
}
func keyboardWillShow() {
didKeyboardWillShow = true
}
func keyboardWillHide() {
didKeyboardWillHide = true
}
func startEditing() {
}
func stopEditing() {
}
func updateButtons() {
}
func resetAfterSuccessfulPost() {
didReset = true
}
}
class OmnibarViewControllerSpec: QuickSpec {
override func spec() {
var subject: OmnibarViewController!
var screen: OmnibarMockScreen!
describe("OmnibarViewController") {
context("determining screen isComment") {
it("should be false for a new post") {
subject = OmnibarViewController()
showController(subject)
expect(subject.screen.isComment) == false
}
it("should be false for editing post") {
subject = OmnibarViewController(editPost: stub([:]))
showController(subject)
expect(subject.screen.isComment) == false
}
it("should be true for a new comment") {
subject = OmnibarViewController(parentPostId: "123")
showController(subject)
expect(subject.screen.isComment) == true
}
it("should be true for editing a comment") {
subject = OmnibarViewController(editComment: stub([:]))
showController(subject)
expect(subject.screen.isComment) == true
}
}
context("setting up the Screen") {
beforeEach {
subject = OmnibarViewController()
screen = OmnibarMockScreen()
subject.screen = screen
showController(subject)
}
it("has the correct title") {
expect(subject.screen.title) == ""
}
it("has the correct submit title") {
expect(subject.screen.submitTitle) == InterfaceString.Omnibar.CreatePostButton
}
}
context("submitting a post") {
it("should generate PostEditingService.PostContentRegion") {
let image = UIImage.imageWithColor(UIColor.black)!
let data = Data()
let contentType = "image/gif"
let text = NSAttributedString(string: "test")
let regions = [
OmnibarRegion.image(image),
OmnibarRegion.imageData(image, data, contentType),
OmnibarRegion.attributedText(text),
OmnibarRegion.spacer,
OmnibarRegion.imageURL(URL(string: "http://example.com")!),
]
subject = OmnibarViewController()
let content = subject.generatePostRegions(regions)
expect(content.count) == 3
guard case let PostEditingService.PostContentRegion.image(outImage) = content[0]
else {
fail("content[0] is not PostEditingService.PostContentRegion.Image")
return
}
expect(outImage) == image
guard
case let PostEditingService.PostContentRegion.imageData(
_,
outData,
outType
) = content[1]
else {
fail("content[1] is not PostEditingService.PostContentRegion.ImageData")
return
}
expect(outData) == data
expect(outType) == contentType
guard case let PostEditingService.PostContentRegion.text(outText) = content[2]
else {
fail("content[2] is not PostEditingService.PostContentRegion.Text")
return
}
expect(outText) == text.string
}
describe("testing the submission in flight") {
it("disables interaction while submitting the post") {
ElloProvider.moya = ElloProvider.DelayedStubbingProvider()
let text = NSAttributedString(string: "test")
let regions = [OmnibarRegion.attributedText(text)]
subject = OmnibarViewController()
subject.currentUser = User.stub([:])
screen = OmnibarMockScreen()
subject.screen = screen
showController(subject)
subject.submitted(regions: regions, buyButtonURL: nil)
expect(screen.isInteractionEnabled) == false
}
it("enables interaction after submitting the post") {
let text = NSAttributedString(string: "test")
let regions = [OmnibarRegion.attributedText(text)]
subject = OmnibarViewController()
subject.currentUser = User.stub([:])
screen = OmnibarMockScreen()
subject.screen = screen
showController(subject)
subject.submitted(regions: regions, buyButtonURL: nil)
expect(screen.isInteractionEnabled) == true
}
}
}
context("submitting a comment") {
var post: Post!
beforeEach {
// need to pull the parent post id out of the create-comment sample json
let commentData = ElloAPI.createComment(parentPostId: "-", body: [:]).sampleData
let commentJSON = try! JSONSerialization.jsonObject(
with: commentData,
options: []
) as! [String: Any]
let postId = (commentJSON["comments"] as! [String: Any])["post_id"] as! String
post = Post.stub(["id": postId, "watching": false])
ElloProvider.moya = ElloProvider.RecordedStubbingProvider([
RecordedResponse(
endpoint: .postDetail(postParam: postId),
response: .networkResponse(
200,
// the id of this stubbed post must match the postId above ("52" last time I checked)
stubbedData("post_detail__watching")
)
),
])
subject = OmnibarViewController(parentPostId: post.id)
subject.currentUser = User.stub([:])
showController(subject)
let text = NSAttributedString(string: "test")
let regions = [OmnibarRegion.attributedText(text)]
subject.submitted(regions: regions, buyButtonURL: nil)
}
it(
"sets the watching property of the parent post to true after submitting the post"
) {
let parentPost = ElloLinkedStore.shared.getObject(post.id, type: .postsType)
as! Post
expect(parentPost.isWatching) == true
}
}
context("restoring a comment") {
beforeEach {
let post = Post.stub([
"author": User.stub(["username": "colinta"])
])
let attributedString = NSAttributedString(defaults: "text")
let image = UIImage.imageWithColor(.black)!
let omnibarData = OmnibarCacheData()
omnibarData.regions = [attributedString, image]
let data = NSKeyedArchiver.archivedData(withRootObject: omnibarData)
subject = OmnibarViewController(parentPostId: post.id)
if let fileName = subject.omnibarDataName() {
_ = Tmp.write(data, to: fileName)
}
screen = OmnibarMockScreen()
subject.screen = screen
showController(subject)
}
afterEach {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
}
it("has text set") {
checkRegions(screen.regions, equal: "text")
}
it("has image set") {
expect(screen).to(haveImageRegion())
}
}
context("saving a comment") {
beforeEach {
let post = Post.stub([
"author": User.stub(["username": "colinta"])
])
subject = OmnibarViewController(parentPostId: post.id)
screen = OmnibarMockScreen()
subject.screen = screen
subject.beginAppearanceTransition(true, animated: false)
subject.endAppearanceTransition()
let image = UIImage.imageWithColor(.black)!
screen.regions = [
.text("text"), .image(image)
]
}
afterEach {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
}
it("saves the data when cancelled") {
expect(Tmp.fileExists(subject.omnibarDataName()!)).to(beFalse())
subject.cancelTapped()
expect(Tmp.fileExists(subject.omnibarDataName()!)).to(beTrue())
}
}
context("initialization with default text") {
let post = Post.stub([:])
beforeEach {
subject = OmnibarViewController(parentPostId: post.id, defaultText: "@666 ")
showController(subject)
}
afterEach {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
}
it("has the text in the textView") {
checkRegions(subject.screen.regions, contain: "@666 ")
}
it("ignores the saved text when defaultText is given") {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
let text = NSAttributedString(defaults: "testing!")
let omnibarData = OmnibarCacheData()
omnibarData.regions = [text]
let data = NSKeyedArchiver.archivedData(withRootObject: omnibarData)
if let fileName = subject.omnibarDataName() {
_ = Tmp.write(data, to: fileName)
}
subject = OmnibarViewController(parentPostId: post.id, defaultText: "@666 ")
checkRegions(subject.screen.regions, contain: "@666 ")
checkRegions(subject.screen.regions, notToContain: "testing!")
}
it("does not have the text if the tmp text was on another post") {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
let text = NSAttributedString(defaults: "testing!")
let omnibarData = OmnibarCacheData()
omnibarData.regions = [text]
let data = Data()
if let fileName = subject.omnibarDataName() {
_ = Tmp.write(data, to: fileName)
}
subject = OmnibarViewController(parentPostId: "123", defaultText: "@666 ")
checkRegions(subject.screen.regions, contain: "@666 ")
checkRegions(subject.screen.regions, notToContain: "testing!")
}
it("has the correct title") {
expect(subject.screen.title) == "Leave a comment"
}
it("has the correct submit title") {
expect(subject.screen.submitTitle) == "Comment"
}
}
context("editing a post") {
let post = Post.stub([:])
beforeEach {
// NB: this post will be *reloaded* using the stubbed json response
// so if you wonder where the text comes from, it's from there, not
// the stubbed post.
subject = OmnibarViewController(editPost: post)
}
it("has the post body in the textView") {
checkRegions(subject.screen.regions, contain: "did you say \"mancrush\"")
}
it("has the text if there was tmp text available") {
if let fileName = subject.omnibarDataName() {
_ = Tmp.remove(fileName)
}
let text = NSAttributedString(defaults: "testing!")
let omnibarData = OmnibarCacheData()
omnibarData.regions = [text]
let data = NSKeyedArchiver.archivedData(withRootObject: omnibarData)
if let fileName = subject.omnibarDataName() {
_ = Tmp.write(data, to: fileName)
}
subject = OmnibarViewController(editPost: post)
checkRegions(subject.screen.regions, notToContain: "testing!")
}
it("has the correct title") {
expect(subject.screen.title) == "Edit this post"
}
it("has the correct submit title") {
expect(subject.screen.submitTitle) == "Edit Post"
}
}
context("post editability") {
it("can edit a single text region") {
let regions: [Regionable]? = [
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("can edit a single image region") {
let regions: [Regionable]? = [
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("can edit an image region followed by a text region") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("cannot edit zero regions") {
let regions: [Regionable]? = [Regionable]()
expect(OmnibarViewController.canEditRegions(regions)) == false
}
it("cannot edit nil") {
let regions: [Regionable]? = nil
expect(OmnibarViewController.canEditRegions(regions)) == false
}
it("can edit two text regions") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("can edit two image regions") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("can edit a text region followed by an image region") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
describe("can edit two text regions and a single image region") {
it("text, text, image") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
TextRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("text, image, text") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
ImageRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("image, text, text") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
TextRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
}
describe("can edit two image regions and a single text region") {
it("text, image, image") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
ImageRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("image, text, image") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
TextRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
it("image, image, text") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
ImageRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == true
}
}
describe("cannot edit embed regions") {
it("text, embed, image") {
let regions: [Regionable]? = [
TextRegion.stub([:]),
EmbedRegion.stub([:]),
ImageRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == false
}
it("embed, image, text") {
let regions: [Regionable]? = [
EmbedRegion.stub([:]),
ImageRegion.stub([:]),
TextRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == false
}
it("image, text, embed") {
let regions: [Regionable]? = [
ImageRegion.stub([:]),
TextRegion.stub([:]),
EmbedRegion.stub([:])
]
expect(OmnibarViewController.canEditRegions(regions)) == false
}
}
}
}
}
}
|
mit
|
df3a6981dd456b292947830626c34ab1
| 39.90566 | 117 | 0.452352 | 5.779792 | false | false | false | false |
sauravexodus/RxFacebook
|
Carthage/Checkouts/facebook-sdk-swift/Samples/Catalog/Sources/AlertController.swift
|
2
|
3507
|
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import UIKit
extension UIAlertAction {
/// Action types most commonly used
public enum ActionType {
///Ok Option
case ok
/// Default Cancel Option
case cancel
/// Destructive action with custom title
case destructive(String)
/// Custom action with title and style
case custom(String, UIAlertActionStyle)
/**
Creates the action instance for UIAlertController
- parameter handler: Call Back function
- returns UIAlertAction Instance
*/
public func action(handler: ((String) -> Void)? = nil) -> UIAlertAction {
//Default value
var actionStyle = UIAlertActionStyle.default
var title = ""
// Action configuration based on the action type
switch self {
case .cancel:
actionStyle = .cancel
title = "Cancel"
case .destructive(let optionTitle):
title = optionTitle
actionStyle = .destructive
case .custom(let optionTitle, let style):
title = optionTitle
actionStyle = style
default:
title = "OK"
}
//Creating UIAlertAction instance
return UIAlertAction(title:title, style:actionStyle) { nativeAction in
if let handler = handler {
handler(title)
}
}
}
}
}
extension UIAlertController {
/**
Creates the alert view controller using the actions specified
- parameter title: Title of the alert.
- parameter message: Alert message body.
- parameter actions: Variable numbre of actions as an Array of actionType values.
- parameter style: UIAlertControllerStyle enum value
- parameter handler: Handler block/closure for the clicked option.
*/
convenience init(title: String,
message: String,
actions: UIAlertAction.ActionType?...,
style: UIAlertControllerStyle = .alert,
handler: ((String) -> Swift.Void)? = nil) {
//initialize the contoller (self) instance
self.init(title: title, message: message, preferredStyle: style)
if actions.isEmpty {
addAction(UIAlertAction.ActionType.ok.action(handler: handler))
} else {
//Fetching actions specidied by the user and adding actions accordingly
for actionType in actions {
addAction((actionType?.action(handler: handler))!)
}
}
}
}
|
mit
|
ce6618e2f0ac6bff6422cb231a723300
| 33.048544 | 84 | 0.676076 | 4.98862 | false | false | false | false |
tuanan94/FRadio-ios
|
SwiftRadio/Libraries/Spring/AsyncImageView.swift
|
1
|
2074
|
// The MIT License (MIT)
//
// Copyright (c) 2015 James Tang ([email protected])
//
// 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 class AsyncImageView: UIImageView {
@objc public var placeholderImage : UIImage?
@objc public var url : NSURL? {
didSet {
self.image = placeholderImage
if let urlString = url?.absoluteString {
ImageLoader.sharedLoader.imageForUrl(urlString: urlString) { [weak self] image, url in
if let strongSelf = self {
DispatchQueue.main.async(execute: { () -> Void in
if strongSelf.url?.absoluteString == url {
strongSelf.image = image ?? strongSelf.placeholderImage
}
})
}
}
}
}
}
@objc public func setURL(url: NSURL?, placeholderImage: UIImage?) {
self.placeholderImage = placeholderImage
self.url = url
}
}
|
mit
|
9df3be4028b025027b235c8feea596aa
| 39.666667 | 102 | 0.647059 | 4.973621 | false | false | false | false |
ccrama/Slide-iOS
|
Slide for Reddit/UIAlert+Extensions.swift
|
1
|
5127
|
//
// UIAlert+Extensions.swift
// Slide for Reddit
//
// Created by Carlos Crane on 2/3/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import Anchorage
import Foundation
import SDCAlertView
extension AlertController {
public func addCancelButton() {
if self.preferredStyle == .actionSheet {
let cancelAction = AlertAction(title: "Cancel", style: .preferred, handler: nil)
self.addAction(cancelAction)
} else {
let cancelAction = AlertAction(title: "Cancel", style: .preferred, handler: nil)
self.addAction(cancelAction)
}
}
public func addCloseButton() {
if self.preferredStyle == .actionSheet {
let cancelAction = AlertAction(title: "Close", style: .preferred, handler: nil)
self.addAction(cancelAction)
} else {
let cancelAction = AlertAction(title: "Close", style: .preferred, handler: nil)
self.addAction(cancelAction)
}
}
}
extension UIAlertController {
public func addCancelButton() {
if self.preferredStyle == .actionSheet {
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
self.addAction(cancelAction)
} else {
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
self.addAction(cancelAction)
}
}
private struct AssociatedKeys {
static var blurStyleKey = "UIAlertController.blurStyleKey"
}
public var cancelButtonColor: UIColor? {
return ColorUtil.theme.foregroundColor
}
private var visualEffectView: UIVisualEffectView? {
if let presentationController = presentationController, presentationController.responds(to: Selector(("popoverView"))), let view = presentationController.value(forKey: "popoverView") as? UIView // We're on an iPad and visual effect view is in a different place.
{
return view.recursiveSubviews.compactMap({ $0 as? UIVisualEffectView }).first
}
return view.recursiveSubviews.compactMap({ $0 as? UIVisualEffectView }).first
}
private var cancelActionView: UIView? {
return view.recursiveSubviews.compactMap({
$0 as? UILabel }
).first(where: {
$0.text == actions.first(where: { $0.style == .cancel })?.title
})?.superview?.superview
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.view.tag != -1 {
objc_setAssociatedObject(self, &AssociatedKeys.blurStyleKey, ColorUtil.theme.isLight ? UIBlurEffect.Style.light : UIBlurEffect.Style.dark, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
view.tag = -1
view.setNeedsLayout()
view.layoutIfNeeded()
self.view.tintColor = ColorUtil.baseAccent
let titleFont = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]
let messageFont = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]
let titleAttrString = NSMutableAttributedString(string: title ?? "", attributes: titleFont)
let messageAttrString = NSMutableAttributedString(string: message ?? "", attributes: messageFont)
self.setValue(titleAttrString, forKey: "attributedTitle")
if !(message?.isEmpty ?? true) {
self.setValue(messageAttrString, forKey: "attributedMessage")
}
if let firstSubview = self.view.subviews.first, let alertContentView = firstSubview.subviews.first {
for view in alertContentView.subviews {
view.backgroundColor = ColorUtil.theme.foregroundColor.withAlphaComponent(0.6)
}
}
}
visualEffectView?.effect = UIBlurEffect(style: ColorUtil.theme.isLight ? UIBlurEffect.Style.light : UIBlurEffect.Style.dark)
if self.preferredStyle == .actionSheet && UIDevice.current.userInterfaceIdiom != .pad {
cancelActionView?.backgroundColor = ColorUtil.theme.foregroundColor
}
}
}
extension UIView {
var recursiveSubviews: [UIView] {
var subviews = self.subviews.compactMap({ $0 })
subviews.forEach { subviews.append(contentsOf: $0.recursiveSubviews) }
return subviews
}
}
class CancelButtonViewController: UIViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let cancelView = UILabel().then {
$0.text = "Cancel"
$0.font = UIFont.boldSystemFont(ofSize: 20)
$0.textColor = ColorUtil.baseAccent
$0.clipsToBounds = true
$0.backgroundColor = ColorUtil.theme.foregroundColor
$0.textAlignment = .center
}
self.view.addSubview(cancelView)
cancelView.edgeAnchors == self.view.edgeAnchors
}
}
|
apache-2.0
|
f5f823140f71d4929d8c92ad7163a415
| 40.674797 | 269 | 0.643192 | 5.105578 | false | false | false | false |
arbitur/Func
|
source/UI/ViewControllers/SlideTabController.swift
|
1
|
10004
|
//
// ViewController.swift
// Test
//
// Created by Philip Fryklund on 27/9/16.
// Copyright © 2016 Philip Fryklund. All rights reserved.
//
import Foundation
open class SlideTabController: UIViewController {
fileprivate let scrollView = ScrollView()
private let menu = Menu()
public var selectedIndex: Int { return menu.index }
public var selectedViewController: UIViewController? {
return self.children[safe: menu.index]
}
open override var childForStatusBarHidden: UIViewController? {
DispatchQueue.main.async {
NotificationCenter.default.post(name: UIApplication.didChangeStatusBarFrameNotification, object: nil)
}
return self.selectedViewController
}
open override var childForStatusBarStyle: UIViewController? {
return self.selectedViewController
}
// func selectViewController(index: Int) {
// menu.selectViewController(index: index)
// }
private func showViewController(_ vc: UIViewController) {
if !vc.isViewLoaded {
vc.loadViewIfNeeded()
self.scrollView.addSubview(vc.view)
vc.view.frame.size = scrollView.bounds.size
vc.view.layoutIfNeeded()
vc.didMove(toParent: self)
}
}
public func load(viewControllers: [UIViewController]) {
if !viewControllers.isEmpty {
self.loadViewIfNeeded()
for vc in viewControllers {
self.addChild(vc)
scrollView.stackView.addArrangedSubview(vc.view)
menu.addTab(title: vc.title ?? "Title")
vc.view.lac.width.equalTo(self.view.lac.width)
}
// selectViewController(index: 0)
menu.index = 0
showViewController(self.children.first!)
}
}
public var initialIndex: Int?
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// print(scrollView.frame, scrollView.contentSize)
if scrollView.contentSize != CGSize.zero, let index = initialIndex {
initialIndex = nil
let x = CGFloat(index) * scrollView.bounds.width
scrollView.contentOffset.x = x
menu.index = index
}
}
open override func loadView() {
self.view = UIView(backgroundColor: .white)
self.view.add(views: menu, scrollView)
menu.lac.make {
$0.left.equalToSuperview()
$0.right.equalToSuperview()
switch SlideTabAppearance.align {
case .top: $0.top.equalTo(self.topLayoutGuide.lac.bottom)
case .bottom: $0.bottom.equalTo(self.bottomLayoutGuide.lac.top)
}
}
scrollView.lac.make {
$0.left.equalToSuperview()
$0.right.equalToSuperview()
switch SlideTabAppearance.align {
case .top:
$0.top.equalTo(menu.lac.bottom)
$0.bottom.equalToSuperview()
case .bottom:
$0.top.equalToSuperview()
$0.bottom.equalTo(menu.lac.top)
}
}
}
open override func viewDidLoad() {
super.viewDidLoad()
scrollView.isPagingEnabled = true
scrollView.delegate = self
}
public convenience init(viewControllers: [UIViewController]) {
self.init(nibName: nil, bundle: nil)
load(viewControllers: viewControllers)
}
}
extension SlideTabController: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let fullWidth = scrollView.contentSize.width
let leftPosition = scrollView.contentOffset.x
let rightPosition = scrollView.contentOffset.x + scrollView.bounds.width
// let index = Int((rightPosition - 1) / scrollView.bounds.width)
//// print(index)
//
// if let vc = self.childViewControllers[safe: index] {
// showViewController(vc)
// }
// print("Left: \(leftPosition / fullWidth)%", "Right: \(rightPosition / fullWidth)%")
menu.indicator.frame.left = menu.contentSize.width * (leftPosition / fullWidth)
menu.indicator.frame.size.width = menu.contentSize.width * ((rightPosition - leftPosition) / fullWidth)
//TODO: Right edge not flush
if scrollView.contentSize.width > scrollView.bounds.width {
let offset = menu.contentOffset.x
let width = menu.bounds.width
let left = menu.indicator.frame.left
let right = menu.indicator.frame.right
let maxOffset = menu.contentSize.width - width
let limitOffset: CGFloat = width * 0.2
let leftLimit = offset + limitOffset
let rightLimit = offset + width - limitOffset
if offset > 0 && left < leftLimit {
let distance = leftLimit - left
menu.contentOffset.x = max(0, offset - distance)
}
else if offset < maxOffset && right > rightLimit {
let distance = right - rightLimit
menu.contentOffset.x = min(maxOffset, offset + distance)
}
}
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = false
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.isUserInteractionEnabled = true
let index = (scrollView.contentOffset.x + scrollView.bounds.width) / scrollView.bounds.width
menu.index = Int(index) - 1
}
}
//extension SlideTabController: RootViewControllable {
//
// public var viewForEdgePanGestureRecognizer: UIView {
// return self.scrollView
// }
//}
private class ScrollView: UIScrollView {
var tabController: SlideTabController { return self.superViewController as! SlideTabController }
let stackView = UIStackView()
// private override func layoutSubviews() {
// super.layoutSubviews()
//
// self.contentSize.height = self.bounds.height
// self.contentSize.width = self.bounds.width * CGFloat(tabController.childViewControllers.count)
//
// for (i, vc) in tabController.childViewControllers.enumerated() {
// if let view = vc.viewIfLoaded {
// view.frame.size = self.bounds.size
// view.frame.left = self.bounds.width * CGFloat(i)
// }
// }
// }
convenience init() {
self.init(frame: CGRect.zero)
self.showsHorizontalScrollIndicator = false
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
self.addSubview(stackView)
stackView.lac.make {
$0.top.equalToSuperview()
$0.left.equalToSuperview()
$0.right.equalToSuperview()
$0.bottom.equalToSuperview()
$0.height.equalToSuperview()
}
}
}
public class SlideTabAppearance {
public static var backgroundColor: UIColor = .white
public static var indicatorColor: UIColor = .orange
public static var tabDeselectedTitleColor: UIColor = .lightGray
public static var tabSelectedTitleColor: UIColor = .darkGray
public static var tabTitleFont: UIFont = UIFont.systemFont(ofSize: 15, weight: .semibold)
public static var indicatorHeight: CGFloat = 2
public static var indicatorMinimumWidth: CGFloat = 95
public static var align: MenuAlign = .top
}
public enum MenuAlign {
case top, bottom
}
protocol MenuDelegate {
func selected(vc: UIViewController)
}
private class Menu: UIScrollView {
let stackView = StackView()
var indicator: UIView { return stackView.indicator }
var index: Int = 0 {
willSet {
let button = stackView.arrangedSubviews[index] as! UIButton
button.tintColor = SlideTabAppearance.tabDeselectedTitleColor
}
didSet {
let button = stackView.arrangedSubviews[index] as! UIButton
button.tintColor = SlideTabAppearance.tabSelectedTitleColor
self.superViewController?.setNeedsStatusBarAppearanceUpdate()
}
}
func selectViewController(index: Int) {
self.index = index
let tc = self.superViewController as! SlideTabController
let offset = CGPoint(tc.scrollView.bounds.width * CGFloat(index), tc.scrollView.contentOffset.y)
tc.scrollView.setContentOffset(offset, animated: true)
}
@objc func press(button: UIButton) {
selectViewController(index: button.tag)
}
func addTab(title: String) {
let btn = UIButton(type: .system)
btn.titleLabel!.font = SlideTabAppearance.tabTitleFont
btn.tintColor = SlideTabAppearance.tabDeselectedTitleColor
btn.setTitle(title, for: .normal)
btn.tag = stackView.arrangedSubviews.count
btn.addTarget(self, action: #selector(press(button:)), for: .touchUpInside)
stackView.addArrangedSubview(btn)
btn.lac.make {
$0.width.greaterThan(SlideTabAppearance.indicatorMinimumWidth)
$0.width.lessThan(self.lac.width, multiplier: 0.6)
}
}
private var heightConstraint: NSLayoutConstraint?
private var topConstraint: NSLayoutConstraint?
@objc func didChangeStatusBar(_ notification: Notification) {
var vc: UIViewController? = self.superViewController
while(vc != nil) {
if let nc = vc as? UINavigationController, !nc.isNavigationBarHidden { return }
vc = vc?.parent
}
let height = UIApplication.shared.statusBarFrame.height
heightConstraint?.constant = 44 + height
topConstraint?.constant = height
}
convenience init() {
self.init(frame: CGRect.zero)
self.bounces = false
self.showsHorizontalScrollIndicator = false
self.backgroundColor = SlideTabAppearance.backgroundColor
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.spacing = 10
self.addSubview(stackView)
heightConstraint = self.lac.height.equalTo(44)
stackView.lac.make {
topConstraint = $0.top.equalToSuperview()
$0.left.equalToSuperview()
$0.right.equalToSuperview()
$0.bottom.equalToSuperview()
$0.width.greaterThan(self.lac.width)
$0.height.equalTo(44)
}
NotificationCenter.default.addObserver(self, selector: #selector(didChangeStatusBar(_:)), name: UIApplication.didChangeStatusBarFrameNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
class StackView: UIStackView {
let indicator = UIView(backgroundColor: SlideTabAppearance.indicatorColor)
override func layoutSubviews() {
super.layoutSubviews()
indicator.frame.bottom = self.bounds.height
if let btn = self.arrangedSubviews[safe: 0] {
indicator.frame.size.width = btn.bounds.width
}
}
convenience init() {
self.init(frame: CGRect.zero)
indicator.frame.size.height = SlideTabAppearance.indicatorHeight
self.addSubview(indicator)
}
}
}
|
mit
|
dd620e79a07f702129f6a8092a4d498e
| 22.591981 | 161 | 0.722183 | 3.851752 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/binary-trees-with-factors.swift
|
2
|
803
|
/**
* https://leetcode.com/problems/binary-trees-with-factors/
*
*
*/
// Date: Thu Mar 18 21:09:13 PDT 2021
class Solution {
func numFactoredBinaryTrees(_ arr: [Int]) -> Int {
let arr = arr.sorted()
let mod = 1_000_000_007
var map: [Int : Int] = [:]
for x in arr {
map[x] = 1
}
var result = 0
for i in stride(from: 0, to: arr.count, by: 1) {
for j in stride(from: 0, to: i, by: 1) {
if arr[i] % arr[j] == 0, let x = map[arr[j]], let y = map[arr[i] / arr[j]] {
map[arr[i]] = (map[arr[i]]! + x * y) % mod
}
}
// print("\(arr[i]) - \(map[arr[i]])")
result = (result + map[arr[i]]!) % mod
}
return result
}
}
|
mit
|
04600a22d5e17c04085afaa2facc2b7b
| 28.777778 | 92 | 0.429639 | 3.14902 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/subarray-sum-equals-k.swift
|
2
|
1306
|
/**
* https://leetcode.com/problems/subarray-sum-equals-k/
*
*
*/
// Date: Wed Apr 22 09:38:00 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(n^2), n is the number of elements in the array.
/// - Space: O(n)
///
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
var count = 0
var sum: [Int] = [0]
for n in nums {
sum.append((sum.last ?? 0) + n)
}
for start in 0 ..< sum.count - 1 {
for end in start + 1 ..< sum.count {
if sum[end] - sum[start] == k {
count += 1
}
}
}
return count
}
}
/**
* https://leetcode.com/problems/subarray-sum-equals-k/
*
*
*/
// Date: Wed Apr 22 11:49:46 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(n), n is the number of elements in the array.
/// - Space: O(n)
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
var count = 0
var sumCount: [Int : Int] = [0 : 1]
var sum = 0
for n in nums {
sum += n
if let sumC = sumCount[sum - k] {
count += sumC
}
sumCount[sum] = 1 + sumCount[sum, default: 0]
}
return count
}
}
|
mit
|
bd0466b29b61a9cb2f77facfd283e50f
| 24.115385 | 69 | 0.438744 | 3.482667 | false | false | false | false |
yahoojapan/SwiftyXMLParser
|
SwiftyXMLParserTests/ConverterTests.swift
|
1
|
8010
|
/**
* The MIT License (MIT)
*
* Copyright (C) 2016 Yahoo Japan Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import XCTest
import SwiftyXMLParser
class ConverterTests: XCTestCase {
func testMakeDosument() {
// no chiled element, text only
do {
let element = XML.Element(name: "name",
text: "text",
attributes: ["key": "value"])
let converter = XML.Converter(XML.Accessor(element))
guard let result = try? converter.makeDocument() else {
XCTFail("fail to make document")
return
}
let extpected = """
<?xml version="1.0" encoding="UTF-8"?><name key="value">text</name>
"""
XCTAssertEqual(result, extpected)
}
// no text, chiled elements only
do {
let childElements = [
XML.Element(name: "c_name1", text: "c_text1", attributes: ["c_key1": "c_value1"]),
XML.Element(name: "c_name2", text: "c_text2", attributes: ["c_key2": "c_value2"])
]
let element = XML.Element(name: "name",
text: nil,
attributes: ["key": "value"],
childElements: childElements)
let converter = XML.Converter(XML.Accessor(element))
guard let result = try? converter.makeDocument() else {
XCTFail("fail to make document")
return
}
let extpected = """
<?xml version="1.0" encoding="UTF-8"?><name key="value"><c_name1 c_key1="c_value1">c_text1</c_name1><c_name2 c_key2="c_value2">c_text2</c_name2></name>
"""
XCTAssertEqual(result, extpected)
}
// both text and chiled element
do {
let childElements = [
XML.Element(name: "c_name1", text: "c_text1", attributes: ["c_key1": "c_value1"]),
XML.Element(name: "c_name2", text: "c_text2", attributes: ["c_key2": "c_value2"])
]
let element = XML.Element(name: "name",
text: "text",
attributes: ["key": "value"],
childElements: childElements)
let converter = XML.Converter(XML.Accessor(element))
guard let result = try? converter.makeDocument() else {
XCTFail("fail to make document")
return
}
let extpected = """
<?xml version="1.0" encoding="UTF-8"?><name key="value">text<c_name1 c_key1="c_value1">c_text1</c_name1><c_name2 c_key2="c_value2">c_text2</c_name2></name>
"""
XCTAssertEqual(result, extpected)
}
// nested child elements
do {
let grateGrandchildElements = [
XML.Element(name: "ggc_name1", text: "ggc_text1", attributes: ["ggc_key1": "ggc_value1"])
]
let grandchildElements = [
XML.Element(name: "gc_name1", text: "gc_text1", attributes: ["gc_key1": "gc_value1"], childElements: grateGrandchildElements)
]
let childElements = [
XML.Element(name: "c_name1", text: "c_text1", attributes: ["c_key1": "c_value1"]),
XML.Element(name: "c_name2", text: "c_text2", attributes: ["c_key2": "c_value2"], childElements: grandchildElements)
]
let element = XML.Element(name: "name",
text: "text",
attributes: ["key": "value"],
childElements: childElements)
let converter = XML.Converter(XML.Accessor(element))
guard let result = try? converter.makeDocument() else {
XCTFail("fail to make document")
return
}
let extpected = """
<?xml version="1.0" encoding="UTF-8"?><name key="value">text<c_name1 c_key1="c_value1">c_text1</c_name1><c_name2 c_key2="c_value2">c_text2<gc_name1 gc_key1="gc_value1">gc_text1<ggc_name1 ggc_key1="ggc_value1">ggc_text1</ggc_name1></gc_name1></c_name2></name>
"""
XCTAssertEqual(result, extpected)
}
}
func testMakeDocumentEscapingCharacters() throws {
let element = XML.Element(name: "name", text: "me&you", childElements: [
XML.Element(name: "child", text: "& < > &")
])
let converter = XML.Converter(XML.Accessor(element))
XCTAssertEqual(
try converter.makeDocument(),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><name>me&you<child>& < > &</child></name>",
"escape characters when making xml document"
)
}
func testMakeDocumentWithoutAttributes() throws {
let element = XML.Element(name: "name")
let converter = XML.Converter(XML.Accessor(element))
XCTAssertEqual(
try converter.makeDocument(),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><name></name>",
"convert xml document without extra spaces when no attributes are provided"
)
let element2 = XML.Element(name: "name",
text: "text",
attributes: ["key": "value"],
childElements: [
XML.Element(name: "name1"),
XML.Element(name: "name2", text: "text2")
])
let converter2 = XML.Converter(XML.Accessor(element2))
XCTAssertEqual(
try converter2.makeDocument(),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><name key=\"value\">text<name1></name1><name2>text2</name2></name>",
"convert xml document with child elements without extra spaces when no attributes are provided"
)
}
func testMakeWithoutDeclaration() throws {
let element = XML.Element(name: "name")
let converter = XML.Converter(XML.Accessor(element))
XCTAssertEqual(
try converter.makeDocument(withDeclaration: false),
"<name></name>",
"convert xml document without xml declaration header"
)
let element2 = XML.Element(name: "name",
text: "text",
attributes: ["key": "value"])
let converter2 = XML.Converter(XML.Accessor(element2))
XCTAssertEqual(
try converter2.makeDocument(withDeclaration: false),
"<name key=\"value\">text</name>",
"convert xml document without xml declaration header"
)
}
}
|
mit
|
a6bf5754188fd22c444c0d5f8e1f6a9d
| 43.5 | 266 | 0.539076 | 4.346175 | false | false | false | false |
hooman/swift
|
test/Concurrency/Runtime/async_taskgroup_is_asyncsequence.swift
|
2
|
1521
|
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library) | %FileCheck %s --dump-input=always
// REQUIRES: executable_test
// REQUIRES: concurrency
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: linux
@available(SwiftStdlib 5.5, *)
func test_taskGroup_is_asyncSequence() async {
print(#function)
let sum = await withTaskGroup(of: Int.self, returning: Int.self) { group in
for n in 1...10 {
group.spawn {
print("add \(n)")
return n
}
}
var sum = 0
for await r in group { // here
print("next: \(r)")
sum += r
}
return sum
}
print("result: \(sum)")
}
@available(SwiftStdlib 5.5, *)
func test_throwingTaskGroup_is_asyncSequence() async throws {
print(#function)
let sum = try await withThrowingTaskGroup(of: Int.self, returning: Int.self) { group in
for n in 1...10 {
group.spawn {
print("add \(n)")
return n
}
}
var sum = 0
for try await r in group { // here
print("next: \(r)")
sum += r
}
return sum
}
print("result: \(sum)")
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_is_asyncSequence()
// CHECK: test_taskGroup_is_asyncSequence()
// CHECK: result: 55
try! await test_throwingTaskGroup_is_asyncSequence()
// CHECK: test_throwingTaskGroup_is_asyncSequence()
// CHECK: result: 55
}
}
|
apache-2.0
|
016ffeddae3be7aafd05028e7c51609f
| 20.422535 | 130 | 0.614727 | 3.604265 | false | true | false | false |
lorentey/swift
|
test/expr/closure/closures.swift
|
1
|
14590
|
// RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
// expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11)
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base.
doVoidStuff({ self.x += 1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}}
// Methods follow the same rules as properties, uses of 'self' must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
doStuff { self.method() }
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }}
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0
var height = 0
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
// Don't expose @lvalue-ness in diagnostics.
let closure = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> Bool in }}
var helper = true
return helper
}
|
apache-2.0
|
7ccf66d26ead666e257bbd8372063e69
| 39.082418 | 270 | 0.643317 | 3.583006 | false | false | false | false |
samodom/TestSwagger
|
TestSwaggerTests/Tools/Spying/Spies/SpiesCommon.swift
|
1
|
2318
|
//
// SpiesCommon.swift
// TestSwagger
//
// Created by Sam Odom on 2/15/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
import TestSwagger
let SampleAssociationReference = SpyEvidenceReference(key: sampleKey)
fileprivate let sampleKeyString = UUIDKeyString()
fileprivate let sampleKey = ObjectAssociationKey(sampleKeyString)
let samplePath = TemporaryDirectoryPath.appendingFormat("sampleEvidence")
let SampleSerializationReference = SpyEvidenceReference(path: samplePath)
let SampleReferences: Set = [
SampleAssociationReference,
SampleSerializationReference
]
protocol SampleObjectSpyable: ObjectSpyable {}
extension SampleObjectSpyable {
var sampleInstanceMethodCalledAssociated: Bool {
get {
return loadEvidence(with: SampleAssociationReference) as? Bool ?? false
}
set {
guard newValue else {
return removeEvidence(with: SampleAssociationReference)
}
saveEvidence(true, with: SampleAssociationReference)
}
}
var sampleInstanceMethodCalledSerialized: Bool {
get {
return loadEvidence(with: SampleSerializationReference) as? Bool ?? false
}
set {
guard newValue else {
return removeEvidence(with: SampleSerializationReference)
}
saveEvidence(true, with: SampleSerializationReference)
}
}
}
protocol SampleClassSpyable: ClassSpyable {}
extension SampleClassSpyable {
static var sampleClassMethodCalledAssociated: Bool {
get {
return loadEvidence(with: SampleAssociationReference) as? Bool ?? false
}
set {
guard newValue else {
return removeEvidence(with: SampleAssociationReference)
}
saveEvidence(true, with: SampleAssociationReference)
}
}
static var sampleClassMethodCalledSerialized: Bool {
get {
return loadEvidence(with: SampleSerializationReference) as? Bool ?? false
}
set {
guard newValue else {
return removeEvidence(with: SampleSerializationReference)
}
saveEvidence(true, with: SampleSerializationReference)
}
}
}
|
mit
|
b7da1865954eac4e516a0ac89bd0643e
| 25.329545 | 85 | 0.6612 | 5.438967 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/AssistantV2/Models/RuntimeResponseGenericRuntimeResponseTypeAudio.swift
|
1
|
2332
|
/**
* (C) Copyright IBM Corp. 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import IBMSwiftSDKCore
/**
RuntimeResponseGenericRuntimeResponseTypeAudio.
Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeAudio:
RuntimeResponseGeneric
*/
public struct RuntimeResponseGenericRuntimeResponseTypeAudio: Codable, Equatable {
/**
The type of response returned by the dialog node. The specified response type must be supported by the client
application or channel.
*/
public var responseType: String
/**
The `https:` URL of the audio clip.
*/
public var source: String
/**
The title or introductory text to show before the response.
*/
public var title: String?
/**
The description to show with the the response.
*/
public var description: String?
/**
An array of objects specifying channels for which the response is intended. If **channels** is present, the
response is intended for a built-in integration and should not be handled by an API client.
*/
public var channels: [ResponseGenericChannel]?
/**
For internal use only.
*/
public var channelOptions: [String: JSON]?
/**
Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen.
*/
public var altText: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case responseType = "response_type"
case source = "source"
case title = "title"
case description = "description"
case channels = "channels"
case channelOptions = "channel_options"
case altText = "alt_text"
}
}
|
apache-2.0
|
223f3a462d4dffe50cb1d88476f64328
| 29.684211 | 116 | 0.694683 | 4.664 | false | false | false | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Exercise4.playgroundpage/Contents.swift
|
1
|
1704
|
//#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Collect as many gems as there are switches.
In this puzzle, you'll use a [constant](glossary://constant) called `switchCounter` to collect as many gems as there are switches. Like a [variable](glossary://variable), a constant is a named container that stores a value. However, the value of a constant *cannot* change while the program is running.
You [declare](glossary://declaration) a constant using the word `let` instead of `var`, and you use it when you know that a value won’t change.
* callout(Declaring a constant):
`let numberOfTries = 3`
To solve this puzzle, you’ll write conditional code that compares the value of a gem-counting variable with the constant `switchCounter`, using a [comparison operator](glossary://comparison%20operator) such as `<`, `>`, `==`, or `!=`.
1. steps: Declare a variable to track the number of gems Byte collects.
2. Compare the value of your gem-counting variable with `switchCounter` to determine when to stop Byte from collecting gems.
*/
//#-hidden-code
playgroundPrologue()
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, if, func, for, while, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, isOnClosedSwitch, var, =, <, >, ==, !=, +, -, switchCount, isBlocked, true, false, isBlockedLeft, &&, ||, !, isBlockedRight)
//#-editable-code Tap to enter code
let switchCounter = numberOfSwitches
//#-end-editable-code
//#-hidden-code
playgroundEpilogue()
//#-end-hidden-code
|
mit
|
bbcbe3a9f3ad79f5fafe1b515e5f4e46
| 44.945946 | 302 | 0.722353 | 4.057279 | false | false | false | false |
mshhmzh/firefox-ios
|
Client/Frontend/Widgets/HistoryBackButton.swift
|
2
|
2491
|
/* 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 SnapKit
import Shared
private struct HistoryBackButtonUX {
static let HistoryHistoryBackButtonHeaderChevronInset: CGFloat = 10
static let HistoryHistoryBackButtonHeaderChevronSize: CGFloat = 20
static let HistoryHistoryBackButtonHeaderChevronLineWidth: CGFloat = 3.0
}
class HistoryBackButton : UIButton {
lazy var title: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
label.text = Strings.HistoryBackButtonTitle
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .Left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronLineWidth
return chevron
}()
lazy var topBorder: UIView = self.createBorderView()
lazy var bottomBorder: UIView = self.createBorderView()
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = true
addSubview(topBorder)
addSubview(chevron)
addSubview(title)
backgroundColor = UIColor.whiteColor()
chevron.snp_makeConstraints { make in
make.leading.equalTo(self).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
make.size.equalTo(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronSize)
}
title.snp_makeConstraints { make in
make.leading.equalTo(chevron.snp_trailing).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.trailing.greaterThanOrEqualTo(self).offset(-HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
}
topBorder.snp_makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
}
private func createBorderView() -> UIView {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mpl-2.0
|
383d5c0d720442a369a2602f0951fb53
| 34.6 | 125 | 0.697712 | 5.222222 | false | false | false | false |
benlangmuir/swift
|
stdlib/public/BackDeployConcurrency/AsyncCompactMapSequence.swift
|
5
|
4866
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that maps the given closure over the
/// asynchronous sequence’s elements, omitting results that don't return a
/// value.
///
/// Use the `compactMap(_:)` method to transform every element received from
/// a base asynchronous sequence, while also discarding any `nil` results
/// from the closure. Typically, you use this to transform from one type of
/// element to another.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `5`. The closure provided to the `compactMap(_:)`
/// method takes each `Int` and looks up a corresponding `String` from a
/// `romanNumeralDict` dictionary. Because there is no key for `4`, the closure
/// returns `nil` in this case, which `compactMap(_:)` omits from the
/// transformed asynchronous sequence.
///
/// let romanNumeralDict: [Int : String] =
/// [1: "I", 2: "II", 3: "III", 5: "V"]
///
/// let stream = Counter(howHigh: 5)
/// .compactMap { romanNumeralDict[$0] }
/// for await numeral in stream {
/// print("\(numeral) ", terminator: " ")
/// }
/// // Prints: I II III V
///
/// - Parameter transform: A mapping closure. `transform` accepts an element
/// of this sequence as its parameter and returns a transformed value of the
/// same or of a different type.
/// - Returns: An asynchronous sequence that contains, in order, the
/// non-`nil` elements produced by the `transform` closure.
@inlinable
public __consuming func compactMap<ElementOfResult>(
_ transform: @escaping (Element) async -> ElementOfResult?
) -> AsyncCompactMapSequence<Self, ElementOfResult> {
return AsyncCompactMapSequence(self, transform: transform)
}
}
/// An asynchronous sequence that maps a given closure over the asynchronous
/// sequence’s elements, omitting results that don't return a value.
@available(SwiftStdlib 5.1, *)
public struct AsyncCompactMapSequence<Base: AsyncSequence, ElementOfResult> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async -> ElementOfResult?
@usableFromInline
init(
_ base: Base,
transform: @escaping (Base.Element) async -> ElementOfResult?
) {
self.base = base
self.transform = transform
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncCompactMapSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The compact map sequence produces whatever type of element its
/// transforming closure produces.
public typealias Element = ElementOfResult
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the compact map sequence.
public struct Iterator: AsyncIteratorProtocol {
public typealias Element = ElementOfResult
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async -> ElementOfResult?
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async -> ElementOfResult?
) {
self.baseIterator = baseIterator
self.transform = transform
}
/// Produces the next element in the compact map sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns `nil`. Otherwise, `next()` calls the
/// transforming closure on the received element, returning it if the
/// transform returns a non-`nil` value. If the transform returns `nil`,
/// this method continues to wait for further elements until it gets one
/// that transforms to a non-`nil` value.
@inlinable
public mutating func next() async rethrows -> ElementOfResult? {
while true {
guard let element = try await baseIterator.next() else {
return nil
}
if let transformed = await transform(element) {
return transformed
}
}
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
|
apache-2.0
|
60c4019f2746a4d8b24404788f0385d3
| 36.114504 | 81 | 0.660222 | 4.748047 | false | false | false | false |
uias/Tabman
|
Sources/Tabman/AutoInsetter/AutoInsetter.swift
|
1
|
2485
|
//
// AutoInsetter.swift
// AutoInset
//
// Created by Merrick Sapsford on 16/01/2018.
// Copyright © 2018 UI At Six. All rights reserved.
//
import UIKit
/// Engine that provides Auto Insetting to UIViewControllers.
internal final class AutoInsetter {
// MARK: Properties
private var currentContentInsets = [UIScrollView: UIEdgeInsets]()
private var currentContentOffsets = [UIScrollView: CGPoint]()
private let insetStore: InsetStore = DefaultInsetStore()
/// Whether auto-insetting is enabled.
@available(*, deprecated, message: "Use enable(for:)")
public var isEnabled: Bool {
get {
return _isEnabled
}
set {
if newValue {
_enable(for: nil)
}
}
}
private var _isEnabled: Bool = false
// MARK: Init
init() {}
// MARK: State
/// Enable Auto Insetting for a view controller.
///
/// - Parameter viewController: View controller that will provide insetting.
func enable(for viewController: UIViewController?) {
_enable(for: viewController)
}
private func _enable(for viewController: UIViewController?) {
_isEnabled = true
}
// MARK: Insetting
/// Inset a view controller by a set of required insets.
///
/// - Parameters:
/// - viewController: view controller to inset.
/// - requiredInsetSpec: The required inset specification.
func inset(_ viewController: UIViewController?,
requiredInsetSpec: AutoInsetSpec) {
guard let viewController = viewController, _isEnabled else {
return
}
if requiredInsetSpec.additionalRequiredInsets != viewController.additionalSafeAreaInsets {
viewController.additionalSafeAreaInsets = requiredInsetSpec.additionalRequiredInsets
}
}
}
// MARK: - Utilities
private extension AutoInsetter {
/// Check whether a view controller is an 'embedded' view controller type (i.e. UITableViewController)
///
/// - Parameters:
/// - viewController: The view controller.
/// - success: Execution if view controller is not embedded type.
func isEmbeddedViewController(_ viewController: UIViewController) -> Bool {
if (viewController is UITableViewController) || (viewController is UICollectionViewController) {
return true
}
return false
}
}
|
mit
|
c0c76277d3776f06fa2d69531e8bf0d4
| 28.223529 | 106 | 0.630435 | 5.153527 | false | false | false | false |
ahoppen/swift
|
test/Generics/concrete_conformances_in_protocol.swift
|
6
|
2956
|
// RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
struct S : P {
typealias T = S
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R0@
// CHECK-LABEL: Requirement signature: <Self where Self.[R0]A == S>
protocol R0 {
associatedtype A where A : P, A == S
// expected-warning@-1 {{redundant conformance constraint 'S' : 'P'}}
}
////
struct G<T> : P {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R1@
// CHECK-LABEL: Requirement signature: <Self where Self.[R1]B == G<Self.[R1]A>>
protocol R1 {
associatedtype A
associatedtype B where B : P, B == G<A>
// expected-warning@-1 {{redundant conformance constraint 'G<Self.A>' : 'P'}}
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R2@
// CHECK-LABEL: Requirement signature: <Self where Self.[R2]A == G<Self.[R2]B>>
protocol R2 {
associatedtype A where A : P, A == G<B>
// expected-warning@-1 {{redundant conformance constraint 'G<Self.B>' : 'P'}}
associatedtype B
}
////
protocol PP {
associatedtype T : P
}
struct GG<T : P> : PP {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR3@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR3]A : P, Self.[RR3]B == GG<Self.[RR3]A>>
protocol RR3 {
associatedtype A : P
associatedtype B where B : PP, B == GG<A>
// expected-warning@-1 {{redundant conformance constraint 'GG<Self.A>' : 'PP'}}
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR4@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR4]A == GG<Self.[RR4]B>, Self.[RR4]B : P>
protocol RR4 {
associatedtype A where A : PP, A == GG<B>
// expected-warning@-1 {{redundant conformance constraint 'GG<Self.B>' : 'PP'}}
associatedtype B : P
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR5@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR5]A : PP, Self.[RR5]B == GG<Self.[RR5]A.[PP]T>>
protocol RR5 {
associatedtype A : PP
associatedtype B where B : PP, B == GG<A.T>
// expected-warning@-1 {{redundant conformance constraint 'GG<Self.A.T>' : 'PP'}}
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR6@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR6]A == GG<Self.[RR6]B.[PP]T>, Self.[RR6]B : PP>
protocol RR6 {
associatedtype A where A : PP, A == GG<B.T>
// expected-warning@-1 {{redundant conformance constraint 'GG<Self.B.T>' : 'PP'}}
associatedtype B : PP
}
protocol P1 {
associatedtype T : P1
}
struct GGG<U : P1> : P1 {
typealias T = GGG<GGG<U>>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).P2@
// CHECK-LABEL: Requirement signature: <Self where Self.[P2]T == GGG<Self.[P2]U>, Self.[P2]U : P1>
protocol P2 {
associatedtype T : P1 where T == GGG<U>
// expected-warning@-1 {{redundant conformance constraint 'GGG<Self.U>' : 'P1'}}
associatedtype U : P1
}
|
apache-2.0
|
c79d73a4cb16c5e620a2d97327c51f06
| 28.267327 | 106 | 0.667118 | 3.044284 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/Supporting Files/UIComponents/WaveformView.swift
|
1
|
3872
|
//
// WaveformView.swift
// Pods
//
// Created by Alankar Misra on 7/23/15.
//
// Swift adaption of: https://github.com/stefanceriu/SCSiriWaveformView (interface incompatible)
import UIKit
open class WaveformView: UIView {
/*
* The frequency of the sinus wave. The higher the value, the more sinus wave peaks you will have.
* Default: 1.5
*/
@IBInspectable open var frequency:CGFloat = 1.5
/*
* The amplitude that is used when the incoming amplitude is near zero.
* Setting a value greater 0 provides a more vivid visualization.
* Default: 0.01
*/
@IBInspectable open var idleAmplitude:CGFloat = 0.01
/*
* The phase shift that will be applied with each level setting
* Change this to modify the animation speed or direction
* Default: -0.15
*/
@IBInspectable open var phaseShift:CGFloat = -0.15
/*
* The lines are joined stepwise, the more dense you draw, the more CPU power is used.
* Default: 1
*/
@IBInspectable open var density:CGFloat = 1.0
/*
* Line width used for the prominent wave
* Default: 1.5
*/
@IBInspectable open var primaryLineWidth:CGFloat = 1.5
/*
* Line width used for all secondary waves
* Default: 0.5
*/
@IBInspectable open var secondaryLineWidth:CGFloat = 0.5
/*
* The total number of waves
* Default: 6
*/
@IBInspectable open var numberOfWaves:Int = 6
/*
* Color to use when drawing the waves
* Default: white
*/
@IBInspectable open var waveColor:UIColor = UIColor.white
/*
* The current amplitude.
*/
@IBInspectable open var amplitude:CGFloat = 1.0 {
didSet {
amplitude = max(amplitude, self.idleAmplitude)
self.setNeedsDisplay()
}
}
fileprivate var phase:CGFloat = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func draw(_ rect: CGRect) {
// Convenience function to draw the wave
func drawWave(_ index:Int, maxAmplitude:CGFloat, normedAmplitude:CGFloat) {
let path = UIBezierPath()
let mid = self.bounds.width/2.0
path.lineWidth = index == 0 ? self.primaryLineWidth : self.secondaryLineWidth
for x in Swift.stride(from:0, to:self.bounds.width + self.density, by:self.density) {
// Parabolic scaling
let scaling = -pow(1 / mid * (x - mid), 2) + 1
let y = scaling * maxAmplitude * normedAmplitude * sin(CGFloat(2 * Double.pi) * self.frequency * (x / self.bounds.width) + self.phase) + self.bounds.height/2.0
if x == 0 {
path.move(to: CGPoint(x:x, y:y))
} else {
path.addLine(to: CGPoint(x:x, y:y))
}
}
path.stroke()
}
let context = UIGraphicsGetCurrentContext()
context?.setAllowsAntialiasing(true)
self.backgroundColor?.set()
context?.fill(rect)
let halfHeight = self.bounds.height / 2.0
let maxAmplitude = halfHeight - self.primaryLineWidth
for i in 0 ..< self.numberOfWaves {
let progress = 1.0 - CGFloat(i) / CGFloat(self.numberOfWaves)
let normedAmplitude = (1.5 * progress - 0.8) * self.amplitude
let multiplier = min(1.0, (progress/3.0*2.0) + (1.0/3.0))
self.waveColor.withAlphaComponent(multiplier * self.waveColor.cgColor.alpha).set()
drawWave(i, maxAmplitude: maxAmplitude, normedAmplitude: normedAmplitude)
}
self.phase += self.phaseShift
}
}
|
gpl-3.0
|
a19c5a7c5b7358153a277cae20d62570
| 29.976 | 176 | 0.586519 | 4.172414 | false | false | false | false |
adyrda2/Exercism.io
|
swift/word-count/WordCount.swift
|
1
|
668
|
import Foundation
class WordCount {
let words: String
init(words: String) {
self.words = words.lowercaseString
}
func count() -> [String: Int] {
let arrayOfWords = words.componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet).filter({ $0.isEmpty == false })
var dictionaryOfWords = [String: Int]()
for word in arrayOfWords {
if let count = dictionaryOfWords[word] {
dictionaryOfWords[word] = count + 1
} else {
dictionaryOfWords[word] = 1
}
}
return dictionaryOfWords
}
}
|
mit
|
aeac1e55f43b079140afaab499565001
| 26.875 | 156 | 0.579341 | 5.21875 | false | false | false | false |
zisko/swift
|
test/Serialization/noinline.swift
|
1
|
1342
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_noinline.swift
// RUN: llvm-bcanalyzer %t/def_noinline.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -sil-link-all -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_noinline
// SIL-LABEL: sil @main
// SIL: [[RAW:%.+]] = global_addr @$S8noinline3rawSbvp : $*Bool
// SIL: [[FUNC:%.+]] = function_ref @$S12def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool
// SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
var raw = testNoinline(x: false)
// SIL: [[FUNC2:%.+]] = function_ref @$S12def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
// SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
var a = NoInlineInitStruct(x: false)
// SIL-LABEL: [serialized] [noinline] @$S12def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool
// SIL-LABEL: sil public_external [serialized] [noinline] @$S12def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct {
|
apache-2.0
|
380d70bb59bd57b9668945ee4cee9d61
| 54.916667 | 192 | 0.685544 | 3.330025 | false | true | false | false |
SomeHero/iShopAwayAPIManager
|
IShopAwayApiManager/Classes/models/PaymentMethod.swift
|
1
|
1166
|
//
// PaymentMethod.swift
// Pods
//
// Created by James Rhodes on 6/21/16.
//
//
import Foundation
import ObjectMapper
public class PaymentMethod: Mappable {
public var id: String!
public var type: String!
public var cardType: String!
public var cardLastFour: String!
public var expirationMonth: Int!
public var expirationYear: Int!
public var isDefault: Bool = false
public init(type: String, cardType: String, cardLastFour: String, expirationMonth: Int, expirationYear: Int, isDefault: Bool) {
self.type = type
self.cardType = cardType
self.cardLastFour = cardLastFour
self.expirationMonth = expirationMonth
self.expirationYear = expirationYear
}
public required init?(_ map: Map){
mapping(map)
}
public func mapping(map: Map) {
id <- map["_id"]
type <- map["type"]
cardType <- map["card_info.card_type"]
cardLastFour <- map["card_info.card_last_four"]
expirationMonth <- map["card_info.expiration_month"]
expirationYear <- map["card_info.expiration_year"]
isDefault <- map["is_default"]
}
}
|
mit
|
3076e0705968379d9799489266be1f04
| 27.439024 | 131 | 0.638937 | 4.24 | false | false | false | false |
ddstone/4ddcmj
|
AmateurTimeRecoder/MDRotatingPieChart.swift
|
1
|
20216
|
//
// MDRotatingPieChart.swift
// MDRotatingPieChart
//
// Created by Maxime DAVID on 2015-04-03.
// Copyright (c) 2015 Maxime DAVID. All rights reserved.
//
import UIKit
import QuartzCore
/**
* DataSource : all methods are mandatory to build the pie chart
*/
protocol MDRotatingPieChartDataSource {
/**
Gets slice color
:param: index slice index in your data array
:returns: the color of the slice at the given index
*/
func colorForSliceAtIndex(index:Int) -> UIColor
/**
Gets slice value
:param: index slice index in your data array
:returns: the value of the slice at the given index
*/
func valueForSliceAtIndex(index:Int) -> CGFloat
/**
Gets slice label
:param: index slice index in your data array
:returns: the label of the slice at the given index
*/
func labelForSliceAtIndex(index:Int) -> String
/**
Gets number of slices
:param: index slice index in your data array
:returns: the number of slices
*/
func numberOfSlices() -> Int
}
/**
* Delegate : all methods are optional
*/
@objc protocol MDRotatingPieChartDelegate {
/**
Triggered when a slice is going to be opened
:param: index slice index in your data array
*/
optional func willOpenSliceAtIndex(index:Int)
/**
Triggered when a slice is going to be closed
:param: index slice index in your data array
*/
optional func willCloseSliceAtIndex(index:Int)
/**
Triggered when a slice has just finished opening
:param: index slice index in your data array
*/
optional func didOpenSliceAtIndex(index:Int)
/**
Triggered when a slice has just finished closing
:param: index slice index in your data array
*/
optional func didCloseSliceAtIndex(index:Int)
}
/**
* Properties, to customize your pie chart (actually this is not mandatory to use this structure since all values have a default behaviour)
*/
struct Properties {
//smallest of both radius
var smallRadius:CGFloat = 50
//biggest of both radius
var bigRadius:CGFloat = 120
//value of the translation when a slice is openned
var expand:CGFloat = 25
//label format in slices
var displayValueTypeInSlices:DisplayValueType = .Percent
//label format in center
var displayValueTypeCenter:DisplayValueType = .Label
//font to use in slices
var fontTextInSlices:UIFont = UIFont(name: "Arial", size: 12)!
//font to use in the center
var fontTextCenter:UIFont = UIFont(name: "Arial", size: 10)!
//tells whether or not the pie should be animated
var enableAnimation = true
//if so, this describes the duration of the animation
var animationDuration:CFTimeInterval = 0.5
//number formatter to use
var nf = NSNumberFormatter()
init() {
nf.groupingSize = 3
nf.maximumSignificantDigits = 3
nf.minimumSignificantDigits = 3
}
}
class MDRotatingPieChart: UIControl {
//stores the slices
var slicesArray:Array<Slice> = Array<Slice>()
var delta:CGFloat = 0
//properties configuration
var properties = Properties()
//datasource and delegate
var datasource:MDRotatingPieChartDataSource!
var delegate:MDRotatingPieChartDelegate!
//tells whether or not a drag action has been done, is so, do not open or close a slice
var hasBeenDraged:Bool = false
//saves the previous transfomation
var oldTransform:CATransform3D?
//saves the selected slice index
var currentSelected:Int = -1
//label
var labelCenter:UILabel = UILabel()
//saves the center of the pie chart
var pieChartCenter:CGPoint = CGPointZero
//current slice translation
var currentTr:CGPoint = CGPointZero
override init(frame: CGRect) {
super.init(frame: frame)
//saves the center (since the frame will change after some rotations)
pieChartCenter.x = frame.width/2
pieChartCenter.y = frame.height/2
//builds and adds the centered label
labelCenter.frame = CGRectZero
labelCenter.center = CGPointMake(pieChartCenter.x, pieChartCenter.y)
labelCenter.textColor = UIColor.blackColor()
labelCenter.textAlignment = NSTextAlignment.Center
addSubview(labelCenter)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
/**
Resets the pie chart
*/
func reset() {
self.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0)
labelCenter.transform = self.transform
labelCenter.text = ""
for currentShape in slicesArray {
currentShape.shapeLayer.removeFromSuperlayer()
}
slicesArray.removeAll(keepCapacity: false)
}
/**
Contructs the pie chart
*/
func build() {
if(datasource == nil) {
print("Did you forget to set your datasource ?")
return
}
reset()
let total = computeTotal()
var currentStartAngle:CGFloat = 0
var angleSum:CGFloat = 0
if let ds = datasource {
for index in 0..<ds.numberOfSlices() {
prepareSlice(&angleSum, currentStartAngle: ¤tStartAngle, total: total, index: index)
}
}
}
/**
Prepares the slice and adds it to the pie chart
:param: angleSum sum of already prepared slices
:param: currentStartAngle start angle
:param: total total value of the pie chart
:param: index slice index
*/
func prepareSlice(inout angleSum:CGFloat, inout currentStartAngle:CGFloat, total:CGFloat, index:Int) {
let currentValue = datasource.valueForSliceAtIndex(index)
let currentAngle = currentValue * 2 * CGFloat(M_PI) / total
let currentColor = datasource.colorForSliceAtIndex(index)
let currentLabel = datasource.labelForSliceAtIndex(index)
//create slice
let slice = createSlice(currentStartAngle, end: CGFloat(currentStartAngle - currentAngle), color:currentColor, label:currentLabel, value:currentValue, percent:100 * currentValue/total)
slicesArray.append(slice)
//create label
let label = createLabel(angleSum + slice.angle/2, slice: slice)
//populate slicesArray
slicesArray[index].labelObj = label
slicesArray[index].shapeLayer.addSublayer(label.layer)
angleSum += slice.angle
self.layer.insertSublayer(slice.shapeLayer, atIndex:0)
currentStartAngle -= currentAngle
if(properties.enableAnimation) {
addAnimation(slice)
}
}
/**
Retrieves the middle point of a slice (to set the label)
:param: angleSum sum of already prepared slices
:returns: the middle point
*/
func getMiddlePoint(angleSum:CGFloat) -> CGPoint {
let middleRadiusX = properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2
let middleRadiusY = properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2
return CGPointMake(
cos(angleSum) * middleRadiusX + pieChartCenter.x,
sin(angleSum) * middleRadiusY + pieChartCenter.y
)
}
/**
Creates the label
:param: angleSum sum of already prepared slices
:param: slice the slice
:returns: a new label
*/
func createLabel(angleSum:CGFloat, slice:Slice) -> UILabel {
let label = UILabel(frame: CGRectZero)
label.center = getMiddlePoint(angleSum)
label.textAlignment = NSTextAlignment.Center
label.textColor = UIColor.blackColor()
label.font = properties.fontTextInSlices
label.text = formatFromDisplayValueType(slice, displayType: properties.displayValueTypeInSlices)
let tmpCenter = label.center
label.sizeToFit()
label.center = tmpCenter
label.hidden = !frameFitInPath(label.frame, path: slice.paths.bezierPath, inside:true)
return label;
}
/**
Adds an animation to a slice
:param: slice the slice to be animated
*/
func addAnimation(slice:Slice) {
let animateStrokeEnd = CABasicAnimation(keyPath: "strokeEnd")
animateStrokeEnd.duration = properties.animationDuration
animateStrokeEnd.fromValue = 0.0
animateStrokeEnd.toValue = 1.0
slice.shapeLayer.addAnimation(animateStrokeEnd, forKey: "animate stroke end animation")
CATransaction.commit()
}
/**
Computes the total value of slices
:returns: the total value
*/
func computeTotal() -> CGFloat {
var total:CGFloat = 0
for index in 0 ..< datasource.numberOfSlices() {
total = total + datasource.valueForSliceAtIndex(index)
}
return total;
}
/**
Closes a slice
*/
func closeSlice() {
delegate?.willCloseSliceAtIndex!(currentSelected)
slicesArray[currentSelected].shapeLayer.transform = oldTransform!
delegate?.didCloseSliceAtIndex!(currentSelected)
labelCenter.text = ""
}
/**
Opens a slice
:param: index the slice index in the data array
*/
func openSlice(index:Int) {
//save the transformation
oldTransform = slicesArray[index].shapeLayer.transform
//update the label
labelCenter.text = formatFromDisplayValueType(slicesArray[index], displayType: properties.displayValueTypeCenter)
let centerTmp = labelCenter.center
labelCenter.sizeToFit()
labelCenter.center = centerTmp
labelCenter.hidden = false
if let ds = datasource {
for cpt in 0..<ds.numberOfSlices() {
if (!frameFitInPath(labelCenter.frame, path: slicesArray[cpt].paths.bezierPath, inside: false)) {
labelCenter.hidden = true
}
}
}
//move
var angleSum:CGFloat = 0
for i in 0..<index {
angleSum += slicesArray[i].angle
}
angleSum += slicesArray[index].angle/2.0
let transX:CGFloat = properties.expand*cos(angleSum)
let transY:CGFloat = properties.expand*sin(angleSum)
let translate = CATransform3DMakeTranslation(transX, transY, 0);
currentTr = CGPointMake(-transX, -transY)
delegate?.willOpenSliceAtIndex!(index)
slicesArray[index].shapeLayer.transform = translate
delegate?.didOpenSliceAtIndex!(index)
currentSelected = index
}
/**
Computes the logic of opening/closing slices
:param: index the slice index
*/
func openCloseSlice(index:Int) {
// nothing is opened, let's opened one slice
if(currentSelected == -1) {
openSlice(index)
}
// here a slice is opened, so let's close it before
else {
closeSlice()
//if the same slice is chosen, no need to open
if(currentSelected == index) {
currentSelected = -1
}
else {
openSlice(index)
}
}
}
//UIControl implementation
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
//makes sure to reset the drag event
hasBeenDraged = false
let currentPoint = touch.locationInView(self)
if ignoreThisTap(currentPoint) {
return false;
}
let deltaX = currentPoint.x - pieChartCenter.x
let deltaY = currentPoint.y - pieChartCenter.y
delta = atan2(deltaY,deltaX)
return true
}
//UIControl implementation
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
//drag event detected, we won't open/close any slices
hasBeenDraged = true
let currentPoint = touch.locationInView(self)
let deltaX = currentPoint.x - pieChartCenter.x
let deltaY = currentPoint.y - pieChartCenter.y
let ang = atan2(deltaY,deltaX);
let angleDifference = delta - ang
//rotate !
self.transform = CGAffineTransformRotate(self.transform, -angleDifference)
//reset labels
let savedTransform = slicesArray[0].labelObj?.transform
let savedTransformCenter = labelCenter.transform
for slice in slicesArray {
if(slice.labelObj != nil) {
slice.labelObj?.transform = CGAffineTransformRotate(savedTransform!, angleDifference)
}
}
labelCenter.transform = CGAffineTransformRotate(savedTransformCenter, angleDifference)
return true;
}
//UIControl implementation
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
//don't open/close slice if a drag event has been detected
if(hasBeenDraged) {
return
}
let currentPoint = touch!.locationInView(self)
var cpt = 0
for currentPath in slicesArray {
//click on a slice
if currentPath.paths.bezierPath.containsPoint(currentPoint) {
openCloseSlice(cpt)
return
}
//click on the current opened slice
if currentPath.paths.bezierPath.containsPoint(CGPointMake(currentPoint.x+currentTr.x, currentPoint.y+currentTr.y)) && cpt == currentSelected {
openCloseSlice(cpt)
return
}
cpt += 1
}
}
/**
Checks whether or not a tap shoud be dismissed (too close from the center or too far)
:param: currentPoint current tapped point
:returns: true if it should be ignored, false otherwise
*/
func ignoreThisTap(currentPoint:CGPoint) -> Bool {
let dx = currentPoint.x - pieChartCenter.x
let dy = currentPoint.y - pieChartCenter.y
let sqroot = sqrt(dx*dx + dy*dy)
return sqroot < properties.smallRadius || sqroot > (properties.bigRadius + properties.expand + (properties.bigRadius-properties.smallRadius)/2)
}
/**
Creates a slice
:param: start start angle
:param: end end angle
:param: color color
:param: label label
:param: value value
:param: percent percent value
:returns: a new slice
*/
func createSlice(start:CGFloat, end:CGFloat, color:UIColor, label:String, value:CGFloat, percent:CGFloat) -> Slice {
let mask = CAShapeLayer()
mask.frame = self.frame
let path = computeDualPath(start, end: end)
mask.path = path.animationBezierPath.CGPath
mask.lineWidth = properties.bigRadius - properties.smallRadius
mask.strokeColor = color.CGColor
mask.fillColor = color.CGColor
let slice = Slice(myPaths: path, myShapeLayer: mask, myAngle: end-start, myLabel:label, myValue:value, myPercent:percent)
return slice;
}
/**
Formats the text
:param: slice a slice
:param: displayType an enum representing a display value type
:returns: a formated text ready to be displayed
*/
func formatFromDisplayValueType(slice:Slice, displayType:DisplayValueType) -> String {
var toRet = ""
switch(displayType) {
case .Value :
toRet = properties.nf.stringFromNumber(slice.value)!
break
case .Percent :
toRet = (properties.nf.stringFromNumber(slice.percent)?.stringByAppendingString("%"))!
break
case .Label :
toRet = slice.label
break
}
return toRet;
}
/**
Computes and returns a path representing a slice
:param: start start angle
:param: end end angle
:returns: the UIBezierPath build
*/
func computeAnimationPath(start:CGFloat, end:CGFloat) -> UIBezierPath {
let animationPath = UIBezierPath()
animationPath.moveToPoint(getMiddlePoint(start))
animationPath.addArcWithCenter(pieChartCenter, radius: (properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2), startAngle: start, endAngle: end, clockwise: false)
animationPath.addArcWithCenter(pieChartCenter, radius: (properties.smallRadius + (properties.bigRadius-properties.smallRadius)/2), startAngle: end, endAngle: start, clockwise: true)
return animationPath;
}
/**
Computes and returns a pair of UIBezierPaths
:param: start start angle
:param: end end angle
:returns: the pair
*/
func computeDualPath(start:CGFloat, end:CGFloat) -> DualPath {
let pathRef = computeAnimationPath(start, end: end)
// let other = CGPathCreateCopyByStrokingPath(pathRef.CGPath, nil, properties.bigRadius-properties.smallRadius, kCGLineCapButt, kCGLineJoinMiter, 1)
let other = CGPathCreateCopyByStrokingPath(pathRef.CGPath, nil, properties.bigRadius-properties.smallRadius, .Butt, .Miter, 1)
let ok = UIBezierPath(CGPath: other!)
return DualPath(myBezierPath: ok, myAnimationBezierPath: pathRef)
}
/**
Tells whether or not the given frame is overlapping with a shape (delimited by an UIBeizerPath)
:param: frame the frame
:param: path the path
:param: inside tells whether or not the path should be inside the path
:returns: true if it fits, false otherwise
*/
func frameFitInPath(frame:CGRect, path:UIBezierPath, inside:Bool) -> Bool {
let topLeftPoint = frame.origin
let topRightPoint = CGPointMake(frame.origin.x + frame.width, frame.origin.y)
let bottomLeftPoint = CGPointMake(frame.origin.x, frame.origin.y + frame.height)
let bottomRightPoint = CGPointMake(frame.origin.x + frame.width, frame.origin.y + frame.height)
if(inside) {
if(!path.containsPoint(topLeftPoint)
|| !path.containsPoint(topRightPoint)
|| !path.containsPoint(bottomLeftPoint)
|| !path.containsPoint(bottomRightPoint)) {
return false
}
}
if(!inside) {
if(path.containsPoint(topLeftPoint)
|| path.containsPoint(topRightPoint)
|| path.containsPoint(bottomLeftPoint)
|| path.containsPoint(bottomRightPoint)) {
return false
}
}
return true
}
}
/**
* Stores both BezierPaths, one for the animation and the "real one"
*/
struct DualPath {
var bezierPath:UIBezierPath
var animationBezierPath:UIBezierPath
init(myBezierPath:UIBezierPath, myAnimationBezierPath:UIBezierPath) {
self.bezierPath = myBezierPath
self.animationBezierPath = myAnimationBezierPath
}
}
/**
* Stores a slice
*/
struct Slice {
var paths:DualPath
var shapeLayer:CAShapeLayer
var angle:CGFloat
var label:String
var value:CGFloat
var labelObj:UILabel?
var percent:CGFloat
init(myPaths:DualPath, myShapeLayer:CAShapeLayer, myAngle:CGFloat, myLabel:String, myValue:CGFloat, myPercent:CGFloat) {
self.paths = myPaths
self.shapeLayer = myShapeLayer
self.angle = myAngle
self.label = myLabel
self.value = myValue
self.percent = myPercent
}
}
/**
Helper enum to format the labels
- Percent: the percent value
- Value: the raw value
- Label: the description
*/
enum DisplayValueType {
case Percent
case Value
case Label
}
|
gpl-3.0
|
9d430355853c6761356d1da848ffd4d3
| 29.676783 | 192 | 0.62317 | 4.784852 | false | false | false | false |
google/flatbuffers
|
swift/Sources/FlatBuffers/String+extension.swift
|
4
|
3294
|
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
extension String: Verifiable {
/// Verifies that the current value is which the bounds of the buffer, and if
/// the current `Value` is aligned properly
/// - Parameters:
/// - verifier: Verifier that hosts the buffer
/// - position: Current position within the buffer
/// - type: The type of the object to be verified
/// - Throws: Errors coming from `inBuffer`, `missingNullTerminator` and `outOfBounds`
public static func verify<T>(
_ verifier: inout Verifier,
at position: Int,
of type: T.Type) throws where T: Verifiable
{
let range = try String.verifyRange(&verifier, at: position, of: UInt8.self)
/// Safe &+ since we already check for overflow in verify range
let stringLen = range.start &+ range.count
if stringLen >= verifier.capacity {
throw FlatbuffersErrors.outOfBounds(
position: UInt(clamping: stringLen.magnitude),
end: verifier.capacity)
}
let isNullTerminated = verifier._buffer.read(
def: UInt8.self,
position: stringLen) == 0
if !verifier._options._ignoreMissingNullTerminators && !isNullTerminated {
let str = verifier._buffer.readString(at: range.start, count: range.count)
throw FlatbuffersErrors.missingNullTerminator(
position: position,
str: str)
}
}
}
extension String: FlatbuffersInitializable {
/// Initailizes a string from a Flatbuffers ByteBuffer
/// - Parameters:
/// - bb: ByteBuffer containing the readable string
/// - o: Current position
public init(_ bb: ByteBuffer, o: Int32) {
let v = Int(o)
let count = bb.read(def: Int32.self, position: v)
self = bb.readString(
at: MemoryLayout<Int32>.size + v,
count: Int(count)) ?? ""
}
}
extension String: ObjectAPIPacker {
public static func pack(
_ builder: inout FlatBufferBuilder,
obj: inout String?) -> Offset
{
guard var obj = obj else { return Offset() }
return pack(&builder, obj: &obj)
}
public static func pack(
_ builder: inout FlatBufferBuilder,
obj: inout String) -> Offset
{
builder.create(string: obj)
}
public mutating func unpack() -> String {
self
}
}
extension String: NativeObject {
public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
where T.T == Self
{
fatalError("serialize should never be called from string directly")
}
public func serialize<T: ObjectAPIPacker>(
builder: inout FlatBufferBuilder,
type: T.Type) -> ByteBuffer where T.T == Self
{
fatalError("serialize should never be called from string directly")
}
}
|
apache-2.0
|
f7a103fedf5ece205c80c8409d210788
| 28.150442 | 88 | 0.682453 | 4.107232 | false | false | false | false |
yakirlee/TwitterDemo
|
TwitterDemo/TwitterDemo/TableViewCell.swift
|
1
|
1724
|
//
// TableViewCell.swift
// TwitterDemo
//
// Created by 李 on 16/4/24.
// Copyright © 2016年 李. All rights reserved.
//
import UIKit
import SnapKit
private let margin = 10.0
class TableViewCell: UITableViewCell {
var user: User? {
didSet {
statusView.user = user
actionView.user = user
}
}
// MARK: - 私有控件
private lazy var statusView = CellStatusView(frame: CGRectZero)
private lazy var actionView = CellActionsView(frame: CGRectZero)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI设计
extension TableViewCell {
func setupUI() {
contentView.addSubview(statusView)
contentView.addSubview(actionView)
statusView.snp_makeConstraints { (make) in
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.top.equalTo(contentView)
}
actionView.snp_makeConstraints { (make) in
make.left.equalTo(statusView).offset(8 * margin)
make.top.equalTo(statusView.snp_bottom).offset(margin)
make.right.equalTo(statusView)
make.bottom.equalTo(contentView)
}
actionView.userInteractionEnabled = true
// 性能调优 关键 异步绘制栅格化
layer.drawsAsynchronously = true
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
}
}
|
mit
|
0eb59f78e2578cba5d5a89b84e1dbec1
| 26.52459 | 74 | 0.620012 | 4.6 | false | false | false | false |
ashfurrow/eidolon
|
Kiosk/Bid Fulfillment/StripeManager.swift
|
2
|
2183
|
import Foundation
import RxSwift
import Stripe
protocol Tokenable {
var tokenId: String { get }
var creditCard: CreditCard? { get }
}
extension STPToken: Tokenable {
var creditCard: CreditCard? {
return self.card
}
}
protocol Clientable {
func kiosk_createToken(withCard card: STPCardParams, completion: ((Tokenable?, Error?) -> Void)?)
}
extension STPAPIClient: Clientable {
func kiosk_createToken(withCard card: STPCardParams, completion: ((Tokenable?, Error?) -> Void)?) {
self.createToken(withCard: card) { (token, error) in
completion?(token, error)
}
}
}
class StripeManager: NSObject {
var stripeClient: Clientable = STPAPIClient.shared()
func registerCard(digits: String, month: UInt, year: UInt, securityCode: String, postalCode: String) -> Observable<Tokenable> {
let card = STPCardParams()
card.number = digits
card.expMonth = month
card.expYear = year
card.cvc = securityCode
card.address.postalCode = postalCode
return Observable.create { [weak self] observer in
guard let me = self else {
observer.onCompleted()
return Disposables.create()
}
me.stripeClient.kiosk_createToken(withCard: card) { (token, error) in
if let token = token {
observer.onNext(token)
observer.onCompleted()
} else {
observer.onError(error!)
}
}
return Disposables.create()
}
}
func stringIsCreditCard(_ cardNumber: String) -> Bool {
return validateCreditCardNumber(cardNumber)
}
}
extension STPCardBrand {
var name: String? {
switch self {
case .visa:
return "Visa"
case .amex:
return "American Express"
case .masterCard:
return "MasterCard"
case .discover:
return "Discover"
case .JCB:
return "JCB"
case .dinersClub:
return "Diners Club"
default:
return nil
}
}
}
|
mit
|
5488bbf3f7b809d25acfa8bf623a90d2
| 25.950617 | 131 | 0.572607 | 4.684549 | false | false | false | false |
tonyqiu1019/tsoc
|
ios/Smashtag/Smashtag/TweetTableViewCell.swift
|
1
|
2508
|
//
// TweetTableViewCell.swift
// Smashtag
//
// Created by Tong Qiu on 8/16/17.
// Copyright © 2017 Tong Qiu. All rights reserved.
//
import UIKit
import Twitter
class TweetTableViewCell: UITableViewCell {
@IBOutlet weak var tweetProfileImageView: UIImageView!
@IBOutlet weak var tweetUserLabel: UILabel!
@IBOutlet weak var tweetCreatedLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
var tweet: Twitter.Tweet? { didSet { updateUI() } }
// MARK: - Private implementation
private final let hashtagColor = UIColor.blue
private final let userMentionColor = UIColor.orange
private final let urlColor = UIColor.brown
private func updateUI() {
if let existingTweet = tweet {
let colorString = NSMutableAttributedString(string: existingTweet.text)
for hashtag in existingTweet.hashtags {
colorString.addAttribute(NSForegroundColorAttributeName, value: hashtagColor, range: hashtag.nsrange)
}
for userMention in existingTweet.userMentions {
colorString.addAttribute(NSForegroundColorAttributeName, value: userMentionColor, range: userMention.nsrange)
}
for url in existingTweet.urls {
colorString.addAttribute(NSForegroundColorAttributeName, value: urlColor, range: url.nsrange)
}
tweetTextLabel?.attributedText = colorString
}
tweetUserLabel?.text = tweet?.user.description
if let url = tweet?.user.profileImageURL {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
let urlContents = try? Data(contentsOf: url)
if let imageData = urlContents, url == self?.tweet?.user.profileImageURL {
DispatchQueue.main.async {
self?.tweetProfileImageView?.image = UIImage(data: imageData)
}
}
}
} else {
tweetProfileImageView?.image = nil
}
if let created = tweet?.created {
let formatter = DateFormatter()
if Date().timeIntervalSince(created) > 24*60*60 {
formatter.dateStyle = .short
} else {
formatter.timeStyle = .short
}
tweetCreatedLabel?.text = formatter.string(from: created)
} else {
tweetCreatedLabel?.text = nil
}
}
}
|
mit
|
47dbcacfd9957599c1b949d425eaab4b
| 34.814286 | 125 | 0.606701 | 5.356838 | false | false | false | false |
wbaumann/SmartReceiptsiOS
|
SmartReceipts/Extensions/DateFormatter+Extensions.swift
|
2
|
931
|
//
// DateFormatter+Extensions.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 03/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
extension DateFormatter {
func configure(format: String, timeZone: TimeZone = TimeZone.current) {
self.timeZone = timeZone
self.dateFormat = format
}
func configure(timeZone: TimeZone = TimeZone.current) {
configure(format: WBPreferences.dateFormat(), timeZone: timeZone)
}
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
func addWeekdayFormat() {
dateFormat = "EEE, " + dateFormat
}
}
|
agpl-3.0
|
b0c279965cf5f80cbae85a620164396b
| 29 | 75 | 0.651613 | 4.366197 | false | true | false | false |
CanyFrog/HCComponent
|
HCSource/HCRuntime.swift
|
1
|
2264
|
//
// HCRuntime.swift
// HCComponents
//
// Created by Magee Huang on 4/14/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
import ObjectiveC.runtime
/**
Gets the Obj-C reference for the instance object within the UIView extension.
- Parameter base: Base object.
- Parameter key: Memory key pointer.
- Parameter initializer: Object initializer.
- Returns: The associated reference for the initializer object.
*/
internal func AssociatedObject<T: Any>(base: Any, key: UnsafePointer<UInt8>, initializer: () -> T) -> T {
if let v = objc_getAssociatedObject(base, key) as? T {
return v
}
let v = initializer()
objc_setAssociatedObject(base, key, v, .OBJC_ASSOCIATION_RETAIN)
return v
}
/**
Sets the Obj-C reference for the instance object within the UIView extension.
- Parameter base: Base object.
- Parameter key: Memory key pointer.
- Parameter value: The object instance to set for the associated object.
- Returns: The associated reference for the initializer object.
*/
internal func AssociateObject<T: Any>(base: Any, key: UnsafePointer<UInt8>, value: T) {
objc_setAssociatedObject(base, key, value, .OBJC_ASSOCIATION_RETAIN)
}
public protocol HCObjectConvertProtocol: class {
var propertyList: [String]? { get }
func toDictionary() -> [String: Any]?
}
extension HCObjectConvertProtocol where Self: NSObject {
public var propertyList: [String]? {
var count: UInt32 = 0
guard let properties = class_copyPropertyList(self.classForCoder , &count) else {
return nil
}
var results = [String]()
for i in 0 ..< count {
let property = properties[Int(i)]
let cname = property_getName(property)
//convert the c string into a Swift string
let name = String.init(cString: cname!)
results.append(name)
}
return results
}
public func toDictionary() -> [String: Any]? {
guard let list = propertyList else { return nil }
return list.reduce([String: Any]()) { (result, property) -> [String: Any] in
var res = result
res[property] = value(forKeyPath: property)
return res
}
}
}
|
mit
|
1eba9989d61278a8b2bca2fd9bb61689
| 30.873239 | 105 | 0.646045 | 4.269811 | false | false | false | false |
cristianames/shopping-tracker
|
shopping-tracker/UIComponent/MyItems/MyItemsViewController.swift
|
1
|
1282
|
//
// MyItemsViewController.swift
// shopping-tracker
//
// Created by Cristian Ames on 2/13/17.
// Copyright © 2017 Cristian Ames. All rights reserved.
//
import UIKit
class MyItemsViewController: ViewController {
private var _viewModel: MyItemsViewModel { return viewModel as! MyItemsViewModel }
private var _view: MyItemsView { return view as! MyItemsView }
public override func loadView() {
view = MyItemsView.loadFromNib()
let tableView = UITableView(frame: _view.tableView.frame)
tableView.delegate = self
tableView.loadInto(_view.tableView)
}
override func viewDidLoad() {
super.viewDidLoad()
_view.tableView.reloadInputViews()
// Do any additional setup after loading the view.
}
}
extension MyItemsViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
@nonobjc public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: .none)
cell.detailTextLabel?.text = "HOLA \(indexPath.row)"
return cell
}
}
|
mit
|
65074e7dfb3742f1a4d5c96688a8153a
| 28.790698 | 116 | 0.683841 | 4.744444 | false | false | false | false |
nmdias/FeedKit
|
Sources/FeedKit/Models/Atom/AtomFeedCategory.swift
|
2
|
3582
|
//
// AtomFeedCategory.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// The "atom:category" element conveys information about a category
/// associated with an entry or feed. This specification assigns no
/// meaning to the content (if any) of this element.
public class AtomFeedCategory {
/// The element's attributes.
public class Attributes {
/// The "term" attribute is a string that identifies the category to
/// which the entry or feed belongs. Category elements MUST have a
/// "term" attribute.
public var term: String?
/// The "scheme" attribute is an IRI that identifies a categorization
/// scheme. Category elements MAY have a "scheme" attribute.
public var scheme: String?
/// The "label" attribute provides a human-readable label for display in
/// end-user applications. The content of the "label" attribute is
/// Language-Sensitive. Entities such as "&" and "<" represent
/// their corresponding characters ("&" and "<", respectively), not
/// markup. Category elements MAY have a "label" attribute.
public var label: String?
}
/// The element's attributes.
public var attributes: Attributes?
public init() { }
}
// MARK: - Initializers
extension AtomFeedCategory {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = AtomFeedCategory.Attributes(attributes: attributeDict)
}
}
extension AtomFeedCategory.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.term = attributeDict["term"]
self.scheme = attributeDict["scheme"]
self.label = attributeDict["label"]
}
}
// MARK: - Equatable
extension AtomFeedCategory: Equatable {
public static func ==(lhs: AtomFeedCategory, rhs: AtomFeedCategory) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension AtomFeedCategory.Attributes: Equatable {
public static func ==(lhs: AtomFeedCategory.Attributes, rhs: AtomFeedCategory.Attributes) -> Bool {
return
lhs.term == rhs.term &&
lhs.scheme == rhs.scheme &&
lhs.label == rhs.label
}
}
|
mit
|
fd1debd2ea8ca565044c8f14cf621d49
| 31.862385 | 103 | 0.660804 | 4.719368 | false | false | false | false |
antlr/grammars-v4
|
swift/swift2/examples/test9.swift
|
2
|
5041
|
class TestClass {
var x = 0.0, y = 0.0
// Subscript Syntax
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
// Closure Expression Syntax
var reversed = names.sort({ (s1: String, s2: String) -> Bool in
return s1 > s2
})
func backwards(s1: String, _ s2: String) -> Bool {
return s1 > s2
}
// Inferring Type From Context
var reversed = names.sort( { s1, s2 in return s1 > s2 } )
// Implicit Returns from Single-Expression Closures
var reversed = names.sort( { s1, s2 in s1 > s2 } )
// Shorthand Argument Names
var reversed = names.sort( { $0 > $1 } )
let strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
// Capturing Values
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
// Nonescaping Closures
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: () -> Void) {
completionHandlers.append(completionHandler)
}
// Generic Functions
func swapTwoValues<T>(inout a: T, inout _ b: T) {
let temporaryA = a
a = b
b = temporaryA
}
// Calling generic functions with parameters
var someInt = 3
var anotherInt = 107
func foo() { swapTwoValues(&someInt, &anotherInt) }
// someInt is now 107, and anotherInt is now 3
var someString = "hello"
var anotherString = "world"
// Type Constraint Syntax
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
// Type constraints in action
func findStringIndex(array: [String], _ valueToFind: String) -> Int? {
for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
}
return nil
}
func findIndex<T>(array: [T], _ valueToFind: T) -> Int? {
for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
}
return nil
}
// Where clauses
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, _ anotherContainer: C2) -> Bool {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
// Bitwise NOT Operator
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
// Bitwise AND Operator
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // equals 00111100
// Bitwise OR Operator
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // equals 11111110
// Bitwise XOR Operator
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // equals 00010001
// Shifting Behavior for Unsigned Integers
let shiftBits: UInt8 = 4 // 00000100 in binary
func foo() {
shiftBits << 1 // 00001000
shiftBits << 2 // 00010000
shiftBits << 5 // 10000000
shiftBits << 6 // 00000000
shiftBits >> 2 // 00000001
}
// Overflow Operators
var unsignedOverflow = UInt8.max
// unsignedOverflow equals 255, which is the maximum value a UInt8 can hold
func foo() {
unsignedOverflow = unsignedOverflow &+ 1
// unsignedOverflow equals 0, which is the minimum value a UInt8 can hold
unsignedOverflow = unsignedOverflow &- 1
}
var unsignedOverflow = UInt8.min
// unsignedOverflow is now equal to 255
func precedenceAndAssociativity() -> Void {
2 + 3 % 4 * 5 // equals 17
}
// Prefix Operators
prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
// Compount assignment operators
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
}
|
mit
|
fad69e901c836b0342c255c828e5f2de
| 27.480226 | 81 | 0.575283 | 4.364502 | false | false | false | false |
syd24/DouYuZB
|
DouYu/DouYu/classes/home/view/CollectionViewNormalCell.swift
|
1
|
1295
|
//
// CollectionViewNormalCell.swift
// DouYu
//
// Created by Kobe24 on 16/10/28.
// Copyright © 2016年 ADMIN. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionViewNormalCell: UICollectionViewCell {
@IBOutlet weak var liveNum: UIButton!
@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nickNameLabel: UILabel!
var anchorModel: AnchorModel? {
didSet{
guard let anchor = anchorModel else {return;}
var onlineNum : String = "";
if anchor.online >= 10000 {
onlineNum = "\(Int(anchor.online / 10000))万在线"
}else{
onlineNum = "\(anchor.online)在线";
}
liveNum.setTitle(onlineNum, for: .normal);
titleLabel.text = anchor.room_name;
nickNameLabel.text = anchor.nickname;
let url = NSURL(string: anchor.vertical_src)
let source = ImageResource(downloadURL: url as! URL);
bgImage.kf_setImage(with: source);
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
mit
|
5c8dfeb83724aa311b63d8c3ad8d9fe5
| 25.708333 | 65 | 0.556942 | 4.856061 | false | false | false | false |
iAugux/Zoom-Contacts
|
Phonetic/Extensions/Utils.swift
|
1
|
1624
|
//
// Utils.swift
//
// Created by Augus on 11/10/15.
// Copyright © 2015 iAugus. All rights reserved.
//
import Foundation
public typealias CompletionHandler = () -> ()
class Utils {
class func documentPath() -> String {
return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
}
class func appGroupDocumentPath(appGroupId: String) -> String {
let url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(appGroupId)
let path = url!.absoluteString.stringByReplacingOccurrencesOfString("file:", withString: "", options: .LiteralSearch, range: nil)
return path
}
}
// MARK: - GCD
var GlobalMainQueue: dispatch_queue_t {
return dispatch_get_main_queue()
}
var GlobalUserInteractiveQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.rawValue), 0)
}
var GlobalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
}
var GlobalUtilityQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)
}
var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
}
// MARK: - Delay
func executeAfterDelay(seconds: Double, completion: (() -> Void)) {
let delayInSeconds: Double = seconds
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * delayInSeconds))
dispatch_after(popTime, dispatch_get_main_queue(), {
completion()
})
}
|
mit
|
97c752af1b55297c3c14456d90d303ef
| 25.622951 | 137 | 0.712877 | 4.047382 | false | false | false | false |
koher/EasyImagy
|
Sources/EasyImagy/Extrapolation.swift
|
1
|
4342
|
public enum ExtrapolationMethod<Pixel> {
case constant(Pixel)
case edge
case `repeat`
case reflection
}
private func reminder(_ a: Int, _ b: Int) -> Int {
let result = a % b
return result < 0 ? result + b : result
}
extension ImageProtocol {
public subscript(x: Int, y: Int, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> Pixel {
switch extrapolationMethod {
case .constant(let value):
return extrapolatedPixelByFillingAt(x: x, y: y, by: value)
case .edge:
return extrapolatedPixelByEdgeAt(x: x, y: y, xRange: ClosedRange(xRange), yRange: ClosedRange(yRange))
case .repeat:
return extrapolatedPixelByRepeatAt(x: x, y: y, minX: xRange.lowerBound, minY: yRange.lowerBound, width: width, height: height)
case .reflection:
let doubleWidth = width * 2
let doubleHeight = height * 2
return extrapolatedPixelByReflectionAt(
x: x,
y: y,
minX: xRange.lowerBound,
minY: yRange.lowerBound,
doubleWidth: doubleWidth,
doubleHeight: doubleHeight,
doubleWidthMinusOne: doubleWidth - 1,
doubleHeightMinusOne: doubleHeight - 1
)
}
}
@usableFromInline
internal func extrapolatedPixelByFillingAt(x: Int, y: Int, by value: Pixel) -> Pixel {
guard xRange.contains(x) && yRange.contains(y) else {
return value
}
return self[x, y]
}
@usableFromInline
internal func extrapolatedPixelByEdgeAt(x: Int, y: Int, xRange: ClosedRange<Int>, yRange: ClosedRange<Int>) -> Pixel {
return self[clamp(x, lower: xRange.lowerBound, upper: xRange.upperBound), clamp(y, lower: yRange.lowerBound, upper: yRange.upperBound)]
}
@usableFromInline
internal func extrapolatedPixelByRepeatAt(x: Int, y: Int, minX: Int, minY: Int, width: Int, height: Int) -> Pixel {
let x2 = reminder(x - minX, width) + minX
let y2 = reminder(y - minY, height) + minY
return self[x2, y2]
}
@usableFromInline
internal func extrapolatedPixelByReflectionAt(
x: Int,
y: Int,
minX: Int,
minY: Int,
doubleWidth: Int,
doubleHeight: Int,
doubleWidthMinusOne: Int,
doubleHeightMinusOne: Int
) -> Pixel {
let width = self.width
let height = self.height
let x2 = reminder(x - minX, doubleWidth)
let y2 = reminder(y - minY, doubleHeight)
let x3 = (x2 < width ? x2 : doubleWidthMinusOne - x2) + minX
let y3 = (y2 < height ? y2 : doubleHeightMinusOne - y2) + minY
return self[x3, y3]
}
}
extension ImageProtocol {
public subscript(xRange: Range<Int>, yRange: Range<Int>, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> AnyImage<Pixel> {
return ExtrapolatedImage<Self>(
image: self,
extrapolationMethod: extrapolationMethod
)[xRange, yRange]
}
public subscript<R1: RangeExpression, R2: RangeExpression>(xRange: R1, yRange: R2, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> AnyImage<Pixel> where R1.Bound == Int, R2.Bound == Int {
return self[range(from: xRange, relativeTo: self.xRange), range(from: yRange, relativeTo: self.yRange), extrapolation: extrapolationMethod]
}
public subscript<R1: RangeExpression>(xRange: R1, yRange: UnboundedRange, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> AnyImage<Pixel> where R1.Bound == Int {
return self[range(from: xRange, relativeTo: self.xRange), self.yRange, extrapolation: extrapolationMethod]
}
public subscript<R2: RangeExpression>(xRange: UnboundedRange, yRange: R2, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> AnyImage<Pixel> where R2.Bound == Int {
return self[self.xRange, range(from: yRange, relativeTo: self.yRange), extrapolation: extrapolationMethod]
}
public subscript(xRange: UnboundedRange, yRange: UnboundedRange, extrapolation extrapolationMethod: ExtrapolationMethod<Pixel>) -> AnyImage<Pixel> {
return self[self.xRange, self.yRange, extrapolation: extrapolationMethod]
}
}
|
mit
|
37c2523b98eb3756162f742c8709e82a
| 41.568627 | 209 | 0.645325 | 3.990809 | false | false | false | false |
natecook1000/swift
|
test/DebugInfo/basic.swift
|
2
|
5065
|
// A (no longer) basic test for debug info.
// --------------------------------------------------------------------
// Verify that we don't emit any debug info by default.
// RUN: %target-swift-frontend %s -emit-ir -o - \
// RUN: | %FileCheck %s --check-prefix NDEBUG
// NDEBUG-NOT: !dbg
// NDEBUG-NOT: DW_TAG
// --------------------------------------------------------------------
// Verify that we don't emit any debug info with -gnone.
// RUN: %target-swift-frontend %s -emit-ir -gnone -o - \
// RUN: | %FileCheck %s --check-prefix NDEBUG
// --------------------------------------------------------------------
// Verify that we don't emit any type info with -gline-tables-only.
// RUN: %target-swift-frontend %s -emit-ir -gline-tables-only -o - \
// RUN: | %FileCheck %s --check-prefix CHECK-LINETABLES
// CHECK: !dbg
// CHECK-LINETABLES-NOT: DW_TAG_{{.*}}variable
// CHECK-LINETABLES-NOT: DW_TAG_structure_type
// CHECK-LINETABLES-NOT: DW_TAG_basic_type
// --------------------------------------------------------------------
// Now check that we do generate line+scope info with -g.
// RUN: %target-swift-frontend %s -emit-ir -g -o - \
// RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK
// --------------------------------------------------------------------
// Currently -gdwarf-types should give the same results as -g.
// RUN: %target-swift-frontend %s -emit-ir -gdwarf-types -o - \
// RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK
// --------------------------------------------------------------------
// Verify that -g -debug-info-format=dwarf gives the same results as -g.
// RUN: %target-swift-frontend %s -emit-ir -g -debug-info-format=dwarf -o - \
// RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK
// --------------------------------------------------------------------
// RUN: %target-swift-frontend %s -emit-ir -g -debug-info-format=codeview -o - \
// RUN: | %FileCheck %s --check-prefixes CHECK,CV-CHECK
// --------------------------------------------------------------------
//
// CHECK: foo
// CHECK-DAG: ret{{.*}}, !dbg ![[RET:[0-9]+]]
// CHECK-DAG: ![[FOO:[0-9]+]] = distinct !DISubprogram(name: "foo",{{.*}} line: [[@LINE+2]],{{.*}} type: ![[FOOTYPE:[0-9]+]]
public
func foo(_ a: Int64, _ b: Int64) -> Int64 {
var a = a
var b = b
// CHECK-DAG: !DILexicalBlock(scope: ![[FOO]],{{.*}} line: [[@LINE-3]]
// CHECK-DAG: ![[ASCOPE:.*]] = !DILocation(line: [[@LINE-4]],{{.*}} scope: ![[FOO]])
// Check that a is the first and b is the second argument.
// CHECK-DAG: store i64 %0, i64* [[AADDR:.*]], align
// CHECK-DAG: store i64 %1, i64* [[BADDR:.*]], align
// CHECK-DAG: [[AVAL:%.*]] = getelementptr inbounds {{.*}}, [[AMEM:.*]], i32 0, i32 0
// CHECK-DAG: [[BVAL:%.*]] = getelementptr inbounds {{.*}}, [[BMEM:.*]], i32 0, i32 0
// CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[AADDR]], metadata ![[AARG:.*]], metadata !DIExpression()), !dbg ![[ASCOPE]]
// CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[BADDR]], metadata ![[BARG:.*]], metadata !DIExpression())
// CHECK-DAG: ![[AARG]] = !DILocalVariable(name: "a", arg: 1
// CHECK-DAG: ![[BARG]] = !DILocalVariable(name: "b", arg: 2
if b != 0 {
// CHECK-DAG: !DILexicalBlock({{.*}} line: [[@LINE-1]]
// Transparent inlined multiply:
// CHECK-DAG: smul{{.*}}, !dbg ![[MUL:[0-9]+]]
// CHECK-DAG: [[MUL]] = !DILocation(line: [[@LINE+1]],
return a*b
} else {
// CHECK-DAG: ![[PARENT:[0-9]+]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-1]]
var c: Int64 = 42
// CHECK-DAG: ![[CONDITION:[0-9]+]] = distinct !DILexicalBlock(scope: ![[PARENT]], {{.*}}, line: [[@LINE+1]]
if a == 0 {
// CHECK-DAG: !DILexicalBlock(scope: ![[CONDITION]], {{.*}}, line: [[@LINE-1]]
// What about a nested scope?
return 0
}
return c
}
}
// CHECK-DAG: ![[FILE_CWD:[0-9]+]] = !DIFile(filename: "{{.*}}DebugInfo/basic.swift", directory: "{{.*}}")
// CHECK-DAG: ![[MAINFILE:[0-9]+]] = !DIFile(filename: "basic.swift", directory: "{{.*}}DebugInfo")
// CHECK-DAG: !DICompileUnit(language: DW_LANG_Swift, file: ![[FILE_CWD]],{{.*}} producer: "{{.*}}Swift version{{.*}},{{.*}}
// CHECK-DAG: !DISubprogram(name: "main", {{.*}}file: ![[MAINFILE]],
// Function type for foo.
// CHECK-DAG: ![[FOOTYPE]] = !DISubroutineType(types: ![[PARAMTYPES:[0-9]+]])
// CHECK-DAG: ![[INT64:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64", {{.*}}, identifier: "$Ss5Int64VD")
// CHECK-DAG: ![[PARAMTYPES]] = !{![[INT64]], ![[INT64]], ![[INT64]]}
// Import of the main module with the implicit name.
// CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[MAINFILE]], entity: ![[MAINMODULE:[0-9]+]], file: ![[MAINFILE]])
// CHECK-DAG: ![[MAINMODULE]] = !DIModule({{.*}}, name: "basic"
// DWARF Version
// DWARF-CHECK-DAG: i32 2, !"Dwarf Version", i32 4}
// CV-CHECK-DAG: i32 2, !"CodeView", i32 1}
// Debug Info Version
// CHECK-DAG: i32 2, !"Debug Info Version", i32
|
apache-2.0
|
46d7831b85ceaf60e70820d90c15f2b8
| 54.054348 | 138 | 0.520829 | 3.436228 | false | false | false | false |
OpenKitten/MongoKitten
|
Sources/_MongoKittenCrypto/MD5.swift
|
2
|
4120
|
fileprivate let s: [UInt32] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
fileprivate let k: [UInt32] = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
fileprivate let chunkSize = 64
public struct MD5 : Hash {
public static let littleEndian = true
public static let chunkSize = 64
public static let digestSize = 16
// The initial hash
var a0: UInt32 = 0x67452301
var b0: UInt32 = 0xefcdab89
var c0: UInt32 = 0x98badcfe
var d0: UInt32 = 0x10325476
// Working variables
var a1: UInt32 = 0
var b1: UInt32 = 0
var c1: UInt32 = 0
var d1: UInt32 = 0
var F: UInt32 = 0
var g: Int = 0
var Mg: UInt32 = 0
public private(set) var processedBytes: UInt64 = 0
public mutating func reset() {
a0 = 0x67452301
b0 = 0xefcdab89
c0 = 0x98badcfe
d0 = 0x10325476
processedBytes = 0
}
public init() {
reset()
}
public var hashValue: [UInt8] {
var buffer = [UInt8]()
buffer.reserveCapacity(16)
func convert(_ int: UInt32) {
let int = int.littleEndian
buffer.append(UInt8(int & 0xff))
buffer.append(UInt8((int >> 8) & 0xff))
buffer.append(UInt8((int >> 16) & 0xff))
buffer.append(UInt8((int >> 24) & 0xff))
}
convert(a0)
convert(b0)
convert(c0)
convert(d0)
return buffer
}
public mutating func update(from pointer: UnsafePointer<UInt8>) {
a1 = a0
b1 = b0
c1 = c0
d1 = d0
for i in 0...63 {
switch i {
case 0...15:
F = (b1 & c1) | ((~b1) & d1)
g = i
case 16...31:
F = (d1 & b1) | ((~d1) & c1)
g = (5 &* i &+ 1) % 16
case 32...47:
F = b1 ^ c1 ^ d1
g = (3 &* i &+ 5) % 16
default:
F = c1 ^ (b1 | (~d1))
g = (7 &* i) % 16
}
Mg = pointer.advanced(by: g << 2).withMemoryRebound(to: UInt32.self, capacity: 1) { $0.pointee }
F = F &+ a1 &+ k[i] &+ Mg
a1 = d1
d1 = c1
c1 = b1
b1 = b1 &+ leftRotate(F, count: s[i])
}
a0 = a0 &+ a1
b0 = b0 &+ b1
c0 = c0 &+ c1
d0 = d0 &+ d1
}
}
fileprivate func leftRotate(_ x: UInt32, count c: UInt32) -> UInt32 {
return (x << c) | (x >> (32 - c))
}
|
mit
|
3f31bb74401170248c87fdcc39467e63
| 33.049587 | 108 | 0.452184 | 3.083832 | false | false | false | false |
podverse/podverse-ios
|
Podverse/DownloadingEpisodeList.swift
|
1
|
1114
|
//
// DownloadingEpisodeList.swift
// Podverse
//
// Created by Creon on 12/24/16.
// Copyright © 2016 Podverse LLC. All rights reserved.
//
import UIKit
final class DownloadingEpisodeList {
static var shared = DownloadingEpisodeList()
var downloadingEpisodes = [DownloadingEpisode]()
static func removeDownloadingEpisodeWithMediaURL(mediaUrl:String?) {
var downloadingEpisodes = DownloadingEpisodeList.shared.downloadingEpisodes
if let mediaUrl = mediaUrl, let index = downloadingEpisodes.index(where: { $0.mediaUrl == mediaUrl }), index < downloadingEpisodes.count {
downloadingEpisodes[index].removeFromDownloadHistory()
downloadingEpisodes.remove(at: index)
PVDownloader.shared.decrementBadge()
DownloadingEpisodeList.shared.downloadingEpisodes = downloadingEpisodes
}
}
static func removeAllEpisodesForPodcast(feedUrl: String) {
DownloadingEpisodeList.shared.downloadingEpisodes = DownloadingEpisodeList.shared.downloadingEpisodes.filter({$0.podcastFeedUrl != feedUrl})
}
}
|
agpl-3.0
|
f785db5acaf2ddf743650d912e33c94f
| 36.1 | 148 | 0.720575 | 4.881579 | false | false | false | false |
JakeLin/IBAnimatable
|
Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallBeat.swift
|
2
|
2158
|
//
// Created by Tom Baranes on 21/08/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallBeat: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.7
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - circleSize) / 2
let beginTime = layer.currentMediaTime
let beginTimes = [0.35, 0, 0.35]
// Draw circles
for i in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallBeat {
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: .scale)
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.75, 1]
scaleAnimation.duration = duration
return scaleAnimation
}
var opacityAnimation: CAKeyframeAnimation {
let opacityAnimation = CAKeyframeAnimation(keyPath: .opacity)
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.values = [1, 0.2, 1]
opacityAnimation.duration = duration
return opacityAnimation
}
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunctionType = .linear
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
|
mit
|
01dd6051c29f1546383bafd2ffa2ee72
| 29.814286 | 125 | 0.684747 | 4.63871 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/Others/CustomPicker/GradientView.swift
|
1
|
1754
|
//
// GradientView.swift
// Yona
//
// Created by Chandan on 13/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
import UIKit
class GradientView: UIView {
var shapeLayer = CAShapeLayer()
let gradientLayer = CAGradientLayer()
@IBInspectable var gradientColor: UIColor! {
didSet{
self.awakeFromNib()
}
}
@IBInspectable var gradientColor2: UIColor! {
didSet{
self.awakeFromNib()
}
}
// Default Colors
var colors:[UIColor] = [] {
didSet {
setGradient(colors[0], color2: colors[1])
}
}
func setGradient(_ color1: UIColor, color2: UIColor) {
gradientColor = color1
gradientColor2 = color2
shapeLayer.frame = self.bounds
shapeLayer.path = getPath()
shapeLayer.lineWidth = 1.0
shapeLayer.strokeColor = gradientColor.cgColor
shapeLayer.fillColor = gradientColor2.cgColor
self.layer.insertSublayer(shapeLayer, at: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
self.shapeLayer.path = getPath()
}
func getPath() -> CGPath {
let size = self.bounds.size
let path = CGMutablePath()
//CGPathMoveToPoint(path, nil, 0, 0)
path.move(to: CGPoint(x:0,y:0))
//CGPathAddLineToPoint(path, nil, (size.width/3)*2, 0)
path.addLine(to: CGPoint(x:(size.width/3)*2,y:0))
//CGPathAddLineToPoint(path, nil, 0, size.height-15)
path.addLine(to: CGPoint(x:0,y:size.height-15))
// CGPathAddLineToPoint(path, nil, 0, 0)
path.addLine(to: CGPoint(x:0,y:0))
return path
}
}
|
mpl-2.0
|
d26956fe9171ac927177fc3844724c65
| 23.690141 | 62 | 0.571592 | 4.203837 | false | false | false | false |
MukeshKumarS/Swift
|
stdlib/public/core/Availability.swift
|
1
|
2989
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Returns 1 if the running OS version is greater than or equal to
/// major.minor.patchVersion and 0 otherwise.
///
/// This is a magic entry point known to the compiler. It is called in
/// generated code for API availability checking.
@warn_unused_result
@_semantics("availability.osversion")
public func _stdlib_isOSVersionAtLeast(
major: Builtin.Word,
_ minor: Builtin.Word,
_ patch: Builtin.Word
) -> Builtin.Int1 {
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
let runningVersion = _swift_stdlib_operatingSystemVersion()
let queryVersion = _SwiftNSOperatingSystemVersion(
majorVersion: Int(major),
minorVersion: Int(minor),
patchVersion: Int(patch)
)
let result = runningVersion >= queryVersion
return result._value
#else
// FIXME: As yet, there is no obvious versioning standard for platforms other
// than Darwin-based OS', so we just assume false for now.
// rdar://problem/18881232
return false._value
#endif
}
extension _SwiftNSOperatingSystemVersion : Comparable { }
@warn_unused_result
public func == (
left: _SwiftNSOperatingSystemVersion,
right: _SwiftNSOperatingSystemVersion
) -> Bool {
return left.majorVersion == right.majorVersion &&
left.minorVersion == right.minorVersion &&
left.patchVersion == right.patchVersion
}
/// Lexicographic comparison of version components.
@warn_unused_result
public func < (
_lhs: _SwiftNSOperatingSystemVersion,
_rhs: _SwiftNSOperatingSystemVersion
) -> Bool {
if _lhs.majorVersion > _rhs.majorVersion {
return false
}
if _lhs.majorVersion < _rhs.majorVersion {
return true
}
if _lhs.minorVersion > _rhs.minorVersion {
return false
}
if _lhs.minorVersion < _rhs.minorVersion {
return true
}
if _lhs.patchVersion > _rhs.patchVersion {
return false
}
if _lhs.patchVersion < _rhs.patchVersion {
return true
}
return false
}
@warn_unused_result
public func >= (
_lhs: _SwiftNSOperatingSystemVersion,
_rhs: _SwiftNSOperatingSystemVersion
) -> Bool {
if _lhs.majorVersion < _rhs.majorVersion {
return false
}
if _lhs.majorVersion > _rhs.majorVersion {
return true
}
if _lhs.minorVersion < _rhs.minorVersion {
return false
}
if _lhs.minorVersion > _rhs.minorVersion {
return true
}
if _lhs.patchVersion < _rhs.patchVersion {
return false
}
if _lhs.patchVersion > _rhs.patchVersion {
return true
}
return true
}
|
apache-2.0
|
5207057df361e47bf0bdc35b5fee9afd
| 23.702479 | 80 | 0.664771 | 4.331884 | false | false | false | false |
MukeshKumarS/Swift
|
test/IRGen/enum_resilience.swift
|
1
|
8982
|
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience %s | FileCheck %s
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience -O %s
import resilient_enum
import resilient_struct
// CHECK: %C15enum_resilience5Class = type <{ %swift.refcounted }>
// CHECK: %V15enum_resilience9Reference = type <{ %C15enum_resilience5Class* }>
// Public fixed layout struct contains a public resilient struct,
// cannot use spare bits
// CHECK: %O15enum_resilience6Either = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }>
// Public resilient struct contains a public resilient struct,
// can use spare bits (FIXME)
// CHECK: %O15enum_resilience15ResilientEither = type <{ [[REFERENCE_TYPE]], [1 x i8] }>
// Internal fixed layout struct contains a public resilient struct,
// can use spare bits (FIXME)
// CHECK: %O15enum_resilience14InternalEither = type <{ [[REFERENCE_TYPE]], [1 x i8] }>
// Public fixed layout struct contains a fixed layout struct,
// can use spare bits
// CHECK: %O15enum_resilience10EitherFast = type <{ [[REFERENCE_TYPE]] }>
public class Class {}
public struct Reference {
public var n: Class
}
@_fixed_layout public enum Either {
case Left(Reference)
case Right(Reference)
}
public enum ResilientEither {
case Left(Reference)
case Right(Reference)
}
enum InternalEither {
case Left(Reference)
case Right(Reference)
}
@_fixed_layout public struct ReferenceFast {
public var n: Class
}
@_fixed_layout public enum EitherFast {
case Left(ReferenceFast)
case Right(ReferenceFast)
}
// CHECK-LABEL: define void @_TF15enum_resilience25functionWithResilientEnumFO14resilient_enum6MediumS1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithResilientEnum(m: Medium) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return m
}
// CHECK-LABEL: define void @_TF15enum_resilience33functionWithIndirectResilientEnumFO14resilient_enum16IndirectApproachS1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithIndirectResilientEnum(ia: IndirectApproach) -> IndirectApproach {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum16IndirectApproach()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return ia
}
// CHECK-LABEL: define void @_TF15enum_resilience31constructResilientEnumNoPayloadFT_O14resilient_enum6Medium
public func constructResilientEnumNoPayload() -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 25
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 2, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Paper
}
// CHECK-LABEL: define void @_TF15enum_resilience29constructResilientEnumPayloadFV16resilient_struct4SizeO14resilient_enum6Medium
public func constructResilientEnumPayload(s: Size) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium()
// CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8***
// CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 25
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 1, %swift.type* [[METADATA2]])
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Postcard(s)
}
// CHECK-LABEL: define {{i32|i64}} @_TF15enum_resilience19resilientSwitchTestFO14resilient_enum6MediumSi(%swift.opaque* noalias nocapture)
// CHECK: [[BUFFER:%.*]] = alloca [[BUFFER_TYPE:\[(12|24) x i8\]]]
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaO14resilient_enum6Medium()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 5
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]]([[BUFFER_TYPE]]* [[BUFFER]], %swift.opaque* %0, %swift.type* [[METADATA]])
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 23
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* [[ENUM_COPY]], %swift.type* [[METADATA]])
// CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [
// CHECK: i32 0, label %[[PAMPHLET_CASE:.*]]
// CHECK: i32 2, label %[[PAPER_CASE:.*]]
// CHECK: i32 3, label %[[CANVAS_CASE:.*]]
// CHECK: ]
// CHECK: ; <label>:[[PAPER_CASE]]
// CHECK: br label %[[END:.*]]
// CHECK: ; <label>:[[CANVAS_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[PAMPHLET_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[DEFAULT_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[END]]
// CHECK: ret
public func resilientSwitchTest(m: Medium) -> Int {
switch m {
case .Paper:
return 1
case .Canvas:
return 2
case .Pamphlet(let m):
return resilientSwitchTest(m)
default:
return 3
}
}
public func reabstraction<T>(f: Medium -> T) {}
// CHECK-LABEL: define void @_TF15enum_resilience25resilientEnumPartialApplyFFO14resilient_enum6MediumSiT_(i8*, %swift.refcounted*)
public func resilientEnumPartialApply(f: Medium -> Int) {
// CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_allocObject
// CHECK: call void @_TF15enum_resilience13reabstractionurFFO14resilient_enum6MediumxT_(i8* bitcast (void (%Si*, %swift.opaque*, %swift.refcounted*)* @_TPA__TTRXFo_iO14resilient_enum6Medium_dSi_XFo_iS0__iSi_ to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_TMSi)
reabstraction(f)
// CHECK: ret void
}
// CHECK-LABEL: define internal void @_TPA__TTRXFo_iO14resilient_enum6Medium_dSi_XFo_iS0__iSi_(%Si* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted*)
|
apache-2.0
|
329a411cf2e9277acc0642e349e897ab
| 43.246305 | 277 | 0.649744 | 3.287701 | false | false | false | false |
hua16/summary
|
stanford-game/stanford-game/Card.swift
|
1
|
555
|
//
// Card.swift
// stanford-game
//
// Created by xulihua on 2017/11/20.
// Copyright © 2017年 huage. All rights reserved.
//
import Foundation
//1、struct 没有继承
//2、值传递,class是指针传递
struct Card {
var isFaceUp = false
var isMatched = false
var identifier: Int
static var identifierFactory = 0
static func getUniqueIdentifier () -> Int {
identifierFactory += 1
return identifierFactory
}
init() {
self.identifier = Card.getUniqueIdentifier();
}
}
|
mit
|
97662fec2d109ca397dc459acd1a7b8c
| 17 | 53 | 0.62069 | 3.755396 | false | false | false | false |
mnito/alt-file
|
io/ByteWriter.swift
|
1
|
610
|
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#else
import Glibc
#endif
public struct ByteWriter {
internal var fp: UnsafeMutablePointer<FILE>
init(path: String) {
fp = fopen(path, "a")
}
public func write(byte: Byte) -> Int {
return Int(fputc(Int32(byte), fp))
}
public func write(bytes: [Byte]) -> Int {
var written = 0
for byte in bytes {
let c = write(byte)
guard c >= 0 else {
break
}
written += 1
}
return written
}
public func toStart() {
rewind(fp)
}
public func close() {
fclose(fp)
}
}
|
mit
|
a6bb469769af6c027b4e33c2f229138c
| 15.486486 | 49 | 0.565574 | 3.370166 | false | false | false | false |
HarwordLiu/Ing.
|
Ing/Ing/Manager/CoreDataManager.swift
|
1
|
7022
|
//
// HLCoreDataManager.swift
// Ing
//
// Created by 刘浩 on 2017/8/12.
// Copyright © 2017年 刘浩. All rights reserved.
//
import UIKit
import CoreData
import CloudKit
typealias networkOperationResult = (_ success: Bool, _ errorMessage: String?) -> Void
class CoreDataManager: NSObject {
var mainThreadManagedObjectContext: NSManagedObjectContext
var cloudKitManager: CloudKitManager?
fileprivate var privateObjectContext: NSManagedObjectContext
fileprivate let coordinator: NSPersistentStoreCoordinator
init(closure:@escaping ()->()) {
guard let modelURL = Bundle.main.url(forResource: "Ing", withExtension: "momd"),
let managedObjectModel = NSManagedObjectModel.init(contentsOf: modelURL)
else {
fatalError("CoreDataManager - COULD NOT INIT MANAGED OBJECT MODEL")
}
coordinator = NSPersistentStoreCoordinator.init(managedObjectModel: managedObjectModel)
mainThreadManagedObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
privateObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
privateObjectContext.persistentStoreCoordinator = coordinator
mainThreadManagedObjectContext.persistentStoreCoordinator = coordinator
super.init()
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
[unowned self] in
let options = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true,
NSSQLitePragmasOption: ["journal_mode": "DELETE"]
] as [String : Any]
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let storeURL = URL.init(string: "coredatamodel.sqlite", relativeTo: documentsURL)
do {
try self.coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
DispatchQueue.main.async {
closure()
}
}
catch let error as NSError {
fatalError("CoreDataManager - COULD NOT INIT SQLITE STORE: \(error.localizedDescription)")
}
}
cloudKitManager = CloudKitManager(coreDataManager: self)
NotificationCenter.default.addObserver(self, selector: #selector(CoreDataManager.mergeContext(_:)), name:NSNotification.Name.NSManagedObjectContextDidSave , object: nil)
}
func mergeContext(_ notification: Notification) {
let sender = notification.object as! NSManagedObjectContext
if sender != mainThreadManagedObjectContext {
mainThreadManagedObjectContext.performAndWait {
[unowned self] in
print("mainThreadManagedObjectContext.mergeChangesFromContextDidSaveNotification")
self.mainThreadManagedObjectContext.mergeChanges(fromContextDidSave: notification)
}
}
}
func createBackgroundManagedContext() -> NSManagedObjectContext {
let backgroundManagedObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
backgroundManagedObjectContext.persistentStoreCoordinator = coordinator
backgroundManagedObjectContext.undoManager = nil
return backgroundManagedObjectContext
}
func save() {
let insertedObjects = mainThreadManagedObjectContext.insertedObjects
let modifiedObjects = mainThreadManagedObjectContext.updatedObjects
let deletedRecordIDs = mainThreadManagedObjectContext.deletedObjects.flatMap { ($0 as? CloudKitManagedObject)?.cloudKitRecordID() }
if privateObjectContext.hasChanges || mainThreadManagedObjectContext.hasChanges {
self.mainThreadManagedObjectContext.performAndWait {
[unowned self] in
do {
try self.mainThreadManagedObjectContext.save()
self.savePrivateObjectContext()
}
catch let error as NSError {
fatalError("CoreDataManager - SAVE MANAGEDOBJECTCONTEXT FAILED: \(error.localizedDescription)")
}
let insertedManagedObjectIDs = insertedObjects.flatMap { $0.objectID }
let modifiedManagedObjectIDs = modifiedObjects.flatMap { $0.objectID }
self.cloudKitManager?.saveChangesToCloudKit(insertedManagedObjectIDs, modifiedManagedObjectIDs: modifiedManagedObjectIDs, deletedRecordIDs: deletedRecordIDs)
}
}
}
func saveBackgroundManagedObjectContext(_ backgroundManagedObjectContext: NSManagedObjectContext) {
if backgroundManagedObjectContext.hasChanges {
do {
try backgroundManagedObjectContext.save()
}
catch let error as NSError {
fatalError("CoreDataManager - save backgroundManagedObjectContext ERROR: \(error.localizedDescription)")
}
}
}
func sync() {
cloudKitManager?.performFullSync()
}
internal func savePrivateObjectContext() {
privateObjectContext.performAndWait {
[unowned self] in
print("savePrivateObjectContext")
do {
try self.privateObjectContext.save()
}
catch let error as NSError {
fatalError("CoreDataManager - SAVE PRIVATEOBJECTCONTEXT FAILED: \(error.localizedDescription)")
}
}
}
// MARK: Fetch CloudKitManagedObjects from Context by NSManagedObjectID
func fetchCloudKitManagedObjects(_ managedObjectContext: NSManagedObjectContext, managedObjectIDs: [NSManagedObjectID]) -> [CloudKitManagedObject] {
var cloudKitManagedObjects: [CloudKitManagedObject] = []
for managedObjectID in managedObjectIDs {
do {
let managedObject = try managedObjectContext.existingObject(with: managedObjectID)
if let cloudKitManagedObject = managedObject as? CloudKitManagedObject {
cloudKitManagedObjects.append(cloudKitManagedObject)
}
}
catch let error as NSError {
print("Error fetching from CoreData: \(error.localizedDescription)")
}
}
return cloudKitManagedObjects
}
}
|
mit
|
faeb2098f1d2d114560b5510ca8bc1da
| 37.734807 | 177 | 0.638425 | 6.941584 | false | false | false | false |
mauryat/firefox-ios
|
Client/Frontend/Home/BookmarksPanel.swift
|
1
|
23843
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
// MARK: - Placeholder strings for Bug 1232810.
let deleteWarningTitle = NSLocalizedString("This folder isn't empty.", tableName: "BookmarkPanelDeleteConfirm", comment: "Title of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteWarningDescription = NSLocalizedString("Are you sure you want to delete it and its contents?", tableName: "BookmarkPanelDeleteConfirm", comment: "Main body of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteCancelButtonLabel = NSLocalizedString("Cancel", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label to cancel deletion when the user tried to delete a non-empty folder.")
let deleteDeleteButtonLabel = NSLocalizedString("Delete", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label for the button that deletes a folder and all of its children.")
// Placeholder strings for Bug 1248034
let emptyBookmarksText = NSLocalizedString("Bookmarks you save will show up here.", comment: "Status label for the empty Bookmarks state.")
// MARK: - UX constants.
struct BookmarksPanelUX {
static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10
static let BookmarkFolderChevronSize: CGFloat = 20
static let BookmarkFolderChevronLineWidth: CGFloat = 2.0
static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0)
static let BookmarkFolderBGColor = UIColor(rgb: 0xf7f8f7).withAlphaComponent(0.3)
static let WelcomeScreenPadding: CGFloat = 15
static let WelcomeScreenItemTextColor = UIColor.gray
static let WelcomeScreenItemWidth = 170
static let SeparatorRowHeight: CGFloat = 0.5
static let IconSize: CGFloat = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
var source: BookmarksModel?
var parentFolders = [BookmarkFolder]()
var bookmarkFolder: BookmarkFolder?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(BookmarksPanel.longPress(_:)))
}()
fileprivate lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
fileprivate let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier"
fileprivate let BookmarkSeparatorCellIdentifier = "BookmarkSeparatorIdentifier"
fileprivate let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier"
init() {
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BookmarksPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil)
self.tableView.register(SeparatorTableCell.self, forCellReuseIdentifier: BookmarkSeparatorCellIdentifier)
self.tableView.register(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier)
self.tableView.register(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
self.tableView.accessibilityIdentifier = "Bookmarks List"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// If we've not already set a source for this panel, fetch a new model from
// the root; otherwise, just use the existing source to select a folder.
guard let source = self.source else {
// Get all the bookmarks split by folders
if let bookmarkFolder = bookmarkFolder {
profile.bookmarks.modelFactory >>== { $0.modelForFolder(bookmarkFolder).upon(self.onModelFetched) }
} else {
profile.bookmarks.modelFactory >>== { $0.modelForRoot().upon(self.onModelFetched) }
}
return
}
if let bookmarkFolder = bookmarkFolder {
source.selectFolder(bookmarkFolder).upon(onModelFetched)
} else {
source.selectFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched)
}
}
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
fileprivate func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.white
let logoImageView = UIImageView(image: UIImage(named: "emptyBookmarks"))
overlayView.addSubview(logoImageView)
logoImageView.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100)
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
}
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = emptyBookmarksText
welcomeLabel.textAlignment = NSTextAlignment.center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = BookmarksPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
make.top.equalTo(logoImageView.snp.bottom).offset(BookmarksPanelUX.WelcomeScreenPadding)
make.width.equalTo(BookmarksPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
fileprivate func updateEmptyPanelState() {
if source?.current.count == 0 && source?.current.guid == BookmarkRoots.MobileFolderGUID {
if self.emptyStateOverlayView.superview == nil {
self.view.addSubview(self.emptyStateOverlayView)
self.view.bringSubview(toFront: self.emptyStateOverlayView)
self.emptyStateOverlayView.snp.makeConstraints { make -> Void in
make.edges.equalTo(self.tableView)
}
}
} else {
self.emptyStateOverlayView.removeFromSuperview()
}
}
fileprivate func onModelFetched(_ result: Maybe<BookmarksModel>) {
guard let model = result.successValue else {
self.onModelFailure(result.failureValue as Any)
return
}
self.onNewModel(model)
}
fileprivate func onNewModel(_ model: BookmarksModel) {
if Thread.current.isMainThread {
self.source = model
self.tableView.reloadData()
return
}
DispatchQueue.main.async {
self.source = model
self.tableView.reloadData()
self.updateEmptyPanelState()
}
}
fileprivate func onModelFailure(_ e: Any) {
log.error("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData().upon(onModelFetched)
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
presentContextMenu(for: indexPath)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let source = source, let bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAt: indexPath) }
switch bookmark {
case let item as BookmarkItem:
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
if let url = bookmark.favicon?.url.asURL, url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else {
cell.imageView?.layer.borderColor = BookmarksPanelUX.IconBorderColor.cgColor
cell.imageView?.layer.borderWidth = BookmarksPanelUX.IconBorderWidth
let bookmarkURL = URL(string: item.url)
cell.imageView?.setIcon(bookmark.favicon, forURL: bookmarkURL, completed: { (color, url) in
if bookmarkURL == url {
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: BookmarksPanelUX.IconSize, height: BookmarksPanelUX.IconSize))
cell.imageView?.backgroundColor = color
cell.imageView?.contentMode = .center
}
})
}
return cell
case is BookmarkSeparator:
return tableView.dequeueReusableCell(withIdentifier: BookmarkSeparatorCellIdentifier, for: indexPath)
case let bookmark as BookmarkFolder:
let cell = tableView.dequeueReusableCell(withIdentifier: BookmarkFolderCellIdentifier, for: indexPath)
cell.textLabel?.text = bookmark.title
return cell
default:
// This should never happen.
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
if let cell = cell as? BookmarkFolderTableViewCell {
cell.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show a header for the root
if source == nil || parentFolders.isEmpty {
return nil
}
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil }
// register as delegate to ensure we get notified when the user interacts with this header
if header.delegate == nil {
header.delegate = self
}
if parentFolders.count == 1 {
header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label")
} else if let parentFolder = parentFolders.last {
header.textLabel?.text = parentFolder.title
}
return header
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let it = self.source?.current[indexPath.row], it is BookmarkSeparator {
return BookmarksPanelUX.SeparatorRowHeight
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || parentFolders.isEmpty {
return 0
}
return SiteTableViewControllerUX.RowHeight
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? BookmarkFolderTableViewHeader {
// for some reason specifying the font in header view init is being ignored, so setting it here
header.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel
}
}
override func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool {
// Show a full-width border for cells above separators, so they don't have a weird step.
// Separators themselves already have a full-width border, but let's force the issue
// just in case.
let this = self.source?.current[indexPath.row]
if (indexPath.row + 1) < (self.source?.current.count)! {
let below = self.source?.current[indexPath.row + 1]
if this is BookmarkSeparator || below is BookmarkSeparator {
return true
}
}
return super.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
guard let source = source else {
return
}
let bookmark = source.current[indexPath.row]
switch bookmark {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURLString: item.url, visitType: VisitType.bookmark)
LeanplumIntegration.sharedInstance.track(eventName: .openedBookmark)
break
case let folder as BookmarkFolder:
log.debug("Selected \(folder.guid)")
let nextController = BookmarksPanel()
nextController.parentFolders = parentFolders + [source.current]
nextController.bookmarkFolder = folder
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
source.modelFactory.uponQueue(DispatchQueue.main) { maybe in
guard let factory = maybe.successValue else {
// Nothing we can do.
return
}
let specificFactory = factory.factoryForIndex(indexPath.row, inFolder: source.current)
nextController.source = BookmarksModel(modelFactory: specificFactory, root: folder)
self.navigationController?.pushViewController(nextController, animated: true)
}
break
default:
// You can't do anything with separators.
break
}
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(_ tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle {
guard let source = source else {
return .none
}
if source.current[indexPath.row] is BookmarkSeparator {
// Because the deletion block is too big.
return .none
}
if source.current.itemIsEditableAtIndex(indexPath.row) {
return .delete
}
return .none
}
func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? {
guard let source = self.source else {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in
self.deleteBookmark(indexPath: indexPath, source: source)
})
return [delete]
}
func pinTopSite(_ site: Site) {
_ = profile.history.addPinnedTopSite(site).value
}
func deleteBookmark(indexPath: IndexPath, source: BookmarksModel) {
guard let bookmark = source.current[indexPath.row] else {
return
}
assert(!(bookmark is BookmarkFolder))
if bookmark is BookmarkFolder {
// TODO: check whether the folder is empty (excluding separators). If it isn't
// then we must ask the user to confirm. Bug 1232810.
log.debug("Not deleting folder.")
return
}
log.debug("Removing rows \(indexPath).")
// Block to do this -- this is UI code.
guard let factory = source.modelFactory.value.successValue else {
log.error("Couldn't get model factory. This is unexpected.")
self.onModelFailure(DatabaseError(description: "Unable to get factory."))
return
}
let specificFactory = factory.factoryForIndex(indexPath.row, inFolder: source.current)
if let err = specificFactory.removeByGUID(bookmark.guid).value.failureValue {
log.debug("Failed to remove \(bookmark.guid).")
self.onModelFailure(err)
return
}
self.tableView.beginUpdates()
self.source = source.removeGUIDFromCurrent(bookmark.guid)
self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
self.tableView.endUpdates()
self.updateEmptyPanelState()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: BookmarkStatusChangedNotification), object: bookmark, userInfo: ["added": false]
)
}
}
extension BookmarksPanel: HomePanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
guard let bookmarkItem = source?.current[indexPath.row] as? BookmarkItem else { return nil }
let site = Site(url: bookmarkItem.url, title: bookmarkItem.title, bookmarked: true, guid: bookmarkItem.guid)
site.icon = bookmarkItem.favicon
return site
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil }
let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in
self.pinTopSite(site)
})
actions.append(pinTopSite)
// Only local bookmarks can be removed
guard let source = source else { return nil }
if source.current.itemIsEditableAtIndex(indexPath.row) {
let removeAction = PhotonActionSheetItem(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in
self.deleteBookmark(indexPath: indexPath, source: source)
})
actions.append(removeAction)
}
return actions
}
}
private protocol BookmarkFolderTableViewHeaderDelegate {
func didSelectHeader()
}
extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate {
fileprivate func didSelectHeader() {
_ = self.navigationController?.popViewController(animated: true)
}
}
class BookmarkFolderTableViewCell: TwoLineTableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = BookmarksPanelUX.BookmarkFolderBGColor
textLabel?.backgroundColor = UIColor.clear
textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
imageView?.image = UIImage(named: "bookmarkFolder")
accessoryType = UITableViewCellAccessoryType.disclosureIndicator
separatorInset = UIEdgeInsets.zero
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
fileprivate class BookmarkFolderTableViewHeader: UITableViewHeaderFooterView {
var delegate: BookmarkFolderTableViewHeaderDelegate?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
return chevron
}()
lazy var topBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
lazy var bottomBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(BookmarkFolderTableViewHeader.viewWasTapped(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
addSubview(topBorder)
addSubview(bottomBorder)
contentView.addSubview(chevron)
contentView.addSubview(titleLabel)
chevron.snp.makeConstraints { make in
make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize)
}
titleLabel.snp.makeConstraints { make in
make.left.equalTo(chevron.snp.right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.right.greaterThanOrEqualTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
}
topBorder.snp.makeConstraints { make in
make.left.right.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
bottomBorder.snp.makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc fileprivate func viewWasTapped(_ gestureRecognizer: UITapGestureRecognizer) {
delegate?.didSelectHeader()
}
}
|
mpl-2.0
|
313e790d5c476faa784e497140b327f2
| 41.2 | 278 | 0.677977 | 5.594322 | false | false | false | false |
malaonline/iOS
|
mala-ios/View/OrderForm/OrderFormPaymentChannelCell.swift
|
1
|
3976
|
//
// OrderFormPaymentChannelCell.swift
// mala-ios
//
// Created by 王新宇 on 16/5/13.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class OrderFormPaymentChannelCell: UITableViewCell {
// MARK: - Property
/// 支付方式
var channel: MalaPaymentChannel = .Other {
didSet {
switch channel {
case .Alipay:
payChannelLabel.text = "支付宝"
iconView.image = UIImage(asset: .alipayIcon)
break
case .Wechat:
payChannelLabel.text = "微信"
iconView.image = UIImage(asset: .wechatIcon)
break
case .AliQR:
payChannelLabel.text = "支付宝扫码支付"
iconView.image = UIImage(asset: .qcpayIcon)
break
case .WxQR:
payChannelLabel.text = "微信扫码支付"
iconView.image = UIImage(asset: .qcpayIcon)
break
case .QRPay:
payChannelLabel.text = "家长代付"
iconView.image = UIImage(asset: .qcpayIcon)
break
case .WechatPub:
payChannelLabel.text = "微信公众号支付"
iconView.image = UIImage(asset: .wechatIcon)
break
case .Other:
payChannelLabel.text = "其他支付方式"
break
}
}
}
// MARK: - Components
/// 布局容器
private lazy var content: UIView = {
let view = UIView(UIColor.white)
return view
}()
/// cell标题
private lazy var titleLabel: UILabel = {
let label = UILabel(
text: "支付方式",
fontSize: 15,
textColor: UIColor(named: .ThemeTextBlue)
)
return label
}()
/// 支付渠道icon
private lazy var iconView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
/// 支付渠道
private lazy var payChannelLabel: UILabel = {
let label = UILabel(
text: "支付方式",
fontSize: 13,
textColor: UIColor(named: .ArticleText)
)
return label
}()
// MARK: - Contructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
contentView.backgroundColor = UIColor(named: .CardBackground)
// SubViews
contentView.addSubview(content)
content.addSubview(titleLabel)
content.addSubview(iconView)
content.addSubview(payChannelLabel)
// Autolayout
content.snp.makeConstraints { (maker) in
maker.top.equalTo(contentView)
maker.left.equalTo(contentView).offset(12)
maker.right.equalTo(contentView).offset(-12)
maker.bottom.equalTo(contentView)
maker.height.equalTo(44)
}
titleLabel.snp.updateConstraints { (maker) -> Void in
maker.centerY.equalTo(content)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(17)
}
iconView.snp.makeConstraints { (maker) in
maker.centerY.equalTo(content)
maker.right.equalTo(payChannelLabel.snp.left).offset(-5)
maker.width.equalTo(22)
maker.height.equalTo(22)
}
payChannelLabel.snp.updateConstraints { (maker) -> Void in
maker.centerY.equalTo(content)
maker.right.equalTo(content).offset(-12)
maker.height.equalTo(21)
}
}
}
|
mit
|
f799ecce28993c942e8717c29040006b
| 29.039063 | 74 | 0.546424 | 4.599282 | false | false | false | false |
hanhailong/practice-swift
|
Tutorials/Developing_iOS_Apps_With_Swift/lesson5/lesson5/SearchResultsViewController.swift
|
3
|
2332
|
import UIKit
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {
@IBOutlet var appTableView: UITableView
var api: APIController = APIController()
var tableData: NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
self.api.delegate = self
api.searchItunesFor("Apple")
}
func didRecieveAPIResults(results: NSDictionary) {
if results.count>0 {
self.tableData = results["results"] as NSArray
self.appTableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
// Get the row data for the selected row
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
var name: String = rowData["trackName"] as String
var formattedPrice: String = rowData["formattedPrice"] as String
var alert: UIAlertView = UIAlertView()
alert.title = name
alert.message = formattedPrice
alert.addButtonWithTitle("OK")
alert.show()
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
// Optimizing the cell creation
let kIdentifierCell: String = "SearchResultCell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kIdentifierCell) as UITableViewCell
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
cell.text = rowData["trackName"] as String
var imgString = rowData["artworkUrl60"] as String
var imgURL: NSURL = NSURL(string: imgString)
var imgData: NSData = NSData(contentsOfURL: imgURL)
cell.image = UIImage(data: imgData)
var formattedPrice: NSString = rowData["formattedPrice"] as NSString
cell.detailTextLabel.text = formattedPrice
return cell
}
}
|
mit
|
3740a6e5eacd7d887a2219005516da40
| 31.84507 | 120 | 0.647513 | 5.7866 | false | false | false | false |
Mamesoft/SocketChat_SimpleClient_Swift
|
Test-Chat/AppDelegate.swift
|
1
|
4581
|
//
// AppDelegate.swift
// Test-Chat
//
// Copyright (c) 2014年 Mamesoft. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, SocketIODelegate {
var socketIO: SocketIO!
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var inoutTextField: NSTextField!
@IBOutlet weak var commentTextField: NSTextField!
@IBOutlet var logTextView: NSTextView!
@IBOutlet weak var inoutButton: NSButton!
@IBOutlet weak var usersTextField: NSTextField!
@IBOutlet weak var hashtagTextField: NSTextField!
func applicationDidFinishLaunching(aNotification: NSNotification?) {
socketIO = SocketIO(delegate: self)
socketIO.connectToHost("localhost", onPort: 8080) //Connect Host
}
func socketIODidConnect(socket: SocketIO) {
socketIO.sendEvent("register", withData: ["mode": "client", "lastid": 1])
}
var users: Dictionary<Int, JSONValue> = [:]
var logs: Array<Dictionary<String, String>> = []
func socketIO(socket: SocketIO!, didReceiveEvent packet: SocketIOPacket!) {
let json: AnyObject! = packet.dataAsJSON()
let event: String = json["name"].description
let dataany: AnyObject! = json["args"]
let data: JSONValue = JSONValue(dataany[0])
switch event{
case "init":
println("init")
var logsjson: [JSONValue] = data["logs"].array!
for var i = logsjson.count - 1; i >= 0; --i{
addlog(logsjson[i])
}
showlogs()
case "users":
println("users")
var usersjson: [JSONValue] = data["users"].array!
for value in usersjson{
edituser(value)
}
showusers()
case "newuser":
println("newuser")
edituser(data)
showusers()
case "inout":
println("inout")
edituser(data)
showusers()
case "deluser":
println("deluser")
users.removeValueForKey(data.integer!)
showusers()
case "userinfo":
println("userinfo")
var rom = data["rom"].bool!
if(rom == true){
inoutButton.title = "In"
inoutTextField.enabled = true
}else{
inoutButton.title = "Out"
inoutTextField.enabled = false
}
case "log":
println("log")
addlog(data)
showlogs()
default:
println("no-maching")
}
}
func addlog(data: JSONValue) {
logs.append( [
"name": data["name"].string!,
"comment": data["comment"].string!,
"ip": data["ip"].string!,
"time": data["time"].string!,
] )
}
func edituser(data: JSONValue) {
users[data["id"].integer!] = data
}
func showlogs(){
var logstring = ""
for log: Dictionary<String, String> in logs{
logstring = log["name"]! + "> " + log["comment"]! + " ( " + log["ip"]! + ", " + log["time"]! + " )\n" + logstring
}
logTextView.string = logstring
}
func showusers(){
var romusers: [JSONValue] = []
var onlineusers: [JSONValue] = []
for (id, user) in users{
var rom: Bool = user["rom"].bool!
if(rom == true){
romusers.append(user)
}else{
onlineusers.append(user)
}
}
var userstring = "Online(\(onlineusers.count)): "
for user: JSONValue in onlineusers{
userstring += user["name"].string! + "(" + user["ip"].string! + "), "
}
userstring += "Rom(\(romusers.count))"
usersTextField.stringValue = userstring
}
@IBAction func inout(sender: AnyObject) {
socketIO.sendEvent("inout", withData: ["name": inoutTextField.stringValue])
}
@IBAction func commentTextFieldReturn(sender: NSTextField) {
socketIO.sendEvent("say", withData: ["comment": commentTextField.stringValue, "channel": hashtagTextField.stringValue])
commentTextField.stringValue = ""
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
}
|
mit
|
8265fd0974e345632c35440086cd5e29
| 28.928105 | 127 | 0.525224 | 4.706064 | false | false | false | false |
KevinYangGit/DYTV
|
DYZB/DYZB/Classes/Main/ViewModel/BaseViewModel.swift
|
1
|
1381
|
//
// BaseViewModel.swift
// DYZB
//
// Created by boxfishedu on 2016/10/17.
// Copyright © 2016年 杨琦. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () ->()) {
NetworkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in
//对结果进行处理
guard let resultDict = result as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
//是否分组数据
if isGroupData {
for dict in dataArray {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
} else {
//创建组
let group = AnchorGroup()
//遍历dataArray的所有字典
for dict in dataArray {
group.anchors.append(AnchorModel(dict : dict))
}
//将group添加到anchorGroups
self.anchorGroups.append(group)
}
finishedCallback()
}
}
}
|
mit
|
02c0ba4d07968acce514a5f44fef3928
| 29 | 139 | 0.518939 | 5.019011 | false | false | false | false |
michael-groble/Geohash
|
Sources/Geohash/Location.swift
|
1
|
1034
|
//
// Location.swift
// Geohash
//
// Created by michael groble on 1/6/17.
//
//
import Foundation
public class Location {
static let radiansPerDegree = Double.pi / 180.0
static let earthDiameterMeters = 2.0 * 6_371_000.0
public let longitude: Double
public let latitude: Double
public init(longitude lon: Double, latitude lat: Double) {
self.longitude = lon
self.latitude = lat
}
public func distanceInMeters(to: Location) -> Double {
let aLat = Double(Location.radiansPerDegree * latitude)
let bLat = Double(Location.radiansPerDegree * to.latitude)
let deltaLat = bLat - aLat
let deltaLon = Double(Location.radiansPerDegree * (to.longitude - longitude))
let sinHalfLat = sin(Double(0.5) * deltaLat)
let sinHalfLon = sin(Double(0.5) * deltaLon)
let x = sinHalfLat * sinHalfLat + sinHalfLon * sinHalfLon * cos(aLat) * cos(bLat)
let arc = asin(sqrt(x)) // only good for smallish angles, otherwise user atan2
return Location.earthDiameterMeters * Double(arc)
}
}
|
bsd-3-clause
|
5015c2a3741eb0c8403f4b292d5120f0
| 28.542857 | 85 | 0.693424 | 3.469799 | false | false | false | false |
BenEmdon/swift-algorithm-club
|
Linked List/LinkedList.swift
|
1
|
3828
|
public class LinkedListNode<T> {
var value: T
var next: LinkedListNode?
weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
}
public class LinkedList<T> {
public typealias Node = LinkedListNode<T>
fileprivate var head: Node?
public init() {}
public var isEmpty: Bool {
return head == nil
}
public var first: Node? {
return head
}
public var last: Node? {
if var node = head {
while case let next? = node.next {
node = next
}
return node
} else {
return nil
}
}
public var count: Int {
if var node = head {
var c = 1
while case let next? = node.next {
node = next
c += 1
}
return c
} else {
return 0
}
}
public func node(atIndex index: Int) -> Node? {
if index >= 0 {
var node = head
var i = index
while node != nil {
if i == 0 { return node }
i -= 1
node = node!.next
}
}
return nil
}
public subscript(index: Int) -> T {
let node = self.node(atIndex: index)
assert(node != nil)
return node!.value
}
public func append(_ value: T) {
let newNode = Node(value: value)
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) {
assert(index >= 0)
var i = index
var next = head
var prev: Node?
while next != nil && i > 0 {
i -= 1
prev = next
next = next!.next
}
assert(i == 0) // if > 0, then specified index was too large
return (prev, next)
}
public func insert(_ value: T, atIndex index: Int) {
let (prev, next) = nodesBeforeAndAfter(index: index)
let newNode = Node(value: value)
newNode.previous = prev
newNode.next = next
prev?.next = newNode
next?.previous = newNode
if prev == nil {
head = newNode
}
}
public func removeAll() {
head = nil
}
public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value
}
public func removeLast() -> T {
assert(!isEmpty)
return remove(node: last!)
}
public func remove(atIndex index: Int) -> T {
let node = self.node(atIndex: index)
assert(node != nil)
return remove(node: node!)
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
var s = "["
var node = head
while node != nil {
s += "\(node!.value)"
node = node!.next
if node != nil { s += ", " }
}
return s + "]"
}
}
extension LinkedList {
public func reverse() {
var node = head
while let currentNode = node {
node = currentNode.next
swap(¤tNode.next, ¤tNode.previous)
head = currentNode
}
}
}
extension LinkedList {
public func map<U>(transform: (T) -> U) -> LinkedList<U> {
let result = LinkedList<U>()
var node = head
while node != nil {
result.append(transform(node!.value))
node = node!.next
}
return result
}
public func filter(predicate: (T) -> Bool) -> LinkedList<T> {
let result = LinkedList<T>()
var node = head
while node != nil {
if predicate(node!.value) {
result.append(node!.value)
}
node = node!.next
}
return result
}
}
extension LinkedList {
convenience init(array: Array<T>) {
self.init()
for element in array {
self.append(element)
}
}
}
|
mit
|
1b67c8208a68f8f28da1a55971ff6b9f
| 18.333333 | 66 | 0.549112 | 3.870576 | false | false | false | false |
glwithu06/ReTodo
|
ReTodo/Action/TodoAction.swift
|
1
|
1073
|
//
// TodoAction.swift
// ReTodo
//
// Created by Nate Kim on 07/07/2017.
// Copyright © 2017 NateKim. All rights reserved.
//
import ReSwift
struct AddTaskAction: Action {
var title:String
var note:String?
var dueDate:Date?
init(title: String, note: String? = nil, dueDate: Date? = nil) {
self.title = title
self.note = note
self.dueDate = dueDate
}
}
struct EditTaskAction: Action {
var id:Int
var title:String
var note:String?
var dueDate:Date?
init(id:Int, title: String, note: String? = nil, dueDate: Date? = nil) {
self.id = id
self.title = title
self.note = note
self.dueDate = dueDate
}
}
struct ToggleTaskAction: Action {
var id:Int
init(id:Int) {
self.id = id
}
}
struct DeleteTaskAction: Action {
var id:Int
init(id:Int) {
self.id = id
}
}
struct DeleteTasksAction: Action {
var ids:[Int]
init(ids:[Int]) {
self.ids = ids
}
}
struct ToggleAllTaskAction: Action { }
|
mit
|
c223d95548e465f3ef05e47bfe682d83
| 16.57377 | 76 | 0.576493 | 3.435897 | false | false | false | false |
davidmfry/robodub-hud-siftw-ui
|
AnalogStick Demo/AnalogStick Demo/GameScene.swift
|
1
|
3624
|
//
// GameScene.swift
// stick test
//
// Created by Dmitriy Mitrophanskiy on 28.09.14.
// Copyright (c) 2014 Dmitriy Mitrophanskiy. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, AnalogStickProtocol {
var appleNode: SKSpriteNode?
var crossHair: SKSpriteNode?
let moveAnalogStick: AnalogStick = AnalogStick()
let rotateAnalogStick: AnalogStick = AnalogStick()
override func didMoveToView(view: SKView)
{
/* Setup your scene here */
let bgDiametr: CGFloat = 120
let thumbDiametr: CGFloat = 60
let joysticksRadius = bgDiametr / 2
// Setup left joystick
moveAnalogStick.bgNodeDiametr = bgDiametr
moveAnalogStick.thumbNodeDiametr = thumbDiametr
moveAnalogStick.position = CGPointMake(joysticksRadius + 15, joysticksRadius + 15)
moveAnalogStick.delagate = self
self.addChild(moveAnalogStick)
// Setup right joystick
rotateAnalogStick.bgNodeDiametr = bgDiametr
rotateAnalogStick.thumbNodeDiametr = thumbDiametr
rotateAnalogStick.position = CGPointMake(CGRectGetMaxX(self.frame) - joysticksRadius - 15, joysticksRadius + 15)
rotateAnalogStick.delagate = self
self.addChild(rotateAnalogStick)
// Crosshair setup
self.crossHair = SKSpriteNode(imageNamed: "crosshair-20")
if let cHNode = self.crossHair {
cHNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
}
self.addChild(self.crossHair!)
// apple
appleNode = SKSpriteNode(imageNamed: "apple")
if let aN = appleNode {
aN.physicsBody = SKPhysicsBody(texture: aN.texture, size: aN.size)
aN.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
aN.physicsBody?.affectedByGravity = false;
self.insertChild(aN, atIndex: 0)
}
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
//addOneApple()
}
func addOneApple()->Void {
let appleNode = SKSpriteNode(imageNamed: "apple");
appleNode.physicsBody = SKPhysicsBody(texture: appleNode.texture, size: appleNode.size)
appleNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
appleNode.physicsBody?.affectedByGravity = false;
self.addChild(appleNode)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
super.touchesBegan(touches, withEvent: event)
if let touch = touches.anyObject() as? UITouch {
appleNode?.position = touch.locationInNode(self)
println(touch.locationInNode(self))
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
// MARK: AnalogStickProtocol
func moveAnalogStick(analogStick: AnalogStick, velocity: CGPoint, angularVelocity: Float) {
if let aN = appleNode {
if analogStick.isEqual(moveAnalogStick)
{
println("move stick: \(velocity)")
aN.position = CGPointMake(aN.position.x + (velocity.x * 0.12), aN.position.y + (velocity.y * 0.12))
//println("Apple location on screen \(aN.position)")
} else if analogStick.isEqual(rotateAnalogStick)
{
println("move stick: \(angularVelocity)")
aN.zRotation = CGFloat(angularVelocity)
}
}
}
}
|
mit
|
88e6389153b6b6c8f44090c6503a8e49
| 37.553191 | 120 | 0.639073 | 4.408759 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Views/Cells/Chat/Info/MemberCell.swift
|
1
|
2668
|
//
// MemberCell.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/19/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
struct MemberCellData {
let member: UnmanagedUser
var nameText: String {
let utcText = "(UTC \(member.utcOffset))"
return "\(member.displayName) \(utcText)"
}
var statusColor: UIColor {
switch member.status {
case .online:
return .RCOnline()
case .away:
return .RCAway()
case .busy:
return .RCBusy()
case .offline:
return .RCInvisible()
}
}
}
final class MemberCell: UITableViewCell {
static let identifier = "MemberCell"
@IBOutlet weak var statusView: UIView! {
didSet {
statusView.layer.cornerRadius = statusView.layer.frame.width / 2
}
}
@IBOutlet weak var statusViewWidthConstraint: NSLayoutConstraint! {
didSet {
statusViewWidthConstraint?.constant = hideStatus ? 0 : 8
}
}
var hideStatus: Bool = false {
didSet {
statusViewWidthConstraint?.constant = hideStatus ? 0 : 8
}
}
@IBOutlet weak var avatarViewContainer: UIView! {
didSet {
avatarViewContainer.layer.masksToBounds = true
avatarViewContainer.layer.cornerRadius = 5
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.addSubview(avatarView)
}
}
lazy var avatarView: AvatarView = {
let avatarView = AvatarView()
avatarView.layer.cornerRadius = 4
avatarView.layer.masksToBounds = true
return avatarView
}()
@IBOutlet weak var nameLabel: UILabel!
var data: MemberCellData? = nil {
didSet {
statusView.backgroundColor = data?.statusColor
nameLabel.text = data?.nameText
avatarView.username = data?.member.username
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
// MARK: ReactorCell
extension MemberCell: ReactorPresenter {
var reactor: String {
set {
guard !newValue.isEmpty else { return }
if let user = User.find(username: newValue)?.unmanaged {
data = MemberCellData(member: user)
return
}
User.fetch(by: .username(newValue), completion: { user in
guard let user = user?.unmanaged else { return }
self.data = MemberCellData(member: user)
})
}
get {
return data?.member.username ?? ""
}
}
}
|
mit
|
5e88d21baa4bf2c67102bb5bb2659ed5
| 23.694444 | 76 | 0.575178 | 4.805405 | false | false | false | false |
kedar18/tumblr-image-download-library
|
DownloadManager/DownloadManager.swift
|
1
|
1309
|
//
// DownloadManager.swift
// DownloadManager
//
// Created by Kedar Navgire on 14/01/17.
// Copyright © 2017 kedar. All rights reserved.
//
import Foundation
import UIKit
open class DownloadManager
{
fileprivate static let session = URLSession.shared
fileprivate static let queue = DispatchQueue(label: "download_manager")
static let sharedCache: NSCache = { () -> NSCache<AnyObject, AnyObject> in
let cache = NSCache<AnyObject, AnyObject>()
cache.totalCostLimit = 60*1024*1024 // 60mb
return cache
}()
open class func downloadFrom(stringUrl:String,completion: @escaping (URL?,URLResponse?,Error?) -> Void)
{
guard let url = URL(string: stringUrl) else{
print("url failed to create")
return}
queue.async {
let downloadTask = session.downloadTask(with: url, completionHandler: completion)
downloadTask.resume()
}
}
open class func storeCache(forFile:AnyObject,cost:Int,key:String)
{
sharedCache.setObject(forFile, forKey: key as AnyObject, cost: cost)
}
open class func getCacheForFile(key:String) -> AnyObject
{
return sharedCache.object(forKey: key as NSString) as AnyObject
}
}
|
mit
|
ba9287a63ca017d53493e0c9d28d0225
| 26.829787 | 107 | 0.633792 | 4.525952 | false | false | false | false |
nicolastinkl/CardDeepLink
|
CardDeepLinkKit/CardDeepLinkKit/UIGitKit/Alamofire/Request.swift
|
1
|
19484
|
// Request.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as
managing its underlying `NSURLSessionTask`.
*/
internal class Request {
// MARK: - Properties
/// The delegate for the underlying task.
internal let delegate: TaskDelegate
/// The underlying task.
internal var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
internal let session: NSURLSession
/// The request sent or to be sent to the server.
internal var request: NSURLRequest? { return task.originalRequest }
/// The response received from the server, if any.
internal var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
internal var progress: NSProgress { return delegate.progress }
// MARK: - Lifecycle
internal init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: - Authentication
/**
Associates an HTTP Basic credential with the request.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
- returns: The request.
*/
internal func authenticate(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
-> Self
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
- parameter credential: The credential.
- returns: The request.
*/
internal func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: - Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
to write.
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
expected to read.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
internal func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
/**
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
This closure returns the bytes most recently received from the server, not including data from previous calls.
If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
also important to note that the `response` closure will be called with nil `responseData`.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
internal func stream(closure: (NSData -> Void)? = nil) -> Self {
if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataStream = closure
}
return self
}
// MARK: - State
/**
Suspends the request.
*/
internal func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
internal func resume() {
task.resume()
}
/**
Cancels the request.
*/
internal func cancel() {
if let
downloadDelegate = delegate as? DownloadTaskDelegate,
downloadTask = downloadDelegate.downloadTask
{
downloadTask.cancelByProducingResumeData { data in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
// MARK: - TaskDelegate
/**
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
executing all operations attached to the serial operation queue upon task completion.
*/
internal class TaskDelegate: NSObject {
/// The serial operation queue used to execute all operations after the task completes.
internal let queue: NSOperationQueue
let task: NSURLSessionTask
let progress: NSProgress
var data: NSData? { return nil }
var error: NSError?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.suspended = true
if #available(OSX 10.10, *) {
operationQueue.qualityOfService = NSQualityOfService.Utility
}
return operationQueue
}()
}
deinit {
queue.cancelAllOperations()
queue.suspended = false
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
{
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
{
var bodyStream: NSInputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
self.error = error
if let
downloadDelegate = self as? DownloadTaskDelegate,
userInfo = error.userInfo as? [String: AnyObject],
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
{
downloadDelegate.resumeData = resumeData
}
}
queue.suspended = false
}
}
}
// MARK: - DataTaskDelegate
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
private var totalBytesReceived: Int64 = 0
private var mutableData: NSMutableData
override var data: NSData? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
private var expectedContentLength: Int64?
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
private var dataStream: ((data: NSData) -> Void)?
override init(task: NSURLSessionTask) {
mutableData = NSMutableData()
super.init(task: task)
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: (NSURLSessionResponseDisposition -> Void))
{
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data: data)
} else {
mutableData.appendData(data)
}
totalBytesReceived += data.length
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
dataProgress?(
bytesReceived: Int64(data.length),
totalBytesReceived: totalBytesReceived,
totalBytesExpectedToReceive: totalBytesExpected
)
}
}
func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
{
var cachedResponse: NSCachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/**
The textual representation used when written to an output stream, which includes the HTTP method and URL, as
well as the response status code if a response has been received.
*/
internal var description: String {
var components: [String] = []
if let HTTPMethod = request?.HTTPMethod {
components.append(HTTPMethod)
}
if let URLString = request?.URL?.absoluteString {
components.append(URLString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joinWithSeparator(" ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
func cURLRepresentation() -> String {
var components = ["$ curl -i"]
guard let
request = self.request,
URL = request.URL,
host = URL.host
else {
return "$ curl command could not be created"
}
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(
host: host,
port: URL.port?.integerValue ?? 0,
`protocol`: URL.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
for credential in credentials {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if session.configuration.HTTPShouldSetCookies {
if let
cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let
HTTPBodyData = request.HTTPBody,
HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding)
{
let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(URL.absoluteString)\"")
return components.joinWithSeparator(" \\\n\t")
}
/// The textual representation used when written to an output stream, in the form of a cURL command.
internal var debugDescription: String {
return cURLRepresentation()
}
}
|
bsd-2-clause
|
a8fef60cbc2d54d73af90c2808344044
| 35.211896 | 162 | 0.615953 | 6.362508 | false | false | false | false |
RxSwiftCommunity/RxWebKit
|
Sources/RxWebKit/WKNavigationDelegateEvents+Rx.swift
|
1
|
16396
|
//
// WKNavigationDelegateEvents+Rx.swift
// RxWebKit
//
// Created by Bob Obi on 23.10.17.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import WebKit
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
extension Reactive where Base: WKWebView {
/// WKNavigationEvent emits a tuple that contains both
/// WKWebView + WKNavigation
public typealias WKNavigationEvent = (webView: WKWebView, navigation: WKNavigation)
/// WKNavigationFailedEvent emits a tuple that contains both
/// WKWebView + WKNavigation + Swift.Error
public typealias WKNavigationFailEvent = (webView: WKWebView, navigation: WKNavigation, error: Error)
/// ChallengeHandler this is exposed to the user on subscription
public typealias ChallengeHandler = (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
/// WKNavigationChallengeEvent emits a tuple event of WKWebView + challenge + ChallengeHandler
public typealias WKNavigationChallengeEvent = (webView: WKWebView, challenge: URLAuthenticationChallenge, handler: ChallengeHandler)
/// DecisionHandler this is the block exposed to the user on subscription
public typealias DecisionHandler = (WKNavigationResponsePolicy) -> Void
/// WKNavigationResponsePolicyEvent emits a tuple event of WKWebView + WKNavigationResponse + DecisionHandler
public typealias WKNavigationResponsePolicyEvent = ( webView: WKWebView, reponse: WKNavigationResponse, handler: DecisionHandler)
/// ActionHandler this is the block exposed to the user on subscription
public typealias ActionHandler = (WKNavigationActionPolicy) -> Void
/// WKNavigationActionPolicyEvent emits a tuple event of WKWebView + WKNavigationAction + ActionHandler
public typealias WKNavigationActionPolicyEvent = ( webView: WKWebView, action: WKNavigationAction, handler: ActionHandler)
/// Reactive wrapper for `navigationDelegate`.
public var delegate: DelegateProxy<WKWebView, WKNavigationDelegate> {
return RxWKNavigationDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didCommit navigation: WKNavigation!)`.
public var didCommitNavigation: ControlEvent<WKNavigationEvent> {
let source: Observable<WKNavigationEvent> = delegate
.methodInvoked(.didCommitNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
return (view, nav)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)`.
public var didStartProvisionalNavigation: ControlEvent<WKNavigationEvent> {
let source: Observable<WKNavigationEvent> = delegate
.methodInvoked(.didStartProvisionalNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
return (view, nav)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)`
public var didFinishNavigation: ControlEvent<WKNavigationEvent> {
let source: Observable<WKNavigationEvent> = delegate
.methodInvoked(.didFinishNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
return (view, nav)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webViewWebContentProcessDidTerminate(_ webView: WKWebView)`.
@available(iOS 9.0, *)
public var didTerminate: ControlEvent<WKWebView> {
let source: Observable<WKWebView> = delegate
.methodInvoked(.didTerminate)
.map { try castOrThrow(WKWebView.self, $0[0]) }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!)`.
public var didReceiveServerRedirectForProvisionalNavigation: ControlEvent<WKNavigationEvent> {
let source: Observable<WKNavigationEvent> = delegate
.methodInvoked(.didReceiveServerRedirectForProvisionalNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
return (view, nav)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error)`.
public var didFailNavigation: ControlEvent<WKNavigationFailEvent> {
let source: Observable<WKNavigationFailEvent> = delegate
.methodInvoked(.didFailNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
let error = try castOrThrow(Swift.Error.self, arg[2])
return (view, nav, error)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)`.
public var didFailProvisionalNavigation: ControlEvent<WKNavigationFailEvent> {
let source: Observable<WKNavigationFailEvent> = delegate
.methodInvoked(.didFailProvisionalNavigation)
.map { arg in
let view = try castOrThrow(WKWebView.self, arg[0])
let nav = try castOrThrow(WKNavigation.self, arg[1])
let error = try castOrThrow(Swift.Error.self, arg[2])
return (view, nav, error)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)`
public var didReceiveChallenge: ControlEvent<WKNavigationChallengeEvent> {
/// __ChallengeHandler is same as ChallengeHandler
/// They are interchangeable, __ChallengeHandler is for internal use.
/// ChallengeHandler is exposed to the user on subscription.
/// @convention attribute makes the swift closure compatible with Objc blocks
typealias __ChallengeHandler = @convention(block) (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
/*! @abstract Invoked when the web view needs to respond to an authentication challenge.
@param webView The web view that received the authentication challenge.
@param challenge The authentication challenge.
@param completionHandler The completion handler you must invoke to respond to the challenge. The
disposition argument is one of the constants of the enumerated type
NSURLSessionAuthChallengeDisposition. When disposition is NSURLSessionAuthChallengeUseCredential,
the credential argument is the credential to use, or nil to indicate continuing without a
credential.
@discussion If you do not implement this method, the web view will respond to the authentication challenge with the NSURLSessionAuthChallengeRejectProtectionSpace disposition.
*/
let source: Observable<WKNavigationChallengeEvent> = delegate
.sentMessage(.didReceiveChallenge)
.map { arg in
/// Extracting the WKWebView from the array at index zero
/// which is the first argument of the function signature
let view = try castOrThrow(WKWebView.self, arg[0])
/// Extracting the URLAuthenticationChallenge from the array at index one
/// which is the second argument of the function signature
let challenge = try castOrThrow(URLAuthenticationChallenge.self, arg[1])
/// Now you `Can't` transform closure easily because they are excuted
/// in the stack if try it you will get the famous error
/// `Could not cast value of type '__NSStackBlock__' (0x12327d1a8) to`
/// this is because closures are transformed into a system type which is `__NSStackBlock__`
/// the above mentioned type is not exposed to `developer`. So everytime
/// you execute a closure the compiler transforms it into this Object.
/// So you go through the following steps to get a human readable type
/// of the closure signature:
/// 1. closureObject is type of AnyObject to that holds the raw value from
/// the array.
var closureObject: AnyObject? = nil
/// 2. make the array mutable in order to access the `withUnsafeMutableBufferPointer`
/// fuctionalities
var mutableArg = arg
/// 3. Grab the closure at index 3 of the array, but we have to use the C-style
/// approach to access the raw memory underpinning the array and store it in closureObject
/// Now the object stored in the `closureObject` is `Unmanaged` and `some unspecified type`
/// the intelligent swift compiler doesn't know what sort of type it contains. It is Raw.
mutableArg.withUnsafeMutableBufferPointer { ptr in
closureObject = ptr[2] as AnyObject
}
/// 4. instantiate an opaque pointer to referenc the value of the `unspecified type`
let __challengeBlockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(closureObject as AnyObject).toOpaque())
/// 5. Here the magic happen we forcefully tell the compiler that anything
/// found at this memory address that is refrenced should be a type of
/// `__ChallengeHandler`!
let handler = unsafeBitCast(__challengeBlockPtr, to: __ChallengeHandler.self)
return (view, challenge, handler)
}
return ControlEvent(events: source)
/**
Reference:
This is a holy grail part for more information please read the following articles.
1: http://codejaxy.com/q/332345/ios-objective-c-memory-management-automatic-ref-counting-objective-c-blocks-understand-one-edge-case-of-block-memory-management-in-objc
2: http://www.galloway.me.uk/2012/10/a-look-inside-blocks-episode-2/
3: https://maniacdev.com/2013/11/tutorial-an-in-depth-guide-to-objective-c-block-debugging
4: get know how [__NSStackBlock__ + UnsafeRawPointer + unsafeBitCast] works under the hood
5: https://en.wikipedia.org/wiki/Opaque_pointer
6: https://stackoverflow.com/questions/43662363/cast-objective-c-block-nsstackblock-into-swift-3
*/
}
/// Reactive wrapper for `func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void)`
public var decidePolicyNavigationResponse: ControlEvent<WKNavigationResponsePolicyEvent> {
typealias __DecisionHandler = @convention(block) (WKNavigationResponsePolicy) -> ()
let source:Observable<WKNavigationResponsePolicyEvent> = delegate
.methodInvoked(.decidePolicyNavigationResponse).map { args in
let view = try castOrThrow(WKWebView.self, args[0])
let response = try castOrThrow(WKNavigationResponse.self, args[1])
var closureObject: AnyObject? = nil
var mutableArgs = args
mutableArgs.withUnsafeMutableBufferPointer { ptr in
closureObject = ptr[2] as AnyObject
}
let __decisionBlockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(closureObject as AnyObject).toOpaque())
let handler = unsafeBitCast(__decisionBlockPtr, to: __DecisionHandler.self)
return (view, response, handler)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for `func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void)`
public var decidePolicyNavigationAction: ControlEvent<WKNavigationActionPolicyEvent> {
typealias __ActionHandler = @convention(block) (WKNavigationActionPolicy) -> ()
let source:Observable<WKNavigationActionPolicyEvent> = delegate
.methodInvoked(.decidePolicyNavigationAction).map { args in
let view = try castOrThrow(WKWebView.self, args[0])
let action = try castOrThrow(WKNavigationAction.self, args[1])
var closureObject: AnyObject? = nil
var mutableArgs = args
mutableArgs.withUnsafeMutableBufferPointer { ptr in
closureObject = ptr[2] as AnyObject
}
let __actionBlockPtr = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(closureObject as AnyObject).toOpaque())
let handler = unsafeBitCast(__actionBlockPtr, to: __ActionHandler.self)
return (view, action, handler)
}
return ControlEvent(events: source)
}
}
extension Selector {
static let didCommitNavigation = #selector(WKNavigationDelegate.webView(_:didCommit:))
static let didStartProvisionalNavigation = #selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:))
static let didFinishNavigation = #selector(WKNavigationDelegate.webView(_:didFinish:))
static let didReceiveServerRedirectForProvisionalNavigation = #selector(WKNavigationDelegate.webView(_:didReceiveServerRedirectForProvisionalNavigation:))
static let didFailNavigation = #selector(WKNavigationDelegate.webView(_:didFail:withError:))
static let didFailProvisionalNavigation = #selector(WKNavigationDelegate.webView(_:didFailProvisionalNavigation:withError:))
static let didReceiveChallenge = #selector(WKNavigationDelegate.webView(_:didReceive:completionHandler:))
@available(iOS 9.0, *)
static let didTerminate = #selector(WKNavigationDelegate.webViewWebContentProcessDidTerminate(_:))
/// Xcode give error when selectors results into having same signature
/// because of swift style you get for example:
/// Ambiguous use of 'webView(_:decidePolicyFor:decisionHandler:)'
/// please see this link for further understanding
/// https://bugs.swift.org/browse/SR-3062
#if swift(>=5.7)
static let decidePolicyNavigationResponse = #selector(WKNavigationDelegate.webView(_:decidePolicyFor:decisionHandler:) as (WKNavigationDelegate) -> ((WKWebView, WKNavigationResponse, @escaping(WKNavigationResponsePolicy) -> Void) -> Void)?)
static let decidePolicyNavigationAction = #selector(WKNavigationDelegate.webView(_:decidePolicyFor:decisionHandler:) as (WKNavigationDelegate) -> ((WKWebView, WKNavigationAction, @escaping (WKNavigationActionPolicy) -> Void) -> Void)?)
#else
static let decidePolicyNavigationResponse = #selector(WKNavigationDelegate.webView(_:decidePolicyFor:decisionHandler:) as ((WKNavigationDelegate) -> (WKWebView, WKNavigationResponse, @escaping(WKNavigationResponsePolicy) -> Void) -> Void)?)
static let decidePolicyNavigationAction = #selector(WKNavigationDelegate.webView(_:decidePolicyFor:decisionHandler:) as ((WKNavigationDelegate) -> (WKWebView, WKNavigationAction, @escaping(WKNavigationActionPolicy) -> Void) -> Void)?)
#endif
}
|
mit
|
f9cd2a51dcb394e5fec3e6e3690b6df1
| 59.947955 | 244 | 0.687283 | 5.527647 | false | false | false | false |
tavultesoft/keymanweb
|
oem/firstvoices/ios/FirstVoices/DownloadStatusToolbar.swift
|
1
|
2752
|
/*
* DownloadStatusToolbar.swift
* FirstVoices app
*
* License: MIT
*
* Copyright © 2022 FirstVoices.
*
* Created by Shawn Schantz on 2022-03-25.
*
* Toolbar class to show activity indicator during downloads.
*
*/
import UIKit
class DownloadStatusToolbar: UIToolbar {
private var activityIndicator: UIActivityIndicatorView?
private var _navigationController: UINavigationController?
override init(frame: CGRect) {
super.init(frame: frame)
}
// Only here because it's required by Swift.
required init?(coder: NSCoder) {
super.init(coder: coder)
}
public var navigationController: UINavigationController? {
get {
return _navigationController
}
set {
_navigationController = newValue
}
}
/**
* Creates the spinner to show that activity is in progress.
*/
private func setupActivityIndicator() -> UIActivityIndicatorView {
let indicatorView = UIActivityIndicatorView(style: .gray)
indicatorView.center = CGPoint(x: frame.width - indicatorView.frame.width,
y: frame.height * 0.5)
indicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleBottomMargin]
indicatorView.startAnimating()
return indicatorView
}
private func clearSubviews() {
activityIndicator?.removeFromSuperview()
}
/*
public func startAnimating() {
self.activityIndicator = self.setupActivityIndicator()
}
*/
public func hideStatus() {
if !(navigationController?.isToolbarHidden ?? true) {
navigationController!.setToolbarHidden(true, animated: true)
}
}
public func displayStatus(_ withIndicator: Bool, duration: TimeInterval? = nil) {
clearSubviews()
if withIndicator {
activityIndicator = setupActivityIndicator()
addSubview(activityIndicator!)
}
// Automatically display if we're hidden and have access to our owning UINavigationController.
if navigationController?.isToolbarHidden ?? false {
navigationController!.setToolbarHidden(false, animated: true)
}
if let timeout = duration {
hideAfterDelay(timeout: timeout)
}
}
private func hideAfterDelay(timeout: TimeInterval) {
Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(self.delayedHide),
userInfo: nil, repeats: false)
}
@objc private func delayedHide() {
// If the navigation controller exists and the toolbar is not hidden. The ! + true literal together
// give false for the condition when the navigation controller does not exist.
if !(navigationController?.isToolbarHidden ?? true) {
navigationController!.setToolbarHidden(true, animated: true)
}
}
}
|
apache-2.0
|
70700ab73e7b8d887c32b0bf0bf37dfe
| 26.51 | 104 | 0.695747 | 5.047706 | false | false | false | false |
radazzouz/firefox-ios
|
UITests/ClearPrivateDataTests.swift
|
1
|
10305
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
import UIKit
import GCDWebServers
class ClearPrivateDataTests: KIFTestCase, UITextFieldDelegate {
/*
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
webRoot = SimplePageServer.start()
BrowserUtils.dismissFirstRunUI(tester())
}
override func tearDown() {
BrowserUtils.resetToAboutHome(tester())
BrowserUtils.clearPrivateData(tester: tester())
}
func visitSites(noOfSites: Int) -> [(title: String, domain: String, dispDomain: String, url: String)] {
var urls: [(title: String, domain: String, dispDomain: String, url: String)] = []
for pageNo in 1...noOfSites {
tester().tapView(withAccessibilityIdentifier: "url")
let url = "\(webRoot)/numberedPage.html?page=\(pageNo)"
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
let dom = URL(string: url)!.normalizedHost!
let index = dom.startIndex.advancedBy(7)
let dispDom = dom.substringToIndex(index) // On IPhone, it only displays first 8 chars
let tuple: (title: String, domain: String, dispDomain: String, url: String) = ("Page \(pageNo)", dom, dispDom, url)
urls.append(tuple)
}
BrowserUtils.resetToAboutHome(tester())
return urls
}
func anyDomainsExistOnTopSites(_ domains: Set<String>, fulldomains: Set<String>) {
for domain in domains {
if self.tester().viewExistsWithLabel(domain) {
return
}
}
for domain in fulldomains {
if self.tester().viewExistsWithLabel(domain) {
return
}
}
XCTFail("Couldn't find any domains in top sites.")
}
func testRemembersToggles(_ swipe: Bool) {
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe:swipe, tester: tester())
BrowserUtils.openClearPrivateDataDialog(swipe, tester: tester())
// Ensure the toggles match our settings.
[
(BrowserUtils.Clearable.Cache, "0"),
(BrowserUtils.Clearable.Cookies, "0"),
(BrowserUtils.Clearable.OfflineData, "0"),
(BrowserUtils.Clearable.History, "1")
].forEach { clearable, switchValue in
XCTAssertNotNil(tester().waitForView(withAccessibilityLabel: clearable.rawValue, value: switchValue, traits: UIAccessibilityTraitNone))
}
BrowserUtils.closeClearPrivateDataDialog(tester())
}
func testClearsTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let dispDomains = Set<String>(urls.map { $0.dispDomain })
let fullDomains = Set<String>(urls.map { $0.domain })
tester().tapView(withAccessibilityLabel: "Top sites")
// Only one will be found -- we collapse by domain.
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe: false, tester: tester())
XCTAssertFalse(tester().viewExistsWithLabel(urls[0].title), "Expected to have removed top site panel \(urls[0])")
XCTAssertFalse(tester().viewExistsWithLabel(urls[1].title), "We shouldn't find the other URL, either.")
}
func testDisabledHistoryDoesNotClearTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let dispDomains = Set<String>(urls.map { $0.dispDomain })
let fullDomains = Set<String>(urls.map { $0.domain })
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.History]), swipe: false, tester: tester())
anyDomainsExistOnTopSites(dispDomains, fulldomains: fullDomains)
}
func testClearsHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapView(withAccessibilityLabel: "History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.History], swipe: false, tester: tester())
tester().tapView(withAccessibilityLabel: "Bookmarks")
tester().tapView(withAccessibilityLabel: "History")
XCTAssertFalse(tester().viewExistsWithLabel(url1), "Expected to have removed history row \(url1)")
XCTAssertFalse(tester().viewExistsWithLabel(url2), "Expected to have removed history row \(url2)")
}
func testDisabledHistoryDoesNotClearHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapView(withAccessibilityLabel: "History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.History]), swipe: false, tester: tester())
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to not have removed history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to not have removed history row \(url2)")
}
func testClearsCookies() {
tester().tapView(withAccessibilityIdentifier: "url")
let url = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
// Set and verify a dummy cookie value.
setCookies(webView, cookie: "foo=bar")
var cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are not cleared when Cookies is deselected.
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.Cookies]), swipe: true, tester: tester())
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are cleared when Cookies is selected.
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.Cookies], swipe: true, tester: tester())
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "")
XCTAssertNil(cookies.localStorage)
XCTAssertNil(cookies.sessionStorage)
}
func testClearsCache() {
let cachedServer = CachedPageServer()
let cacheRoot = cachedServer.start()
let url = "\(cacheRoot)/cachedPage.html"
tester().tapView(withAccessibilityIdentifier: "url")
tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Cache test")
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
let requests = cachedServer.requests
// Verify that clearing non-cache items will keep the page in the cache.
BrowserUtils.clearPrivateData(BrowserUtils.AllClearables.subtracting([BrowserUtils.Clearable.Cache]), swipe: true, tester: tester())
webView.reload()
XCTAssertEqual(cachedServer.requests, requests)
// Verify that clearing the cache will fire a new request.
BrowserUtils.clearPrivateData([BrowserUtils.Clearable.Cache], swipe: true, tester: tester())
webView.reload()
XCTAssertEqual(cachedServer.requests, requests + 1)
}
fileprivate func setCookies(_ webView: WKWebView, cookie: String) {
let expectation = self.expectation(description: "Set cookie")
webView.evaluateJavaScript("document.cookie = \"\(cookie)\"; localStorage.cookie = \"\(cookie)\"; sessionStorage.cookie = \"\(cookie)\";") { result, _ in
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
fileprivate func getCookies(_ webView: WKWebView) -> (cookie: String, localStorage: String?, sessionStorage: String?) {
var cookie: (String, String?, String?)!
let expectation = self.expectation(description: "Got cookie")
webView.evaluateJavaScript("JSON.stringify([document.cookie, localStorage.cookie, sessionStorage.cookie])") { result, _ in
let cookies = JSON(parseJSON: result as! String).asArray!
cookie = (cookies[0].asString!, cookies[1].asString, cookies[2].asString)
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
return cookie
}
*/
}
/// Server that keeps track of requests.
private class CachedPageServer {
var requests = 0
func start() -> String {
let webServer = GCDWebServer()
webServer?.addHandler(forMethod: "GET", path: "/cachedPage.html", request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
self.requests += 1
return GCDWebServerDataResponse(html: "<html><head><title>Cached page</title></head><body>Cache test</body></html>")
}
webServer?.start(withPort: 0, bonjourName: nil)
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://127.0.0.1:\(webServer?.port)"
return webRoot
}
}
|
mpl-2.0
|
8f1f3390d7e459d6a4e9e5774e91a2c0
| 45.004464 | 161 | 0.67016 | 5.01216 | false | true | false | false |
chicio/Sales-Taxes
|
SalesTaxesSwift/Controller/ShoppingViewController.swift
|
1
|
5477
|
//
// ViewController.swift
// SalesTaxesSwift
//
// Created by Fabrizio Duroni on 20/11/2016.
// Copyright © 2016 Fabrizio Duroni. All rights reserved.
//
import UIKit
class ShoppingViewController: UITableViewController {
/// Product list that could be selected.
private var productList:[Product] = [Product]()
/// Shopping cart.
private var shoppingCart:ShoppingCart = ShoppingCart()
override func viewDidLoad() {
super.viewDidLoad()
//Static load (demo...)
self.productList.append(Product(aName:"book", aPrice:12.49, aType:.Book, aOrigin:.Local))
self.productList.append(Product(aName:"music", aPrice:14.99, aType:.Other, aOrigin:.Local))
self.productList.append(Product(aName:"chocolate", aPrice:0.85, aType:.Food, aOrigin:.Local))
self.productList.append(Product(aName:"imported box of chocolate", aPrice:10.00, aType:.Food, aOrigin:.Imported))
self.productList.append(Product(aName:"imported perfume chanel", aPrice:47.50, aType:.Other, aOrigin:.Imported))
self.productList.append(Product(aName:"imported perfume armani", aPrice:27.99, aType:.Other, aOrigin:.Imported))
self.productList.append(Product(aName:"bottle of perfume", aPrice:18.99, aType:.Other, aOrigin:.Local))
self.productList.append(Product(aName:"packet of headachepills", aPrice:9.75, aType:.Medical, aOrigin:.Local))
self.productList.append(Product(aName:"box of imported chocolates", aPrice:11.25, aType:.Food, aOrigin:.Imported))
}
//MARK: UITableView delegate
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.productList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ShoppingCell = tableView.dequeueReusableCell(withIdentifier:"ShoppingCell", for:indexPath) as! ShoppingCell
let product:Product = self.productList[indexPath.row]
cell.productName.text = product.productName
cell.productType.text = product.productType.rawValue
cell.productOrigin.text = product.productOrigin.rawValue
cell.productPrice.text = String(format:"%.2f", product.productPrice)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell:UITableViewCell = tableView.cellForRow(at: indexPath)!
let product:Product = self.productList[indexPath.row]
if cell.accessoryType == .checkmark {
//Remove product from shopping cart.
self.shoppingCart.remove(shoppingItemName: product.productName)
cell.accessoryType = .none
} else {
//Add product to shopping cart.
//Use UIAlertController to get the quantity for the product selected.
let quantityAlertController = UIAlertController(title: "Quantity",
message: "Insert quantity",
preferredStyle: .alert)
quantityAlertController.addTextField(configurationHandler:{ (textField) in
textField.placeholder = "Quantity"
textField.text = "1"
})
quantityAlertController.addAction(UIAlertAction(title:"OK",
style:UIAlertActionStyle.default,
handler:{ (action) in
if let quantityField = quantityAlertController.textFields?[0] {
var quantity:Int = Int(quantityField.text!)!
if quantity == 0 {
quantity = 1
}
let item = ShoppingItem(aProduct: product, aQuantity:quantity, aTaxCalculator: TaxCalculator())
self.shoppingCart.add(aShoppingItem: item)
}
})
)
self.present(quantityAlertController, animated: true, completion: nil)
cell.accessoryType = .checkmark
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75.0
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ReceiptSegue" {
let receiptController:ReceiptViewController = segue.destination as! ReceiptViewController
receiptController.receipt = Receipt(aShoppingCart: self.shoppingCart)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
318fe5c6c0e7fa7b6bcfcc335b094792
| 41.449612 | 124 | 0.557889 | 5.553753 | false | false | false | false |
joerocca/GitHawk
|
Pods/Apollo/Sources/Apollo/GraphQLQueryWatcher.swift
|
2
|
1767
|
import Dispatch
/// A `GraphQLQueryWatcher` is responsible for watching the store, and calling the result handler with a new result whenever any of the data the previous result depends on changes.
public final class GraphQLQueryWatcher<Query: GraphQLQuery>: Cancellable, ApolloStoreSubscriber {
weak var client: ApolloClient?
let query: Query
let handlerQueue: DispatchQueue
let resultHandler: OperationResultHandler<Query>
private var context = 0
private weak var fetching: Cancellable?
private var dependentKeys: Set<CacheKey>?
init(client: ApolloClient, query: Query, handlerQueue: DispatchQueue, resultHandler: @escaping OperationResultHandler<Query>) {
self.client = client
self.query = query
self.handlerQueue = handlerQueue
self.resultHandler = resultHandler
client.store.subscribe(self)
}
/// Refetch a query from the server.
public func refetch() {
fetch(cachePolicy: .fetchIgnoringCacheData)
}
func fetch(cachePolicy: CachePolicy) {
fetching = client?._fetch(query: query, cachePolicy: cachePolicy, context: &context, queue: handlerQueue) { (result, error) in
self.dependentKeys = result?.dependentKeys
self.resultHandler(result, error)
}
}
/// Cancel any in progress fetching operations and unsubscribe from the store.
public func cancel() {
fetching?.cancel()
client?.store.unsubscribe(self)
}
func store(_ store: ApolloStore, didChangeKeys changedKeys: Set<CacheKey>, context: UnsafeMutableRawPointer?) {
if context == &self.context { return }
guard let dependentKeys = dependentKeys else { return }
if !dependentKeys.isDisjoint(with: changedKeys) {
fetch(cachePolicy: .returnCacheDataElseFetch)
}
}
}
|
mit
|
f9479f9d19879f8ca6ecffc46931f3d2
| 32.980769 | 180 | 0.726655 | 4.827869 | false | false | false | false |
skyylex/HaffmanSwift
|
Haffman.playground/Sources/BitCoding.swift
|
1
|
5799
|
//
// BitCoding.swift
// HaffmanCoding
//
// Created by Yury Lapitsky on 12/14/15.
// Copyright © 2015 skyylex. All rights reserved.
//
import Foundation
public let bytesInUInt32 = 4
public typealias DoubleWord = UInt32
public let bitsInByte = 8
public let doubleWordBitsAmount = sizeof(DoubleWord) * bitsInByte
public struct BytesSequence {
public let bytes: [DoubleWord]
public let digitsLeft: Int
}
public class BitsDecoder {
public static func transform(doubleWord: DoubleWord) -> String {
return String(doubleWord, radix: 2).fillWithZeros(doubleWordBitsAmount)
}
public static func transform(doubleWords: [DoubleWord]) -> String {
return doubleWords.reduce("") { current, next -> String in current + transform(next) }
}
private static func fixLastSymbols(doubleWord: DoubleWord, decodingMap: [String: Character], digitsLeft: Int, decoded: String) -> String? {
if (digitsLeft == 0) {
return decoded
} else {
let unwantedStringRange = ((doubleWordBitsAmount - digitsLeft)...(doubleWordBitsAmount - 1))
let digitsString = transform(doubleWord)
let unwantedCharaters = Array(digitsString.characters)[unwantedStringRange]
if let minimum = findShortestKeyLength(decodingMap) {
let unwantedString = decode(String(unwantedCharaters), decodingMap: decodingMap, minDigitsAmount: minimum)
let endIndex = decoded.characters.count - 1
let startIndex = endIndex - unwantedString.characters.count
let fixed = Array(decoded.characters)[(0...startIndex)]
return String(fixed)
} else {
return nil
}
}
}
public static func decode(doubleWords: [DoubleWord], decodingMap:[String: Character], digitsLeft: Int) -> String? {
let combinedString = transform(doubleWords)
if let mininumAmount = findShortestKeyLength(decodingMap) {
let decoded = decode(combinedString, decodingMap: decodingMap, minDigitsAmount:mininumAmount)
let lastDoubleWord = doubleWords[doubleWords.count - 1]
return fixLastSymbols(lastDoubleWord, decodingMap: decodingMap, digitsLeft: digitsLeft, decoded: decoded)
} else {
return nil
}
}
private static func findShortestKeyLength(decodingMap:[String: Character]) -> Int? {
if let first = decodingMap.keys.first {
let randomMinimum = first.characters.count
return decodingMap.keys.reduce(randomMinimum) { currentMinimum, next -> Int in
let next = next.characters.count
let min = (currentMinimum <= next) ? currentMinimum : next
return min
}
} else {
return nil
}
}
private static func decode(encodedString: String, decodingMap: [String: Character], minDigitsAmount: Int) -> String {
let (_, decoded) = encodedString.characters.reduce(("", "")) { current, nextSymbol -> (String, String) in
let buffer = current.0
let decoded = current.1
if buffer.characters.count < minDigitsAmount {
return (buffer + String(nextSymbol), decoded)
} else {
if let decodedSymbol = decodingMap[buffer] {
return ("" + String(nextSymbol), decoded + String(decodedSymbol))
}
}
return (buffer + String(nextSymbol), decoded)
}
return decoded
}
}
public class BitsCoder {
public static func transform(bits: [Bit]) -> DoubleWord {
let endIndex = (bits.count - 1)
let startIndex = 0
let result = (startIndex...endIndex).reduce(DoubleWord(0)) { currentSum, nextIndex -> DoubleWord in
return currentSum + DoubleWord(bits[nextIndex].rawValue << (endIndex - nextIndex))
}
return result
}
public static func transform(sequences: [[Bit]]) -> BytesSequence {
var buffer = DoubleWord(0)
var storage = [DoubleWord]()
var digitsLeft = doubleWordBitsAmount
for digitsSequence in sequences {
let digitsAmount = digitsSequence.count
if (digitsLeft == 0) {
storage.append(buffer)
buffer = DoubleWord(0)
digitsLeft = doubleWordBitsAmount
}
if (digitsLeft < digitsAmount) {
let diff = digitsAmount - digitsLeft
let digitsPartLeft = Array(digitsSequence[0...(digitsLeft - 1)])
let digitsPartRight = Array(digitsSequence[(digitsLeft)...(digitsLeft + diff) - 1])
let doubleWordPartLeft = transform(digitsPartLeft)
let doubleWordPartRight = transform(digitsPartRight)
buffer = buffer | doubleWordPartLeft
storage.append(buffer)
let shiftedRightPart = (doubleWordPartRight << (DoubleWord(doubleWordBitsAmount) - DoubleWord(diff)))
buffer = DoubleWord(0) | shiftedRightPart
digitsLeft = doubleWordBitsAmount - diff
} else {
let doubleWord = transform(digitsSequence)
let shiftLength = DoubleWord(digitsLeft - digitsAmount)
let shiftedNumber = doubleWord << shiftLength
buffer = buffer | shiftedNumber
digitsLeft = Int(shiftLength)
}
}
if digitsLeft < doubleWordBitsAmount {
storage.append(buffer)
}
return BytesSequence(bytes: storage, digitsLeft: digitsLeft)
}
}
|
mit
|
d9e522759700bed22241a8b5cce71cf8
| 38.993103 | 143 | 0.601759 | 4.799669 | false | false | false | false |
bignerdranch/DeferredTCPSocket
|
DeferredTCPSocket/DeferredTCPSocket/DeferredIOOperation.swift
|
1
|
2264
|
//
// DeferredIOOperation.swift
// DeferredIO
//
// Created by John Gallagher on 9/12/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
public var DeferredIOOperationLeeway = UInt64(NSEC_PER_SEC / 20)
class DeferredIOOperation: NSOperation {
let queue: dispatch_queue_t
let source: dispatch_source_t
private let timeout: NSTimeInterval?
private let timerSource: dispatch_source_t
private var _executing: Bool = false {
willSet {
self.willChangeValueForKey("isExecuting")
}
didSet {
self.didChangeValueForKey("isExecuting")
}
}
override var executing: Bool {
get { return _executing }
set { _executing = newValue }
}
override var asynchronous: Bool { return true }
init(queue: dispatch_queue_t, source: dispatch_source_t, timerSource: dispatch_source_t, timeout: NSTimeInterval? = nil) {
self.queue = queue
self.source = source
self.timerSource = timerSource
self.timeout = timeout
super.init()
}
func resumeSources() {
if let timeout = timeout {
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(NSTimeInterval(NSEC_PER_SEC)*timeout))
dispatch_source_set_timer(timerSource, when, 0, DeferredIOOperationLeeway)
dispatch_source_set_event_handler(timerSource) { [weak self] in
self?.handleTimeout()
return
}
dispatch_resume(timerSource)
}
dispatch_source_set_event_handler(source) { [weak self] in
self?.handleEvent()
return
}
dispatch_resume(source)
}
func suspendSources() {
if let timeout = timeout {
dispatch_suspend(timerSource)
}
dispatch_suspend(source)
}
func handleTimeout() {
assert(false, "subclasses must implement handleTimeout")
}
func handleEvent() {
assert(false, "subclasses must implement handleEvent")
}
func willChangeValueForKeyFinished() {
self.willChangeValueForKey("isFinished")
}
func didChangeValueForKeyFinished() {
self.didChangeValueForKey("isFinished")
}
}
|
mit
|
c05df84a38499770fd6f9fb22a4393e9
| 25.964286 | 126 | 0.620583 | 4.546185 | false | false | false | false |
jacobwhite/firefox-ios
|
SyncTests/Mocking.swift
|
9
|
2658
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftyJSON
@testable import Sync
class MockBackoffStorage: BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp?
func clearServerBackoff() {
serverBackoffUntilLocalTimestamp = nil
}
func isInBackoff(_ now: Timestamp) -> Timestamp? {
return nil
}
}
class MockSyncCollectionClient<T: CleartextPayloadJSON>: Sync15CollectionClient<T> {
let uploader: BatchUploadFunction
let infoConfig: InfoConfiguration
init(uploader: @escaping BatchUploadFunction,
infoConfig: InfoConfiguration,
collection: String,
encrypter: RecordEncrypter<T>,
client: Sync15StorageClient = getClient(server: getServer(preStart: { _ in })),
serverURI: URL = URL(string: "http://localhost/collections")!) {
self.uploader = uploader
self.infoConfig = infoConfig
super.init(client: client, serverURI: serverURI, collection: collection, encrypter: encrypter)
}
override func newBatch(ifUnmodifiedSince: Timestamp? = nil, onCollectionUploaded: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> Sync15BatchClient<T> {
return Sync15BatchClient(config: self.infoConfig,
ifUnmodifiedSince: ifUnmodifiedSince,
serializeRecord: self.serializeRecord,
uploader: self.uploader,
onCollectionUploaded: onCollectionUploaded)
}
}
// MARK: Various mocks
// Non-encrypting 'encrypter'.
func getEncrypter() -> RecordEncrypter<CleartextPayloadJSON> {
let serializer: (Record<CleartextPayloadJSON>) -> JSON? = { $0.payload.json }
let factory: (String) -> CleartextPayloadJSON = { CleartextPayloadJSON($0) }
return RecordEncrypter(serializer: serializer, factory: factory)
}
func getClient(server: MockSyncServer) -> Sync15StorageClient {
let url = server.baseURL.asURL!
let authorizer: Authorizer = identity
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage())
}
func getServer(username: String = "1234567", preStart: (MockSyncServer) -> Void) -> MockSyncServer {
let server = MockSyncServer(username: username)
preStart(server)
server.start()
return server
}
|
mpl-2.0
|
df3ac8402c6d6a064f322149260efd3b
| 38.088235 | 168 | 0.692626 | 4.763441 | false | true | false | false |
slepcat/mint
|
MINT/MintCommands.swift
|
1
|
16418
|
//
// MintCommands.swift
// MINT
//
// Created by NemuNeko on 2015/03/19.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
class AddLeaf:MintCommand {
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
let leafType : String
let category : String
var pos : NSPoint
init(toolName: String, setName: String, pos:NSPoint) {
leafType = toolName + "\n"
category = setName
self.pos = pos
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// add leaf
if let uid = interpreter.newSExpr(leafType) {
// add view controller and view
let leafctrl = workspace.addLeaf(leafType, setName: category, pos: pos, uid: uid)
// register to standard err output port
if let port = MintStdPort.get.errport as? MintSubject {
port.registerObserver(leafctrl)
}
// post process for link and ref
let leaf = interpreter.lookup(uid)
if let context = context(ofLeaf: leaf.target) {
if context == .Display {
let proc = post_process(context)
proc(leaf.target, leaf.conscell)
}
}
interpreter.run_around(uid)
workspace.edited = true
}
}
func undo() {
}
func redo() {
}
}
class AddOperand:MintCommand {
let leafid : UInt
let newvalue : String
var addedargid : UInt = 0
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(leafid: UInt, newvalue:String) {
self.leafid = leafid
self.newvalue = newvalue
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
addedargid = interpreter.add_arg(leafid, rawstr: newvalue)
interpreter.run_around(leafid)
// post process
let added = interpreter.lookup(addedargid)
if let context = context(ofElem: added.target) {
let post_proc = post_process(context)
post_proc(added.target, added.conscell)
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class SetOperand:MintCommand {
let leafid : UInt
let argid : UInt
let newvalue : String
var oldarg : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(argid: UInt, leafid: UInt, newvalue:String) {
self.leafid = leafid
self.argid = argid
self.newvalue = newvalue
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// save old value for undo or exception restre operation
let old = interpreter.lookup(argid)
oldarg = old.target
// pre process
if let context = context(ofElem: old.target) {
let prev_proc = pre_process(context)
prev_proc(old.target, old.conscell)
}
let uid = interpreter.overwrite_arg(argid, leafid: leafid, rawstr: newvalue)
interpreter.run_around(leafid)
// post process
let newexp = interpreter.lookup(uid)
if let context = context(ofElem: newexp.target) {
let post_proc = post_process(context)
post_proc(newexp.target, newexp.conscell)
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class RemoveOperand:MintCommand {
let argid : UInt
let leafid : UInt
var oldarg : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(argid: UInt, ofleafid: UInt) {
self.argid = argid
self.leafid = ofleafid
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// save old value for undo or exception restre operation
let old = interpreter.lookup(argid)
oldarg = old.target
// pre process
if let context = context(ofElem: old.target) {
let prev_proc = pre_process(context)
prev_proc(old.target, old.conscell)
var wasGlobal = false
if let sym = old.target as? MSymbol {
wasGlobal = interpreter.isSymbol_as_global(sym)
}
interpreter.remove_arg(argid, ofleafid: leafid)
interpreter.run_around(leafid)
switch context {
case .DeclVar, .Define:
if wasGlobal {
// if changed declaration is global, reset all ref links
for tree in self.interpreter.trees {
self.rec_add_ref_links(ofleaf: tree)
}
} else {
// if changed declaration is local, add ref links of the tree
if let i = self.interpreter.lookup_treeindex_of(leafid) {
self.rec_add_ref_links(ofleaf: self.interpreter.trees[i])
}
}
default:
break
}
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class LinkOperand:MintCommand {
let returnLeafID : UInt
let argumentID : UInt
let argumentLeafID : UInt
var oldvalue : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(retLeafID: UInt, argID: UInt, argleafID: UInt) {
returnLeafID = retLeafID
argumentLeafID = argleafID
argumentID = argID
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// loop check
if interpreter.lookup_treeindex_of(returnLeafID) == interpreter.lookup_treeindex_of(argumentLeafID) {
print("🚫Cannot link within a tree", terminator:"\n")
return
}
// save old value for undo
let old = interpreter.lookup(argumentID)
oldvalue = old.target
// pre process for overwritten operand
if let context = context(ofElem: old.target) {
let prev_proc = pre_process(context)
prev_proc(old.target, old.conscell)
}
// pre process for linked (parent of the operand) leaf
let leaf = interpreter.lookup(argumentLeafID)
if let context = context(ofLeaf: leaf.target) {
if context == .Define {
let pre_proc = pre_process(context)
pre_proc(leaf.target, leaf.conscell)
}
}
// pre process for linking leaf
let added = interpreter.lookup(returnLeafID)
let prev_proc = pre_process(.Link)
prev_proc(added.target, added.conscell)
interpreter.link_toArg(argumentLeafID, uid: argumentID, fromUid: returnLeafID)
interpreter.run_around(argumentLeafID)
// update ref links to new scope
// for leaf of return value
let post_added = interpreter.lookup(returnLeafID)
let post_proc = post_process(.Link)
post_proc(post_added.target, post_added.conscell)
// if removed arg is link to another leaf, update ref of the leaf to new scope
if let context = context(ofElem: old.target) {
if context == .Link {
let post_proc = post_process(context)
let removed = interpreter.lookup(old.target.uid)
post_proc(removed.target, removed.conscell)
}
}
// psot process for linked (parent of the operand) leaf
if let context = context(ofLeaf: leaf.target) {
if context == .Define {
let post_proc = post_process(context)
post_proc(leaf.target, leaf.conscell)
}
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class RemoveLink:MintCommand {
let argleafID : UInt
let argumentID : UInt
var oldvalue : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(rmArgID: UInt, argID: UInt) {
argleafID = rmArgID
argumentID = argID
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// save old value for undo
let old = interpreter.lookup(argumentID)
oldvalue = old.target
// pre process
let pre_argleaf = interpreter.lookup(argleafID)
let pre_retleaf = interpreter.lookup(argumentID)
let pre_proc = pre_process(.Link)
pre_proc(pre_argleaf.target, pre_argleaf.conscell)
pre_proc(pre_retleaf.target, pre_retleaf.conscell)
interpreter.unlink_arg(argumentID, ofleafid: argleafID)
//interpreter.run_around(argumentID)
interpreter.run_around(argleafID)
// post process
let argleaf = interpreter.lookup(argleafID)
let retleaf = interpreter.lookup(argumentID)
let post_proc = post_process(.Link)
post_proc(argleaf.target, argleaf.conscell)
post_proc(retleaf.target, retleaf.conscell)
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class SetReference:MintCommand {
let returnLeafID : UInt
let argumentID : UInt
let argumentLeafID : UInt
var oldvalue : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(retLeafID: UInt, argID: UInt, argleafID: UInt) {
returnLeafID = retLeafID
argumentLeafID = argleafID
argumentID = argID
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
// save old value for undo
let old = interpreter.lookup(argumentID)
oldvalue = old.target
// pre process
if let context = context(ofElem: old.target) {
if context != .DeclVar {
let pre_proc = pre_process(context)
pre_proc(old.target, old.conscell)
} else {
return
}
}
if let newargid = interpreter.set_ref(argumentID, ofleafid: argumentLeafID, symbolUid: returnLeafID) {
interpreter.run_around(argumentLeafID)
let newarg = interpreter.lookup(newargid)
let post_proc = post_process(MintLeafContext.VarRef)
post_proc(newarg.target, newarg.conscell)
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
class RemoveReference:MintCommand {
let argleafID : UInt
let argumentID : UInt
var oldvalue : SExpr? = nil
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(rmArgID: UInt, argID: UInt) {
argleafID = rmArgID
argumentID = argID
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
let res = interpreter.lookup(argumentID)
oldvalue = res.target
if let _ = res.target as? MSymbol {
let pre_proc = pre_process(.VarRef)
pre_proc(res.target, res.conscell)
interpreter.remove_arg(argumentID, ofleafid: argleafID)
interpreter.run_around(argleafID)
modelView.setNeedDisplay()
}
}
func undo() {
}
func redo() {
}
}
class RemoveLeaf:MintCommand {
let removeID : UInt
var oldvalue : SExpr = MNull()
weak var workspace:MintWorkspaceController!
weak var modelView: MintModelViewController!
weak var interpreter: MintInterpreter!
init(removeID: UInt) {
self.removeID = removeID
}
func prepare(_ workspace: MintWorkspaceController, modelView: MintModelViewController, interpreter: MintInterpreter) {
self.workspace = workspace
self.modelView = modelView
self.interpreter = interpreter
}
func execute() {
let old = interpreter.lookup(removeID)
oldvalue = old.target
if let context = context(ofLeaf: old.target) {
let pre_proc = pre_process(context)
pre_proc(old.target, old.conscell)
var leaves : [(target: SExpr, conscell: SExpr)] = []
if context == .Link {
if let cons = interpreter.lookup_leaf_of(old.conscell.uid) {
leaves.append(interpreter.lookup(cons))
}
let opds = delayed_list_of_values(old.target)
for op in opds {
if let pair = op as? Pair {
leaves.append((pair, old.target))
}
}
}
interpreter.remove(removeID)
if let leaf = workspace.removeLeaf(removeID), let port = MintStdPort.get.errport as? MintSubject {
port.removeObserver(leaf)
}
if context != .Link {
let post_proc = post_process(context)
post_proc(MNull(), MNull())
} else {
let post_proc = post_process(.Link)
for leaf in leaves {
post_proc(leaf.target, leaf.conscell)
}
}
}
workspace.edited = true
modelView.setNeedDisplay()
}
func undo() {
}
func redo() {
}
}
|
gpl-3.0
|
a7862a15c5a1c0e70f75fe1311cea6e9
| 27.396194 | 122 | 0.564857 | 4.62338 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
EnjoyUniversity/EnjoyUniversity/Classes/View/Activity/EUActivityCell.swift
|
1
|
1708
|
//
// EUActivityCell.swift
// EnjoyUniversity
//
// Created by lip on 17/3/7.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
import Kingfisher
class EUActivityCell: UITableViewCell {
var activityVM:ActivityViewModel?{
didSet{
activityName.text = activityVM?.activitymodel.avTitle
activityTime.text = activityVM?.startTime
activityLocation.text = activityVM?.activitymodel.avPlace
activityPrice.text = activityVM?.price
if activityVM?.isFinished ?? true{
activityIcon.image = UIImage(named: "av_finished")
activityIcon.contentMode = .scaleAspectFit
}else{
let iconurl = URL(string: activityVM?.imageURL ?? "")
activityIcon.kf.setImage(with: iconurl,
placeholder: UIImage(named: "eu_placeholder"),
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
}
}
@IBOutlet weak var activityIcon: UIImageView!
@IBOutlet weak var activityName: UILabel!
@IBOutlet weak var activityLocation: UILabel!
@IBOutlet weak var activityTime: UILabel!
@IBOutlet weak var activityPrice: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
292a39d3337771f9b6bfb51fc28d5e20
| 28.396552 | 87 | 0.561877 | 5.361635 | false | false | false | false |
mayqiyue/RZEdgeSlideViewController
|
RZEdgeSlideViewController/Classes/RZEdgeSlideViewController.swift
|
1
|
19475
|
//
// RZEdgeSlideViewController.swift
// RZEgeSlideViewController
//
// Created by Mayqiyue on 17/03/2017.
// Copyright © 2017 mayqiyue. All rights reserved.
//
import UIKit
@objc public protocol RZEdgeSlideViewControllerDelegate {
@objc optional func edgeSlideViewController(_ viewController: RZEdgeSlideViewController, willChangeTo state: RZEdgeSlideViewController.DrawerState)
@objc optional func edgeSlideViewController(_ viewController: RZEdgeSlideViewController, didChangeTo state: RZEdgeSlideViewController.DrawerState)
// changedePercent: {-1.0 ~ 1.0}; -1.0 means switch to DrawerState.left, 0.0 means .center 1.0 means .right
@objc optional func edgeSlideViewController(_ viewController: RZEdgeSlideViewController, changedePercent: CGFloat);
}
open class RZEdgeSlideViewController : UIViewController, UIGestureRecognizerDelegate {
/**************************************************************************/
// MARK: - Types
/**************************************************************************/
@objc public enum DrawerState: Int {
case left, center, right
}
/**************************************************************************/
// MARK: - Properties
/**************************************************************************/
@IBInspectable public var containerViewMaxAlpha: CGFloat = 0.2
@IBInspectable public var drawerAnimationDuration: TimeInterval = 0.25
private var _leftWidthConstraint: NSLayoutConstraint!
private var _rightWidthConstraint: NSLayoutConstraint!
private var _leftTrailingConstraint: NSLayoutConstraint!
private var _panStartLocation = CGPoint.zero
private var _constraitStartConstant : CGFloat = 0.0
private var _panDelta: CGFloat = 0
private var _state: DrawerState = .center
private lazy var leftContaienrView : UIView = {
let view = UIView.init()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var rightContainerView : UIView = {
let view = UIView.init()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
public var swipeEnabled = true
public private(set) lazy var screenEdgePanGesture: UIScreenEdgePanGestureRecognizer = {
let gesture = UIScreenEdgePanGestureRecognizer(
target: self,
action: #selector(RZEdgeSlideViewController.handlePanGesture(_:))
)
gesture.delegate = self
gesture.edges = UIRectEdge.init(rawValue: UIRectEdge.left.rawValue | UIRectEdge.right.rawValue)
return gesture
}()
public private(set) lazy var panGesture: UIPanGestureRecognizer = {
let gesture = UIPanGestureRecognizer(
target: self,
action: #selector(RZEdgeSlideViewController.handlePanGesture(_:))
)
gesture.delegate = self
return gesture
}()
public weak var delegate: RZEdgeSlideViewControllerDelegate?
public var drawerState: DrawerState {
get {return _state}
set {setDrawerState(newValue, animated: true) }
}
@IBInspectable public var drawerWidth: CGFloat = UIScreen.main.bounds.size.width {
didSet {
_leftWidthConstraint?.constant = drawerWidth
_rightWidthConstraint?.constant = drawerWidth
}
}
public var displayingViewController: UIViewController? {
switch drawerState {
case .left:
return leftViewController
case .center:
return mainViewController
case .right:
return rightViewController
}
}
public var mainViewController: UIViewController! {
didSet {
if let oldController = oldValue {
oldController.willMove(toParentViewController: nil)
oldController.view.removeFromSuperview()
oldController.removeFromParentViewController()
}
guard let mainViewController = mainViewController else { return }
addChildViewController(mainViewController)
mainViewController.didMove(toParentViewController: self)
mainViewController.view.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(mainViewController.view, at: 0)
let viewDictionary = ["mainView" : mainViewController.view!]
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[mainView]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[mainView]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
mainViewController.didMove(toParentViewController: self)
}
}
public var leftViewController : UIViewController? {
didSet {
if let oldController = oldValue {
oldController.willMove(toParentViewController: nil)
oldController.view.removeFromSuperview()
oldController.removeFromParentViewController()
}
guard let leftViewController = leftViewController else { return }
addChildViewController(leftViewController)
leftViewController.didMove(toParentViewController: self)
leftViewController.view.translatesAutoresizingMaskIntoConstraints = false
leftContaienrView.addSubview(leftViewController.view)
let viewDictionary = ["view" : leftViewController.view!]
leftContaienrView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
leftContaienrView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
leftContaienrView.updateConstraints()
leftViewController.didMove(toParentViewController: self)
}
}
public var rightViewController : UIViewController? {
didSet {
if let oldController = oldValue {
oldController.willMove(toParentViewController: nil)
oldController.view.removeFromSuperview()
oldController.removeFromParentViewController()
}
guard let rightViewController = rightViewController else { return }
addChildViewController(rightViewController)
rightViewController.didMove(toParentViewController: self)
rightViewController.view.translatesAutoresizingMaskIntoConstraints = false
rightContainerView.addSubview(rightViewController.view)
let viewDictionary = ["view" : rightViewController.view!]
rightContainerView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
rightContainerView.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
rightContainerView.updateConstraints()
rightViewController.didMove(toParentViewController: self)
}
}
/**************************************************************************/
// MARK: - initialize
/**************************************************************************/
/**************************************************************************/
// MARK: - Life Cycle
/**************************************************************************/
override open func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(self.screenEdgePanGesture)
self.view.addGestureRecognizer(self.panGesture)
self.view.addSubview(self.leftContaienrView)
self.view.addSubview(self.rightContainerView)
// Concigure left container view
var viewDictionary = ["view" : self.leftContaienrView]
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
self.view.addConstraint(
NSLayoutConstraint(
item: self.leftContaienrView,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1.0,
constant:0.0
)
)
_leftTrailingConstraint = NSLayoutConstraint(
item: self.leftContaienrView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.leading,
multiplier: 1.0,
constant:0.0
)
self.view.addConstraint(_leftTrailingConstraint)
// Configure right container view
viewDictionary = ["view" : self.rightContainerView]
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|",
options: [],
metrics: nil,
views: viewDictionary
)
)
self.view.addConstraint (
NSLayoutConstraint(
item: self.rightContainerView,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1.0,
constant:0.0
)
)
let horizaontalConstraint = NSLayoutConstraint (
item: self.rightContainerView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.leftContaienrView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1.0,
constant:self.view.bounds.size.width
)
self.view.addConstraint(horizaontalConstraint)
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
displayingViewController?.beginAppearanceTransition(true, animated: animated)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
displayingViewController?.endAppearanceTransition()
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
displayingViewController?.beginAppearanceTransition(false, animated: animated)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
displayingViewController?.endAppearanceTransition()
}
override open var shouldAutomaticallyForwardAppearanceMethods: Bool {
get {
return false
}
}
open override var childViewControllerForStatusBarStyle: UIViewController? {
switch self._state {
case .left:
return self.leftViewController
case .center:
return self.mainViewController
case .right:
return self.rightViewController
}
}
open override var childViewControllerForStatusBarHidden: UIViewController? {
switch self._state {
case .left:
return self.leftViewController
case .center:
return self.mainViewController
case .right:
return self.rightViewController
}
}
/**************************************************************************/
// MARK: - Public Method
/**************************************************************************/
public func setDrawerState(_ state: DrawerState, animated: Bool) {
let duration: TimeInterval = animated ? drawerAnimationDuration : 0
let needCallEndAppearanceVCs: NSMutableArray = NSMutableArray()
if _state != state {
switch state {
case .left:
leftViewController?.beginAppearanceTransition(true, animated: animated)
needCallEndAppearanceVCs.add(leftViewController!)
if isViewVisiable(mainViewController.view) {
mainViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(mainViewController)
}
if isViewVisiable(rightContainerView) {
rightViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(rightViewController!)
}
case .center:
mainViewController?.beginAppearanceTransition(true, animated: animated)
needCallEndAppearanceVCs.add(mainViewController)
if isViewVisiable(leftContaienrView) {
leftViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(leftViewController!)
}
if isViewVisiable(rightContainerView) {
rightViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(rightViewController!)
}
case .right:
rightViewController?.beginAppearanceTransition(true, animated: animated)
needCallEndAppearanceVCs.add(rightViewController!)
if isViewVisiable(mainViewController.view) {
mainViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(mainViewController)
}
if isViewVisiable(leftContaienrView) {
leftViewController?.beginAppearanceTransition(false, animated: animated)
needCallEndAppearanceVCs.add(leftViewController!)
}
}
}
self.delegate?.edgeSlideViewController?(self, willChangeTo: state);
UIView.animate(withDuration: duration,
delay: 0,
options: .curveEaseOut,
animations: { () -> Void in
switch state {
case .left:
self._leftTrailingConstraint.constant = self.view.bounds.size.width
case .center:
self._leftTrailingConstraint.constant = 0.0
case .right:
self._leftTrailingConstraint.constant = -self.view.bounds.size.width
}
self.view.layoutIfNeeded()
}) { (finished: Bool) -> Void in
for obj in needCallEndAppearanceVCs {
let vc : UIViewController = obj as! UIViewController
vc.endAppearanceTransition()
}
self.delegate?.edgeSlideViewController?(self, didChangeTo: state)
self._state = state;
self.setNeedsStatusBarAppearanceUpdate()
}
}
/**************************************************************************/
// MARK: - Private Method
/**************************************************************************/
@objc final func handlePanGesture(_ sender: UIPanGestureRecognizer) {
if sender.state == .began {
_panStartLocation = sender.location(in: view)
_constraitStartConstant = _leftTrailingConstraint.constant
}
let delta = CGFloat(sender.location(in: view).x - _panStartLocation.x)
let threshold = CGFloat(0.5)
var constant : CGFloat
let drawerState : DrawerState
let viewWidth = self.view.bounds.size.width
let velocity = sender.velocity(in: view)
let velocityThres = CGFloat(400.0)
constant = min(max(_constraitStartConstant + delta, -viewWidth), viewWidth)
_leftTrailingConstraint.constant = constant
if constant >= viewWidth && delta < 0 {
return;
}
else if constant <= -viewWidth && delta > 0 {
return;
}
if velocity.x < -velocityThres {
constant -= viewWidth*threshold;
}
else if velocity.x > velocityThres {
constant += viewWidth*threshold;
}
drawerState = constant < -viewWidth * threshold ? .right : constant > viewWidth*threshold ? .left : .center
switch sender.state {
case .changed:
let percent = CGFloat(round(-_leftTrailingConstraint.constant/viewWidth * 100.0) / 100)
self.delegate?.edgeSlideViewController!(self, changedePercent: percent)
case .ended, .cancelled:
setDrawerState(drawerState, animated: true)
default:
break
}
}
private func isViewVisiable(_ view: UIView) -> Bool {
func isVisible(view: UIView, inView: UIView?) -> Bool {
guard let inView = inView else { return true }
let viewFrame = inView.convert(view.bounds, from: view)
if viewFrame.intersects(inView.bounds) {
return isVisible(view: view, inView: inView.superview)
}
return false
}
return isVisible(view: view, inView: view.superview)
}
/**************************************************************************/
// MARK: - UIGestureRecognizerDelegate
/**************************************************************************/
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if self.displayingViewController is UINavigationController {
let vc = self.displayingViewController as! UINavigationController
if vc.viewControllers.count > 1 {
return false
}
}
return self.swipeEnabled;
}
}
|
mit
|
aa329de18ad9a0f86377bed317b7a73d
| 38.026052 | 151 | 0.553815 | 6.324781 | false | false | false | false |
WalterCreazyBear/Swifter30
|
iMessageDemo/iMessageExtension/BGRootViewController.swift
|
1
|
2838
|
//
// BGRootViewController.swift
// iMessageDemo
//
// Created by Bear on 2017/8/7.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class BGRootViewController: UIViewController {
lazy var stickerButton : UIButton = {
let view : UIButton = UIButton()
view.backgroundColor = UIColor.white
view.layer.borderColor = UIColor.gray.cgColor
view.layer.borderWidth = 0.5
view.setTitle("sticker", for: .normal)
view.setTitleColor(UIColor.black, for: .normal)
view.addTarget(self, action: #selector(handleStickerButtonClick(sender:)), for: .touchUpInside)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
func handleStickerButtonClick(sender:UIButton) {
let stickerVC = BGStickerBrowserViewController(stickerSize: .small)
self.navigationController?.pushViewController(stickerVC, animated: true)
}
lazy var selfDefineButton : UIButton = {
let view : UIButton = UIButton()
view.backgroundColor = UIColor.white
view.layer.borderColor = UIColor.gray.cgColor
view.layer.borderWidth = 0.5
view.setTitle("SelfDefine", for: .normal)
view.setTitleColor(UIColor.black, for: .normal)
view.addTarget(self, action: #selector(handleSelfDefineButtonClick(sender:)), for: .touchUpInside)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
func handleSelfDefineButtonClick(sender:UIButton) {
let selfDefineButton = BGSelfDefineViewController()
self.navigationController?.pushViewController(selfDefineButton, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
self.view.addSubview(stickerButton)
self.view.addSubview(selfDefineButton)
stickerButton.widthAnchor.constraint(equalToConstant: 140).isActive = true
stickerButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
stickerButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stickerButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -25).isActive = true
selfDefineButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
selfDefineButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 25).isActive = true
selfDefineButton.widthAnchor.constraint(equalToConstant: 140).isActive = true
selfDefineButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = true
}
}
|
mit
|
f61c9c9c802ebd2e650df0ad0434c9a8
| 37.835616 | 113 | 0.697354 | 4.982425 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift
|
Solutions/SolutionsTests/Medium/Medium_048_Rotate_Image_Test.swift
|
1
|
2706
|
//
// Medium_048_Rotate_Image_Test.swift
// Solutions
//
// Created by Di Wu on 5/23/15.
// Copyright (c) 2015 diwu. All rights reserved.
//
import XCTest
class Medium_048_Rotate_Image_Test: XCTestCase, SolutionsTestCase {
func test_001() {
let input: [[Int]] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let expected: [[Int]] = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
asyncHelper(input: input, expected: expected)
}
func test_002() {
let input: [[Int]] = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
let expected: [[Int]] = [
[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 11, 7, 3],
[16, 12, 8, 4]
]
asyncHelper(input: input, expected: expected)
}
func test_003() {
let input: [[Int]] = [
[1]
]
let expected: [[Int]] = [
[1]
]
asyncHelper(input: input, expected: expected)
}
func test_004() {
let input: [[Int]] = [
[1, 2],
[3, 4]
]
let expected: [[Int]] = [
[3, 1],
[4, 2]
]
asyncHelper(input: input, expected: expected)
}
func test_005() {
let input: [[Int]] = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
let expected: [[Int]] = [
[21, 16, 11, 6, 1],
[22, 17, 12, 7, 2],
[23, 18, 13, 8, 3],
[24, 19, 14, 9, 4],
[25, 20, 15, 10, 5]
]
asyncHelper(input: input, expected: expected)
}
private func asyncHelper(input: [[Int]], expected: [[Int]]) {
weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
serialQueue().async(execute: { () -> Void in
var result = input
Medium_048_Rotate_Image.rotate(&result)
assertHelper(compareTwoDimensionIntArray(arr0: result, arr1: expected), problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
}
}
}
}
|
mit
|
12217b2984d1eb607fb51efa423641f0
| 28.096774 | 175 | 0.445307 | 3.671642 | false | true | false | false |
kellanburket/Passenger
|
Pod/Classes/Utilities/Hmac.swift
|
1
|
1758
|
//
// Hmac.swift
// Pods
//
// Created by Kellan Cummings on 6/12/15.
//
//
import Foundation
import CommonCrypto
internal enum HMACAlgorithm: Printable {
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
func toCCEnum() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .MD5:
result = kCCHmacAlgMD5
case .SHA1:
result = kCCHmacAlgSHA1
case .SHA224:
result = kCCHmacAlgSHA224
case .SHA256:
result = kCCHmacAlgSHA256
case .SHA384:
result = kCCHmacAlgSHA384
case .SHA512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
func digestLength() -> Int {
var result: CInt = 0
switch self {
case .MD5:
result = CC_MD5_DIGEST_LENGTH
case .SHA1:
result = CC_SHA1_DIGEST_LENGTH
case .SHA224:
result = CC_SHA224_DIGEST_LENGTH
case .SHA256:
result = CC_SHA256_DIGEST_LENGTH
case .SHA384:
result = CC_SHA384_DIGEST_LENGTH
case .SHA512:
result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
var description: String {
get {
switch self {
case .MD5:
return "HMAC.MD5"
case .SHA1:
return "HMAC.SHA1"
case .SHA224:
return "HMAC.SHA224"
case .SHA256:
return "HMAC.SHA256"
case .SHA384:
return "HMAC.SHA384"
case .SHA512:
return "HMAC.SHA512"
}
}
}
}
|
mit
|
b772edb721c7bf3dae05d5091ec12dd2
| 23.774648 | 50 | 0.482366 | 4.417085 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/System/Floating Create Button/CreateButtonCoordinator.swift
|
1
|
13503
|
import Gridicons
import WordPressFlux
@objc class CreateButtonCoordinator: NSObject {
private enum Constants {
static let padding: CGFloat = -16 // Bottom and trailing padding to position the button along the bottom right corner
static let heightWidth: CGFloat = 56 // Height and width of the button
static let popoverOffset: CGFloat = -10 // The vertical offset of the iPad popover
static let maximumTooltipViews = 5 // Caps the number of times the user can see the announcement tooltip
}
var button: FloatingActionButton = {
let button = FloatingActionButton(image: .gridicon(.create))
button.accessibilityLabel = NSLocalizedString("Create", comment: "Accessibility label for create floating action button")
button.accessibilityIdentifier = "floatingCreateButton"
return button
}()
private weak var viewController: UIViewController?
private let noticeAnimator = NoticeAnimator(duration: 0.5, springDampening: 0.7, springVelocity: 0.0)
private func notice(for blog: Blog) -> Notice {
let showsStories = blog.supports(.stories)
let title = showsStories ? NSLocalizedString("Create a post, page, or story", comment: "The tooltip title for the Floating Create Button") : NSLocalizedString("Creates new post, or page", comment: " Accessibility hint for create floating action button")
let notice = Notice(title: title,
message: "",
style: ToolTipNoticeStyle()) { [weak self] _ in
self?.didDismissTooltip = true
self?.hideNotice()
}
return notice
}
// Once this reaches `maximumTooltipViews` we won't show the tooltip again
private var shownTooltipCount: Int {
set {
if newValue >= Constants.maximumTooltipViews {
didDismissTooltip = true
} else {
UserPersistentStoreFactory.instance().createButtonTooltipDisplayCount = newValue
}
}
get {
return UserPersistentStoreFactory.instance().createButtonTooltipDisplayCount
}
}
private var didDismissTooltip: Bool {
set {
UserPersistentStoreFactory.instance().createButtonTooltipWasDisplayed = newValue
}
get {
return UserPersistentStoreFactory.instance().createButtonTooltipWasDisplayed
}
}
// TODO: when prompt is used, get prompt from cache so it's using the latest.
private var prompt: BloggingPrompt?
private lazy var bloggingPromptsService: BloggingPromptsService? = {
return BloggingPromptsService(blog: blog)
}()
private weak var noticeContainerView: NoticeContainerView?
private let actions: [ActionSheetItem]
private let source: String
private let blog: Blog?
/// Returns a newly initialized CreateButtonCoordinator
/// - Parameters:
/// - viewController: The UIViewController from which the menu should be shown.
/// - actions: A list of actions to display in the menu
/// - source: The source where the create button is being presented from
/// - blog: The current blog in context
init(_ viewController: UIViewController, actions: [ActionSheetItem], source: String, blog: Blog? = nil) {
self.viewController = viewController
self.actions = actions
self.source = source
self.blog = blog
super.init()
listenForQuickStart()
// Only fetch the prompt if it is actually needed, i.e. on the FAB that has multiple actions.
if actions.count > 1 {
fetchBloggingPrompt()
}
}
deinit {
quickStartObserver = nil
}
/// Should be called any time the `viewController`'s trait collections will change. Dismisses when horizontal class changes to transition from .popover -> .custom
/// - Parameter previousTraitCollection: The previous trait collection
/// - Parameter newTraitCollection: The new trait collection
@objc func presentingTraitCollectionWillChange(_ previousTraitCollection: UITraitCollection, newTraitCollection: UITraitCollection) {
if let actionSheetController = viewController?.presentedViewController as? ActionSheetViewController {
if previousTraitCollection.horizontalSizeClass != newTraitCollection.horizontalSizeClass {
viewController?.dismiss(animated: false, completion: { [weak self] in
guard let self = self else {
return
}
self.setupPresentation(on: actionSheetController, for: newTraitCollection)
self.viewController?.present(actionSheetController, animated: false, completion: nil)
})
}
}
}
/// Button must be manually shown _after_ adding using `showCreateButton`
@objc func add(to view: UIView, trailingAnchor: NSLayoutXAxisAnchor, bottomAnchor: NSLayoutYAxisAnchor) {
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = true
view.addSubview(button)
NSLayoutConstraint.activate([
button.bottomAnchor.constraint(equalTo: bottomAnchor, constant: Constants.padding),
button.heightAnchor.constraint(equalToConstant: Constants.heightWidth),
button.widthAnchor.constraint(equalToConstant: Constants.heightWidth),
button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: Constants.padding)
])
button.addTarget(self, action: #selector(showCreateSheet), for: .touchUpInside)
}
private var currentTourElement: QuickStartTourElement?
@objc func showCreateSheet() {
didDismissTooltip = true
hideNotice()
guard let viewController = viewController else {
return
}
if actions.count == 1 {
actions.first?.handler()
} else {
let actionSheetVC = actionSheetController(with: viewController.traitCollection)
viewController.present(actionSheetVC, animated: true, completion: { [weak self] in
WPAnalytics.track(.createSheetShown, properties: ["source": self?.source ?? ""])
if let element = self?.currentTourElement {
QuickStartTourGuide.shared.visited(element)
}
})
}
}
private func isShowingStoryOption() -> Bool {
actions.contains(where: { $0 is StoryAction })
}
private func actionSheetController(with traitCollection: UITraitCollection) -> UIViewController {
let actionSheetVC = CreateButtonActionSheet(headerView: createPromptHeaderView(), actions: actions)
setupPresentation(on: actionSheetVC, for: traitCollection)
return actionSheetVC
}
private func setupPresentation(on viewController: UIViewController, for traitCollection: UITraitCollection) {
if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular {
viewController.modalPresentationStyle = .popover
} else {
viewController.modalPresentationStyle = .custom
}
viewController.popoverPresentationController?.sourceView = self.button
viewController.popoverPresentationController?.sourceRect = self.button.bounds.offsetBy(dx: 0, dy: Constants.popoverOffset)
viewController.transitioningDelegate = self
}
private func hideNotice() {
if let container = noticeContainerView {
NoticePresenter.dismiss(container: container)
}
}
func hideCreateButtonTooltip() {
didDismissTooltip = true
hideNotice()
}
@objc func hideCreateButton() {
hideNotice()
if UIAccessibility.isReduceMotionEnabled {
button.isHidden = true
} else {
button.springAnimation(toShow: false)
}
}
func removeCreateButton() {
button.removeFromSuperview()
noticeContainerView?.removeFromSuperview()
}
@objc func showCreateButton(for blog: Blog) {
let showsStories = blog.supports(.stories)
button.accessibilityHint = showsStories ? NSLocalizedString("Creates new post, page, or story", comment: " Accessibility hint for create floating action button") : NSLocalizedString("Create a post or page", comment: " Accessibility hint for create floating action button")
showCreateButton(notice: notice(for: blog))
}
private func showCreateButton(notice: Notice) {
if !didDismissTooltip {
noticeContainerView = noticeAnimator.present(notice: notice, in: viewController!.view, sourceView: button)
shownTooltipCount += 1
}
if UIAccessibility.isReduceMotionEnabled {
button.isHidden = false
} else {
button.springAnimation(toShow: true)
}
}
// MARK: - Quick Start
private var quickStartObserver: Any?
private func quickStartNotice(_ description: NSAttributedString) -> Notice {
let notice = Notice(title: "",
message: "",
style: ToolTipNoticeStyle(attributedMessage: description)) { [weak self] _ in
self?.didDismissTooltip = true
self?.hideNotice()
}
return notice
}
private func listenForQuickStart() {
quickStartObserver = NotificationCenter.default.addObserver(forName: .QuickStartTourElementChangedNotification, object: nil, queue: nil) { [weak self] (notification) in
guard let self = self,
let userInfo = notification.userInfo,
let element = userInfo[QuickStartTourGuide.notificationElementKey] as? QuickStartTourElement,
let description = userInfo[QuickStartTourGuide.notificationDescriptionKey] as? NSAttributedString,
element == .newpost || element == .newPage else {
return
}
self.currentTourElement = element
self.hideNotice()
self.didDismissTooltip = false
self.showCreateButton(notice: self.quickStartNotice(description))
}
}
}
// MARK: Tranisitioning Delegate
extension CreateButtonCoordinator: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BottomSheetAnimationController(transitionType: .presenting)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BottomSheetAnimationController(transitionType: .dismissing)
}
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let presentationController = BottomSheetPresentationController(presentedViewController: presented, presenting: presenting)
return presentationController
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return (viewController?.presentedViewController?.presentationController as? BottomSheetPresentationController)?.interactionController
}
}
// MARK: - Blogging Prompts Methods
private extension CreateButtonCoordinator {
private func fetchBloggingPrompt() {
// TODO: check for cached prompt first.
guard let bloggingPromptsService = bloggingPromptsService else {
DDLogError("FAB: failed creating BloggingPromptsService instance.")
prompt = nil
return
}
bloggingPromptsService.todaysPrompt(success: { [weak self] (prompt) in
self?.prompt = prompt
}, failure: { [weak self] (error) in
self?.prompt = nil
DDLogError("FAB: failed fetching blogging prompt: \(String(describing: error))")
})
}
private func createPromptHeaderView() -> BloggingPromptsHeaderView? {
guard FeatureFlag.bloggingPrompts.enabled,
let blog = blog,
blog.isAccessibleThroughWPCom(),
let prompt = prompt else {
return nil
}
let promptsHeaderView = BloggingPromptsHeaderView.view(for: prompt)
promptsHeaderView.answerPromptHandler = { [weak self] in
WPAnalytics.track(.promptsBottomSheetAnswerPrompt)
self?.viewController?.dismiss(animated: true) {
let editor = EditPostViewController(blog: blog, prompt: prompt)
editor.modalPresentationStyle = .fullScreen
editor.entryPoint = .bloggingPromptsActionSheetHeader
self?.viewController?.present(editor, animated: true)
}
}
promptsHeaderView.infoButtonHandler = { [weak self] in
WPAnalytics.track(.promptsBottomSheetHelp)
guard let presentedViewController = self?.viewController?.presentedViewController else {
return
}
BloggingPromptsIntroductionPresenter(interactionType: .actionable(blog: blog)).present(from: presentedViewController)
}
return promptsHeaderView
}
}
|
gpl-2.0
|
389b7bd0acccbc93c8c473eed851851b
| 40.042553 | 280 | 0.668518 | 5.645067 | false | false | false | false |
migue1s/habitica-ios
|
HabitRPG/UI/Login/LoginTableViewController.swift
|
1
|
11525
|
//
// LoginTableViewController.swift
// Habitica
//
// Created by Phillip Thelen on 25/12/2016.
// Copyright © 2016 Phillip Thelen. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import CRToast
class LoginTableViewController: UIViewController, UITextFieldDelegate {
public var isRootViewController = false
@IBOutlet weak private var authTypeButton: UIBarButtonItem!
@IBOutlet weak private var usernameTextField: UITextField!
@IBOutlet weak private var emailTextField: UITextField!
@IBOutlet weak private var passwordTextField: UITextField!
@IBOutlet weak private var passwordRepeatTextField: UITextField!
@IBOutlet weak private var loginButton: UIButton!
@IBOutlet weak private var loginButtonBackground: UIView!
@IBOutlet weak private var onePasswordButton: UIButton!
@IBOutlet weak private var googleLoginButton: UIButton!
@IBOutlet weak private var facebookLoginButton: UIButton!
@IBOutlet weak private var emailFieldHeight: NSLayoutConstraint!
@IBOutlet weak private var emailFieldTopSpacing: NSLayoutConstraint!
@IBOutlet weak private var passwordRepeatFieldHeight: NSLayoutConstraint!
@IBOutlet weak private var passwordRepeatFieldTopSpacing: NSLayoutConstraint!
@IBOutlet weak private var loginActivityIndicator: UIActivityIndicatorView!
private let viewModel = LoginViewModel()
private var sharedManager: HRPGManager?
override func viewDidLoad() {
super.viewDidLoad()
let delegate = UIApplication.shared.delegate as? HRPGAppDelegate
self.sharedManager = delegate?.sharedManager
self.viewModel.inputs.setSharedManager(sharedManager: self.sharedManager)
self.viewModel.inputs.setViewController(viewController: self)
self.configureNavigationBar()
authTypeButton.target = self
authTypeButton.action = #selector(authTypeButtonTapped)
usernameTextField.addTarget(self, action: #selector(usernameTextFieldChanged(textField:)), for: .editingChanged)
emailTextField.addTarget(self, action: #selector(emailTextFieldChanged(textField:)), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(passwordTextFieldChanged(textField:)), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(passwordTextFieldChanged(textField:)), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(passwordTextFieldDoneEditing(textField:)), for: .editingDidEnd)
passwordRepeatTextField.addTarget(self, action: #selector(passwordRepeatTextFieldChanged(textField:)), for: .editingChanged)
passwordRepeatTextField.addTarget(self, action: #selector(passwordRepeatTextFieldDoneEditing(textField:)), for: .editingDidEnd)
loginButton.addTarget(self, action: #selector(loginButtonPressed), for: .touchUpInside)
googleLoginButton.addTarget(self, action: #selector(googleLoginButtonPressed), for: .touchUpInside)
facebookLoginButton.addTarget(self, action: #selector(facebookLoginButtonPressed), for: .touchUpInside)
onePasswordButton.addTarget(self, action: #selector(onePasswordButtonPressed), for: .touchUpInside)
bindViewModel()
self.viewModel.setAuthType(authType: LoginViewAuthType.Login)
self.viewModel.inputs.onePassword(
isAvailable: OnePasswordExtension.shared().isAppExtensionAvailable()
)
}
private func configureNavigationBar() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
self.navigationController?.navigationBar.backgroundColor = .clear
}
func bindViewModel() {
setupButtons()
setupFieldVisibility()
setupReturnTypes()
setupTextInput()
setupOnePassword()
self.viewModel.outputs.usernameFieldTitle.observeValues {[weak self] value in
self?.usernameTextField.placeholder = value
}
self.viewModel.outputs.showError
.observe(on: QueueScheduler.main)
.observeValues { [weak self] message in
self?.present(UIAlertController.genericError(message: message), animated: true, completion: nil)
}
self.viewModel.outputs.showNextViewController
.observeValues {[weak self] segueName in
guard let weakSelf = self else {
return
}
if weakSelf.isRootViewController {
weakSelf.performSegue(withIdentifier: segueName, sender: self)
} else {
weakSelf.dismiss(animated: true, completion:nil)
}
}
self.viewModel.outputs.loadingIndicatorVisibility
.observeValues {[weak self] isVisible in
if isVisible {
self?.loginActivityIndicator.startAnimating()
UIView.animate(withDuration: 0.5, animations: {
self?.loginButton.alpha = 0
self?.loginActivityIndicator.alpha = 1
})
} else {
UIView.animate(withDuration: 0.5, animations: {
self?.loginButton.alpha = 1
self?.loginActivityIndicator.alpha = 0
}, completion: { (_) in
self?.loginActivityIndicator.stopAnimating()
})
}
}
}
func setupButtons() {
self.authTypeButton.reactive.title <~ self.viewModel.outputs.authTypeButtonTitle
self.loginButton.reactive.title <~ self.viewModel.outputs.loginButtonTitle
self.loginButton.reactive.isEnabled <~ self.viewModel.outputs.isFormValid
}
func setupFieldVisibility() {
self.viewModel.outputs.emailFieldVisibility.observeValues {[weak self] value in
guard let weakSelf = self else {
return
}
if value {
weakSelf.showField(fieldHeightConstraint: weakSelf.emailFieldHeight, spacingHeightConstraint:weakSelf.emailFieldTopSpacing)
weakSelf.emailTextField.isEnabled = true
} else {
weakSelf.hideField(fieldHeightConstraint: weakSelf.emailFieldHeight, spacingHeightConstraint:weakSelf.emailFieldTopSpacing)
weakSelf.emailTextField.isEnabled = false
}
}
self.viewModel.outputs.passwordRepeatFieldVisibility.observeValues {[weak self] value in
guard let weakSelf = self else {
return
}
if value {
weakSelf.showField(fieldHeightConstraint: weakSelf.passwordRepeatFieldHeight, spacingHeightConstraint:weakSelf.passwordRepeatFieldTopSpacing)
weakSelf.passwordRepeatTextField.isEnabled = true
} else {
weakSelf.hideField(fieldHeightConstraint: weakSelf.passwordRepeatFieldHeight, spacingHeightConstraint:weakSelf.passwordRepeatFieldTopSpacing)
weakSelf.passwordRepeatTextField.isEnabled = false
}
}
}
func setupReturnTypes() {
self.viewModel.outputs.passwordFieldReturnButtonIsDone.observeValues {[weak self] value in
if value {
self?.passwordTextField.returnKeyType = .done
} else {
self?.passwordTextField.returnKeyType = .next
}
}
self.viewModel.outputs.passwordRepeatFieldReturnButtonIsDone.observeValues {[weak self] value in
if value {
self?.passwordRepeatTextField.returnKeyType = .done
} else {
self?.passwordRepeatTextField.returnKeyType = .next
}
}
}
func setupTextInput() {
self.usernameTextField.reactive.text <~ self.viewModel.outputs.usernameText
self.emailTextField.reactive.text <~ self.viewModel.outputs.emailText
self.passwordTextField.reactive.text <~ self.viewModel.outputs.passwordText
self.passwordRepeatTextField.reactive.text <~ self.viewModel.outputs.passwordRepeatText
}
func setupOnePassword() {
self.onePasswordButton.reactive.isHidden <~ self.viewModel.outputs.onePasswordButtonHidden
self.viewModel.outputs.onePasswordFindLogin.observeValues {[weak self] _ in
OnePasswordExtension.shared().findLogin(forURLString: "https://habitica.com", for: self!, sender: self?.onePasswordButton, completion: { (data, _) in
guard let loginData = data else {
return
}
let username = loginData[AppExtensionUsernameKey] as? String ?? ""
let password = loginData[AppExtensionPasswordKey] as? String ?? ""
self?.viewModel.onePasswordFoundLogin(username: username, password: password)
})
}
}
func authTypeButtonTapped() {
self.viewModel.inputs.authTypeChanged()
}
func usernameTextFieldChanged(textField: UITextField) {
self.viewModel.inputs.usernameChanged(username: textField.text)
}
func emailTextFieldChanged(textField: UITextField) {
self.viewModel.inputs.emailChanged(email: textField.text)
}
func passwordTextFieldChanged(textField: UITextField) {
self.viewModel.inputs.passwordChanged(password: textField.text)
}
func passwordTextFieldDoneEditing(textField: UITextField) {
self.viewModel.inputs.passwordDoneEditing()
}
func passwordRepeatTextFieldChanged(textField: UITextField) {
self.viewModel.inputs.passwordRepeatChanged(passwordRepeat: textField.text)
}
func passwordRepeatTextFieldDoneEditing(textField: UITextField) {
self.viewModel.inputs.passwordRepeatDoneEditing()
}
func showField(fieldHeightConstraint: NSLayoutConstraint, spacingHeightConstraint: NSLayoutConstraint) {
fieldHeightConstraint.constant = 44
spacingHeightConstraint.constant = 12
UIView.animate(withDuration: 0.3) {
self.view .layoutIfNeeded()
}
}
func hideField(fieldHeightConstraint: NSLayoutConstraint, spacingHeightConstraint: NSLayoutConstraint) {
fieldHeightConstraint.constant = 0
spacingHeightConstraint.constant = 0
UIView.animate(withDuration: 0.3) {
self.view .layoutIfNeeded()
}
}
func loginButtonPressed() {
self.viewModel.inputs.loginButtonPressed()
}
func googleLoginButtonPressed() {
self.viewModel.inputs.googleLoginButtonPressed()
}
func onePasswordButtonPressed() {
self.viewModel.inputs.onePasswordTapped()
}
func facebookLoginButtonPressed() {
self.viewModel.inputs.facebookLoginButtonPressed()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.returnKeyType == .next {
guard let next = textField.superview?.superview?.viewWithTag(textField.tag+1) as? UITextField else {
return false
}
if next.isEnabled {
next.becomeFirstResponder()
} else {
let _ = self.textFieldShouldReturn(next)
}
} else if textField.returnKeyType == .done {
textField.resignFirstResponder()
}
return true
}
}
|
gpl-3.0
|
08ae7fd1555423b5f011b62b5b7e2ebc
| 41.212454 | 161 | 0.680406 | 5.629702 | false | false | false | false |
Samarkin/PixelEditor
|
PixelEditor/PixelMasher.swift
|
1
|
1460
|
import Cocoa
final class PixelMasher {
private let pixelCoder: PixelCoder
init(pixelCoder: PixelCoder) {
self.pixelCoder = pixelCoder
}
var code: UInt8 {
return self.pixelCoder.code
}
func addPixel(pixel: NSColor, var unfinishedByte: UInt8, var bitsFilled: Int) -> (finishedBytes: [UInt8], unfinishedByte: UInt8, filledBits: Int) {
assert(bitsFilled >= 0 && bitsFilled <= 8, "Invalid bitsFilled value: \(bitsFilled)")
var answer = [UInt8]()
let newByte: UInt8
let filledBits: Int
if bitsFilled == 8 {
answer.append(unfinishedByte)
bitsFilled = 0
}
unfinishedByte = unfinishedByte & UInt8((1 << bitsFilled) - 1)
var tmpBytes: UInt64
var tmpBits: Int
(tmpBytes, tmpBits) = pixelCoder.encodePixel(pixel)
while bitsFilled + tmpBits >= 8 {
let overflowBits = bitsFilled + tmpBits - 8
let fullByte = (bitsFilled > 0 ? (unfinishedByte << UInt8(8 - bitsFilled)) : 0) | UInt8(tmpBytes >> UInt64(overflowBits))
unfinishedByte = 0
bitsFilled = 0
answer.append(fullByte)
tmpBytes = tmpBytes & UInt64((1 << overflowBits) - 1)
tmpBits = overflowBits
}
newByte = (unfinishedByte << UInt8(tmpBits)) | UInt8(tmpBytes)
filledBits = bitsFilled + tmpBits
return (answer, newByte, filledBits)
}
}
|
mit
|
6732cf5fd9ebaf7525c651748c0bdf86
| 31.466667 | 151 | 0.59726 | 3.978202 | false | false | false | false |
mcgraw/tomorrow
|
Tomorrow/IGICustomerDetailsViewController.swift
|
1
|
4049
|
//
// IGICustomerDetailsViewController.swift
// Tomorrow
//
// Created by David McGraw on 1/24/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
import Realm
enum IGIGender: Int {
case Unspecified, Male, Female
}
class IGICustomerDetailsViewController: GAITrackedViewController, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet weak var inputField: IGITextField!
@IBOutlet weak var titleLabel: IGILabel!
var selectedGender: IGIGender = .Unspecified
var accessoryView: UIView?
var userObject: IGIUser?
override func viewDidLoad() {
super.viewDidLoad()
// We only want to worry about one user object on the device
RLMRealm.defaultRealm().beginWriteTransaction()
let users = IGIUser.allObjects()
if users.count == 0 {
userObject = IGIUser()
userObject?.userId = 1
IGIUser.createOrUpdateInDefaultRealmWithValue(userObject)
} else {
userObject = users[0] as? IGIUser
}
RLMRealm.defaultRealm().commitWriteTransaction()
println(RLMRealm.defaultRealm().path)
inputField.becomeFirstResponder()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
screenName = "Onboard Name Screen"
view.backgroundColor = UIColor.clearColor()
// addInfoAccessoryView()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playIntroductionAnimation()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
inputField.resignFirstResponder()
}
func addInfoAccessoryView() {
accessoryView = UIView()
accessoryView?.alpha = 0
accessoryView!.frame = CGRectMake(0, 0, view.frame.width, 50)
accessoryView!.backgroundColor = UIColor.clearColor()
let info = UIButton(frame: accessoryView!.frame)
info.setTitle("Why is Tomorrow asking for this?", forState: UIControlState.Normal)
info.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
info.titleLabel?.textAlignment = NSTextAlignment.Center
info.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 12.0)
info.addTarget(self, action: "displayInfo", forControlEvents: UIControlEvents.TouchUpInside)
accessoryView!.addSubview(info)
inputField.inputAccessoryView = accessoryView!
}
func displayInfo() {
let alert = UIAlertView(title: nil, message: "To better personalize Tomorrow. This information is never uploaded or shared anywhere.", delegate: self, cancelButtonTitle: "Got it!")
alert.show()
}
// MARK: Animation
func playIntroductionAnimation() {
titleLabel.revealView(constant: 50)
inputField.revealView(constant: 130)
UIView.animateWithDuration(0.5, animations: {
println()
self.accessoryView?.alpha = 1.0
})
}
func playDismissAnimation() {
UIView.animateWithDuration(0.5, animations: {
println()
self.accessoryView?.alpha = 0.0
})
inputField.dismissViewWithDelay(constant: Int(view.bounds.size.height), delay: 0.4)
titleLabel.dismissViewWithDelay(constant: Int(view.bounds.size.height), delay: 0.6)
}
// Text Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// inputField.selectable = false
userObject?.setUserName(name: textField.text)
playDismissAnimation()
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "advanceOnboarding", userInfo: nil, repeats: false)
return true
}
func advanceOnboarding() {
performSegueWithIdentifier("infoSegue", sender: self)
}
}
|
bsd-2-clause
|
5c04d1242996a8f790d9f87a793b1fdd
| 30.632813 | 188 | 0.639911 | 5.029814 | false | false | false | false |
pkx0128/UIKit
|
MscrollAndPage/MscrollAndPage/ViewController.swift
|
1
|
2352
|
//
// ViewController.swift
// MscrollAndPage
//
// Created by pankx on 2017/10/4.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var myscoll: UIScrollView!
var mypage: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension ViewController: UIScrollViewDelegate {
func setupUI() {
view.backgroundColor = UIColor.white
myscoll = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
myscoll.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.5)
myscoll.contentSize = CGSize(width: view.bounds.width * 5, height: view.bounds.height)
myscoll.delegate = self
myscoll.isPagingEnabled = true
myscoll.showsVerticalScrollIndicator = false
myscoll.showsHorizontalScrollIndicator = false
view.addSubview(myscoll)
mypage = UIPageControl(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 40))
mypage.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.9)
mypage.currentPage = 0
mypage.numberOfPages = 5
mypage.addTarget(self, action: #selector(pagechange), for: .valueChanged)
mypage.currentPageIndicatorTintColor = UIColor.darkGray
mypage.pageIndicatorTintColor = UIColor.blue
view.addSubview(mypage)
var myLabel: UILabel!
for i in 0...4 {
myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 40))
myLabel.center = CGPoint(x: view.bounds.width * (0.5 + CGFloat(i)), y: view.bounds.height * 0.2)
myLabel.text = "\(i + 1)"
myLabel.textAlignment = .center
myLabel.textColor = UIColor.red
myscoll.addSubview(myLabel)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let p = Int(scrollView.contentOffset.x / scrollView.bounds.width)
mypage.currentPage = p
}
@objc func pagechange(_ sender: UIPageControl) {
var frame = myscoll.frame
frame.origin.x = frame.width * (CGFloat(sender.currentPage))
frame.origin.y = 0
myscoll.scrollRectToVisible(frame, animated: true)
}
}
|
mit
|
977c1db026c11ee2a9e0758c1f81eff1
| 35.138462 | 111 | 0.639847 | 4.008532 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Card/Detail/View/CardDetailMVCell.swift
|
2
|
3164
|
//
// CardDetailMVCell.swift
// DereGuide
//
// Created by zzk on 29/09/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import TTGTagCollectionView
protocol CardDetailMVCellDelegate: class {
func cardDetailMVCell(_ cardDetailMVCell: CardDetailMVCell, didClickAt index: Int)
}
class CardDetailMVCell: UITableViewCell {
let leftLabel = UILabel()
var tagViews = [BannerView]()
let collectionView = TTGTagCollectionView()
weak var delegate: CardDetailMVCellDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(leftLabel)
leftLabel.font = UIFont.systemFont(ofSize: 16)
leftLabel.text = NSLocalizedString("出演MV", comment: "")
leftLabel.snp.makeConstraints { (make) in
make.left.equalTo(readableContentGuide)
make.top.equalTo(10)
}
collectionView.contentInset = .zero
collectionView.verticalSpacing = 5
collectionView.horizontalSpacing = 5
contentView.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.snp.makeConstraints { (make) in
make.left.equalTo(readableContentGuide)
make.right.equalTo(readableContentGuide)
make.top.equalTo(leftLabel.snp.bottom).offset(5)
make.bottom.equalTo(-10)
}
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(songs: [CGSSSong]) {
tagViews.removeAll()
for song in songs {
let tagView = BannerView()
tagView.sd_setImage(with: song.jacketURL)
tagViews.append(tagView)
}
collectionView.reload()
}
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
layoutIfNeeded()
collectionView.invalidateIntrinsicContentSize()
return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
}
}
extension CardDetailMVCell: TTGTagCollectionViewDelegate, TTGTagCollectionViewDataSource {
func numberOfTags(in tagCollectionView: TTGTagCollectionView!) -> UInt {
return UInt(tagViews.count)
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, tagViewFor index: UInt) -> UIView! {
return tagViews[Int(index)]
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, sizeForTagAt index: UInt) -> CGSize {
return CGSize(width: 66, height: 66)
}
func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, didSelectTag tagView: UIView!, at index: UInt) {
delegate?.cardDetailMVCell(self, didClickAt: Int(index))
}
}
|
mit
|
17ffd2fc62d23944095e2dcfea1c1165
| 33.336957 | 193 | 0.683761 | 5.0544 | false | false | false | false |
jmayoralas/Sems
|
Sems/VmScreen.swift
|
1
|
12077
|
//
// VmScreen.swift
// Z80VirtualMachineKit
//
// Created by Jose Luis Fernandez-Mayoralas on 7/8/16.
// Copyright © 2016 lomocorp. All rights reserved.
//
import Foundation
public struct PixelData {
var a:UInt8 = 255
var r:UInt8
var g:UInt8
var b:UInt8
}
let colorTable = [
PixelData(a: 255, r: 0, g: 0, b: 0),
PixelData(a: 255, r: 0, g: 0, b: 0xCD),
PixelData(a: 255, r: 0xCD, g: 0, b: 0),
PixelData(a: 255, r: 0xCD, g: 0, b: 0xCD),
PixelData(a: 255, r: 0, g: 0xCD, b: 0),
PixelData(a: 255, r: 0, g: 0xCD, b: 0xCD),
PixelData(a: 255, r: 0xCD, g: 0xCD, b: 0),
PixelData(a: 255, r: 0xCD, g: 0xCD, b: 0xCD),
PixelData(a: 255, r: 0, g: 0, b: 0),
PixelData(a: 255, r: 0, g: 0, b: 0xFF),
PixelData(a: 255, r: 0xFF, g: 0, b: 0),
PixelData(a: 255, r: 0xFF, g: 0, b: 0xFF),
PixelData(a: 255, r: 0, g: 0xFF, b: 0),
PixelData(a: 255, r: 0, g: 0xFF, b: 0xFF),
PixelData(a: 255, r: 0xFF, g: 0xFF, b: 0),
PixelData(a: 255, r: 0xFF, g: 0xFF, b: 0xFF),
]
let kWhiteColor = colorTable[7]
extension PixelData: Equatable {}
public func ==(lhs: PixelData, rhs: PixelData) -> Bool {
return lhs.a == rhs.a && lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b
}
struct Attribute {
var flashing: Bool
var paperColor: PixelData
var inkColor: PixelData
}
let kBaseWidth = 320
let kBorderLastTCycle = 62639 // last tcycle for coord. x=312, y=239
struct BorderData {
let color: PixelData
var tCycle: Int
}
@objc final public class VmScreen: NSObject {
var flashState: Bool = false
public var width: Int
public var height: Int
public var buffer: [PixelData]
var changed: Bool = false
var memory: ULAMemory!
private var zoomFactor: Int
private var lastTCycle: Int = 0
private var memoryScreen: Ram
private var addressUpdated: [UInt16] = []
private var currentBorderData: BorderData
private var previousBorderColor: PixelData = kWhiteColor
private var floatDataTable: [UInt16?] = Array(repeating: nil, count: 224 * 192)
public init(zoomFactor: Int) {
self.zoomFactor = zoomFactor
width = kBaseWidth * zoomFactor
height = width * 3 / 4
buffer = VmScreen.initBuffer(zoomFactor: zoomFactor)
memoryScreen = Ram(base_address: 16384, block_size: 0x1B00)
currentBorderData = BorderData(color: kWhiteColor, tCycle: 0)
super.init()
fillFloatingDataTable()
}
final func setZoomFactor(zoomFactor: Int) {
if self.zoomFactor != zoomFactor {
self.zoomFactor = zoomFactor
width = kBaseWidth * zoomFactor
height = width * 3 / 4
buffer = VmScreen.initBuffer(zoomFactor: zoomFactor)
}
}
final func step(tCycle: Int) {
for i in self.lastTCycle...tCycle {
processTCycle(tCycle: i)
}
self.lastTCycle = tCycle + 1
self.lastTCycle = (self.lastTCycle > FRAME_TSTATES ? self.lastTCycle - FRAME_TSTATES : self.lastTCycle)
}
final func updateFlashing() {
for i in 0..<0x300 {
addressUpdated.append(0x5800 + UInt16(i))
}
changed = true
}
final func setBorderData(borderData: BorderData) {
previousBorderColor = currentBorderData.color
currentBorderData = borderData
changed = true
}
final func updateScreenBuffer() {
updateBitmap()
changed = false
}
private func updateScreenBufferAt(_ address: UInt16) {
guard 0x4000 <= address && address <= 0x5AFF else {
return
}
if address < 0x5800 {
// btimap area
fillEightBitLineAt(address: address)
} else {
// attr area
updateCharAt(address: address)
}
}
private func fillEightBitLineAt(address: UInt16) {
guard let coord = getXYForAddress(address) else {
return
}
let value = memoryScreen.read(address)
let attribute = VmScreen.getAttribute(memoryScreen.read(getAttributeAddress(address)!))
fillEightBitLineAt(coord: coord, value: value, attribute: attribute)
}
private func fillEightBitLineAt(coord: (x: Int, y: Int), value: UInt8, attribute: Attribute) {
let inkColor: PixelData!
let paperColor: PixelData!
if flashState && attribute.flashing {
inkColor = attribute.paperColor
paperColor = attribute.inkColor
} else {
inkColor = attribute.inkColor
paperColor = attribute.paperColor
}
let bitmapCoord = (x: coord.x * 8 + 32, y: coord.y + 24)
var bit = 0
for i in (0...7).reversed() {
let index = getBufferIndex(bitmapCoord.x + bit, bitmapCoord.y)
let pixelData: PixelData = ((Int(value) & 1 << i) > 0) ? inkColor : paperColor
setBuffer(atIndex: index, withPixelData: pixelData)
bit += 1
}
}
private func updateCharAt(address: UInt16) {
let local_address = address & 0x3FFF
let offset = Int(local_address) & 0x7FF
let coord = (x: offset % 32, y: (offset / 32) * 8)
let attribute = VmScreen.getAttribute(memoryScreen.read(address))
let line_address = UInt16(0x4000 + coord.y * 32 + coord.x)
var line_address_corrected = (line_address & 0xF800)
line_address_corrected |= ((line_address & 0x700) >> 3)
line_address_corrected |= ((line_address & 0xE0) << 3)
line_address_corrected |= (line_address & 0x1F)
for i in 0...7 {
let coord_i = (coord.x, coord.y + i)
fillEightBitLineAt(coord: coord_i, value: memoryScreen.read(line_address_corrected + UInt16(i * 0x100)), attribute: attribute)
}
}
private func getBufferIndex(_ x: Int, _ y: Int) -> Int {
return y * zoomFactor * width + x * zoomFactor
}
private func setBuffer(atIndex index: Int, withPixelData pixelData: PixelData) {
for i in 0 ..< zoomFactor {
for j in 0 ..< zoomFactor {
if buffer[index + i + j * width] != pixelData {
buffer[index + i + j * width] = pixelData
}
}
}
}
static func getAttribute(_ value: UInt8) -> Attribute {
return Attribute(
flashing: (value & 0b10000000) > 0 ? true : false,
paperColor: colorTable[(Int(value) >> 3) & 0b00001111],
inkColor: colorTable[((Int(value) >> 3) & 0b00001000) | (Int(value) & 0b00000111)]
)
}
private static func initBuffer(zoomFactor: Int) -> [PixelData] {
let width = kBaseWidth * zoomFactor
let height = width * 3 / 4
return [PixelData](repeating: kWhiteColor, count: width * height)
}
private func getMemoryAddress(tCycle: Int) -> UInt16? {
guard tCycle % 4 == 1 else {
return nil
}
let line = (tCycle / 224 - 64)
guard 0 <= line && line <= 191 else {
return nil
}
let lineTCycleBase = 14336 + (224 * line)
let lineBaseAddress = 16384 + 32 * line
let offset = (tCycle - lineTCycleBase) / 4
guard 0 <= offset && offset <= 31 else {
return nil
}
return UInt16(lineBaseAddress + offset)
}
private func getAttributeAddress(_ address: UInt16) -> UInt16? {
guard let coord = getXYForAddress(address) else {
return nil
}
return UInt16(0x5800 + coord.x + (coord.y / 8) * 32)
}
private func processTCycle(tCycle: Int) {
if let coord = getBorderXY(tCycle: tCycle) {
updateBorderData(coord: coord, tCycle: tCycle)
}
guard let address = self.getMemoryAddress(tCycle: tCycle) else {
return
}
let attributeAddress = getAttributeAddress(address)!
let newValue = memory.readNoContention(address)
let newAttribute = memory.readNoContention(attributeAddress)
saveByteIntoBuffer(address: address, byte: newValue)
saveByteIntoBuffer(address: attributeAddress, byte: newAttribute)
}
private func updateBorderData(coord: (x: Int, y: Int), tCycle: Int) {
let colorToSet = tCycle < currentBorderData.tCycle ? previousBorderColor : currentBorderData.color
if buffer[getBufferIndex(coord.x, coord.y)] != colorToSet {
for i in 0...7 {
setBuffer(atIndex: getBufferIndex(coord.x + i, coord.y), withPixelData: colorToSet)
}
}
// when we are at the end of frame,
// assume current border data from the beginning of next frame
if tCycle >= kBorderLastTCycle {
currentBorderData.tCycle = 0
}
}
private func saveByteIntoBuffer(address: UInt16, byte: UInt8) {
guard byte != memoryScreen.read(address) else {
return
}
memoryScreen.write(address, value: byte)
addressUpdated.append(address)
changed = true
}
private func getXYForAddress(_ address: UInt16) -> (x: Int, y: Int)? {
let local_address = address & 0x3FFF
guard local_address < 0x1800 else {
return nil
}
let x = local_address.low & 0b00011111
var y = (local_address.high & 0b00011000) << 3
y |= (local_address.low & 0b11100000) >> 2
y |= local_address.high & 0b00000111
return (Int(x),Int(y))
}
private func getBorderXY(tCycle: Int) -> (x:Int, y:Int)? {
guard tCycle >= FIRST_VISIBLE_SCANLINE * SCANLINE_TSTATES - 24 else {
return nil
}
let y = (tCycle + 24) / SCANLINE_TSTATES - FIRST_VISIBLE_SCANLINE
let lineTCycleBase = 3584 + y * SCANLINE_TSTATES // left border first pixel
let x = (tCycle + 24 - lineTCycleBase) / 4
guard 2 <= x && x < 44 - 2 else {
return nil
}
guard 24 <= y && y < 288 - 24 else {
return nil
}
let res_x = (x - 2) * 8
let res_y = y - 24
if res_x >= 32 && res_x < 288 && res_y >= 24 && res_y < 216 {
return nil
}
return (res_x, res_y)
}
private func updateBitmap() {
for address in addressUpdated {
updateScreenBufferAt(address)
}
addressUpdated = []
}
private func fillFloatingData(line: Int, fromAddress: UInt16) {
var address = fromAddress
let baseline = line * 224
for i in stride(from: baseline, to: baseline + 127, by: 8) {
floatDataTable[i] = address
floatDataTable[i + 1] = getAttributeAddress(address)
floatDataTable[i + 2] = address + 1
floatDataTable[i + 3] = getAttributeAddress(address + 1)
address += 2
}
}
private func fillFloatingDataTable() {
var address: UInt16 = 0x4000
for line in 0...191 {
fillFloatingData(line: line, fromAddress: address)
address += 32
}
}
private func getFloatDataAddress(tCycle: Int) -> UInt16? {
guard 14339 <= tCycle && tCycle < 57344 else {
return nil
}
return floatDataTable[tCycle - 14339]
}
func getFloatData(tCycle: Int) -> UInt8 {
guard let address = getFloatDataAddress(tCycle: tCycle) else {
return 0xFF
}
return memory.readNoContention(address)
}
}
|
gpl-3.0
|
73e44e0a8d866f00cd57c2c9ed461147
| 29.341709 | 138 | 0.555316 | 3.886707 | false | false | false | false |
rharri/swift-ios
|
JustDataTaskDemo/JustDataTaskDemo/Post.swift
|
1
|
4161
|
//
// Post.swift
// HTTPSessionDemo
//
// Created by Ryan Harri on 2016-11-04.
// Copyright © 2016 Ryan Harri. All rights reserved.
//
import Foundation
/// Inspired by: https://developer.apple.com/swift/blog/?id=37
struct Post: ResourceObject {
typealias PostsHandler = (_ posts: [Post]?) -> Void
typealias PostHandler = (_ post: Post?) -> Void
static var path = "/posts"
let userID: Int
let postID: Int
let title: String
let body: String
init(json: [String:AnyObject]) throws {
guard let userID = json["userId"] as? Int else {
throw SerializationError.missing("userId")
}
guard let postID = json["id"] as? Int else {
throw SerializationError.missing("ID")
}
guard let title = json["title"] as? String else {
throw SerializationError.missing("title")
}
guard let body = json["body"] as? String else {
throw SerializationError.missing("body")
}
self.userID = userID
self.postID = postID
self.title = title
self.body = body
}
/// /posts
static func posts(_ completionHandler: @escaping PostsHandler) {
let URL = JSONPlaceholder.baseURL.appending(Post.path)
JustDataTask.sharedInstance.perform(.get, withURL: URL) { (data, error) in
guard error == nil else {
completionHandler(nil)
return
}
guard let data = data else {
completionHandler(nil)
return
}
var posts: [Post] = []
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as Any, let results = jsonObject as? [[String:AnyObject]] {
for case let result in results {
if let post = try? Post(json: result) {
posts.append(post)
}
}
completionHandler(posts)
}
}
}
/// /posts?userId={id}
static func posts(byUserID ID: Int, completionHandler: @escaping PostsHandler) {
let URL = JSONPlaceholder.baseURL.appending(Post.path)
let parameters: [URLQueryItem] = [
URLQueryItem(name: "userId", value: "\(ID)")
]
JustDataTask.sharedInstance.perform(.get, withURL: URL, headers: nil, parameters: parameters) { (data, error) in
guard error == nil else {
completionHandler(nil)
return
}
guard let data = data else {
completionHandler(nil)
return
}
var posts: [Post] = []
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as Any, let results = jsonObject as? [[String:AnyObject]] {
for case let result in results {
if let post = try? Post(json: result) {
posts.append(post)
}
}
completionHandler(posts)
}
}
}
/// /posts/{id}
static func post(byPostID postID: Int, completionHandler: @escaping PostHandler) {
let URL = JSONPlaceholder.baseURL.appending("\(Post.path)/\(postID)")
JustDataTask.sharedInstance.perform(.get, withURL: URL) { (data, error) in
guard error == nil else {
completionHandler(nil)
return
}
guard let data = data else {
completionHandler(nil)
return
}
if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as Any, let result = jsonObject as? [String:AnyObject] {
if let post = try? Post(json: result) {
completionHandler(post)
}
}
}
}
}
|
mit
|
c2b0c021328a6d2e03a3187105e007e9
| 30.755725 | 150 | 0.501683 | 5.12947 | false | false | false | false |
KieranHarper/KJHUIKit
|
Sources/Animation.swift
|
1
|
9597
|
//
// Animation.swift
// KJHUIKit
//
// Created by Kieran Harper on 16/7/17.
// Copyright © 2017 Kieran Harper. All rights reserved.
//
import UIKit
/// Animation closure which passes a view instance to configure what's being animated.
public typealias ViewAnimation<T: UIView> = (T) -> Void
/// Describer of the timing and nature of an animation.
public enum AnimationCurve {
case easing(curve: UIView.AnimationCurve, duration: TimeInterval, additive: Bool)
case spring(damping: CGFloat, initialVelocity: CGFloat, duration: TimeInterval, additive: Bool)
}
/// Useful constants when performing animations
public struct AnimationConstants {
/// Zero for the purposes of animating a transform scale to zero without breaking the math
public static let zeroScale: CGFloat = 0.0001
}
/// Helper structure to pair the animation closure with its curve.
public struct AnimationConfig<T: UIView> {
public let curve: AnimationCurve
public let animations: ViewAnimation<T>
public init(curve: AnimationCurve, animations: @escaping ViewAnimation<T>) {
self.curve = curve
self.animations = animations
}
}
/// Behaviour rules for how animations should interrupt others.
public enum AnimationPlayoutBehaviour {
/// Animation can immediately be interrupted by another animation.
case none
/// Other animations always wait for an animation to fully complete / play out.
case full
/// Other animations wait for a minimum interval to pass before potentially interrupting an animation.
case minimum(duration: TimeInterval)
}
/// Targets which can be asked to perform "tap down" and "tap up" behaviours
public protocol TapDownUpAnimatable {
associatedtype TargetType: UIView
/// Set the animation that will run on tap down (NOTE: this overrides any previous setting)
func animateOnTapDown(with curve: AnimationCurve, animations: @escaping ViewAnimation<TargetType>)
/// Set the animation that will run on tap up (NOTE: this overrides any previous setting)
func animateOnTapUp(with curve: AnimationCurve, animations: @escaping ViewAnimation<TargetType>)
/// Add any number of secondary tap down animations that trigger alongside the primary animation but run with different curves
func addSecondaryAnimationOnTapDown(with curve: AnimationCurve, animations: @escaping ViewAnimation<TargetType>)
/// Add any number of secondary tap up animations that trigger alongside the primary animation but run with different curves
func addSecondaryAnimationOnTapUp(with curve: AnimationCurve, animations: @escaping ViewAnimation<TargetType>)
/// Set a closure to run just before tap down animations run
func beforeTapDownAnimation(do closure: @escaping ()->())
/// Set a closure to run just before tap up animations run
func beforeTapUpAnimation(do closure: @escaping ()->())
/// Set a closure to run just after tap down animations run
func afterTapDownAnimation(do closure: @escaping ()->())
/// Set a closure to run just after tap up animations run
func afterTapUpAnimation(do closure: @escaping ()->())
}
/// Protocol for views that can perform "breathe" animations - ambient animations that are cycling or ongoing.
@objc public protocol Breathable {
/// Start the breathing animations
@objc func startBreathing()
/// Stop the breathing animations
@objc func stopBreathing()
/// Whether or not the view is currently breathing
@objc var isBreathing: Bool { get }
}
/// Protocol for views that can perform show and hide animations.
@objc public protocol ShowHideable {
/// Reveal the view with or without animation.
@objc func show(animate: Bool, alongside: (()->())?, completion: (()->())?)
/// Make the view disappear with or without animation.
@objc func hide(animate: Bool, alongside: (()->())?, completion: (()->())?)
/// Whether or not the view is currently showing
@objc var isShowing: Bool { get }
}
/// Protocol for views that can perform a brief "pulse" animation and return to normal - designed to draw attention to itself without interaction.
@objc public protocol Pulseable {
/// Perform the pulse animation.
@objc func pulse(completion: (()->())?)
}
/** Protocol for objects that will do animations on behalf of a target.
General guidelines for Animators:
- They should be retained by something else, rather than retain themselves (ie within animation blocks etc).
- They should not strongly retain the target.
- Controllers wishing to interrupt animations should cancel() the animator then stopAnimations() on the target.
- Views can encapsulate animators inside them for convenience and retention, and are encouraged to call cancel() on their animators when stopAnimations() is called.
- Animators should not call stopAnimations() on the target during cancel(), so as to avoid infinite loops when encapsulated within views. That's why it's called cancel - just prevent further animations that may not have been set yet. In many cases an animator may have nothing to do in response to cancel().
- Animators should contain actual animations (which may or may not be controlled by parameters) rather than just 'helper' logic. You should be able to simply apply an animator and see it working with default behaviours.
*/
public protocol Animator {
/// The view subclass the animator knows how to deal with (UIView may be sufficient).
associatedtype TargetType: UIView
/// The target view to animate. Should be weakly held!
var target: TargetType? { get }
/// Initialise with a target view to animate.
init(target: TargetType)
/// Prevent further animations from being scheduled on the target.
func cancel()
}
/// Handy helpers for UIView
public extension UIView {
/// Interrupt any running animations, forcing them to halt as they currently appear (rather than completing instantly or returning to their initial state)
@objc public func stopAnimations() {
if let presentation = self.layer.presentation() {
// Copy any animatable properties from the presentation layer to the model layer
layer.contents = presentation.contents
layer.contentsRect = presentation.contentsRect
layer.contentsCenter = presentation.contentsCenter
layer.opacity = presentation.opacity
layer.isHidden = presentation.isHidden
layer.masksToBounds = presentation.isHidden
layer.isDoubleSided = presentation.isDoubleSided
layer.cornerRadius = presentation.cornerRadius
layer.borderWidth = presentation.borderWidth
layer.borderColor = presentation.borderColor
layer.backgroundColor = presentation.backgroundColor
layer.shadowOpacity = presentation.shadowOpacity
layer.shadowRadius = presentation.shadowRadius
layer.shadowOffset = presentation.shadowOffset
layer.shadowColor = presentation.shadowColor
layer.shadowPath = presentation.shadowPath
layer.filters = presentation.filters
layer.compositingFilter = presentation.compositingFilter
layer.backgroundFilters = presentation.backgroundFilters
layer.shouldRasterize = presentation.shouldRasterize
layer.rasterizationScale = presentation.rasterizationScale
layer.bounds = presentation.bounds
layer.position = presentation.position
layer.zPosition = presentation.zPosition
layer.anchorPointZ = presentation.anchorPointZ
layer.anchorPoint = presentation.anchorPoint
layer.transform = presentation.transform
layer.sublayerTransform = presentation.sublayerTransform
}
self.layer.removeAllAnimations()
}
/// Apply the animations as set out in an animation config
public func runAnimation<T>(_ animationConfig: AnimationConfig<T>, delay: TimeInterval = 0.0, completion: ((Bool)->())? = nil) {
guard let selfRef = self as? T else { return }
let animations = {
animationConfig.animations(selfRef)
}
switch animationConfig.curve {
case .easing(let curve, let duration, let additive):
if !additive {
stopAnimations()
}
var translatedCurve: UIView.AnimationOptions
switch curve {
case .easeIn:
translatedCurve = .curveEaseIn
case .easeOut:
translatedCurve = .curveEaseOut
case .easeInOut:
translatedCurve = .curveEaseInOut
case .linear:
translatedCurve = .curveLinear
}
translatedCurve = [translatedCurve, .allowUserInteraction, .beginFromCurrentState]
UIView.animate(withDuration: duration, delay: delay, options: translatedCurve, animations: animations, completion: completion)
case .spring(let damping, let initialVelocity, let duration, let additive):
if !additive {
stopAnimations()
}
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: .allowUserInteraction, animations: animations, completion: completion)
}
}
}
|
mit
|
b64c631d980180fa12c0944267501ba4
| 41.460177 | 308 | 0.693414 | 5.378924 | false | false | false | false |
justindarc/firefox-ios
|
Client/Frontend/Share/ShareExtensionHelper.swift
|
2
|
6850
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import OnePasswordExtension
private let log = Logger.browserLogger
class ShareExtensionHelper: NSObject {
fileprivate weak var selectedTab: Tab?
fileprivate let selectedURL: URL // for non copy ones
fileprivate let fileURL: URL? // for copy type
fileprivate var onePasswordExtensionItem: NSExtensionItem!
fileprivate let browserFillIdentifier = "org.appextension.fill-browser-action"
init(url: URL, file: URL? = nil, tab: Tab?) {
self.selectedURL = tab?.canonicalURL?.displayURL ?? url
self.selectedTab = tab
self.fileURL = file
}
func createActivityViewController(_ completionHandler: @escaping (_ completed: Bool, _ activityType: UIActivity.ActivityType?) -> Void) -> UIActivityViewController {
var activityItems = [AnyObject]()
let printInfo = UIPrintInfo(dictionary: nil)
let absoluteString = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString
printInfo.jobName = absoluteString
printInfo.outputType = .general
activityItems.append(printInfo)
if let tab = selectedTab {
activityItems.append(TabPrintPageRenderer(tab: tab))
}
if let title = selectedTab?.title {
activityItems.append(TitleActivityItemProvider(title: title))
}
activityItems.append(self)
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// Hide 'Add to Reading List' which currently uses Safari.
// We would also hide View Later, if possible, but the exclusion list doesn't currently support
// third-party activity types (rdar://19430419).
activityViewController.excludedActivityTypes = [
UIActivity.ActivityType.addToReadingList,
]
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
findLoginExtensionItem()
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if !completed {
completionHandler(completed, activityType)
return
}
// Bug 1392418 - When copying a url using the share extension there are 2 urls in the pasteboard.
// This is a iOS 11.0 bug. Fixed in 11.2
if UIPasteboard.general.hasURLs, let url = UIPasteboard.general.urls?.first {
UIPasteboard.general.urls = [url]
}
if self.isPasswordManager(activityType: activityType) {
if let logins = returnedItems {
self.fillPasswords(logins as [AnyObject])
}
}
completionHandler(completed, activityType)
}
return activityViewController
}
}
extension ShareExtensionHelper: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return fileURL ?? selectedURL
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
if isPasswordManager(activityType: activityType) {
return onePasswordExtensionItem
} else if isOpenByCopy(activityType: activityType) {
return fileURL ?? selectedURL
}
// Return the URL for the selected tab. If we are in reader view then decode
// it so that we copy the original and not the internal localhost one.
return selectedURL.isReaderModeURL ? selectedURL.decodeReaderModeURL : selectedURL
}
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
if isPasswordManager(activityType: activityType) {
return browserFillIdentifier
} else if isOpenByCopy(activityType: activityType) {
return fileURL != nil ? kUTTypeFileURL as String : kUTTypeURL as String
}
return activityType == nil ? browserFillIdentifier : kUTTypeURL as String
}
private func isPasswordManager(activityType: UIActivity.ActivityType?) -> Bool {
guard let activityType = activityType?.rawValue else { return false }
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier.
return (activityType.range(of: "password") != nil)
|| (activityType == "com.lastpass.ilastpass.LastPassExt")
|| (activityType == "in.sinew.Walletx.WalletxExt")
|| (activityType == "com.8bit.bitwarden.find-login-action-extension")
|| (activityType == "me.mssun.passforios.find-login-action-extension")
}
private func isOpenByCopy(activityType: UIActivity.ActivityType?) -> Bool {
guard let activityType = activityType?.rawValue else { return false }
return activityType.lowercased().range(of: "remoteopeninapplication-bycopy") != nil
}
}
private extension ShareExtensionHelper {
func findLoginExtensionItem() {
guard let selectedWebView = selectedTab?.webView else {
return
}
// Add 1Password to share sheet
OnePasswordExtension.shared().createExtensionItem(forWebView: selectedWebView, completion: {(extensionItem, error) -> Void in
if extensionItem == nil {
log.error("Failed to create the password manager extension item: \(error.debugDescription).")
return
}
// Set the 1Password extension item property
self.onePasswordExtensionItem = extensionItem
})
}
func fillPasswords(_ returnedItems: [AnyObject]) {
guard let selectedWebView = selectedTab?.webView else {
return
}
OnePasswordExtension.shared().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in
if !success {
log.error("Failed to fill item into webview: \(returnedItemsError ??? "nil").")
}
})
}
}
|
mpl-2.0
|
0a141599cfa5d785bc03103c4311161d
| 42.630573 | 169 | 0.673577 | 5.488782 | false | false | false | false |
domenicosolazzo/practice-swift
|
Games/TextShooter/TextShooter/StartScene.swift
|
1
|
1320
|
//
// StartScene.swift
// TextShooter
//
// Created by Domenico on 01/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import SpriteKit
class StartScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
backgroundColor = SKColor.green
let topLabel = SKLabelNode(fontNamed: "Courier")
topLabel.text = "TextShooter"
topLabel.fontColor = SKColor.black
topLabel.fontSize = 48
topLabel.position = CGPoint(x: frame.size.width/2,
y: frame.size.height * 0.7)
addChild(topLabel)
let bottomLabel = SKLabelNode(fontNamed: "Courier")
bottomLabel.text = "Touch anywhere to start"
bottomLabel.fontColor = SKColor.black
bottomLabel.fontSize = 20
bottomLabel.position = CGPoint(x: frame.size.width/2,
y: frame.size.height * 0.3)
addChild(bottomLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<NSObject>,
with event: UIEvent) {
let transition = SKTransition.doorway(withDuration: 1.0)
let game = GameScene(size:frame.size)
view!.presentScene(game, transition: transition)
}
}
|
mit
|
30b527282af2a84a6bbd47e09afdcdb3
| 29 | 68 | 0.621212 | 4.217252 | false | false | false | false |
snakajima/vs-metal
|
vs-metal/vs-metal/VSVideoSessionController.swift
|
1
|
2425
|
//
// VSVideoSessionController.swift
// vs-metal
//
// Created by SATOSHI NAKAJIMA on 6/20/17.
// Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved.
//
import UIKit
import AVFoundation
import MetalKit
class VSVideoSessionController: UIViewController {
// Public properties to be specified by the callers
var urlScript:URL?
// VideoShader properties
var context:VSContext = VSContext(device: MTLCreateSystemDefaultDevice()!)
var runtime:VSRuntime!
lazy var session:VSCaptureSession = VSCaptureSession(device: self.context.device, pixelFormat: self.context.pixelFormat, delegate: self.context)
lazy var renderer:VSRenderer = VSRenderer(device:self.context.device, pixelFormat:self.context.pixelFormat)
// For benchmark
var frameCount = 0
var totalTime = CFTimeInterval(0.0)
override func viewDidLoad() {
super.viewDidLoad()
if let mtkView = self.view as? MTKView,
let script = VSScript.load(from: urlScript) {
runtime = script.compile(context: context)
context.pixelFormat = mtkView.colorPixelFormat
mtkView.device = context.device
mtkView.delegate = self
mtkView.transform = (session.cameraPosition == .front) ? CGAffineTransform(scaleX: -1.0, y: 1.0) : CGAffineTransform.identity
session.preset = AVCaptureSessionPreset640x480
session.start()
}
}
deinit {
print("Average Elapsed Time = ", totalTime / Double(frameCount))
}
}
extension VSVideoSessionController : MTKViewDelegate {
public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {}
public func draw(in view: MTKView) {
if context.hasUpdate {
let commandBuffer = runtime.encode(commandBuffer: context.makeCommandBuffer(label: "myCompute"), context: context)
let startTime = CFAbsoluteTimeGetCurrent()
commandBuffer.addCompletedHandler(){ (_) in
self.totalTime += CFAbsoluteTimeGetCurrent() - startTime
self.frameCount += 1
}
commandBuffer.commit()
if let texture = context.pop() {
renderer.encode(commandBuffer:context.makeCommandBuffer(label: "myRender"), view:view, texture: texture.texture)?
.commit()
}
context.flush()
}
}
}
|
mit
|
f557fb4bb167650fbaa8e71262313b4a
| 33.628571 | 148 | 0.651403 | 4.625954 | false | false | false | false |
zxwWei/SwfitZeng
|
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/Main(主要)/View/XWCompassView.swift
|
1
|
10629
|
//
// XWCompassView.swift
// XWWeibo
//
// Created by apple on 15/10/26.
// Copyright © 2015年 ZXW. All rights reserved.
//
import UIKit
// MARK: - 代理协议
protocol XWCompassViewDelegate: NSObjectProtocol {
func vistorWillRegegister()
func vistorWillLogin()
}
class XWCompassView: UIView {
// MARK: - 判断遵守代理的控制器是否遵守代理方法
weak var vistorDelegate: XWCompassViewDelegate?
func willRegister() {
// 如果遵守代理执行?后面的方法
vistorDelegate?.vistorWillRegegister()
}
func willLogin() {
vistorDelegate?.vistorWillLogin()
}
// MARK: - 初始化方法
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.prepareUi()
}
// MARK: - 准备UI
func prepareUi() {
// 往view添加子控件
addSubview(rotationIconView)
addSubview(coverImage)
addSubview(homeView)
// addSubview(coverImage)
addSubview(messageLabel)
addSubview(registerButton)
addSubview(loginButton)
// 设置约束
rotationIconView.translatesAutoresizingMaskIntoConstraints = false
homeView.translatesAutoresizingMaskIntoConstraints = false
coverImage.translatesAutoresizingMaskIntoConstraints = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
registerButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.translatesAutoresizingMaskIntoConstraints = false
// 添加约束
// 转轮 centerX
addConstraint(NSLayoutConstraint(item: rotationIconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: rotationIconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -40))
// 小房子
addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: rotationIconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: rotationIconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
// 信息
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: homeView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: homeView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 44))
// 信息的宽度
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 240))
// 登陆按钮
// 左边
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
// 顶部
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// 宽度
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 36))
// 注册按钮
// 右边
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
// 顶部
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// 宽度
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 36))
// 渲染图层
// 左边
addConstraint(NSLayoutConstraint(item: self.coverImage, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: self.coverImage, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: self.coverImage, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
// 与注册按钮约定约束
addConstraint(NSLayoutConstraint(item: self.coverImage, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.registerButton, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1)
}
// MARK: - 不同的控制器显示不同的信息
func setupVistorView(message: String, rotationViewName: String){
homeView.hidden = true
rotationIconView.image = UIImage(named: rotationViewName )
messageLabel.text = message;
// 将子控件放在最下面
sendSubviewToBack(coverImage)
}
// MARK: - 旋转方法
func rotation(){
// 创建动画对象
let anim = CABasicAnimation()
// transform.rotation
anim.keyPath = "transform.rotation"
anim.toValue = 2 * M_PI
anim.repeatCount = MAXFLOAT
anim.duration = 20
// 完成时不移除动画
anim.removedOnCompletion = false
rotationIconView.layer.addAnimation(anim, forKey: "rotation")
}
/// 暂停旋转
func pauseAnimation() {
// 记录暂停时间
let pauseTime = rotationIconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
// 设置动画速度为0
rotationIconView.layer.speed = 0
// 设置动画偏移时间
rotationIconView.layer.timeOffset = pauseTime
}
/// 恢复旋转
func resumeAnimation() {
// 获取暂停时间
let pauseTime = rotationIconView.layer.timeOffset
// 设置动画速度为1
rotationIconView.layer.speed = 1
rotationIconView.layer.timeOffset = 0
rotationIconView.layer.beginTime = 0
let timeSincePause = rotationIconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pauseTime
rotationIconView.layer.beginTime = timeSincePause
}
// MARK: - 懒加载
/// 旋转的图像
private lazy var rotationIconView: UIImageView = {
let iconView = UIImageView()
iconView.image = UIImage(named: "visitordiscover_feed_image_smallicon")
// 自动适配图像
iconView.sizeToFit()
return iconView
}()
/// 小房子
private lazy var homeView: UIImageView = {
let homeView = UIImageView()
homeView.image = UIImage(named: "visitordiscover_feed_image_house")
homeView.sizeToFit()
return homeView
}()
/// 信息
private lazy var messageLabel: UILabel = {
let messageLabel = UILabel()
messageLabel.text = "想看更多的好东西吗"
messageLabel.textColor = UIColor.blackColor()
// 设置分行
messageLabel.numberOfLines = 0
messageLabel.textAlignment = NSTextAlignment.Center
messageLabel.sizeToFit()
return messageLabel
}()
/// 注册按钮
private lazy var registerButton: UIButton = {
let registerButton = UIButton()
registerButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
registerButton.setTitle("注册", forState: UIControlState.Normal)
registerButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
registerButton.addTarget(self , action: "willRegister", forControlEvents: UIControlEvents.TouchUpInside)
registerButton.sizeToFit()
return registerButton
}()
/// 登陆按钮
private lazy var loginButton: UIButton = {
let loginButton = UIButton()
// setBackgroundImage 才会切割
loginButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
loginButton.setTitle("登陆", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
loginButton.addTarget(self , action: "willLogin", forControlEvents: UIControlEvents.TouchUpInside)
loginButton.sizeToFit()
return loginButton
}()
/// 渲染图层
private lazy var coverImage: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
}
|
apache-2.0
|
ea9fbcbd923b4b024dda8e62861f5d80
| 38.166023 | 230 | 0.681487 | 5.364357 | false | false | false | false |
HenryFanDi/HFSwipeTableViewCell
|
HFSwipeTableViewCell/HFSwipeButton.swift
|
1
|
2799
|
//
// HFSwipeButton.swift
// HFSwipeTableViewCell
//
// Created by HenryFan on 15/9/2016.
// Copyright © 2016 HenryFanDi. All rights reserved.
//
import UIKit
enum HFSwipeButtonType {
case hfSwipeButtonUnknown
case hfSwipeButtonDial
}
protocol HFSwipeButtonDelegate {
func dialBtnOnTap()
}
class HFSwipeButton: UIButton {
var delegate: HFSwipeButtonDelegate?
fileprivate var swipeButtonType: HFSwipeButtonType
fileprivate let swipeImageView: UIImageView
fileprivate var swipeImageSize: CGFloat
// MARK: Lifecycle
convenience required init?(coder aDecoder: NSCoder) {
self.init(swipeButtonType: .hfSwipeButtonUnknown)
}
init(swipeButtonType: HFSwipeButtonType) {
self.delegate = nil
self.swipeButtonType = swipeButtonType
self.swipeImageView = UIImageView()
self.swipeImageSize = 0.0
super.init(frame: CGRect.zero)
setupButton()
}
// MARK: Private
fileprivate func setupButton() {
setupSwipeButton()
setupSwipeImageView()
setupSwipeButtonWithSwipeButtonType()
setupSwipeButtonConstraints()
}
fileprivate func setupSwipeButton() {
translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setupSwipeImageView() {
swipeImageSize = 20.0
swipeImageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(swipeImageView)
}
fileprivate func setupSwipeButtonWithSwipeButtonType() {
var btnBackgroundColor = .white as UIColor
var imageNamed = ""
switch swipeButtonType {
case .hfSwipeButtonDial:
btnBackgroundColor = .init(red: 255.0/255.0, green: 198.0/255.0, blue: 26.0/255.0, alpha: 1.0)
imageNamed = "Dial"
addTarget(self, action: #selector(HFSwipeButton.dialBtnOnTap), for: .touchUpInside)
break
default:
break
}
backgroundColor = btnBackgroundColor
swipeImageView.image = UIImage.init(named: imageNamed)
}
fileprivate func setupSwipeButtonConstraints() {
swipeImageView.addConstraints([
NSLayoutConstraint.init(item: swipeImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: swipeImageSize),
NSLayoutConstraint.init(item: swipeImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: swipeImageSize)
])
addConstraints([
NSLayoutConstraint.init(item: swipeImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint.init(item: swipeImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)
])
}
// MARK: Dial
func dialBtnOnTap() {
delegate?.dialBtnOnTap()
}
}
|
mit
|
d09427c3a38035a08736539dc4a83ab9
| 28.145833 | 167 | 0.720157 | 4.413249 | false | false | false | false |
ddki/my_study_project
|
language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/tunnel_server/ServerTunnelConnection.swift
|
1
|
9630
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the ServerTunnelConnection class. The ServerTunnelConnection class handles the encapsulation and decapsulation of IP packets in the server side of the SimpleTunnel tunneling protocol.
*/
import Foundation
import Darwin
/// An object that provides a bridge between a logical flow of packets in the SimpleTunnel protocol and a UTUN interface.
class ServerTunnelConnection: Connection {
// MARK: Properties
/// The virtual address of the tunnel.
var tunnelAddress: String?
/// The name of the UTUN interface.
var utunName: String?
/// A dispatch source for the UTUN interface socket.
var utunSource: dispatch_source_t?
/// A flag indicating if reads from the UTUN interface are suspended.
var isSuspended = false
// MARK: Interface
/// Send an "open result" message with optionally the tunnel settings.
func sendOpenResult(result: TunnelConnectionOpenResult, extraProperties: [String: AnyObject] = [:]) {
guard let serverTunnel = tunnel else { return }
var resultProperties = extraProperties
resultProperties[TunnelMessageKey.ResultCode.rawValue] = result.rawValue
let properties = createMessagePropertiesForConnection(identifier, commandType: .OpenResult, extraProperties: resultProperties)
serverTunnel.sendMessage(properties)
}
/// "Open" the connection by setting up the UTUN interface.
func open() -> Bool {
// Allocate the tunnel virtual address.
guard let address = ServerTunnel.configuration.addressPool?.allocateAddress() else {
simpleTunnelLog("Failed to allocate a tunnel address")
sendOpenResult(.Refused)
return false
}
// Create the virtual interface and assign the address.
guard setupVirtualInterface(address) else {
simpleTunnelLog("Failed to set up the virtual interface")
ServerTunnel.configuration.addressPool?.deallocateAddress(address)
sendOpenResult(.InternalError)
return false
}
tunnelAddress = address
var response = [String: AnyObject]()
// Create a copy of the configuration, so that it can be personalized with the tunnel virtual interface.
var personalized = ServerTunnel.configuration.configuration
guard let IPv4Dictionary = personalized[SettingsKey.IPv4.rawValue] as? [NSObject: AnyObject] else {
simpleTunnelLog("No IPv4 Settings available")
sendOpenResult(.InternalError)
return false
}
// Set up the "IPv4" sub-dictionary to contain the tunne virtual address and network mask.
var newIPv4Dictionary = IPv4Dictionary
newIPv4Dictionary[SettingsKey.Address.rawValue] = tunnelAddress
newIPv4Dictionary[SettingsKey.Netmask.rawValue] = "255.255.255.255"
personalized[SettingsKey.IPv4.rawValue] = newIPv4Dictionary
response[TunnelMessageKey.Configuration.rawValue] = personalized
// Send the personalized configuration along with the "open result" message.
sendOpenResult(.Success, extraProperties: response)
return true
}
/// Create a UTUN interface.
func createTUNInterface() -> Int32 {
let utunSocket = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL)
guard utunSocket >= 0 else {
simpleTunnelLog("Failed to open a kernel control socket")
return -1
}
let controlIdentifier = getUTUNControlIdentifier(utunSocket)
guard controlIdentifier > 0 else {
simpleTunnelLog("Failed to get the control ID for the utun kernel control")
close(utunSocket)
return -1
}
// Connect the socket to the UTUN kernel control.
var socketAddressControl = sockaddr_ctl(sc_len: UInt8(sizeof(sockaddr_ctl.self)), sc_family: UInt8(AF_SYSTEM), ss_sysaddr: UInt16(AF_SYS_CONTROL), sc_id: controlIdentifier, sc_unit: 0, sc_reserved: (0, 0, 0, 0, 0))
let connectResult = withUnsafePointer(&socketAddressControl) {
connect(utunSocket, UnsafePointer<sockaddr>($0), socklen_t(sizeofValue(socketAddressControl)))
}
if let errorString = String(UTF8String: strerror(errno)) where connectResult < 0 {
simpleTunnelLog("Failed to create a utun interface: \(errorString)")
close(utunSocket)
return -1
}
return utunSocket
}
/// Get the name of a UTUN interface the associated socket.
func getTUNInterfaceName(utunSocket: Int32) -> String? {
var buffer = [Int8](count: Int(IFNAMSIZ), repeatedValue: 0)
var bufferSize: socklen_t = socklen_t(buffer.count)
let resultCode = getsockopt(utunSocket, SYSPROTO_CONTROL, getUTUNNameOption(), &buffer, &bufferSize)
if let errorString = String(UTF8String: strerror(errno)) where resultCode < 0 {
simpleTunnelLog("getsockopt failed while getting the utun interface name: \(errorString)")
return nil
}
return String(UTF8String: &buffer)
}
/// Set up the UTUN interface, start reading packets.
func setupVirtualInterface(address: String) -> Bool {
let utunSocket = createTUNInterface()
guard let interfaceName = getTUNInterfaceName(utunSocket)
where utunSocket >= 0 &&
setUTUNAddress(interfaceName, address)
else { return false }
startTunnelSource(utunSocket)
utunName = interfaceName
return true
}
/// Read packets from the UTUN interface.
func readPackets() {
guard let source = utunSource else { return }
var packets = [NSData]()
var protocols = [NSNumber]()
// We use a 2-element iovec list. The first iovec points to the protocol number of the packet, the second iovec points to the buffer where the packet should be read.
var buffer = [UInt8](count: Tunnel.packetSize, repeatedValue:0)
var protocolNumber: UInt32 = 0
var iovecList = [ iovec(iov_base: &protocolNumber, iov_len: sizeofValue(protocolNumber)), iovec(iov_base: &buffer, iov_len: buffer.count) ]
let iovecListPointer = UnsafeBufferPointer<iovec>(start: &iovecList, count: iovecList.count)
let utunSocket = Int32(dispatch_source_get_handle(source))
repeat {
let readCount = readv(utunSocket, iovecListPointer.baseAddress, Int32(iovecListPointer.count))
guard readCount > 0 || errno == EAGAIN else {
if let errorString = String(UTF8String: strerror(errno)) where readCount < 0 {
simpleTunnelLog("Got an error on the utun socket: \(errorString)")
}
dispatch_source_cancel(source)
break
}
guard readCount > sizeofValue(protocolNumber) else { break }
if protocolNumber.littleEndian == protocolNumber {
protocolNumber = protocolNumber.byteSwapped
}
protocols.append(NSNumber(unsignedInt: protocolNumber))
packets.append(NSData(bytes: &buffer, length: readCount - sizeofValue(protocolNumber)))
// Buffer up packets so that we can include multiple packets per message. Once we reach a per-message maximum send a "packets" message.
if packets.count == Tunnel.maximumPacketsPerMessage {
tunnel?.sendPackets(packets, protocols: protocols, forConnection: identifier)
packets = [NSData]()
protocols = [NSNumber]()
if isSuspended { break } // If the entire message could not be sent and the connection is suspended, stop reading packets.
}
} while true
// If there are unsent packets left over, send them now.
if packets.count > 0 {
tunnel?.sendPackets(packets, protocols: protocols, forConnection: identifier)
}
}
/// Start reading packets from the UTUN interface.
func startTunnelSource(utunSocket: Int32) {
guard setSocketNonBlocking(utunSocket) else { return }
guard let newSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, UInt(utunSocket), 0, dispatch_get_main_queue()) else { return }
dispatch_source_set_cancel_handler(newSource) {
close(utunSocket)
return
}
dispatch_source_set_event_handler(newSource) {
self.readPackets()
}
dispatch_resume(newSource)
utunSource = newSource
}
// MARK: Connection
/// Abort the connection.
override func abort(error: Int = 0) {
super.abort(error)
closeConnection(.All)
}
/// Close the connection.
override func closeConnection(direction: TunnelConnectionCloseDirection) {
super.closeConnection(direction)
if currentCloseDirection == .All {
if utunSource != nil {
dispatch_source_cancel(utunSource!)
}
// De-allocate the address.
if tunnelAddress != nil {
ServerTunnel.configuration.addressPool?.deallocateAddress(tunnelAddress!)
}
utunName = nil
}
}
/// Stop reading packets from the UTUN interface.
override func suspend() {
isSuspended = true
if let source = utunSource {
dispatch_suspend(source)
}
}
/// Resume reading packets from the UTUN interface.
override func resume() {
isSuspended = false
if let source = utunSource {
dispatch_resume(source)
readPackets()
}
}
/// Write packets and associated protocols to the UTUN interface.
override func sendPackets(packets: [NSData], protocols: [NSNumber]) {
guard let source = utunSource else { return }
let utunSocket = Int32(dispatch_source_get_handle(source))
for (index, packet) in packets.enumerate() {
guard index < protocols.count else { break }
var protocolNumber = protocols[index].unsignedIntValue.bigEndian
let buffer = UnsafeMutablePointer<Void>(packet.bytes)
var iovecList = [ iovec(iov_base: &protocolNumber, iov_len: sizeofValue(protocolNumber)), iovec(iov_base: buffer, iov_len: packet.length) ]
let writeCount = writev(utunSocket, &iovecList, Int32(iovecList.count))
if writeCount < 0 {
if let errorString = String(UTF8String: strerror(errno)) {
simpleTunnelLog("Got an error while writing to utun: \(errorString)")
}
}
else if writeCount < packet.length + sizeofValue(protocolNumber) {
simpleTunnelLog("Wrote \(writeCount) bytes of a \(packet.length) byte packet to utun")
}
}
}
}
|
mit
|
d56a985fd689ce4a23eb5d289d266227
| 34.397059 | 216 | 0.741795 | 3.665017 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Onboarding/PageCell.swift
|
1
|
4532
|
//
// PageCell.swift
// audible
//
// Created by Josh Doman on 11/23/16.
// Copyright © 2016 Josh Doman. All rights reserved.
//
import UIKit
class PageCell: UICollectionViewCell {
private lazy var confettiView: SAConfettiView = SAConfettiView(frame: self.bounds)
var page: OnboardingPage? {
didSet {
guard let page = page else {
return
}
imageView.image = UIImage(named: page.imageName)
let color = UIColor(white: 0.2, alpha: 1)
let attributedText = NSMutableAttributedString(string: page.title, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium), convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): color]))
attributedText.append(NSAttributedString(string: "\n\n\(page.message)", attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.systemFont(ofSize: 14), convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): color])))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let length = attributedText.string.count
attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: length))
textView.attributedText = attributedText
imageView.removeFromSuperview()
addSubview(imageView)
_ = imageView.anchor(nil, left: leftAnchor, bottom: textView.topAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
if page.isFullScreen {
imageView.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
} else {
let height = imageView.image!.size.height / imageView.image!.size.width * UIScreen.main.bounds.size.width
imageView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
if page.showConfetti {
addSubview(confettiView)
confettiView.startConfetti()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .white
iv.contentMode = .scaleAspectFit
iv.image = #imageLiteral(resourceName: "Onboard 1")
iv.clipsToBounds = false // clips image so same size as screen
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
let textView: UITextView = {
let tv = UITextView()
tv.text = "SAMPLE TEXT"
tv.isEditable = false
tv.contentInset = UIEdgeInsets(top: 24, left: 0, bottom: 0, right: 0)
return tv
}()
let lineSeperatorView: UIView = {
let view = UIView()
view.backgroundColor = .grey6
return view
}()
func setupViews() {
addSubview(imageView)
addSubview(textView)
addSubview(lineSeperatorView)
textView.anchorWithConstantsToTop(nil, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 16, bottomConstant: 0, rightConstant: 16)
textView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.3).isActive = true
lineSeperatorView.anchorToTop(nil, left: leftAnchor, bottom: textView.topAnchor, right: rightAnchor)
lineSeperatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
|
mit
|
1cd1c8597e11daef7cfc423db14cc3c9
| 37.726496 | 347 | 0.679762 | 5.125566 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsComponents/BadgeCellPresenters/CardIssuingCellPresenter.swift
|
1
|
1297
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import PlatformUIKit
import RxRelay
import RxSwift
/// A `BadgeCellPresenting` class for showing the user's card issuing status
final class CardIssuingCellPresenter: BadgeCellPresenting {
private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell
// MARK: - Properties
let accessibility: Accessibility = .id(AccessibilityId.CardIssuing.title)
let labelContentPresenting: LabelContentPresenting
let badgeAssetPresenting: BadgeAssetPresenting
var isLoading: Bool {
isLoadingRelay.value
}
// MARK: - Private Properties
private let isLoadingRelay = BehaviorRelay<Bool>(value: true)
private let disposeBag = DisposeBag()
// MARK: - Setup
init(interactor: CardIssuingBadgeInteractor) {
labelContentPresenting = DefaultLabelContentPresenter(
knownValue: LocalizationConstants.Settings.Badge.cardIssuing,
descriptors: .settings
)
badgeAssetPresenting = DefaultBadgeAssetPresenter(
interactor: interactor
)
badgeAssetPresenting.state
.map(\.isLoading)
.bindAndCatch(to: isLoadingRelay)
.disposed(by: disposeBag)
}
}
|
lgpl-3.0
|
1e040ac1e148f94466643ee0703a2c2c
| 29.139535 | 86 | 0.712963 | 5.634783 | false | false | false | false |
bcesur/FitPocket
|
FitPocket/FitPocket/ExerciseViewController.swift
|
1
|
2080
|
//
// ExerciseViewController.swift
// FitPocket
//
// Created by Berkay Cesur on 23/12/14.
// Copyright (c) 2014 Berkay Cesur. All rights reserved.
//
import UIKit
var exerciseArray = [Exercise]()
class ExerciseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBAction func backButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exerciseArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println(exerciseArray.isEmpty)
let exerciseIndex = indexPath.item
var cell = tableView.dequeueReusableCellWithIdentifier("exerciseCell") as! UITableViewCell
cell.textLabel!.text = exerciseArray[exerciseIndex].toString()
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
exerciseArray.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
/*
// 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.
}
*/
}
|
gpl-2.0
|
fefecd2fdec43965aa329e39f47c9f7a
| 30.515152 | 148 | 0.689423 | 5.667575 | false | false | false | false |
ohde-sg/SwiftCrypton
|
SwiftCrypton/SHA256.swift
|
1
|
4523
|
//
// SHA256.swift
// Crypton
//
// Created by 大出喜之 on 2015/12/14.
// Copyright © 2015年 yoshiyuki ohde. All rights reserved.
//
import Foundation
class SHA256 : HashAlgo ,HashAlgoProtocol{
// Initialize hash values:
// (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
var h0:UInt32 = 0x6a09e667 // a
var h1:UInt32 = 0xbb67ae85 // b
var h2:UInt32 = 0x3c6ef372 // c
var h3:UInt32 = 0xa54ff53a // d
var h4:UInt32 = 0x510e527f // e
var h5:UInt32 = 0x9b05688c // f
var h6:UInt32 = 0x1f83d9ab // g
var h7:UInt32 = 0x5be0cd19 // h
// Initialize array of round constants:
// (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):
let initK: [UInt32] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
func getHashedByteArray(data: NSData) -> [UInt8]{
return getHashedByteArray(self.toUInt8Array(data))
}
func getHashedByteArray(bytes: [UInt8]) -> [UInt8] {
//パディング処理
let paddedArray = getUInt8ArrayWithPadding(bytes)
//ハッシュ処理
//バイト配列から4バイト配列に変換
let uintArray = getUInt32Array(paddedArray)
var a: UInt32
var b: UInt32
var c: UInt32
var d: UInt32
var e: UInt32
var f: UInt32
var g: UInt32
var h: UInt32
for index in 0..<(paddedArray.count/64) {
//indexで指定したメッセージブロックを取得
let msgBlock = getMsgBlockByIndex(uintArray,index:index)
//拡張ブロックを作成
let extBlock = getExtendedMsgBlock(msgBlock)
a = h0
b = h1
c = h2
d = h3
e = h4
f = h5
g = h6
h = h7
var T1:UInt32 = 0
var T2:UInt32 = 0
for t in 0..<64 {
T1 = h &+ sigmaU1(e) &+ Ch(e,y: f,z: g) &+ initK[t] &+ extBlock[t]
T2 = sigmaU0(a) &+ Maj(a, y: b, z: c)
h = g
g = f
f = e
e = d &+ T1
d = c
c = b
b = a
a = T1 &+ T2
#if DEBUG
dump_hash(index,t:t,dmp: [a,b,c,d,e,f,g,h])
#endif
}
h0 = a &+ h0
h1 = b &+ h1
h2 = c &+ h2
h3 = d &+ h3
h4 = e &+ h4
h5 = f &+ h5
h6 = g &+ h6
h7 = h &+ h7
}
let rtnArray = [h0,h1,h2,h3,h4,h5,h6,h7]
return toUInt8Array(rtnArray)
}
//メッセージブロック(長さ16のUInt32配列)から拡張メッセージブロックを返す
private func getExtendedMsgBlock(msgBlock: [UInt32]) -> [UInt32] {
var rtnArray = msgBlock
for i in 16 ..< 64 {
rtnArray.append(sigmaL1(rtnArray[i-2]) &+ rtnArray[i-7] &+ sigmaL0(rtnArray[i-15]) &+ rtnArray[i-16])
}
return rtnArray
}
private func sigmaU0(x: UInt32) -> UInt32 {
return ROTR(x,n: 2) ^ ROTR(x, n: 13) ^ ROTR(x, n: 22)
}
private func sigmaU1(x: UInt32) -> UInt32 {
return ROTR(x,n: 6) ^ ROTR(x, n: 11) ^ ROTR(x, n: 25)
}
private func sigmaL0(x: UInt32) -> UInt32 {
return ROTR(x,n: 7) ^ ROTR(x, n: 18) ^ SHR(x, n: 3)
}
private func sigmaL1(x: UInt32) -> UInt32 {
return ROTR(x,n: 17) ^ ROTR(x, n: 19) ^ SHR(x, n: 10)
}
}
|
mit
|
04fa540eb4f7e401cc3240757d6a780c
| 27.96 | 113 | 0.530157 | 2.71161 | false | false | false | false |
banxi1988/BXForm
|
Pod/Classes/Cells/InputGroupView.swift
|
1
|
2662
|
//
// InputCell.swift
// Pods
//
// Created by Haizhen Lee on 16/1/7.
//
//
import Foundation
// Build for target uimodel
//locale (None, None)
import UIKit
import SwiftyJSON
import BXModel
import BXiOSUtils
// -InputView:v
// _[l15,y,r15,r0]:f
// span[w115,ver0,r0]:b
open class InputGroupView : UIView{
open let textField = UITextField(frame:CGRect.zero)
open let spanButton = UIButton(type:.custom)
open var showSpanButton:Bool = true{
didSet{
spanButton.isHidden = !showSpanButton
relayout()
}
}
open var showSpanDivider:Bool = true{
didSet{
setNeedsDisplay()
}
}
open var spanDividerColor:UIColor = UIColor(white: 0.937, alpha: 1.0){
didSet{
setNeedsDisplay()
}
}
open var spanDividerLineWidth:CGFloat = 1.0{
didSet{
setNeedsDisplay()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
open override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [textField,spanButton]
}
var allUIButtonOutlets :[UIButton]{
return [spanButton]
}
var allUITextFieldOutlets :[UITextField]{
return [textField]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit(){
installChildViews()
installConstaints()
setupAttrs()
}
func relayout(){
for childView in allOutlets{
childView.removeFromSuperview()
}
installChildViews()
installConstaints()
}
func installChildViews(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
}
func installConstaints(){
textField.pa_centerY.install()
textField.pa_leading.eq(15).install()
textField.pa_height.eq(32).install()
if showSpanButton{
textField.pa_before(spanButton, offset: 4).install()
spanButton.pa_trailingMargin.eq(0).install()
spanButton.pac_vertical(0)
spanButton.pa_width.eq(115).install()
}else{
textField.pa_trailingMargin.eq(FormMetrics.cellPaddingLeft).install()
}
}
open func setupAttrs(){
backgroundColor = .white
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if showSpanButton && showSpanDivider{
let ctx = UIGraphicsGetCurrentContext()
let startX = spanButton.frame.minX
spanDividerColor.setStroke()
ctx?.move(to: CGPoint(x: startX, y: rect.minY))
ctx?.addLine(to: CGPoint(x: startX, y: rect.maxY))
ctx?.strokePath()
}
}
}
|
mit
|
c7637afb590ccce414309362423e053e
| 19.320611 | 75 | 0.647633 | 4.015083 | false | false | false | false |
eraydiler/password-locker
|
PasswordLockerSwift/Classes/Controller/Onboarding/SplashViewController.swift
|
1
|
734
|
//
// SplashViewController.swift
// PasswordLockerSwift
//
// Created by Eray on 21/04/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
class SplashViewController: UIViewController {
private let TAG = "SplashViewController"
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
var segueID = ""
(checkPassword()) ? (segueID = "toAuthenticationVCSegue") : (segueID = "toCreatePasswordVCSegue")
self.performSegue(withIdentifier: segueID, sender: nil)
}
// Helper Methods
func checkPassword() -> Bool {
return (KeychainService.value(forKey: KeychainService.appPasswordKey) != nil)
}
}
|
mit
|
a0d77a1818fc1306bf7b8a56cf33e5f4
| 24.310345 | 105 | 0.66485 | 4.267442 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.