repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FsThatOne/VOne | refs/heads/master | VOne/Classes/Controller/Main/FSMainViewController.swift | mit | 1 | //
// FSMainViewController.swift
// VOne
//
// Created by 王正一 on 16/7/19.
// Copyright © 2016年 FsThatOne. All rights reserved.
//
import UIKit
class FSMainViewController: UITabBarController {
fileprivate lazy var funnyBtn: UIButton = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
setupChildViewControllers()
// rainbowTabbar()
// setupFunnyButton()
}
// 设置支持的屏幕方向, 设置之后, 当前控制器和其子控制器都遵循这个道理, modal视图不受影响
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
// MARK: 设置界面
extension FSMainViewController {
fileprivate func setupChildViewControllers() {
let dictArr = [
["name": "SessionsViewController", "title": "聊天", "imageName": "chat"],
["name": "ContactViewController", "title": "通讯录", "imageName": "contact"],
["name": "MomentsViewController", "title": "圈子", "imageName": "mycircle"],
["name": "MineViewController", "title": "个人中心", "imageName": "mine_center"],
]
var controllersArray = [UIViewController]()
for item in dictArr {
controllersArray.append(controller(item))
}
viewControllers = controllersArray
}
fileprivate func controller(_ dict: [String: String]) -> UIViewController {
// 配置字典内容
guard let vcName = dict["name"],
let vcTitle = dict["title"],
let vcImage = dict["imageName"],
// 反射机制取得vc
let cls = NSClassFromString(Bundle.main.nameSpace + "." + vcName) as? FSBaseViewController.Type
else {
return UIViewController()
}
// 根据字典内容设置UI
let vc = cls.init()
vc.title = vcTitle
vc.tabBarItem.image = UIImage(named: vcImage)?.withRenderingMode(.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(named: vcImage)
let nav = FSNavigationController(rootViewController: vc)
return nav
}
// fileprivate func rainbowTabbar() {
// let rainbowLayer: CAGradientLayer = CAGradientLayer()
// rainbowLayer.frame = tabBar.bounds
// rainbowLayer.colors = [UIColor(red:0.244, green:0.673, blue:0.183, alpha:1).cgColor, UIColor(red:0.376, green:0.564, blue:0.984, alpha:1).cgColor]
// tabBar.layer.insertSublayer(rainbowLayer, at: 0)
// }
//
// fileprivate func setupFunnyButton() {
//
// let itemCount = CGFloat(childViewControllers.count)
// let itemWidth = (tabBar.bounds.width / itemCount) - 1
//
// funnyBtn.setBackgroundImage(UIImage(named: "heartBeat")?.withRenderingMode(.alwaysOriginal), for: .normal)
// funnyBtn.contentMode = .center
// funnyBtn.frame = tabBar.bounds.insetBy(dx: 2 * itemWidth, dy: 0)
//
// tabBar.addSubview(funnyBtn)
// }
}
| 250d86b2778c4df5d1fdb4e423ed7e68 | 33.282353 | 156 | 0.615305 | false | false | false | false |
honishi/Hakumai | refs/heads/main | Hakumai/Controllers/MainWindowController/TableCellView/TimeTableCellView.swift | mit | 1 | //
// TimeTableCellView.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 11/25/14.
// Copyright (c) 2014 Hiroyuki Onishi. All rights reserved.
//
import Foundation
import AppKit
private let defaultTimeValue = "-"
final class TimeTableCellView: NSTableCellView {
@IBOutlet weak var coloredView: ColoredView!
@IBOutlet weak var timeLabel: NSTextField!
var fontSize: CGFloat? { didSet { set(fontSize: fontSize) } }
}
extension TimeTableCellView {
func configure(live: Live?, message: Message?) {
coloredView.fillColor = color(message: message)
timeLabel.stringValue = time(live: live, message: message)
}
}
private extension TimeTableCellView {
func color(message: Message?) -> NSColor {
guard let message = message else { return UIHelper.systemMessageBgColor() }
switch message.content {
case .system:
return UIHelper.systemMessageBgColor()
case .chat(let chat):
return chat.isSystem ? UIHelper.systemMessageBgColor() : UIHelper.greenScoreColor()
case .debug:
return UIHelper.debugMessageBgColor()
}
}
func time(live: Live?, message: Message?) -> String {
guard let message = message else { return defaultTimeValue }
switch message.content {
case .system, .debug:
return "[\(message.date.toLocalTimeString())]"
case .chat(chat: let chat):
guard let beginDate = live?.beginTime,
let elapsed = chat.date.toElapsedTimeString(from: beginDate) else {
return defaultTimeValue
}
return elapsed
}
}
func set(fontSize: CGFloat?) {
let size = fontSize ?? CGFloat(kDefaultFontSize)
timeLabel.font = NSFont.systemFont(ofSize: size)
}
}
private extension Date {
func toElapsedTimeString(from fromDate: Date) -> String? {
let comps = Calendar.current.dateComponents(
[.hour, .minute, .second], from: fromDate, to: self)
guard let h = comps.hour, let m = comps.minute, let s = comps.second else { return nil }
return "\(h):\(m.zeroPadded):\(s.zeroPadded)"
}
func toLocalTimeString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "H:mm:ss"
return formatter.string(from: self)
}
}
private extension Int {
var zeroPadded: String { String(format: "%02d", self) }
}
| f5875ebfadb936b88455a785fd5969a9 | 30.358974 | 96 | 0.634914 | false | false | false | false |
abonz/Swift | refs/heads/master | CoreLocation/CoreLocation/ViewController.swift | gpl-3.0 | 6 | //
// ViewController.swift
// CoreLocation
//
// Created by Carlos Butron on 19/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager: CLLocationManager = CLLocationManager()
var myLatitude: CLLocationDegrees!
var myLongitude: CLLocationDegrees!
var finalLatitude: CLLocationDegrees!
var finalLongitude: CLLocationDegrees!
var distance: CLLocationDistance!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let tap = UITapGestureRecognizer(target: self, action: "action:")
myMap.addGestureRecognizer(tap)
}
func action(gestureRecognizer:UIGestureRecognizer) {
let touchPoint = gestureRecognizer.locationInView(self.myMap)
let newCoord:CLLocationCoordinate2D = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)
let getLat: CLLocationDegrees = newCoord.latitude
let getLon: CLLocationDegrees = newCoord.longitude
//Convert to points to CLLocation. In this way we can measure distanceFromLocation
let newCoord2: CLLocation = CLLocation(latitude: getLat, longitude: getLon)
let newCoord3: CLLocation = CLLocation(latitude: myLatitude, longitude: myLongitude)
finalLatitude = newCoord2.coordinate.latitude
finalLongitude = newCoord2.coordinate.longitude
print("Original Latitude: \(myLatitude)")
print("Original Longitude: \(myLongitude)")
print("Final Latitude: \(finalLatitude)")
print("Final Longitude: \(finalLongitude)")
//distance between our position and the new point created
let distance = newCoord2.distanceFromLocation(newCoord3)
print("Distance between two points: \(distance)")
let newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoord
newAnnotation.title = "My target"
newAnnotation.subtitle = ""
myMap.addAnnotation(newAnnotation)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
//get data from placemark
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
myLongitude = (containsPlacemark.location!.coordinate.longitude)
myLatitude = (containsPlacemark.location!.coordinate.latitude)
// testing show data
print("Locality: \(locality)")
print("PostalCode: \(postalCode)")
print("Area: \(administrativeArea)")
print("Country: \(country)")
print(myLatitude)
print(myLongitude)
//update map with my location
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1 , 0.1)
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: myLatitude, longitude: myLongitude)
let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan)
myMap.setRegion(theRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location " + error.localizedDescription)
}
//distance between two points
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }
func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {
let lat1 = degreesToRadians(point1.coordinate.latitude)
let lon1 = degreesToRadians(point1.coordinate.longitude)
let lat2 = degreesToRadians(point2.coordinate.latitude);
let lon2 = degreesToRadians(point2.coordinate.longitude);
print("Start latitude: \(point1.coordinate.latitude)")
print("Start longitude: \(point1.coordinate.longitude)")
print("Final latitude: \(point2.coordinate.latitude)")
print("Final longitude: \(point2.coordinate.longitude)")
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radiansBearing)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| c4d705149153a0515e99c73af8d4f775 | 38.034091 | 126 | 0.647889 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/FriendRequest/FriendRequestView.swift | mit | 1 | //
// FriendRequestView.swift
// Yep
//
// Created by nixzhu on 15/8/14.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class FriendRequestView: UIView {
static let height: CGFloat = 60
enum State {
case Add(prompt: String)
case Consider(prompt: String, friendRequestID: String)
var prompt: String {
switch self {
case .Add(let prompt):
return prompt
case .Consider(let prompt, _):
return prompt
}
}
var friendRequestID: String? {
switch self {
case .Consider( _, let friendRequestID):
return friendRequestID
default:
return nil
}
}
}
let state: State
init(state: State) {
self.state = state
super.init(frame: CGRectZero)
self.stateLabel.text = state.prompt
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var user: User? {
willSet {
if let user = newValue {
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nicknameLabel.text = user.nickname
}
}
}
var addAction: (FriendRequestView -> Void)?
var acceptAction: (FriendRequestView -> Void)?
var rejectAction: (FriendRequestView -> Void)?
lazy var avatarImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
lazy var nicknameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(16)
label.text = "NIX"
label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.9)
return label
}()
lazy var stateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(14)
label.numberOfLines = 0
label.textColor = UIColor.grayColor().colorWithAlphaComponent(0.9)
return label
}()
func baseButton() -> UIButton {
let button = UIButton()
button.setContentHuggingPriority(300, forAxis: UILayoutConstraintAxis.Horizontal)
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 15, bottom: 5, right: 15)
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
button.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled)
button.layer.cornerRadius = 5
return button
}
lazy var addButton: UIButton = {
let button = self.baseButton()
button.setTitle(NSLocalizedString("button.add", comment: ""), forState: .Normal)
button.backgroundColor = UIColor.yepTintColor()
button.addTarget(self, action: #selector(FriendRequestView.tryAddAction), forControlEvents: .TouchUpInside)
return button
}()
lazy var acceptButton: UIButton = {
let button = self.baseButton()
button.setTitle(NSLocalizedString("button.accept", comment: ""), forState: .Normal)
button.backgroundColor = UIColor.yepTintColor()
button.addTarget(self, action: #selector(FriendRequestView.tryAcceptAction), forControlEvents: .TouchUpInside)
return button
}()
lazy var rejectButton: UIButton = {
let button = self.baseButton()
button.setTitle(NSLocalizedString("Reject", comment: ""), forState: .Normal)
button.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
button.addTarget(self, action: #selector(FriendRequestView.tryRejectAction), forControlEvents: .TouchUpInside)
return button
}()
// MARK: Actions
func tryAddAction() {
addAction?(self)
}
func tryAcceptAction() {
acceptAction?(self)
}
func tryRejectAction() {
rejectAction?(self)
}
// MARK: UI
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.clearColor()
makeUI()
}
class ContainerView: UIView {
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.clearColor()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
let y = CGRectGetHeight(rect)
CGContextMoveToPoint(context, 0, y)
CGContextAddLineToPoint(context, CGRectGetWidth(rect), y)
let bottomLineWidth: CGFloat = 1 / UIScreen.mainScreen().scale
CGContextSetLineWidth(context, bottomLineWidth)
UIColor.lightGrayColor().setStroke()
CGContextStrokePath(context)
}
}
func makeUI() {
let blurEffect = UIBlurEffect(style: .ExtraLight)
let visualEffectView = UIVisualEffectView(effect: blurEffect)
visualEffectView.translatesAutoresizingMaskIntoConstraints = false
addSubview(visualEffectView)
let containerView = ContainerView()
containerView.translatesAutoresizingMaskIntoConstraints = false
addSubview(containerView)
avatarImageView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(avatarImageView)
nicknameLabel.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(nicknameLabel)
stateLabel.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(stateLabel)
let viewsDictionary: [String: AnyObject] = [
"visualEffectView": visualEffectView,
"containerView": containerView,
]
// visualEffectView
let visualEffectViewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[visualEffectView]|", options: [], metrics: nil, views: viewsDictionary)
let visualEffectViewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[visualEffectView]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(visualEffectViewConstraintH)
NSLayoutConstraint.activateConstraints(visualEffectViewConstraintV)
// containerView
let containerViewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: [], metrics: nil, views: viewsDictionary)
let containerViewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(containerViewConstraintH)
NSLayoutConstraint.activateConstraints(containerViewConstraintV)
// avatarImageView
let avatarImageViewCenterY = NSLayoutConstraint(item: avatarImageView, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0)
let avatarImageViewLeading = NSLayoutConstraint(item: avatarImageView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: YepConfig.chatCellGapBetweenWallAndAvatar())
let avatarImageViewWidth = NSLayoutConstraint(item: avatarImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: YepConfig.chatCellAvatarSize())
let avatarImageViewHeight = NSLayoutConstraint(item: avatarImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: YepConfig.chatCellAvatarSize())
NSLayoutConstraint.activateConstraints([avatarImageViewCenterY, avatarImageViewLeading, avatarImageViewWidth, avatarImageViewHeight])
// nicknameLabel
let nicknameLabelTop = NSLayoutConstraint(item: nicknameLabel, attribute: .Top, relatedBy: .Equal, toItem: avatarImageView, attribute: .Top, multiplier: 1, constant: 0)
let nicknameLabelLeft = NSLayoutConstraint(item: nicknameLabel, attribute: .Left, relatedBy: .Equal, toItem: avatarImageView, attribute: .Right, multiplier: 1, constant: 8)
NSLayoutConstraint.activateConstraints([nicknameLabelTop, nicknameLabelLeft])
// stateLabel
let stateLabelTop = NSLayoutConstraint(item: stateLabel, attribute: .Top, relatedBy: .Equal, toItem: nicknameLabel, attribute: .Bottom, multiplier: 1, constant: 0)
let stateLabelBottom = NSLayoutConstraint(item: stateLabel, attribute: .Bottom, relatedBy: .LessThanOrEqual, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: -4)
let stateLabelLeft = NSLayoutConstraint(item: stateLabel, attribute: .Left, relatedBy: .Equal, toItem: nicknameLabel, attribute: .Left, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([stateLabelTop, stateLabelBottom, stateLabelLeft])
switch state {
case .Add:
// addButton
addButton.translatesAutoresizingMaskIntoConstraints = false
addButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
containerView.addSubview(addButton)
let addButtonTrailing = NSLayoutConstraint(item: addButton, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: -YepConfig.chatCellGapBetweenWallAndAvatar())
let addButtonCenterY = NSLayoutConstraint(item: addButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([addButtonTrailing, addButtonCenterY])
// labels' right
let nicknameLabelRight = NSLayoutConstraint(item: nicknameLabel, attribute: .Right, relatedBy: .Equal, toItem: addButton, attribute: .Left, multiplier: 1, constant: -8)
let stateLabelRight = NSLayoutConstraint(item: stateLabel, attribute: .Right, relatedBy: .Equal, toItem: addButton, attribute: .Left, multiplier: 1, constant: -8)
NSLayoutConstraint.activateConstraints([nicknameLabelRight, stateLabelRight])
case .Consider:
// acceptButton
acceptButton.translatesAutoresizingMaskIntoConstraints = false
acceptButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
containerView.addSubview(acceptButton)
let acceptButtonTrailing = NSLayoutConstraint(item: acceptButton, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: -YepConfig.chatCellGapBetweenWallAndAvatar())
let acceptButtonCenterY = NSLayoutConstraint(item: acceptButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([acceptButtonTrailing, acceptButtonCenterY])
// rejectButton
rejectButton.translatesAutoresizingMaskIntoConstraints = false
rejectButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
containerView.addSubview(rejectButton)
let rejectButtonRight = NSLayoutConstraint(item: rejectButton, attribute: .Right, relatedBy: .Equal, toItem: acceptButton, attribute: .Left, multiplier: 1, constant: -8)
let rejectButtonCenterY = NSLayoutConstraint(item: rejectButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([rejectButtonRight, rejectButtonCenterY])
// labels' right
let nicknameLabelRight = NSLayoutConstraint(item: nicknameLabel, attribute: .Right, relatedBy: .Equal, toItem: rejectButton, attribute: .Left, multiplier: 1, constant: -8)
let stateLabelRight = NSLayoutConstraint(item: stateLabel, attribute: .Right, relatedBy: .Equal, toItem: rejectButton, attribute: .Left, multiplier: 1, constant: -8)
NSLayoutConstraint.activateConstraints([nicknameLabelRight, stateLabelRight])
}
}
}
| b464f2667100fd6332f83aa8e1c6dd66 | 41.698305 | 234 | 0.693792 | false | false | false | false |
VladiMihaylenko/omim | refs/heads/master | iphone/Maps/Classes/CarPlay/Template Builders/ListTemplateBuilder.swift | apache-2.0 | 1 | import CarPlay
@available(iOS 12.0, *)
final class ListTemplateBuilder {
enum ListTemplateType {
case history
case bookmarkLists
case bookmarks(category: MWMCategory)
case searchResults(results: [MWMCarPlaySearchResultObject])
}
enum BarButtonType {
case bookmarks
case search
}
// MARK: - CPListTemplate bilder
class func buildListTemplate(for type: ListTemplateType) -> CPListTemplate {
var title = ""
var trailingNavigationBarButtons = [CPBarButton]()
switch type {
case .history:
title = L("pick_destination")
let bookmarksButton = buildBarButton(type: .bookmarks) { _ in
let listTemplate = ListTemplateBuilder.buildListTemplate(for: .bookmarkLists)
CarPlayService.shared.pushTemplate(listTemplate, animated: true)
}
let searchButton = buildBarButton(type: .search) { _ in
if CarPlayService.shared.isKeyboardLimited {
CarPlayService.shared.showKeyboardAlert()
} else {
let searchTemplate = SearchTemplateBuilder.buildSearchTemplate()
CarPlayService.shared.pushTemplate(searchTemplate, animated: true)
}
}
trailingNavigationBarButtons = [searchButton, bookmarksButton]
case .bookmarkLists:
title = L("bookmarks")
case .searchResults:
title = L("search_results")
case .bookmarks(let category):
title = category.title
}
let template = CPListTemplate(title: title, sections: [])
template.trailingNavigationBarButtons = trailingNavigationBarButtons
obtainResources(for: type, template: template)
return template
}
private class func obtainResources(for type: ListTemplateType, template: CPListTemplate) {
switch type {
case .history:
obtainHistory(template: template)
case .bookmarks(let category):
obtainBookmarks(template: template, categoryId: category.categoryId)
case .bookmarkLists:
obtainCategories(template: template)
case .searchResults(let results):
convertSearchResults(results, template: template)
}
}
private class func obtainHistory(template: CPListTemplate) {
let searchQueries = FrameworkHelper.obtainLastSearchQueries() ?? []
let items = searchQueries.map({ (text) -> CPListItem in
let item = CPListItem(text: text, detailText: nil, image: UIImage(named: "ic_carplay_recent"))
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.history,
metadata: nil)
return item
})
let section = CPListSection(items: items)
template.updateSections([section])
}
private class func obtainCategories(template: CPListTemplate) {
let bookmarkManager = MWMBookmarksManager.shared()
let categories = bookmarkManager.userCategories()
let items: [CPListItem] = categories.compactMap({ category in
if category.bookmarksCount == 0 { return nil }
let placesString = String(format: L("bookmarks_places"), category.bookmarksCount)
let item = CPListItem(text: category.title, detailText: placesString)
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.bookmarkLists,
metadata: CategoryInfo(category: category))
return item
})
let section = CPListSection(items: items)
template.updateSections([section])
}
private class func obtainBookmarks(template: CPListTemplate, categoryId: MWMMarkGroupID) {
let bookmarkManager = MWMBookmarksManager.shared()
let bookmarks = bookmarkManager.bookmarks(forCategory: categoryId)
let items = bookmarks.map({ (bookmark) -> CPListItem in
let item = CPListItem(text: bookmark.prefferedName, detailText: bookmark.address)
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.bookmarks,
metadata: BookmarkInfo(categoryId: categoryId,
bookmarkId: bookmark.bookmarkId))
return item
})
let section = CPListSection(items: items)
template.updateSections([section])
}
private class func convertSearchResults(_ results: [MWMCarPlaySearchResultObject], template: CPListTemplate) {
var items = [CPListItem]()
for object in results {
let item = CPListItem(text: object.title, detailText: object.address)
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.searchResults,
metadata: SearchResultInfo(originalRow: object.originalRow))
items.append(item)
}
let section = CPListSection(items: items)
template.updateSections([section])
}
// MARK: - CPBarButton builder
private class func buildBarButton(type: BarButtonType, action: ((CPBarButton) -> Void)?) -> CPBarButton {
switch type {
case .bookmarks:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_bookmark")
return button
case .search:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_keyboard")
return button
}
}
}
| 4450b2c660885a38b810d455e7bc9208 | 38.813953 | 112 | 0.685164 | false | false | false | false |
MatheusGodinho/SnapKitLearning | refs/heads/master | SnapKitCRUD/ViewController.swift | mit | 1 | //
// ViewController.swift
// SnapKitCRUD
//
// Created by Matheus Godinho on 15/09/16.
// Copyright © 2016 Godinho. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController{
//Declare controller
let userController = UserController()
// Center View
let fieldsView = CenterFieldView()
let buttonBox = SocialView()
let finalPage = ButtonPageView()
let logoView = LogoView()
//Background
let backgroundView = UIImageView()
let faceButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureBackgroundView(superview: self.view!)
fieldsView.configureCenterView(superview: self)
buttonBox.configureButtonBox(superview: self.view!)
finalPage.configureButtonPageView(superview: self.view!)
logoView.configureView(superview: self.view!)
self.setDelegates()
self.addObservers()
self.dismissKeyboard()
}
override func viewWillDisappear(_ animated: Bool) {
self.removeObservers()
}
private func configureBackgroundView(superview:UIView){
superview.addSubview(self.backgroundView)
let image = #imageLiteral(resourceName: "ui_bg_login")
self.backgroundView.image = image
backgroundView.snp.makeConstraints { (make) in
make.size.equalTo(superview)
}
self.hideKeyboardWhenTappedAround()
}
func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func removeObservers() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: view.window)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: view.window)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height/2
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height/2
}
}
}
}
| f5d543bb38acbb5f352b0105a715e569 | 30.703297 | 165 | 0.658579 | false | true | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Shared/Activity/ActivityType.swift | mit | 1 | //
// ActivityType.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 8/24/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
enum ActivityType: String {
case restoration = "Restoration"
case selectFeed = "SelectFeed"
case nextUnread = "NextUnread"
case readArticle = "ReadArticle"
case addFeedIntent = "AddFeedIntent"
}
| 3db045d6a1f700ab81929af698409648 | 21.058824 | 60 | 0.730667 | false | false | false | false |
iamyuiwong/swift-common | refs/heads/master | errno/PosixErrno.swift | lgpl-3.0 | 1 | /*
* NAME PosixErrno.swift
*
* C 15/9/30 +0800
*
* DESC
* - Xcode 7.0.1 / Swift 2.0.1 supported (Created)
*
* V1.0.0.0_
*/
import Foundation
/*
* NAME PosixErrno - class PosixErrno
*/
class PosixErrno {
static func errno2string (posixErrno _en: Int32) -> String {
var en: Int32 = 0
if (_en < 0) {
en = -_en;
} else {
en = _en;
}
let cs = strerror(en)
let ret = StringUtil.toString(fromCstring: cs,
encoding: NSUTF8StringEncoding)
if (nil != ret) {
return ret!
} else {
return "Unresolved \(en)"
}
}
}
| b538f55c4873287dc78afac72b77194a | 13.578947 | 61 | 0.581227 | false | false | false | false |
koba-uy/chivia-app-ios | refs/heads/master | src/Chivia/Services/Internal/GeocodingService.swift | lgpl-3.0 | 1 | //
// File.swift
// Chivia
//
// Created by Agustín Rodríguez on 10/21/17.
// Copyright © 2017 Agustín Rodríguez. All rights reserved.
//
import Alamofire
import CoreLocation
import PromiseKit
import SwiftyJSON
class GeocodingService {
let GEOCODING_SERVICE_URL = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyC_LXnJZa7FXv_xsz8_WCL_4Ltt1MdExNU"
func get(address: String) -> Promise<CLLocationCoordinate2D> {
return Promise { fulfill, reject in
Alamofire
.request("\(GEOCODING_SERVICE_URL)&address=\(address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)")
.validate()
.responseJSON { response in
if response.result.isSuccess, let data = response.data {
let json = JSON(data: data)
let location = json["results"][0]["geometry"]["location"]
let lat = location["lat"].doubleValue
let lng = location["lng"].doubleValue
fulfill(CLLocationCoordinate2D(latitude: lat, longitude: lng))
}
else if let data = response.data {
let json = JSON(data: data)
reject(GenericError(message: json["message"].stringValue))
}
else if let err = response.error {
reject(err)
}
}
}
}
}
| 2b6b2a27bb28116ffd4ca2254d0dcbb8 | 35.642857 | 147 | 0.545809 | false | false | false | false |
iosphere/ISHPullUp | refs/heads/master | ISHPullUpSample/ISHPullUpSample/BottomVC.swift | mit | 1 | //
// ScrollViewController.swift
// ISHPullUpSample
//
// Created by Felix Lamouroux on 25.06.16.
// Copyright © 2016 iosphere GmbH. All rights reserved.
//
import UIKit
import ISHPullUp
import MapKit
class BottomVC: UIViewController, ISHPullUpSizingDelegate, ISHPullUpStateDelegate {
@IBOutlet private weak var handleView: ISHPullUpHandleView!
@IBOutlet private weak var rootView: UIView!
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var topLabel: UILabel!
@IBOutlet private weak var topView: UIView!
@IBOutlet private weak var buttonLock: UIButton?
private var firstAppearanceCompleted = false
weak var pullUpController: ISHPullUpViewController!
// we allow the pullUp to snap to the half way point
private var halfWayPoint = CGFloat(0)
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
topView.addGestureRecognizer(tapGesture)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
firstAppearanceCompleted = true;
}
@objc
private func handleTapGesture(gesture: UITapGestureRecognizer) {
if pullUpController.isLocked {
return
}
pullUpController.toggleState(animated: true)
}
@IBAction private func buttonTappedLearnMore(_ sender: AnyObject) {
// for demo purposes we replace the bottomViewController with a web view controller
// there is no way back in the sample app though
// This also highlights the behaviour of the pullup view controller without a sizing and state delegate
let webVC = WebViewController()
webVC.loadURL(URL(string: "https://iosphere.de")!)
pullUpController.bottomViewController = webVC
}
@IBAction private func buttonTappedLock(_ sender: AnyObject) {
pullUpController.isLocked = !pullUpController.isLocked
buttonLock?.setTitle(pullUpController.isLocked ? "Unlock" : "Lock", for: .normal)
}
// MARK: ISHPullUpSizingDelegate
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, maximumHeightForBottomViewController bottomVC: UIViewController, maximumAvailableHeight: CGFloat) -> CGFloat {
let totalHeight = rootView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
// we allow the pullUp to snap to the half way point
// we "calculate" the cached value here
// and perform the snapping in ..targetHeightForBottomViewController..
halfWayPoint = totalHeight / 2.0
return totalHeight
}
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, minimumHeightForBottomViewController bottomVC: UIViewController) -> CGFloat {
return topView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height;
}
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, targetHeightForBottomViewController bottomVC: UIViewController, fromCurrentHeight height: CGFloat) -> CGFloat {
// if around 30pt of the half way point -> snap to it
if abs(height - halfWayPoint) < 30 {
return halfWayPoint
}
// default behaviour
return height
}
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, update edgeInsets: UIEdgeInsets, forBottomViewController bottomVC: UIViewController) {
// we update the scroll view's content inset
// to properly support scrolling in the intermediate states
scrollView.contentInset = edgeInsets;
}
// MARK: ISHPullUpStateDelegate
func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, didChangeTo state: ISHPullUpState) {
topLabel.text = textForState(state);
handleView.setState(ISHPullUpHandleView.handleState(for: state), animated: firstAppearanceCompleted)
// Hide the scrollview in the collapsed state to avoid collision
// with the soft home button on iPhone X
UIView.animate(withDuration: 0.25) { [weak self] in
self?.scrollView.alpha = (state == .collapsed) ? 0 : 1;
}
}
private func textForState(_ state: ISHPullUpState) -> String {
switch state {
case .collapsed:
return "Drag up or tap"
case .intermediate:
return "Intermediate"
case .dragging:
return "Hold on"
case .expanded:
return "Drag down or tap"
@unknown default:
return "Unknown value"
}
}
}
class ModalViewController: UIViewController {
@IBAction func buttonTappedDone(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
| 81418bcecd90b1da9f59d5b182dbf514 | 37.244094 | 190 | 0.701256 | false | false | false | false |
appsquickly/Typhoon-Swift-Example | refs/heads/master | PocketForecastTests/Integration/WeatherClientTests.swift | apache-2.0 | 1 | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import PocketForecast
public class WeatherClientTests : XCTestCase {
var weatherClient: WeatherClient!
public override func setUp() {
let assembly = ApplicationAssembly().activate()
let configurer = TyphoonConfigPostProcessor()
configurer.useResourceWithName("Configuration.plist")
assembly.attachPostProcessor(configurer)
self.weatherClient = assembly.coreComponents.weatherClient() as! WeatherClient
}
public func test_it_receives_a_wather_report_given_a_valid_city() {
var receivedReport : WeatherReport?
self.weatherClient.loadWeatherReportFor("Manila", onSuccess: {
(weatherReport) in
receivedReport = weatherReport
}, onError: {
(message) in
print("Unexpected error: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedReport != nil
}, andPerformTests: {
print(String(format: "Got report: %@", receivedReport!))
})
}
public func test_it_invokes_error_block_given_invalid_city() {
var receivedMessage : String?
self.weatherClient.loadWeatherReportFor("Foobarville", onSuccess: nil, onError: {
(message) in
receivedMessage = message
print("Got message: " + message)
})
TyphoonTestUtils.waitForCondition( { () -> Bool in
return receivedMessage == "Unable to find any matching weather location to the query submitted!"
})
}
}
| b515d2f23cdd6784c2df615d418baf48 | 28.253333 | 108 | 0.541933 | false | true | false | false |
safx/TypetalkApp | refs/heads/master | TypetalkApp/iOS/ViewControllers/MessageListViewController.swift | mit | 1 | //
// MessageListViewController.swift
// TypetalkApp
//
// Created by Safx Developer on 2014/11/08.
// Copyright (c) 2014年 Safx Developers. All rights reserved.
//
import UIKit
import TypetalkKit
import RxSwift
import SlackTextViewController
class MessageListViewController: SLKTextViewController {
private let viewModel = MessageListViewModel()
typealias CompletionModel = CompletionDataSource.CompletionModel
var completionList = [CompletionModel]()
var oldNumberOfRows = 0
private let disposeBag = DisposeBag()
var topic: TopicWithUserInfo? {
didSet {
self.configureView()
self.viewModel.fetch(topic!.topic.id)
}
}
/*override init!(tableViewStyle style: UITableViewStyle) {
super.init(tableViewStyle: .Plain)
}
required init!(coder decoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}*/
override class func tableViewStyleForCoder(decoder: NSCoder) -> UITableViewStyle {
return .Plain
}
func configureView() {
// Update the user interface for the detail item.
if let t = self.topic {
self.title = t.topic.name
}
}
override func viewDidLoad() {
super.viewDidLoad()
inverted = true
shouldScrollToBottomAfterKeyboardShows = true
bounces = true
shakeToClearEnabled = true
keyboardPanningEnabled = true
tableView?.separatorStyle = .None
tableView?.estimatedRowHeight = 64
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.registerClass(MessageCell.self, forCellReuseIdentifier: "MessageCell")
textView.placeholder = NSLocalizedString("Message", comment: "Message")
//let icon = IonIcons.imageWithIcon(icon_arrow_down_c, size: 30, color:UIColor.grayColor())
//leftButton.setImage(icon, forState: .Normal)
registerPrefixesForAutoCompletion(["@", "#", ":"])
autoCompletionView.registerClass(AutoCompletionCell.self, forCellReuseIdentifier: "AutoCompletionCell")
self.configureView()
weak var weakTableView = tableView
viewModel.model.posts.rx_events()
.observeOn(MainScheduler.instance)
.subscribeNext { next in
if self.oldNumberOfRows == 0 {
self.tableView?.reloadData()
} else {
if let t = weakTableView {
let c = self.viewModel.model.posts.count - 1
let f = { NSIndexPath(forRow: c - $0, inSection: 0) }
let i = next.insertedIndices.map(f)
let d = next.deletedIndices.map(f)
let u = next.updatedIndices.map(f)
t.beginUpdates()
t.insertRowsAtIndexPaths(i, withRowAnimation: .None)
t.deleteRowsAtIndexPaths(d, withRowAnimation: .Automatic)
t.reloadRowsAtIndexPaths(u, withRowAnimation: .Automatic)
t.endUpdates()
}
}
self.oldNumberOfRows = self.viewModel.model.posts.count
}
.addDisposableTo(disposeBag)
tableView?.dataSource = viewModel
//viewModel.fetch()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Text Editing
/*override func didPressReturnKey(sender: AnyObject!) {
post(textView.text)
super.didPressReturnKey(sender)
}*/
override func didPressRightButton(sender: AnyObject!) {
viewModel.post(textView.text)
super.didPressRightButton(sender)
}
override func didCommitTextEditing(sender: AnyObject) {
super.didCommitTextEditing(sender)
}
// MARK: - completion
override func didChangeAutoCompletionPrefix(prefix: String, andWord word: String) {
completionList = viewModel.autoCompletionElements(foundPrefix!, foundWord: foundWord!)
showAutoCompletionView(!completionList.isEmpty)
}
override func heightForAutoCompletionView() -> CGFloat {
let len = completionList.count
return CGFloat(len * 36)
}
// MARK: UITableViewDataSource Methods (for Completion)
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return completionList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AutoCompletionCell", forIndexPath: indexPath) as! AutoCompletionCell
cell.setModel(completionList[indexPath.row])
return cell
}
// MARK: UITableViewDelegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == autoCompletionView {
let c = completionList[indexPath.row]
acceptAutoCompletionWithString("\(c.completionString) ")
}
}
// MARK: - load
func handleMore(sender: AnyObject!) {
self.viewModel.fetchMore(topic!.topic.id)
}
}
| df805397770478e76d6bbaf7bee4b90a | 31.969697 | 132 | 0.638419 | false | false | false | false |
cloudinary/cloudinary_ios | refs/heads/master | Example/Tests/BaseNetwork/Extensions/FileManager+CloudinaryTests.swift | mit | 1 | //
// FileManager+CloudinaryTests.swift
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension FileManager {
// MARK: - Common Directories
static var temporaryDirectoryPath: String {
return NSTemporaryDirectory()
}
static var temporaryDirectoryURL: URL {
return URL(fileURLWithPath: FileManager.temporaryDirectoryPath, isDirectory: true)
}
// MARK: - File System Modification
@discardableResult
static func createDirectory(atPath path: String) -> Bool {
do {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
return true
} catch {
return false
}
}
@discardableResult
static func createDirectory(at url: URL) -> Bool {
return createDirectory(atPath: url.path)
}
@discardableResult
static func removeItem(atPath path: String) -> Bool {
do {
try FileManager.default.removeItem(atPath: path)
return true
} catch {
return false
}
}
@discardableResult
static func removeItem(at url: URL) -> Bool {
return removeItem(atPath: url.path)
}
@discardableResult
static func removeAllItemsInsideDirectory(atPath path: String) -> Bool {
let enumerator = FileManager.default.enumerator(atPath: path)
var result = true
while let fileName = enumerator?.nextObject() as? String {
let success = removeItem(atPath: path + "/\(fileName)")
if !success { result = false }
}
return result
}
@discardableResult
static func removeAllItemsInsideDirectory(at url: URL) -> Bool {
return removeAllItemsInsideDirectory(atPath: url.path)
}
}
| b529fa27ea42aca31724746f8b3496e3 | 31.977011 | 117 | 0.679679 | false | false | false | false |
d-date/SwiftBarcodeReader | refs/heads/master | SwiftBarcodeReader/Sources/UIViewController+BarcodeReader.swift | mit | 1 | import UIKit
import AVFoundation
private var AssociationKey: UInt8 = 0
public extension UIViewController {
var layer: AVCaptureVideoPreviewLayer! {
get {
return objc_getAssociatedObject(self, &AssociationKey) as? AVCaptureVideoPreviewLayer
}
set(newValue) {
objc_setAssociatedObject(self, &AssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
//MARK: - Private
private func addDeviceOrientationChangeNotification() {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(UIViewController.onChangedOrientation), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
private func removeDeviceOrientationChangeNotification() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
@objc private func onChangedOrientation() {
setDeviceOrientation(orientation: UIDevice.current.orientation)
}
private func setDeviceOrientation(orientation: UIDeviceOrientation) {
if (orientation == .landscapeLeft) || (orientation == .landscapeRight) {
layer.connection.videoOrientation = captureVideoOrientation(deviceOrientation: orientation)
} else {
layer.connection.videoOrientation = captureVideoOrientation(deviceOrientation: orientation)
}
}
private func captureVideoOrientation(deviceOrientation: UIDeviceOrientation) -> AVCaptureVideoOrientation {
var orientation: AVCaptureVideoOrientation
switch deviceOrientation {
case .portraitUpsideDown: orientation = .portraitUpsideDown
case .landscapeLeft: orientation = .landscapeRight
case .landscapeRight: orientation = .landscapeLeft
default: orientation = .portrait
}
return orientation
}
//MARK: - Public
func presentBarcodeReader(scanTypes: [AVMetadataObjectType],
needChangePositionButton: Bool,
success: ((_ type:AVMetadataObjectType, _ value: String) -> ())?,
failure: @escaping ((_ cancel: Bool, _ error: Error?) -> ())) {
let bundle = Bundle(identifier: "SBRResource")
let storyboard = UIStoryboard(name: "BarcodeReader", bundle: bundle)
let vc: BarcodeReaderViewController = storyboard.instantiateInitialViewController() as! BarcodeReaderViewController
vc.successClosure = success
vc.failureClosure = failure
vc.scanType = scanTypes
vc.needChangePositionButton = needChangePositionButton
present(vc, animated: true, completion: nil)
}
func startCodeCapture(position: AVCaptureDevicePosition, captureType: [AVMetadataObjectType]) {
addDeviceOrientationChangeNotification()
if DMCodeCaptureHandler.shared.session.outputs.count == 0 {
DMCodeCaptureHandler.shared.prepareCaptureSession(position: position)
}
layer = AVCaptureVideoPreviewLayer(session: DMCodeCaptureHandler.shared.session)
layer.frame = view.bounds
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
setDeviceOrientation(orientation: UIDevice.current.orientation)
view.layer.addSublayer(layer)
DMCodeCaptureHandler.shared.session.startRunning()
}
func switchCamera(to position: AVCaptureDevicePosition) {
DMCodeCaptureHandler.shared.switchInputDevice(for: position)
}
func endCodeCapture() {
DMCodeCaptureHandler.shared.session.stopRunning()
removeDeviceOrientationChangeNotification()
}
}
| f470c2a0e73b7057fd005622b0ed9ce1 | 44.139535 | 181 | 0.69526 | false | false | false | false |
BronxDupaix/WaffleLuv | refs/heads/master | WaffleLuv/MyColors.swift | apache-2.0 | 1 | //
// UIColor extension.swift
// WaffleLuv
//
// Created by Bronson Dupaix on 4/7/16.
// Copyright © 2016 Bronson Dupaix. All rights reserved.
//
import Foundation
struct MyColors{
static var getCustomPurpleColor = {
return UIColor(red:0.55, green:0.5 , blue:1.00, alpha:1.0)
}
static var getCustomCyanColor = {
return UIColor(red:1.00, green:0.93, blue:0.88, alpha:1.00)
}
static var getCustomPinkColor = {
return UIColor(red:1.0, green:0.4 ,blue:0.78 , alpha:1.00) }
static var getCustomRedColor = {
return UIColor(red:1.0, green:0.00, blue:0.00, alpha:1.00)
}
static var getCustomCreamColor = {
return UIColor(red:0.9, green:0.9, blue:1.00, alpha:1.00)
}
static var getCustomBananaColor = {
return UIColor(red:1.00, green:0.93, blue:0.50, alpha:1.00 )
}
static var getCustomBlueGreenColor = {
return UIColor(red:0.00, green:1 , blue:1 , alpha:0.75)
}
static var getCustomYellowColor = {
return UIColor(red:1.00, green:0.93, blue:0.00, alpha:1.00)
}
static var getCustomlightPurpleColor = {
return UIColor(red:0.8, green:0.18 , blue:1.00, alpha:0.6)
}
static var getCustomOrangeColor = {
return UIColor(red:1.00, green:0.66 , blue:0.00, alpha:1.00)
}
}
| 7998cca4a6fcf6a11279d81f2e84d257 | 21.661538 | 68 | 0.562118 | false | false | false | false |
deege/deegeu-swift-eventkit | refs/heads/master | CalendarTest/ViewController.swift | mit | 1 | //
// ViewController.swift
// CalendarTest
//
// Created by Daniel Spiess on 9/2/15.
// Copyright © 2015 Daniel Spiess. All rights reserved.
//
import UIKit
import EventKit
class ViewController: UIViewController {
var savedEventId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Creates an event in the EKEventStore. The method assumes the eventStore is created and
// accessible
func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.saveEvent(event, span: .ThisEvent)
savedEventId = event.eventIdentifier
} catch {
print("Bad things happened")
}
}
// Removes an event from the EKEventStore. The method assumes the eventStore is created and
// accessible
func deleteEvent(eventStore: EKEventStore, eventIdentifier: String) {
let eventToRemove = eventStore.eventWithIdentifier(eventIdentifier)
if (eventToRemove != nil) {
do {
try eventStore.removeEvent(eventToRemove!, span: .ThisEvent)
} catch {
print("Bad things happened")
}
}
}
// Responds to button to add event. This checks that we have permission first, before adding the
// event
@IBAction func addEvent(sender: UIButton) {
let eventStore = EKEventStore()
let startDate = NSDate()
let endDate = startDate.dateByAddingTimeInterval(60 * 60) // One hour
if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
eventStore.requestAccessToEntityType(.Event, completion: {
granted, error in
self.createEvent(eventStore, title: "DJ's Test Event", startDate: startDate, endDate: endDate)
})
} else {
createEvent(eventStore, title: "DJ's Test Event", startDate: startDate, endDate: endDate)
}
}
// Responds to button to remove event. This checks that we have permission first, before removing the
// event
@IBAction func removeEvent(sender: UIButton) {
let eventStore = EKEventStore()
if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
eventStore.requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in
self.deleteEvent(eventStore, eventIdentifier: self.savedEventId)
})
} else {
deleteEvent(eventStore, eventIdentifier: savedEventId)
}
}
}
| b060ca6adccd9aded981d9dcfbad0d82 | 33.395604 | 110 | 0.635783 | false | false | false | false |
zonble/MRTSwift | refs/heads/master | MRTTransitSwift/MRTRouteTableViewController.swift | mit | 1 | import UIKit
import MRTLib
class MRTRouteTableViewController: UITableViewController {
var route: MRTRoute? {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "台北捷運轉乘"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.route?.transitions.count ?? 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.route?.transitions[section].count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "Cell")
}
if let cell = cell {
cell.textLabel?.textColor = UIColor.label
cell.textLabel?.textAlignment = .left
cell.selectionStyle = .none
if let route = self.route {
let routeSection = route.transitions[indexPath.section]
let (lineID, from, to) = routeSection[indexPath.row]
cell.textLabel?.text = indexPath.row == 0 ? "\(from.name) - \(to.name)" : to.name
cell.detailTextLabel?.text = MRTLineName(lineID: lineID)
cell.detailTextLabel?.textColor = MRTLineColor(lineID: lineID)
}
}
return cell!
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
if let route = self.route {
return "共 \(route.links.count) 站,轉乘 \(route.transitions.count - 1) 次"
}
}
return nil
}
}
| 79e2bb58516750d8816cc345e8d39fc4 | 28.277778 | 106 | 0.704617 | false | false | false | false |
creatubbles/ctb-api-swift | refs/heads/develop | CreatubblesAPIClient/Sources/Requests/Hashtag/SearchForHashtagResponseHandler.swift | mit | 1 | //
// SearchForHashtagResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import ObjectMapper
class SearchForHashtagResponseHandler: ResponseHandler
{
fileprivate let completion: HashtagsClosure?
init(completion: HashtagsClosure?)
{
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?)
{
if let response = response,
let mappers = Mapper<HashtagMapper>().mapArray(JSONObject: response["data"])
{
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let hashtags = mappers.map({ Hashtag(mapper: $0, dataMapper: dataMapper, metadata: metadata) })
executeOnMainQueue { self.completion?(hashtags, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| a8f332a8bb62422df0efa3c8c709e19f | 42.62963 | 131 | 0.71944 | false | false | false | false |
warren-gavin/OBehave | refs/heads/master | OBehave/Classes/Tools/ChangeLocalization/OBChangeLocalizationBehavior.swift | mit | 1 | //
// OBChangeLocalizationBehavior.swift
// OBehave
//
// Created by Warren Gavin on 26/11/15.
// Copyright © 2015 Apokrupto. All rights reserved.
//
import UIKit
/**
* Perform a runtime switch of an app's language.
*
* Normally when an app has its language changed the user won't see the
* change until the next time the app is run. For apps that provide the
* user with the abiltity to change language in-app there are a number
* of solutions, all of which involve having to create custom code that
* overrides, mimics or wraps NSLocalizedString() in some way.
*
* While this is a reasonable solution it does not handle localization
* of visual elements very well. Localized storyboards cannot delegate
* to the custom solution and any properly localized storyboard will
* result in a call to NSLocalizedString().
*
* Some solutions I've seen included using a localize method that had
* to be called on each load, which meant absolutely every text element
* was forced to be an outlet of the view controller. This is not an
* elegant solution.
*
* This behavior swizzles localizedStringForKey:value:table: so that
* NSLocalizedString calls a new implementation using the bundle that
* corresponds to the localization specified in the data source.
*
* This behavior will post a notification to view controllers that are
* already loaded so they can reset any labels. You must make sure that
* your view controllers listen for this notification for best results.
*
* @param localization ISO country code for the localization to switch
* to.
*/
public final class OBChangeLocalizationBehavior: OBBehavior {
private var localizationObserver: NSKeyValueObservation?
override public func setup() {
super.setup()
localizationObserver = owner?.observe(\.view, options: .new) { [unowned self] (owner, _) in
owner.observeLocalizationChanges()
self.localizationObserver?.invalidate()
}
}
deinit {
if let owner = owner {
NotificationCenter.default.removeObserver(owner)
}
}
@IBAction func switchLocalization(_ sender: AnyObject?) {
// If we have switched to a different bundle we reset the runtime bundle and
// post a notification to all listeners (any loaded view controllers)
if let path = pathForLocalizationBundle(), let bundle = Bundle(path: path) {
NotificationCenter.default.post(name: .appLanguageWillChange, object: nil)
Bundle.switchToLocalizationInBundle(bundle)
NotificationCenter.default.post(name: .appLanguageDidChange, object: nil)
}
}
}
private extension OBChangeLocalizationBehavior {
func pathForLocalizationBundle() -> String? {
guard let dataSource: OBChangeLocalizationBehaviorDataSource = getDataSource() else {
return nil
}
let localization = dataSource.localizationToChangeTo(self)
if localization == Bundle.Localization.currentLocalization {
return nil
}
return Bundle.main.path(forResource: localization, ofType: .projectFileExt)
}
}
extension Notification.Name {
static let appLanguageWillChange = Notification.Name(rawValue: "com.apokrupto.OBChangeLocalizationBehavior.languageWillChange")
static let appLanguageDidChange = Notification.Name(rawValue: "com.apokrupto.OBChangeLocalizationBehavior.languageDidChange")
}
/**
* The behavior's data source must supply the localization to switch to. If there is
* no data source this behavior will do nothing.
*/
@objc protocol OBChangeLocalizationBehaviorDataSource: OBBehaviorDataSource {
func localizationToChangeTo(_ behavior: OBChangeLocalizationBehavior) -> String
}
private let swizzleLocalizationMethods: () = {
guard
let originalMethod = class_getInstanceMethod(Bundle.self, .originalSelector),
let swizzledMethod = class_getInstanceMethod(Bundle.self, .swizzledSelector)
else {
return
}
method_exchangeImplementations(originalMethod, swizzledMethod)
}()
/**
* Extension for NSBundle to swizzle localization
*/
extension Bundle {
struct Localization {
static var currentBundle = Bundle.main
static var currentLocalization: String {
return currentBundle.preferredLocalizations[0]
}
}
// Swizzled implementation of the localization functionality
@objc func swizzledLocalizedString(forKey key: String, value: String?, table tableName: String?) -> String {
return Localization.currentBundle.swizzledLocalizedString(forKey: key, value: value, table: tableName)
}
// Perform the swizzling of the localization functionality & set the active bundle
public class func switchToLocalizationInBundle(_ bundle: Bundle) {
_ = swizzleLocalizationMethods
Localization.currentBundle = bundle
}
}
extension UIViewController {
func observeLocalizationChanges() {
NotificationCenter.default.addObserver(self,
selector: .reloadViewController,
name: .appLanguageDidChange,
object: nil)
}
}
private extension String {
static let projectFileExt = "lproj"
}
private extension Selector {
static let originalSelector = #selector(Bundle.localizedString(forKey:value:table:))
static let swizzledSelector = #selector(Bundle.swizzledLocalizedString(forKey:value:table:))
static let reloadViewController = #selector(UIViewController.loadView)
}
| edfe0d2a313daea7696f941b9975cbf9 | 37.311258 | 131 | 0.690752 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | stdlib/public/core/Repeat.swift | apache-2.0 | 3 | //===--- Repeat.swift - A Collection that repeats a value N times ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection whose elements are all identical.
///
/// You create an instance of the `Repeated` collection by calling the
/// `repeatElement(_:count:)` function. The following example creates a
/// collection containing the name "Humperdinck" repeated five times:
///
/// let repeatedName = repeatElement("Humperdinck", count: 5)
/// for name in repeatedName {
/// print(name)
/// }
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
@_fixed_layout
public struct Repeated<Element> : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a "past the
/// end" position that's not valid for use as a subscript.
public typealias Index = Int
/// Creates an instance that contains `count` elements having the
/// value `repeatedValue`.
@_versioned
@_inlineable
internal init(_repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Repetition count should be non-negative")
self.count = count
self.repeatedValue = repeatedValue
}
/// The position of the first element in a nonempty collection.
///
/// In a `Repeated` collection, `startIndex` is always equal to zero. If the
/// collection is empty, `startIndex` is equal to `endIndex`.
@_inlineable
public var startIndex: Index {
return 0
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In a `Repeated` collection, `endIndex` is always equal to `count`. If the
/// collection is empty, `endIndex` is equal to `startIndex`.
@_inlineable
public var endIndex: Index {
return count
}
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@_inlineable
public subscript(position: Int) -> Element {
_precondition(position >= 0 && position < count, "Index out of range")
return repeatedValue
}
/// The number of elements in this collection.
public let count: Int
/// The value of every element in this collection.
public let repeatedValue: Element
}
/// Creates a collection containing the specified number of the given element.
///
/// The following example creates a `Repeated<Int>` collection containing five
/// zeroes:
///
/// let zeroes = repeatElement(0, count: 5)
/// for x in zeroes {
/// print(x)
/// }
/// // 0
/// // 0
/// // 0
/// // 0
/// // 0
///
/// - Parameters:
/// - element: The element to repeat.
/// - count: The number of times to repeat `element`.
/// - Returns: A collection that contains `count` elements that are all
/// `element`.
@_inlineable
public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {
return Repeated(_repeating: element, count: n)
}
| 5dedad336177fe7662207e7b87e07fab | 32.440367 | 80 | 0.649931 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/Snowball/Snowball_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Snowball
public struct SnowballErrorType: AWSErrorType {
enum Code: String {
case clusterLimitExceededException = "ClusterLimitExceededException"
case conflictException = "ConflictException"
case ec2RequestFailedException = "Ec2RequestFailedException"
case invalidAddressException = "InvalidAddressException"
case invalidInputCombinationException = "InvalidInputCombinationException"
case invalidJobStateException = "InvalidJobStateException"
case invalidNextTokenException = "InvalidNextTokenException"
case invalidResourceException = "InvalidResourceException"
case kMSRequestFailedException = "KMSRequestFailedException"
case returnShippingLabelAlreadyExistsException = "ReturnShippingLabelAlreadyExistsException"
case unsupportedAddressException = "UnsupportedAddressException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Snowball
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Job creation failed. Currently, clusters support five nodes. If you have less than five nodes for your cluster and you have more nodes to create for this cluster, try again and create jobs until your cluster has exactly five notes.
public static var clusterLimitExceededException: Self { .init(.clusterLimitExceededException) }
/// You get this exception when you call CreateReturnShippingLabel more than once when other requests are not completed.
public static var conflictException: Self { .init(.conflictException) }
/// Your IAM user lacks the necessary Amazon EC2 permissions to perform the attempted action.
public static var ec2RequestFailedException: Self { .init(.ec2RequestFailedException) }
/// The address provided was invalid. Check the address with your region's carrier, and try again.
public static var invalidAddressException: Self { .init(.invalidAddressException) }
/// Job or cluster creation failed. One or more inputs were invalid. Confirm that the CreateClusterRequest$SnowballType value supports your CreateJobRequest$JobType, and try again.
public static var invalidInputCombinationException: Self { .init(.invalidInputCombinationException) }
/// The action can't be performed because the job's current state doesn't allow that action to be performed.
public static var invalidJobStateException: Self { .init(.invalidJobStateException) }
/// The NextToken string was altered unexpectedly, and the operation has stopped. Run the operation without changing the NextToken string, and try again.
public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) }
/// The specified resource can't be found. Check the information you provided in your last request, and try again.
public static var invalidResourceException: Self { .init(.invalidResourceException) }
/// The provided AWS Key Management Service key lacks the permissions to perform the specified CreateJob or UpdateJob action.
public static var kMSRequestFailedException: Self { .init(.kMSRequestFailedException) }
/// You get this exception if you call CreateReturnShippingLabel and a valid return shipping label already exists. In this case, use DescribeReturnShippingLabel to get the url.
public static var returnShippingLabelAlreadyExistsException: Self { .init(.returnShippingLabelAlreadyExistsException) }
/// The address is either outside the serviceable area for your region, or an error occurred. Check the address with your region's carrier and try again. If the issue persists, contact AWS Support.
public static var unsupportedAddressException: Self { .init(.unsupportedAddressException) }
}
extension SnowballErrorType: Equatable {
public static func == (lhs: SnowballErrorType, rhs: SnowballErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension SnowballErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 62f76f8e2fd046c34c1e71e5de1460ab | 56.850575 | 239 | 0.733161 | false | false | false | false |
larryhou/swift | refs/heads/master | VisualEffect/VisualEffect/ViewController.swift | mit | 1 | //
// ViewController.swift
// VisualEffect
//
// Created by larryhou on 28/08/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import UIKit
class BlurController: UIViewController {
@IBOutlet weak var blurView: UIVisualEffectView!
override func viewDidLoad() {
super.viewDidLoad()
let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:)))
view.addGestureRecognizer(pan)
blurView.clipsToBounds = true
}
var fractionComplete = CGFloat.nan
var dismissAnimator: UIViewPropertyAnimator!
@objc func panUpdate(sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in
self.view.frame.origin.y = self.view.frame.height
self.blurView.layer.cornerRadius = 40
}
dismissAnimator.addCompletion { [unowned self] position in
if position == .end {
self.dismiss(animated: false, completion: nil)
}
self.fractionComplete = CGFloat.nan
}
dismissAnimator.pauseAnimation()
case .changed:
if fractionComplete.isNaN {fractionComplete = 0}
let translation = sender.translation(in: view)
fractionComplete += translation.y / view.frame.height
fractionComplete = min(1, max(0, fractionComplete))
dismissAnimator.fractionComplete = fractionComplete
sender.setTranslation(CGPoint.zero, in: view)
default:
if dismissAnimator.fractionComplete <= 0.25 {
dismissAnimator.isReversed = true
}
dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0)
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| ef9e2a584bc2345a009597a634d1704e | 35.265625 | 107 | 0.607497 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Views/ClearAllHeaderCell.swift | mit | 1 | //
// SearchRecentHeaderCell.swift
// Freetime
//
// Created by Ryan Nystrom on 9/4/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
protocol ClearAllHeaderCellDelegate: class {
func didSelectClear(cell: ClearAllHeaderCell)
}
final class ClearAllHeaderCell: UICollectionViewCell {
weak var delegate: ClearAllHeaderCellDelegate?
private let label = UILabel()
private let button = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
label.font = Styles.Fonts.secondary
label.textColor = Styles.Colors.Gray.light.color
contentView.addSubview(label)
label.snp.makeConstraints { make in
make.left.equalTo(Styles.Sizes.gutter)
make.centerY.equalTo(contentView)
}
button.setTitle(Constants.Strings.clearAll, for: .normal)
button.setTitleColor(Styles.Colors.Blue.medium.color, for: .normal)
button.titleLabel?.font = Styles.Fonts.button
button.addTarget(self, action: #selector(ClearAllHeaderCell.onClear), for: .touchUpInside)
contentView.addSubview(button)
button.snp.makeConstraints { make in
make.right.equalTo(-Styles.Sizes.gutter)
make.centerY.equalTo(label)
}
addBorder(.bottom, useSafeMargins: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentViewForSafeAreaInsets()
}
func configure(title text: String) {
label.text = text
}
// MARK: Private API
@objc func onClear() {
delegate?.didSelectClear(cell: self)
}
}
| 9d73bcb7d9a2d0f505adc9030ed0f182 | 25.833333 | 98 | 0.665161 | false | false | false | false |
wayfair/brickkit-ios | refs/heads/master | Example/Source/Navigation/NavigationViewController.swift | apache-2.0 | 1 | //
// NavigationViewController.swift
// BrickKit iOS Example
//
// Created by Ruben Cagnie on 10/17/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
/// Main navigation controller that holds the dataSource and is responsible for animating from Master > Detail and back
class NavigationViewController: UINavigationController {
/// DataSource that holds the navigation items that need to be shown
lazy var dataSource = NavigationDataSource()
// Transition
lazy fileprivate var navigationTransition = NavigationTransition()
// Mark: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
}
// MARK: - UINavigationControllerDelegate
extension NavigationViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if fromVC is NavigationMasterViewController && toVC is NavigationDetailViewController {
navigationTransition.presenting = true
return navigationTransition
} else if fromVC is NavigationDetailViewController && toVC is NavigationMasterViewController {
navigationTransition.presenting = false
return navigationTransition
}
return nil
}
}
| 8c6a8afa64fd64bd2c2665f6dd42fc6e | 33.465116 | 247 | 0.738192 | false | false | false | false |
apple/swift-docc-symbolkit | refs/heads/main | Sources/SymbolKit/SymbolGraph/Symbol/KindIdentifier.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
extension SymbolGraph.Symbol {
/**
A unique identifier of a symbol's kind, such as a structure or protocol.
*/
public struct KindIdentifier: Equatable, Hashable, Codable, CaseIterable {
private var rawValue: String
/// Create a new ``SymbolGraph/Symbol/KindIdentifier``.
///
/// - Note: Only use this initilaizer for defining a new kind. For initializing instances manually,
/// copy the initial initializer. For extracting identifiers form raw strings, use ``init(identifier:)``.
public init(rawValue: String) {
self.rawValue = rawValue
}
public static let `associatedtype` = KindIdentifier(rawValue: "associatedtype")
public static let `class` = KindIdentifier(rawValue: "class")
public static let `deinit` = KindIdentifier(rawValue: "deinit")
public static let `enum` = KindIdentifier(rawValue: "enum")
public static let `case` = KindIdentifier(rawValue: "enum.case")
public static let `func` = KindIdentifier(rawValue: "func")
public static let `operator` = KindIdentifier(rawValue: "func.op")
public static let `init` = KindIdentifier(rawValue: "init")
public static let ivar = KindIdentifier(rawValue: "ivar")
public static let macro = KindIdentifier(rawValue: "macro")
public static let method = KindIdentifier(rawValue: "method")
public static let property = KindIdentifier(rawValue: "property")
public static let `protocol` = KindIdentifier(rawValue: "protocol")
public static let snippet = KindIdentifier(rawValue: "snippet")
public static let snippetGroup = KindIdentifier(rawValue: "snippetGroup")
public static let `struct` = KindIdentifier(rawValue: "struct")
public static let `subscript` = KindIdentifier(rawValue: "subscript")
public static let typeMethod = KindIdentifier(rawValue: "type.method")
public static let typeProperty = KindIdentifier(rawValue: "type.property")
public static let typeSubscript = KindIdentifier(rawValue: "type.subscript")
public static let `typealias` = KindIdentifier(rawValue: "typealias")
public static let `var` = KindIdentifier(rawValue: "var")
public static let module = KindIdentifier(rawValue: "module")
public static let `extension` = KindIdentifier(rawValue: "extension")
/// A string that uniquely identifies the symbol kind.
///
/// If the original kind string was not recognized, this will return `"unknown"`.
public var identifier: String {
rawValue
}
public static var allCases: Dictionary<String, Self>.Values {
_allCases.values
}
private static var _allCases: [String: Self] = [
Self.associatedtype.rawValue: .associatedtype,
Self.class.rawValue: .class,
Self.deinit.rawValue: .deinit,
Self.enum.rawValue: .enum,
Self.case.rawValue: .case,
Self.func.rawValue: .func,
Self.operator.rawValue: .operator,
Self.`init`.rawValue: .`init`,
Self.ivar.rawValue: .ivar,
Self.macro.rawValue: .macro,
Self.method.rawValue: .method,
Self.property.rawValue: .property,
Self.protocol.rawValue: .protocol,
Self.snippet.rawValue: .snippet,
Self.snippetGroup.rawValue: .snippetGroup,
Self.struct.rawValue: .struct,
Self.subscript.rawValue: .subscript,
Self.typeMethod.rawValue: .typeMethod,
Self.typeProperty.rawValue: .typeProperty,
Self.typeSubscript.rawValue: .typeSubscript,
Self.typealias.rawValue: .typealias,
Self.var.rawValue: .var,
Self.module.rawValue: .module,
Self.extension.rawValue: .extension,
]
/// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly and
/// appear in ``allCases``.
///
/// If a type is not registered, language prefixes cannot be removed correctly.
///
/// - Note: When working in an uncontrolled environment where other parts of your executable might be disturbed by your
/// modifications to the symbol graph structure or might be registering identifiers concurrently, register identifiers on your
/// coder instead using ``register(_:to:)`` and maintain your own list of ``allCases``.
public static func register(_ identifiers: Self...) {
for identifier in identifiers {
_allCases[identifier.rawValue] = identifier
}
}
/// Check the given identifier string against the list of known identifiers.
///
/// - Parameter identifier: The identifier string to check.
/// - Parameter extensionCases: A set of custom identifiers to be considered in this lookup.
/// - Returns: The matching `KindIdentifier` case, or `nil` if there was no match.
private static func lookupIdentifier(identifier: String, using extensionCases: [String: Self]? = nil) -> KindIdentifier? {
_allCases[identifier] ?? extensionCases?[identifier]
}
/// Compares the given identifier against the known default symbol kinds, and returns whether it matches one.
///
/// The identifier will also be checked without its first component, so that (for example) `"swift.func"`
/// will be treated the same as just `"func"`, and match `.func`.
///
/// - Parameter identifier: The identifier string to compare.
/// - Returns: `true` if the given identifier matches a known symbol kind; otherwise `false`.
///
/// - Note: This initializer does only recognize custom identifiers if they were registered previously using
/// ``register(_:)``.
public static func isKnownIdentifier(_ identifier: String) -> Bool {
var kind: KindIdentifier?
if let cachedDetail = Self.lookupIdentifier(identifier: identifier) {
kind = cachedDetail
} else {
let cleanIdentifier = KindIdentifier.cleanIdentifier(identifier)
kind = Self.lookupIdentifier(identifier: cleanIdentifier)
}
return kind != nil
}
/// Parses the given identifier to return a matching symbol kind.
///
/// The identifier will also be checked without its first component, so that (for example) `"swift.func"`
/// will be treated the same as just `"func"`, and match `.func`.
///
/// - Parameter identifier: The identifier string to parse.
///
/// - Note: This initializer does only recognize custom identifiers if they were registered previously using
/// ``register(_:)``.
public init(identifier: String) {
self.init(identifier: identifier, using: nil)
}
private init(identifier: String, using extensionCases: [String: Self]?) {
// Check if the identifier matches a symbol kind directly.
if let firstParse = Self.lookupIdentifier(identifier: identifier, using: extensionCases) {
self = firstParse
} else {
// For symbol graphs which include a language identifier with their symbol kinds
// (e.g. "swift.func" instead of just "func"), strip off the language prefix and
// try again.
let cleanIdentifier = KindIdentifier.cleanIdentifier(identifier)
if let secondParse = Self.lookupIdentifier(identifier: cleanIdentifier, using: extensionCases) {
self = secondParse
} else {
// If that doesn't help either, use the original identifier as a raw value.
self = Self.init(rawValue: identifier)
}
}
}
public init(from decoder: Decoder) throws {
let identifier = try decoder.singleValueContainer().decode(String.self)
self = KindIdentifier(identifier: identifier, using: decoder.registeredSymbolKindIdentifiers)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(identifier)
}
/// Strips the first component of the given identifier string, so that (for example) `"swift.func"` will return `"func"`.
///
/// Symbol graphs may store symbol kinds as either bare identifiers (e.g. `"class"`, `"enum"`, etc), or as identifiers
/// prefixed with the language identifier (e.g. `"swift.func"`, `"objc.method"`, etc). This method allows us to
/// treat the language-prefixed symbol kinds as equivalent to the "bare" symbol kinds.
///
/// - Parameter identifier: An identifier string to clean.
/// - Returns: A new identifier string without its first component, or the original identifier if there was only one component.
private static func cleanIdentifier(_ identifier: String) -> String {
// FIXME: Take an "expected" language identifier instead of universally dropping the first component? (rdar://84276085)
if let periodIndex = identifier.firstIndex(of: ".") {
return String(identifier[identifier.index(after: periodIndex)...])
}
return identifier
}
}
}
extension SymbolGraph.Symbol.KindIdentifier {
/// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly while
/// decoding symbols in an uncontrolled environment.
///
/// If a type is not registered, language prefixes cannot be removed correctly.
///
/// - Note: Registering custom identifiers on your decoder is only necessary when working in an uncontrolled environment where
/// other parts of your executable might be disturbed by your modifications to the symbol graph structure. If that is not the case, use
/// ``SymbolGraph/Symbol/KindIdentifier/register(_:)``.
///
/// - Parameter userInfo: A property which allows editing the `userInfo` member of the
/// `Decoder` protocol.
public static func register<I: Sequence>(_ identifiers: I,
to userInfo: inout [CodingUserInfoKey: Any]) where I.Element == Self {
var registeredIdentifiers = userInfo[.symbolKindIdentifierKey] as? [String: SymbolGraph.Symbol.KindIdentifier] ?? [:]
for identifier in identifiers {
registeredIdentifiers[identifier.identifier] = identifier
}
userInfo[.symbolKindIdentifierKey] = registeredIdentifiers
}
}
public extension JSONDecoder {
/// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly while
/// decoding symbols in an uncontrolled environment.
///
/// If a type is not registered, language prefixes cannot be removed correctly.
///
/// - Note: Registering custom identifiers on your decoder is only necessary when working in an uncontrolled environment where
/// other parts of your executable might be disturbed by your modifications to the symbol graph structure. If that is not the case, use
/// ``SymbolGraph/Symbol/KindIdentifier/register(_:)``.
func register(symbolKinds identifiers: SymbolGraph.Symbol.KindIdentifier...) {
SymbolGraph.Symbol.KindIdentifier.register(identifiers, to: &self.userInfo)
}
}
extension Decoder {
var registeredSymbolKindIdentifiers: [String: SymbolGraph.Symbol.KindIdentifier]? {
self.userInfo[.symbolKindIdentifierKey] as? [String: SymbolGraph.Symbol.KindIdentifier]
}
}
extension CodingUserInfoKey {
static let symbolKindIdentifierKey = CodingUserInfoKey(rawValue: "org.swift.symbolkit.symbolKindIdentifierKey")!
}
| ec03b1fea51f25e40abe781cc5746c87 | 46.630189 | 139 | 0.637775 | false | false | false | false |
hhsolar/MemoryMaster-iOS | refs/heads/master | MemoryMaster/View/TestCollectionViewCell.swift | mit | 1 | //
// TestCollectionViewCell.swift
// MemoryMaster
//
// Created by apple on 4/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
import QuartzCore
class TestCollectionViewCell: UICollectionViewCell, UITextViewDelegate {
// public api
var questionAtFront = true
@IBOutlet weak var containerView: UIView!
let questionView = UIView()
let answerView = UIView()
let questionLabel = UILabel()
let answerLabel = UILabel()
let qTextView = UITextView()
let aTextView = UITextView()
let indexLabel = UILabel()
weak var delegate: EnlargeImageCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
func updateUI(question: NSAttributedString, answer: NSAttributedString, index: Int, total: Int) {
qTextView.attributedText = question.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange.init(location: 0, length: question.length))
aTextView.attributedText = answer.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange.init(location: 0, length: answer.length))
indexLabel.text = String(format: "%d / %d", index + 1, total)
}
private func setupUI() {
containerView.addSubview(answerView)
containerView.addSubview(questionView)
containerView.backgroundColor = UIColor.white
questionView.backgroundColor = CustomColor.lightBlue
questionView.addSubview(questionLabel)
questionView.addSubview(qTextView)
questionView.addSubview(indexLabel)
answerView.backgroundColor = CustomColor.lightGreen
answerView.addSubview(answerLabel)
answerView.addSubview(aTextView)
questionLabel.text = "QUESTION"
questionLabel.textAlignment = .center
questionLabel.textColor = CustomColor.deepBlue
questionLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid)
questionLabel.adjustsFontSizeToFitWidth = true
indexLabel.textAlignment = .center
indexLabel.textColor = CustomColor.deepBlue
indexLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid)
answerLabel.text = "ANSWER"
answerLabel.textAlignment = .center
answerLabel.textColor = CustomColor.deepBlue
answerLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid)
answerLabel.adjustsFontSizeToFitWidth = true
qTextView.isEditable = false
qTextView.font = UIFont(name: "Helvetica", size: 16)
qTextView.textColor = UIColor.darkGray
qTextView.backgroundColor = CustomColor.lightBlue
qTextView.showsVerticalScrollIndicator = false
qTextView.delegate = self
aTextView.isEditable = false
aTextView.font = UIFont(name: "Helvetica", size: 16)
aTextView.textColor = UIColor.darkGray
aTextView.backgroundColor = CustomColor.lightGreen
aTextView.showsVerticalScrollIndicator = false
aTextView.delegate = self
}
override func layoutSubviews() {
super .layoutSubviews()
containerView.layer.cornerRadius = 15
containerView.layer.masksToBounds = true
questionView.frame = CGRect(x: 0, y: 0, width: contentView.bounds.width - CustomDistance.midEdge * 2, height: contentView.bounds.height - CustomDistance.midEdge * 2)
questionView.layer.cornerRadius = 15
questionView.layer.masksToBounds = true
questionView.layer.borderWidth = 3
questionView.layer.borderColor = CustomColor.deepBlue.cgColor
questionView.layer.shadowOpacity = 0.8
questionView.layer.shadowColor = UIColor.gray.cgColor
questionView.layer.shadowRadius = 10
questionView.layer.shadowOffset = CGSize(width: 1, height: 1)
answerView.frame = questionView.frame
answerView.layer.cornerRadius = 15
answerView.layer.masksToBounds = true
answerView.layer.borderWidth = 3
answerView.layer.borderColor = CustomColor.deepBlue.cgColor
answerView.layer.shadowOpacity = 0.8
answerView.layer.shadowColor = UIColor.gray.cgColor
answerView.layer.shadowRadius = 10
answerView.layer.shadowOffset = CGSize(width: 1, height: 1)
questionLabel.frame = CGRect(x: questionView.bounds.midX - questionView.bounds.width / 6, y: CustomDistance.midEdge, width: questionView.bounds.width / 3, height: CustomSize.titleLabelHeight)
qTextView.frame = CGRect(x: 0, y: CustomDistance.midEdge * 2 + CustomSize.titleLabelHeight, width: questionView.bounds.width, height: questionView.bounds.height - CustomDistance.midEdge * 4 - CustomSize.titleLabelHeight * 2)
qTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.narrowEdge, bottom: 0, right: CustomDistance.narrowEdge)
indexLabel.frame = CGRect(x: questionView.bounds.midX - questionView.bounds.width / 6, y: questionView.bounds.height - CustomSize.titleLabelHeight - CustomDistance.midEdge, width: questionView.bounds.width / 3, height: CustomSize.titleLabelHeight)
answerLabel.frame = questionLabel.frame
aTextView.frame = qTextView.frame
aTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.narrowEdge, bottom: 0, right: CustomDistance.narrowEdge)
aTextView.frame.size.height += (CustomDistance.midEdge + CustomSize.titleLabelHeight)
}
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
var image: UIImage? = nil
if textAttachment.image != nil {
image = textAttachment.image
} else {
image = textAttachment.image(forBounds: textAttachment.bounds, textContainer: nil, characterIndex: characterRange.location)
}
if let image = image {
delegate?.enlargeTapedImage(image: image)
}
return true
}
}
| 6017b081720d418f38e8a0b843afec26 | 44.294118 | 255 | 0.69513 | false | false | false | false |
gerardogrisolini/Webretail | refs/heads/master | Sources/Webretail/Models/AttributeValue.swift | apache-2.0 | 1 | //
// AttributeValue.swift
// Webretail
//
// Created by Gerardo Grisolini on 17/02/17.
//
//
import Foundation
import StORM
class AttributeValue: PostgresSqlORM, Codable {
public var attributeValueId : Int = 0
public var attributeId : Int = 0
public var attributeValueCode : String = ""
public var attributeValueName : String = ""
public var attributeValueTranslates: [Translation] = [Translation]()
public var attributeValueCreated : Int = Int.now()
public var attributeValueUpdated : Int = Int.now()
private enum CodingKeys: String, CodingKey {
case attributeValueId
case attributeId
case attributeValueCode
case attributeValueName
case attributeValueTranslates = "translations"
}
open override func table() -> String { return "attributevalues" }
open override func tableIndexes() -> [String] { return ["attributeValueCode", "attributeValueName"] }
open override func to(_ this: StORMRow) {
attributeValueId = this.data["attributevalueid"] as? Int ?? 0
attributeId = this.data["attributeid"] as? Int ?? 0
attributeValueCode = this.data["attributevaluecode"] as? String ?? ""
attributeValueName = this.data["attributevaluename"] as? String ?? ""
if let translates = this.data["attributevaluetranslates"] {
let jsonData = try! JSONSerialization.data(withJSONObject: translates, options: [])
attributeValueTranslates = try! JSONDecoder().decode([Translation].self, from: jsonData)
}
attributeValueCreated = this.data["attributevaluecreated"] as? Int ?? 0
attributeValueUpdated = this.data["attributevalueupdated"] as? Int ?? 0
}
func rows() -> [AttributeValue] {
var rows = [AttributeValue]()
for i in 0..<self.results.rows.count {
let row = AttributeValue()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
attributeValueId = try container.decode(Int.self, forKey: .attributeValueId)
attributeId = try container.decode(Int.self, forKey: .attributeId)
attributeValueCode = try container.decode(String.self, forKey: .attributeValueCode)
attributeValueName = try container.decode(String.self, forKey: .attributeValueName)
attributeValueTranslates = try container.decodeIfPresent([Translation].self, forKey: .attributeValueTranslates) ?? [Translation]()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(attributeValueId, forKey: .attributeValueId)
try container.encode(attributeId, forKey: .attributeId)
try container.encode(attributeValueCode, forKey: .attributeValueCode)
try container.encode(attributeValueName, forKey: .attributeValueName)
try container.encode(attributeValueTranslates, forKey: .attributeValueTranslates)
}
}
| 4bc5cc8183841ef82abe89698ad2c337 | 39.417722 | 138 | 0.676793 | false | false | false | false |
wwu-pi/md2-framework | refs/heads/master | de.wwu.md2.framework/res/resources/ios/lib/controller/eventhandler/MD2OnClickHandler.swift | apache-2.0 | 1 | //
// MD2OnClickHandler.swift
// md2-ios-library
//
// Created by Christoph Rieger on 30.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
import UIKit
/// Event handler for click events.
class MD2OnClickHandler: MD2WidgetEventHandler {
/// Convenience typealias for the tuple of action and widget
typealias actionWidgetTuple = (MD2Action, MD2WidgetWrapper)
/// The singleton instance.
static let instance: MD2OnClickHandler = MD2OnClickHandler()
/// The list of registered action-widget tuples.
var actions: Dictionary<String, actionWidgetTuple> = [:]
/// Singleton initializer.
private init() {
// Nothing to initialize
}
/**
Register an action.
:param: action The action to execute in case of an event.
:param: widget The widget that the action should be bound to.
*/
func registerAction(action: MD2Action, widget: MD2WidgetWrapper) {
actions[action.actionSignature] = (action, widget)
}
/**
Unregister an action.
:param: action The action to remove.
:param: widget The widget the action was registered to.
*/
func unregisterAction(action: MD2Action, widget: MD2WidgetWrapper) {
for (key, value) in actions {
if key == action.actionSignature {
actions[key] = nil
break
}
}
}
/**
Method that is called to fire an event.
*Notice* Visible to Objective-C runtime to receive events from UI elements.
:param: sender The widget sending the event.
*/
@objc
func fire(sender: UIControl) {
//println("Event fired to OnClickHandler: " + String(sender.tag) + "=" + WidgetMapping.fromRawValue(sender.tag).description)
for (_, (action, widget)) in actions {
if widget.widgetId == MD2WidgetMapping.fromRawValue(sender.tag) {
action.execute()
}
}
}
} | 1152bb28d5f1a5a4506cc6765a71a13c | 27.760563 | 132 | 0.609505 | false | false | false | false |
NUKisZ/MyTools | refs/heads/master | BeeFun/Pods/GDPerformanceView-Swift/GDPerformanceView-Swift/GDPerformanceMonitoring/GDPerformanceMonitor.swift | mit | 2 | //
// Copyright © 2017 Gavrilov Daniil
//
// 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 GDPerformanceMonitor: NSObject {
// MARK: Public Properties
/**
GDPerformanceMonitorDelegate delegate.
*/
public weak var delegate: GDPerformanceMonitorDelegate? {
didSet {
self.performanceView?.performanceDelegate = self.delegate
}
}
/**
Change it to hide or show application version from monitoring view. Default is false.
*/
public var appVersionHidden: Bool = false {
didSet {
self.performanceView?.appVersionHidden = self.appVersionHidden
}
}
/**
Change it to hide or show device iOS version from monitoring view. Default is false.
*/
public var deviceVersionHidden: Bool = false {
didSet {
self.performanceView?.deviceVersionHidden = self.deviceVersionHidden
}
}
/**
Instance of GDPerformanceMonitor as singleton.
*/
public static let sharedInstance: GDPerformanceMonitor = GDPerformanceMonitor.init()
// MARK: Private Properties
private var performanceView: GDPerformanceView?
private var performanceViewPaused: Bool = false
private var performanceViewHidden: Bool = false
private var performanceViewStopped: Bool = false
private var prefersStatusBarHidden: Bool = false
private var preferredStatusBarStyle: UIStatusBarStyle = UIStatusBarStyle.default
// MARK: Init Methods & Superclass Overriders
/**
Creates and returns instance of GDPerformanceMonitor.
*/
public override init() {
super.init()
self.subscribeToNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Notifications & Observers
@objc private func applicationDidBecomeActive(notification: NSNotification) {
if self.performanceViewPaused {
return
}
self.startOrResumeMonitoring()
}
@objc private func applicationWillResignActive(notification: NSNotification) {
self.performanceView?.pauseMonitoring()
}
// MARK: Public Methods
/**
Overrides prefersStatusBarHidden and preferredStatusBarStyle properties to return the desired status bar attributes.
Default prefersStatusBarHidden is false, preferredStatusBarStyle is UIStatusBarStyle.default.
*/
public func configureStatusBarAppearance(prefersStatusBarHidden: Bool, preferredStatusBarStyle: UIStatusBarStyle) {
self.prefersStatusBarHidden = prefersStatusBarHidden
self.preferredStatusBarStyle = preferredStatusBarStyle
self.checkAndApplyStatusBarAppearance(prefersStatusBarHidden: prefersStatusBarHidden, preferredStatusBarStyle: preferredStatusBarStyle)
}
/**
Starts or resumes performance monitoring, initialize monitoring view if not initialized and shows monitoring view. Use configuration block to change appearance as you like.
*/
public func startMonitoring(configuration: (UILabel?) -> Void) {
self.performanceViewPaused = false
self.performanceViewHidden = false
self.performanceViewStopped = false
self.startOrResumeMonitoring()
let textLabel = self.performanceView?.textLabel()
configuration(textLabel)
}
/**
Starts or resumes performance monitoring, initialize monitoring view if not initialized and shows monitoring view.
*/
public func startMonitoring() {
self.performanceViewPaused = false
self.performanceViewHidden = false
self.performanceViewStopped = false
self.startOrResumeMonitoring()
}
/**
Pauses performance monitoring and hides monitoring view.
*/
public func pauseMonitoring() {
self.performanceViewPaused = true
self.performanceView?.pauseMonitoring()
}
/**
Hides monitoring view.
*/
public func hideMonitoring() {
self.performanceViewHidden = true
self.performanceView?.hideMonitoring()
}
/**
Stops and removes monitoring view. Call when you're done with performance monitoring.
*/
public func stopMonitoring() {
self.performanceViewStopped = true
self.performanceView?.stopMonitoring()
self.performanceView = nil
}
/**
Use configuration block to change appearance as you like.
*/
public func configure(configuration: (UILabel?) -> Void) {
let textLabel = self.performanceView?.textLabel()
configuration(textLabel)
}
// MARK: Private Methods
// MARK: Default Setups
private func subscribeToNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(GDPerformanceMonitor.applicationDidBecomeActive(notification:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(GDPerformanceMonitor.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
// MARK: Monitoring
private func startOrResumeMonitoring() {
if self.performanceView == nil {
self.setupPerformanceView()
} else {
self.performanceView?.resumeMonitoring(shouldShowMonitoringView: !self.performanceViewHidden)
}
if UIApplication.shared.applicationState == UIApplicationState.active {
self.performanceView?.addMonitoringViewAboveStatusBar()
}
}
private func setupPerformanceView() {
if self.performanceViewStopped {
return
}
self.performanceView = GDPerformanceView.init()
self.performanceView?.appVersionHidden = self.appVersionHidden
self.performanceView?.deviceVersionHidden = self.deviceVersionHidden
self.performanceView?.performanceDelegate = self.delegate
self.checkAndApplyStatusBarAppearance(prefersStatusBarHidden: self.prefersStatusBarHidden, preferredStatusBarStyle: self.preferredStatusBarStyle)
if self.performanceViewPaused {
self.performanceView?.pauseMonitoring()
}
if self.performanceViewHidden {
self.performanceView?.hideMonitoring()
}
}
// MARK: Other Methods
private func checkAndApplyStatusBarAppearance(prefersStatusBarHidden: Bool, preferredStatusBarStyle: UIStatusBarStyle) {
if self.performanceView?.prefersStatusBarHidden != prefersStatusBarHidden || self.performanceView?.preferredStatusBarStyle != preferredStatusBarStyle {
self.performanceView?.prefersStatusBarHidden = prefersStatusBarHidden
self.performanceView?.preferredStatusBarStyle = preferredStatusBarStyle
self.performanceView?.configureRootViewController()
}
}
}
| c7d292ccfad771f0f49edc0055e2fb67 | 34.398268 | 208 | 0.690106 | false | false | false | false |
ReticentJohn/Amaroq | refs/heads/master | Carthage/Checkouts/OAuth2/Sources/Flows/OAuth2DynReg.swift | apache-2.0 | 4 | //
// OAuth2DynReg.swift
// c3-pro
//
// Created by Pascal Pfiffner on 6/1/15.
// Copyright 2015 Pascal Pfiffner
//
// 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
#if !NO_MODULE_IMPORT
import Base
#endif
/**
Class to handle OAuth2 Dynamic Client Registration.
This is a lightweight class that uses a OAuth2 instance's settings when registering, only few settings are held by instances of this class.
Hence it's highly portable and can be instantiated when needed with ease.
For the full OAuth2 Dynamic Client Registration spec see https://tools.ietf.org/html/rfc7591
*/
open class OAuth2DynReg {
/// Additional HTTP headers to supply during registration.
open var extraHeaders: OAuth2StringDict?
/// Whether registration should also allow refresh tokens. Defaults to true, making sure "refresh_token" grant type is being registered.
open var allowRefreshTokens = true
/** Designated initializer. */
public init() { }
// MARK: - Registration
/**
Register the given client.
- parameter client: The client to register and update with client credentials, when successful
- parameter callback: The callback to call when done with the registration response (JSON) and/or an error
*/
open func register(client: OAuth2, callback: @escaping ((_ json: OAuth2JSON?, _ error: OAuth2Error?) -> Void)) {
do {
let req = try registrationRequest(for: client)
client.logger?.debug("OAuth2", msg: "Registering client at \(req.url!) with scopes “\(client.scope ?? "(none)")”")
client.perform(request: req) { response in
do {
let data = try response.responseData()
let dict = try self.parseRegistrationResponse(data: data, client: client)
try client.assureNoErrorInResponse(dict)
if response.response.statusCode >= 400 {
client.logger?.warn("OAuth2", msg: "Registration failed with \(response.response.statusCode)")
}
else {
self.didRegisterWith(json: dict, client: client)
}
callback(dict, nil)
}
catch let error {
callback(nil, error.asOAuth2Error)
}
}
}
catch let error {
callback(nil, error.asOAuth2Error)
}
}
// MARK: - Registration Request
/**
Returns a URL request, set up to be used for registration: POST method, JSON body data.
- parameter for: The OAuth2 client the request is built for
- returns: A URL request to be used for registration
*/
open func registrationRequest(for client: OAuth2) throws -> URLRequest {
guard let registrationURL = client.clientConfig.registrationURL else {
throw OAuth2Error.noRegistrationURL
}
var req = URLRequest(url: registrationURL)
req.httpMethod = "POST"
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
if let headers = extraHeaders {
for (key, val) in headers {
req.setValue(val, forHTTPHeaderField: key)
}
}
let body = registrationBody(for: client)
client.logger?.debug("OAuth2", msg: "Registration parameters: \(body)")
req.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
return req
}
/** The body data to use for registration. */
open func registrationBody(for client: OAuth2) -> OAuth2JSON {
var dict = OAuth2JSON()
if let client = client.clientConfig.clientName {
dict["client_name"] = client
}
if let redirect = client.clientConfig.redirectURLs {
dict["redirect_uris"] = redirect
}
if let logoURL = client.clientConfig.logoURL?.absoluteString {
dict["logo_uri"] = logoURL
}
if let scope = client.scope {
dict["scope"] = scope
}
// grant types, response types and auth method
var grant_types = [type(of: client).grantType]
if allowRefreshTokens {
grant_types.append("refresh_token")
}
dict["grant_types"] = grant_types
if let responseType = type(of: client).responseType {
dict["response_types"] = [responseType]
}
dict["token_endpoint_auth_method"] = client.clientConfig.endpointAuthMethod.rawValue
return dict
}
/**
Parse the registration data that's being returned.
This implementation uses `OAuth2.parseJSON()` to convert the data to `OAuth2JSON`.
- parameter data: The NSData instance returned by the server
- parameter client: The client for which we're doing registration
- returns: An OAuth2JSON representation of the registration data
*/
open func parseRegistrationResponse(data: Data, client: OAuth2) throws -> OAuth2JSON {
return try client.parseJSON(data)
}
/**
Called when registration has returned data and that data has been parsed.
This implementation extracts `client_id`, `client_secret` and `token_endpoint_auth_method` and invokes the client's
`storeClientToKeychain()` method.
- parameter json: The registration data in JSON format
- parameter client: The client for which we're doing registration
*/
open func didRegisterWith(json: OAuth2JSON, client: OAuth2) {
if let id = json["client_id"] as? String {
client.clientId = id
client.logger?.debug("OAuth2", msg: "Did register with client-id “\(id)”, params: \(json)")
}
else {
client.logger?.debug("OAuth2", msg: "Did register but did not get a client-id. Params: \(json)")
}
if let secret = json["client_secret"] as? String {
client.clientSecret = secret
if let expires = json["client_secret_expires_at"] as? Double, 0 != expires {
client.logger?.debug("OAuth2", msg: "Client secret will expire on \(Date(timeIntervalSince1970: expires))")
}
}
if let methodName = json["token_endpoint_auth_method"] as? String, let method = OAuth2EndpointAuthMethod(rawValue: methodName) {
client.clientConfig.endpointAuthMethod = method
}
if client.useKeychain {
client.storeClientToKeychain()
}
}
}
| 5a7149432f82792e8187f1850e711305 | 32.743316 | 139 | 0.712995 | false | false | false | false |
frootloops/swift | refs/heads/master | stdlib/public/core/StringUTF16.swift | apache-2.0 | 1 | //===--- StringUTF16.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-16 code units.
///
/// You can access a string's view of UTF-16 code units by using its `utf16`
/// property. A string's UTF-16 view encodes the string's Unicode scalar
/// values as 16-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf16 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 55357
/// // 56464
///
/// Unicode scalar values that make up a string's contents can be up to 21
/// bits long. The longer scalar values may need two `UInt16` values for
/// storage. Those "pairs" of code units are called *surrogate pairs*.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf16 {
/// print(v)
/// }
/// // 55357
/// // 56464
///
/// To convert a `String.UTF16View` instance back into a string, use the
/// `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.utf16.index(where: { $0 >= 128 }) {
/// let asciiPrefix = String(favemoji.utf16[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
///
/// UTF16View Elements Match NSString Characters
/// ============================================
///
/// The UTF-16 code units of a string's `utf16` view match the elements
/// accessed through indexed `NSString` APIs.
///
/// print(flowers.utf16.count)
/// // Prints "10"
///
/// let nsflowers = flowers as NSString
/// print(nsflowers.length)
/// // Prints "10"
///
/// Unlike `NSString`, however, `String.UTF16View` does not use integer
/// indices. If you need to access a specific position in a UTF-16 view, use
/// Swift's index manipulation methods. The following example accesses the
/// fourth code unit in both the `flowers` and `nsflowers` strings:
///
/// print(nsflowers.character(at: 3))
/// // Prints "119"
///
/// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3)
/// print(flowers.utf16[i])
/// // Prints "119"
///
/// Although the Swift overlay updates many Objective-C methods to return
/// native Swift indices and index ranges, some still return instances of
/// `NSRange`. To convert an `NSRange` instance to a range of
/// `String.Index`, use the `Range(_:in:)` initializer, which takes an
/// `NSRange` and a string as arguments.
///
/// let snowy = "❄️ Let it snow! ☃️"
/// let nsrange = NSRange(location: 3, length: 12)
/// if let range = Range(nsrange, in: snowy) {
/// print(snowy[range])
/// }
/// // Prints "Let it snow!"
@_fixed_layout // FIXME(sil-serialize-all)
public struct UTF16View
: BidirectionalCollection,
CustomStringConvertible,
CustomDebugStringConvertible {
public typealias Index = String.Index
/// The position of the first code unit if the `String` is
/// nonempty; identical to `endIndex` otherwise.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return Index(encodedOffset: _offset)
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty UTF-16 view, `endIndex` is equal to `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return Index(encodedOffset: _offset + _length)
}
@_fixed_layout // FIXME(sil-serialize-all)
public struct Indices {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(
_elements: String.UTF16View, _startIndex: Index, _endIndex: Index
) {
self._elements = _elements
self._startIndex = _startIndex
self._endIndex = _endIndex
}
@_versioned // FIXME(sil-serialize-all)
internal var _elements: String.UTF16View
@_versioned // FIXME(sil-serialize-all)
internal var _startIndex: Index
@_versioned // FIXME(sil-serialize-all)
internal var _endIndex: Index
}
@_inlineable // FIXME(sil-serialize-all)
public var indices: Indices {
return Indices(
_elements: self, startIndex: startIndex, endIndex: endIndex)
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(encodedOffset: _unsafePlus(i.encodedOffset, 1))
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(encodedOffset: _unsafeMinus(i.encodedOffset, 1))
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(encodedOffset: i.encodedOffset.advanced(by: n))
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: range check i?
let d = i.encodedOffset.distance(to: limit.encodedOffset)
if (d >= 0) ? (d < n) : (d > n) {
return nil
}
return Index(encodedOffset: i.encodedOffset.advanced(by: n))
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
// FIXME: swift-3-indexing-model: range check start and end?
return start.encodedOffset.distance(to: end.encodedOffset)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func _internalIndex(at i: Int) -> Int {
return _core.startIndex + i
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-16 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf16.startIndex
/// print("First character's UTF-16 code unit: \(greeting.utf16[i])")
/// // Prints "First character's UTF-16 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position` must be
/// less than the view's end index.
@_inlineable // FIXME(sil-serialize-all)
public subscript(i: Index) -> UTF16.CodeUnit {
_precondition(i >= startIndex && i < endIndex,
"out-of-range access on a UTF16View")
let index = _internalIndex(at: i.encodedOffset)
let u = _core[index]
if _fastPath((u &>> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit.
return u
}
if (u &>> 10) == 0b1101_10 {
// `u` is a high-surrogate. Sequence is well-formed if it
// is followed by a low-surrogate.
if _fastPath(
index + 1 < _core.count &&
(_core[index + 1] &>> 10) == 0b1101_11) {
return u
}
return 0xfffd
}
// `u` is a low-surrogate. Sequence is well-formed if
// previous code unit is a high-surrogate.
if _fastPath(index != 0 && (_core[index - 1] &>> 10) == 0b1101_10) {
return u
}
return 0xfffd
}
#if _runtime(_ObjC)
// These may become less important once <rdar://problem/19255291> is addressed.
@available(
*, unavailable,
message: "Indexing a String's UTF16View requires a String.UTF16View.Index, which can be constructed from Int when Foundation is imported")
public subscript(i: Int) -> UTF16.CodeUnit {
Builtin.unreachable()
}
@available(
*, unavailable,
message: "Slicing a String's UTF16View requires a Range<String.UTF16View.Index>, String.UTF16View.Index can be constructed from Int when Foundation is imported")
public subscript(bounds: Range<Int>) -> UTF16View {
Builtin.unreachable()
}
#endif
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ _core: _StringCore) {
self.init(_core, offset: 0, length: _core.count)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ _core: _StringCore, offset: Int, length: Int) {
self._offset = offset
self._length = length
self._core = _core
}
@_inlineable // FIXME(sil-serialize-all)
public var description: String {
let start = _internalIndex(at: _offset)
let end = _internalIndex(at: _offset + _length)
return String(_core[start..<end])
}
@_inlineable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "StringUTF16(\(self.description.debugDescription))"
}
@_versioned // FIXME(sil-serialize-all)
internal var _offset: Int
@_versioned // FIXME(sil-serialize-all)
internal var _length: Int
@_versioned // FIXME(sil-serialize-all)
internal let _core: _StringCore
}
/// A UTF-16 encoding of `self`.
@_inlineable // FIXME(sil-serialize-all)
public var utf16: UTF16View {
get {
return UTF16View(_core)
}
set {
self = String(describing: newValue)
}
}
/// Creates a string corresponding to the given sequence of UTF-16 code units.
///
/// If `utf16` contains unpaired UTF-16 surrogates, the result is `nil`.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `utf16` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.utf16.index(of: 32) {
/// let adjective = String(picnicGuest.utf16[..<i])
/// print(adjective)
/// }
/// // Prints "Optional(Deserving)"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.utf16` view.
///
/// - Parameter utf16: A UTF-16 code sequence.
@_inlineable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2, obsoleted: 4.0)
public init?(_ utf16: UTF16View) {
// Attempt to recover the whole string, the better to implement the actual
// Swift 3.1 semantics, which are not as documented above! Full Swift 3.1
// semantics may be impossible to preserve in the case of string literals,
// since we no longer have access to the length of the original string when
// there is no owner and elements are dropped from the end.
let wholeString = utf16._core.nativeBuffer.map { String(_StringCore($0)) }
?? String(utf16._core)
guard
let start = UTF16Index(_offset: utf16._offset)
.samePosition(in: wholeString),
let end = UTF16Index(_offset: utf16._offset + utf16._length)
.samePosition(in: wholeString)
else
{
return nil
}
self = wholeString[start..<end]
}
/// Creates a string corresponding to the given sequence of UTF-16 code units.
@_inlineable // FIXME(sil-serialize-all)
@available(swift, introduced: 4.0)
public init(_ utf16: UTF16View) {
self = String(utf16._core)
}
/// The index type for subscripting a string.
public typealias UTF16Index = UTF16View.Index
}
extension String.UTF16View : _SwiftStringView {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _ephemeralContent : String { return _persistentContent }
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _persistentContent : String { return String(self._core) }
}
// Index conversions
extension String.UTF16View.Index {
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified string position.
///
/// If the index passed as `sourcePosition` represents either the start of a
/// Unicode scalar value or the position of a UTF-16 trailing surrogate,
/// then the initializer succeeds. If `sourcePosition` does not have an
/// exact corresponding position in `target`, then the result is `nil`. For
/// example, an attempt to convert the position of a UTF-8 continuation byte
/// results in `nil`.
///
/// The following example finds the position of a space in a string and then
/// converts that position to an index in the string's `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let stringIndex = cafe.index(of: "é")!
/// let utf16Index = String.Index(stringIndex, within: cafe.utf16)!
///
/// print(cafe.utf16[...utf16Index])
/// // Prints "Café"
///
/// - Parameters:
/// - sourcePosition: A position in at least one of the views of the string
/// shared by `target`.
/// - target: The `UTF16View` in which to find the new position.
@_inlineable // FIXME(sil-serialize-all)
public init?(
_ sourcePosition: String.Index, within target: String.UTF16View
) {
guard sourcePosition._transcodedOffset == 0 else { return nil }
self.init(encodedOffset: sourcePosition.encodedOffset)
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// This index must be a valid index of `String(unicodeScalars).utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method to find the same
/// position in the string's `unicodeScalars` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.index(of: 32)!
/// let j = i.samePosition(in: cafe.unicodeScalars)!
/// print(cafe.unicodeScalars[..<j])
/// // Prints "Café"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// This index must be a valid index of at least one view of the string
/// shared by `unicodeScalars`.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `unicodeScalars`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-16 trailing surrogate
/// returns `nil`.
@_inlineable // FIXME(sil-serialize-all)
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
}
// Reflection
extension String.UTF16View : CustomReflectable {
/// Returns a mirror that reflects the UTF-16 view of a string.
@_inlineable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UTF16View : CustomPlaygroundQuickLookable {
@_inlineable // FIXME(sil-serialize-all)
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
extension String.UTF16View.Indices : BidirectionalCollection {
public typealias Index = String.UTF16View.Index
public typealias Indices = String.UTF16View.Indices
public typealias SubSequence = String.UTF16View.Indices
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(
_elements: String.UTF16View,
startIndex: Index,
endIndex: Index
) {
self._elements = _elements
self._startIndex = startIndex
self._endIndex = endIndex
}
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _startIndex
}
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _endIndex
}
@_inlineable // FIXME(sil-serialize-all)
public var indices: Indices {
return self
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return i
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> String.UTF16View.Indices {
// FIXME: swift-3-indexing-model: range check.
return String.UTF16View.Indices(
_elements: _elements,
startIndex: bounds.lowerBound,
endIndex: bounds.upperBound)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(after: i)
}
@_inlineable // FIXME(sil-serialize-all)
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(after: &i)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(before: i)
}
@_inlineable // FIXME(sil-serialize-all)
public func formIndex(before i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(before: &i)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return _elements.index(i, offsetBy: n)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: range check i?
return _elements.index(i, offsetBy: n, limitedBy: limit)
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
// FIXME: swift-3-indexing-model: range check start and end?
return _elements.distance(from: start, to: end)
}
}
// backward compatibility for index interchange.
extension String.UTF16View {
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(after i: Index?) -> Index {
return index(after: i!)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public func index(
_ i: Index?, offsetBy n: Int) -> Index {
return index(i!, offsetBy: n)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices")
public func distance(from i: Index?, to j: Index?) -> Int {
return distance(from: i!, to: j!)
}
@_inlineable // FIXME(sil-serialize-all)
@available(
swift, obsoleted: 4.0,
message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index")
public subscript(i: Index?) -> Unicode.UTF16.CodeUnit {
return self[i!]
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.utf16[someString.utf16.startIndex..<someString.utf16.endIndex]
///
/// was deduced to be of type `String.UTF16View`. Provide a more-specific
/// Swift-3-only `subscript` overload that continues to produce
/// `String.UTF16View`.
extension String.UTF16View {
public typealias SubSequence = Substring.UTF16View
@_inlineable // FIXME(sil-serialize-all)
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UTF16View.SubSequence {
return String.UTF16View.SubSequence(self, _bounds: r)
}
@_inlineable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(bounds: Range<Index>) -> String.UTF16View {
return String.UTF16View(
_core,
offset: _internalIndex(at: bounds.lowerBound.encodedOffset),
length: bounds.upperBound.encodedOffset - bounds.lowerBound.encodedOffset)
}
@_inlineable // FIXME(sil-serialize-all)
@available(swift, obsoleted: 4)
public subscript(bounds: ClosedRange<Index>) -> String.UTF16View {
return self[bounds.relative(to: self)]
}
}
| acfd4ebaed3cd11e79c03a3edf93426b | 34.209917 | 167 | 0.637546 | false | false | false | false |
EstebanVallejo/sdk-ios | refs/heads/master | MercadoPagoSDK/MercadoPagoSDK/NewCardViewController.swift | mit | 2 | //
// NewCardViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 29/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class NewCardViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, KeyboardDelegate {
// ViewController parameters
var key : String?
var keyType : String?
var paymentMethod: PaymentMethod?
var requireSecurityCode : Bool?
var callback: ((cardToken: CardToken) -> Void)?
var identificationType : IdentificationType?
var identificationTypes : [IdentificationType]?
var bundle : NSBundle? = MercadoPago.getBundle()
// Input controls
@IBOutlet weak private var tableView : UITableView!
var cardNumberCell : MPCardNumberTableViewCell!
var expirationDateCell : MPExpirationDateTableViewCell!
var cardholderNameCell : MPCardholderNameTableViewCell!
var userIdCell : MPUserIdTableViewCell!
var securityCodeCell : MPSecurityCodeTableViewCell!
var hasError : Bool = false
var loadingView : UILoadingView!
var inputsCells : NSMutableArray!
init(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: ((cardToken: CardToken) -> Void)?) {
super.init(nibName: "NewCardViewController", bundle: bundle)
self.paymentMethod = paymentMethod
self.requireSecurityCode = requireSecurityCode
self.key = key
self.keyType = keyType
self.callback = callback
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init() {
super.init(nibName: nil, bundle: nil)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override public func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized)
self.title = "Datos de tu tarjeta".localized
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Continuar".localized, style: UIBarButtonItemStyle.Plain, target: self, action: "submitForm")
self.view.addSubview(self.loadingView)
var mercadoPago : MercadoPago
mercadoPago = MercadoPago(keyType: self.keyType, key: self.key)
mercadoPago.getIdentificationTypes({(identificationTypes: [IdentificationType]?) -> Void in
self.identificationTypes = identificationTypes
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}, failure: { (error: NSError?) -> Void in
if error?.code == MercadoPago.ERROR_API_CODE {
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
self.userIdCell.hidden = true
}
}
)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func willHideKeyboard(notification: NSNotification) {
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, 0.0, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
func willShowKeyboard(notification: NSNotification) {
let s:NSValue? = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)
var keyboardBounds :CGRect = s!.CGRectValue()
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, keyboardBounds.size.height, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
public func getIndexForObject(object: AnyObject) -> Int {
var i = 0
for arr in self.inputsCells {
if let input = object as? UITextField {
if let arrTextField = arr[0] as? UITextField {
if input == arrTextField {
return i
}
}
}
i++
}
return -1
}
public func scrollToRow(indexPath: NSIndexPath) {
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
public func focusAndScrollForIndex(index: Int) {
let textField = self.inputsCells[index][0] as? UITextField!
let cell = self.inputsCells[index][1] as? ErrorTableViewCell!
if textField != nil {
if !textField!.isFirstResponder() {
textField!.becomeFirstResponder()
}
}
if cell != nil {
let indexPath = self.tableView.indexPathForCell(cell!)
if indexPath != nil {
scrollToRow(indexPath!)
}
}
}
public func prev(object: AnyObject?) {
if object != nil {
var index = getIndexForObject(object!)
if index >= 1 {
focusAndScrollForIndex(index-1)
}
}
}
public func next(object: AnyObject?) {
if object != nil {
var index = getIndexForObject(object!)
if index < self.inputsCells.count - 1 {
focusAndScrollForIndex(index+1)
}
}
}
public func done(object: AnyObject?) {
if object != nil {
var index = getIndexForObject(object!)
if index < self.inputsCells.count {
let textField = self.inputsCells[index][0] as? UITextField!
let cell = self.inputsCells[index][1] as? ErrorTableViewCell!
if textField != nil {
textField!.resignFirstResponder()
}
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
scrollToRow(indexPath!)
}
}
}
public func prepareTableView() {
self.inputsCells = NSMutableArray()
var cardNumberNib = UINib(nibName: "MPCardNumberTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardNumberNib, forCellReuseIdentifier: "cardNumberCell")
self.cardNumberCell = self.tableView.dequeueReusableCellWithIdentifier("cardNumberCell") as! MPCardNumberTableViewCell
self.cardNumberCell.height = 55.0
if self.paymentMethod != nil {
self.cardNumberCell.setIcon(self.paymentMethod!._id)
self.cardNumberCell._setSetting(self.paymentMethod!.settings[0])
}
self.cardNumberCell.cardNumberTextField.inputAccessoryView = MPToolbar(prevEnabled: false, nextEnabled: true, delegate: self, textFieldContainer: self.cardNumberCell.cardNumberTextField)
self.inputsCells.addObject([self.cardNumberCell.cardNumberTextField, self.cardNumberCell])
var expirationDateNib = UINib(nibName: "MPExpirationDateTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(expirationDateNib, forCellReuseIdentifier: "expirationDateCell")
self.expirationDateCell = self.tableView.dequeueReusableCellWithIdentifier("expirationDateCell") as! MPExpirationDateTableViewCell
self.expirationDateCell.height = 55.0
self.expirationDateCell.expirationDateTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.expirationDateCell.expirationDateTextField)
self.inputsCells.addObject([self.expirationDateCell.expirationDateTextField, self.expirationDateCell])
var cardholderNameNib = UINib(nibName: "MPCardholderNameTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardholderNameNib, forCellReuseIdentifier: "cardholderNameCell")
self.cardholderNameCell = self.tableView.dequeueReusableCellWithIdentifier("cardholderNameCell") as! MPCardholderNameTableViewCell
self.cardholderNameCell.height = 55.0
self.cardholderNameCell.cardholderNameTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.cardholderNameCell.cardholderNameTextField)
self.inputsCells.addObject([self.cardholderNameCell.cardholderNameTextField, self.cardholderNameCell])
var userIdNib = UINib(nibName: "MPUserIdTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(userIdNib, forCellReuseIdentifier: "userIdCell")
self.userIdCell = self.tableView.dequeueReusableCellWithIdentifier("userIdCell") as! MPUserIdTableViewCell
self.userIdCell._setIdentificationTypes(self.identificationTypes)
self.userIdCell.height = 55.0
self.userIdCell.userIdTypeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdTypeTextField)
self.userIdCell.userIdValueTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdValueTextField)
self.inputsCells.addObject([self.userIdCell.userIdTypeTextField, self.userIdCell])
self.inputsCells.addObject([self.userIdCell.userIdValueTextField, self.userIdCell])
self.tableView.delegate = self
self.tableView.dataSource = self
}
public func submitForm() {
var cardToken = CardToken(cardNumber: self.cardNumberCell.getCardNumber(), expirationMonth: self.expirationDateCell.getExpirationMonth(), expirationYear: self.expirationDateCell.getExpirationYear(), securityCode: nil, cardholderName: self.cardholderNameCell.getCardholderName(), docType: self.userIdCell.getUserIdType(), docNumber: self.userIdCell.getUserIdValue())
self.view.addSubview(self.loadingView)
if validateForm(cardToken) {
callback!(cardToken: cardToken)
} else {
self.hasError = true
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell
} else if indexPath.row == 1 {
return self.expirationDateCell
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell
} else if indexPath.row == 1 {
return self.userIdCell
}
}
return UITableViewCell()
}
override public func viewDidLayoutSubviews() {
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.separatorInset = UIEdgeInsetsZero
}
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.layoutMargins = UIEdgeInsetsZero
}
}
public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.layoutMargins = UIEdgeInsetsZero
}
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell.getHeight()
} else if indexPath.row == 1 {
return self.expirationDateCell.getHeight()
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell.getHeight()
} else if indexPath.row == 1 {
return self.userIdCell.getHeight()
}
}
return 55
}
public func validateForm(cardToken : CardToken) -> Bool {
var result : Bool = true
var focusSet : Bool = false
// Validate card number
let errorCardNumber = cardToken.validateCardNumber(paymentMethod!)
if errorCardNumber != nil {
self.cardNumberCell.setError(errorCardNumber!.userInfo!["cardNumber"] as? String)
result = false
} else {
self.cardNumberCell.setError(nil)
}
// Validate expiry date
let errorExpiryDate = cardToken.validateExpiryDate()
if errorExpiryDate != nil {
self.expirationDateCell.setError(errorExpiryDate!.userInfo!["expiryDate"] as? String)
result = false
} else {
self.expirationDateCell.setError(nil)
}
// Validate card holder name
let errorCardholder = cardToken.validateCardholderName()
if errorCardholder != nil {
self.cardholderNameCell.setError(errorCardholder!.userInfo!["cardholder"] as? String)
result = false
} else {
self.cardholderNameCell.setError(nil)
}
// Validate identification number
let errorIdentificationType = cardToken.validateIdentificationType()
var errorIdentificationNumber : NSError? = nil
if self.identificationType != nil {
errorIdentificationNumber = cardToken.validateIdentificationNumber(self.identificationType!)
} else {
errorIdentificationNumber = cardToken.validateIdentificationNumber()
}
if errorIdentificationType != nil {
self.userIdCell.setError(errorIdentificationType!.userInfo!["identification"] as? String)
result = false
} else if errorIdentificationNumber != nil {
self.userIdCell.setError(errorIdentificationNumber!.userInfo!["identification"] as? String)
result = false
} else {
self.userIdCell.setError(nil)
}
return result
}
} | fefcd709c9184fda02a2ea9ae3a7bd12 | 38.065753 | 373 | 0.712162 | false | false | false | false |
miracl/amcl | refs/heads/master | version3/swift/hash512.swift | apache-2.0 | 2 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// hash512.swift - Implementation of SHA-512
//
// Created by Michael Scott on 29/03/2016.
// Copyright © 2016 Michael Scott. All rights reserved.
//
import Foundation
public struct HASH512{
private var length=[UInt64](repeating: 0,count: 2)
private var h=[UInt64](repeating: 0,count: 8)
private var w=[UInt64](repeating: 0,count: 80)
static let H0:UInt64=0x6a09e667f3bcc908
static let H1:UInt64=0xbb67ae8584caa73b
static let H2:UInt64=0x3c6ef372fe94f82b
static let H3:UInt64=0xa54ff53a5f1d36f1
static let H4:UInt64=0x510e527fade682d1
static let H5:UInt64=0x9b05688c2b3e6c1f
static let H6:UInt64=0x1f83d9abfb41bd6b
static let H7:UInt64=0x5be0cd19137e2179
static let len:Int=64
static let K:[UInt64]=[
0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc,
0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118,
0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694,
0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65,
0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5,
0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70,
0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df,
0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b,
0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30,
0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec,
0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b,
0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178,
0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b,
0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c,
0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817]
private static func S(_ n: UInt32,_ x: UInt64) -> UInt64
{
return ((x>>UInt64(n))|(x<<(64-UInt64(n))))
}
private static func R(_ n: UInt32,_ x: UInt64) -> UInt64
{
return (x>>UInt64(n))
}
private static func Ch(_ x: UInt64,_ y: UInt64,_ z:UInt64) -> UInt64
{
return ((x&y)^(~(x)&z))
}
private static func Maj(_ x: UInt64,_ y: UInt64,_ z:UInt64) -> UInt64
{
return ((x&y)^(x&z)^(y&z))
}
private static func Sig0(_ x: UInt64) -> UInt64
{
return (S(28,x)^S(34,x)^S(39,x))
}
private static func Sig1(_ x: UInt64) -> UInt64
{
return (S(14,x)^S(18,x)^S(41,x))
}
private static func theta0(_ x: UInt64) -> UInt64
{
return (S(1,x)^S(8,x)^R(7,x))
}
private static func theta1(_ x: UInt64) -> UInt64
{
return (S(19,x)^S(61,x)^R(6,x))
}
private mutating func transform()
{ /* basic transformation step */
var a,b,c,d,e,f,g,hh,t1,t2 :UInt64
for j in 16 ..< 80
{
w[j]=HASH512.theta1(w[j-2])&+w[j-7]&+HASH512.theta0(w[j-15])&+w[j-16]
}
a=h[0]; b=h[1]; c=h[2]; d=h[3]
e=h[4]; f=h[5]; g=h[6]; hh=h[7]
for j in 0 ..< 80
{ /* 64 times - mush it up */
t1=hh&+HASH512.Sig1(e)&+HASH512.Ch(e,f,g)&+HASH512.K[j]&+w[j]
t2=HASH512.Sig0(a)&+HASH512.Maj(a,b,c)
hh=g; g=f; f=e;
e=d&+t1;
d=c;
c=b;
b=a;
a=t1&+t2;
}
h[0]=h[0]&+a; h[1]=h[1]&+b; h[2]=h[2]&+c; h[3]=h[3]&+d
h[4]=h[4]&+e; h[5]=h[5]&+f; h[6]=h[6]&+g; h[7]=h[7]&+hh;
}
/* Re-Initialise Hash function */
mutating func init_it()
{ /* initialise */
for i in 0 ..< 80 {w[i]=0}
length[0]=0; length[1]=0
h[0]=HASH512.H0;
h[1]=HASH512.H1;
h[2]=HASH512.H2;
h[3]=HASH512.H3;
h[4]=HASH512.H4;
h[5]=HASH512.H5;
h[6]=HASH512.H6;
h[7]=HASH512.H7;
}
public init()
{
init_it()
}
/* process a single byte */
public mutating func process(_ byt: UInt8)
{ /* process the next message byte */
let cnt=Int((length[0]/64)%16)
w[cnt]<<=8;
w[cnt]|=(UInt64(byt)&0xFF);
length[0]+=8;
if (length[0]==0) { length[1] += 1; length[0]=0 }
if ((length[0]%1024)==0) {transform()}
}
/* process an array of bytes */
public mutating func process_array(_ b: [UInt8])
{
for i in 0 ..< b.count {process((b[i]))}
}
/* process a 32-bit integer */
public mutating func process_num(_ n:Int32)
{
process(UInt8((n>>24)&0xff))
process(UInt8((n>>16)&0xff))
process(UInt8((n>>8)&0xff))
process(UInt8(n&0xff))
}
/* Generate 64-byte Hash */
public mutating func hash() -> [UInt8]
{ /* pad message and finish - supply digest */
var digest=[UInt8](repeating: 0,count: 64)
let len0=length[0]
let len1=length[1]
process(0x80);
while ((length[0]%1024) != 896) {process(0)}
w[14]=len1
w[15]=len0;
transform()
for i in 0 ..< HASH512.len
{ /* convert to bytes */
digest[i]=UInt8((h[i/8]>>(8*(7-UInt64(i)%8))) & 0xff);
}
init_it();
return digest;
}
}
| 8ade9e1474c9975e0fa3fb09c993331c | 32.939394 | 84 | 0.622917 | false | false | false | false |
svachmic/ios-url-remote | refs/heads/master | URLRemote/Classes/Controllers/LoginTableViewController.swift | apache-2.0 | 1 | //
// LoginTableViewController.swift
// URLRemote
//
// Created by Michal Švácha on 23/11/16.
// Copyright © 2016 Svacha, Michal. All rights reserved.
//
import UIKit
import Bond
import ReactiveKit
import Material
/// Controller used for logging user in. It is presented when the there is no user logged in.
class LoginTableViewController: UITableViewController, PersistenceStackController {
var stack: PersistenceStack! {
didSet {
viewModel = LoginViewModel(authentication: stack.authentication)
}
}
var viewModel: LoginViewModel!
override func viewDidLoad() {
super.viewDidLoad()
self.setupNotificationHandler()
tableView.apply(Stylesheet.Login.tableView)
self.setupTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/// Sets up event handlers for sign in/up actions.
func setupNotificationHandler() {
viewModel.errors.observeNext { [unowned self] error in
self.handle(error: error)
}.dispose(in: bag)
viewModel.dataSource.flatMap {$0}.observeNext { [unowned self] _ in
self.parent?.dismiss(animated: true)
}.dispose(in: bag)
}
/// Handles an error simply by displaying an alert dialog with the error message describing the problem that has occurred.
///
/// - Parameter error: Error to be handled.
func handle(error: Error) {
let message = error.localizedDescription
self.presentSimpleAlertDialog(
header: NSLocalizedString("ERROR", comment: ""),
message: message)
}
/// Sets up the full table view by hooking in up to the view-model.
func setupTableView() {
self.viewModel.contents.bind(to: self.tableView) { conts, indexPath, tableView in
let content = conts[indexPath.row]
let identifier = content.identifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
cell.selectionStyle = .none
cell.backgroundColor = .clear
switch identifier {
case "emailCell", "passwordCell", "passwordAgainCell":
let textField = cell.viewWithTag(1) as! TextField
textField.placeholder = content.text
textField.apply(Stylesheet.Login.textField)
let leftView = UIImageView()
if identifier == "emailCell" {
leftView.image = Icon.email
self.bindEmailCell(textField: textField)
} else if identifier == "passwordCell" {
leftView.image = Icon.visibility
self.bindPasswordCell(index: 0, textField: textField)
} else if identifier == "passwordAgainCell" {
leftView.image = Icon.visibility
self.bindPasswordCell(index: 1, textField: textField)
}
textField.leftView = leftView
case "signUpCell":
let button = cell.viewWithTag(1) as! RaisedButton
button.titleLabel?.font = RobotoFont.bold(with: 17)
button.title = content.text
button.backgroundColor = UIColor(named: .red)
self.bindSignButton(state: .signIn, button: button)
case "signInCell":
let button = cell.viewWithTag(1) as! RaisedButton
button.titleLabel?.font = RobotoFont.bold(with: 17)
button.title = content.text
button.backgroundColor = UIColor(named: .yellow)
self.bindSignButton(state: .signUp, button: button)
case "textCell":
let label = cell.viewWithTag(1) as! UILabel
label.text = content.text
default:
break
}
return cell
}
}
// MARK: - Bindings
/// Binds the e-mail TextField to the view-model. Also sets up binding for detail label of the TextField to display when the e-mail is invalid.
///
/// - Parameter textField: TextField object to be bound.
func bindEmailCell(textField: TextField) {
textField.reactive.text
.bind(to: viewModel.email)
.dispose(in: textField.bag)
textField.reactive.text.map { text -> String in
if let text = text, !text.isValidEmail(), text != "" {
return NSLocalizedString("INVALID_EMAIL", comment: "")
}
return ""
}.bind(to: textField.reactive.detail)
.dispose(in: textField.bag)
}
/// Binds the password and repeated password TextFields to the view-model.
/// - First TextField has length validation.
/// - Second TextField has similarity validation (to the first one entered).
///
/// - Parameter index: Integer indicating which TextField is to be handled. 0 is for the first, 1 is for the second.
/// - Parameter textField: TextField object to be bound.
func bindPasswordCell(index: Int, textField: TextField) {
if index == 0 {
// first password field during both sign in/up
textField.reactive.text
.bind(to: self.viewModel.password)
.dispose(in: textField.bag)
textField.reactive.text.skip(first: 1).map { text in
if let text = text, (text.count < 6 && text.count != 0) {
return NSLocalizedString("INVALID_PASSWORD_LENGTH", comment: "")
}
return ""
}.bind(to: textField.reactive.detail)
.dispose(in: textField.bag)
} else {
// second password field during sign up
textField.reactive.text
.bind(to: self.viewModel.passwordAgain)
.dispose(in: textField.bag)
combineLatest(self.viewModel.password, self.viewModel.passwordAgain)
.map { password, repeated in
if let pwd = password, let rep = repeated, pwd != rep {
return NSLocalizedString("INVALID_PASSWORD", comment: "")
}
return ""
}.bind(to: textField.reactive.detail)
.dispose(in: textField.bag)
}
}
/// Binds the sign-action button to the desired activity. It is used for both "Sign In" and "Sign Up" buttons, because their actions are the same (just reversed).
/// - "Sign In" transforms when state is .signUp.
/// - "Sign Up" transforms when state is .signIn.
///
/// - Parameter state: State to be compared for transformation.
/// - Parameter button: RaisedButton object to be bound.
func bindSignButton(state: LoginState, button: RaisedButton) {
button.reactive.tap.observeNext { [unowned self] _ in
self.view.endEditing(true)
if self.viewModel.state == state {
self.viewModel.transform()
} else {
if state == .signIn {
self.viewModel.signUp()
} else {
self.viewModel.signIn()
}
}
}.dispose(in: button.bag)
}
// MARK: - UITableView delegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.viewModel.contents[indexPath.row].height
}
}
| 2f9022023a9af8c9df35bea7c2abc8c4 | 38.807292 | 166 | 0.57726 | false | false | false | false |
Zewo/HTTPSerializer | refs/heads/master | Sources/Cookie.swift | mit | 1 | extension Cookie: CustomStringConvertible {
public var description: String {
var string = "\(name)=\(value)"
if let expires = expires {
string += "; Expires=\(expires)"
}
if let maxAge = maxAge {
string += "; Max-Age=\(maxAge)"
}
if let domain = domain {
string += "; Domain=\(domain)"
}
if let path = path {
string += "; Path=\(path)"
}
if secure {
string += "; Secure"
}
if HTTPOnly {
string += "; HttpOnly"
}
return string
}
}
| 95b0b17c2cb892496c0d3f18032b66f8 | 19.290323 | 44 | 0.435612 | false | false | false | false |
designatednerd/EasingExample | refs/heads/master | Easing/ViewController.swift | mit | 1 | //
// ViewController.swift
// Easing
//
// Created by Ellen Shapiro on 10/26/14.
// Copyright (c) 2014 Designated Nerd Software. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var easeInView : UIView?
@IBOutlet var easeOutView : UIView?
@IBOutlet var easeInOutView : UIView?
@IBOutlet var linearView : UIView?
@IBOutlet var goButton : UIButton?
@IBOutlet var resetButton : UIButton?
var targetMove : CGFloat = 0.0
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
resetButton?.enabled = false;
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let reallyAView = easeInView {
let fullViewWidth = CGRectGetWidth(self.view.frame)
targetMove = fullViewWidth - CGRectGetMinX(reallyAView.frame) - CGRectGetWidth(reallyAView.frame) - 20.0
}
}
//MARK: Easy Show/Hide
@IBAction func toggleAlpha(sender: UITapGestureRecognizer) {
if let view = sender.view {
if view.alpha == 1 {
//Dropping alpha to .01 or below causes the tap gesture recognizers to fail. ಠ_ಠ
view.alpha = 0.011
} else {
view.alpha = 1
}
}
}
//MARK: Animations
@IBAction func fireAnimations() {
goButton?.enabled = false;
fireAnimations(2.0, reverse: false)
}
func fireAnimations(duration : NSTimeInterval, reverse : Bool) {
fireAnimationForView(easeInView!, easing: .CurveEaseIn, duration: duration, reverse: reverse)
fireAnimationForView(easeOutView!, easing: .CurveEaseOut, duration: duration, reverse: reverse)
fireAnimationForView(easeInOutView!, easing: .CurveEaseInOut, duration: duration, reverse: reverse)
fireAnimationForView(linearView!, easing: .CurveLinear, duration: duration, reverse: reverse)
}
func fireAnimationForView(view : UIView, easing : UIViewAnimationOptions, duration : NSTimeInterval, reverse : Bool ) {
var move = self.targetMove
if reverse {
move *= -1
}
UIView.animateWithDuration(duration,
delay: 0,
options: easing,
animations: { () -> Void in
view.frame = CGRectOffset(view.frame, move, 0);
}) { (Bool) -> Void in
if reverse {
self.goButton?.enabled = true;
self.resetButton?.enabled = false;
} else {
self.resetButton?.enabled = true;
self.goButton?.enabled = false;
}
}
}
@IBAction func reset() {
fireAnimations(0.0, reverse: true)
}
}
| 1c431b9204d2792d04186107f4ab28ff | 30.815217 | 123 | 0.591732 | false | false | false | false |
JohnEstropia/CoreStore | refs/heads/develop | Sources/Transformable.swift | mit | 1 | //
// Transformable.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - DynamicObject
extension DynamicObject where Self: CoreStoreObject {
/**
The containing type for transformable properties. `Transformable` properties support types that conforms to `NSCoding & NSCopying`.
```
class Animal: CoreStoreObject {
let species = Value.Required<String>("species", initial: "")
let nickname = Value.Optional<String>("nickname")
let color = Transformable.Optional<UIColor>("color")
}
```
- Important: `Transformable` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties.
*/
public typealias Transformable = TransformableContainer<Self>
}
// MARK: - TransformableContainer
/**
The containing type for transformable properties. Use the `DynamicObject.Transformable` typealias instead for shorter syntax.
```
class Animal: CoreStoreObject {
let species = Value.Required<String>("species", initial: "")
let nickname = Value.Optional<String>("nickname")
let color = Transformable.Optional<UIColor>("color")
}
```
*/
public enum TransformableContainer<O: CoreStoreObject> {}
| 15498c90df4cd9eb1961b5d9867b93f9 | 38.180328 | 159 | 0.728452 | false | false | false | false |
LincLiu/SuspensionMenu | refs/heads/master | Classes/Tools.swift | mit | 1 | //
// Tools.swift
// SuspensionMenu
//
// Created by YunKuai on 2017/8/8.
// Copyright © 2017年 dev.liufeng@gmail. All rights reserved.
//
import Foundation
import UIKit
let SCREEN_WIDTH = UIScreen.main.bounds.width
let SCREEN_HEIGHT = UIScreen.main.bounds.height
let SCREEN_RECT = UIScreen.main.bounds
//设置颜色
func RGBA(r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat)->UIColor {return UIColor.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)}
//设置字体大小
func FONT(size:CGFloat,isBold: Bool=false)->UIFont {
if isBold{
return UIFont.boldSystemFont(ofSize: size)
}else{
return UIFont.systemFont(ofSize: size)
}
}
//设置Plus的字号,字体名称,其他机型自适应
func FONT(sizePlus:CGFloat,isBold: Bool=false)->UIFont{
if SCREEN_WIDTH == 375{return FONT(size: CGFloat((375.0/414))*sizePlus,isBold: isBold)}
if SCREEN_WIDTH == 320{return FONT(size: CGFloat((320.0/414))*sizePlus,isBold: isBold)}
return FONT(size: sizePlus)
}
//输入跟屏宽的比,得到对应的距离
func GET_DISTANCE(ratio:Float)->CGFloat{
let distance = SCREEN_WIDTH*CGFloat(ratio)
return distance
}
extension CGRect{
func getMaxY()->CGFloat{
return self.origin.y+self.size.height
}
}
| 46f905bb34a1bcd64db6796dfde2149c | 24.12766 | 136 | 0.700254 | false | false | false | false |
huonw/swift | refs/heads/master | stdlib/public/core/RangeReplaceableCollection.swift | apache-2.0 | 1 | //===--- RangeReplaceableCollection.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A Collection protocol with replaceSubrange.
//
//===----------------------------------------------------------------------===//
/// A type that supports replacement of an arbitrary subrange of elements with
/// the elements of another collection.
///
/// In most cases, it's best to ignore this protocol and use the
/// `RangeReplaceableCollection` protocol instead, because it has a more
/// complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead")
public typealias RangeReplaceableIndexable = RangeReplaceableCollection
/// A collection that supports replacement of an arbitrary subrange of elements
/// with the elements of another collection.
///
/// Range-replaceable collections provide operations that insert and remove
/// elements. For example, you can add elements to an array of strings by
/// calling any of the inserting or appending operations that the
/// `RangeReplaceableCollection` protocol defines.
///
/// var bugs = ["Aphid", "Damselfly"]
/// bugs.append("Earwig")
/// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1)
/// print(bugs)
/// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Likewise, `RangeReplaceableCollection` types can remove one or more
/// elements using a single operation.
///
/// bugs.removeLast()
/// bugs.removeSubrange(1...2)
/// print(bugs)
/// // Prints "["Aphid", "Damselfly"]"
///
/// bugs.removeAll()
/// print(bugs)
/// // Prints "[]"
///
/// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace
/// a subrange of elements with the contents of another collection. Here,
/// three elements in the middle of an array of integers are replaced by the
/// five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// Conforming to the RangeReplaceableCollection Protocol
/// =====================================================
///
/// To add `RangeReplaceableCollection` conformance to your custom collection,
/// add an empty initializer and the `replaceSubrange(_:with:)` method to your
/// custom type. `RangeReplaceableCollection` provides default implementations
/// of all its other methods using this initializer and method. For example,
/// the `removeSubrange(_:)` method is implemented by calling
/// `replaceSubrange(_:with:)` with an empty collection for the `newElements`
/// parameter. You can override any of the protocol's required methods to
/// provide your own custom implementation.
public protocol RangeReplaceableCollection : Collection
where SubSequence : RangeReplaceableCollection {
// FIXME(ABI): Associated type inference requires this.
associatedtype SubSequence
//===--- Fundamental Requirements ---------------------------------------===//
/// Creates a new, empty collection.
init()
/// Replaces the specified subrange of elements with the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameters:
/// - subrange: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*m*), where *m* is the combined length of the collection
/// and `newElements`. If the call to `replaceSubrange` simply appends the
/// contents of `newElements` to the collection, the complexity is O(*n*),
/// where *n* is the length of `newElements`.
mutating func replaceSubrange<C>(
_ subrange: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Element
/// Prepares the collection to store the specified number of elements, when
/// doing so is appropriate for the underlying type.
///
/// If you are adding a known number of elements to a collection, use this
/// method to avoid multiple reallocations. A type that conforms to
/// `RangeReplaceableCollection` can choose how to respond when this method
/// is called. Depending on the type, it may make sense to allocate more or
/// less storage than requested, or to take no action at all.
///
/// - Parameter n: The requested number of elements to store.
mutating func reserveCapacity(_ n: Int)
//===--- Derivable Requirements -----------------------------------------===//
/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// The following example creates an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
init(repeating repeatedValue: Element, count: Int)
/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
init<S : Sequence>(_ elements: S)
where S.Element == Element
/// Adds an element to the end of the collection.
///
/// If the collection does not have sufficient capacity for another element,
/// additional storage is allocated before appending `newElement`. The
/// following example adds a new number to an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// - Parameter newElement: The element to append to the collection.
///
/// - Complexity: O(1) on average, over many additions to the same
/// collection.
mutating func append(_ newElement: Element)
/// Adds the elements of a sequence or collection to the end of this
/// collection.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// The following example appends the elements of a `Range<Int>` instance to
/// an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting
/// collection.
// FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with +=
// suggestion in SE-91
mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Element
/// Inserts a new element into the collection at the specified position.
///
/// The new element is inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as
/// the `index` parameter, the new element is appended to the
/// collection.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElement: The new element to insert into the collection.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index into the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func insert(_ newElement: Element, at i: Index)
/// Inserts the elements of a sequence into the collection at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// Here's an example of inserting a range of integers into an array of the
/// same type:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(contentsOf: 100...103, at: 3)
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElements: The new elements to insert into the collection.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(*m*), where *m* is the combined length of the collection
/// and `newElements`. If `i` is equal to the collection's `endIndex`
/// property, the complexity is O(*n*), where *n* is the length of
/// `newElements`.
mutating func insert<S : Collection>(contentsOf newElements: S, at i: Index)
where S.Element == Element
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes the middle element from an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.2, 1.5, 1.2, 1.6]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter i: The position of the element to remove. `index` must be
/// a valid index of the collection that is not equal to the collection's
/// end index.
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@discardableResult
mutating func remove(at i: Index) -> Element
/// Removes the specified subrange of elements from the collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeSubrange(1...3)
/// print(bugs)
/// // Prints "["Aphid", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The subrange of the collection to remove. The bounds
/// of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeSubrange(_ bounds: Range<Index>)
/// Customization point for `removeLast()`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: A non-nil value if the operation was performed.
mutating func _customRemoveLast() -> Element?
/// Customization point for `removeLast(_:)`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: `true` if the operation was performed.
mutating func _customRemoveLast(_ n: Int) -> Bool
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst()
/// print(bugs)
/// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@discardableResult
mutating func removeFirst() -> Element
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst(3)
/// print(bugs)
/// // Prints "["Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter n: The number of elements to remove from the collection.
/// `n` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeFirst(_ n: Int)
/// Removes all elements from the collection.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter keepCapacity: Pass `true` to request that the collection
/// avoid releasing its storage. Retaining the collection's storage can
/// be a useful optimization when you're planning to grow the collection
/// again. The default value is `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/)
/// Removes from the collection all elements that satisfy the given predicate.
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool) rethrows
// FIXME(ABI): Associated type inference requires this.
subscript(bounds: Index) -> Element { get }
// FIXME(ABI): Associated type inference requires this.
subscript(bounds: Range<Index>) -> SubSequence { get }
}
//===----------------------------------------------------------------------===//
// Default implementations for RangeReplaceableCollection
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollection {
/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@inlinable
public init(repeating repeatedValue: Element, count: Int) {
self.init()
if count != 0 {
let elements = Repeated(_repeating: repeatedValue, count: count)
append(contentsOf: elements)
}
}
/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
@inlinable
public init<S : Sequence>(_ elements: S)
where S.Element == Element {
self.init()
append(contentsOf: elements)
}
/// Adds an element to the end of the collection.
///
/// If the collection does not have sufficient capacity for another element,
/// additional storage is allocated before appending `newElement`. The
/// following example adds a new number to an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// - Parameter newElement: The element to append to the collection.
///
/// - Complexity: O(1) on average, over many additions to the same
/// collection.
@inlinable
public mutating func append(_ newElement: Element) {
insert(newElement, at: endIndex)
}
/// Adds the elements of a sequence or collection to the end of this
/// collection.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// The following example appends the elements of a `Range<Int>` instance to
/// an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting
/// collection.
@inlinable
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Element {
let approximateCapacity = self.count +
numericCast(newElements.underestimatedCount)
self.reserveCapacity(approximateCapacity)
for element in newElements {
append(element)
}
}
/// Inserts a new element into the collection at the specified position.
///
/// The new element is inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as
/// the `index` parameter, the new element is appended to the
/// collection.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElement: The new element to insert into the collection.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index into the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func insert(
_ newElement: Element, at i: Index
) {
replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}
/// Inserts the elements of a sequence into the collection at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// Here's an example of inserting a range of integers into an array of the
/// same type:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(contentsOf: 100...103, at: 3)
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElements: The new elements to insert into the collection.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(*m*), where *m* is the combined length of the collection
/// and `newElements`. If `i` is equal to the collection's `endIndex`
/// property, the complexity is O(*n*), where *n* is the length of
/// `newElements`.
@inlinable
public mutating func insert<C : Collection>(
contentsOf newElements: C, at i: Index
) where C.Element == Element {
replaceSubrange(i..<i, with: newElements)
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes the middle element from an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.2, 1.5, 1.2, 1.6]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter position: The position of the element to remove. `position` must be
/// a valid index of the collection that is not equal to the collection's
/// end index.
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func remove(at position: Index) -> Element {
_precondition(!isEmpty, "Can't remove from an empty collection")
let result: Element = self[position]
replaceSubrange(position..<index(after: position), with: EmptyCollection())
return result
}
/// Removes the elements in the specified subrange from the collection.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes three elements from the middle of an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
/// measurements.removeSubrange(1..<4)
/// print(measurements)
/// // Prints "[1.2, 1.5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The range of the collection to be removed. The
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeSubrange(_ bounds: Range<Index>) {
replaceSubrange(bounds, with: EmptyCollection())
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst(3)
/// print(bugs)
/// // Prints "["Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter n: The number of elements to remove from the collection.
/// `n` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"Can't remove more items from a collection than it has")
let end = index(startIndex, offsetBy: numericCast(n))
removeSubrange(startIndex..<end)
}
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst()
/// print(bugs)
/// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty,
"Can't remove first element from an empty collection")
let firstElement = first!
removeFirst(1)
return firstElement
}
/// Removes all elements from the collection.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter keepCapacity: Pass `true` to request that the collection
/// avoid releasing its storage. Retaining the collection's storage can
/// be a useful optimization when you're planning to grow the collection
/// again. The default value is `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
self = Self()
}
else {
replaceSubrange(startIndex..<endIndex, with: EmptyCollection())
}
}
/// Prepares the collection to store the specified number of elements, when
/// doing so is appropriate for the underlying type.
///
/// If you will be adding a known number of elements to a collection, use
/// this method to avoid multiple reallocations. A type that conforms to
/// `RangeReplaceableCollection` can choose how to respond when this method
/// is called. Depending on the type, it may make sense to allocate more or
/// less storage than requested or to take no action at all.
///
/// - Parameter n: The requested number of elements to store.
@inlinable
public mutating func reserveCapacity(_ n: Int) {}
}
extension RangeReplaceableCollection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
/// - Precondition: `!self.isEmpty`.
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty, "Can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter n: The number of elements to remove from the collection.
/// `n` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(1)
@inlinable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex]
}
}
extension RangeReplaceableCollection {
/// Replaces the specified subrange of elements with the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameters:
/// - subrange: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*m*), where *m* is the combined length of the collection
/// and `newElements`. If the call to `replaceSubrange` simply appends the
/// contents of `newElements` to the collection, the complexity is O(*n*),
/// where *n* is the length of `newElements`.
@inlinable
public mutating func replaceSubrange<C: Collection, R: RangeExpression>(
_ subrange: R,
with newElements: C
) where C.Element == Element, R.Bound == Index {
self.replaceSubrange(subrange.relative(to: self), with: newElements)
}
/// Removes the elements in the specified subrange from the collection.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes three elements from the middle of an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
/// measurements.removeSubrange(1..<4)
/// print(measurements)
/// // Prints "[1.2, 1.5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The range of the collection to be removed. The
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeSubrange<R: RangeExpression>(
_ bounds: R
) where R.Bound == Index {
removeSubrange(bounds.relative(to: self))
}
}
extension RangeReplaceableCollection {
@inlinable
public mutating func _customRemoveLast() -> Element? {
return nil
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
return false
}
}
extension RangeReplaceableCollection
where Self : BidirectionalCollection, SubSequence == Self {
@inlinable
public mutating func _customRemoveLast() -> Element? {
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))]
return true
}
}
extension RangeReplaceableCollection where Self : BidirectionalCollection {
/// Removes and returns the last element of the collection.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection if the collection is not
/// empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popLast() -> Element? {
if isEmpty { return nil }
// duplicate of removeLast logic below, to avoid redundant precondition
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeLast() -> Element {
_precondition(!isEmpty, "Can't remove last element from an empty collection")
// NOTE if you change this implementation, change popLast above as well
// AND change the tie-breaker implementations in the next extension
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes the specified number of elements from the end of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter n: The number of elements to remove from the collection.
/// `n` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the specified number of elements.
@inlinable
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"Can't remove more items from a collection than it contains")
if _customRemoveLast(n) {
return
}
let end = endIndex
removeSubrange(index(end, offsetBy: numericCast(-n))..<end)
}
}
/// Ambiguity breakers.
extension RangeReplaceableCollection
where Self : BidirectionalCollection, SubSequence == Self {
/// Removes and returns the last element of the collection.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection if the collection is not
/// empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popLast() -> Element? {
if isEmpty { return nil }
// duplicate of removeLast logic below, to avoid redundant precondition
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeLast() -> Element {
_precondition(!isEmpty, "Can't remove last element from an empty collection")
// NOTE if you change this implementation, change popLast above as well
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes the specified number of elements from the end of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter n: The number of elements to remove from the collection.
/// `n` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the specified number of elements.
@inlinable
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"Can't remove more items from a collection than it contains")
if _customRemoveLast(n) {
return
}
let end = endIndex
removeSubrange(index(end, offsetBy: numericCast(-n))..<end)
}
}
extension RangeReplaceableCollection {
/// Creates a new collection by concatenating the elements of a collection and
/// a sequence.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of an integer array and a `Range<Int>` instance.
///
/// let numbers = [1, 2, 3, 4]
/// let moreNumbers = numbers + 5...10
/// print(moreNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of the argument on the left-hand
/// side. In the example above, `moreNumbers` has the same type as `numbers`,
/// which is `[Int]`.
///
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: A collection or finite sequence.
@inlinable
public static func + <
Other : Sequence
>(lhs: Self, rhs: Other) -> Self
where Element == Other.Element {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.append(contentsOf: rhs)
return lhs
}
/// Creates a new collection by concatenating the elements of a sequence and a
/// collection.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of a `Range<Int>` instance and an integer array.
///
/// let numbers = [7, 8, 9, 10]
/// let moreNumbers = 1...6 + numbers
/// print(moreNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of argument on the right-hand side.
/// In the example above, `moreNumbers` has the same type as `numbers`, which
/// is `[Int]`.
///
/// - Parameters:
/// - lhs: A collection or finite sequence.
/// - rhs: A range-replaceable collection.
@inlinable
public static func + <
Other : Sequence
>(lhs: Other, rhs: Self) -> Self
where Element == Other.Element {
var result = Self()
result.reserveCapacity(rhs.count + numericCast(lhs.underestimatedCount))
result.append(contentsOf: lhs)
result.append(contentsOf: rhs)
return result
}
/// Appends the elements of a sequence to a range-replaceable collection.
///
/// Use this operator to append the elements of a sequence to the end of
/// range-replaceable collection with same `Element` type. This example appends
/// the elements of a `Range<Int>` instance to an array of integers.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers += 10...15
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameters:
/// - lhs: The array to append to.
/// - rhs: A collection or finite sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting array.
@inlinable
public static func += <
Other : Sequence
>(lhs: inout Self, rhs: Other)
where Element == Other.Element {
lhs.append(contentsOf: rhs)
}
/// Creates a new collection by concatenating the elements of two collections.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of two integer arrays.
///
/// let lowerNumbers = [1, 2, 3, 4]
/// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10]
/// let allNumbers = lowerNumbers + higherNumbers
/// print(allNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of the argument on the left-hand
/// side. In the example above, `moreNumbers` has the same type as `numbers`,
/// which is `[Int]`.
///
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: Another range-replaceable collection.
@inlinable
public static func + <
Other : RangeReplaceableCollection
>(lhs: Self, rhs: Other) -> Self
where Element == Other.Element {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.append(contentsOf: rhs)
return lhs
}
}
extension RangeReplaceableCollection {
/// Returns a new collection of the same type containing, in order, the
/// elements of the original collection that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `isIncluded` allowed.
@inlinable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Self {
return try Self(self.lazy.filter(isIncluded))
}
}
extension RangeReplaceableCollection where Self: MutableCollection {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. This example removes all the odd values from an
/// array of numbers:
///
/// var numbers = [5, 6, 7, 8, 9, 10, 11]
/// numbers.removeAll(where: { $0 % 2 == 1 })
/// // numbers == [6, 8, 10]
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved)
removeSubrange(suffixStart...)
}
}
extension RangeReplaceableCollection {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. This example removes all the vowels from a string:
///
/// var phrase = "The rain in Spain stays mainly in the plain."
///
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// phrase.removeAll(where: { vowels.contains($0) })
/// // phrase == "Th rn n Spn stys mnly n th pln."
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
// FIXME: Switch to using RRC.filter once stdlib is compiled for 4.0
// self = try filter { try !predicate($0) }
self = try Self(self.lazy.filter { try !shouldBeRemoved($0) })
}
}
| 16622f97e3f03f387e17179b33ebb08a | 37.782265 | 115 | 0.652435 | false | false | false | false |
maor-eini/Chop-Chop | refs/heads/master | chopchop/chopchop/ModelSql.swift | mit | 1 | //
// ModelSql.swift
// chopchop
//
// Created by Maor Eini on 18/03/2017.
// Copyright © 2017 Maor Eini. All rights reserved.
//
import Foundation
extension String {
public init?(validatingUTF8 cString: UnsafePointer<UInt8>) {
if let (result, _) = String.decodeCString(cString, as: UTF8.self,
repairingInvalidCodeUnits: false) {
self = result
}
else {
return nil
}
}
}
class ModelSql{
var database: OpaquePointer? = nil
init?(){
let dbFileName = "database.db"
if let dir = FileManager.default.urls(for: .documentDirectory, in:
.userDomainMask).first{
let path = dir.appendingPathComponent(dbFileName)
if sqlite3_open(path.absoluteString, &database) != SQLITE_OK {
print("Failed to open db file: \(path.absoluteString)")
return nil
}
}
if User.createTable(database: database) == false{
return nil
}
if FeedItem.createTable(database: database) == false{
return nil
}
if LastUpdateTableService.createTable(database: database) == false{
return nil
}
}
}
| 208d3cb36dbc509378519431192ae9fc | 24.843137 | 85 | 0.53566 | false | false | false | false |
xGoPox/vapor-authentification | refs/heads/master | Sources/App/Models/UserCredentials.swift | mit | 1 | //
// UserCredentials.swift
// vapor-authentification
//
// Created by Clement Yerochewski on 1/13/17.
//
//
import Auth
import BCrypt
import Node
import Vapor
typealias HashedPassword = (secret: User.Secret, salt: User.Salt)
struct UserCredentials: Credentials {
var password: String
var email: String
private let hash: HashProtocol
init(email: String, password: String, hash: HashProtocol) {
self.email = email
self.hash = hash
self.password = password
}
func hashPassword(using salt: User.Salt = BCryptSalt().string) throws -> HashedPassword {
return (try hash.make((password) + salt), salt)
}
}
struct AuthenticatedUserCredentials: Credentials {
let id: String
/*
init(node: Node) throws {
guard let id: String = try node.extract(User.Keys.id) else {
throw VaporAuthError.couldNotLogIn
}
self.id = id
}*/
}
| adf0083d255da06d2a71c16c1dcd5e79 | 19.630435 | 93 | 0.641728 | false | false | false | false |
OrRon/NexmiiHack | refs/heads/develop | Carthage/Checkouts/LayoutKit/LayoutKit/Layouts/StackLayout.swift | apache-2.0 | 6 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import CoreGraphics
/**
A layout that stacks sublayouts along an axis.
Axis space is allocated to sublayouts according to the distribution policy.
If this not enough space along the axis for all sublayouts then layouts with the highest flexibility are removed
until there is enough space to posistion the remaining layouts.
*/
open class StackLayout<V: View>: BaseLayout<V> {
/// The axis along which sublayouts are stacked.
open let axis: Axis
/**
The distance in points between adjacent edges of sublayouts along the axis.
For Distribution.EqualSpacing, this is a minimum spacing. For all other distributions it is an exact spacing.
*/
open let spacing: CGFloat
/// The distribution of space along the stack's axis.
open let distribution: StackLayoutDistribution
/// The stacked layouts.
open let sublayouts: [Layout]
public init(axis: Axis,
spacing: CGFloat = 0,
distribution: StackLayoutDistribution = .fillFlexing,
alignment: Alignment = .fill,
flexibility: Flexibility? = nil,
viewReuseId: String? = nil,
sublayouts: [Layout],
config: ((V) -> Void)? = nil) {
self.axis = axis
self.spacing = spacing
self.distribution = distribution
self.sublayouts = sublayouts
let flexibility = flexibility ?? StackLayout.defaultFlexibility(axis: axis, sublayouts: sublayouts)
super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, config: config)
}
}
// MARK: - Layout interface
extension StackLayout: ConfigurableLayout {
public func measurement(within maxSize: CGSize) -> LayoutMeasurement {
var availableSize = AxisSize(axis: axis, size: maxSize)
var sublayoutMeasurements = [LayoutMeasurement?](repeating: nil, count: sublayouts.count)
var usedSize = AxisSize(axis: axis, size: .zero)
let sublayoutLengthForEqualSizeDistribution: CGFloat?
if distribution == .fillEqualSize {
sublayoutLengthForEqualSizeDistribution = sublayoutSpaceForEqualSizeDistribution(
totalAvailableSpace: availableSize.axisLength, sublayoutCount: sublayouts.count)
} else {
sublayoutLengthForEqualSizeDistribution = nil
}
for (index, sublayout) in sublayoutsByAxisFlexibilityAscending() {
if availableSize.axisLength <= 0 || availableSize.crossLength <= 0 {
// There is no more room in the stack so don't bother measuring the rest of the sublayouts.
break
}
let sublayoutMasurementAvailableSize: CGSize
if let sublayoutLengthForEqualSizeDistribution = sublayoutLengthForEqualSizeDistribution {
sublayoutMasurementAvailableSize = AxisSize(axis: axis,
axisLength: sublayoutLengthForEqualSizeDistribution,
crossLength: availableSize.crossLength).size
} else {
sublayoutMasurementAvailableSize = availableSize.size
}
let sublayoutMeasurement = sublayout.measurement(within: sublayoutMasurementAvailableSize)
sublayoutMeasurements[index] = sublayoutMeasurement
let sublayoutAxisSize = AxisSize(axis: axis, size: sublayoutMeasurement.size)
if sublayoutAxisSize.axisLength > 0 {
// If we are the first sublayout in the stack, then no leading spacing is required.
// Otherwise account for the spacing.
let leadingSpacing = (usedSize.axisLength > 0) ? spacing : 0
usedSize.axisLength += leadingSpacing + sublayoutAxisSize.axisLength
usedSize.crossLength = max(usedSize.crossLength, sublayoutAxisSize.crossLength)
// Reserve spacing for the next sublayout.
availableSize.axisLength -= sublayoutAxisSize.axisLength + spacing
}
}
let nonNilMeasuredSublayouts = sublayoutMeasurements.flatMap { $0 }
if distribution == .fillEqualSize && !nonNilMeasuredSublayouts.isEmpty {
let maxAxisLength = nonNilMeasuredSublayouts.map({ AxisSize(axis: axis, size: $0.size).axisLength }).max() ?? 0
usedSize.axisLength = (maxAxisLength + spacing) * CGFloat(nonNilMeasuredSublayouts.count) - spacing
}
return LayoutMeasurement(layout: self, size: usedSize.size, maxSize: maxSize, sublayouts: nonNilMeasuredSublayouts)
}
public func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement {
let frame = alignment.position(size: measurement.size, in: rect)
let availableSize = AxisSize(axis: axis, size: frame.size)
let excessAxisLength = availableSize.axisLength - AxisSize(axis: axis, size: measurement.size).axisLength
let config = distributionConfig(excessAxisLength: excessAxisLength)
var nextOrigin = AxisPoint(axis: axis, axisOffset: config.initialAxisOffset, crossOffset: 0)
var sublayoutArrangements = [LayoutArrangement]()
for (index, sublayout) in measurement.sublayouts.enumerated() {
var sublayoutAvailableSize = AxisSize(axis: axis, size: sublayout.size)
sublayoutAvailableSize.crossLength = availableSize.crossLength
if distribution == .fillEqualSize {
sublayoutAvailableSize.axisLength = sublayoutSpaceForEqualSizeDistribution(
totalAvailableSpace: AxisSize(axis: axis, size: frame.size).axisLength,
sublayoutCount: measurement.sublayouts.count)
} else if config.stretchIndex == index {
sublayoutAvailableSize.axisLength += excessAxisLength
}
let sublayoutArrangement = sublayout.arrangement(within: CGRect(origin: nextOrigin.point, size: sublayoutAvailableSize.size))
sublayoutArrangements.append(sublayoutArrangement)
nextOrigin.axisOffset += sublayoutAvailableSize.axisLength
if sublayoutAvailableSize.axisLength > 0 {
// Only add spacing below a view if it was allocated non-zero height.
nextOrigin.axisOffset += config.axisSpacing
}
}
return LayoutArrangement(layout: self, frame: frame, sublayouts: sublayoutArrangements)
}
private func sublayoutSpaceForEqualSizeDistribution(totalAvailableSpace: CGFloat, sublayoutCount: Int) -> CGFloat {
guard sublayoutCount > 0 else {
return totalAvailableSpace
}
if spacing == 0 {
return totalAvailableSpace / CGFloat(sublayoutCount)
}
// Note: we don't actually need to check for zero spacing above, because division by zero produces a valid result for floating point values.
// We check anyway for the sake of clarity.
let maxSpacings = floor(totalAvailableSpace / spacing)
let visibleSublayoutCount = min(CGFloat(sublayoutCount), maxSpacings + 1)
let spaceAvailableForSublayouts = totalAvailableSpace - CGFloat(visibleSublayoutCount - 1) * spacing
return spaceAvailableForSublayouts / CGFloat(visibleSublayoutCount)
}
}
// MARK: - Distribution
/**
Specifies how excess space along the axis is allocated.
*/
public enum StackLayoutDistribution {
/**
Sublayouts are positioned starting at the top edge of vertical stacks or at the leading edge of horizontal stacks.
*/
case leading
/**
Sublayouts are positioned starting at the bottom edge of vertical stacks or at the the trailing edge of horizontal stacks.
*/
case trailing
/**
Sublayouts are positioned so that they are centered along the stack's axis.
*/
case center
/**
Distributes excess axis space by increasing the spacing between each sublayout by an equal amount.
The sublayouts and the adjusted spacing consume all of the available axis space.
*/
case fillEqualSpacing
/**
Distributes axis space equally among the sublayouts.
The spacing between the sublayouts remains equal to the spacing parameter.
*/
case fillEqualSize
/**
Distributes excess axis space by growing the most flexible sublayout along the axis.
*/
case fillFlexing
}
private struct DistributionConfig {
let initialAxisOffset: CGFloat
let axisSpacing: CGFloat
let stretchIndex: Int?
}
extension StackLayout {
fileprivate func distributionConfig(excessAxisLength: CGFloat) -> DistributionConfig {
let initialAxisOffset: CGFloat
let axisSpacing: CGFloat
var stretchIndex: Int? = nil
switch distribution {
case .leading:
initialAxisOffset = 0
axisSpacing = spacing
case .trailing:
initialAxisOffset = excessAxisLength
axisSpacing = spacing
case .center:
initialAxisOffset = excessAxisLength / 2.0
axisSpacing = spacing
case .fillEqualSpacing:
initialAxisOffset = 0
axisSpacing = max(spacing, excessAxisLength / CGFloat(sublayouts.count - 1))
case .fillEqualSize:
initialAxisOffset = 0
axisSpacing = spacing
case .fillFlexing:
axisSpacing = spacing
initialAxisOffset = 0
if excessAxisLength > 0 {
stretchIndex = stretchableSublayoutIndex()
}
}
return DistributionConfig(initialAxisOffset: initialAxisOffset, axisSpacing: axisSpacing, stretchIndex: stretchIndex)
}
// MARK: - Axis flexing
/**
Returns the sublayouts sorted by flexibility ascending.
*/
fileprivate func sublayoutsByAxisFlexibilityAscending() -> [(offset: Int, element: Layout)] {
return sublayouts.enumerated().sorted(by: layoutsFlexibilityAscending)
}
/**
Returns the index of the most flexible sublayout.
It returns nil if there are no flexible sublayouts.
*/
private func stretchableSublayoutIndex() -> Int? {
guard let (index, sublayout) = sublayouts.enumerated().max(by: layoutsFlexibilityAscending) else {
return nil
}
if sublayout.flexibility.flex(axis) == nil {
// The most flexible sublayout is still not flexible, so don't stretch it.
return nil
}
return index
}
/**
Returns true iff the left layout is less flexible than the right layout.
If two sublayouts have the same flexibility, then sublayout with the higher index is considered more flexible.
Inflexible layouts are sorted before all flexible layouts.
*/
private func layoutsFlexibilityAscending(compare :(left: (offset: Int, element: Layout), right: (offset: Int, element: Layout))) -> Bool {
let leftFlex = compare.left.element.flexibility.flex(axis)
let rightFlex = compare.right.element.flexibility.flex(axis)
if leftFlex == rightFlex {
return compare.left.offset < compare.right.offset
}
// nil is less than all integers
return leftFlex ?? .min < rightFlex ?? .min
}
/**
Inherit the maximum flexibility of sublayouts along the axis and minimum flexibility of sublayouts across the axis.
*/
fileprivate static func defaultFlexibility(axis: Axis, sublayouts: [Layout]) -> Flexibility {
let initial = AxisFlexibility(axis: axis, axisFlex: nil, crossFlex: .max)
return sublayouts.reduce(initial) { (flexibility: AxisFlexibility, sublayout: Layout) -> AxisFlexibility in
let subflex = AxisFlexibility(axis: axis, flexibility: sublayout.flexibility)
let axisFlex = Flexibility.max(flexibility.axisFlex, subflex.axisFlex)
let crossFlex = Flexibility.min(flexibility.crossFlex, subflex.crossFlex)
return AxisFlexibility(axis: axis, axisFlex: axisFlex, crossFlex: crossFlex)
}.flexibility
}
}
| e472e58f5ddf52025affd2855d64d81c | 43.094406 | 148 | 0.671874 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/Core/Test/Code/MockResponseCache.swift | apache-2.0 | 3 | //
// MockResponseCache.swift
// edX
//
// Created by Akiva Leffert on 6/19/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import edXCore
class MockResponseCache: NSObject, ResponseCache {
private var backing : [String: ResponseCacheEntry] = [:]
func fetchCacheEntryWithRequest(request: NSURLRequest, completion: ResponseCacheEntry? -> Void) {
let key = responseCacheKeyForRequest(request)
completion(key.flatMap{ backing[$0] })
}
func setCacheResponse(response: NSHTTPURLResponse, withData data: NSData?, forRequest request: NSURLRequest, completion: (Void -> Void)?) {
if let key = responseCacheKeyForRequest(request) {
backing[key] = ResponseCacheEntry(data : data, response : response)
}
completion?()
}
func clear() {
backing = [:]
}
var isEmpty : Bool {
return backing.count == 0
}
}
| 169966021b61458b8a63192533df3e68 | 27.121212 | 143 | 0.640086 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | refs/heads/develop | Example/Pods/RxCocoa/RxCocoa/RxCocoa.swift | apache-2.0 | 19 | //
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSNull
// Importing RxCocoa also imports RxRelay
@_exported import RxRelay
import RxSwift
#if os(iOS)
import UIKit
#endif
/// RxCocoa errors.
public enum RxCocoaError
: Swift.Error
, CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown
/// Invalid operation was attempted.
case invalidOperation(object: Any)
/// Items are not yet bound to user interface but have been requested.
case itemsNotYetBound(object: Any)
/// Invalid KVO Path.
case invalidPropertyName(object: Any, propertyName: String)
/// Invalid object on key path.
case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String)
/// Error during swizzling.
case errorDuringSwizzling
/// Casting error.
case castingError(object: Any, targetType: Any.Type)
}
// MARK: Debug descriptions
extension RxCocoaError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .itemsNotYetBound(object):
return "Data source is set, but items are not yet bound to user interface for `\(object)`."
case let .invalidPropertyName(object, propertyName):
return "Object `\(object)` doesn't have a property named `\(propertyName)`."
case let .invalidObjectOnKeyPath(object, sourceObject, propertyName):
return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`."
case .errorDuringSwizzling:
return "Error during swizzling."
case let .castingError(object, targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
// MARK: Error binding policies
func bindingError(_ error: Swift.Error) {
let error = "Binding error: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never {
rxFatalError(message, file: file, line: line)
}
func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage(), file: file, line: line)
}
func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
fatalError(lastMessage(), file: file, line: line)
#else
print("\(file):\(line): \(lastMessage())")
#endif
}
// MARK: casts or fatal error
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
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
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(String(describing: value)) to \(T.self)")
}
return result
}
// MARK: Error messages
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
// MARK: Shared with RxSwift
func rxFatalError(_ lastMessage: String) -> Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
| feb76673204f75ccedc4b958530cafa1 | 30.122581 | 230 | 0.672264 | false | false | false | false |
hyperoslo/Orchestra | refs/heads/master | Example/OrchestraDemo/OrchestraDemo/Sources/Controllers/MainController.swift | mit | 1 | import UIKit
import Hue
class MainController: UITabBarController {
lazy var projectListController: UINavigationController = {
let controller = ProjectListController()
let navigationController = UINavigationController(rootViewController: controller)
controller.tabBarItem.title = "Open Source"
controller.tabBarItem.image = UIImage(named: "tabProjects")
return navigationController
}()
lazy var teamController: TeamController = {
let controller = TeamController()
controller.tabBarItem.title = "Team"
controller.tabBarItem.image = UIImage(named: "tabTeam")
return controller
}()
lazy var playgroundController: PlaygroundController = {
let controller = PlaygroundController()
controller.tabBarItem.title = "Playground"
controller.tabBarItem.image = UIImage(named: "tabPlayground")
return controller
}()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureTabBar()
}
// MARK: - Configuration
func configureTabBar() {
tabBar.translucent = true
tabBar.tintColor = UIColor.hex("F57D2D")
viewControllers = [
projectListController,
teamController,
playgroundController
]
selectedIndex = 0
}
}
| 11eb8c2c721cd0d89b4bdedc9c643f70 | 23.096154 | 85 | 0.71668 | false | true | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Domain Model/EurofurenceModel/Private/Objects/Entities/EventImpl.swift | mit | 1 | import EventBus
import Foundation
class EventImpl: Event {
private let eventBus: EventBus
private let imageCache: ImagesCache
private let shareableURLFactory: ShareableURLFactory
private let posterImageId: String?
private let bannerImageId: String?
var posterGraphicPNGData: Data? {
return posterImageId.let(imageCache.cachedImageData)
}
var bannerGraphicPNGData: Data? {
return bannerImageId.let(imageCache.cachedImageData)
}
var identifier: EventIdentifier
var title: String
var subtitle: String
var abstract: String
var room: Room
var track: Track
var hosts: String
var startDate: Date
var endDate: Date
var eventDescription: String
var isSponsorOnly: Bool
var isSuperSponsorOnly: Bool
var isArtShow: Bool
var isKageEvent: Bool
var isDealersDen: Bool
var isMainStage: Bool
var isPhotoshoot: Bool
var isAcceptingFeedback: Bool
var day: ConferenceDayCharacteristics
init(eventBus: EventBus,
imageCache: ImagesCache,
shareableURLFactory: ShareableURLFactory,
isFavourite: Bool,
identifier: EventIdentifier,
title: String,
subtitle: String,
abstract: String,
room: Room,
track: Track,
hosts: String,
startDate: Date,
endDate: Date,
eventDescription: String,
posterImageId: String?,
bannerImageId: String?,
isSponsorOnly: Bool,
isSuperSponsorOnly: Bool,
isArtShow: Bool,
isKageEvent: Bool,
isDealersDen: Bool,
isMainStage: Bool,
isPhotoshoot: Bool,
isAcceptingFeedback: Bool,
day: ConferenceDayCharacteristics) {
self.eventBus = eventBus
self.imageCache = imageCache
self.shareableURLFactory = shareableURLFactory
self.isFavourite = isFavourite
self.identifier = identifier
self.title = title
self.subtitle = subtitle
self.abstract = abstract
self.room = room
self.track = track
self.hosts = hosts
self.startDate = startDate
self.endDate = endDate
self.eventDescription = eventDescription
self.posterImageId = posterImageId
self.bannerImageId = bannerImageId
self.isSponsorOnly = isSponsorOnly
self.isSuperSponsorOnly = isSuperSponsorOnly
self.isArtShow = isArtShow
self.isKageEvent = isKageEvent
self.isDealersDen = isDealersDen
self.isMainStage = isMainStage
self.isPhotoshoot = isPhotoshoot
self.isAcceptingFeedback = isAcceptingFeedback
self.day = day
}
private var observers: [EventObserver] = []
func add(_ observer: EventObserver) {
observers.append(observer)
provideFavouritedStateToObserver(observer)
}
func remove(_ observer: EventObserver) {
observers.removeAll(where: { $0 === observer })
}
private var isFavourite: Bool {
didSet {
postFavouriteStateChangedEvent()
}
}
func favourite() {
isFavourite = true
notifyObserversFavouritedStateDidChange()
}
func unfavourite() {
isFavourite = false
notifyObserversFavouritedStateDidChange()
}
func prepareFeedback() -> EventFeedback {
if isAcceptingFeedback {
return AcceptingEventFeedback(eventBus: eventBus, eventIdentifier: identifier)
} else {
return NotAcceptingEventFeedback()
}
}
func makeContentURL() -> URL {
return shareableURLFactory.makeURL(for: identifier)
}
private func notifyObserversFavouritedStateDidChange() {
observers.forEach(provideFavouritedStateToObserver)
}
private func provideFavouritedStateToObserver(_ observer: EventObserver) {
if isFavourite {
observer.eventDidBecomeFavourite(self)
} else {
observer.eventDidBecomeUnfavourite(self)
}
}
private func postFavouriteStateChangedEvent() {
let event: Any
if isFavourite {
event = DomainEvent.FavouriteEvent(identifier: identifier)
} else {
event = DomainEvent.UnfavouriteEvent(identifier: identifier)
}
eventBus.post(event)
}
}
| 715ea720c1285f14def2ef0c1a83adfe | 27.393548 | 90 | 0.642354 | false | false | false | false |
ps2/rileylink_ios | refs/heads/dev | MinimedKit/Messages/PumpErrorMessageBody.swift | mit | 1 | //
// PumpErrorMessageBody.swift
// RileyLink
//
// Created by Pete Schwamb on 5/10/17.
// Copyright © 2017 Pete Schwamb. All rights reserved.
//
import Foundation
public enum PumpErrorCode: UInt8, CustomStringConvertible {
// commandRefused can happen when temp basal type is set incorrectly, during suspended pump, or unfinished prime.
case commandRefused = 0x08
case maxSettingExceeded = 0x09
case bolusInProgress = 0x0c
case pageDoesNotExist = 0x0d
public var description: String {
switch self {
case .commandRefused:
return LocalizedString("Command refused", comment: "Pump error code returned when command refused")
case .maxSettingExceeded:
return LocalizedString("Max setting exceeded", comment: "Pump error code describing max setting exceeded")
case .bolusInProgress:
return LocalizedString("Bolus in progress", comment: "Pump error code when bolus is in progress")
case .pageDoesNotExist:
return LocalizedString("History page does not exist", comment: "Pump error code when invalid history page is requested")
}
}
public var recoverySuggestion: String? {
switch self {
case .commandRefused:
return LocalizedString("Check that the pump is not suspended or priming, or has a percent temp basal type", comment: "Suggestions for diagnosing a command refused pump error")
default:
return nil
}
}
}
public class PumpErrorMessageBody: DecodableMessageBody {
public static let length = 1
let rxData: Data
public let errorCode: PartialDecode<PumpErrorCode, UInt8>
public required init?(rxData: Data) {
self.rxData = rxData
let rawErrorCode = rxData[0]
if let errorCode = PumpErrorCode(rawValue: rawErrorCode) {
self.errorCode = .known(errorCode)
} else {
self.errorCode = .unknown(rawErrorCode)
}
}
public var txData: Data {
return rxData
}
public var description: String {
return "PumpError(\(errorCode))"
}
}
| f96e4055cec0151f9ec2e2dd51732de5 | 32.734375 | 187 | 0.659101 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Metadata/Sources/MetadataKit/Models/MetadataPayload.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct MetadataPayload: Equatable {
let version: Int
let payload: String
let signature: String
let prevMagicHash: String?
let typeId: Int
let createdAt: Int
let updatedAt: Int
let address: String
public init(
version: Int,
payload: String,
signature: String,
prevMagicHash: String?,
typeId: Int,
createdAt: Int,
updatedAt: Int,
address: String
) {
self.version = version
self.payload = payload
self.signature = signature
self.prevMagicHash = prevMagicHash
self.typeId = typeId
self.createdAt = createdAt
self.updatedAt = updatedAt
self.address = address
}
}
public struct MetadataBody: Equatable {
public let version: Int
public let payload: String
public let signature: String
public let prevMagicHash: String?
public let typeId: Int
public init(
version: Int,
payload: String,
signature: String,
prevMagicHash: String?,
typeId: Int
) {
self.version = version
self.payload = payload
self.signature = signature
self.prevMagicHash = prevMagicHash
self.typeId = typeId
}
}
| 23cc72cab94e9e6f979b1c8c9535e624 | 22.275862 | 62 | 0.614815 | false | false | false | false |
Chovans/WeatherAppDemo | refs/heads/master | Chovans2/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// Chovans2
//
// Created by chovans on 15/9/6.
// Copyright © 2015年 chovans. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
let menuItemView:MenuItemView = MenuItemView()
override func viewDidLoad() {
super.viewDidLoad()
menuItemView.itemArray[1].addTarget(self, action: Selector("trun2Weather:"), forControlEvents: .TouchDown)
menuItemView.itemArray[2].addTarget(self, action: Selector("turn2News:"), forControlEvents: .TouchDown)
view.addSubview(menuItemView)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("menuItemShow:"))
rightSwipe.direction = UISwipeGestureRecognizerDirection.Right
view.addGestureRecognizer(rightSwipe)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("menuItemHidden:"))
leftSwipe.direction = UISwipeGestureRecognizerDirection.Left
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
// modalPresentationStyle = UIModalPresentationStyle.Popover
//跳转效果,未实现自定义
modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
}
func menuItemShow(sender:UISwipeGestureRecognizer){
menuItemView.showAnimation()
}
func menuItemHidden(sender:UISwipeGestureRecognizer){
menuItemView.hideAnimation(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func trun2Weather(sender:AnyObject){
// self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController((storyboard?.instantiateViewControllerWithIdentifier("WeatherScene"))!, animated: true, completion: nil)
}
func turn2News(sender:AnyObject){
// self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController((storyboard?.instantiateViewControllerWithIdentifier("NewsScene"))!, animated: true, completion: nil)
}
}
| a7d4416caf43cf8c369adbfafa319e76 | 31.90625 | 139 | 0.704179 | false | false | false | false |
ZeldaIV/TDC2015-FP | refs/heads/master | Demo 2/Sequences/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift | gpl-3.0 | 26 | //
// RecursiveScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RecursiveScheduler<State, S: SchedulerType>: RecursiveSchedulerOf<State, S.TimeInterval> {
let scheduler: S
init(scheduler: S, action: Action) {
self.scheduler = scheduler
super.init(action: action)
}
override func scheduleRelativeAdapter(state: State, dueTime: S.TimeInterval, action: State -> Disposable) -> Disposable {
return scheduler.scheduleRelative(state, dueTime: dueTime, action: action)
}
override func scheduleAdapter(state: State, action: State -> Disposable) -> Disposable {
return scheduler.schedule(state, action: action)
}
}
/**
Type erased recursive scheduler.
*/
public class RecursiveSchedulerOf<State, TimeInterval> {
typealias Action = (state: State, scheduler: RecursiveSchedulerOf<State, TimeInterval>) -> Void
let lock = NSRecursiveLock()
// state
let group = CompositeDisposable()
var action: Action?
init(action: Action) {
self.action = action
}
// abstract methods
func scheduleRelativeAdapter(state: State, dueTime: TimeInterval, action: State -> Disposable) -> Disposable {
return abstractMethod()
}
func scheduleAdapter(state: State, action: State -> Disposable) -> Disposable {
return abstractMethod()
}
/**
Schedules an action to be executed recursively.
- parameter state: State passed to the action to be executed.
- parameter dueTime: Relative time after which to execute the recursive action.
*/
public func schedule(state: State, dueTime: TimeInterval) {
var isAdded = false
var isDone = false
var removeKey: CompositeDisposable.DisposeKey? = nil
let d = scheduleRelativeAdapter(state, dueTime: dueTime) { (state) -> Disposable in
// best effort
if self.group.disposed {
return NopDisposable.instance
}
let action = self.lock.calculateLocked { () -> Action? in
if isAdded {
self.group.removeDisposable(removeKey!)
}
else {
isDone = true
}
return self.action
}
if let action = action {
action(state: state, scheduler: self)
}
return NopDisposable.instance
}
lock.performLocked {
if !isDone {
removeKey = group.addDisposable(d)
isAdded = true
}
}
}
/**
Schedules an action to be executed recursively.
- parameter state: State passed to the action to be executed.
*/
public func schedule(state: State) {
var isAdded = false
var isDone = false
var removeKey: CompositeDisposable.DisposeKey? = nil
let d = scheduleAdapter(state) { (state) -> Disposable in
// best effort
if self.group.disposed {
return NopDisposable.instance
}
let action = self.lock.calculateLocked { () -> Action? in
if isAdded {
self.group.removeDisposable(removeKey!)
}
else {
isDone = true
}
return self.action
}
if let action = action {
action(state: state, scheduler: self)
}
return NopDisposable.instance
}
lock.performLocked {
if !isDone {
removeKey = group.addDisposable(d)
isAdded = true
}
}
}
func dispose() {
self.lock.performLocked {
self.action = nil
}
self.group.dispose()
}
}
/**
Type erased recursive scheduler.
*/
public class RecursiveImmediateSchedulerOf<State> {
typealias Action = (state: State, recurse: State -> Void) -> Void
var lock = SpinLock()
let group = CompositeDisposable()
var action: Action?
let scheduler: ImmediateSchedulerType
init(action: Action, scheduler: ImmediateSchedulerType) {
self.action = action
self.scheduler = scheduler
}
// immediate scheduling
/**
Schedules an action to be executed recursively.
- parameter state: State passed to the action to be executed.
*/
public func schedule(state: State) {
var isAdded = false
var isDone = false
var removeKey: CompositeDisposable.DisposeKey? = nil
let d = self.scheduler.schedule(state) { (state) -> Disposable in
// best effort
if self.group.disposed {
return NopDisposable.instance
}
let action = self.lock.calculateLocked { () -> Action? in
if isAdded {
self.group.removeDisposable(removeKey!)
}
else {
isDone = true
}
return self.action
}
if let action = action {
action(state: state, recurse: self.schedule)
}
return NopDisposable.instance
}
lock.performLocked {
if !isDone {
removeKey = group.addDisposable(d)
isAdded = true
}
}
}
func dispose() {
self.lock.performLocked {
self.action = nil
}
self.group.dispose()
}
} | cef503bc3fbdfc43a7c2958304204cbf | 26.380734 | 125 | 0.529993 | false | false | false | false |
aliyasineser/Minify | refs/heads/develop | Minify/Utils/ScrollingTextView.swift | apache-2.0 | 1 | //
// ScrollingTextView.swift
// Minify
//
// Created by Ali Yasin Eser on 6.05.2021.
// Copyright © 2021 aliyasineser. All rights reserved.
//
import Foundation
import Cocoa
open class ScrollingTextView: NSView {
// MARK: - Open variables
/// Text to scroll
open var text: NSString?
/// Font for scrolling text
open var font: NSFont?
/// Scrolling text color
open var textColor: NSColor = .headerTextColor
/// Determines if the text should be delayed before starting scroll
open var isDelayed: Bool = true
/// Spacing between the tail and head of the scrolling text
open var spacing: CGFloat = 20
/// Length of the scrolling text view
open var length: CGFloat = 0 {
didSet {
updateTraits()
}
}
/// Amount of time the text is delayed before scrolling
open var delay: TimeInterval = 2 {
didSet {
updateTraits()
}
}
/// Speed at which the text scrolls. This number is divided by 100.
open var speed: Double = 4 {
didSet {
updateTraits()
}
}
// MARK: - Private variables
private var timer: Timer?
private var point = NSPoint(x: 0, y: 0)
private var timeInterval: TimeInterval?
private(set) var stringSize = NSSize(width: 0, height: 0) {
didSet {
point.x = 0
}
}
private var timerSpeed: Double? {
return speed / 100
}
private lazy var textFontAttributes: [NSAttributedString.Key: Any] = {
return [NSAttributedString.Key.font: font ?? NSFont.systemFont(ofSize: 14)]
}()
// MARK: - Open functions
/**
Sets up the scrolling text view
- Parameters:
- string: The string that will be used as the text in the view
*/
open func setup(string: String) {
text = string as NSString
stringSize = text?.size(withAttributes: textFontAttributes) ?? NSSize(width: 0, height: 0)
setNeedsDisplay(NSRect(x: 0, y: 0, width: frame.width, height: frame.height))
updateTraits()
}
}
// MARK: - Private extension
private extension ScrollingTextView {
func setSpeed(newInterval: TimeInterval) {
clearTimer()
timeInterval = newInterval
guard let timeInterval = timeInterval else { return }
if timer == nil, timeInterval > 0.0, text != nil {
if #available(OSX 10.12, *) {
timer = Timer.scheduledTimer(timeInterval: newInterval, target: self, selector: #selector(update(_:)), userInfo: nil, repeats: true)
guard let timer = timer else { return }
RunLoop.main.add(timer, forMode: .common)
} else {
// Fallback on earlier versions
}
} else {
clearTimer()
point.x = 0
}
}
func updateTraits() {
clearTimer()
if stringSize.width > length {
guard let speed = timerSpeed else { return }
if #available(OSX 10.12, *), isDelayed {
timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false, block: { [weak self] timer in
self?.setSpeed(newInterval: speed)
})
} else {
setSpeed(newInterval: speed)
}
} else {
setSpeed(newInterval: 0.0)
}
}
func clearTimer() {
timer?.invalidate()
timer = nil
}
@objc
func update(_ sender: Timer) {
point.x = point.x - 1
setNeedsDisplay(NSRect(x: 0, y: 0, width: frame.width, height: frame.height))
}
}
// MARK: - Overrides
extension ScrollingTextView {
override open func draw(_ dirtyRect: NSRect) {
if point.x + stringSize.width < 0 {
point.x += stringSize.width + spacing
}
textFontAttributes[NSAttributedString.Key.foregroundColor] = textColor
text?.draw(at: point, withAttributes: textFontAttributes)
if point.x < 0 {
var otherPoint = point
otherPoint.x += stringSize.width + spacing
text?.draw(at: otherPoint, withAttributes: textFontAttributes)
}
}
override open func layout() {
super.layout()
point.y = (frame.height - stringSize.height) / 2
}
}
| 26cac48c273c920c338f13b3acf2dafa | 26.417722 | 148 | 0.581025 | false | false | false | false |
Unipagos/UnipagosIntegrationIOSSwift | refs/heads/master | UnipagosIntegrationTest/ViewController.swift | mit | 1 | //
// ViewController.swift
// UnipagosIntegrationTest
//
// Created by Leonardo Cid on 22/09/14.
// Copyright (c) 2014 Unipagos. All rights reserved.
//
import UIKit
let kPaymentURLiteralAmount = "a";
let kPaymentURLiteralRecipientID = "r";
let kPaymentURLiteralReferenceID = "i";
let kPaymentURLiteralCallbackURL = "url";
let kPaymentURLiteralReferenceText = "t";
let kPaymentURLiteralNeedsUserValidation = "v";
let kPaymentURLiteralURLScheme = "unipagos://pay";
//you will use one of these two
let kPaymentURLiteralMerchant = "merchant";
let kPaymentURLiteralMDN = "mdn";
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var recipientText : UITextField!
@IBOutlet weak var amountText : UITextField!
@IBOutlet weak var refIdText : UITextField!
@IBOutlet weak var refText : UITextField!
@IBOutlet weak var validationSwitch : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func payButtonTapped (sender: UIButton) {
let uri = NSMutableString()
let recipientString = recipientText.text
let amountString = amountText.text
let refIdString = refIdText.text
let refString = refText.text
uri.appendFormat("%@?%@=@(%@:%@)&%@=%@",kPaymentURLiteralURLScheme,
kPaymentURLiteralRecipientID,
kPaymentURLiteralMerchant,
recipientString!,
kPaymentURLiteralAmount,
amountString!)
if (!(refIdString?.isEmpty)!) {
uri.appendFormat("&%@=%@",kPaymentURLiteralReferenceID, refIdString!)
}
if (refString?.isEmpty)! {
uri.appendFormat("&%@=%@",kPaymentURLiteralReferenceText, refString!)
}
if(validationSwitch.isOn){
uri.appendFormat("&%@=true", kPaymentURLiteralNeedsUserValidation)
}
uri.append("&url=unipagosint://") //callback URL
print(uri)
if let anURL = URL(string: uri as String) {
print(anURL);
UIApplication.shared.openURL(anURL)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.tag == 4 {
textField.resignFirstResponder()
} else {
let txtField : UITextField? = self.view.viewWithTag(textField.tag + 1) as? UITextField
txtField?.becomeFirstResponder()
}
textField.resignFirstResponder()
return false;
}
}
| 216fec20cb3a6c886fc98ca50b649392 | 30.842697 | 98 | 0.622795 | false | false | false | false |
Ataraxiis/MGW-Esport | refs/heads/master | Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxTests/Event+Equatable.swift | apache-2.0 | 11 | //
// Event+Equatable.swift
// Rx
//
// Created by Krunoslav Zaher on 12/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
/**
Compares two events. They are equal if they are both the same member of `Event` enumeration.
In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code)
and their string representations are equal.
*/
public func == <Element: Equatable>(lhs: Event<Element>, rhs: Event<Element>) -> Bool {
switch (lhs, rhs) {
case (.Completed, .Completed): return true
case (.Error(let e1), .Error(let e2)):
// if the references are equal, then it's the same object
if let lhsObject = lhs as? AnyObject,
rhsObject = rhs as? AnyObject
where lhsObject === rhsObject {
return true
}
#if os(Linux)
return "\(e1)" == "\(e2)"
#else
let error1 = e1 as NSError
let error2 = e2 as NSError
return error1.domain == error2.domain
&& error1.code == error2.code
&& "\(e1)" == "\(e2)"
#endif
case (.Next(let v1), .Next(let v2)): return v1 == v2
default: return false
}
}
| db83099d42e87e8ebfb5457586e7082d | 29.404762 | 125 | 0.595928 | false | false | false | false |
MakeSchool/ConvenienceKit | refs/heads/master | Pod/Classes/NSCacheSwift.swift | mit | 2 | //
// NSCacheSwift.swift
// ConvenienceKit
//
// Created by Benjamin Encz on 6/4/15.
// Copyright (c) 2015 Benjamin Encz. All rights reserved.
//
import Foundation
public class NSCacheSwift<T: Hashable, U> {
private let cache: NSCache
public var delegate: NSCacheDelegate? {
get {
return cache.delegate
}
set {
cache.delegate = delegate
}
}
public var name: String {
get {
return cache.name
}
set {
cache.name = name
}
}
public var totalCostLimit: Int {
get {
return cache.totalCostLimit
}
set {
cache.totalCostLimit = totalCostLimit
}
}
public var countLimit: Int {
get {
return cache.countLimit
}
set {
cache.countLimit = countLimit
}
}
public var evictsObjectsWithDiscardedContent: Bool {
get {
return cache.evictsObjectsWithDiscardedContent
}
set {
cache.evictsObjectsWithDiscardedContent = evictsObjectsWithDiscardedContent
}
}
public init() {
cache = NSCache()
}
public func objectForKey(key: T) -> U? {
let key: AnyObject = replaceKeyIfNeccessary(key)
let value = cache.objectForKey(key) as? U
?? (cache.objectForKey(key) as? Container<U>)?.content
return value
}
public func setObject(obj: U, forKey key: T) {
let object: AnyObject = obj as? AnyObject ?? Container(content: obj)
let key: AnyObject = replaceKeyIfNeccessary(key)
cache.setObject(object, forKey: key)
}
public func setObject(obj: U, forKey key: T, cost g: Int) {
cache.setObject(obj as! AnyObject, forKey: key as! AnyObject, cost: g)
}
public func removeObjectForKey(key: T) {
let key: AnyObject = replaceKeyIfNeccessary(key)
cache.removeObjectForKey(key)
}
public func removeAllObjects() {
cache.removeAllObjects()
}
public subscript(key: T) -> U? {
get {
return objectForKey(key)
}
set(newValue) {
if let newValue = newValue {
setObject(newValue, forKey: key)
}
}
}
// MARK: Wrapping Value Types into Reference Type Containers
/*
NSCache can only store types that conform to AnyObject. It compares keys by object identity. To allow value types as keys, NSCacheSwift requires keys to conform to Hashable. NSCacheSwift then creates an NSObject for each unique value (as determined by equality) that acts as the key in NSCache.
*/
private var keyReplacers = [T : NSObject]()
private func replaceKeyIfNeccessary(originalKey :T) -> AnyObject {
let key: AnyObject? = originalKey as? AnyObject ?? keyReplacers[originalKey]
if let key: AnyObject = key {
return key
} else {
let container = NSObject()
keyReplacers[originalKey] = container
return container
}
}
}
private class Container<T> {
private (set) var content: T
init(content: T) {
self.content = content
}
}
| 9ff2767eaa50025dc18bb3af4441132d | 21.484848 | 304 | 0.641846 | false | false | false | false |
EvgenyKarkan/Feeds4U | refs/heads/develop | iFeed/Sources/Data/Models/Feed.swift | mit | 1 | //
// Feed.swift
// iFeed
//
// Created by Evgeny Karkan on 9/2/15.
// Copyright (c) 2015 Evgeny Karkan. All rights reserved.
//
import Foundation
import CoreData
@objc(Feed)
class Feed: NSManagedObject {
@NSManaged var rssURL: String
@NSManaged var title: String!
@NSManaged var summary: String?
@NSManaged var feedItems: NSSet
//sorted 'feedItems' by publish date
func sortedItems() -> [FeedItem] {
guard let unsortedItems: [FeedItem] = feedItems.allObjects as? [FeedItem] else {
return []
}
let sortedArray = unsortedItems.sorted(by: { (item1: FeedItem, item2: FeedItem) -> Bool in
return item1.publishDate.timeIntervalSince1970 > item2.publishDate.timeIntervalSince1970
})
return sortedArray
}
//unread 'feedItems'
func unreadItems() -> [FeedItem] {
guard let items: [FeedItem] = feedItems.allObjects as? [FeedItem] else {
return []
}
let unReadItem = items.filter({ (item: FeedItem) -> Bool in
return item.wasRead.boolValue == false
})
return unReadItem
}
}
| 8482b928f77baa1aeadd5e4d1b9bacef | 24.234043 | 100 | 0.602024 | false | false | false | false |
ikuehne/Papaya | refs/heads/master | Sources/Graph.swift | mit | 1 | /*
This file defines graph types as protocols, as well as related errors.
*/
/**
Errors related to the `Graph` protocol.
- `.VertexAlreadyPresent`: Error due to a vertex already being in the graph.
- `.VertexNotPresent`: Error due to a vertex not being in the graph.
- `.EdgeNotPresent`: Error due to an edge not being in the graph.
*/
public enum GraphError: ErrorType {
case VertexAlreadyPresent
case VertexNotPresent
case EdgeNotPresent
}
/**
Description of abstract graph type.
Provides a generic set of graph operations, without assuming a weighting on
the graph.
*/
public protocol Graph {
/**
Type representing vertices.
All instances of this type in the graph should be unique, so that
∀ v ∈ `vertices`, (v, v') ∈ `edges` & v'' = v ⟹ (v'', v') ∈ `edges`. That
is, all edges and vertices should be unique.
*/
typealias Vertex
/**
Initializes an empty graph.
*/
init()
/**
Initializes a graph with the given vertices and no edges.
A *default implementation* using the empty initializer and `addVertex` is
provided.
- parameter vertices: A collection of vertices to include initially.
*/
//init<V: CollectionType where V.Generator.Element == Vertex> (vertices: V)
// Maybe shouldn't be required?
// Default implementation may be good enough without requiring adopters
// of the protocol to provide their own?
/**
Initializes a graph with the same vertices and edges as the given graph.
A *default implementation* using the empty initializer, `addVertex`, and
`addEdge` is provided.
- parameter graph: The graph to copy.
*/
//init<G: Graph where G.Vertex == Vertex>(graph: G)
/**
An array of all the vertices in the graph.
*/
var vertices: [Vertex] { get }
/**
An array of all the edges in the graph, represented as tuples of vertices.
*/
var edges: [(Vertex, Vertex)] { get }
/**
Returns whether there is an edge from one vertex to another in the graph.
- parameter from: The vertex to check from.
- parameter to: The destination vertex.
- returns: `true` if the edge exists; `false` otherwise.
- throws: `GraphError.VertexNotPresent` if either vertex is not in the
graph.
*/
func edgeExists(from: Vertex, to: Vertex) throws -> Bool
/**
Creates an array of all vertices reachable from a vertex.
A *default implementation* using `vertices` and `edgeExists` is provided.
It works in O(V) time.
- parameter vertex: The vertex whose neighbors to retrieve.
- returns: An array of all vertices with edges from `vertex` to them, in no
particular order, and not including `vertex` unless there is a loop.
- throws: `GraphError.VertexNotPresent` if `vertex` is not in the graph.
*/
func neighbors(vertex: Vertex) throws -> [Vertex]
/**
Adds a new vertex to the graph with no edges connected to it.
Changes the graph in-place to add the vertex.
- parameter vertex: The vertex to add.
- throws: `GraphError.VertexAlreadyPresent` if `vertex` is already in the
graph.
*/
mutating func addVertex(vertex: Vertex) throws
/**
Adds a new edge to the graph from one vertex to another.
Changes the graph in-place to add the edge.
- parameter from: The vertex to start the edge from.
- parameter to: The vertex the edge ends on.
- throws: `GraphError.VertexNotPresent` if either vertex is not in the
graph.
*/
mutating func addEdge(from: Vertex, to: Vertex) throws
/**
Removes a vertex and all edges connected to it.
- parameter vertex: The vertex to remove.
- throws: `GraphError.VertexNotPresent` if the vertex to be deleted is not
in the graph.
*/
mutating func removeVertex(vertex: Vertex) throws
/**
Removes an edge from one vertex to another.
- parameter from: The 'source' of the edge.
- parameter to: The 'destination' of the edge.
- throws: `GraphError.EdgeNotPresent` if the edge to be removed is not in
the graph.
*/
mutating func removeEdge(from: Vertex, to: Vertex) throws
}
/**
Description of an undirected graph.
This protocol is identical to Graph and DirectedGraph, but new types should
implement this protocol if the `edgeExists` function is reflexive, i.e. if the
edges have no associated direction.
*/
public protocol UndirectedGraph: Graph { }
/**
Description of a directed graph.
This protocol is identical to Graph and UndirectedGraph, but new types should
implement this protocol with the `edgeExists` function not reflexive, i.e. if
the edges have an associated direction.
*/
public protocol DirectedGraph: Graph { }
/**
Description of a weighted graph.
Weighted graphs have a weight associated with each edge.
*/
public protocol WeightedGraph: Graph {
/**
Computes the weight associated with the given edge.
- parameter to: The 'source' of the edge to use.
- parameter from: The 'destination' of the edge to use.
- returns: The weight associated with the given edge, or `nil` if the edge
is not in the graph.
- throws: `GraphError.VertexNotPresent` if either vertex is not in the
graph.
*/
func weight(from: Vertex, to: Vertex) throws -> Double?
/**
Adds a new weighted edge to the graph from one vertex to another.
Changes the graph in-place to add the edge.
- parameter from: The 'source' of the edge to use.
- parameter to: The 'destination' of the edge to use.
- parameter weight: The 'weight' of the new edge to add.
- throws: `GraphError.VertexNotPresent` if either vertex in the edge
does not exist in the graph.
*/
mutating func addEdge(from: Vertex, to: Vertex, weight: Double) throws
}
/**
A weighted undirected graph protocol.
This protocol is identical to a weighted graph, but it requires that the
implementation of `edgeExists` be symmetric, i.e. edges go both ways.
*/
public protocol WeightedUndirectedGraph : WeightedGraph {}
/**
A weighted directed graph protocol.
This protocol is idential to a weighted graph, but it requires that the
implementation of `edgeExists` not be symmetric, i.e. edges go in only one
direction
*/
public protocol WeightedDirectedGraph : WeightedGraph {}
// Provides a default implementation for the `neighbors` function.
public extension Graph {
public init<V: CollectionType
where V.Generator.Element == Vertex> (vertices: V) {
self = Self()
for vertex in vertices {
let _ = try? addVertex(vertex)
// I believe this is a no-op if it throws.
}
}
public init<G: Graph where G.Vertex == Vertex>(graph: G) {
self = Self(vertices: graph.vertices)
for (from, to) in graph.edges {
// For a properly implemented graph, the edges are all unique and
// this will never throw.
try! addEdge(from, to: to)
}
}
public func neighbors(vertex: Vertex) throws -> [Vertex] {
var neighbors: [Vertex] = []
for vertex2 in vertices {
if try edgeExists(vertex, to: vertex2) {
neighbors.append(vertex)
}
}
return neighbors
}
}
/**
Gives the total weight of all edges in the graph. Useful for minimum
spanning trees and setting an effectively infinite weight value in some
graph algorithms.
A default implementaion using the edges property and weight method is
provided here.
- returns: the sum of all of the edge weights in the graph, a Double.
*/
public extension WeightedGraph {
public var totalWeight: Double {
var result = 0.0
for (from, to) in edges {
result += try! weight(from, to: to)!
}
return result
}
}
| 24493250d84c3eabedfd3bd3a6192931 | 28.313653 | 80 | 0.664527 | false | false | false | false |
masteranca/Flow | refs/heads/master | Flow/Request.swift | mit | 1 | //
// Created by Anders Carlsson on 14/01/16.
// Copyright (c) 2016 CoreDev. All rights reserved.
//
import Foundation
public final class Request {
private let task: NSURLSessionTask
public var isRunning: Bool {
return task.state == NSURLSessionTaskState.Running
}
public var isFinished: Bool {
return task.state == NSURLSessionTaskState.Completed
}
public var isCanceling: Bool {
return task.state == NSURLSessionTaskState.Canceling
}
init(task: NSURLSessionTask) {
self.task = task
}
public func cancel() -> Request {
task.cancel()
return self
}
} | fb214385d1a16c0a331ccbb5ee853a44 | 19.3125 | 60 | 0.645609 | false | false | false | false |
adrianomazucato/CoreStore | refs/heads/master | CoreStore/Migrating/MigrationChain.swift | mit | 4 | //
// MigrationChain.swift
// CoreStore
//
// Copyright (c) 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - MigrationChain
/**
A `MigrationChain` indicates the sequence of model versions to be used as the order for incremental migration. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants.
Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable incremental migrations:
let dataStack = DataStack(migrationChain: nil)
This means that the mapping model will be computed from the store's version straight to the `DataStack`'s model version.
To support incremental migrations, specify the linear order of versions:
let dataStack = DataStack(migrationChain:
["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"])
or for more complex migration paths, a version tree that maps the key-values to the source-destination versions:
let dataStack = DataStack(migrationChain: [
"MyAppModel": "MyAppModelV3",
"MyAppModelV2": "MyAppModelV4",
"MyAppModelV3": "MyAppModelV4"
])
This allows for different migration paths depending on the starting version. The example above resolves to the following paths:
- MyAppModel-MyAppModelV3-MyAppModelV4
- MyAppModelV2-MyAppModelV4
- MyAppModelV3-MyAppModelV4
The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met:
- a version appears twice in an array
- a version appears twice as a key in a dictionary literal
- a loop is found in any of the paths
*/
public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible {
// MARK: NilLiteralConvertible
public init(nilLiteral: ()) {
self.versionTree = [:]
self.rootVersions = []
self.leafVersions = []
self.valid = true
}
// MARK: StringLiteralConvertible
public init(stringLiteral value: String) {
self.versionTree = [:]
self.rootVersions = [value]
self.leafVersions = [value]
self.valid = true
}
// MARK: ExtendedGraphemeClusterLiteralConvertible
public init(extendedGraphemeClusterLiteral value: String) {
self.versionTree = [:]
self.rootVersions = [value]
self.leafVersions = [value]
self.valid = true
}
// MARK: UnicodeScalarLiteralConvertible
public init(unicodeScalarLiteral value: String) {
self.versionTree = [:]
self.rootVersions = [value]
self.leafVersions = [value]
self.valid = true
}
// MARK: DictionaryLiteralConvertible
public init(dictionaryLiteral elements: (String, String)...) {
var valid = true
let versionTree = elements.reduce([String: String]()) { (var versionTree, tuple: (String, String)) -> [String: String] in
if let _ = versionTree.updateValue(tuple.1, forKey: tuple.0) {
CoreStore.assert(false, "\(typeName(MigrationChain))'s migration chain could not be created due to ambiguous version paths.")
valid = false
}
return versionTree
}
let leafVersions = Set(
elements.filter { (tuple: (String, String)) -> Bool in
return versionTree[tuple.1] == nil
}.map { $1 }
)
let isVersionAmbiguous = { (start: String) -> Bool in
var checklist: Set<String> = [start]
var version = start
while let nextVersion = versionTree[version] where nextVersion != version {
if checklist.contains(nextVersion) {
CoreStore.assert(false, "\(typeName(MigrationChain))'s migration chain could not be created due to looping version paths.")
return true
}
checklist.insert(nextVersion)
version = nextVersion
}
return false
}
self.versionTree = versionTree
self.rootVersions = Set(versionTree.keys).subtract(versionTree.values)
self.leafVersions = leafVersions
self.valid = valid && Set(versionTree.keys).union(versionTree.values).filter { isVersionAmbiguous($0) }.count <= 0
}
// MARK: ArrayLiteralConvertible
public init(arrayLiteral elements: String...) {
CoreStore.assert(Set(elements).count == elements.count, "\(typeName(MigrationChain))'s migration chain could not be created due to duplicate version strings.")
var lastVersion: String?
var versionTree = [String: String]()
var valid = true
for version in elements {
if let lastVersion = lastVersion,
let _ = versionTree.updateValue(version, forKey: lastVersion) {
valid = false
}
lastVersion = version
}
self.versionTree = versionTree
self.rootVersions = Set([elements.first].flatMap { $0 == nil ? [] : [$0!] })
self.leafVersions = Set([elements.last].flatMap { $0 == nil ? [] : [$0!] })
self.valid = valid
}
// MARK: Internal
internal let rootVersions: Set<String>
internal let leafVersions: Set<String>
internal let valid: Bool
internal var empty: Bool {
return self.versionTree.count <= 0
}
internal func contains(version: String) -> Bool {
return self.rootVersions.contains(version)
|| self.leafVersions.contains(version)
|| self.versionTree[version] != nil
}
internal func nextVersionFrom(version: String) -> String? {
guard let nextVersion = self.versionTree[version] where nextVersion != version else {
return nil
}
return nextVersion
}
// MARK: Private
private let versionTree: [String: String]
}
// MARK: - MigrationChain: CustomDebugStringConvertible
extension MigrationChain: CustomDebugStringConvertible {
public var debugDescription: String {
guard self.valid else {
return "<invalid migration chain>"
}
var paths = [String]()
for var version in self.rootVersions {
var steps = [version]
while let nextVersion = self.nextVersionFrom(version) {
steps.append(nextVersion)
version = nextVersion
}
paths.append(steps.joinWithSeparator(" → "))
}
return "[" + paths.joinWithSeparator("], [") + "]"
}
}
| 23c9ff54c9ac8127a929fe0b72c3be3a | 33.308642 | 270 | 0.617728 | false | false | false | false |
JakobR/XML.swift | refs/heads/master | XML/XPath.swift | mit | 1 | import libxml2
/// Represents a compiled XPath expression
public class XPath {
private let ptr: xmlXPathCompExprPtr
public init(_ expression: String, namespaces: [String:String] = [:]) throws {
// TODO: Namespaces, variables, custom functions
// (when adding this, we should probably re-use the XPathContext. (which makes this object very thread-unsafe, but then again, how thread-safe is the rest of this wrapper?))
// Solution for thread-unsafety:
// Provide a "copy" method that copies the context. (the xmlXPathCompExpr should be able to be shared between different threads?)
// This way the compilation only has to happen once even if someone needs multiple objects for different threads.
// (Every thread can make a copy from the previously prepared "master" XPath object.)
assert(namespaces.count == 0, "XPath.evaluateOn: Namespace mappings not yet implemented")
let context: XPathContext
do { context = try XPathContext() } catch let e { ptr = nil; throw e } // If only we could throw errors without initializing all properties first…
ptr = xmlXPathCtxtCompile(context.ptr, expression)
guard ptr != nil else {
throw context.grabAndResetError() ?? XPathError(xmlError: nil)
}
}
deinit {
xmlXPathFreeCompExpr(ptr);
}
/// Evaluates the XPath query with the given node as context node.
public func evaluateOn(node: Node) throws -> XPathResult {
let context = try XPathContext(node: node)
let obj = xmlXPathCompiledEval(ptr, context.ptr)
guard obj != nil else {
throw context.grabAndResetError() ?? XPathError(xmlError: nil)
}
return XPathResult(ptr: obj, onNode: node)
}
/// Evaluates the XPath query with the given document's root node as context node.
public func evaluateOn(doc: Document) throws -> XPathResult {
return try evaluateOn(doc.root)
}
}
private class XPathContext {
private let ptr: xmlXPathContextPtr
private var error: XPathError? = nil
private init(_doc: xmlDocPtr) throws {
ptr = xmlXPathNewContext(_doc);
guard ptr != nil else { throw Error.MemoryError }
assert(ptr.memory.doc == _doc);
// Set up error handling
ptr.memory.userData = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque())
ptr.memory.error = { (userData, error: xmlErrorPtr) in
assert(userData != nil)
let context = Unmanaged<XPathContext>.fromOpaque(COpaquePointer(userData)).takeUnretainedValue()
context.error = XPathError(xmlError: error, previous: context.error)
}
}
/// Create an XPathContext with a NULL document.
convenience init() throws {
try self.init(_doc: nil);
}
convenience init(node: Node) throws {
try self.init(_doc: node.doc.ptr)
ptr.memory.node = node.ptr
}
deinit {
xmlXPathFreeContext(ptr);
}
func grabAndResetError() -> XPathError? {
defer { error = nil }
return error
}
}
| ec6b59f60cfade45c2be7194fd1a46dd | 37.716049 | 181 | 0.655293 | false | false | false | false |
LeeMZC/MZCWB | refs/heads/master | MZCWB/MZCWB/Classes/Home-首页/Mode/MZCTimeDelegate.swift | artistic-2.0 | 1 | //
// MZCTimeDelegate.swift
// MZCWB
//
// Created by 马纵驰 on 16/7/30.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import Foundation
protocol MZCTimeDelegate {
func handleRequest(time : NSDate) -> String
}
class MZCBaseTimer : MZCTimeDelegate {
var formatterStr = "HH:mm"
let calendar = NSCalendar.currentCalendar()
private func timeString(dateFormat : String , date : NSDate) -> String {
// 昨天
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en")
formatterStr = dateFormat + formatterStr
formatter.dateFormat = formatterStr
return formatter.stringFromDate(date)
}
var nextSuccessor: MZCTimeDelegate?
func handleRequest(time : NSDate) -> String{
guard let t_nextSuccessor = nextSuccessor else {
return "责任对象错误"
}
return t_nextSuccessor.handleRequest(time)
}
}
//MARK:- 头
class MZCTimeHead: MZCBaseTimer{
}
//MARK:- 当天 X小时前(当天)
class MZCToday: MZCBaseTimer{
override func handleRequest(time : NSDate) -> String{
let interval = Int(NSDate().timeIntervalSinceDate(time))
if !calendar.isDateInToday(time) {
return (self.nextSuccessor?.handleRequest(time))!
}
if interval < 60
{
return "刚刚"
}else if interval < 60 * 60
{
return "\(interval / 60)分钟前"
}else
{
return "\(interval / (60 * 60))小时前"
}
}
}
//MARK:- 昨天 HH:mm(昨天)
class MZCYesterday: MZCBaseTimer{
override func handleRequest(time : NSDate) -> String{
if !calendar.isDateInYesterday(time)
{
return (self.nextSuccessor?.handleRequest(time))!
}
// 昨天
return self.timeString("昨天: ", date: time)
}
}
//MARK:- MM-dd HH:mm(一年内)
class MZCYear: MZCBaseTimer{
override func handleRequest(time : NSDate) -> String{
let comps = calendar.components(NSCalendarUnit.Year, fromDate: time, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
if comps.year >= 1
{
return (self.nextSuccessor?.handleRequest(time))!
}
return self.timeString("MM-dd ", date: time)
}
}
//MARK:- yyyy-MM-dd HH:mm(更早期)
class MZCYearAgo: MZCBaseTimer{
override func handleRequest(time : NSDate) -> String{
let comps = calendar.components(NSCalendarUnit.Year, fromDate: time, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
if comps.year >= 1
{
return self.timeString("yyyy-MM-dd ", date: time)
}
return (self.nextSuccessor?.handleRequest(time))!
}
}
//MARK:- 尾
class MZCTimeEnd: MZCBaseTimer{
override func handleRequest(time : NSDate) ->String {
return "无法获取到正确的时间"
}
} | 2277524c3b17fe6904e100494b83d8b9 | 22.217054 | 136 | 0.577822 | false | false | false | false |
johnno1962e/swift-corelibs-foundation | refs/heads/master | TestFoundation/TestUtils.swift | apache-2.0 | 4 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
func ensureFiles(_ fileNames: [String]) -> Bool {
var result = true
let fm = FileManager.default
for name in fileNames {
guard !fm.fileExists(atPath: name) else {
continue
}
if name.hasSuffix("/") {
do {
try fm.createDirectory(atPath: name, withIntermediateDirectories: true, attributes: nil)
} catch let err {
print(err)
return false
}
} else {
var isDir: ObjCBool = false
let dir = NSString(string: name).deletingLastPathComponent
if !fm.fileExists(atPath: dir, isDirectory: &isDir) {
do {
try fm.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
} catch let err {
print(err)
return false
}
} else if !isDir {
return false
}
result = result && fm.createFile(atPath: name, contents: nil, attributes: nil)
}
}
return result
}
| 2d4701bf0ec6da857615e929670b56ee | 30.5 | 107 | 0.565934 | false | false | false | false |
Karumi/KataTODOApiClientIOS | refs/heads/master | KataTODOAPIClientTests/AnyPublisher+Utils.swift | apache-2.0 | 1 | import Combine
import Nimble
private extension DispatchTimeInterval {
static var defaultGetTimeout: DispatchTimeInterval { .seconds(30) }
}
extension AnyPublisher {
static var neverPublishing: Self { Future { _ in }.eraseToAnyPublisher() }
static func fail(_ failure: Failure) -> Self {
Fail(outputType: Output.self, failure: failure).eraseToAnyPublisher()
}
static func just(_ output: Output) -> Self {
Just(output).setFailureType(to: Failure.self).eraseToAnyPublisher()
}
func get(timeout: DispatchTimeInterval = .defaultGetTimeout) throws -> [Output] {
var subscriptions = Set<AnyCancellable>()
var output: [Output] = []
var error: Error?
waitUntil(timeout: timeout) { done in
self.sink(receiveCompletion: {
if case let .failure(receivedError) = $0 {
error = receivedError
}
done()
}, receiveValue: { value in
output.append(value)
}).store(in: &subscriptions)
}
if let err = error { throw err }
return output
}
}
| 0e1dee262393e09f375ac41928f6526d | 29.102564 | 85 | 0.584327 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/WordPressTest/Classes/Stores/StatsPeriodStoreTests.swift | gpl-2.0 | 2 | import WordPressKit
import XCTest
@testable import WordPress
class StatsPeriodStoreTests: XCTestCase {
private var sut: StatsPeriodStore!
override func setUp() {
super.setUp()
sut = StatsPeriodStore()
sut.statsServiceRemote = StatsServiceRemoteV2Mock(wordPressComRestApi: WordPressComRestApi(oAuthToken: nil, userAgent: nil), siteID: 123, siteTimezone: .autoupdatingCurrent)
}
override func tearDown() {
sut = nil
super.tearDown()
}
func testMarkReferrerAsSpam() {
guard
let firstURL = URL(string: "https://www.domain.com/test"),
let secondURL = URL(string: "https://www.someotherdomain.com/test") else {
XCTFail("Failed to create URLs")
return
}
let referrerOne = StatsReferrer(title: "A title", viewsCount: 0, url: firstURL, iconURL: nil, children: [])
let referrerTwo = StatsReferrer(title: "A title", viewsCount: 0, url: secondURL, iconURL: nil, children: [])
sut.state.topReferrers = .init(period: .month, periodEndDate: Date(), referrers: [referrerOne, referrerTwo], totalReferrerViewsCount: 0, otherReferrerViewsCount: 0)
sut.toggleSpamState(for: referrerOne.url?.host ?? "", currentValue: referrerOne.isSpam)
XCTAssertTrue(sut.state.topReferrers!.referrers[0].isSpam)
XCTAssertFalse(sut.state.topReferrers!.referrers[1].isSpam)
}
func testUnmarkReferrerAsSpam() {
guard
let firstURL = URL(string: "https://www.domain.com/test"),
let secondURL = URL(string: "https://www.someotherdomain.com/test") else {
XCTFail("Failed to create URLs")
return
}
var referrerOne = StatsReferrer(title: "A title", viewsCount: 0, url: firstURL, iconURL: nil, children: [])
referrerOne.isSpam = true
let referrerTwo = StatsReferrer(title: "A title", viewsCount: 0, url: secondURL, iconURL: nil, children: [])
sut.state.topReferrers = .init(period: .month, periodEndDate: Date(), referrers: [referrerOne, referrerTwo], totalReferrerViewsCount: 0, otherReferrerViewsCount: 0)
sut.toggleSpamState(for: referrerOne.url?.host ?? "", currentValue: referrerOne.isSpam)
XCTAssertFalse(sut.state.topReferrers!.referrers[0].isSpam)
XCTAssertFalse(sut.state.topReferrers!.referrers[1].isSpam)
}
}
private extension StatsPeriodStoreTests {
class StatsServiceRemoteV2Mock: StatsServiceRemoteV2 {
override func toggleSpamState(for referrerDomain: String, currentValue: Bool, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
success()
}
}
}
| cc37ec55cbc294babd29d03c64d33b0e | 42.370968 | 181 | 0.670509 | false | true | false | false |
fuku2014/swift-simple-matt-chat | refs/heads/master | MqttChat/src/HomeViewController.swift | mit | 1 | import UIKit
import SpriteKit
class HomeViewController: UIViewController, UITextFieldDelegate {
private var roomTextField : UITextField!
private var nameTextField : UITextField!
private var submitButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.setComponents()
}
func setComponents() {
self.title = "Home"
self.view.backgroundColor = UIColor.whiteColor()
// RoomID
roomTextField = UITextField(frame: CGRectMake(0,0,self.view.frame.size.width,30))
roomTextField.delegate = self
roomTextField.borderStyle = UITextBorderStyle.RoundedRect
roomTextField.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2)
roomTextField.returnKeyType = UIReturnKeyType.Done
roomTextField.keyboardType = UIKeyboardType.Default
roomTextField.placeholder = "Input Room Name"
self.view.addSubview(roomTextField)
// Name
nameTextField = UITextField(frame: CGRectMake(0,0,self.view.frame.size.width,30))
nameTextField.delegate = self
nameTextField.borderStyle = UITextBorderStyle.RoundedRect
nameTextField.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2 - 50)
nameTextField.returnKeyType = UIReturnKeyType.Done
nameTextField.keyboardType = UIKeyboardType.Default
nameTextField.placeholder = "Input Your Name"
self.view.addSubview(nameTextField)
// Button
submitButton = UIButton(type: UIButtonType.Custom)
submitButton.frame = CGRectMake(0, 0, 150, 40)
submitButton.layer.masksToBounds = true
submitButton.backgroundColor = UIColor.blueColor()
submitButton.layer.cornerRadius = 20.0
submitButton.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2 + 50)
submitButton.setTitle("Enter", forState: UIControlState.Normal)
submitButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
submitButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
submitButton.addTarget(self, action: "doEnter:", forControlEvents: UIControlEvents.TouchUpInside)
submitButton.enabled = false
self.view.addSubview(submitButton)
}
func doEnter(sender: UIButton) {
let chatViewController = ChatViewController()
chatViewController.roomName = self.roomTextField.text!
chatViewController.userName = self.nameTextField.text!
self.navigationController?.pushViewController(chatViewController, animated: true)
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// UITextFieldDelegate
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
submitButton.enabled = !roomTextField.text!.isEmpty && !nameTextField.text!.isEmpty
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 6ca0931f6e9e7ceba5fe6732765ebaf0 | 42.986667 | 116 | 0.668687 | false | false | false | false |
lysongzi/iOS-Demon | refs/heads/master | Swift/SwiftDemon/SwiftDemon/Shape.swift | mit | 1 | //
// myClass.swift
// SwiftDemon
//
// Created by lysongzi on 16/1/29.
// Copyright © 2016年 lysongzi. All rights reserved.
//
import Foundation
class Shape
{
var height : Double = 0.0
var width : Double = 0.0
var area : Double{
get
{
return height * width
}
set
{
self.area = height * width
}
}
init(h: Double, w :Double)
{
self.height = h
self.width = w
}
func Description() -> String
{
return "Height = \(self.height), Width = \(self.width)"
}
} | f30a65389646aa193e6067d7d385e20a | 15.184211 | 63 | 0.480456 | false | false | false | false |
wayfair/brickkit-ios | refs/heads/master | Example/Source/Examples/Sticking/StackedStickingViewController.swift | apache-2.0 | 1 | //
// StackedStickingViewController.swift
// BrickKit
//
// Created by Ruben Cagnie on 6/1/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
class StackedStickingViewController: BaseRepeatBrickViewController, HasTitle {
class var brickTitle: String {
return "Stacked Headers"
}
class var subTitle: String {
return "Example how headers stack while scrolling"
}
override func viewDidLoad() {
super.viewDidLoad()
repeatLabel.width = .ratio(ratio: 1)
titleLabelModel.text = "All uneven bricks should stick"
behavior = StickyLayoutBehavior(dataSource: self)
}
}
extension StackedStickingViewController: StickyLayoutBehaviorDataSource {
func stickyLayoutBehavior(_ stickyLayoutBehavior: StickyLayoutBehavior, shouldStickItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool {
return identifier != BrickIdentifiers.titleLabel && indexPath.row % 2 != 0
}
}
| b008d4739a7f3c0eaadc451ace342eeb | 30.852941 | 238 | 0.734072 | false | false | false | false |
arikis/Overdrive | refs/heads/master | Tests/OverdriveTests/DependencyTests.swift | mit | 1 | //
// DependencyTests.swift
// Overdrive
//
// Created by Said Sikira on 6/23/16.
// Copyright © 2016 Said Sikira. All rights reserved.
//
import XCTest
@testable import Overdrive
class DependencyTests: TestCase {
/// Test `addDependency(_:)` method
func testDependencyAdd() {
let testTask = Task<Int>()
let dependencyTask = Task<String>()
testTask.add(dependency: dependencyTask)
XCTAssertEqual(testTask.dependencies.count, 1)
}
/// Tests `getDependency(_:)` method
func testGetDependency() {
let testTask = Task<Int>()
let dependencyTask = Task<String>()
dependencyTask.name = "DependencyTask"
testTask.add(dependency: dependencyTask)
let dependencies = testTask.get(dependency: type(of: dependencyTask))
XCTAssertEqual(dependencies[0].name, "DependencyTask")
}
func testRemoveValidDependency() {
let task = Task<Int>()
let dependency = Task<String>()
task.add(dependency: dependency)
let status = task.remove(dependency: dependency)
XCTAssertEqual(status, true)
XCTAssertEqual(task.dependencies.count, 0)
}
func testRemoveDependencyWithType() {
let task = Task<Int>()
let dependency = Task<String>()
task.add(dependency: dependency)
task.remove(dependency: type(of: dependency))
// XCTAssertEqual(status, true)
XCTAssertEqual(task.dependencies.count, 0)
}
func testRemoveUnknownDependencyWithType() {
let task = Task<Int>()
let dependency = Task<String>()
task.add(dependency: dependency)
task.remove(dependency: Task<Double>.self)
XCTAssertEqual(task.dependencies.count, 1)
}
func testOrderOfExecution() {
let testExpecation = expectation(description: "Dependency order of execution test expectation")
var results: [Result<Int>] = []
func add(result: Result<Int>) {
dispatchQueue.sync {
results.append(result)
}
}
let firstTask = anyTask(withResult: .value(1))
let secondTask = anyTask(withResult: .value(2))
let thirdTask = anyTask(withResult: .value(3))
thirdTask.add(dependency: secondTask)
secondTask.add(dependency: firstTask)
firstTask.onValue { add(result: .value($0)) }
secondTask.onValue { add(result: .value($0)) }
thirdTask.onValue {
add(result: .value($0))
testExpecation.fulfill()
XCTAssertEqual(results[0].value, 1)
XCTAssertEqual(results[1].value, 2)
XCTAssertEqual(results[2].value, 3)
}
let queue = TaskQueue(qos: .utility)
queue.add(task: thirdTask)
queue.add(task: secondTask)
queue.add(task: firstTask)
waitForExpectations(timeout: 1, handler: nil)
}
}
| ee4dfc890eec424397b3f7ff3802da52 | 27.472727 | 103 | 0.579502 | false | true | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/Stores/StatsWidgetsStore.swift | gpl-2.0 | 1 | import WidgetKit
import WordPressAuthenticator
class StatsWidgetsStore {
private let blogService: BlogService
init(blogService: BlogService = BlogService(managedObjectContext: ContextManager.shared.mainContext)) {
self.blogService = blogService
observeAccountChangesForWidgets()
observeAccountSignInForWidgets()
observeApplicationLaunched()
}
/// Refreshes the site list used to configure the widgets when sites are added or deleted
@objc func refreshStatsWidgetsSiteList() {
initializeStatsWidgetsIfNeeded()
if let newTodayData = refreshStats(type: HomeWidgetTodayData.self) {
HomeWidgetTodayData.write(items: newTodayData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind)
}
}
if let newAllTimeData = refreshStats(type: HomeWidgetAllTimeData.self) {
HomeWidgetAllTimeData.write(items: newAllTimeData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind)
}
}
if let newThisWeekData = refreshStats(type: HomeWidgetThisWeekData.self) {
HomeWidgetThisWeekData.write(items: newThisWeekData)
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind)
}
}
}
/// Initialize the local cache for widgets, if it does not exist
func initializeStatsWidgetsIfNeeded() {
guard #available(iOS 14.0, *) else {
return
}
if HomeWidgetTodayData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetTodayData.plist")
HomeWidgetTodayData.write(items: initializeHomeWidgetData(type: HomeWidgetTodayData.self))
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind)
}
if HomeWidgetThisWeekData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetThisWeekData.plist")
HomeWidgetThisWeekData.write(items: initializeHomeWidgetData(type: HomeWidgetThisWeekData.self))
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind)
}
if HomeWidgetAllTimeData.read() == nil {
DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetAllTimeData.plist")
HomeWidgetAllTimeData.write(items: initializeHomeWidgetData(type: HomeWidgetAllTimeData.self))
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind)
}
}
/// Store stats in the widget cache
/// - Parameters:
/// - widgetType: concrete type of the widget
/// - stats: stats to be stored
func storeHomeWidgetData<T: HomeWidgetData>(widgetType: T.Type, stats: Codable) {
guard #available(iOS 14.0, *),
let siteID = SiteStatsInformation.sharedInstance.siteID else {
return
}
var homeWidgetCache = T.read() ?? initializeHomeWidgetData(type: widgetType)
guard let oldData = homeWidgetCache[siteID.intValue] else {
DDLogError("StatsWidgets: Failed to find a matching site")
return
}
guard let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else {
DDLogError("StatsWidgets: the site does not exist anymore")
// if for any reason that site does not exist anymore, remove it from the cache.
homeWidgetCache.removeValue(forKey: siteID.intValue)
T.write(items: homeWidgetCache)
return
}
var widgetKind = ""
if widgetType == HomeWidgetTodayData.self, let stats = stats as? TodayWidgetStats {
widgetKind = AppConfiguration.Widget.Stats.todayKind
homeWidgetCache[siteID.intValue] = HomeWidgetTodayData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
} else if widgetType == HomeWidgetAllTimeData.self, let stats = stats as? AllTimeWidgetStats {
widgetKind = AppConfiguration.Widget.Stats.allTimeKind
homeWidgetCache[siteID.intValue] = HomeWidgetAllTimeData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
} else if widgetType == HomeWidgetThisWeekData.self, let stats = stats as? ThisWeekWidgetStats {
homeWidgetCache[siteID.intValue] = HomeWidgetThisWeekData(siteID: siteID.intValue,
siteName: blog.title ?? oldData.siteName,
url: blog.url ?? oldData.url,
timeZone: blog.timeZone,
date: Date(),
stats: stats) as? T
}
T.write(items: homeWidgetCache)
WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)
}
}
// MARK: - Helper methods
private extension StatsWidgetsStore {
// creates a list of days from the current date with empty stats to avoid showing an empty widget preview
var initializedWeekdays: [ThisWeekWidgetDay] {
var days = [ThisWeekWidgetDay]()
for index in 0...7 {
days.insert(ThisWeekWidgetDay(date: NSCalendar.current.date(byAdding: .day,
value: -index,
to: Date()) ?? Date(),
viewsCount: 0,
dailyChangePercent: 0),
at: index)
}
return days
}
func refreshStats<T: HomeWidgetData>(type: T.Type) -> [Int: T]? {
guard let currentData = T.read() else {
return nil
}
let updatedSiteList = (try? BlogQuery().visible(true).hostedByWPCom(true).blogs(in: blogService.managedObjectContext)) ?? []
let newData = updatedSiteList.reduce(into: [Int: T]()) { sitesList, site in
guard let blogID = site.dotComID else {
return
}
let existingSite = currentData[blogID.intValue]
let siteURL = site.url ?? existingSite?.url ?? ""
let siteName = (site.title ?? siteURL).isEmpty ? siteURL : site.title ?? siteURL
var timeZone = existingSite?.timeZone ?? TimeZone.current
if let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) {
timeZone = blog.timeZone
}
let date = existingSite?.date ?? Date()
if type == HomeWidgetTodayData.self {
let stats = (existingSite as? HomeWidgetTodayData)?.stats ?? TodayWidgetStats()
sitesList[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
} else if type == HomeWidgetAllTimeData.self {
let stats = (existingSite as? HomeWidgetAllTimeData)?.stats ?? AllTimeWidgetStats()
sitesList[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
} else if type == HomeWidgetThisWeekData.self {
let stats = (existingSite as? HomeWidgetThisWeekData)?.stats ?? ThisWeekWidgetStats(days: initializedWeekdays)
sitesList[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue,
siteName: siteName,
url: siteURL,
timeZone: timeZone,
date: date,
stats: stats) as? T
}
}
return newData
}
func initializeHomeWidgetData<T: HomeWidgetData>(type: T.Type) -> [Int: T] {
let blogs = (try? BlogQuery().visible(true).hostedByWPCom(true).blogs(in: blogService.managedObjectContext)) ?? []
return blogs.reduce(into: [Int: T]()) { result, element in
if let blogID = element.dotComID,
let url = element.url,
let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) {
// set the title to the site title, if it's not nil and not empty; otherwise use the site url
let title = (element.title ?? url).isEmpty ? url : element.title ?? url
let timeZone = blog.timeZone
if type == HomeWidgetTodayData.self {
result[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: TodayWidgetStats()) as? T
} else if type == HomeWidgetAllTimeData.self {
result[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: AllTimeWidgetStats()) as? T
} else if type == HomeWidgetThisWeekData.self {
result[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue,
siteName: title,
url: url,
timeZone: timeZone,
date: Date(timeIntervalSinceReferenceDate: 0),
stats: ThisWeekWidgetStats(days: initializedWeekdays)) as? T
}
}
}
}
}
// MARK: - Extract this week data
extension StatsWidgetsStore {
func updateThisWeekHomeWidget(summary: StatsSummaryTimeIntervalData?) {
guard #available(iOS 14.0, *) else {
return
}
switch summary?.period {
case .day:
guard summary?.periodEndDate == StatsDataHelper.currentDateForSite().normalizedDate() else {
return
}
let summaryData = Array(summary?.summaryData.reversed().prefix(ThisWeekWidgetStats.maxDaysToDisplay + 1) ?? [])
let stats = ThisWeekWidgetStats(days: ThisWeekWidgetStats.daysFrom(summaryData: summaryData))
StoreContainer.shared.statsWidgets.storeHomeWidgetData(widgetType: HomeWidgetThisWeekData.self, stats: stats)
case .week:
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind)
default:
break
}
}
}
// MARK: - Login/Logout notifications
private extension StatsWidgetsStore {
/// Observes WPAccountDefaultWordPressComAccountChanged notification and reloads widget data based on the state of account.
/// The site data is not yet loaded after this notification and widget data cannot be cached for newly signed in account.
func observeAccountChangesForWidgets() {
guard #available(iOS 14.0, *) else {
return
}
NotificationCenter.default.addObserver(forName: .WPAccountDefaultWordPressComAccountChanged,
object: nil,
queue: nil) { notification in
UserDefaults(suiteName: WPAppGroupName)?.setValue(AccountHelper.isLoggedIn, forKey: AppConfiguration.Widget.Stats.userDefaultsLoggedInKey)
if !AccountHelper.isLoggedIn {
HomeWidgetTodayData.delete()
HomeWidgetThisWeekData.delete()
HomeWidgetAllTimeData.delete()
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind)
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind)
WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind)
}
}
}
/// Observes WPSigninDidFinishNotification notification and initializes the widget.
/// The site data is loaded after this notification and widget data can be cached.
func observeAccountSignInForWidgets() {
guard #available(iOS 14.0, *) else {
return
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: WordPressAuthenticator.WPSigninDidFinishNotification),
object: nil,
queue: nil) { [weak self] _ in
self?.initializeStatsWidgetsIfNeeded()
}
}
/// Observes applicationLaunchCompleted notification and runs migration.
func observeApplicationLaunched() {
guard #available(iOS 14.0, *) else {
return
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.applicationLaunchCompleted,
object: nil,
queue: nil) { [weak self] _ in
self?.handleJetpackWidgetsMigration()
}
}
}
private extension StatsWidgetsStore {
/// Handles migration to a Jetpack app version that started supporting Stats widgets.
/// The required flags in shared UserDefaults are set and widgets are initialized.
func handleJetpackWidgetsMigration() {
// If user is logged in but defaultSiteIdKey is not set
guard let account = try? WPAccount.lookupDefaultWordPressComAccount(in: blogService.managedObjectContext),
let siteId = account.defaultBlog?.dotComID,
let userDefaults = UserDefaults(suiteName: WPAppGroupName),
userDefaults.value(forKey: AppConfiguration.Widget.Stats.userDefaultsSiteIdKey) == nil else {
return
}
userDefaults.setValue(AccountHelper.isLoggedIn, forKey: AppConfiguration.Widget.Stats.userDefaultsLoggedInKey)
userDefaults.setValue(siteId, forKey: AppConfiguration.Widget.Stats.userDefaultsSiteIdKey)
initializeStatsWidgetsIfNeeded()
}
}
extension StatsViewController {
@objc func initializeStatsWidgetsIfNeeded() {
StoreContainer.shared.statsWidgets.initializeStatsWidgetsIfNeeded()
}
}
extension BlogListViewController {
@objc func refreshStatsWidgetsSiteList() {
StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList()
}
}
| 9a98d5f20078b6b7a0ff4ab2276f49da | 48.05949 | 150 | 0.533433 | false | false | false | false |
Shvier/Dota2Helper | refs/heads/master | Dota2Helper/Dota2Helper/Main/Setting/View/DHSDKTableViewCell.swift | apache-2.0 | 1 | //
// DHSDKTableViewCell.swift
// Dota2Helper
//
// Created by Shvier on 10/20/16.
// Copyright © 2016 Shvier. All rights reserved.
//
import UIKit
class DHSDKTableViewCell: DHBaseTableViewCell {
let kSDKNameLabelFontSize: CGFloat = 15
let kSDKNameLabelOffsetTop: CGFloat = 5
let kSDKNameLabelOffsetLeft: CGFloat = 12
let kAuthorNameLabelFontSize: CGFloat = 12
let kAuthorNameLabelOffsetTop: CGFloat = 5
var sdkNameLabel: UILabel!
var authorNameLabel: UILabel!
// MARK: - Life Cycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initUI()
self.makeConstraints()
}
func initUI() {
self.accessoryType = .disclosureIndicator
sdkNameLabel = ({
let label = UILabel()
label.font = UIFont.systemFont(ofSize: kSDKNameLabelFontSize)
label.textAlignment = .left
label.preferredMaxLayoutWidth = kScreenWidth
label.text = "(null)"
return label
}())
contentView.addSubview(sdkNameLabel)
authorNameLabel = ({
let label = UILabel()
label.font = UIFont.systemFont(ofSize: kAuthorNameLabelFontSize)
label.textAlignment = .left
label.preferredMaxLayoutWidth = kScreenWidth
label.textColor = .gray
label.text = "(null)"
return label
}())
contentView.addSubview(authorNameLabel)
}
func makeConstraints() {
sdkNameLabel.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(kSDKNameLabelOffsetLeft)
make.top.equalTo(contentView).offset(kSDKNameLabelOffsetTop)
}
authorNameLabel.snp.makeConstraints { (make) in
make.left.equalTo(sdkNameLabel)
make.top.equalTo(sdkNameLabel.snp.lastBaseline).offset(kAuthorNameLabelOffsetTop)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 0bac0c5f561fba4e6d8789057ee32f67 | 28.961538 | 93 | 0.627728 | false | false | false | false |
JohnnyIsHereNow/POCA | refs/heads/master | poca/FirstApp/FirstApp/RetrieveUserWithId.swift | gpl-2.0 | 1 | //
// RetrieveUserWithId.swift
// POCA
//
// Created by Alexandru Draghi on 10/06/16.
// Copyright © 2016 Alex. All rights reserved.
//
import UIKit
class RetrieveUserWithId: UIViewController {
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.
}
public func retriveUser(userID:Int) -> User
{
let user = User()
var newString = ""
do {
let post:NSString = "userID=\(userID)"
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string:"http://angelicapp.com/POCA/jsonGetUserById.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do
{
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
}
catch let error as NSError
{
reponseError = error
urlData = nil
}
if ( urlData != nil )
{
let res = response as! NSHTTPURLResponse!;
//NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
newString = responseData.substringFromIndex(0)
let newStringArr = newString.componentsSeparatedByString("+")
print(newStringArr)
if newStringArr.count != 0
{
user.Name = newStringArr[0]
user.Email = newStringArr[1]
user.Username = newStringArr[2]
user.passion1 = Int(newStringArr[4]) as Int!
user.passion2 = Int(newStringArr[5]) as Int!
user.passion3 = Int(newStringArr[6]) as Int!
}
}
else
{
let alertView:UIAlertView = UIAlertView()
alertView.title = "Update Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
else
{
let alertView:UIAlertView = UIAlertView()
alertView.title = "Update Failed!"
alertView.message = "Connection Failure"
if let error = reponseError
{
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
return user;
}
}
| 204342cbb1890fd37132ce0306fb2061 | 35.236364 | 106 | 0.508028 | false | false | false | false |
Cloudage/XWebView | refs/heads/master | XWebView/XWVLogging.swift | apache-2.0 | 1 | /*
Copyright 2015 XWebView
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 Darwin
public typealias asl_object_t = COpaquePointer
@_silgen_name("asl_open") func asl_open(ident: UnsafePointer<Int8>, _ facility: UnsafePointer<Int8>, _ opts: UInt32) -> asl_object_t;
@_silgen_name("asl_close") func asl_close(obj: asl_object_t);
@_silgen_name("asl_vlog") func asl_vlog(obj: asl_object_t, _ msg: asl_object_t, _ level: Int32, _ format: UnsafePointer<Int8>, _ ap: CVaListPointer) -> Int32;
@_silgen_name("asl_add_output_file") func asl_add_output_file(client: asl_object_t, _ descriptor: Int32, _ msg_fmt: UnsafePointer<Int8>, _ time_fmt: UnsafePointer<Int8>, _ filter: Int32, _ text_encoding: Int32) -> Int32;
@_silgen_name("asl_set_output_file_filter") func asl_set_output_file_filter(asl: asl_object_t, _ descriptor: Int32, _ filter: Int32) -> Int32;
public class XWVLogging : XWVScripting {
public enum Level : Int32 {
case Emergency = 0
case Alert = 1
case Critical = 2
case Error = 3
case Warning = 4
case Notice = 5
case Info = 6
case Debug = 7
private static let symbols : [Character] = [
"\0", "\0", "$", "!", "?", "-", "+", " "
]
private init?(symbol: Character) {
guard symbol != "\0", let value = Level.symbols.indexOf(symbol) else {
return nil
}
self = Level(rawValue: Int32(value))!
}
}
public struct Filter : OptionSetType {
private var value: Int32
public var rawValue: Int32 {
return value
}
public init(rawValue: Int32) {
self.value = rawValue
}
public init(mask: Level) {
self.init(rawValue: 1 << mask.rawValue)
}
public init(upto: Level) {
self.init(rawValue: 1 << (upto.rawValue + 1) - 1)
}
public init(filter: Level...) {
self.init(rawValue: filter.reduce(0) { $0 | $1.rawValue })
}
}
public var filter: Filter {
didSet {
asl_set_output_file_filter(client, STDERR_FILENO, filter.rawValue)
}
}
private let client: asl_object_t
private var lock: pthread_mutex_t = pthread_mutex_t()
public init(facility: String, format: String? = nil) {
client = asl_open(nil, facility, 0)
pthread_mutex_init(&lock, nil)
#if DEBUG
filter = Filter(upto: .Debug)
#else
filter = Filter(upto: .Notice)
#endif
let format = format ?? "$((Time)(lcl)) $(Facility) <$((Level)(char))>: $(Message)"
asl_add_output_file(client, STDERR_FILENO, format, "sec", filter.rawValue, 1)
}
deinit {
asl_close(client)
pthread_mutex_destroy(&lock)
}
public func log(message: String, level: Level) {
pthread_mutex_lock(&lock)
asl_vlog(client, nil, level.rawValue, message, getVaList([]))
pthread_mutex_unlock(&lock)
}
public func log(message: String, level: Level? = nil) {
var msg = message
var lvl = level ?? .Debug
if level == nil, let ch = msg.characters.first, l = Level(symbol: ch) {
msg = msg[msg.startIndex.successor() ..< msg.endIndex]
lvl = l
}
log(msg, level: lvl)
}
@objc public func invokeDefaultMethodWithArguments(args: [AnyObject]!) -> AnyObject! {
guard args.count > 0 else { return nil }
let message = args[0] as? String ?? "\(args[0])"
var level: Level? = nil
if args.count > 1, let num = args[1] as? Int {
if 3 <= num && num <= 7 {
level = Level(rawValue: Int32(num))
} else {
level = .Debug
}
}
log(message, level: level)
return nil
}
}
private let logger = XWVLogging(facility: "org.xwebview.xwebview")
func log(message: String, level: XWVLogging.Level? = nil) {
logger.log(message, level: level)
}
@noreturn func die(@autoclosure message: ()->String, file: StaticString = #file, line: UInt = #line) {
logger.log(message(), level: .Alert)
fatalError(message, file: file, line: line)
}
| 250b289de1ff698ffbecca07479cfb69 | 34.044444 | 220 | 0.590996 | false | false | false | false |
JosephNK/SwiftyIamport | refs/heads/master | SwiftyIamportDemo/Controller/WKRemoteViewController.swift | mit | 1 | //
// WKRemoteViewController.swift
// SwiftyIamportDemo
//
// Created by JosephNK on 29/11/2018.
// Copyright © 2018 JosephNK. All rights reserved.
//
import UIKit
import SwiftyIamport
import WebKit
class WKRemoteViewController: UIViewController {
lazy var wkWebView: WKWebView = {
var view = WKWebView()
view.backgroundColor = UIColor.clear
view.navigationDelegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(wkWebView)
self.wkWebView.frame = self.view.bounds
// 결제 환경 설정
IAMPortPay.sharedInstance.configure(scheme: "iamporttest") // info.plist에 설정한 scheme
IAMPortPay.sharedInstance
.setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정
.setRedirectUrl(nil) // m_redirect_url 주소
// ISP 취소시 이벤트 (NicePay만 가능)
IAMPortPay.sharedInstance.setCancelListenerForNicePay { [weak self] in
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: "ISP 결제 취소", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
}
// 결제 웹페이지(Remote) 호출
if let url = URL(string: "http://www.iamport.kr/demo") {
let request = URLRequest(url: url)
self.wkWebView.load(request)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension WKRemoteViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in
// Background Thread 처리
var resultData: [String: Any]?
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
switch statusCode {
case 200:
resultData = [
"isSuccess": "OK"
]
break
default:
break
}
}
return resultData
}) { (pasingData) in
// Main Thread 처리
}
let result = IAMPortPay.sharedInstance.requestAction(for: request)
decisionHandler(result ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과
IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in
if error != nil {
switch error! {
case .custom(let reason):
print("error: \(reason)")
break
}
}else {
print("OK")
}
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation \(error.localizedDescription)")
}
}
| 765d1d4e530f4664ec7233b1d8fd30ab | 32.290909 | 157 | 0.578099 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieGraphics/ApplePlatform/Graphic/CGPattern.swift | mit | 1 | //
// CGPattern.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(CoreGraphics)
public func CGPatternCreate(
version: UInt32,
bounds: CGRect,
matrix: CGAffineTransform,
xStep: CGFloat,
yStep: CGFloat,
tiling: CGPatternTiling,
isColored: Bool,
callbacks: @escaping (CGContext) -> Void
) -> CGPattern? {
typealias CGPatternCallback = (CGContext) -> Void
let info = UnsafeMutablePointer<CGPatternCallback>.allocate(capacity: 1)
info.initialize(to: callbacks)
let callback = CGPatternCallbacks(version: version, drawPattern: { (info, context) in
guard let callbacks = info?.assumingMemoryBound(to: CGPatternCallback.self).pointee else { return }
callbacks(context)
}, releaseInfo: { info in
guard let info = info?.assumingMemoryBound(to: CGPatternCallback.self) else { return }
info.deinitialize(count: 1)
info.deallocate()
})
return CGPattern(info: info, bounds: bounds, matrix: matrix, xStep: xStep, yStep: yStep, tiling: tiling, isColored: isColored, callbacks: [callback])
}
#endif
| cef5c0ea27251206d77ee814474be73c | 37.2 | 153 | 0.70637 | false | false | false | false |
GuiminChu/HishowZone-iOS | refs/heads/master | HiShow/General/View/ImageViewingController.swift | mit | 1 | import UIKit
import Kingfisher
class ImageViewingController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
private lazy var scrollView: UIScrollView = {
let view = UIScrollView(frame: self.view.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.delegate = self
view.showsHorizontalScrollIndicator = false
view.zoomScale = 1.0
view.maximumZoomScale = 8.0
view.isScrollEnabled = false
return view
}()
private let duration = 0.3
private let zoomScale: CGFloat = 3.0
private let dismissDistance: CGFloat = 100.0
private var image: UIImage!
private var imageView: AnimatedImageView!
private var imageInfo: ImageInfo!
private var startFrame: CGRect!
private var snapshotView: UIView!
private var originalScrollViewCenter: CGPoint = .zero
private var singleTapGestureRecognizer: UITapGestureRecognizer!
private var panGestureRecognizer: UIPanGestureRecognizer!
private var longPressGestureRecognizer: UILongPressGestureRecognizer!
private var doubleTapGestureRecognizer: UITapGestureRecognizer!
init(imageInfo: ImageInfo) {
super.init(nibName: nil, bundle: nil)
self.imageInfo = imageInfo
image = imageInfo.image
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
let referenceFrameCurrentView = imageInfo.referenceView.convert(imageInfo.referenceRect, to: view)
imageView = AnimatedImageView(frame: referenceFrameCurrentView)
imageView.isUserInteractionEnabled = true
imageView.image = image
// imageView.originalData = imageInfo.originalData // used for gif image
imageView.contentMode = .scaleAspectFill // reset content mode
imageView.backgroundColor = .clear
setupGestureRecognizers()
view.backgroundColor = .black
}
func presented(by viewController: UIViewController) {
view.isUserInteractionEnabled = false
snapshotView = snapshotParentmostViewController(of: viewController)
snapshotView.alpha = 0.1
view.insertSubview(snapshotView, at: 0)
let referenceFrameInWindow = imageInfo.referenceView.convert(imageInfo.referenceRect, to: nil)
view.addSubview(imageView) // will move to scroll view after transition finishes
viewController.present(self, animated: false) {
self.imageView.frame = referenceFrameInWindow
self.startFrame = referenceFrameInWindow
UIView.animate(withDuration: self.duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.resizedFrame(forImageSize: self.image.size)
self.imageView.center = CGPoint(x: self.view.bounds.width / 2.0, y: self.view.bounds.height / 2.0)
}, completion: { (_) in
self.scrollView.addSubview(self.imageView)
self.updateScrollViewAndImageView()
self.view.isUserInteractionEnabled = true
})
}
}
private func dismiss() {
view.isUserInteractionEnabled = false
let imageFrame = view.convert(imageView.frame, from: scrollView)
imageView.removeFromSuperview()
imageView.frame = imageFrame
view.addSubview(imageView)
scrollView.removeFromSuperview()
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.startFrame
}) { (_) in
self.dismiss(animated: false, completion: nil)
}
}
// MARK: - Private
private func cancelImageDragging() {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.imageView.center = CGPoint(x: self.scrollView.contentSize.width / 2.0, y: self.scrollView.contentSize.height / 2.0)
self.updateScrollViewAndImageView()
self.snapshotView.alpha = 0.1
}, completion: nil)
}
private func setupGestureRecognizers() {
doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
doubleTapGestureRecognizer.delegate = self
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGestureRecognizer.delegate = self
singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(singleTap))
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
singleTapGestureRecognizer.require(toFail: longPressGestureRecognizer)
singleTapGestureRecognizer.delegate = self
view.addGestureRecognizer(singleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
view.addGestureRecognizer(doubleTapGestureRecognizer)
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
panGestureRecognizer.maximumNumberOfTouches = 1
panGestureRecognizer.delegate = self
scrollView.addGestureRecognizer(panGestureRecognizer)
}
private func snapshotParentmostViewController(of viewController: UIViewController) -> UIView {
var snapshot = viewController.view
if var presentingViewController = viewController.view.window!.rootViewController {
while presentingViewController.presentedViewController != nil {
presentingViewController = presentingViewController.presentedViewController!
}
snapshot = presentingViewController.view.snapshotView(afterScreenUpdates: true)
}
return snapshot ?? UIView()
}
private func updateScrollViewAndImageView() {
scrollView.frame = view.bounds
imageView.frame = resizedFrame(forImageSize: image.size)
scrollView.contentSize = imageView.frame.size
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
}
private func contentInsetForScrollView(withZoomScale zoomScale: CGFloat) -> UIEdgeInsets {
let boundsWidth = scrollView.bounds.width
let boundsHeight = scrollView.bounds.height
let contentWidth = image.size.width
let contentHeight = image.size.height
var minContentHeight: CGFloat!
var minContentWidth: CGFloat!
if (contentHeight / contentWidth) < (boundsHeight / boundsWidth) {
minContentWidth = boundsWidth
minContentHeight = minContentWidth * (contentHeight / contentWidth)
} else {
minContentHeight = boundsHeight
minContentWidth = minContentHeight * (contentWidth / contentHeight)
}
minContentWidth = minContentWidth * zoomScale
minContentHeight = minContentHeight * zoomScale
let hDiff = max(boundsWidth - minContentWidth, 0)
let vDiff = max(boundsHeight - minContentHeight, 0)
let inset = UIEdgeInsets(top: vDiff / 2.0, left: hDiff / 2.0, bottom: vDiff / 2.0, right: hDiff / 2.0)
return inset
}
private func resizedFrame(forImageSize size: CGSize) -> CGRect {
guard size.width > 0, size.height > 0 else {
return .zero
}
var frame = view.bounds
let nativeWidth = size.width
let nativeHeight = size.height
var targetWidth = frame.width * scrollView.zoomScale
var targetHeight = frame.height * scrollView.zoomScale
if (targetHeight / targetWidth) < (nativeHeight / nativeWidth) {
targetWidth = targetHeight * (nativeWidth / nativeHeight)
} else {
targetHeight = targetWidth * (nativeHeight / nativeWidth)
}
frame = CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight)
return frame
}
// MARK: - Gesture Recognizer Actions
@objc
private func singleTap() {
dismiss()
}
@objc
private func pan(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
let translationDistance = sqrt(pow(translation.x, 2) + pow(translation.y, 2))
switch sender.state {
case .began:
originalScrollViewCenter = scrollView.center
case .changed:
scrollView.center = CGPoint(x: originalScrollViewCenter.x + translation.x, y: originalScrollViewCenter.y + translation.y)
snapshotView.alpha = min(max(translationDistance / dismissDistance * 0.5, 0.1), 0.6)
default:
if translationDistance > dismissDistance {
dismiss()
} else {
cancelImageDragging()
}
}
}
@objc
private func longPress() {
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
}
@objc
private func doubleTap(_ sender: UITapGestureRecognizer) {
let rawLocation = sender.location(in: sender.view)
let point = scrollView.convert(rawLocation, from: sender.view)
var targetZoomRect: CGRect
var targetInsets: UIEdgeInsets
if scrollView.zoomScale == 1.0 {
let zoomWidth = view.bounds.width / zoomScale
let zoomHeight = view.bounds.height / zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: zoomScale)
} else {
let zoomWidth = view.bounds.width * scrollView.zoomScale
let zoomHeight = view.bounds.height * scrollView.zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: 1.0)
}
view.isUserInteractionEnabled = false
CATransaction.begin()
CATransaction.setCompletionBlock {
self.scrollView.contentInset = targetInsets
self.view.isUserInteractionEnabled = true
}
scrollView.zoom(to: targetZoomRect, animated: true)
CATransaction.commit()
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == panGestureRecognizer, scrollView.zoomScale != 1.0 {
return false
}
return true
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
scrollView.isScrollEnabled = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.isScrollEnabled = (scale > 1)
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scale)
}
}
struct ImageInfo {
var image: UIImage!
var originalData: Data?
var referenceRect: CGRect!
var referenceView: UIView!
}
| 26b4ad05387287494bcae6a879df9015 | 42.568266 | 183 | 0.672567 | false | false | false | false |
RizanHa/RHImgPicker | refs/heads/master | RHImgPicker/Classes/Models/AlbumTableViewDataSource.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Rizan Hamza
//
// 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.
//
// AlbumTableViewDataSource.swift
// Pods
//
// Created by rizan on 27/08/2016.
//
//
import UIKit
import Photos
fileprivate enum AlbumPreviewImageIndex : Int {
case imgNotFound = -1
case img1 = 0
case img2 = 1
case img3 = 2
}
final class AlbumTableViewDataSource : NSObject, UITableViewDataSource {
class func registerCellIdentifiersForTableView(_ tableView: UITableView?) {
tableView?.register(AlbumCell.self, forCellReuseIdentifier: AlbumCell.IDENTIFIER)
}
fileprivate struct AlbumData {
var albumTitle : String?
var img1 : UIImage?
var img2 : UIImage?
var img3 : UIImage?
}
let fetchResults: [PHFetchResult<AnyObject>]
let settings: RHImgPickerSettings?
fileprivate var DATACach : [AlbumData] = []
fileprivate func dataCachIndexForAlbum(_ albumTitle : String?) -> AlbumPreviewImageIndex {
var ObjIndex : AlbumPreviewImageIndex = .imgNotFound
for (idx,data) in DATACach.enumerated() {
if data.albumTitle == albumTitle {
let index = min(idx, AlbumPreviewImageIndex.img3.rawValue)
if let oj = AlbumPreviewImageIndex(rawValue: idx) {
ObjIndex = oj
}
break
}
}
return ObjIndex
}
fileprivate func updataDATACach(_ albumTitle : String?, img : UIImage?, imgIndex : AlbumPreviewImageIndex) {
if albumTitle == nil {
return
}
let objIndex = dataCachIndexForAlbum(albumTitle)
if (objIndex != .imgNotFound ) {
var data = DATACach[objIndex.rawValue]
DATACach.remove(at: objIndex.rawValue)
switch imgIndex {
case .img1:
data.img1 = img
break
case .img2:
data.img2 = img
break
case .img3:
data.img3 = img
break
default:
break
}
DATACach.append(data)
}
}
init(fetchResults: [PHFetchResult<AnyObject>], settings: RHImgPickerSettings?) {
self.fetchResults = fetchResults
self.settings = settings
super.init()
}
func numberOfSections(in tableView: UITableView) -> Int {
return fetchResults.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchResults[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
UIView.setAnimationsEnabled(false)
let cell = tableView.dequeueReusableCell(withIdentifier: AlbumCell.IDENTIFIER, for: indexPath) as! AlbumCell
cell.layoutCell()
let cachingManager = PHCachingImageManager.default() as? PHCachingImageManager
cachingManager?.allowsCachingHighQualityImages = false
// Fetch album
if let album = fetchResults[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row] as? PHAssetCollection {
// Title
cell.albumTitleLabel.text = album.localizedTitle
// check for album preview cash DATA
let objIndex = dataCachIndexForAlbum(album.localizedTitle)
if (objIndex != .imgNotFound ) {
let data = DATACach[objIndex.rawValue]
cell.albumTitleLabel.text = data.albumTitle
cell.firstImageView.image = data.img1
cell.secondImageView.image = data.img2
cell.thirdImageView.image = data.img3
UIView.setAnimationsEnabled(true)
return cell
}
// request Album preview DATA
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: false)
]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let result = PHAsset.fetchAssets(in: album, options: fetchOptions)
result.enumerateObjects( { (object, idx, stop) in
if let asset = object as? PHAsset {
let imageSize = CGSize(width: 80, height: 80)
let imageContentMode: PHImageContentMode = .aspectFill
switch idx {
case AlbumPreviewImageIndex.img1.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.firstImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.firstImageView.image, imgIndex: .img1)
}
case AlbumPreviewImageIndex.img2.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.secondImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.secondImageView.image, imgIndex: .img2)
}
case AlbumPreviewImageIndex.img3.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.thirdImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.thirdImageView.image, imgIndex: .img3)
}
default:
// Stop enumeration
stop.initialize(to: true)
}
}
})
}
let newData : AlbumData = AlbumData(albumTitle: cell.albumTitleLabel.text, img1: cell.firstImageView.image, img2: cell.secondImageView.image, img3: cell.thirdImageView.image)
self.DATACach.append(newData)
UIView.setAnimationsEnabled(true)
return cell
}
}
| 27baf31dde1cfac38c07a857d8df2fc3 | 31.595142 | 182 | 0.564154 | false | false | false | false |
tensorflow/examples | refs/heads/master | lite/examples/pose_estimation/ios/PoseEstimation/Camera/CameraFeedManager.swift | apache-2.0 | 1 | // Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import AVFoundation
import Accelerate.vImage
import UIKit
/// Delegate to receive the frames captured from the device's camera.
protocol CameraFeedManagerDelegate: AnyObject {
/// Callback method that receives frames from the camera.
/// - Parameters:
/// - cameraFeedManager: The CameraFeedManager instance which calls the delegate.
/// - pixelBuffer: The frame received from the camera.
func cameraFeedManager(
_ cameraFeedManager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer)
}
/// Manage the camera pipeline.
final class CameraFeedManager: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
/// Delegate to receive the frames captured by the device's camera.
var delegate: CameraFeedManagerDelegate?
override init() {
super.init()
configureSession()
}
/// Start capturing frames from the camera.
func startRunning() {
captureSession.startRunning()
}
/// Stop capturing frames from the camera.
func stopRunning() {
captureSession.stopRunning()
}
let captureSession = AVCaptureSession()
/// Initialize the capture session.
private func configureSession() {
captureSession.sessionPreset = AVCaptureSession.Preset.photo
guard
let backCamera = AVCaptureDevice.default(
.builtInWideAngleCamera, for: .video, position: .back)
else {
return
}
do {
let input = try AVCaptureDeviceInput(device: backCamera)
captureSession.addInput(input)
} catch {
return
}
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.videoSettings = [
(kCVPixelBufferPixelFormatTypeKey as String): NSNumber(value: kCVPixelFormatType_32BGRA)
]
videoOutput.alwaysDiscardsLateVideoFrames = true
let dataOutputQueue = DispatchQueue(
label: "video data queue",
qos: .userInitiated,
attributes: [],
autoreleaseFrequency: .workItem)
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
videoOutput.connection(with: .video)?.videoOrientation = .portrait
captureSession.startRunning()
}
videoOutput.setSampleBufferDelegate(self, queue: dataOutputQueue)
}
// MARK: Methods of the AVCaptureVideoDataOutputSampleBufferDelegate
func captureOutput(
_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
delegate?.cameraFeedManager(self, didOutput: pixelBuffer)
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
}
}
| 985dbaed69b8cb7f1a68f6d7ba8c910c | 32.980198 | 94 | 0.722028 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-fuzzing/22685-no-stacktrace.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
init("cd"A<T: (v: c> U)
class a {
class A<T : A {
typealias f : where g<T
func f: e: a {
{
}
}
{
{
class A {
{
}
}
struct B<b() -> ( )
}
}
}
{
struct c : T
func a
let h == b
-> = b
{
}
class c<T : T: d: A<I : d {
let : a = B)
{
}
enum A {
struct Q<T: A<T where g
enum S {
{
let h = b
class a
let i: A {
"
class B {
struct B : T) {
{
A {
struct Q<T.g = b(c<T) {
{
{
e {
}
protocol A {
}
var d = 1
struct Q<T : B<T where g: B)
println(f<T where g
}
class B : where h> ()
var a<T : T where g
class d>
}
}
var d {
func a
}
let : C {
struct B {
A ) -> {
class A {
struct c : c<T) {
}
{
}
{
struct B {
class c
}
init(object2: e.B<T) -> {
init(f: T: e
{
class a {
}
}
println(T! {
{
{
{
println() -> ( ( ) -> {
{
init("])
struct Q<T where g<T.h
class A ) {
}
class b {
class B {
class c<b
}
}
v
class C(a
var d = {
init < {
func b<d: a {
init(A
typealias f : B<h: A {
{
var d = b> U>
{
}
}
}
}
var d {
struct B {
enum a<T: a {
}
}
{
let h = b("
let h = 1
class B<T: T where g: A : T) {
init() -> {
struct B {
{
{
func f<T where H : c> ( )
class d<T where g: a {
}
}
-> = [T where k : A {
let i: d {
{
{
{
enum A {
{
protocol a {
}
var f : C {
class a<T : A {
extension {
}
let a {
}
{
class a: A {
typealias e {
}
class B? {
typealias b {
}
class d: C {
class B<b() {
let i( )
}
class B {
}
class B<b(f<T where g: C {
}
class d
class B : (A
init(f<T where h
}
class c<T where g
let i: d {
enum S : a {
struct B<T where g
struct B<T where h
var f : b<T) {
{
}
{
init(f<T.h == e: a {
enum A {
enum A {
func c<S : a {
}
A {
let : T>
typealias b {
struct Q<d
var f : A<T : A {
{
struct Q<b> {
struct B<U>])
class d>
println(a: A {
class B<T where g
var e
{
class B<T) -> {
func i: NSObject {
init() -> {
struct g: T, A {
let start = c
class d
enum S : e
{
init < {
}
{
}
class A {
class B : a {
init(f<T where g
func a
protocol a = b(T) -> {
}
class b : (f: d<h: a = B<T where g
{
{
"
let h = b<d: (
| 095467328801638cd0096e3014b40bac | 8.70892 | 87 | 0.523694 | false | false | false | false |
OctMon/OMExtension | refs/heads/master | OMExtension/OMExtension/Source/Foundation/OMInt.swift | mit | 1 | //
// OMInt.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if !os(macOS)
import UIKit
#endif
public extension Int {
struct OM {
public static func random(_ range: Range<Int>) -> Int {
return random(range.lowerBound, range.upperBound - 1)
}
public static func random(_ range: ClosedRange<Int>) -> Int {
return random(range.lowerBound, range.upperBound)
}
public static func random(_ lower: Int = 0, _ upper: Int = 9) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
}
public extension Int {
var omToString: String {
return String(self)
}
var omToDouble: Double {
return Double(self)
}
var omToFloat: Float {
return Float(self)
}
var omToCGFloat: CGFloat {
return CGFloat(self)
}
var omIsEven: Bool {
return (self % 2 == 0)
}
var omIsOdd: Bool {
return !omIsEven
}
var omAbs: Int {
return abs(self)
}
var omLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
}
| 4d4ec38b1886ea75372bae804040f745 | 25.323232 | 82 | 0.610898 | false | false | false | false |
xilosada/TravisViewerIOS | refs/heads/master | TVModel/RepositoryEntity.swift | mit | 1 | //
// RepositoryEntity.swift
// TravisViewerIOS
//
// Created by X.I. Losada on 04/02/16.
// Copyright © 2016 XiLosada. All rights reserved.
//
import Foundation
public struct RepositoryEntity {
public let id: Int
public let slug: String
public let description: String
public var builds = [BuildEntity]()
init(id: Int, slug: String, description: String) {
self.id = id
self.slug = slug
self.description = description
}
}
extension RepositoryEntity {
init?(dictionary: NSDictionary) {
guard let id = dictionary["id"] as? Int,
slug = dictionary["slug"] as? String,
description = dictionary["description"] as? String
else{
return nil
}
self.id = id
self.slug = slug
if description.isEmpty {
self.description = "Description not provided"
}else {
self.description = description
}
}
struct Mapper{
static func parseJSONArray(jsonArray: [AnyObject]) throws -> [RepositoryEntity] {
var repos = [RepositoryEntity]()
print(jsonArray)
try jsonArray.forEach { jsonObject in
if let repoDictionary = jsonObject as? NSDictionary {
if let repo = RepositoryEntity(dictionary: repoDictionary){
repos.append(repo)
}
} else {
throw NSError(domain: "repo mapper", code: 0, userInfo: nil)
}
}
return repos
}
}
} | ed1a90289be412903a982e9a414bdb5a | 26.338983 | 89 | 0.549007 | false | false | false | false |
jigneshsheth/Datastructures | refs/heads/master | DataStructure/DataStructure/Cards/Card.swift | mit | 1 | //
// Card.swift
// DataStructure
//
// Created by Jigs Sheth on 3/21/16.
// Copyright © 2016 jigneshsheth.com. All rights reserved.
//
import Foundation
public class Card {
class public func shuffle<T>(input:[T]) -> [T]{
var input:[T] = input
let len = input.count
for i in 0..<len{
let index = Int(arc4random_uniform((UInt32(len - i))))
let temp = input[i]
input[i] = input[index]
input[index] = temp
}
return input
}
}
| fdce6db3d8c6d849d329faaf21d7a209 | 16.814815 | 60 | 0.592516 | false | false | false | false |
Allow2CEO/browser-ios | refs/heads/master | Client/Frontend/Reader/ReaderModeStyleViewController.swift | mpl-2.0 | 1 | /* 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 UIKit
import Shared
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGray // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGray // TODO THis needs to be 44% of 0x333333
static let ThemeRowBackgroundColor = UIColor.white
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.white
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.white
static let ThemeBackgroundColorDark = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xF0E6DC)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
fileprivate var fontTypeButtons: [FontTypeButton]!
fileprivate var fontSizeLabel: FontSizeLabel!
fileprivate var fontSizeButtons: [FontSizeButton]!
fileprivate var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp.makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: #selector(ReaderModeStyleViewController.SELchangeFontType(_:)))
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp.makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp.bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp.makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.smaller),
FontSizeButton(fontSizeAction: FontSizeAction.bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: #selector(ReaderModeStyleViewController.SELchangeFontSize(_:)))
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp.makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp.bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: #selector(ReaderModeStyleViewController.SELchangeTheme(_:)))
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp.makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp.bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.accessibilityLabel = Strings.Brightness
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: #selector(ReaderModeStyleViewController.SELchangeBrightness(_:)), for: UIControlEvents.valueChanged)
slider.snp.makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp.makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp.left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp.makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp.right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.main.brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
fileprivate func setupButtons(_ buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in buttons.enumerated() {
row.addSubview(button)
button.addTarget(self, action: action, for: UIControlEvents.touchUpInside)
button.snp.makeConstraints { make in
make.top.equalTo(row.snp.top)
if idx == 0 {
make.left.equalTo(row.snp.left)
} else {
make.left.equalTo(buttons[idx - 1].snp.right)
}
make.bottom.equalTo(row.snp.bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(_ button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
fileprivate func selectFontType(_ fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.isSelected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(_ button: FontSizeButton) {
switch button.fontSizeAction {
case .smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
fileprivate func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .bigger:
button.isEnabled = !readerModeStyle.fontSize.isLargest()
break
case .smaller:
button.isEnabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(_ button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
fileprivate func selectTheme(_ theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(_ slider: UISlider) {
UIScreen.main.brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRect.zero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, for: UIControlState.selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, for: .normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
accessibilityHint = Strings.Changes_font_type
switch fontType {
case .SansSerif:
setTitle(Strings.SansSerif, for: UIControlState.normal)
let f = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
titleLabel?.font = f
case .Serif:
setTitle(Strings.Serif, for: UIControlState.normal)
let f = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case smaller
case bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRect.zero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, for: UIControlState.normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, for: UIControlState.disabled)
switch fontSizeAction {
case .smaller:
let smallerFontLabel = Strings.Minus
let smallerFontAccessibilityLabel = Strings.Decrease_text_size
setTitle(smallerFontLabel, for: .normal)
accessibilityLabel = smallerFontAccessibilityLabel
case .bigger:
let largerFontLabel = Strings.Plus
let largerFontAccessibilityLabel = Strings.Increase_text_size
setTitle(largerFontLabel, for: .normal)
accessibilityLabel = largerFontAccessibilityLabel
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = UIFont(name: "FiraSans-Light", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = Strings.FontSizeAa
text = fontSizeLabel
isAccessibilityElement = false
}
required init?(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
case .Serif:
font = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRect.zero)
self.theme = theme
setTitle(theme.rawValue, for: .normal)
accessibilityHint = Strings.Changes_color_theme
switch theme {
case .Light:
setTitle(Strings.Light, for: .normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, for: UIControlState.normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(Strings.Dark, for: .normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, for: UIControlState.normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(Strings.Sepia, for: .normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, for: UIControlState.normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = UIFont(name: "FiraSans-Book", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
case .Serif:
titleLabel?.font = UIFont(name: "Charis SIL", size: DynamicFontHelper.defaultHelper.ReaderStandardFontSize)
}
}
}
}
| 3a1b199c36558cef62c93b54808ec3dd | 37.175202 | 144 | 0.683471 | false | false | false | false |
wjk930726/weibo | refs/heads/master | weiBo/weiBo/iPhone/Modules/Compose/EmotionKeyboard/WBEmotionKeyboardCell.swift | mit | 1 | //
// WBEmotionKeyboardCell.swift
// weiBo
//
// Created by 王靖凯 on 2016/12/5.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
fileprivate let basetag: Int = 4526
class WBEmotionKeyboardCell: UICollectionViewCell {
var model: [WBEmotionModel]? {
didSet {
guard let emotions = model else {
return
}
for item in emotions.enumerated() {
let tag = item.offset + basetag
let model = item.element
guard let btn = viewWithTag(tag) as? UIButton else {
print("tag is error")
return
}
if model.type == 0 {
guard let png = model.fullPath else {
print("png is error")
return
}
btn.setTitle(nil, for: .normal)
btn.setImage(UIImage(named: png), for: .normal)
} else {
guard let emoji = model.code else {
print("emoji is error")
return
}
btn.setTitle(String.emoji(stringCode: emoji), for: .normal)
// let str = String.emoji(stringCode: emoji)
// print(str,emoji)
btn.setImage(nil, for: .normal)
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBEmotionKeyboardCell {
fileprivate func setupView() {
let witdhHeight = (screenWidth / 7)
let space = (bounds.size.height - 3 * witdhHeight) / 2
let frame = CGRect(x: 0, y: 0, width: witdhHeight, height: witdhHeight)
for i in 0 ..< 21 {
let btn = UIButton(title: nil, target: self, action: #selector(insertOrDelete(sender:)))
let dx = CGFloat(i % 7)
let dy = CGFloat(i / 7)
btn.frame = frame.offsetBy(dx: dx * witdhHeight, dy: dy * (witdhHeight + space))
if i == 20 {
btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete"), for: .normal)
btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete_highlighted"), for: .highlighted)
}
btn.tag = basetag + i
btn.titleLabel?.font = UIFont.systemFont(ofSize: 34)
contentView.addSubview(btn)
}
}
}
extension WBEmotionKeyboardCell {
@objc fileprivate func insertOrDelete(sender: UIButton) {
let index = sender.tag - basetag
var isDelete: Bool = false
var userInfo: [String: Any] = [:]
if index == 20 {
isDelete = true
userInfo = ["isDelete": isDelete]
} else {
isDelete = false
let emotion = model![index]
userInfo = ["isDelete": isDelete, "emotion": emotion]
}
let notification = Notification(name: addOrDeleteNotification, object: nil, userInfo: userInfo)
NotificationCenter.default.post(notification)
}
}
| 909c68f7c0b36ffe1375eb78102356ce | 32.854167 | 114 | 0.521846 | false | false | false | false |
humberaquino/bufpeek | refs/heads/master | Bufpeek/BufpeekError.swift | mit | 1 | import Foundation
// Error domains, codes and utility functions
public class BufpeekError {
struct Code {
// OAuth
static let FailedOAuth = 1000
static let OAuthMissingAccessToken = 1001
static let OAuthInvalidResponse = 1002
static let TokenNotAvailable = 1003
// Mapping
static let MappingError = 2000
// Fetching
static let MultipleFetchError = 3000
}
struct Domain {
static let OAuth = "OAuth"
static let Mapping = "Mapping"
static let Fetching = "Fetching"
}
public class func authErrorWithMessage(msg: String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.FailedOAuth, userInfo: userInfo)
return error
}
public class func accessTokenNotFoundInResponse(json: NSDictionary) -> NSError {
let msg = "JSON response does not contain 'access_token' element"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.OAuthMissingAccessToken, userInfo: userInfo)
return error
}
public class func responseDataNotJSON(obj: AnyObject?) -> NSError {
let msg = "Response is not a dictionary: \(obj)"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.OAuthInvalidResponse, userInfo: userInfo)
return error
}
public class func mappingError(json: String, className: String) -> NSError {
let msg = "Error while trying to map \(className)"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.Mapping, code: Code.MappingError, userInfo: userInfo)
return error
}
public class func multipleFetchError(msg: String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.Fetching, code: Code.MultipleFetchError, userInfo: userInfo)
return error
}
public class func tokenNotAvailable() -> NSError {
let msg = "Token not available. Probably the user is not logged in"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.TokenNotAvailable, userInfo: userInfo)
return error
}
} | 6e64d5e9554945a007fc35a5a63052d5 | 34.882353 | 105 | 0.653137 | false | false | false | false |
JiongXing/PhotoBrowser | refs/heads/master | Example/Example/ImageSmoothZoomViewController.swift | mit | 1 | //
// LocalImageSmoothZoomViewController.swift
// Example
//
// Created by JiongXing on 2019/11/28.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
import JXPhotoBrowser
class ImageSmoothZoomViewController: BaseCollectionViewController {
override class func name() -> String { "更丝滑的Zoom转场动画" }
override class func remark() -> String { "需要用户自己创建并提供转场视图,以及缩略图位置" }
override func makeDataSource() -> [ResourceModel] {
makeLocalDataSource()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.jx.dequeueReusableCell(BaseCollectionViewCell.self, for: indexPath)
cell.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) }
// 等比拉伸,填满视图
cell.imageView.contentMode = .scaleAspectFill
return cell
}
override func openPhotoBrowser(with collectionView: UICollectionView, indexPath: IndexPath) {
let browser = JXPhotoBrowser()
browser.numberOfItems = {
self.dataSource.count
}
browser.reloadCellAtIndex = { context in
let browserCell = context.cell as? JXPhotoBrowserImageCell
let indexPath = IndexPath(item: context.index, section: indexPath.section)
browserCell?.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) }
}
// 更丝滑的Zoom动画
browser.transitionAnimator = JXPhotoBrowserSmoothZoomAnimator(transitionViewAndFrame: { (index, destinationView) -> JXPhotoBrowserSmoothZoomAnimator.TransitionViewAndFrame? in
let path = IndexPath(item: index, section: indexPath.section)
guard let cell = collectionView.cellForItem(at: path) as? BaseCollectionViewCell else {
return nil
}
let image = cell.imageView.image
let transitionView = UIImageView(image: image)
transitionView.contentMode = cell.imageView.contentMode
transitionView.clipsToBounds = true
let thumbnailFrame = cell.imageView.convert(cell.imageView.bounds, to: destinationView)
return (transitionView, thumbnailFrame)
})
browser.pageIndex = indexPath.item
browser.show(method: .push(inNC: nil))
}
}
| e81e56bee213a17136b9c3c4a2136c7c | 42.436364 | 183 | 0.68648 | false | false | false | false |
Diederia/project | refs/heads/master | Diederick-Calkoen-Project/CollectionViewController.swift | mit | 1 | //
// CollectionViewController.swift
// Diederick-Calkoen-Project
//
// Created by Diederick Calkoen on 12/01/17.
// Copyright © 2017 Diederick Calkoen. All rights reserved.
//
// This view controller shows the schedule of the calendar day. As stundent, teacher or admin user you could schedule yourself in the collection view. All the data of the collection view is saved in FireBase.
import UIKit
import Firebase
class CollectionViewController: UIViewController {
// MARK: - outlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var dateLabel: UILabel!
// MARK: - Constants and variables
let dateCellIdentifier = "DateCellIdentifier"
let contentCellIdentifier = "ContentCellIdentifier"
let timeSlots:[String] = ["9:00","9:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00",
"13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30",
"18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00"]
let hours:[String] = [" 1 uur ", " 1½ uur " , " 2 uur ", " 2½ uur "," 3 uur "," 3½ uur ",
" 4 uur", "4½ uur", " 5 uur ", " 5½ uur ", " 6 uur ", " 6½ uur ",
" 7 uur ", " 7½ uur ", " 8 uur ", " 8½ uur ", " 9 uur "]
var pickerMenu: UIPickerView = UIPickerView()
var sampleSegment: UISegmentedControl = UISegmentedControl ()
var alertController: UIAlertController = UIAlertController()
var selectedRow: Int = 2
var selectedItem = IndexPath()
var ref = FIRDatabase.database().reference()
var userId = String()
var userStatus = Int()
var userData = [String:AnyObject]()
// MARK: - Colors
let colorDictionary: [String:UIColor] = ["lightWhite": UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1),
"greyWhite": UIColor(red: 242/255.0, green: 242/255.0, blue: 242/255.0, alpha: 1),
"green": UIColor(red: 0/255.0, green: 240/255.0, blue: 20/255.0, alpha: 1),
"lightGreen": UIColor(red: 0/255.0, green: 200/255.0, blue: 20/255.0, alpha: 0.3),
"greyGreen": UIColor(red: 0/255.0, green: 200/255.0, blue: 20/255.0, alpha: 0.5),
"lightRed": UIColor(red: 230/255.0, green: 20/255.0, blue: 20/255.0, alpha: 0.3),
"greyRed": UIColor(red: 230/255.0, green: 20/255.0, blue: 20/255.0, alpha: 0.5)]
let white = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
let black = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1)
let pink = UIColor(red: 225/255.0, green: 0/255.0, blue: 122/255.0, alpha: 1.0)
// MARK: - Override functions
override func viewDidLoad()
{
super.viewDidLoad()
setupCollectionView()
setupPickerView()
}
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(CalendarDay.dataOfDate, forKey: "data")
coder.encode(CalendarDay.calendarDayDate, forKey: "date")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
CalendarDay.dataOfDate = coder.decodeObject(forKey: "data") as! [(String) : String]
dateLabel.text = coder.decodeObject(forKey: "date") as! String?
collectionView.reloadData()
super.decodeRestorableState(with: coder)
}
// MARk: - Functions
// Setup all items for the use of the collection view.
func setupCollectionView() {
dateLabel.text = CalendarDay.calendarDayDate
collectionView.layer.borderWidth = 2
collectionView.layer.borderColor = self.pink.cgColor
userData = UserDefaults.standard.value(forKey: "userData") as! [String : AnyObject]
self.userId = userData["id"] as! String
self.userStatus = userData["userStatus"] as! Int
self.collectionView .register(UINib(nibName: "DateCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: dateCellIdentifier)
self.collectionView .register(UINib(nibName: "ContentCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: contentCellIdentifier)
}
// Function to setup the picker view for the input of the user.
func setupPickerView () {
pickerMenu = UIPickerView(frame: CGRect(x: 10.0, y: 40.0, width: 250, height: 170))
pickerMenu.delegate = self;
pickerMenu.dataSource = self;
pickerMenu.showsSelectionIndicator = true
pickerMenu.tintColor = UIColor.red
pickerMenu.reloadAllComponents()
}
// Function to handle all the parameters to configurate the cell of the collection view.
func configurateCell(indexPath: IndexPath, contentCell: Bool, text: String, colorString: String) -> UICollectionViewCell {
if contentCell == true {
let cell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
cell.contentLabel.textColor = self.black
cell.contentLabel.text = text
cell.backgroundColor = self.getColor(indexPath: indexPath, colorString: colorString)
return cell
} else {
let cell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
cell.dateLabel.textColor = self.black
cell.dateLabel.text = text
cell.backgroundColor = self.getColor(indexPath: indexPath, colorString: colorString)
return cell
}
}
// Function the get the right background color of the cell.
func getColor(indexPath: IndexPath, colorString: String) -> UIColor {
var color = UIColor()
if colorString == "green" || colorString == "white" {
color = self.colorDictionary[colorString]!
} else {
if indexPath.section % 2 != 0 {
color = self.colorDictionary["grey" + colorString]!
} else {
color = self.colorDictionary["light" + colorString]!
}
}
return color
}
func reloadCollectionView() {
self.collectionView.reloadData()
}
// Function to convert the index path to a string without brackets for FireBase.
func convertIndexPath (indexPath: IndexPath) -> String {
var stringIndexPath = String(describing: indexPath)
stringIndexPath = stringIndexPath.replacingOccurrences(of: "[", with: "")
stringIndexPath = stringIndexPath.replacingOccurrences(of: "]", with: "")
return stringIndexPath
}
// Function for an alert.
func alert(title: String, message: String) {
alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Terug", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// Function for an alert with a picker view.
func alertWithPickerMenu(title: String, message: String, user: Int) {
alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.view.addSubview(pickerMenu)
alertController.addAction(UIAlertAction(title: "Terug", style: UIAlertActionStyle.default,handler: nil))
alertController.addAction(UIAlertAction(title: "Ja",style: UIAlertActionStyle.default, handler: {
(_)in
if user == 0 {
self.studentPickerView()
} else if user == 1 {
self.teacherPickerView()
} else {
self.adminPickerView()
}
}))
self.present(alertController, animated: true, completion: nil)
}
// Remove teacher id from the database when all hours are deleted.
func removeTeacherId(){
for i in 1...17 {
let indexPath = (String(i) + ", " + String(self.selectedItem.row))
if CalendarDay.dataOfDate[indexPath] != nil {
return
}
}
CalendarDay.dataOfDate.removeValue(forKey: String(0) + ", " + String(self.selectedItem.row))
}
// The picker view function when a teacher clicks on a cell.
func teacherPickerView() {
// check the request is within the schedule
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Error", message: "Plan de uren binnen de roostertijden.")
return
}
// place the use id in the cells
CalendarDay.dataOfDate["0, " + String(self.selectedItem.row)] = self.userId
for i in 0...self.selectedRow - 1 {
let indexPath = IndexPath(row: self.selectedItem.row, section: self.selectedItem.section + i)
let stringIndexPath = self.convertIndexPath(indexPath: indexPath)
CalendarDay.dataOfDate[stringIndexPath] = "Vrij"
}
// save the data of the day in FireBase
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
// The picker view function when a student clicks on a cell.
func studentPickerView() {
// check if the request is within the schedule
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Error", message: "Plan de uren binnen de roostertijden.")
return
}
let section = self.selectedItem.section + self.selectedRow - 1
let indexPath = IndexPath(row: self.selectedItem.row, section: section)
let cell = self.collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// check if teacher is avaible for the input of the student
guard cell.contentLabel.text == "Vrij" else {
self.alert(title: "Error", message: "De docent is niet beschikbaar op deze tijden. Check uw invoer.")
return
}
for i in 0...self.selectedRow - 1 {
let indexPath = String(self.selectedItem.section + i) + ", " + String(self.selectedItem.row)
CalendarDay.dataOfDate.updateValue(self.userId, forKey: indexPath)
}
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
func adminPickerView() {
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Foudmelding", message: "Verwijder binnen de uren van de roostertijden.")
return
}
let section = self.selectedItem.section + self.selectedRow - 1
let indexPath = IndexPath(row: self.selectedItem.row, section: section)
let cell = self.collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// check if teacher is avaible for the input of the student
guard cell.contentLabel.text != "_" else {
self.alert(title: "Foudmelding", message: "Deze uren kunnen niet verwijderd worden. Let op het aantal uren te verwijderen.")
return
}
for i in 0...self.selectedRow - 1 {
let indexPath = String(self.selectedItem.section + i) + ", " + String(self.selectedItem.row)
CalendarDay.dataOfDate.removeValue(forKey: indexPath)
}
removeTeacherId()
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
}
// MARK: - UICollectionView
extension CollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 28
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 8
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.section == 0 {
return
}
self.selectedItem = indexPath
let cell = collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// Check if it's an admin user and if the cell is not empty.
if self.userStatus == 2 && cell.contentLabel.text != "_" {
self.alertWithPickerMenu(title: " Wilt u " + timeSlots[self.selectedItem.section - 1] + " verwijderen? \n\n\n\n\n\n\n\n\n", message: " U moet minimaal 1 uur verwijderen.", user: self.userStatus)
}
guard cell.contentLabel.text == "Vrij" || cell.contentLabel.text == "_" else{
self.alert(title: "Foutmelding", message: "De sectie is al ingepland")
return
}
// Check if it's a student and setup picker view.
if cell.contentLabel.text == "Vrij" {
guard self.userStatus == 0 && indexPath.row != 0 else {
self.alert(title: "Foutmelding", message: "U kunt als docent geen docent reserveren.")
return
}
self.alertWithPickerMenu(title: " Wilt u " + timeSlots[self.selectedItem.section - 1] + " uur inplannen? \n\n\n\n\n\n\n\n\n", message: " U moet minimaal 1 uur inplannen.", user: self.userStatus)
// Check if it's a teacher and setup picker view.
} else if cell.contentLabel.text == "_" {
guard self.userStatus == 1 else {
self.alert(title: "Foutmelding", message: "U kunt als leerling geen beschikbare tijden invoeren.")
return
}
guard CalendarDay.dataOfDate.values.contains(self.userId) == false else {
self.alert(title: "Foutmelding", message: "U heeft deze dag al ingepland.")
return
}
self.alertWithPickerMenu(title: " Wilt u " + self.timeSlots[self.selectedItem.section - 1] + " uur inplannen? \n\n\n\n\n\n\n\n\n", message: "U moet minimaal 1 uur inplannen.", user: self.userStatus)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return configurateCell(indexPath: indexPath,
contentCell: false,
text: "Tijd",
colorString: "White")
} else {
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath: indexPath))] != nil {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))]!,
colorString: "green")
} else {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: "Vrij",
colorString: "White")
}
}
} else {
if indexPath.row == 0 {
return configurateCell(indexPath: indexPath,
contentCell: false,
text: timeSlots[((indexPath as NSIndexPath).section) - 1],
colorString: "White")
} else {
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))] != nil {
var color = String()
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))] == "Vrij"{
color = "Green"
}
else {
color = "Red"
}
return configurateCell(indexPath: indexPath,
contentCell: true,
text: CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))]!,
colorString: color)
} else {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: "_",
colorString: "White")
}
}
}
}
}
// MARK: - UIPickerView
extension CollectionViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 17
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return hours[row] as String
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedRow = 2 + row
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 36.0
}
}
| 7821d02db660e20a3dfdec9ea774cf5e | 44.966057 | 211 | 0.598466 | false | false | false | false |
yar1vn/Swiftilities | refs/heads/master | Swiftilities/Swiftilities/Cache.swift | mit | 1 | //
// Cache.swift
// Switiflities
//
// Created by Yariv on 1/6/15.
// Copyright (c) 2015 Yariv. All rights reserved.
//
import Foundation
struct Cache {
var maxSize = 10
var count: Int { return _cache.count }
var first: String? { return _cache.first }
var last: String? { return _cache.last }
private var _cache = [String]()
init(objects: [String]? = nil) {
_cache = objects ?? []
}
subscript(index: Int) -> String {
get { return _cache[index] }
set { _cache[index] = newValue }
}
mutating func append(object: String) -> String {
// prevent duplicates
if let index = find(_cache, object) {
_cache.removeAtIndex(index)
}
_cache.insert(object, atIndex: 0)
// enforce max size
if _cache.count > maxSize {
_cache.removeLast()
}
return object
}
mutating func removeAll() {
_cache.removeAll()
}
}
extension Cache: Serializable {
func toJSON() -> JSON {
return _cache
}
static func fromJSON(json: JSON) -> Cache? {
if let objects = json as? [String] {
return Cache(objects: objects)
}
return nil
}
} | 97a197c5a8f1f0b0bb2246965aa1f844 | 18.491525 | 50 | 0.590949 | false | false | false | false |
Adlai-Holler/RACReddit | refs/heads/master | RACReddit/SubredditEntriesViewController.swift | mit | 1 | //
// SubredditEntriesViewController.swift
// RACReddit
//
// Created by Adlai Holler on 10/31/15.
// Copyright © 2015 adlai. All rights reserved.
//
import UIKit
import SafariServices
import ReactiveCocoa
final class SubredditEntriesViewController: UITableViewController, UITextFieldDelegate {
var data: [RedditPost] = []
var currentSubredditName: String?
var currentFetchDisposable: Disposable?
@IBOutlet weak var titleTextField: UITextField!
deinit {
currentFetchDisposable?.dispose()
}
override func viewDidLoad() {
super.viewDidLoad()
titleTextField.becomeFirstResponder()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellID", forIndexPath: indexPath)
cell.textLabel?.text = data[indexPath.item].title
return cell
}
// MARK: - Navigation
/// When they select a post, create a Safari view controller and push it.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url = data[indexPath.row].url
let vc = SFSafariViewController(URL: url)
showViewController(vc, sender: self)
}
// MARK: - Handling the Text Field
/// If they tap the return key, dismiss the field.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.endEditing(false)
return true
}
/// When they finish editing, if our subreddit name has changed, do a load.
func textFieldDidEndEditing(textField: UITextField) {
if textField.text != currentSubredditName {
currentSubredditName = textField.text
loadNewData()
}
}
/// Cancel any existing load and load the data for the current subreddit name.
private func loadNewData() {
// Make sure we have a current subreddit name
guard let currentSubredditName = currentSubredditName else { return }
// Dispose of our current fetch if needed.
currentFetchDisposable?.dispose()
RedditPost
// Create a signal producer.
.fetchPostsForSubredditName(currentSubredditName)
// Switch events onto UI scheduler (main thread).
.observeOn(UIScheduler())
// Start the signal producer – produce a signal and listen to its events.
.start {[weak self] event in
self?.handleFetchEventForSubredditName(currentSubredditName, event: event)
}
}
/// We will call this on the main thread for any fetch event that comes through
private func handleFetchEventForSubredditName(name: String, event: Event<[RedditPost], NSError>) {
switch event {
case let .Next(posts):
NSLog("View controller received posts: \(posts)")
data = posts
tableView.reloadData()
case let .Failed(error):
NSLog("Failed to fetch posts for subreddit: \(name) with error: \(error)")
default: ()
}
}
}
| 32fecbbe8538457523b6d60bc4f094a0 | 28.91 | 118 | 0.732197 | false | false | false | false |
arsonik/OrangeTv | refs/heads/master | OrangeTv/OrangeTv.swift | mit | 1 | //
// OrangeTv.swift
// OrangeTv
//
// Created by Florian Morello on 06/11/14.
// Copyright (c) 2014 Florian Morello. All rights reserved.
// http://lsm-rendezvous040413.orange.fr/API/?api_token=be906750a3cd20d6ddb47ec0b50e7a68&output=json&withChannels=1 ??
// http://ip_livebox_tv:8080/remoteControl/cmd?operation=09&epg_id=id_de_la_chaîne&uui=1
// http://wiki.queret.net/docs/multimedia/orangetv
//
import Foundation
import Alamofire
class OrangeTv {
let host:String
let remoteControlCmd:String
init(host:String){
self.host = host
self.remoteControlCmd = "http://\(self.host):8080/remoteControl/cmd"
}
func sendCommand(command:OrangeTv.Command){
return self.sendKey("\(command.code)")
}
func setChannel(channel:OrangeTv.Channel){
return self.send(["operation": "09", "epg_id": channel.epgId, "uui": 1])
}
private func sendKey(cmd:String){
return self.send(["operation": 10, "key": cmd, "mode": OrangeTv.Mode.Press.code])
}
private func send(params:[String:AnyObject]!){
Alamofire.request(.GET, self.remoteControlCmd, parameters: params).responseJSON { (request:NSURLRequest, response:NSHTTPURLResponse?, result:AnyObject?, error:NSError?) -> Void in
if let dico = result as? [String: AnyObject] {
if let result = dico["result"] as? [String: AnyObject] {
}
}
}
}
func tv() {
Alamofire.request(.GET, "http://lsm-rendezvous040413.orange.fr/API/", parameters: ["api_token": "be906750a3cd20d6ddb47ec0b50e7a68", "output": "json", "withChannels": 1]).responseJSON { (request:NSURLRequest, response:NSHTTPURLResponse?, result:AnyObject?, error:NSError?) -> Void in
if let dico = result as? [String: AnyObject] {
if let channels = dico["channels"]?["channel"] as? [[String: AnyObject]] {
for channelData in channels {
OrangeTv.Channel(data: channelData)
}
}
if let diffusions = dico["diffusions"]?["diffusion"] as? [[String: AnyObject]] {
println("Diffusions \(diffusions.count)")
}
}
}
}
func setChannel(code:Int){
for c in "\(code)" {
var key:OrangeTv.Command!
if c == "0" {
key = OrangeTv.Command.N0
}
else if c == "1" {
key = OrangeTv.Command.N1
}
else if c == "2" {
key = OrangeTv.Command.N2
}
else if c == "3" {
key = OrangeTv.Command.N3
}
else if c == "4" {
key = OrangeTv.Command.N4
}
else if c == "5" {
key = OrangeTv.Command.N5
}
else if c == "6" {
key = OrangeTv.Command.N6
}
else if c == "7" {
key = OrangeTv.Command.N7
}
else if c == "8" {
key = OrangeTv.Command.N8
}
else if c == "9" {
key = OrangeTv.Command.N9
}
self.sendCommand(key)
}
}
// MARK: Mode
enum Mode {
case Press
case LongPress
case Release
var code : Int {
switch self {
case .Press:
return 0
case .LongPress:
return 1
case .Release:
return 2
}
}
}
// MARK: Commands
enum Command {
case Power
case N0
case N1
case N2
case N3
case N4
case N5
case N6
case N7
case N8
case N9
case ChannelUp
case ChannelDown
case VolumeUp
case VolumeDown
case Mute
case Up
case Down
case Left
case Right
case Ok
case Back
case Menu
case PlayPause
case FastBackward
case FastForward
case Rec
case Vod
var code:Int {
switch self {
case .Power:
return 116
case .N0:
return 512
case .N1:
return 513
case .N2:
return 514
case .N3:
return 515
case .N4:
return 516
case .N5:
return 517
case .N6:
return 518
case .N7:
return 519
case .N8:
return 520
case .N9:
return 521
case .ChannelUp:
return 402
case .ChannelDown:
return 403
case .VolumeUp:
return 115
case .VolumeDown:
return 114
case .Mute:
return 113
case .Up:
return 103
case .Down:
return 108
case .Left:
return 105
case .Right:
return 116
case .Ok:
return 352
case .Back:
return 158
case .Menu:
return 139
case .PlayPause:
return 164
case .FastBackward:
return 168
case .FastForward:
return 159
case .Rec:
return 167
case .Vod:
return 393
}
}
}
// MARK: Channel
class Channel {
let id:Int! // 78,
let blendedTV:Bool // 0,
let imageUrl:NSURL // http://media.programme-tv.orange.fr/Images/Chaines/415.gif
let htag:String // #nauticalchannel
let image:String // nauticalchannel.png
let tvIndex:Int! // 95
let epgId:Int! // 415
let name:String // Nautical Channel
init(data:[String:AnyObject]){
self.blendedTV = data["blendedTV"] as String == "1"
self.imageUrl = NSURL(string: data["imageUrl"] as String)!
self.id = (data["id"] as String!)?.toInt()
self.htag = data["htag"] as String
self.image = data["image"] as String
self.tvIndex = (data["tvIndex"] as String!).toInt()
self.epgId = (data["epgId"] as String!)?.toInt()
self.name = data["name"] as String
}
}
} | 73b165a06a598d62ae225e67f1d3e892 | 20.140426 | 284 | 0.629555 | false | false | false | false |
Ehrippura/firefox-ios | refs/heads/master | Client/Frontend/Browser/HistoryStateHelper.swift | mpl-2.0 | 8 | /* 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 WebKit
protocol HistoryStateHelperDelegate: class {
func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab)
}
// This tab helper is needed for injecting a user script into the
// WKWebView that intercepts calls to `history.pushState()` and
// `history.replaceState()` so that the BrowserViewController is
// notified when the user navigates a single-page web application.
class HistoryStateHelper: TabHelper {
weak var delegate: HistoryStateHelperDelegate?
fileprivate weak var tab: Tab?
required init(tab: Tab) {
self.tab = tab
if let path = Bundle.main.path(forResource: "HistoryStateHelper", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "historyStateHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let tab = tab {
DispatchQueue.main.async {
self.delegate?.historyStateHelper(self, didPushOrReplaceStateInTab: tab)
}
}
}
class func name() -> String {
return "HistoryStateHelper"
}
}
| 509b428f017b46766ea8249b57376fea | 39.222222 | 141 | 0.69558 | false | false | false | false |
athiercelin/Localizations | refs/heads/master | Localizations/Models/File.swift | mit | 1 | //
// File.swift
// Localizations
//
// Created by Arnaud Thiercelin on 2/4/16.
// Copyright © 2016 Arnaud Thiercelin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Cocoa
class File: NSObject {
enum State {
case New
case Edit
case Obselete
case None
}
var state = State.None
var name = ""
var folder = ""
var path = ""
var rawContent = ""
var translations = [Translation] ()
var languageCode: String {
get {
let folderParts = folder.components(separatedBy: ".")
if folderParts.count > 0 {
return folderParts[0]
}
return ""
}
}
override var description: String {
get {
return self.debugDescription
}
}
override var debugDescription: String {
get {
return "Name: \(self.name)\n" +
"Folder: \(self.folder)\n" +
"Path: \(self.path)\n" +
"State: \(self.state)\n"
}
}
}
| f1d9aea630cf2e91b8dc8a748ebcc16b | 27.893939 | 112 | 0.703199 | false | false | false | false |
flypaper0/ethereum-wallet | refs/heads/release/1.1 | ethereum-wallet/Classes/BusinessLayer/Core/Services/Gas/GasService.swift | gpl-3.0 | 1 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Geth
class GasService: GasServiceProtocol {
private let client: GethEthereumClient
private let context: GethContext
private let callMsgBuilder: GasCallMsgBuilder
init(core: EthereumCoreProtocol, callMsgBuilder: GasCallMsgBuilder) {
self.client = core.client
self.context = core.context
self.callMsgBuilder = callMsgBuilder
}
func getSuggestedGasLimit(from: String, to: String, amount: Decimal, settings: SendSettings, result: @escaping (Result<Decimal>) -> Void) {
Ethereum.syncQueue.async { [unowned self] in
do {
let msg = try self.callMsgBuilder.build(from: from, to: to, amount: amount, settings: settings)
var gasLimit: Int64 = 0
try self.client.estimateGas(self.context, msg: msg, gas: &gasLimit)
DispatchQueue.main.async {
result(.success(Decimal(gasLimit)))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
func getSuggestedGasPrice(result: @escaping (Result<Decimal>) -> Void) {
Ethereum.syncQueue.async {
do {
let gasPrice = try self.client.suggestGasPrice(self.context)
DispatchQueue.main.async {
result(.success(Decimal(gasPrice.getString(10))))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
}
| 8e27be526a1ca267061e67dd11380648 | 27.150943 | 141 | 0.640751 | false | false | false | false |
jonbrown21/Seafood-Guide-iOS | refs/heads/master | Seafood Guide/Lingo/ViewControllers/DetailLingoViewController.swift | mit | 1 | // Converted to Swift 5.1 by Swiftify v5.1.26565 - https://objectivec2swift.com/
//
// DetailLingoViewController.swift
// Seafood Guide
//
// Created by Jon Brown on 9/2/14.
// Copyright (c) 2014 Jon Brown Designs. All rights reserved.
//
import MessageUI
import ProgressHUD
import UIKit
@objcMembers
class DetailLingoViewController: UITableViewController, UIWebViewDelegate, MFMailComposeViewControllerDelegate {
var str = ""
var item: Lingo?
override init(style: UITableView.Style) {
super.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = item?.titlenews
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if indexPath.section == 0 {
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType1")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CellType1")
}
cell?.textLabel?.text = item?.titlenews
cell?.selectionStyle = .none
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType2")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CellType2")
}
cell?.textLabel?.text = item?.descnews
cell?.textLabel?.lineBreakMode = .byWordWrapping
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.font = UIFont(name: "Helvetica", size: 17.0)
cell?.selectionStyle = .none
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType6")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "CellType6")
}
cell?.textLabel?.text = "Email to a friend"
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
return cell!
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
if indexPath.row == 0 {
sendEmail()
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 1 {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
let attributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
let textRect = item?.descnews?.boundingRect(with: CGSize(width: 290 - (10 * 2), height: 200000.0), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let height = Float(textRect?.size.height ?? 0.0)
return CGFloat(height + (2 * 2))
}
return 44
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Lingo Information"
} else if section == 1 {
return "Share"
}
return nil
}
override func viewDidAppear(_ animated: Bool) {
navigationItem.hidesBackButton = false
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
ProgressHUD.showError("Email Not Sent")
case .saved:
ProgressHUD.showSuccess("Email Saved!")
case .sent:
ProgressHUD.showSuccess("Email Sent!")
case .failed:
ProgressHUD.showError("Email Not Sent")
default:
ProgressHUD.showError("Email Not Sent")
}
dismiss(animated: true)
}
func sendEmail() {
str = item?.descnews ?? ""
str = (str as NSString).substring(to: min(1165, str.count))
let one = item?.titlenews
let two = item?.descnews
let All = "Fish Name: \(one ?? "")\n\nType: \(two ?? "")\n\n\nDescription:\n\(str)"
if MFMailComposeViewController.canSendMail() {
let mailer = MFMailComposeViewController()
mailer.mailComposeDelegate = self
mailer.setSubject("Food & Water Watch - Check This Out: \(one ?? "")")
let toRecipients = [config.getMail()]
mailer.setToRecipients(toRecipients)
let emailBody = All
mailer.setMessageBody(emailBody, isHTML: false)
present(mailer, animated: true)
} else {
let alert = UIAlertController(title: "Failure", message: "Your device doesn't support the composer sheet", preferredStyle: .alert)
let noButton = UIAlertAction(title: "Dismiss", style: .default, handler: { action in
//Handle no, thanks button
self.presentedViewController?.dismiss(animated: false)
})
alert.addAction(noButton)
present(alert, animated: true)
}
}
func createButton(withFrame frame: CGRect, andLabel label: String?) -> UIButton? {
let button = UIButton(frame: frame)
button.setTitleShadowColor(UIColor.black, for: .normal)
button.titleLabel?.shadowOffset = CGSize(width: 0, height: -1)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.setTitle(label, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.white.cgColor
button.layer.masksToBounds = true
button.layer.cornerRadius = 4.0 //when radius is 0, the border is a rectangle
button.layer.borderWidth = 1.0
return button
}
func closeView() {
//[self dismissModalViewControllerAnimated:YES];
dismiss(animated: true)
navigationController?.popViewController(animated: true)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| f479c9146953731b1167c672e2b09fae | 31.243243 | 182 | 0.59444 | false | false | false | false |
deuiore/mpv | refs/heads/master | video/out/mac/gl_layer.swift | gpl-2.0 | 13 | /*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
import OpenGL.GL
import OpenGL.GL3
let glVersions: [CGLOpenGLProfile] = [
kCGLOGLPVersion_3_2_Core,
kCGLOGLPVersion_Legacy
]
let glFormatBase: [CGLPixelFormatAttribute] = [
kCGLPFAOpenGLProfile,
kCGLPFAAccelerated,
kCGLPFADoubleBuffer
]
let glFormatSoftwareBase: [CGLPixelFormatAttribute] = [
kCGLPFAOpenGLProfile,
kCGLPFARendererID,
CGLPixelFormatAttribute(UInt32(kCGLRendererGenericFloatID)),
kCGLPFADoubleBuffer
]
let glFormatOptional: [[CGLPixelFormatAttribute]] = [
[kCGLPFABackingStore],
[kCGLPFAAllowOfflineRenderers]
]
let glFormat10Bit: [CGLPixelFormatAttribute] = [
kCGLPFAColorSize,
_CGLPixelFormatAttribute(rawValue: 64),
kCGLPFAColorFloat
]
let glFormatAutoGPU: [CGLPixelFormatAttribute] = [
kCGLPFASupportsAutomaticGraphicsSwitching
]
let attributeLookUp: [UInt32:String] = [
kCGLOGLPVersion_3_2_Core.rawValue: "kCGLOGLPVersion_3_2_Core",
kCGLOGLPVersion_Legacy.rawValue: "kCGLOGLPVersion_Legacy",
kCGLPFAOpenGLProfile.rawValue: "kCGLPFAOpenGLProfile",
UInt32(kCGLRendererGenericFloatID): "kCGLRendererGenericFloatID",
kCGLPFARendererID.rawValue: "kCGLPFARendererID",
kCGLPFAAccelerated.rawValue: "kCGLPFAAccelerated",
kCGLPFADoubleBuffer.rawValue: "kCGLPFADoubleBuffer",
kCGLPFABackingStore.rawValue: "kCGLPFABackingStore",
kCGLPFAColorSize.rawValue: "kCGLPFAColorSize",
kCGLPFAColorFloat.rawValue: "kCGLPFAColorFloat",
kCGLPFAAllowOfflineRenderers.rawValue: "kCGLPFAAllowOfflineRenderers",
kCGLPFASupportsAutomaticGraphicsSwitching.rawValue: "kCGLPFASupportsAutomaticGraphicsSwitching",
]
class GLLayer: CAOpenGLLayer {
unowned var cocoaCB: CocoaCB
var libmpv: LibmpvHelper { get { return cocoaCB.libmpv } }
let displayLock = NSLock()
let cglContext: CGLContextObj
let cglPixelFormat: CGLPixelFormatObj
var needsFlip: Bool = false
var forceDraw: Bool = false
var surfaceSize: NSSize = NSSize(width: 0, height: 0)
var bufferDepth: GLint = 8
enum Draw: Int { case normal = 1, atomic, atomicEnd }
var draw: Draw = .normal
let queue: DispatchQueue = DispatchQueue(label: "io.mpv.queue.draw")
var needsICCUpdate: Bool = false {
didSet {
if needsICCUpdate == true {
update()
}
}
}
var inLiveResize: Bool = false {
didSet {
if inLiveResize {
isAsynchronous = true
}
update(force: true)
}
}
init(cocoaCB ccb: CocoaCB) {
cocoaCB = ccb
(cglPixelFormat, bufferDepth) = GLLayer.createPixelFormat(ccb)
cglContext = GLLayer.createContext(ccb, cglPixelFormat)
super.init()
autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
backgroundColor = NSColor.black.cgColor
if #available(macOS 10.12, *), bufferDepth > 8 {
contentsFormat = .RGBA16Float
}
var i: GLint = 1
CGLSetParameter(cglContext, kCGLCPSwapInterval, &i)
CGLSetCurrentContext(cglContext)
libmpv.initRender()
libmpv.setRenderUpdateCallback(updateCallback, context: self)
libmpv.setRenderControlCallback(cocoaCB.controlCallback, context: cocoaCB)
}
// necessary for when the layer containing window changes the screen
override init(layer: Any) {
guard let oldLayer = layer as? GLLayer else {
fatalError("init(layer: Any) passed an invalid layer")
}
cocoaCB = oldLayer.cocoaCB
surfaceSize = oldLayer.surfaceSize
cglPixelFormat = oldLayer.cglPixelFormat
cglContext = oldLayer.cglContext
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func canDraw(inCGLContext ctx: CGLContextObj,
pixelFormat pf: CGLPixelFormatObj,
forLayerTime t: CFTimeInterval,
displayTime ts: UnsafePointer<CVTimeStamp>?) -> Bool {
if inLiveResize == false {
isAsynchronous = false
}
return cocoaCB.backendState == .initialized &&
(forceDraw || libmpv.isRenderUpdateFrame())
}
override func draw(inCGLContext ctx: CGLContextObj,
pixelFormat pf: CGLPixelFormatObj,
forLayerTime t: CFTimeInterval,
displayTime ts: UnsafePointer<CVTimeStamp>?) {
needsFlip = false
forceDraw = false
if draw.rawValue >= Draw.atomic.rawValue {
if draw == .atomic {
draw = .atomicEnd
} else {
atomicDrawingEnd()
}
}
updateSurfaceSize()
libmpv.drawRender(surfaceSize, bufferDepth, ctx)
if needsICCUpdate {
needsICCUpdate = false
cocoaCB.updateICCProfile()
}
}
func updateSurfaceSize() {
var dims: [GLint] = [0, 0, 0, 0]
glGetIntegerv(GLenum(GL_VIEWPORT), &dims)
surfaceSize = NSSize(width: CGFloat(dims[2]), height: CGFloat(dims[3]))
if NSEqualSizes(surfaceSize, NSZeroSize) {
surfaceSize = bounds.size
surfaceSize.width *= contentsScale
surfaceSize.height *= contentsScale
}
}
func atomicDrawingStart() {
if draw == .normal {
NSDisableScreenUpdates()
draw = .atomic
}
}
func atomicDrawingEnd() {
if draw.rawValue >= Draw.atomic.rawValue {
NSEnableScreenUpdates()
draw = .normal
}
}
override func copyCGLPixelFormat(forDisplayMask mask: UInt32) -> CGLPixelFormatObj {
return cglPixelFormat
}
override func copyCGLContext(forPixelFormat pf: CGLPixelFormatObj) -> CGLContextObj {
contentsScale = cocoaCB.window?.backingScaleFactor ?? 1.0
return cglContext
}
let updateCallback: mpv_render_update_fn = { (ctx) in
let layer: GLLayer = unsafeBitCast(ctx, to: GLLayer.self)
layer.update()
}
override func display() {
displayLock.lock()
let isUpdate = needsFlip
super.display()
CATransaction.flush()
if isUpdate && needsFlip {
CGLSetCurrentContext(cglContext)
if libmpv.isRenderUpdateFrame() {
libmpv.drawRender(NSZeroSize, bufferDepth, cglContext, skip: true)
}
}
displayLock.unlock()
}
func update(force: Bool = false) {
if force { forceDraw = true }
queue.async {
if self.forceDraw || !self.inLiveResize {
self.needsFlip = true
self.display()
}
}
}
class func createPixelFormat(_ ccb: CocoaCB) -> (CGLPixelFormatObj, GLint) {
var pix: CGLPixelFormatObj?
var depth: GLint = 8
var err: CGLError = CGLError(rawValue: 0)
let swRender = ccb.libmpv.macOpts.cocoa_cb_sw_renderer
if swRender != 1 {
(pix, depth, err) = GLLayer.findPixelFormat(ccb)
}
if (err != kCGLNoError || pix == nil) && swRender != 0 {
(pix, depth, err) = GLLayer.findPixelFormat(ccb, software: true)
}
guard let pixelFormat = pix, err == kCGLNoError else {
ccb.log.sendError("Couldn't create any CGL pixel format")
exit(1)
}
return (pixelFormat, depth)
}
class func findPixelFormat(_ ccb: CocoaCB, software: Bool = false) -> (CGLPixelFormatObj?, GLint, CGLError) {
var pix: CGLPixelFormatObj?
var err: CGLError = CGLError(rawValue: 0)
var npix: GLint = 0
for ver in glVersions {
var glBase = software ? glFormatSoftwareBase : glFormatBase
glBase.insert(CGLPixelFormatAttribute(ver.rawValue), at: 1)
var glFormat = [glBase]
if (ccb.libmpv.macOpts.cocoa_cb_10bit_context == 1) {
glFormat += [glFormat10Bit]
}
glFormat += glFormatOptional
if (ccb.libmpv.macOpts.macos_force_dedicated_gpu == 0) {
glFormat += [glFormatAutoGPU]
}
for index in stride(from: glFormat.count-1, through: 0, by: -1) {
let format = glFormat.flatMap { $0 } + [_CGLPixelFormatAttribute(rawValue: 0)]
err = CGLChoosePixelFormat(format, &pix, &npix)
if err == kCGLBadAttribute || err == kCGLBadPixelFormat || pix == nil {
glFormat.remove(at: index)
} else {
let attArray = format.map({ (value: _CGLPixelFormatAttribute) -> String in
return attributeLookUp[value.rawValue] ?? String(value.rawValue)
})
ccb.log.sendVerbose("Created CGL pixel format with attributes: " +
"\(attArray.joined(separator: ", "))")
return (pix, glFormat.contains(glFormat10Bit) ? 16 : 8, err)
}
}
}
let errS = String(cString: CGLErrorString(err))
ccb.log.sendWarning("Couldn't create a " +
"\(software ? "software" : "hardware accelerated") " +
"CGL pixel format: \(errS) (\(err.rawValue))")
if software == false && ccb.libmpv.macOpts.cocoa_cb_sw_renderer == -1 {
ccb.log.sendWarning("Falling back to software renderer")
}
return (pix, 8, err)
}
class func createContext(_ ccb: CocoaCB, _ pixelFormat: CGLPixelFormatObj) -> CGLContextObj {
var context: CGLContextObj?
let error = CGLCreateContext(pixelFormat, nil, &context)
guard let cglContext = context, error == kCGLNoError else {
let errS = String(cString: CGLErrorString(error))
ccb.log.sendError("Couldn't create a CGLContext: " + errS)
exit(1)
}
return cglContext
}
}
| 209136532d07df0a1ba9a70bbe4136ca | 32.701863 | 113 | 0.609289 | false | false | false | false |
Tuslareb/JBDatePicker | refs/heads/master | JBDatePicker/Classes/JBDatePickerEnums.swift | mit | 2 | //
// JBDatePickerEnums.swift
// JBDatePicker
//
// Created by Joost van Breukelen on 09-10-16.
// Copyright © 2016 Joost van Breukelen. All rights reserved.
//
import UIKit
enum MonthViewIdentifier: Int { case previous, presented, next }
enum JBScrollDirection { case none, toNext, toPrevious }
//In a calendar, day, week, weekday, month, and year numbers are generally 1-based. So Sunday is 1.
public enum JBWeekDay: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday }
public enum JBSelectionShape { case circle, square, roundedRect }
public enum JBFontSize { case verySmall, small, medium, large, veryLarge }
//only for debugging
func randomColor() -> UIColor{
let red = CGFloat(randomInt(min: 0, max: 255)) / 255
let green = CGFloat(randomInt(min: 0, max: 255)) / 255
let blue = CGFloat(randomInt(min: 0, max: 255)) / 255
let randomColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
return randomColor
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
func randomFloat(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
| 2879ed980592330c773857b269c567c4 | 32.555556 | 102 | 0.694536 | false | false | false | false |
CoolCodeFactory/Antidote | refs/heads/master | AntidoteArchitectureExample/UIWindow+Extensions.swift | mit | 1 | //
// UIWindow+Extensions.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
extension UIWindow {
func setRootViewController(_ viewController: UIViewController, animated: Bool) {
if animated {
// NavBar Blink - http://stackoverflow.com/a/29235480/2640551
guard let rootViewController = rootViewController else { return }
let snapshotView = rootViewController.view.snapshotView(afterScreenUpdates: true)
self.rootViewController = viewController
viewController.view.addSubview(snapshotView!)
UIView.animate(withDuration: kDefaultAnimationDuration, delay: 0.0, options: [.curveEaseOut], animations: {
snapshotView?.alpha = 0.0
}, completion: { (finished) in
snapshotView?.removeFromSuperview()
})
} else {
self.rootViewController = viewController
}
}
}
| b1c1cbdd26c19db192f27e00e297d3a4 | 31.666667 | 119 | 0.624304 | false | false | false | false |
lucdion/aide-devoir | refs/heads/master | sources/AideDevoir/Classes/Helpers/GeometryHelpers.swift | apache-2.0 | 1 | //
// GeometryHelpers.swift
//
import UIKit
extension UIScrollView {
func insetSetTop(_ top: CGFloat) {
var inset = self.contentInset
inset.top = top
contentInset = inset
}
func insetSetBottom(_ bottom: CGFloat) {
var inset = self.contentInset
inset.bottom = bottom
contentInset = inset
}
}
| 623a88c240211a9554c99f2977156f27 | 18.888889 | 44 | 0.608939 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/UIScrollViewDemo/UIScrollViewDemo/DayPickerView.swift | mit | 1 | //
// DayPickerView.swift
// UIScrollViewDemo
//
// Created by 伯驹 黄 on 2017/6/19.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
private let itemSide: CGFloat = 75
private let padding: CGFloat = 40
extension CGSize {
var rect: CGRect {
return CGRect(origin: .zero, size: self)
}
var flatted: CGSize {
return CGSize(width: flat(width), height: flat(height))
}
}
class DayPicker: UIView {
fileprivate var items: [String]!
private lazy var collectionView: UICollectionView = {
let layout = RulerLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: itemSide, height: itemSide)
layout.minimumLineSpacing = padding
layout.usingScale = true
let collectionView = UICollectionView(frame: self.frame.size.rect, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.white
return collectionView
}()
convenience init(origin: CGPoint, items: [String]) {
self.init(frame: CGRect(origin: origin, size: CGSize(width: UIScreen.main.bounds.width, height: 100)))
self.items = items
backgroundColor = UIColor.white
addSubview(collectionView)
collectionView.register(DayPickerCell.self, forCellWithReuseIdentifier: "cellID")
}
}
extension DayPicker: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
(cell as? DayPickerCell)?.text = items[indexPath.row]
return cell
}
}
extension DayPicker: UICollectionViewDelegate {}
class DayPickerCell: UICollectionViewCell {
private lazy var textLayer: CXETextLayer = {
let textLayer = CXETextLayer()
textLayer.frame = self.bounds
textLayer.bounds = self.bounds
textLayer.alignmentMode = .center
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.backgroundColor = UIColor.red.cgColor
textLayer.cornerRadius = self.bounds.width / 2
return textLayer
}()
var text: String? {
didSet {
textLayer.string = text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.layer.addSublayer(textLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CXETextLayer: CATextLayer {
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
}
required init(coder aDecoder: NSCoder) {
super.init(layer: aDecoder)
}
override func draw(in ctx: CGContext) {
let height = bounds.height
let fontSize = self.fontSize
let yDiff = (height - fontSize) / 2 - fontSize / 10
ctx.saveGState()
ctx.translateBy(x: 0.0, y: yDiff)
super.draw(in: ctx)
ctx.restoreGState()
}
}
| 0f3c691b1049a43ff25875069517d4a5 | 27.91453 | 121 | 0.658883 | false | false | false | false |
coolster01/PokerTouch | refs/heads/master | PokerTouch/Hand.swift | apache-2.0 | 1 | //
// Hand.swift
// PokerTouch
//
// Created by Subhi Sbahi on 5/21/17.
// Copyright © 2017 Rami Sbahi. All rights reserved.
//
import Foundation
class Hand {
var valuesInvolved: [Int] = [] // used to determine ties
/* royal flush
* just put in a zero
* straight flush / straight
* returns highest value in the straight - not other cards
* four/three of kind / one pair
* returns value involved in pair, then high --> low
* flush
* returns the five cards in flush from high --> low, then the last two values high --> low
* two pair
* higher pair, lower pair, remaining cards
* full house
* 3 of a kind, pair, remaining
* none (high card)
* organize high --> low
*/
var outOfIt: [Int] = []
var cardList: [Card] = []
var score: Int = 0
init(eCardList: [Card])
{
cardList = eCardList
self.sortCards()
let oldScore: Int = self.setScore()
var oldValues: [Int] = []
for current in valuesInvolved
{
oldValues.append(current)
}
for currentCard in cardList
{
currentCard.makeAceLow()
}
self.sortCards()
if(self.setScore() <= oldScore) // not any better
{
for currentCard in cardList
{
currentCard.makeAceHigh()
}
score = oldScore
valuesInvolved = oldValues
}
// if it was improved, it will stay that way
self.sortCards()
}
/**
* Insertion sort
*/
func sortCards()
{
var key: Int = 0
for index in 1..<cardList.count
{
let currentCard: Card = cardList[index]
key = index
while(key > 0 && cardList[key - 1].compareTo(otherCard: cardList[index]) < 0)
{
key -= 1
}
cardList.insert(currentCard, at: key)
cardList.remove(at: index + 1)
}
}
func setScore() -> Int
{
if(self.isRoyalFlush())
{
score = 9
}
else if(self.isStraightFlush())
{
score = 8
}
else if(self.isFourOfKind())
{
score = 7
}
else if(self.isFullHouse())
{
score = 6
}
else if(self.isFlush())
{
score = 5
}
else if(self.isStraight())
{
score = 4
}
else if(self.isThreeOfKind())
{
score = 3
}
else if(self.isTwoPair())
{
score = 2
}
else if(self.isPair())
{
score = 1
}
else
{
score = 0
valuesInvolved.removeAll() // should already be clear, but just double-checking
for current in cardList
{
valuesInvolved.append(current.myValue)
}
}
return score
}
func isPair() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] >= 2)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func isFullHouse() -> Bool
{
if(isThreeOfKind() && isTwoPair()) // all full houses are a two pair and a three of kind
{
return true
}
return false
}
func isTwoPair() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
var count: Int = 0
var values: [Int] = []
for index in (1...14).reversed()
{
if(cards[index] >= 2)
{
count += 1
if(cards[index] >= 3) // makes full house, needs priority
{
values.insert(index, at: 0)
}
else
{
values.append(index)
}
}
}
var numAdded: Int = 0
if(count >= 2) // at least 2 pairs
{
valuesInvolved.removeAll()
for value in values
{
if(numAdded <= 1) // 2 pairs have not been accounted for yet
{
valuesInvolved.append(value)
numAdded += 1
}
}
for current in cardList
{
let currentValue: Int = current.myValue;
if(!valuesInvolved.contains(currentValue))
{
valuesInvolved.append(currentValue)
}
}
return true
}
return false
}
func isThreeOfKind() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] >= 3)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func isFourOfKind() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] == 4)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func containsValue(_ val: Int) -> Bool
{
for current in cardList
{
if(current.myValue == val)
{
return true
}
}
return false
}
func containsCard(c: Card) -> Bool
{
for current in cardList
{
if(current.equals(otherCard: c))
{
return true
}
}
return false
}
func isStraightFlush() -> Bool
{
return self.isFlush() && self.isStraight() // will clear and put only highest value involved after flush
}
func isStraight() -> Bool
{
for start in (1...10).reversed()
{
if(self.containsValue(start) && self.containsValue(start+1) && self.containsValue(start+2) && self.containsValue(start+3) && self.containsValue(start+4))
{
valuesInvolved.removeAll()
valuesInvolved.append(start+4) // value of highest card in straight
return true
}
}
return false
}
func isFlush() -> Bool
{
var suits = [Int](repeating: 0, count: 5); // 1 = clubs, 2 = hearts, 3 = spades, 4 = diamonds
for i in 0..<cardList.count
{
suits[cardList[i].getSuitValue()] += 1
}
for j in 1...4
{
if(suits[j] >= 5) // this suit makes a flush
{
valuesInvolved.removeAll()
outOfIt.removeAll()
for index in 0..<cardList.count
{
if(cardList[index].getSuitValue() == j)
{
valuesInvolved.append(cardList[index].myValue) // will add high --> low of flush
}
else
{
outOfIt.append(cardList[index].myValue)
}
}
for out in outOfIt
{
valuesInvolved.append(out)
}
return true
}
}
return false
}
func isRoyalFlush() -> Bool
{
if(self.containsValue(10) && self.containsValue(11) && self.containsValue(12)
&& self.containsValue(13) && self.containsValue(14) && self.isFlush())
{
valuesInvolved.removeAll()
valuesInvolved.append(0)
return true
}
else
{
return false
}
}
func getImages() -> [String]
{
var images: [String] = []
for current in cardList
{
images.append(current.getImage())
}
return images
}
}
| c6f5f51b1b169a3deb554b5c67472463 | 24.278351 | 165 | 0.433524 | false | false | false | false |
airbnb/lottie-ios | refs/heads/master | Sources/Private/CoreAnimation/Layers/InfiniteOpaqueAnimationLayer.swift | apache-2.0 | 2 | // Created by Cal Stephens on 10/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ExpandedAnimationLayer
/// A `BaseAnimationLayer` subclass that renders its background color
/// as if the layer is infinitely large, without affecting its bounds
/// or the bounds of its sublayers
final class InfiniteOpaqueAnimationLayer: BaseAnimationLayer {
// MARK: Lifecycle
override init() {
super.init()
addSublayer(additionalPaddingLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
super.init(layer: layer)
}
// MARK: Internal
override func layoutSublayers() {
super.layoutSublayers()
masksToBounds = false
additionalPaddingLayer.backgroundColor = backgroundColor
// Scale `additionalPaddingLayer` to be larger than this layer
// by `additionalPadding` at each size, and centered at the center
// of this layer. Since `additionalPadding` is very large, this has
// the affect of making `additionalPaddingLayer` appear infinite.
let scaleRatioX = (bounds.width + (CALayer.veryLargeLayerPadding * 2)) / bounds.width
let scaleRatioY = (bounds.height + (CALayer.veryLargeLayerPadding * 2)) / bounds.height
additionalPaddingLayer.transform = CATransform3DScale(
CATransform3DMakeTranslation(-CALayer.veryLargeLayerPadding, -CALayer.veryLargeLayerPadding, 0),
scaleRatioX,
scaleRatioY,
1)
}
// MARK: Private
private let additionalPaddingLayer = CALayer()
}
| a9647de802c2a26dff5484ca0f7f7aaa | 30.035714 | 102 | 0.729574 | false | false | false | false |
fawadsuhail/weather-app | refs/heads/master | WeatherApp/Network/Router.swift | mit | 1 | //
// Router.swift
// WeatherApp
//
// Created by Fawad Suhail on 4/2/17.
// Copyright © 2017 Fawad Suhail. All rights reserved.
//
import Foundation
import Alamofire
enum Router: URLRequestConvertible {
static let baseURLString = K.Network.BASE_URL
case weather(city: String)
var method: HTTPMethod {
switch self {
case .weather:
return .get
}
}
var path: String {
switch self {
case .weather:
return K.Network.WEATHER_URL
}
}
func asURLRequest() throws -> URLRequest {
let url = try Router.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .weather(let cityName):
let params = ["q": cityName,
"key": K.Network.KEY,
"format": K.Network.FORMAT]
urlRequest = try URLEncoding.default.encode(urlRequest, with: params)
}
return urlRequest
}
}
| 5fdb032e4fc5fedf49030687ca0fd15e | 19.117647 | 75 | 0.610136 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.