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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fgengine/quickly | refs/heads/master | Quickly/ViewControllers/Photos/PhotoItems/QImagePhotoItem.swift | mit | 1 | //
// Quickly
//
public class QImagePhotoItem : IQPhotoItem {
public var isNeedLoad: Bool {
get { return false }
}
public var isLoading: Bool {
get { return false }
}
public var size: CGSize {
return CGSize(width: self._image.width, height: self._image.height)
}
public var image: UIImage? {
get { return UIImage(cgImage: self._image) }
}
private var _observer: QObserver< IQPhotoItemObserver >
private var _image: CGImage
public static func photoItems(data: Data) -> [IQPhotoItem] {
guard let provider = CGDataProvider(data: data as CFData) else { return [] }
guard let imageSource = CGImageSourceCreateWithDataProvider(provider, nil) else { return [] }
var photos: [QImagePhotoItem] = []
for index in 0..<CGImageSourceGetCount(imageSource) {
guard let image = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { continue }
photos.append(QImagePhotoItem(image: image))
}
return photos
}
private init(image: CGImage) {
self._observer = QObserver< IQPhotoItemObserver >()
self._image = image
}
public func add(observer: IQPhotoItemObserver) {
self._observer.add(observer, priority: 0)
}
public func remove(observer: IQPhotoItemObserver) {
self._observer.remove(observer)
}
public func load() {
}
public func draw(context: CGContext, bounds: CGRect, scale: CGFloat) {
context.setFillColor(red: 1, green: 1, blue: 1, alpha: 1)
context.fill(bounds)
context.saveGState()
context.translateBy(x: 0, y: bounds.height)
context.scaleBy(x: 1, y: -1)
context.draw(self._image, in: bounds)
context.restoreGState()
}
}
| 4b58d464f6013d1cdd45acd119d2acc4 | 29.666667 | 104 | 0.616848 | false | false | false | false |
iHunterX/SocketIODemo | refs/heads/master | DemoSocketIO/Classes/RequiredViewController.swift | gpl-3.0 | 1 | //
// RequiredViewController.swift
// DemoSocketIO
//
// Created by Đinh Xuân Lộc on 10/28/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
class RequiredViewController: PAPermissionsViewController,PAPermissionsViewControllerDelegate {
let cameraCheck = PACameraPermissionsCheck()
let locationCheck = PALocationPermissionsCheck()
let microphoneCheck = PAMicrophonePermissionsCheck()
let photoLibraryCheck = PAPhotoLibraryPermissionsCheck()
lazy var notificationsCheck : PAPermissionsCheck = {
if #available(iOS 10.0, *) {
return PAUNNotificationPermissionsCheck()
} else {
return PANotificationsPermissionsCheck()
}
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.delegate = self
let permissions = [
PAPermissionsItem.itemForType(.location, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.microphone, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.photoLibrary, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.notifications, reason: "Required to send you great updates")!,
PAPermissionsItem.itemForType(.camera, reason: PAPermissionDefaultReason)!]
let handlers = [
PAPermissionsType.location.rawValue: self.locationCheck,
PAPermissionsType.microphone.rawValue :self.microphoneCheck,
PAPermissionsType.photoLibrary.rawValue: self.photoLibraryCheck,
PAPermissionsType.camera.rawValue: self.cameraCheck,
PAPermissionsType.notifications.rawValue: self.notificationsCheck
]
self.setupData(permissions, handlers: handlers)
// Do any additional setup after loading the view.
self.tintColor = UIColor.white
self.backgroundImage = #imageLiteral(resourceName: "background")
self.useBlurBackground = false
self.titleText = "iSpam"
self.detailsText = "Please enable the following"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func permissionsViewControllerDidContinue(_ viewController: PAPermissionsViewController) {
if let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "MainController") as? UINavigationController {
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let presentingViewController: UIViewController! = self.presentingViewController
//
// self.dismiss(animated: false) {
// // go back to MainMenuView as the eyes of the user
// presentingViewController.dismiss(animated: false, completion: {
//// self.present(loginVC, animated: true, completion: nil)
// })
// }
loginVC.modalTransitionStyle = .crossDissolve
self.present(loginVC, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 632444195f8cc78aa8496f0ace580d4f | 39.213483 | 130 | 0.673931 | false | false | false | false |
pro1polaris/SwiftEssentials | refs/heads/master | SwiftEssentials/SwiftEssentials/_extensions_UIView_PositionContraints.swift | mit | 1 | //
// _extensions_UIView_Position_Constraints.swift
//
// Created by Paul Hopkins on 2017-03-05.
// Modified by Paul Hopkins on 2017-03-22.
// Copyright © 2017 Paul Hopkins. All rights reserved.
//
import UIKit
extension UIView {
// Apply CenterX Position Contraint (constant: 0)
func applyPositionConstraintCenterX(toitem: UIView) {
let centerXConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: toitem, attribute: .centerX, multiplier: 1, constant: 0)
toitem.addConstraint(centerXConstraint)
}
// Apply CenterY Position Constraint (constant: 0)
func applyPositionConstraintCenterY(toitem: UIView) {
let centerYConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: toitem, attribute: .centerY, multiplier: 1, constant: 0)
toitem.addConstraint(centerYConstraint)
}
// Apply All Four Position Constraints (constant: 0)
func applyPositionConstraintAll(toitem: UIView) {
self.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0)
toitem.addConstraint(topConstraint)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0)
toitem.addConstraint(bottomConstraint)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0)
toitem.addConstraint(leftConstraint)
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0)
toitem.addConstraint(rightConstraint)
}
// Apply Top Position Constraint (constant: 0)
func applyPositionConstraintTop(toitem: UIView) {
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0)
toitem.addConstraint(topConstraint)
}
// Apply Top Position Constraint (constant: Int)
func applyPositionConstraintTop_Constant(toitem: UIView, constant: Int) {
let topConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(topConstraint)
}
// Apply Bottom Position Constraint (constant: 0)
func applyPositionConstraintBottom(toitem: UIView) {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0)
toitem.addConstraint(bottomConstraint)
}
// Apply Bottom Position Constraint (constant: Int)
func applyPositionConstraintBottom_Constant(toitem: UIView, constant: Int) {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(bottomConstraint)
}
// Apply Left Position Constraint (constant: 0)
func applyPositionConstraintLeft(toitem: UIView) {
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0)
toitem.addConstraint(leftConstraint)
}
// Apply Left Position Constraint (constant: Int)
func applyPositionConstraintLeft_Constant(toitem: UIView, constant: Int) {
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(leftConstraint)
}
// Apply Right Position Constraint (constant: 0)
func applyPositionConstraintRight(toitem: UIView) {
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0)
toitem.addConstraint(rightConstraint)
}
//Apply Right Position Constraint (constant: Int)
func applyPositionConstraintRight_Constant(toitem: UIView, constant: Int) {
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(rightConstraint)
}
}
| 3ceb18618fda3c9294a4c47febd68233 | 53.482353 | 177 | 0.727057 | false | false | false | false |
zwaldowski/ParksAndRecreation | refs/heads/master | Latest/Keyboard Layout Guide/KeyboardLayoutGuide/KeyboardLayoutGuide.swift | mit | 1 | //
// KeyboardLayoutGuide.swift
// KeyboardLayoutGuide
//
// Created by Zachary Waldowski on 8/23/15.
// Copyright © 2015-2016. Licensed under MIT. Some rights reserved.
//
import UIKit
/// A keyboard layout guide may be used as an item in Auto Layout or for its
/// layout anchors.
public final class KeyboardLayoutGuide: UILayoutGuide {
private static let didUpdate = Notification.Name(rawValue: "KeyboardLayoutGuideDidUpdateNotification")
// MARK: Lifecycle
private let notificationCenter: NotificationCenter
private func commonInit() {
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardDidChangeFrame, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteAncestorGuideUpdate), name: KeyboardLayoutGuide.didUpdate, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteTextFieldDidEndEditing), name: .UITextFieldTextDidEndEditing, object: nil)
}
public required init?(coder aDecoder: NSCoder) {
self.notificationCenter = .default
super.init(coder: aDecoder)
commonInit()
}
fileprivate init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
commonInit()
}
override convenience init() {
self.init(notificationCenter: .default)
}
// MARK: Public API
/// If assigned, the `contentInsets` of the view will be adjusted to match
/// the keyboard insets.
///
/// It is not necessary to track the scroll view that is managed as the
/// primary view of a `UITableViewController` or
/// `UICollectionViewController`.
public weak var adjustContentInsetsInScrollView: UIScrollView?
// MARK: Actions
private var keyboardBottomConstraint: NSLayoutConstraint?
private var lastScrollViewInsetDelta: CGFloat = 0
private var currentAnimator: UIViewPropertyAnimator?
override public var owningView: UIView? {
didSet {
guard owningView !== oldValue else { return }
keyboardBottomConstraint?.isActive = false
keyboardBottomConstraint = nil
guard let view = owningView else { return }
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: trailingAnchor),
topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor), {
let constraint = view.bottomAnchor.constraint(equalTo: bottomAnchor)
constraint.priority = UILayoutPriority(rawValue: 999.5)
self.keyboardBottomConstraint = constraint
return constraint
}()
])
}
}
private func update(for info: KeyboardInfo, in view: UIView, animatingWith animator: UIViewPropertyAnimator?) {
keyboardBottomConstraint?.constant = info.overlap(in: view)
if let animator = animator, !view.isEffectivelyDisappearing {
animator.addAnimations {
info.adjustForOverlap(in: self.adjustContentInsetsInScrollView, lastAppliedInset: &self.lastScrollViewInsetDelta)
view.layoutIfNeeded()
}
} else {
info.adjustForOverlap(in: adjustContentInsetsInScrollView, lastAppliedInset: &lastScrollViewInsetDelta)
}
}
// MARK: - Notifications
@objc
private func noteUpdateKeyboard(_ note: Notification) {
let info = KeyboardInfo(userInfo: note.userInfo)
guard let view = owningView else { return }
let animator = currentAnimator ?? {
UIView.performWithoutAnimation(view.layoutIfNeeded)
let animator = info.makeAnimator()
animator.addCompletion { [weak self] _ in
self?.currentAnimator = nil
}
self.currentAnimator = animator
return animator
}()
update(for: info, in: view, animatingWith: animator)
NotificationCenter.default.post(name: KeyboardLayoutGuide.didUpdate, object: self, userInfo: note.userInfo)
animator.startAnimation()
}
@objc
private func noteAncestorGuideUpdate(note: Notification) {
guard let view = owningView, let ancestor = note.object as? KeyboardLayoutGuide, let ancestorView = ancestor.owningView,
view !== ancestorView, view.isDescendant(of: ancestorView) else { return }
let info = KeyboardInfo(userInfo: note.userInfo)
update(for: info, in: view, animatingWith: ancestor.currentAnimator)
}
// <rdar://problem/30978412> UITextField contents animate in when layout performed during editing end
@objc
private func noteTextFieldDidEndEditing(_ note: Notification) {
guard let view = owningView, let textField = note.object as? UITextField,
view !== textField, textField.isDescendant(of: view), !view.isEffectivelyDisappearing else { return }
UIView.performWithoutAnimation(textField.layoutIfNeeded)
}
}
// MARK: - UIViewController
extension UIViewController {
private static var keyboardLayoutGuideKey = false
/// For unit testing purposes only.
@nonobjc
internal func makeKeyboardLayoutGuide(notificationCenter: NotificationCenter) -> KeyboardLayoutGuide {
assert(isViewLoaded, "This layout guide should not be accessed before the view is loaded.")
let guide = KeyboardLayoutGuide(notificationCenter: notificationCenter)
view.addLayoutGuide(guide)
return guide
}
/// A keyboard layout guide is a rectangle in the layout system representing
/// the area on screen not currently occupied by the keyboard; thus, it is a
/// simplified model for performing layout by avoiding the keyboard.
///
/// Normally, the guide is a rectangle matching the safe area of a view
/// controller's view. When the keyboard is active, its bottom contracts to
/// account for the keyboard. This change is animated alongside the keyboard
/// animation.
///
/// - seealso: KeyboardLayoutGuide
@nonobjc public var keyboardLayoutGuide: KeyboardLayoutGuide {
if let guide = objc_getAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey) as? KeyboardLayoutGuide {
return guide
}
let guide = makeKeyboardLayoutGuide(notificationCenter: .default)
objc_setAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey, guide, .OBJC_ASSOCIATION_ASSIGN)
return guide
}
}
// MARK: -
private struct KeyboardInfo {
let userInfo: [AnyHashable: Any]?
func makeAnimator() -> UIViewPropertyAnimator {
let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0.25
return UIViewPropertyAnimator(duration: duration, timingParameters: UISpringTimingParameters())
}
func overlap(in view: UIView) -> CGFloat {
guard let endFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect,
view.canBeObscuredByKeyboard else { return 0 }
let intersection = view.convert(endFrame, from: UIScreen.main.coordinateSpace).intersection(view.bounds)
guard !intersection.isNull, intersection.maxY == view.bounds.maxY else { return 0 }
var height = intersection.height
if let scrollView = view as? UIScrollView, scrollView.contentInsetAdjustmentBehavior != .never {
height -= view.safeAreaInsets.bottom
}
return max(height, 0)
}
func adjustForOverlap(in scrollView: UIScrollView?, lastAppliedInset: inout CGFloat) {
guard let scrollView = scrollView else { return }
let newOverlap = overlap(in: scrollView)
let delta = newOverlap - lastAppliedInset
lastAppliedInset = newOverlap
scrollView.scrollIndicatorInsets.bottom += delta
scrollView.contentInset.bottom += delta
}
}
| f7566d013cfcc608578962ea3a162622 | 37.99537 | 143 | 0.691915 | false | false | false | false |
longitachi/ZLPhotoBrowser | refs/heads/master | Sources/General/ZLImageNavController.swift | mit | 1 | //
// ZLImageNavController.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/18.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Photos
class ZLImageNavController: UINavigationController {
var isSelectedOriginal: Bool = false
var arrSelectedModels: [ZLPhotoModel] = []
var selectImageBlock: (() -> Void)?
var cancelBlock: (() -> Void)?
deinit {
zl_debugPrint("ZLImageNavController deinit")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ZLPhotoUIConfiguration.default().statusBarStyle
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
navigationBar.barStyle = .black
navigationBar.isTranslucent = true
modalPresentationStyle = .fullScreen
isNavigationBarHidden = true
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 54a8e9bf083d9153bcea8b36211d8a1b | 33.28169 | 82 | 0.700493 | false | false | false | false |
baquiax/ImageProcessor | refs/heads/master | ImageProcessor.playground/Sources/Filters/IncreaseIntensity.swift | mit | 1 | public class IncreaseIntensity : Filter {
var percentage : Double
var color: Colors
public init (increaseFactor v : Double, color c : Colors) {
self.percentage = v
self.color = c
}
func newValue(currentValue: Int) -> UInt8 {
return UInt8(max(0,min(Double(currentValue) * (1 + percentage) , 255)));
}
public func apply(image: RGBAImage) -> RGBAImage {
var pixel : Pixel?
for r in 0...image.height - 1 {
for c in 0...image.width - 1 {
pixel = image.pixels[ image.height * r + c ]
switch self.color {
case Colors.Red:
pixel!.red = newValue(Int(pixel!.red))
case Colors.Green:
pixel!.green = newValue(Int(pixel!.green))
case Colors.Blue:
pixel!.blue = newValue(Int(pixel!.blue))
}
image.pixels[image.height * r + c] = pixel!;
}
}
return image
}
} | df574ad1f846df4a12c2bdfd63b2cf6a | 32.3125 | 80 | 0.486385 | false | false | false | false |
JiriTrecak/Laurine | refs/heads/master | Example/Pods/Warp/Source/WRPObject.swift | mit | 2 | //
// WRPObject.swift
//
// Copyright (c) 2016 Jiri Trecak (http://jiritrecak.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Imports
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Definitions
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extension
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Protocols
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Implementation
open class WRPObject: NSObject {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Setup
override public init() {
super.init()
// No initialization required - nothing to fill object with
}
convenience public init(fromJSON: String) {
if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) {
do {
let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject?
self.init(parameters: jsonObject as! NSDictionary)
} catch let error as NSError {
self.init(parameters: [:])
print ("Error while parsing a json object: \(error.domain)")
}
} else {
self.init(parameters: NSDictionary())
}
}
convenience public init(fromDictionary: NSDictionary) {
self.init(parameters: fromDictionary)
}
required public init(parameters: NSDictionary) {
super.init()
self.preInit()
if self.debugInstantiate() {
NSLog("Object type %@\nParsing using %@", self.self, parameters)
}
self.fillValues(parameters)
self.processClosestRelationships(parameters)
self.postInit()
}
required public init(parameters: NSDictionary, parentObject: WRPObject?) {
super.init()
self.preInit()
if self.debugInstantiate() {
NSLog("Object type %@\nParsing using %@", self.self, parameters)
}
self.fillValues(parameters)
self.processClosestRelationships(parameters, parentObject: parentObject)
self.postInit()
}
open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String) -> [T] {
if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) {
do {
var buffer: [T] = []
let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject?
for jsonDictionary in jsonObject as! NSArray {
let object = T(parameters: jsonDictionary as! NSDictionary)
buffer.append(object)
}
return buffer
} catch let error as NSError {
print ("Error while parsing a json object: \(error.domain)")
return []
}
} else {
return []
}
}
open static func fromArray<T: WRPObject>(_ object: NSArray) -> [T] {
var buffer: [T] = []
for jsonDictionary in object {
let object = T(parameters: jsonDictionary as! NSDictionary)
buffer.append(object)
}
return buffer
}
open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] {
if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) {
do {
var buffer: [WRPObject] = []
let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject?
for object: Any in jsonObject as! NSArray {
if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String {
let type = modelClassTransformer(key)
if let type = type {
let object = type.init(parameters: jsonDictionary)
buffer.append(object)
}
}
}
return buffer as! [T]
} catch let error as NSError {
print ("Error while parsing a json object: \(error.domain)")
return []
}
} else {
return []
}
}
open static func fromArray<T: WRPObject>(_ object: NSArray, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] {
var buffer: [WRPObject] = []
for object: Any in object {
if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String {
let type = modelClassTransformer(key)
if let type = type {
let object = type.init(parameters: jsonDictionary)
buffer.append(object)
}
}
}
return buffer as! [T]
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - User overrides for data mapping
open func propertyMap() -> [WRPProperty] {
return []
}
open func relationMap() -> [WRPRelation] {
return []
}
open func preInit() {
}
open func postInit() {
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
fileprivate func fillValues(_ parameters: NSDictionary) {
for element: WRPProperty in self.propertyMap() {
// Dot convention
self.assignValueForElement(element, parameters: parameters)
}
}
fileprivate func processClosestRelationships(_ parameters: NSDictionary) {
self.processClosestRelationships(parameters, parentObject: nil)
}
fileprivate func processClosestRelationships(_ parameters: NSDictionary, parentObject: WRPObject?) {
for element in self.relationMap() {
self.assignDataObjectForElement(element, parameters: parameters, parentObject: parentObject)
}
}
fileprivate func assignValueForElement(_ element: WRPProperty, parameters: NSDictionary) {
switch element.elementDataType {
// Handle string data type
case .string:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.stringFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle boolean data type
case .bool:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.boolFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle double data type
case .double:
for elementRemoteName in element.remoteNames {
if (self.setValue(.double, value: self.doubleFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle float data type
case .float:
for elementRemoteName in element.remoteNames {
if (self.setValue(.float, value: self.floatFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle int data type
case .int:
for elementRemoteName in element.remoteNames {
if (self.setValue(.int, value: self.intFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle int data type
case .number:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.numberFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle date data type
case .date:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.dateFromParameters(parameters, key: elementRemoteName, format: element.format) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle array data type
case .array:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.arrayFromParameters(parameters, key: elementRemoteName) as AnyObject?,
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
// Handle dictionary data type
case .dictionary:
for elementRemoteName in element.remoteNames {
if (self.setValue(.any, value: self.dictionaryFromParameters(parameters, key: elementRemoteName),
forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break }
}
}
}
@discardableResult
fileprivate func assignDataObjectForElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? {
switch element.relationshipType {
case .toOne:
return self.handleToOneRelationshipWithElement(element, parameters: parameters, parentObject: parentObject)
case .toMany:
self.handleToManyRelationshipWithElement(element, parameters: parameters, parentObject: parentObject)
}
return nil
}
fileprivate func handleToOneRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? {
if let objectData: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? {
if objectData is NSDictionary {
guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else {
return nil
}
// Create object
let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject)
// Set child object to self.property
self.setValue(.any, value: dataObject, forKey: element.localName, optional: element.optional, temporaryOptional: false)
// Set inverse relationship
if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName {
if inverseRelationshipType == .toOne {
dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else if inverseRelationshipType == .toMany {
var objects: [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true)
}
}
return dataObject
} else if objectData is NSNull {
// Set empty object to self.property
self.setValue(.any, value: nil, forKey: element.localName, optional: element.optional, temporaryOptional: false)
return nil
}
}
return nil
}
fileprivate func handleToManyRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) {
if let objectDataPack: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? {
// While the relationship is .ToMany, we can actually add it from single entry
if objectDataPack is NSDictionary {
// Always override local property, there is no inserting allowed
var objects: [WRPObject]? = [WRPObject]()
self.setValue(objects, forKey: element.localName)
guard let classType = self.elementClassType(objectDataPack as! NSDictionary, relationDescriptor: element) else {
return
}
// Create object
let dataObject = self.dataObjectFromParameters(objectDataPack as! NSDictionary, objectType: classType, parentObject: parentObject)
// Set inverse relationship
if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName {
if inverseRelationshipType == .toOne {
dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else if inverseRelationshipType == .toMany {
var objects: [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true)
}
}
// Append new data object to array
objects!.append(dataObject)
// Write new objects back
self.setValue(objects, forKey: element.localName)
// More objects in the same entry
} else if objectDataPack is NSArray {
// Always override local property, there is no inserting allowed
var objects: [WRPObject]? = [WRPObject]()
self.setValue(objects, forKey: element.localName)
// Fill that property with data
for objectData in (objectDataPack as! NSArray) {
// Skip generation of this object, if the class does not exist
guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else {
continue
}
// Create object
let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject)
// Assign inverse relationship
if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName {
if inverseRelationshipType == .toOne {
dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true)
// If the relationship is to .ToMany, then create data pack for that
} else {
var objects: [WRPObject]? = [WRPObject]()
objects?.append(self)
dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true)
}
}
// Append new data
objects!.append(dataObject)
}
// Write new objects back
self.setValue(objects, forKey: element.localName)
// Null encountered, null the output
} else if objectDataPack is NSNull {
self.setValue(nil, forKey: element.localName)
}
}
}
fileprivate func elementClassType(_ element: NSDictionary, relationDescriptor: WRPRelation) -> WRPObject.Type? {
// If there is only one class to pick from (no transform function), return the type
if let type = relationDescriptor.modelClassType {
return type
// Otherwise use transformation function to get object type from string key
} else if let transformer = relationDescriptor.modelClassTypeTransformer, let key = relationDescriptor.modelClassTypeKey {
return transformer(element.object(forKey: key) as! String)
}
// Transformation failed
// TODO: Better error handling
return WRPObject.self
}
@discardableResult
fileprivate func setValue(_ type: WRPPropertyAssignement, value: AnyObject?, forKey key: String, optional: Bool, temporaryOptional: Bool) -> Bool {
if ((optional || temporaryOptional) && value == nil) {
return false
}
if type == .any {
self.setValue(value, forKey: key)
} else if type == .double {
if value is Double {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(value?.doubleValue, forKey: key)
} else {
self.setValue(nil, forKey: key)
}
} else if type == .int {
if value is Int {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(Int32(value as! NSNumber), forKey: key)
} else {
self.setValue(nil, forKey: key)
}
} else if type == .float {
if value is Float {
self.setValue(value as! NSNumber, forKey: key)
} else if value is NSNumber {
self.setValue(value?.floatValue, forKey: key)
} else {
self.setValue(nil, forKey: key)
}
}
return true
}
fileprivate func setDictionary(_ value: Dictionary<AnyKey, AnyKey>?, forKey: String, optional: Bool, temporaryOptional: Bool) -> Bool {
if ((optional || temporaryOptional) && value == nil) {
return false
}
self.setValue((value as AnyObject), forKey: forKey)
return true
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Variable creation
fileprivate func stringFromParameters(_ parameters: NSDictionary, key: String) -> String? {
if let value: NSString = parameters.value(forKeyPath: key) as? NSString {
return value as String
}
return nil
}
fileprivate func numberFromParameters(_ parameters: NSDictionary, key: String) -> NSNumber? {
if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber {
return value as NSNumber
}
return nil
}
fileprivate func intFromParameters(_ parameters: NSDictionary, key: String) -> Int? {
if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber {
return Int(value)
}
return nil
}
fileprivate func doubleFromParameters(_ parameters: NSDictionary, key: String) -> Double? {
if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber {
return Double(value)
}
return nil
}
fileprivate func floatFromParameters(_ parameters: NSDictionary, key: String) -> Float? {
if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber {
return Float(value)
}
return nil
}
fileprivate func boolFromParameters(_ parameters: NSDictionary, key: String) -> Bool? {
if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber {
return Bool(value)
}
return nil
}
fileprivate func dateFromParameters(_ parameters: NSDictionary, key: String, format: String?) -> Date? {
if let value: String = parameters.value(forKeyPath: key) as? String {
// Create date formatter
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: value)
}
return nil
}
fileprivate func arrayFromParameters(_ parameters: NSDictionary, key: String) -> Array<AnyObject>? {
if let value: Array = parameters.value(forKeyPath: key) as? Array<AnyObject> {
return value
}
return nil
}
fileprivate func dictionaryFromParameters(_ parameters: NSDictionary, key: String) -> NSDictionary? {
if let value: NSDictionary = parameters.value(forKeyPath: key) as? NSDictionary {
return value
}
return nil
}
fileprivate func dataObjectFromParameters(_ parameters: NSDictionary, objectType: WRPObject.Type, parentObject: WRPObject?) -> WRPObject {
let dataObject: WRPObject = objectType.init(parameters: parameters, parentObject: parentObject)
return dataObject
}
fileprivate func valueForKey(_ key: String, optional: Bool) -> AnyObject? {
return nil
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Object serialization
open func toDictionary() -> NSDictionary {
return self.toDictionaryWithSerializationOption(.none, without: [])
}
open func toDictionaryWithout(_ exclude: [String]) -> NSDictionary {
return self.toDictionaryWithSerializationOption(.none, without: exclude)
}
open func toDictionaryWithOnly(_ include: [String]) -> NSDictionary {
print("toDictionaryWithOnly(:) is not yet supported. Expected version: 0.2")
return NSDictionary()
// return self.toDictionaryWithSerializationOption(.None, with: include)
}
open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption) -> NSDictionary {
return self.toDictionaryWithSerializationOption(option, without: [])
}
open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption, without: [String]) -> NSDictionary {
// Create output
let outputParams: NSMutableDictionary = NSMutableDictionary()
// Get mapping parameters, go through all of them and serialize them into output
for element: WRPProperty in self.propertyMap() {
// Skip element if it should be excluded
if self.keyPathShouldBeExcluded(element.masterRemoteName, exclusionArray: without) {
continue
}
// Get actual value of property
let actualValue: AnyObject? = self.value(forKey: element.localName) as AnyObject?
// Check for nil, if it is nil, we add <NSNull> object instead of value
if (actualValue == nil) {
if (option == WRPSerializationOption.includeNullProperties) {
outputParams.setObject(NSNull(), forKeyPath: element.remoteNames.first!)
}
} else {
// Otherwise add value itself
outputParams.setObject(self.valueOfElement(element, value: actualValue!), forKeyPath: element.masterRemoteName)
}
}
// Now get all relationships and call .toDictionary above all of them
for element: WRPRelation in self.relationMap() {
if self.keyPathShouldBeExcluded(element.remoteName, exclusionArray: without) {
continue
}
if (element.relationshipType == .toMany) {
// Get data pack
if let actualValues = self.value(forKey: element.localName) as? [WRPObject] {
// Create data pack if exists, get all values, serialize those, and assign all of them
var outputArray = [NSDictionary]()
for actualValue: WRPObject in actualValues {
outputArray.append(actualValue.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)))
}
// Add all intros back
outputParams.setObject(outputArray as AnyObject!, forKeyPath: element.remoteName)
} else {
// Add null value for relationship if needed
if (option == WRPSerializationOption.includeNullProperties) {
outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying)
}
}
} else {
// Get actual value of property
let actualValue: WRPObject? = self.value(forKey: element.localName) as? WRPObject
// Check for nil, if it is nil, we add <NSNull> object instead of value
if (actualValue == nil) {
if (option == WRPSerializationOption.includeNullProperties) {
outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying)
}
} else {
// Otherwise add value itself
outputParams.setObject(actualValue!.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)), forKey: element.remoteName as NSCopying)
}
}
}
return outputParams
}
fileprivate func keyPathForChildWithElement(_ element: WRPRelation, parentRules: [String]) -> [String] {
if (parentRules.count > 0) {
var newExlusionRules = [String]()
for parentRule: String in parentRules {
let objcString: NSString = parentRule as NSString
let range: NSRange = objcString.range(of: String(format: "%@.", element.remoteName))
if range.location != NSNotFound && range.location == 0 {
let newPath = objcString.replacingCharacters(in: range, with: "")
newExlusionRules.append(newPath as String)
}
}
return newExlusionRules
} else {
return []
}
}
fileprivate func keyPathShouldBeExcluded(_ valueKeyPath: String, exclusionArray: [String]) -> Bool {
let objcString: NSString = valueKeyPath as NSString
for exclustionKeyPath: String in exclusionArray {
let range: NSRange = objcString.range(of: exclustionKeyPath)
if range.location != NSNotFound && range.location == 0 {
return true
}
}
return false
}
fileprivate func valueOfElement(_ element: WRPProperty, value: AnyObject) -> AnyObject {
switch element.elementDataType {
case .int:
return NSNumber(value: value as! Int as Int)
case .float:
return NSNumber(value: value as! Float as Float)
case .double:
return NSNumber(value: value as! Double as Double)
case .bool:
return NSNumber(value: value as! Bool as Bool)
case .date:
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = element.format!
return formatter.string(from: value as! Date) as AnyObject
default:
return value
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Convenience
open func updateWithJSONString(_ jsonString: String) -> Bool {
// Try to parse json data
if let jsonData: Data = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true) {
// If it worked, update data of current object (dictionary is expected on root level)
do {
let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject?
self.fillValues(jsonObject as! NSDictionary)
self.processClosestRelationships(jsonObject as! NSDictionary)
return true
} catch let error as NSError {
print ("Error while parsing a json object: \(error.domain)")
}
}
// Could not process json string
return false
}
open func updateWithDictionary(_ objectData: NSDictionary) -> Bool {
// Update data of current object
self.fillValues(objectData)
self.processClosestRelationships(objectData)
return true
}
open func excludeOnSerialization() -> [String] {
return []
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Debug
open func debugInstantiate() -> Bool {
return false
}
override open var debugDescription: String {
return "Class: \(self.self)\nContent: \(self.toDictionary().debugDescription)"
}
}
| 7398682a3cb963b67525febbc7ff24ef | 38.127635 | 214 | 0.544007 | false | false | false | false |
PrajeetShrestha/imgurdemo | refs/heads/master | MobilabDemo/Globals/Utils.swift | apache-2.0 | 1 | //
// Utils.swift
// MobilabDemo
//
// Created by [email protected] on 5/1/16.
// Copyright © 2016 Prajeet Shrestha. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
} | 52675cb70a58e6eeb84989ddd49d214b | 31.636364 | 116 | 0.599721 | false | false | false | false |
typarker/LotLizard | refs/heads/LotLizard | KitchenSink/ExampleFiles/AppDelegate.swift | mit | 1 | // Copyright (c) 2014 evolved.io (http://evolved.io)
//
// 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow!
var drawerController: DrawerController!
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
//let leftSideDrawerViewController = ExampleLeftSideDrawerViewController()
let leftSideDrawerViewController = Left()
//let centerViewController = ExampleCenterTableViewController()
let centerViewController = BuySpotViewController()
let rightSideDrawerViewController = ExampleRightSideDrawerViewController()
let navigationController = UINavigationController(rootViewController: centerViewController)
navigationController.restorationIdentifier = "ExampleCenterNavigationControllerRestorationKey"
let rightSideNavController = UINavigationController(rootViewController: rightSideDrawerViewController)
rightSideNavController.restorationIdentifier = "ExampleRightNavigationControllerRestorationKey"
let leftSideNavController = UINavigationController(rootViewController: leftSideDrawerViewController)
leftSideNavController.restorationIdentifier = "ExampleLeftNavigationControllerRestorationKey"
self.drawerController = DrawerController(centerViewController: navigationController, leftDrawerViewController: leftSideNavController, rightDrawerViewController: rightSideNavController)
self.drawerController.showsShadows = false
self.drawerController.restorationIdentifier = "Drawer"
self.drawerController.maximumRightDrawerWidth = 200.0
self.drawerController.openDrawerGestureModeMask = .All
self.drawerController.closeDrawerGestureModeMask = .All
self.drawerController.drawerVisualStateBlock = { (drawerController, drawerSide, percentVisible) in
let block = ExampleDrawerVisualStateManager.sharedManager.drawerVisualStateBlockForDrawerSide(drawerSide)
block?(drawerController, drawerSide, percentVisible)
}
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let tintColor = UIColor(red: 29 / 255, green: 173 / 255, blue: 234 / 255, alpha: 1.0)
self.window.tintColor = tintColor
self.window.rootViewController = self.drawerController
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("Tuw3w4dCezCqsOUt5SctfNuLW1T5FoxWoZoPJoaL", clientKey: "LyIgRe9qSdUadkny0zcmYMDQbCi4IJ2m7QEYksaX")
self.window.backgroundColor = UIColor.whiteColor()
self.window.makeKeyAndVisible()
return true
}
func application(application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return true
}
func application(application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController? {
if let key = identifierComponents.last as? String {
if key == "Drawer" {
return self.window.rootViewController
} else if key == "ExampleCenterNavigationControllerRestorationKey" {
return (self.window.rootViewController as DrawerController).centerViewController
} else if key == "ExampleRightNavigationControllerRestorationKey" {
return (self.window.rootViewController as DrawerController).rightDrawerViewController
} else if key == "ExampleLeftNavigationControllerRestorationKey" {
return (self.window.rootViewController as DrawerController).leftDrawerViewController
} else if key == "ExampleLeftSideDrawerController" {
if let leftVC = (self.window.rootViewController as? DrawerController)?.leftDrawerViewController {
if leftVC.isKindOfClass(UINavigationController) {
return (leftVC as UINavigationController).topViewController
} else {
return leftVC
}
}
} else if key == "ExampleRightSideDrawerController" {
if let rightVC = (self.window.rootViewController as? DrawerController)?.rightDrawerViewController {
if rightVC.isKindOfClass(UINavigationController) {
return (rightVC as UINavigationController).topViewController
} else {
return rightVC
}
}
}
}
return nil
}
}
| 7781b958670453977379adc26623f55c | 49.31405 | 192 | 0.702201 | false | false | false | false |
Randoramma/ImageSearcher | refs/heads/master | ImageSearcher/Models/RequestManager.swift | mit | 1 | //
// RequestManager.swift
// ImageSearcher
//
// Created by Randy McLain on 10/7/17.
// Copyright © 2017 Randy McLain. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
enum RequestError {
case GeneralError
case NoInternetConnectionError
}
/*
API Service class
1. Create struct containing public members required to use API
2. Create Singleton - service class should be singleton
3.
*/
class RequestManager {
static let sharedInstance = RequestManager()
private var pageForSearch: Int
private var pageForEditorsChoice: Int
private struct API {
/// the URL base for the API
static let baseURL = PrivateConstants.private_store_url
/// The API Key provided to consume the API
static let apiKey = PrivateConstants.private_pixabay_API_Key
}
// private initalizer
private init() {
self.pageForEditorsChoice = 1;
self.pageForSearch = 1;
}
/// Alamofire Service Methods
/// see https://github.com/Alamofire/Alamofire#parameter-encoding for options on request parameters.
func getImagesByName(nameToSearch name: String, completionHandler: @escaping (_ photos: [Photo]?, _ error: Error?) -> Void) {
let queryString = name.URLEncodedValue
let parameters: [String: Any] = ["key": API.apiKey,
"q": queryString,
"safesearch": true,
"page": pageForSearch]
// perform request and increment if request succeeds.
Alamofire.request(API.baseURL, parameters: parameters).validate().responseJSON { (response) in
switch(response.result) {
case .success(let value):
self.pageForSearch += 1
let json = JSON(value)
let photos = self.parseJsonForPhoto(json) // parse for objects
DispatchQueue.main.async(execute: {
completionHandler(photos, nil) // usually return objects on main queue.
})
case .failure(let error):
DispatchQueue.main.async(execute: {
completionHandler(nil, error)
print(error.localizedDescription)
})
}
}
}
func getEditorChoiceImages(completionHandler: @escaping (_ photos: [Photo]?, _ error: Error?) -> Void) {
let parameters: [String: Any] = ["key": API.apiKey,
"editors_choice": true,
"safesearch": true,
"page": pageForEditorsChoice]
// the fetch request and increment request variable if request succeeds.
Alamofire.request(API.baseURL, parameters: parameters).validate().responseJSON { (response) in
switch(response.result) {
case .success(let value):
self.pageForEditorsChoice += 1
let json = JSON(value)
let photos = self.parseJsonForPhoto(json) // parse for objects
DispatchQueue.main.async(execute: {
completionHandler(photos, nil) // usually return objects on main queue.
})
case .failure(let error):
DispatchQueue.main.async(execute: {
completionHandler(nil, error)
print(error.localizedDescription)
})
}
}
}
func getImagesByID(imageID id: String) {
let parameters: [String: Any] = ["key": API.apiKey, "id": id]
Alamofire.request(API.baseURL, parameters: parameters).responseJSON { (response) in
switch(response.result) {
case .success(let value):
print(value)
case .failure(let error):
print(error.localizedDescription)
}
}
}
/*
Automagically caches each image recieved from network requests to improve responsiveness. Prior to making network request AlamofireImage checks if the image was requested previously and if so pulls that image from the cache. Only works while connecetd to network.
*/
func getImageByURL(urlOfImage url: String, completionHandler: @escaping (_ image: UIImage?, _ error: Error?) ->Void) {
Alamofire.request(url).responseImage { (response) in
switch(response.result) {
case .success(let value):
completionHandler(value, nil)
case .failure(let error):
print("the error is \(error)")
}
}
}
fileprivate func parseJsonForPhoto(_ json: JSON)->[Photo] {
var photoArray = [Photo]()
guard let hits = json["hits"].array else {
return photoArray
}
for item in hits { // ensure your keys are spelled and typed correctly. (cmnd+p from results)
if let url = item["webformatURL"].string,
let likes = item["likes"].int,
let favortites = item["favorites"].int {
let photo = Photo(theUrl: url, theLikes: likes, theFavs: favortites)
photoArray.append(photo)
}
}
return photoArray
}
}
public extension String {
/* For performance, I've replaced the char constants with integers, as char constants don't work in Swift.
https://stackoverflow.com/questions/3423545/objective-c-iphone-percent-encode-a-string/20271177#20271177
*/
var URLEncodedValue: String {
let output = NSMutableString()
guard let source = self.cString(using: String.Encoding.utf8) else {
return self
}
let sourceLen = source.count
var i = 0
while i < sourceLen - 1 {
let thisChar = source[i]
if thisChar == 32 {
output.append("+")
} else if thisChar == 46 || thisChar == 45 || thisChar == 95 || thisChar == 126 ||
(thisChar >= 97 && thisChar <= 122) ||
(thisChar >= 65 && thisChar <= 90) ||
(thisChar >= 48 && thisChar <= 57) {
output.appendFormat("%c", thisChar)
} else {
output.appendFormat("%%%02X", thisChar)
}
i += 1
}
return output as String
}
}
/*
Error handling in Swift
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
*/
/*
hits = (
{
comments = 27;
downloads = 113;
favorites = 9;
id = 2802838;
imageHeight = 2929;
imageWidth = 2930;
likes = 31;
pageURL = "https://";
previewHeight = 149;
previewURL = "https:___.jpg";
previewWidth = 150;
tags = "cow, beef, animal";
type = photo;
user = Couleur;
userImageURL = "https://____.jpg";
"user_id" = 1195798;
views = 388;
webformatHeight = 639;
webformatURL = "https://____.jpg";
webformatWidth = 640;
},
*/
| 10095c55316169bfe457267866161594 | 34.193069 | 271 | 0.570263 | false | false | false | false |
JornWu/ZhiBo_Swift | refs/heads/master | Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UIControl.swift | agpl-3.0 | 6 | import ReactiveSwift
import UIKit
import enum Result.NoError
extension Reactive where Base: UIControl {
/// The current associated action of `self`, with its registered event mask
/// and its disposable.
internal var associatedAction: Atomic<(action: CocoaAction<Base>, controlEvents: UIControlEvents, disposable: Disposable)?> {
return associatedValue { _ in Atomic(nil) }
}
/// Set the associated action of `self` to `action`, and register it for the
/// control events specified by `controlEvents`.
///
/// - parameters:
/// - action: The action to be associated.
/// - controlEvents: The control event mask.
/// - disposable: An outside disposable that will be bound to the scope of
/// the given `action`.
internal func setAction(_ action: CocoaAction<Base>?, for controlEvents: UIControlEvents, disposable: Disposable? = nil) {
associatedAction.modify { associatedAction in
associatedAction?.disposable.dispose()
if let action = action {
base.addTarget(action, action: CocoaAction<Base>.selector, for: controlEvents)
let compositeDisposable = CompositeDisposable()
compositeDisposable += isEnabled <~ action.isEnabled
compositeDisposable += { [weak base = self.base] in
base?.removeTarget(action, action: CocoaAction<Base>.selector, for: controlEvents)
}
compositeDisposable += disposable
associatedAction = (action, controlEvents, ScopedDisposable(compositeDisposable))
} else {
associatedAction = nil
}
}
}
/// Create a signal which sends a `value` event for each of the specified
/// control events.
///
/// - parameters:
/// - controlEvents: The control event mask.
///
/// - returns: A signal that sends the control each time the control event
/// occurs.
public func controlEvents(_ controlEvents: UIControlEvents) -> Signal<Base, NoError> {
return Signal { observer in
let receiver = CocoaTarget(observer) { $0 as! Base }
base.addTarget(receiver,
action: #selector(receiver.sendNext),
for: controlEvents)
let disposable = lifetime.ended.observeCompleted(observer.sendCompleted)
return ActionDisposable { [weak base = self.base] in
disposable?.dispose()
base?.removeTarget(receiver,
action: #selector(receiver.sendNext),
for: controlEvents)
}
}
}
@available(*, unavailable, renamed: "controlEvents(_:)")
public func trigger(for controlEvents: UIControlEvents) -> Signal<(), NoError> {
fatalError()
}
/// Sets whether the control is enabled.
public var isEnabled: BindingTarget<Bool> {
return makeBindingTarget { $0.isEnabled = $1 }
}
/// Sets whether the control is selected.
public var isSelected: BindingTarget<Bool> {
return makeBindingTarget { $0.isSelected = $1 }
}
/// Sets whether the control is highlighted.
public var isHighlighted: BindingTarget<Bool> {
return makeBindingTarget { $0.isHighlighted = $1 }
}
}
| a979c31dfce75a45ea42e9657c4f6a83 | 33.206897 | 126 | 0.694892 | false | false | false | false |
kylef/Mockingdrive | refs/heads/master | Pods/WebLinking/WebLinking/WebLinking.swift | bsd-2-clause | 4 | //
// WebLinking.swift
// WebLinking
//
// Created by Kyle Fuller on 20/01/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
/// A structure representing a RFC 5988 link.
public struct Link: Equatable, Hashable {
/// The URI for the link
public let uri:String
/// The parameters for the link
public let parameters:[String:String]
/// Initialize a Link with a given uri and parameters
public init(uri:String, parameters:[String:String]? = nil) {
self.uri = uri
self.parameters = parameters ?? [:]
}
/// Returns the hash value
public var hashValue:Int {
return uri.hashValue
}
/// Relation type of the Link.
public var relationType:String? {
return parameters["rel"]
}
/// Reverse relation of the Link.
public var reverseRelationType:String? {
return parameters["rev"]
}
/// A hint of what the content type for the link may be.
public var type:String? {
return parameters["type"]
}
}
/// Returns whether two Link's are equivalent
public func ==(lhs:Link, rhs:Link) -> Bool {
return lhs.uri == rhs.uri && lhs.parameters == rhs.parameters
}
// MARK: HTML Element Conversion
/// An extension to Link to provide conversion to a HTML element
extension Link {
/// Encode the link into a HTML element
public var html:String {
let components = parameters.map { (key, value) in
"\(key)=\"\(value)\""
} + ["href=\"\(uri)\""]
let elements = components.joinWithSeparator(" ")
return "<link \(elements) />"
}
}
// MARK: Header link conversion
/// An extension to Link to provide conversion to and from a HTTP "Link" header
extension Link {
/// Encode the link into a header
public var header:String {
let components = ["<\(uri)>"] + parameters.map { (key, value) in
"\(key)=\"\(value)\""
}
return components.joinWithSeparator("; ")
}
/*** Initialize a Link with a HTTP Link header
- parameter header: A HTTP Link Header
*/
public init(header:String) {
let (uri, parametersString) = takeFirst(separateBy(";")(input: header))
let parameters = Array(Array(parametersString.map(split("="))).map { parameter in
[parameter.0: trim("\"", rhs: "\"")(input: parameter.1)]
})
self.uri = trim("<", rhs: ">")(input: uri)
self.parameters = parameters.reduce([:], combine: +)
}
}
/*** Parses a Web Linking (RFC5988) header into an array of Links
- parameter header: RFC5988 link header. For example `<?page=3>; rel=\"next\", <?page=1>; rel=\"prev\"`
:return: An array of Links
*/
public func parseLinkHeader(header:String) -> [Link] {
return separateBy(",")(input: header).map { string in
return Link(header: string)
}
}
/// An extension to NSHTTPURLResponse adding a links property
extension NSHTTPURLResponse {
/// Parses the links on the response `Link` header
public var links:[Link] {
if let linkHeader = allHeaderFields["Link"] as? String {
return parseLinkHeader(linkHeader).map { link in
var uri = link.uri
/// Handle relative URIs
if let baseURL = self.URL, URL = NSURL(string: uri, relativeToURL: baseURL) {
uri = URL.absoluteString
}
return Link(uri: uri, parameters: link.parameters)
}
}
return []
}
/// Finds a link which has matching parameters
public func findLink(parameters:[String:String]) -> Link? {
for link in links {
if link.parameters ~= parameters {
return link
}
}
return nil
}
/// Find a link for the relation
public func findLink(relation relation:String) -> Link? {
return findLink(["rel": relation])
}
}
/// MARK: Private methods (used by link header conversion)
// Merge two dictionaries together
func +<K,V>(lhs:Dictionary<K,V>, rhs:Dictionary<K,V>) -> Dictionary<K,V> {
var dictionary = [K:V]()
for (key, value) in rhs {
dictionary[key] = value
}
for (key, value) in lhs {
dictionary[key] = value
}
return dictionary
}
/// LHS contains all the keys and values from RHS
func ~=(lhs:[String:String], rhs:[String:String]) -> Bool {
for (key, value) in rhs {
if lhs[key] != value {
return false
}
}
return true
}
// Separate a trim a string by a separator
func separateBy(separator:String)(input:String) -> [String] {
return input.componentsSeparatedByString(separator).map {
$0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
// Split a string by a separator into two components
func split(separator:String)(input:String) -> (String, String) {
let range = input.rangeOfString(separator, options: NSStringCompareOptions(rawValue: 0), range: nil, locale: nil)
if let range = range {
let lhs = input.substringToIndex(range.startIndex)
let rhs = input.substringFromIndex(range.endIndex)
return (lhs, rhs)
}
return (input, "")
}
// Separate the first element in an array from the rest
func takeFirst(input:[String]) -> (String, ArraySlice<String>) {
if let first = input.first {
let items = input[input.startIndex.successor() ..< input.endIndex]
return (first, items)
}
return ("", [])
}
// Trim a prefix and suffix from a string
func trim(lhs:Character, rhs:Character)(input:String) -> String {
if input.hasPrefix("\(lhs)") && input.hasSuffix("\(rhs)") {
return input[input.startIndex.successor()..<input.endIndex.predecessor()]
}
return input
}
| db0da206a67260e1a2866ab767d40d08 | 25.719212 | 115 | 0.656895 | false | false | false | false |
icecoffin/GlossLite | refs/heads/master | GlossLite/Views/WordList/WordListCell.swift | mit | 1 | //
// WordListCell.swift
// GlossLite
//
// Created by Daniel on 25/09/16.
// Copyright © 2016 icecoffin. All rights reserved.
//
import UIKit
class WordListCell: UITableViewCell {
private let wordTextLabel = UILabel()
private let definitionLabel = UILabel()
static var reuseIdentifier: String {
return String(describing: WordListCell.self)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
addWordTextLabel()
addDefinitionLabel()
}
private func addWordTextLabel() {
contentView.addSubview(wordTextLabel)
wordTextLabel.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.topMargin)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
}
wordTextLabel.font = Fonts.openSans(size: 20)
}
private func addDefinitionLabel() {
contentView.addSubview(definitionLabel)
definitionLabel.snp.makeConstraints { make in
make.top.equalTo(wordTextLabel.snp.bottom)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
make.bottom.equalTo(contentView.snp.bottomMargin)
}
definitionLabel.font = Fonts.openSansItalic(size: 14)
definitionLabel.textColor = UIColor.gray
}
func configure(with viewModel: WordListCellViewModel) {
wordTextLabel.text = viewModel.text
definitionLabel.text = viewModel.definition
}
}
| a569c572dc810c06a5cbbc3f96d55eb6 | 25.854839 | 72 | 0.729129 | false | false | false | false |
hironytic/XMLPullitic | refs/heads/master | Sources/XMLPullParser.swift | mit | 1 | //
// XMLPullParser.swift
// XMLPullitic
//
// Copyright (c) 2016-2019 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class XMLPullParser {
private var internalParser: InternalXMLParser
public convenience init?(contentsOfURL url: URL) {
guard let parser = XMLParser(contentsOf:url) else { return nil }
self.init(xmlParser: parser)
}
public convenience init(data: Data) {
self.init(xmlParser: XMLParser(data: data))
}
public convenience init(stream: InputStream) {
self.init(xmlParser: XMLParser(stream: stream))
}
public convenience init?(string: String) {
guard let data = (string as NSString).data(using: String.Encoding.utf8.rawValue) else { return nil }
self.init(data: data)
}
init(xmlParser: XMLParser) {
self.internalParser = InternalXMLParser(xmlParser: xmlParser)
}
deinit {
abortParsing()
}
public var shouldProcessNamespaces: Bool {
get {
return self.internalParser.xmlParser.shouldProcessNamespaces
}
set(value) {
self.internalParser.xmlParser.shouldProcessNamespaces = value
}
}
public var lineNumber: Int {
get {
return self.internalParser.xmlParser.lineNumber
}
}
public var columnNumber: Int {
get {
return self.internalParser.xmlParser.columnNumber
}
}
public var depth: Int {
get {
return self.internalParser.depth
}
}
public func next() throws -> XMLEvent {
return try internalParser.requestEvent()
}
public func abortParsing() {
internalParser.abortParsing()
}
}
// MARK: -
@objc private class InternalXMLParser: NSObject, XMLParserDelegate {
class LockCondition {
static let Requested: Int = 0
static let Provided: Int = 1
}
enum State {
case notStarted
case parsing
case aborted
case ended
}
enum EventOrError {
case event(XMLEvent)
case error(Error)
}
let xmlParser: XMLParser
let lock: NSConditionLock
var currentEventOrError: EventOrError
var state: State
var depth: Int
var accumulatedChars: String?
// MARK: methods called on original thread
init(xmlParser: XMLParser) {
self.xmlParser = xmlParser
self.lock = NSConditionLock(condition: LockCondition.Requested)
self.currentEventOrError = EventOrError.event(XMLEvent.startDocument)
self.state = .notStarted
self.depth = 0
super.init()
}
func abortParsing() {
guard state == .parsing else { return }
state = .aborted
// awake wating parser
lock.unlock(withCondition: LockCondition.Requested)
}
func requestEvent() throws -> XMLEvent {
switch state {
case .notStarted:
state = .parsing
xmlParser.delegate = self
DispatchQueue.global(qos: .default).async {
self.lock.lock(whenCondition: LockCondition.Requested)
self.xmlParser.parse()
}
case .parsing:
lock.unlock(withCondition: LockCondition.Requested)
case .aborted:
return XMLEvent.endDocument
case .ended:
return XMLEvent.endDocument
}
lock.lock(whenCondition: LockCondition.Provided)
switch currentEventOrError {
case .error(let error):
state = .ended
lock.unlock()
throw error
case .event(XMLEvent.endDocument):
state = .ended
lock.unlock()
return XMLEvent.endDocument
case .event(let event):
return event
}
}
// MARK: methods called on background thread
func provide(_ eventOrError: EventOrError) {
if let chars = accumulatedChars {
accumulatedChars = nil
provide(.event(.characters(chars)))
waitForNextRequest()
}
if (state == .parsing) {
currentEventOrError = eventOrError
lock.unlock(withCondition: LockCondition.Provided)
}
}
func waitForNextRequest() {
guard state == .parsing else {
if (state == .aborted && xmlParser.delegate != nil) {
xmlParser.delegate = nil
xmlParser.abortParsing()
}
return
}
lock.lock(whenCondition: LockCondition.Requested)
if (state == .aborted) {
xmlParser.delegate = nil
xmlParser.abortParsing()
lock.unlock()
}
}
func accumulate(characters chars: String) {
accumulatedChars = (accumulatedChars ?? "") + chars
}
@objc func parserDidStartDocument(_ parser: XMLParser) {
provide(.event(.startDocument))
waitForNextRequest()
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
depth += 1
let element = XMLElement(name: elementName, namespaceURI: namespaceURI, qualifiedName: qName, attributes: attributeDict)
provide(.event(.startElement(name: elementName, namespaceURI: namespaceURI, element: element)))
waitForNextRequest()
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
provide(.event(.endElement(name: elementName, namespaceURI: namespaceURI)))
waitForNextRequest()
depth -= 1
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
accumulate(characters: string)
}
@objc func parserDidEndDocument(_ parser: XMLParser) {
provide(.event(.endDocument))
}
@objc func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
provide(.error(XMLPullParserError.parseError(innerError: parseError)))
}
@objc func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
if let text = NSString(data: CDATABlock, encoding: String.Encoding.utf8.rawValue) {
accumulate(characters: text as String)
}
}
}
| b3fd117f91c8619a60b17b472b53da68 | 29.894309 | 179 | 0.621711 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/Core/API/Requests/SearchPhotosRequest.swift | mit | 1 | //
// SearchPhotosRequest.swift
// Accented
//
// Created by Tiangong You on 5/21/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class SearchPhotosRequest: APIRequest {
private var keyword : String?
private var tag : String?
private var page : Int
private var sorting : PhotoSearchSortingOptions
init(keyword : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) {
self.keyword = keyword
self.page = page
self.sorting = sort
super.init(success: success, failure: failure)
cacheKey = "search_photos/\(keyword)/\(page)"
url = "\(APIRequest.baseUrl)photos/search"
parameters = params
parameters[RequestParameters.term] = keyword
parameters[RequestParameters.page] = String(page)
parameters[RequestParameters.sort] = sort.rawValue
parameters[RequestParameters.includeStates] = "1"
if params[RequestParameters.imageSize] == nil {
parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in
return size.rawValue
}).joined(separator: ",")
}
// By default, exclude node content
parameters[RequestParameters.excludeNude] = "1"
if params[RequestParameters.exclude] == nil {
// Apply default filters
parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",")
}
}
init(tag : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) {
self.tag = tag
self.page = page
self.sorting = sort
super.init(success: success, failure: failure)
cacheKey = "search_photos/\(tag)/\(page)"
url = "\(APIRequest.baseUrl)photos/search"
parameters = params
parameters[RequestParameters.tag] = tag
parameters[RequestParameters.page] = String(page)
parameters[RequestParameters.sort] = sort.rawValue
parameters[RequestParameters.includeStates] = "1"
if params[RequestParameters.imageSize] == nil {
parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in
return size.rawValue
}).joined(separator: ",")
}
// By default, exclude node content
parameters[RequestParameters.excludeNude] = "1"
if params[RequestParameters.exclude] == nil {
// Apply default filters
parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",")
}
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
var userInfo : [String : Any] = [RequestParameters.feature : StreamType.Search.rawValue,
RequestParameters.page : page,
RequestParameters.response : data,
RequestParameters.sort : sorting]
if keyword != nil {
userInfo[RequestParameters.term] = keyword!
} else if tag != nil {
userInfo[RequestParameters.tag] = tag!
}
NotificationCenter.default.post(name: APIEvents.streamPhotosDidReturn, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.streamPhotosFailedReturn, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
| 799ada2adb0881339afc46630f221812 | 37.703704 | 158 | 0.612679 | false | false | false | false |
jyxia/CrowdFood-iOS | refs/heads/master | CrowdFood/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// CrowdFood
//
// Created by Jinyue Xia on 10/10/15.
// Copyright © 2015 Jinyue Xia. All rights reserved.
//
import UIKit
import VideoSplash
class HomeViewController: VideoSplashViewController, VideoPlayerEventDelegate {
@IBOutlet weak var enterBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("restaurant", ofType: "mp4")!)
self.videoFrame = view.frame
self.fillMode = .ResizeAspectFill
self.alwaysRepeat = true
self.sound = true
self.startTime = 0.0
self.alpha = 0.7
self.backgroundColor = UIColor.blackColor()
self.contentURL = url
self.sound = false
self.eventDelegate = self
enterBtn.backgroundColor = UIColor.clearColor()
enterBtn.layer.cornerRadius = 5
enterBtn.layer.borderWidth = 1
enterBtn.layer.borderColor = UIColor.greenColor().CGColor
let text = UILabel(frame: CGRect(x: 0.0, y: 100.0, width: 320.0, height: 100.0))
text.font = UIFont(name: "Museo500-Regular", size: 40)
text.textAlignment = NSTextAlignment.Center
text.textColor = UIColor.whiteColor()
text.text = "Crowd Food"
view.addSubview(text)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
self.navigationController?.setToolbarHidden(false, animated: true)
}
@IBAction func tapEnter(sender: UIButton) {
self.performSegueWithIdentifier("HomeToMap", sender: self)
}
func videoDidEnd() {
self.performSegueWithIdentifier("HomeToMap", sender: self)
}
} | fe3f9cfb93e2a500cc04ad34d55a52a1 | 27.301587 | 104 | 0.704265 | false | false | false | false |
ijoshsmith/swift-morse-code | refs/heads/master | MorseCode/ViewController.swift | mit | 1 | //
// ViewController.swift
// MorseCode
//
// Created by Joshua Smith on 7/8/16.
// Copyright © 2016 iJoshSmith. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var blinkingView: UIView!
@IBOutlet weak var encodedMessageTextView: UITextView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var transmitMessageButton: UIButton!
private var morseTransmitter: MorseTransmitter!
private struct BlinkingViewColors {
static let on = UIColor.greenColor()
static let off = UIColor.lightGrayColor()
}
override func viewDidLoad() {
super.viewDidLoad()
morseTransmitter = MorseTransmitter(blinkingView: blinkingView,
onColor: BlinkingViewColors.on,
offColor: BlinkingViewColors.off)
blinkingView.backgroundColor = BlinkingViewColors.off
blinkingView.layer.cornerRadius = blinkingView.frame.width / 2.0;
}
@IBAction func handleTransmitMessageButton(sender: AnyObject) {
if let message = messageTextField.text where message.isEmpty == false {
transmit(message)
}
}
private func transmit(message: String) {
let morseEncoder = MorseEncoder(codingSystem: .InternationalMorseCode)
if let encodedMessage = morseEncoder.encode(message: message) {
showMorseCodeTextFor(encodedMessage)
beginTransmitting(encodedMessage)
}
else {
encodedMessageTextView.text = "Unable to encode at least one character in message."
}
}
private func showMorseCodeTextFor(encodedMessage: EncodedMessage) {
encodedMessageTextView.text = createMorseCodeText(from: encodedMessage)
encodedMessageTextView.font = UIFont(name: "Menlo", size: 16)
}
private func createMorseCodeText(from encodedMessage: EncodedMessage) -> String {
let transformation = MorseTransformation(
dot: ".",
dash: "-",
markSeparator: "",
symbolSeparator: " ",
termSeparator: "\n")
let characters = transformation.apply(to: encodedMessage)
return characters.joinWithSeparator("")
}
private func beginTransmitting(encodedMessage: EncodedMessage) {
transmitMessageButton.enabled = false
morseTransmitter.startTransmitting(encodedMessage: encodedMessage) { [weak self] in
self?.transmitMessageButton.enabled = true
}
}
}
| 575957237960991dc3305169c98dd38a | 34.266667 | 95 | 0.641588 | false | false | false | false |
seanwoodward/IBAnimatable | refs/heads/master | IBAnimatable/SystemPageAnimator.swift | mit | 1 | //
// Created by Tom Baranes on 28/03/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class SystemPageAnimator: NSObject, AnimatedTransitioning {
// MARK: - AnimatorProtocol
public var transitionAnimationType: TransitionAnimationType
public var transitionDuration: Duration = defaultTransitionDuration
public var reverseAnimationType: TransitionAnimationType?
public var interactiveGestureType: InteractiveGestureType?
// MARK: - private
private var type: TransitionPageType
public init(type: TransitionPageType, transitionDuration: Duration) {
self.transitionDuration = transitionDuration
self.type = type
switch type {
case .Curl:
self.transitionAnimationType = .SystemPage(type: .Curl)
self.reverseAnimationType = .SystemPage(type: .UnCurl)
case .UnCurl:
self.transitionAnimationType = .SystemPage(type: .UnCurl)
self.reverseAnimationType = .SystemPage(type: .Curl)
}
super.init()
}
}
extension SystemPageAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return retrieveTransitionDuration(transitionContext)
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
switch self.type {
case .Curl:
animateWithCATransition(transitionContext, type: SystemTransitionType.PageCurl, subtype: nil)
case .UnCurl:
animateWithCATransition(transitionContext, type: SystemTransitionType.PageUnCurl, subtype: nil)
}
}
}
| 0517acd8aea1e1aea2097fe43b4b6a63 | 32.75 | 110 | 0.760494 | false | false | false | false |
Somnibyte/MLKit | refs/heads/master | Example/MLKit/GameScene.swift | mit | 1 | //
// GameScene.swift
// FlappyBird
//
// Created by Nate Murray on 6/2/14.
// Copyright (c) 2014 Fullstack.io. All rights reserved.
//
import SpriteKit
import MachineLearningKit
import Upsurge
class GameScene: SKScene, SKPhysicsContactDelegate {
// ADDITIONS
/// Container for our Flappy Birds
var flappyBirdGenerationContainer: [FlappyGenome]?
/// The current genome
var currentBird: FlappyGenome?
/// The current flappy bird of the current generation (see 'generationCounter' variable)
var currentFlappy: Int = 0
/// Variable used to count the number of generations that have passed
var generationCounter = 1
/// Variable to keep track of the current time (this is used to determine fitness later)
var currentTimeForFlappyBird = NSDate()
/// The red square (our goal area)
var goalArea: SKShapeNode!
/// The pipe that is in front of the bird
var currentPipe: Int = 0
/// The fitness of the best bird
var maxFitness: Float = 0
/// The best bird (from any generation)
var maxBird: FlappyGenome?
/// The best birds from the previous generation
var lastBestGen: [FlappyGenome] = []
/// SKLabel
var generationLabel: SKLabelNode!
var fitnessLabel: SKLabelNode!
let groundTexture = SKTexture(imageNamed: "land")
/// Best score (regardless of generation)
var bestScore: Int = 0
/// Label that displays the best score (bestScore attribute)
var bestScoreLabel: SKLabelNode!
// END of ADDITIONS
let verticalPipeGap = 150.0
var bird: SKSpriteNode!
var skyColor: SKColor!
var pipeTextureUp: SKTexture!
var pipeTextureDown: SKTexture!
var movePipesAndRemove: SKAction!
var moving: SKNode!
var pipes: SKNode!
var canRestart = Bool()
var scoreLabelNode: SKLabelNode!
var score = NSInteger()
let birdCategory: UInt32 = 1 << 0
let worldCategory: UInt32 = 1 << 1
let pipeCategory: UInt32 = 1 << 2
let scoreCategory: UInt32 = 1 << 3
override func didMove(to view: SKView) {
canRestart = false
// setup physics
self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -5.0 )
self.physicsWorld.contactDelegate = self
// setup background color
skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0)
self.backgroundColor = skyColor
moving = SKNode()
self.addChild(moving)
pipes = SKNode()
moving.addChild(pipes)
// ground
groundTexture.filteringMode = .nearest // shorter form for SKTextureFilteringMode.Nearest
let moveGroundSprite = SKAction.moveBy(x: -groundTexture.size().width * 2.0, y: 0, duration: TimeInterval(0.02 * groundTexture.size().width * 2.0))
let resetGroundSprite = SKAction.moveBy(x: groundTexture.size().width * 2.0, y: 0, duration: 0.0)
let moveGroundSpritesForever = SKAction.repeatForever(SKAction.sequence([moveGroundSprite, resetGroundSprite]))
for i in 0 ..< 2 + Int(self.frame.size.width / ( groundTexture.size().width * 2 )) {
let i = CGFloat(i)
let sprite = SKSpriteNode(texture: groundTexture)
sprite.setScale(2.0)
sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0)
sprite.run(moveGroundSpritesForever)
moving.addChild(sprite)
}
// skyline
let skyTexture = SKTexture(imageNamed: "sky")
skyTexture.filteringMode = .nearest
let moveSkySprite = SKAction.moveBy(x: -skyTexture.size().width * 2.0, y: 0, duration: TimeInterval(0.1 * skyTexture.size().width * 2.0))
let resetSkySprite = SKAction.moveBy(x: skyTexture.size().width * 2.0, y: 0, duration: 0.0)
let moveSkySpritesForever = SKAction.repeatForever(SKAction.sequence([moveSkySprite, resetSkySprite]))
for i in 0 ..< 2 + Int(self.frame.size.width / ( skyTexture.size().width * 2 )) {
let i = CGFloat(i)
let sprite = SKSpriteNode(texture: skyTexture)
sprite.setScale(2.0)
sprite.zPosition = -20
sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0 + groundTexture.size().height * 2.0)
sprite.run(moveSkySpritesForever)
moving.addChild(sprite)
}
// create the pipes textures
pipeTextureUp = SKTexture(imageNamed: "PipeUp")
pipeTextureUp.filteringMode = .nearest
pipeTextureDown = SKTexture(imageNamed: "PipeDown")
pipeTextureDown.filteringMode = .nearest
// create the pipes movement actions
let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeTextureUp.size().width)
let movePipes = SKAction.moveBy(x: -distanceToMove, y:0.0, duration:TimeInterval(0.01 * distanceToMove))
let removePipes = SKAction.removeFromParent()
movePipesAndRemove = SKAction.sequence([movePipes, removePipes])
// spawn the pipes
let spawn = SKAction.run(spawnPipes)
let delay = SKAction.wait(forDuration: TimeInterval(2.0))
let spawnThenDelay = SKAction.sequence([spawn, delay])
let spawnThenDelayForever = SKAction.repeatForever(spawnThenDelay)
self.run(spawnThenDelayForever)
// setup our bird
let birdTexture1 = SKTexture(imageNamed: "bird-01")
birdTexture1.filteringMode = .nearest
let birdTexture2 = SKTexture(imageNamed: "bird-02")
birdTexture2.filteringMode = .nearest
let anim = SKAction.animate(with: [birdTexture1, birdTexture2], timePerFrame: 0.2)
let flap = SKAction.repeatForever(anim)
bird = SKSpriteNode(texture: birdTexture1)
bird.setScale(2.0)
bird.position = CGPoint(x: self.frame.size.width * 0.35, y:self.frame.size.height * 0.6)
bird.run(flap)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0)
bird.physicsBody?.isDynamic = true
bird.physicsBody?.allowsRotation = false
bird.physicsBody?.categoryBitMask = birdCategory
bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory
bird.physicsBody?.contactTestBitMask = worldCategory | pipeCategory
self.addChild(bird)
// create the ground
let ground = SKNode()
ground.position = CGPoint(x: 0, y: groundTexture.size().height)
ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.frame.size.width, height: groundTexture.size().height * 2.0))
ground.physicsBody?.isDynamic = false
ground.physicsBody?.categoryBitMask = worldCategory
self.addChild(ground)
// Initialize label and create a label which holds the score
score = 0
scoreLabelNode = SKLabelNode(fontNamed:"MarkerFelt-Wide")
scoreLabelNode.position = CGPoint( x: self.frame.midX, y: 3 * self.frame.size.height / 4 )
scoreLabelNode.zPosition = 100
scoreLabelNode.text = String(score)
self.addChild(scoreLabelNode)
bestScore = 0
bestScoreLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
bestScoreLabel.position = CGPoint( x: self.frame.midX - 120.0, y: 3 * self.frame.size.height / 4 + 110.0 )
bestScoreLabel.zPosition = 100
bestScoreLabel.text = "bestScore: \(self.bestScore)"
self.addChild(bestScoreLabel)
generationLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
generationLabel.position = CGPoint( x: self.frame.midX - 150.0, y: 3 * self.frame.size.height / 4 + 140.0 )
generationLabel.zPosition = 100
generationLabel.text = "Gen: 1"
self.addChild(generationLabel)
fitnessLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
fitnessLabel.position = CGPoint( x: self.frame.midX + 110.0, y: 3 * self.frame.size.height / 4 + 140.0 )
fitnessLabel.zPosition = 100
fitnessLabel.text = "Fitness: 0"
self.addChild(fitnessLabel)
// Set the current bird
if let generation = flappyBirdGenerationContainer {
currentBird = generation[currentFlappy]
}
}
func spawnPipes() {
let pipePair = SKNode()
pipePair.position = CGPoint( x: self.frame.size.width + pipeTextureUp.size().width * 2, y: 0 )
pipePair.zPosition = -10
let height = UInt32( self.frame.size.height / 4)
let y = Double(arc4random_uniform(height) + height)
let pipeDown = SKSpriteNode(texture: pipeTextureDown)
pipeDown.name = "DOWN"
pipeDown.setScale(2.0)
pipeDown.position = CGPoint(x: 0.0, y: y + Double(pipeDown.size.height) + verticalPipeGap)
pipeDown.physicsBody = SKPhysicsBody(rectangleOf: pipeDown.size)
pipeDown.physicsBody?.isDynamic = false
pipeDown.physicsBody?.categoryBitMask = pipeCategory
pipeDown.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(pipeDown)
let pipeUp = SKSpriteNode(texture: pipeTextureUp)
pipeUp.setScale(2.0)
pipeUp.position = CGPoint(x: 0.0, y: y)
pipeUp.physicsBody = SKPhysicsBody(rectangleOf: pipeUp.size)
pipeUp.physicsBody?.isDynamic = false
pipeUp.physicsBody?.categoryBitMask = pipeCategory
pipeUp.physicsBody?.contactTestBitMask = birdCategory
// ADDITIONS
goalArea = SKShapeNode(rectOf: CGSize(width: 10, height: 10))
goalArea.name = "GOAL"
goalArea.fillColor = SKColor.red
goalArea.position = pipeUp.position
goalArea.position.y += 250
// END of ADDITIONS
pipePair.addChild(pipeUp)
pipePair.addChild(goalArea)
let contactNode = SKNode()
contactNode.position = CGPoint( x: pipeDown.size.width + bird.size.width / 2, y: self.frame.midY )
contactNode.physicsBody = SKPhysicsBody(rectangleOf: CGSize( width: pipeUp.size.width, height: self.frame.size.height ))
contactNode.physicsBody?.isDynamic = false
contactNode.physicsBody?.categoryBitMask = scoreCategory
contactNode.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(contactNode)
pipePair.run(movePipesAndRemove)
pipes.addChild(pipePair)
}
func resetScene () {
// Move bird to original position and reset velocity
bird.position = CGPoint(x: self.frame.size.width / 2.5, y: self.frame.midY)
bird.physicsBody?.velocity = CGVector( dx: 0, dy: 0 )
bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory
bird.speed = 1.0
bird.zRotation = 0.0
// Remove all existing pipes
pipes.removeAllChildren()
// Reset _canRestart
canRestart = false
// Reset score
score = 0
scoreLabelNode.text = String(score)
// Restart animation
moving.speed = 1
// GENETIC ALGORITHM (DOWN BELOW)
// Calculate the amount of time it took until the AI lost.
let endDate: NSDate = NSDate()
let timeInterval: Double = endDate.timeIntervalSince(currentTimeForFlappyBird as Date)
currentTimeForFlappyBird = NSDate()
// Evaluate the current birds fitness
if let bird = currentBird {
bird.generateFitness(score: score, time: Float(timeInterval))
// Current generation, bird, and fitness of current bird information
print("--------------------------- \n")
print("GENERATION: \(generationCounter)")
print("BIRD COUNT: \(currentFlappy)")
print("FITNESS: \(bird.fitness)")
self.generationLabel.text = "Gen: \(self.generationCounter)"
print("--------------------------- \n")
if bird.fitness >= 9.0 {
print("FOUND RARE BIRD")
print(bird.brain?.layers[0].weights)
print(bird.brain?.layers[1].weights)
print(bird.brain?.layers[0].bias)
print(bird.brain?.layers[1].bias)
}
}
// Go to next flappy bird
currentFlappy += 1
if let generation = flappyBirdGenerationContainer {
// Experiment: Keep some of the last best birds and put them back into the population
lastBestGen = generation.filter({$0.fitness >= 6.0})
if lastBestGen.count > 10 {
// We want to make room for unique birds
lastBestGen = Array<FlappyGenome>(lastBestGen[0...6])
}
}
if let bird = currentBird {
if bird.fitness > maxFitness {
maxFitness = bird.fitness
maxBird = bird
}
}
// If we have hit the 20th bird, we need to move on to the next generation
if currentFlappy == 20 {
print("GENERATING NEW GEN!")
currentFlappy = 0
// New generation array
var newGen: [FlappyGenome] = []
newGen = lastBestGen
if let bestBird = maxBird {
flappyBirdGenerationContainer?.append(bestBird)
}
while newGen.count < 20 {
// Select the best parents
let parents = PopulationManager.selectParents(genomes: flappyBirdGenerationContainer!)
print("PARENT 1 FITNESS: \(parents.0.fitness)")
print("PARENT 2 FITNESS: \(parents.1.fitness)")
// Produce new flappy birds
var offspring = BiologicalProcessManager.onePointCrossover(crossoverRate: 0.5, parentOneGenotype: parents.0.genotypeRepresentation, parentTwoGenotype: parents.1.genotypeRepresentation)
// Mutate their genes
BiologicalProcessManager.inverseMutation(mutationRate: 0.7, genotype: &offspring.0)
BiologicalProcessManager.inverseMutation(mutationRate: 0.7, genotype: &offspring.1)
// Create a separate neural network for the birds based on their genes
let brainofOffspring1 = GeneticOperations.decode(genotype: offspring.0)
let brainofOffspring2 = GeneticOperations.decode(genotype: offspring.1)
let offspring1 = FlappyGenome(genotype: offspring.0, network: brainofOffspring1)
let offspring2 = FlappyGenome(genotype: offspring.1, network: brainofOffspring2)
// Add them to the new generation
newGen.append(offspring1)
newGen.append(offspring2)
}
generationCounter += 1
// Replace the old generation
flappyBirdGenerationContainer = newGen
// Set the current bird
if let generation = flappyBirdGenerationContainer {
if generation.count > currentFlappy {
currentBird = generation[currentFlappy]
} else {
if let bestBird = maxBird {
currentBird = maxBird
}
}
}
} else {
// Set the current bird
if let generation = flappyBirdGenerationContainer {
if generation.count > currentFlappy {
currentBird = generation[currentFlappy]
}
} else {
currentBird = maxBird
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if moving.speed > 0 {
for _ in touches { // do we need all touches?
}
} else if canRestart {
self.resetScene()
}
}
// Chooses the closest pipe
func closestPipe(pipes: [SKNode]) -> Int {
var min = 0
var minDist = abs(pipes[0].position.x - bird.position.x)
for (i, pipe) in pipes.enumerated() {
if abs(pipe.position.x - minDist) < minDist {
minDist = abs(pipe.position.x - minDist)
min = i
}
}
return min
}
override func update(_ currentTime: TimeInterval) {
let endDate: NSDate = NSDate()
let timeInterval: Double = endDate.timeIntervalSince(currentTimeForFlappyBird as Date)
self.fitnessLabel.text = "Fitness: \(NSString(format: "%.2f", timeInterval))"
checkIfOutOfBounds(bird.position.y)
/* Called before each frame is rendered */
let value = bird.physicsBody!.velocity.dy * ( bird.physicsBody!.velocity.dy < 0 ? 0.003 : 0.001 )
bird.zRotation = min( max(-1, value), 0.5 )
// If the pipes are now visible...
if pipes.children.count > 0 {
// Check to see if the pipe in front has gone behind the bird
// if so, make the new pipe in front of the bird the target pipe
if pipes.children.count > 1 {
if pipes.children[currentPipe].position.x < bird.position.x {
currentPipe = closestPipe(pipes: pipes.children)
}
}
if pipes.children.count == 1 {
if pipes.children[0].position.x < bird.position.x {
currentPipe = 0
}
}
// Distance between next pipe and bird
let distanceOfNextPipe = abs(pipes.children[currentPipe].position.x - bird.position.x)
let distanceFromBottomPipe = abs(pipes.children[currentPipe].children[1].position.y - bird.position.y)
let normalizedDistanceFromBottomPipe = (distanceFromBottomPipe - 5)/(708 - 5)
let normalizedDistanceOfNextPipe = (distanceOfNextPipe - 3)/(725-3)
let distanceFromTheGround = abs(self.bird.position.y - self.moving.children[1].position.y)
let normalizedDistanceFromTheGround = (distanceFromTheGround - 135)/(840-135)
let distanceFromTheSky = abs(880 - self.bird.position.y)
let normalizedDistanceFromTheSky = distanceFromTheSky/632
// Bird Y position
let birdYPos = bird.position.y/CGFloat(880)
// Measure how close the bird is to the gap between the pipes
let posToGap = pipes.children[0].children[2].position.y - bird.position.y
let normalizedPosToGap = (posToGap - (-439))/(279 - (-439))
if let flappyBird = currentBird {
// Decision AI makes
let input = Matrix<Float>(rows: 6, columns: 1, elements: [Float(normalizedDistanceOfNextPipe), Float(normalizedPosToGap), Float(birdYPos), Float(normalizedDistanceFromBottomPipe), Float(normalizedDistanceFromTheGround), Float(normalizedDistanceFromTheSky)])
let potentialDescision = flappyBird.brain?.feedforward(input: input)
if let decision = potentialDescision {
print("FLAPPY BIRD DECISION: \(decision)")
if (decision.elements[0]) >= Float(0.5) {
if moving.speed > 0 {
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 30))
}
}
}
}
}
if canRestart {
// If the game ends...
// record the current flappy birds fitness...
// then bring in the next flappy bird
self.resetScene()
}
}
// Checks if the bird is at the top of the screen
func checkIfOutOfBounds(_ y: CGFloat) {
if moving.speed > 0 {
if y >= 880 {
moving.speed = 0
bird.physicsBody?.collisionBitMask = worldCategory
bird.run( SKAction.rotate(byAngle: CGFloat(M_PI) * CGFloat(bird.position.y) * 0.01, duration:1), completion: {self.bird.speed = 0 })
// Flash background if contact is detected
self.removeAction(forKey: "flash")
self.run(SKAction.sequence([SKAction.repeat(SKAction.sequence([SKAction.run({
//self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0)
}), SKAction.wait(forDuration: TimeInterval(0.05)), SKAction.run({
self.backgroundColor = self.skyColor
}), SKAction.wait(forDuration: TimeInterval(0.05))]), count:4), SKAction.run({
self.canRestart = true
})]), withKey: "flash")
}
}
}
func didBegin(_ contact: SKPhysicsContact) {
if moving.speed > 0 {
if ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory {
// Bird has contact with score entity
score += 1
scoreLabelNode.text = String(score)
// Update best score label
if score > bestScore {
bestScore = score
bestScoreLabel.text = "Best Score: \(self.bestScore)"
}
// Add a little visual feedback for the score increment
scoreLabelNode.run(SKAction.sequence([SKAction.scale(to: 1.5, duration:TimeInterval(0.1)), SKAction.scale(to: 1.0, duration:TimeInterval(0.1))]))
} else {
moving.speed = 0
bird.physicsBody?.collisionBitMask = worldCategory
bird.run( SKAction.rotate(byAngle: CGFloat(M_PI) * CGFloat(bird.position.y) * 0.01, duration:1), completion: {self.bird.speed = 0 })
// Flash background if contact is detected
self.removeAction(forKey: "flash")
self.run(SKAction.sequence([SKAction.repeat(SKAction.sequence([SKAction.run({
//self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0)
}), SKAction.wait(forDuration: TimeInterval(0.05)), SKAction.run({
self.backgroundColor = self.skyColor
}), SKAction.wait(forDuration: TimeInterval(0.05))]), count:4), SKAction.run({
self.canRestart = true
})]), withKey: "flash")
}
}
}
}
| 08d1875734e439d9aafb81295e9fc823 | 35.961921 | 273 | 0.606226 | false | false | false | false |
terry408911/ReactiveCocoa | refs/heads/swift-development | ReactiveCocoaTests/Swift/DisposableSpec.swift | mit | 2 | //
// DisposableSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-07-13.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Nimble
import Quick
import ReactiveCocoa
class DisposableSpec: QuickSpec {
override func spec() {
describe("SimpleDisposable") {
it("should set disposed to true") {
let disposable = SimpleDisposable()
expect(disposable.disposed).to(beFalsy())
disposable.dispose()
expect(disposable.disposed).to(beTruthy())
}
}
describe("ActionDisposable") {
it("should run the given action upon disposal") {
var didDispose = false
let disposable = ActionDisposable {
didDispose = true
}
expect(didDispose).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
disposable.dispose()
expect(didDispose).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
}
describe("CompositeDisposable") {
var disposable = CompositeDisposable()
beforeEach {
disposable = CompositeDisposable()
}
it("should ignore the addition of nil") {
disposable.addDisposable(nil)
return
}
it("should dispose of added disposables") {
let simpleDisposable = SimpleDisposable()
disposable.addDisposable(simpleDisposable)
var didDispose = false
disposable.addDisposable {
didDispose = true
}
expect(simpleDisposable.disposed).to(beFalsy())
expect(didDispose).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
disposable.dispose()
expect(simpleDisposable.disposed).to(beTruthy())
expect(didDispose).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
it("should not dispose of removed disposables") {
let simpleDisposable = SimpleDisposable()
let handle = disposable.addDisposable(simpleDisposable)
// We should be allowed to call this any number of times.
handle.remove()
handle.remove()
expect(simpleDisposable.disposed).to(beFalsy())
disposable.dispose()
expect(simpleDisposable.disposed).to(beFalsy())
}
}
describe("ScopedDisposable") {
it("should dispose of the inner disposable upon deinitialization") {
let simpleDisposable = SimpleDisposable()
func runScoped() {
let scopedDisposable = ScopedDisposable(simpleDisposable)
expect(simpleDisposable.disposed).to(beFalsy())
expect(scopedDisposable.disposed).to(beFalsy())
}
expect(simpleDisposable.disposed).to(beFalsy())
runScoped()
expect(simpleDisposable.disposed).to(beTruthy())
}
}
describe("SerialDisposable") {
var disposable: SerialDisposable!
beforeEach {
disposable = SerialDisposable()
}
it("should dispose of the inner disposable") {
let simpleDisposable = SimpleDisposable()
disposable.innerDisposable = simpleDisposable
expect(disposable.innerDisposable).notTo(beNil())
expect(simpleDisposable.disposed).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
disposable.dispose()
expect(disposable.innerDisposable).to(beNil())
expect(simpleDisposable.disposed).to(beTruthy())
expect(disposable.disposed).to(beTruthy())
}
it("should dispose of the previous disposable when swapping innerDisposable") {
let oldDisposable = SimpleDisposable()
let newDisposable = SimpleDisposable()
disposable.innerDisposable = oldDisposable
expect(oldDisposable.disposed).to(beFalsy())
expect(newDisposable.disposed).to(beFalsy())
disposable.innerDisposable = newDisposable
expect(oldDisposable.disposed).to(beTruthy())
expect(newDisposable.disposed).to(beFalsy())
expect(disposable.disposed).to(beFalsy())
disposable.innerDisposable = nil
expect(newDisposable.disposed).to(beTruthy())
expect(disposable.disposed).to(beFalsy())
}
}
}
}
| c1ea9d3ddc821e227440b741a48549a3 | 25.664336 | 82 | 0.707317 | false | false | false | false |
jeremiahyan/ResearchKit | refs/heads/main | ResearchKit/ActiveTasks/ORKSwiftStroopStep.swift | bsd-3-clause | 3 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public class ORKSwiftStroopStep: ORKActiveStep {
public var numberOfAttempts = 0
private let minimumAttempts = 10
enum Key: String {
case numberOfAttempts
}
public override class func stepViewControllerClass() -> AnyClass {
return ORKSwiftStroopStepViewController.self
}
public class func supportsSecureCoding() -> Bool {
return true
}
public override init(identifier: String) {
super.init(identifier: identifier)
shouldVibrateOnStart = true
shouldShowDefaultTimer = false
shouldContinueOnFinish = true
stepDuration = TimeInterval(NSIntegerMax)
}
public override func validateParameters() {
super.validateParameters()
assert(numberOfAttempts >= minimumAttempts, "number of attempts should be greater or equal to \(minimumAttempts)")
}
public override func startsFinished() -> Bool {
return false
}
public override var allowsBackNavigation: Bool {
return false
}
public override func copy(with zone: NSZone? = nil) -> Any {
let stroopStep = super.copy(with: zone)
return stroopStep
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
numberOfAttempts = aDecoder.decodeInteger(forKey: Key.numberOfAttempts.rawValue)
}
public override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(numberOfAttempts, forKey: Key.numberOfAttempts.rawValue)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? ORKSwiftStroopStep {
return numberOfAttempts == object.numberOfAttempts
}
return false
}
}
| c6b95e7a3799c42683ba8c278f957fbb | 35.691489 | 122 | 0.719919 | false | false | false | false |
BasThomas/Analysis | refs/heads/main | Example/Analysis/ViewController.swift | mit | 1 | //
// ViewController.swift
// Analysis
//
// Created by Bas Broek on 11/11/2016.
// Copyright (c) 2016 Bas Broek. All rights reserved.
//
import UIKit
private let analyseIdentifier = "analyse"
class ViewController: UIViewController {
@IBOutlet var analyseBarButtonItem: UIBarButtonItem!
@IBOutlet var textView: UITextView! {
didSet {
textView.becomeFirstResponder()
analyseBarButtonItem.isEnabled = !textView.text.isEmpty
}
}
}
// MARK: - Text view delegate
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
analyseBarButtonItem.isEnabled = !textView.text.isEmpty
}
}
// MARK: - Actions
extension ViewController {
@IBAction func analyse(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: analyseIdentifier, sender: self)
}
}
// MARK: - Navigation
extension ViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destinationViewController = segue.destination as? AnalysisTableViewController else { return }
destinationViewController.input = textView.text
}
}
| 17491a587087b9dcc97325f9b2e09634 | 22.978723 | 107 | 0.732032 | false | false | false | false |
arloistale/iOSThrive | refs/heads/master | Thrive/Thrive/MoodControl.swift | mit | 1 | //
// MoodControl.swift
// Thrive
//
// Created by Jonathan Lu on 2/7/16.
// Copyright © 2016 UCSC OpenLab. All rights reserved.
//
import UIKit
class MoodControl: UIView {
// MARK: Properties
private var selectedMood = 0 {
didSet {
setNeedsLayout()
}
}
private var moodButtons = [UIButton]()
private var buttonSpacing = 5
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
for (index, mood) in JournalEntry.MoodType.values.enumerate() {
let normalImage = UIImage(named: mood.rawValue)
let tintedImage = normalImage?.imageWithRenderingMode(.AlwaysTemplate)
let button = UIButton()
button.setImage(tintedImage, forState: .Normal)
button.setImage(tintedImage, forState: .Selected)
button.setImage(tintedImage, forState: [.Highlighted, .Selected])
button.tintColor = JournalEntry.MoodType.colors[index]
button.addTarget(self, action: "moodButtonPressed:", forControlEvents: .TouchDown)
moodButtons += [button]
addSubview(button)
}
}
override func layoutSubviews() {
// adjust buttons to size of container
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
for (index, button) in moodButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + buttonSpacing))
button.frame = buttonFrame
}
moodButtons[selectedMood].selected = true
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + 5) * JournalEntry.MoodType.values.count
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Actions
func moodButtonPressed(button: UIButton) {
// unselect previously selected button
moodButtons[selectedMood].selected = false
// select new button
selectedMood = moodButtons.indexOf(button)!
button.selected = true;
}
// MARK: Getters
func getSelectedMoodIndex() -> Int {
return selectedMood
}
}
| 9485f006e4d8fc80402d3a581fb25bdf | 28.219512 | 94 | 0.599332 | false | false | false | false |
jopamer/swift | refs/heads/master | test/SILGen/objc_generic_class.swift | apache-2.0 | 2 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
// Although we don't ever expose initializers and methods of generic classes
// to ObjC yet, a generic subclass of an ObjC class must still use ObjC
// deallocation.
// CHECK-NOT: sil hidden @$SSo7GenericCfd
// CHECK-NOT: sil hidden @$SSo8NSObjectCfd
class Generic<T>: NSObject {
var x: Int = 10
// CHECK-LABEL: sil hidden @$S18objc_generic_class7GenericCfD : $@convention(method) <T> (@owned Generic<T>) -> () {
// CHECK: bb0({{%.*}} : @owned $Generic<T>):
// CHECK: } // end sil function '$S18objc_generic_class7GenericCfD'
// CHECK-LABEL: sil hidden [thunk] @$S18objc_generic_class7GenericCfDTo : $@convention(objc_method) <T> (Generic<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : @unowned $Generic<T>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[NATIVE:%.*]] = function_ref @$S18objc_generic_class7GenericCfD
// CHECK: apply [[NATIVE]]<T>([[SELF_COPY]])
// CHECK: } // end sil function '$S18objc_generic_class7GenericCfDTo'
deinit {
// Don't blow up when 'self' is referenced inside an @objc deinit method
// of a generic class. <rdar://problem/16325525>
self.x = 0
}
}
// CHECK-NOT: sil hidden @$S18objc_generic_class7GenericCfd
// CHECK-NOT: sil hidden @$SSo8NSObjectCfd
// CHECK-LABEL: sil hidden @$S18objc_generic_class11SubGeneric1CfD : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () {
// CHECK: bb0([[SELF:%.*]] : @owned $SubGeneric1<U, V>):
// CHECK: [[SUPER_DEALLOC:%.*]] = objc_super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.1.foreign : <T> (Generic<T>) -> () -> (), $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> ()
// CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int>
// CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]])
class SubGeneric1<U, V>: Generic<Int> {
}
| 7fb2637f87de741c995370a415d8e633 | 46.627907 | 217 | 0.625 | false | false | false | false |
sgr-ksmt/SUNetworkActivityIndicator | refs/heads/master | SUNetworkActivityIndicator/SUNetworkActivityIndicator.swift | mit | 1 | //
// SUNetworkActivityIndicator.swift
//
// Created by Suguru Kishimoto on 2015/12/17.
import Foundation
import UIKit
/**
Notification name for `activeCount` changed.
Contains `activeCount` in notification.object as `Int`
*/
public let NetworkActivityIndicatorActiveCountChangedNotification = "ActiveCountChanged"
/// NetworkActivityIndicator
public class NetworkActivityIndicator {
/// Singleton: shared instance (private var)
private static let sharedInstance = NetworkActivityIndicator()
/// enable sync access (like Objective-C's `@synchronized`)
private let syncQueue = dispatch_queue_create(
"NetworkActivityIndicatorManager.syncQueue",
DISPATCH_QUEUE_SERIAL
)
/**
ActiveCount
If count is above 0,
```
UIApplication.sharedApplication().networkActivityIndicatorVisible
```
is true, else false.
*/
private(set) public var activeCount: Int {
didSet {
UIApplication.sharedApplication()
.networkActivityIndicatorVisible = activeCount > 0
if activeCount < 0 {
activeCount = 0
}
NSNotificationCenter.defaultCenter().postNotificationName(
NetworkActivityIndicatorActiveCountChangedNotification,
object: activeCount
)
}
}
/**
Initializer (private)
- returns: instance
*/
private init() {
self.activeCount = 0
}
public class func shared() -> NetworkActivityIndicator {
return sharedInstance
}
/**
Count up `activeCount` and `networkActivityIndicatorVisible` change to true.
*/
public func start() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount += 1
}
}
/**
Count down `activeCount` and if count is zero, `networkActivityIndicatorVisible` change to false.
*/
public func end() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount -= 1
}
}
/**
Reset `activeCount` and `networkActivityIndicatorVisible` change to false.
*/
public func endAll() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount = 0
}
}
}
| 7f2746ea3adb46e78029b607805fa15b | 21.655914 | 100 | 0.67869 | false | false | false | false |
wangyaqing/LeetCode-swift | refs/heads/master | Solutions/4. Median of Two Sorted Arrays.playground/Contents.swift | mit | 1 | import UIKit
import Foundation
class Solution {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
var a = nums1, b = nums2, m = a.count, n = b.count
if m > n {
return findMedianSortedArrays(nums2, nums1)
}
var min = 0, max = m
while min <= max {
let i = (min + max) / 2
let j = (m + n + 1) / 2 - i
if j != 0, i != m, b[j-1] > a[i] {
min = i + 1
} else if i != 0, j != n, a[i-1] > b[j] {
max = i - 1
} else {
var left = 0
if i == 0 {
left = b[j-1]
} else if j == 0 {
left = a[i-1]
} else {
left = a[i-1] > b[j-1] ? a[i-1] : b[j-1]
}
if (m + n) % 2 == 1 {
return Double(left)
}
var right = 0
if i == m {
right = b[j]
} else if j == n {
right = a[i]
} else {
right = a[i] < b[j] ? a[i] : b[j]
}
return Double(left + right)/2
}
}
return 0
}
}
Solution().findMedianSortedArrays([1,3], [2])
| ac22759f3c1ce200a935d70968141370 | 27.583333 | 75 | 0.31414 | false | false | false | false |
tnako/Challenge_ios | refs/heads/master | Challenge/ChallengesController.swift | gpl-3.0 | 1 | //
// FirstViewController.swift
// Challenge
//
// Created by Anton Korshikov on 25.09.15.
// Copyright © 2015 Anton Korshikov. All rights reserved.
//
import UIKit
import SwiftEventBus
import SwiftyJSON
// ToDo: разобраться с датой, учитывая часовой пояс
struct Challenge {
var num: Int?;
var action: String?;
var start: timeb?;
var end: timeb?;
var item: String?;
var place: String?;
var person: String?;
init(num: Int?, action: String?,
start: timeb?, end: timeb?,
item: String?, place: String?, person: String?) {
self.num = num;
self.action = action;
self.start = start;
self.end = end;
self.item = item;
self.place = place;
self.person = person;
}
}
class ChallengesController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var ChallengesTable: UITableView!;
var ChallengesArray = [Challenge]()
//var SelectedRow:Int?;
override func viewDidLoad() {
super.viewDidLoad()
SwiftEventBus.post("getChallenges")
SwiftEventBus.onMainThread(self, name: "challenges_list") { result in
let list = (result?.object as! NSArray) as Array;
self.ChallengesArray.removeAll()
for (var i = 0; i < list.count; ++i) {
print("one line : \(list[i])")
let json = JSON(list[i])
var endDate:timeb = timeb();
endDate.time = time_t(arc4random_uniform(98) + 1);
self.ChallengesArray.append(Challenge(num: json["challenge_id"].intValue, action: json["action_id"].stringValue, start: timeb(), end: endDate, item: json["item_id"].stringValue, place: json["where_id"].stringValue, person: json["who_id"].stringValue));
}
self.ChallengesTable.reloadData()
}
ChallengesTable.delegate = self
ChallengesTable.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ChallengesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ChallengesTable.dequeueReusableCellWithIdentifier("OneRow", forIndexPath: indexPath) as! ChallengesTableViewCell
let row = indexPath.row
cell.HeaderLabel?.text = "Quest #\(ChallengesArray[row].num!)";
let minutes:UInt = UInt(ChallengesArray[row].end!.time);
if (minutes > 90 || minutes < 10) {
// проголосовал сам или учавствовал
cell.accessoryType = .Checkmark;
} else {
cell.accessoryType = .DisclosureIndicator;
}
if (minutes > 70) {
cell.backgroundColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1);
cell.TimerLabel.text = "Start in \(minutes) minute";
cell.ProgressBar.progress = Float(minutes) / 100.0;
} else {
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1);
cell.TimerLabel.text = "Ends in \(minutes) minute";
cell.ProgressBar.progress = 1 - Float(minutes) / 100.0;
}
return cell
}
/*
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
ChallengesTable.deselectRowAtIndexPath(indexPath, animated: true)
SelectedRow = indexPath.row;
}
override func prefersStatusBarHidden() -> Bool {
if self.navigationController?.navigationBarHidden == true {
return true
} else {
return false
}
}
*/
// ToDo: передача выбранного номера
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowChallenge" {
print("ShowChallenge debug");
if let indexPath = self.ChallengesTable.indexPathForSelectedRow {
let challenge = ChallengesArray[indexPath.row];
let controller = segue.destinationViewController as! ChallengeDetailViewController;
//controller.PhotoArray.append("Quest #\(challenge.num!)");
//ToDo: передача номера квеста
}
}
}
}
| a1d59f1c8bd26bb777495122d29b0bc9 | 31.282759 | 268 | 0.596881 | false | false | false | false |
artsy/eigen | refs/heads/main | ios/Artsy/View_Controllers/Live_Auctions/LotListCollectionViewCell.swift | mit | 1 | import UIKit
import Interstellar
class LotListCollectionViewCell: UICollectionViewCell {
static let CellIdentifier = "LotCellIdentifier"
static let Height: CGFloat = 80
let lotImageView = UIImageView()
let hammerImageView = UIImageView(image: UIImage(asset: .Lot_bidder_hammer_white))
let labelContainerView = LotListCollectionViewCell._labelContainerView()
let closedLabel = LotListCollectionViewCell._closedLabel()
let currentLotIndicatorImageView = UIImageView()
let lotNumberLabel = LotListCollectionViewCell._lotNumberLabel()
let artistsNamesLabel = LotListCollectionViewCell._artistNamesLabel()
let currentAskingPriceLabel = LotListCollectionViewCell._currentAskingPriceLabel()
let topSeparator = ARSeparatorView()
let bottomSeparator = ARSeparatorView()
var isNotTopCell = true
fileprivate var userInterfaceNeedsSetup = true
fileprivate var lotStateSubscription: ObserverToken<LotState>?
fileprivate var askingPriceSubscription: ObserverToken<UInt64>?
deinit {
lotStateSubscription?.unsubscribe()
askingPriceSubscription?.unsubscribe()
}
}
private typealias Overrides = LotListCollectionViewCell
extension Overrides {
override func prepareForReuse() {
super.prepareForReuse()
defer {
lotStateSubscription = nil
askingPriceSubscription = nil
}
lotStateSubscription?.unsubscribe()
askingPriceSubscription?.unsubscribe()
}
}
private typealias PublicFunctions = LotListCollectionViewCell
extension PublicFunctions {
func configureForViewModel(_ viewModel: LiveAuctionLotViewModelType, indexPath: IndexPath) {
let currencySymbol = viewModel.currencySymbol
if userInterfaceNeedsSetup {
userInterfaceNeedsSetup = false
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.align(toView: self)
lotImageView.contentMode = .scaleAspectFill
lotImageView.clipsToBounds = true
}
resetViewHierarchy()
isNotTopCell = (indexPath.item > 0)
self.lotStateSubscription = viewModel.lotStateSignal.subscribe { [weak self] state in
self?.setLotState(state)
}
askingPriceSubscription = viewModel
.askingPriceSignal
.subscribe { [weak self] askingPrice in
self?.currentAskingPriceLabel.text = askingPrice.convertToDollarString(currencySymbol)
return
}
lotImageView.ar_setImage(with: viewModel.urlForThumbnail)
lotNumberLabel.text = viewModel.formattedLotIndexDisplayString
artistsNamesLabel.text = viewModel.lotArtist
}
}
| daff6bf6e7bfcd34c464919c0784c1e6 | 34.166667 | 102 | 0.716734 | false | false | false | false |
azukinohiroki/positionmaker2 | refs/heads/master | positionmaker2/CoreDataHelper.swift | mit | 1 | //
// CoreDataHelper.swift
// positionmaker2
//
// Created by Hiroki Taoka on 2015/06/11.
// Copyright (c) 2015年 azukinohiroki. All rights reserved.
//
import Foundation
import CoreData
class CoreDataHelper {
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.azk.hr.positionmaker2" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "positionmaker2", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("positionmaker2.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(String(describing: error)), \(error!.userInfo)")
// abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(String(describing: error)), \(error!.userInfo)")
// abort()
}
}
}
}
}
| ef59019ee2acf516804f73beb3e36072 | 46.069767 | 286 | 0.720356 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Rules/Style/UnusedOptionalBindingRule.swift | mit | 1 | import SwiftSyntax
struct UnusedOptionalBindingRule: SwiftSyntaxRule, ConfigurationProviderRule {
var configuration = UnusedOptionalBindingConfiguration(ignoreOptionalTry: false)
init() {}
static let description = RuleDescription(
identifier: "unused_optional_binding",
name: "Unused Optional Binding",
description: "Prefer `!= nil` over `let _ =`",
kind: .style,
nonTriggeringExamples: [
Example("if let bar = Foo.optionalValue {\n" +
"}\n"),
Example("if let (_, second) = getOptionalTuple() {\n" +
"}\n"),
Example("if let (_, asd, _) = getOptionalTuple(), let bar = Foo.optionalValue {\n" +
"}\n"),
Example("if foo() { let _ = bar() }\n"),
Example("if foo() { _ = bar() }\n"),
Example("if case .some(_) = self {}"),
Example("if let point = state.find({ _ in true }) {}")
],
triggeringExamples: [
Example("if let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {\n" +
"}\n"),
Example("guard let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {\n" +
"}\n"),
Example("if let (first, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let (first, _) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let (_, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let ↓(_, _, _) = getOptionalTuple(), let bar = Foo.optionalValue {\n" +
"}\n"),
Example("func foo() {\nif let ↓_ = bar {\n}\n")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(ignoreOptionalTry: configuration.ignoreOptionalTry)
}
}
private extension UnusedOptionalBindingRule {
final class Visitor: ViolationsSyntaxVisitor {
private let ignoreOptionalTry: Bool
init(ignoreOptionalTry: Bool) {
self.ignoreOptionalTry = ignoreOptionalTry
super.init(viewMode: .sourceAccurate)
}
override func visitPost(_ node: OptionalBindingConditionSyntax) {
guard let pattern = node.pattern.as(ExpressionPatternSyntax.self),
pattern.expression.isDiscardExpression else {
return
}
if ignoreOptionalTry,
let tryExpr = node.initializer?.value.as(TryExprSyntax.self),
tryExpr.questionOrExclamationMark?.tokenKind == .postfixQuestionMark {
return
}
violations.append(pattern.expression.positionAfterSkippingLeadingTrivia)
}
}
}
private extension ExprSyntax {
var isDiscardExpression: Bool {
if self.is(DiscardAssignmentExprSyntax.self) {
return true
} else if let tuple = self.as(TupleExprSyntax.self) {
return tuple.elementList.allSatisfy { elem in
elem.expression.isDiscardExpression
}
}
return false
}
}
| 2330d1a66559c3bd80340071d306d30c | 36.218391 | 99 | 0.561149 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/dynamic_lookup.swift | apache-2.0 | 1 |
// RUN: %target-swift-frontend -module-name dynamic_lookup -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name dynamic_lookup -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s --check-prefix=GUARANTEED
// REQUIRES: objc_interop
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F
func direct_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.f!()
}
// CHECK: } // end sil function '$S14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$S14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F
func direct_to_protocol(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.g!()
}
// CHECK: } // end sil function '$S14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$S14dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F
func direct_to_static_method(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
var obj = obj
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: end_access [[READ]]
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = objc_method [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: destroy_value [[OBJBOX]]
type(of: obj).staticF!()
}
// } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}'
// CHECK-LABEL: sil hidden @$S14dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F
func opt_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
var obj = obj
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]]
// CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]]
// CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [callee_guaranteed] [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]]
// CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]]
// CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1
// CHECK: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt
// CHECK: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]]
// CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_guaranteed () -> ()>
// CHECK: dealloc_stack [[OPT_TMP]]
var of: (() -> ())! = obj.f
// Exit
// CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject }
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F
func forced_without_outer(_ obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F
func opt_to_static_method(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF: (() -> ())! = type(of: obj).staticF
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
func opt_to_property(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: project_box [[INT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[BOUND_METHOD]]
// CHECK: [[VALUE:%[0-9]+]] = apply [[B]]() : $@callee_guaranteed () -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[BOUND_METHOD]]
// CHECK: br bb3
var i: Int = obj.value!
}
// CHECK: } // end sil function '$S14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$S14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: project_box [[INT_BOX]]
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// GUARANTEED: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]])
// GUARANTEED: [[BEGIN_BORROW:%.*]] = begin_borrow [[BOUND_METHOD]]
// GUARANTEED: [[VALUE:%[0-9]+]] = apply [[BEGIN_BORROW]]
// GUARANTEED: end_borrow [[BEGIN_BORROW]] from [[BOUND_METHOD]]
// GUARANTEED: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[VALUE]] to [trivial] [[VALUETEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[BOUND_METHOD]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$S14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
func direct_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: alloc_box ${ var Int }
// CHECK: project_box
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
var x: Int = obj[i]!
}
// CHECK: } // end sil function '$S14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$S14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: [[PBI:%.*]] = project_box [[I_BOX]]
// GUARANTEED: store [[I]] to [trivial] [[PBI]] : $*Int
// GUARANTEED: alloc_box ${ var Int }
// GUARANTEED: project_box
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// GUARANTEED: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// GUARANTEED: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]])
// GUARANTEED: [[BORROW:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// GUARANTEED: [[RESULT:%[0-9]+]] = apply [[BORROW]]([[I]])
// GUARANTEED: end_borrow [[BORROW]] from [[GETTER_WITH_SELF]]
// GUARANTEED: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[GETTER_WITH_SELF]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$S14dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F
func opt_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X
// CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject }
// CHECK: return [[X]] : $X
return obj as! X
}
@objc class Juice { }
@objc protocol Fruit {
@objc optional var juice: Juice { get }
}
// CHECK-LABEL: sil hidden @$S14dynamic_lookup7consumeyyAA5Fruit_pF
// CHECK: bb0(%0 : $Fruit):
// CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice>
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2
// CHECK: bb1([[FN:%.*]] : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice
// CHECK: [[B:%.*]] = begin_borrow [[METHOD]]
// CHECK: [[RESULT:%.*]] = apply [[B]]() : $@callee_guaranteed () -> @owned Juice
// CHECK: end_borrow [[B]]
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: store [[RESULT]] to [init] [[PAYLOAD]]
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: destroy_value [[METHOD]]
// CHECK: br bb3
// CHECK: bb2:
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return
func consume(_ fruit: Fruit) {
_ = fruit.juice
}
// rdar://problem/29249513 -- looking up an IUO member through AnyObject
// produces a Foo!? type. The SIL verifier did not correctly consider Optional
// to be the lowering of IUO (which is now eliminated by SIL lowering).
@objc protocol IUORequirement {
var iuoProperty: AnyObject! { get }
}
func getIUOPropertyDynamically(x: AnyObject) -> Any {
return x.iuoProperty
}
| 97c8569371d479c1585612008bc707c3 | 53.038781 | 229 | 0.567665 | false | false | false | false |
wwq0327/iOS9Example | refs/heads/master | DemoLists/DemoLists/HomePageAnimationUtil.swift | apache-2.0 | 1 | //
// HomePageAnimationUtil.swift
// DemoLists
//
// Created by wyatt on 15/12/3.
// Copyright © 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
let kBottomLineWith: CGFloat = 272.0
class HomePageAnimationUtil: NSObject {
// 顶端两行label的动画
class func titleLabelAnimationWithLabel(label: UILabel, view: UIView) {
UIView.animateWithDuration(1) { () -> Void in
label.transform = CGAffineTransformIdentity
}
}
// 手机图标的动画
class func phoneIconImageViewAnimation(imageView: UIImageView, view: UIView) {
UIView.animateWithDuration(1.5, animations: { () -> Void in
// 回归原始位置
imageView.transform = CGAffineTransformIdentity
// 透明度为1,即完全显示出imageview
imageView.alpha = 1.0
}, completion: nil)
}
// 直线的动画
class func textFieldBottomLineAnimationWithConstraint(constraint: NSLayoutConstraint, view: UIView) {
// 先设定好约束,但此是在界面上并没有进行刷新
constraint.constant = kBottomLineWith
UIView.animateWithDuration(1.5) { () -> Void in
// 开始界面刷新,线束开始起作用
view.layoutIfNeeded()
}
}
// 按钮动画
class func registerButtonAnimation(button: UIButton, view: UIView, progress: CGFloat) {
}
// 版权文字动画
class func tipsLabelMaskAnination(view: UIView, beginTime: NSTimeInterval) {
}
}
| 644cbaf3a05d5d5003f3dddc78e3d914 | 25.811321 | 105 | 0.622097 | false | false | false | false |
lawrencelomax/XMLParsable | refs/heads/master | XMLParsable/XML/LibXML/LibXMLDOM.swift | mit | 1 | //
// LibXMLDOM.swift
// XMLParsable
//
// Created by Lawrence Lomax on 26/08/2014.
// Copyright (c) 2014 Lawrence Lomax. All rights reserved.
//
import Foundation
import swiftz_core
public let LibXMLDOMErrorDomain = InMyDomain("libxml.dom")
typealias LibXMLDOMNodeSequence = SequenceOf<xmlNodePtr>
internal final class LibXMLDOM {
struct Context {
let document: xmlDocPtr
let rootNode: xmlNodePtr
init (document: xmlDocPtr, rootNode: xmlNodePtr){
self.document = document
self.rootNode = rootNode
}
func dispose() {
if self.rootNode != nil {
xmlFreeDoc(self.document)
}
}
}
internal class func error(message: String) -> NSError {
return NSError(domain: LibXMLDOMErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: message])
}
internal class func createWithURL(url: NSURL) -> Result<LibXMLDOM.Context> {
let document = self.documentPointer(url)
return { LibXMLDOM.Context(document: document, rootNode: $0) } <^> self.rootNode(document)
}
internal class func createWithData(data: NSData) -> Result<LibXMLDOM.Context> {
let document = self.documentPointer(data)
return { LibXMLDOM.Context(document: document, rootNode: $0) } <^> self.rootNode(document)
}
internal class func childrenOfNode(node: xmlNodePtr) -> LibXMLDOMNodeSequence {
var nextNode = LibXMLDOMGetChildren(node)
let generator: GeneratorOf<xmlNodePtr> = GeneratorOf {
if (nextNode == nil) {
return nil
}
let currentNode = nextNode
nextNode = LibXMLDOMGetSibling(nextNode)
return currentNode
}
return SequenceOf(generator)
}
private class func rootNode(document: xmlDocPtr) -> Result<xmlNodePtr> {
if document == nil {
return Result.error(self.error("Could Not Parse Document"))
}
let rootNode = xmlDocGetRootElement(document)
if rootNode == nil {
xmlFreeDoc(document)
return Result.error(self.error("Could Not Get Root element"))
}
return Result.value(rootNode)
}
private class func documentPointer(url: NSURL) -> xmlDocPtr {
let urlString = url.path
let cString = urlString?.cStringUsingEncoding(NSUTF8StringEncoding)
return xmlParseFile(cString!)
}
private class func documentPointer(data: NSData) -> xmlDocPtr {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
let cString = string.UTF8String
let length = strlen(cString)
return xmlParseMemory(cString, Int32(length))
}
}
| 78434883d8d52337ec91d0a8f1ad6175 | 28.113636 | 105 | 0.685792 | false | false | false | false |
tablexi/txi-ios-bootstrap | refs/heads/develop | Example/Tests/Managers/EnvironmentManagerSpec.swift | mit | 1 | //
// EnvironmentManagerSpec.swift
// TXIBootstrap
//
// Created by Ed Lafoy on 12/11/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TXIBootstrap
class EnvironmentManagerSpec: QuickSpec {
var bundle: Bundle { return Bundle(for: type(of: self)) }
let userDefaults = UserDefaults(suiteName: "test")!
let userDefaultsKey = "environment"
var environmentValues: [[String: AnyObject]] {
let path = self.bundle.path(forResource: "Environments", ofType: "plist")!
let values = NSArray(contentsOfFile: path) as? [[String: AnyObject]]
return values ?? []
}
var environmentManager: EnvironmentManager<TestEnvironment>!
override func spec() {
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
expect(self.environmentValues.count).to(beGreaterThan(0))
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("reads environments from Environments.plist") {
expect(self.environmentManager.environments.count).to(equal(self.environmentValues.count))
}
it("populates valid environments") {
self.validateEnvironmentAtIndex(index: 0)
self.validateEnvironmentAtIndex(index: 1)
}
it("saves the selected environment in user defaults") {
let environment1 = self.environmentManager.environments[0]
let environment2 = self.environmentManager.environments[1]
self.environmentManager.currentEnvironment = environment1
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment1.name))
self.environmentManager.currentEnvironment = environment2
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment2.name))
}
it("shows the correct current environment if it's changed elsewhere by another instance of EnvironmentManager") {
let otherEnvironmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.environments[0]))
self.environmentManager.currentEnvironment = self.environmentManager.environments[1]
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
}
context("with no stored environment") {
var defaultEnvironment: TestEnvironment!
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
defaultEnvironment = self.environmentManager.environments[0]
}
it("defaults to first environment") {
expect(self.environmentManager.currentEnvironment).to(equal(defaultEnvironment))
}
}
context("with saved environment") {
beforeEach {
self.userDefaults.setValue("Stage", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("uses the saved environment") {
guard let stageEnvironment = self.environmentManager.environments.filter({ $0.name == "Stage" }).first else { return fail() }
expect(self.environmentManager.currentEnvironment).to(equal(stageEnvironment))
}
}
}
func validateEnvironmentAtIndex(index: Int) {
let environment = environmentManager.environments[index]
let values = environmentValues[index]
guard let name = values["Name"] as? String,
let domain = values["Domain"] as? String,
let key = values["Key"] as? String else { return fail() }
expect(environment.name).to(equal(name))
expect(environment.domain).to(equal(domain))
expect(environment.key).to(equal(key))
}
}
class TestEnvironment: Environment, CustomDebugStringConvertible {
var name: String = ""
var domain: String = ""
var key: String = ""
required init?(environment: [String: AnyObject]) {
guard let name = environment["Name"] as? String, let domain = environment["Domain"] as? String, let key = environment["Key"] as? String else { return nil }
self.name = name
self.domain = domain
self.key = key
}
var debugDescription: String { return self.name }
}
func ==(left: TestEnvironment, right: TestEnvironment) -> Bool { return left.name == right.name }
| cb3f4ffc2e1827fd29017eb6b6457e62 | 38.754237 | 159 | 0.715199 | false | true | false | false |
jemartti/Hymnal | refs/heads/master | Hymnal/ScheduleViewController.swift | mit | 1 | //
// ScheduleViewController.swift
// Hymnal
//
// Created by Jacob Marttinen on 5/6/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
import CoreData
// MARK: - ScheduleViewController: UITableViewController
class ScheduleViewController: UITableViewController {
// MARK: Properties
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var indicator: UIActivityIndicatorView!
var schedule: [ScheduleLineEntity]!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialiseUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if it's time to update the schedule
var forceFetch = false
if !UserDefaults.standard.bool(forKey: "hasFetchedSchedule") {
forceFetch = true
} else {
let lastScheduleFetch = UserDefaults.standard.double(forKey: "lastScheduleFetch")
if (lastScheduleFetch + 60*60*24 < NSDate().timeIntervalSince1970) {
forceFetch = true
}
}
// Check for existing Schedule in Model
let scheduleFR = NSFetchRequest<NSManagedObject>(entityName: "ScheduleLineEntity")
scheduleFR.sortDescriptors = [NSSortDescriptor(key: "sortKey", ascending: true)]
do {
let scheduleLineEntities = try appDelegate.stack.context.fetch(scheduleFR) as! [ScheduleLineEntity]
if scheduleLineEntities.count <= 0 || forceFetch {
schedule = [ScheduleLineEntity]()
fetchSchedule()
} else {
schedule = scheduleLineEntities
tableView.reloadData()
}
} catch _ as NSError {
alertUserOfFailure(message: "Data load failed.")
}
}
// UI+UX Functionality
private func initialiseUI() {
view.backgroundColor = .white
indicator = createIndicator()
// Set up the Navigation bar
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.stop,
target: self,
action: #selector(ScheduleViewController.returnToRoot)
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.refresh,
target: self,
action: #selector(ScheduleViewController.fetchSchedule)
)
navigationItem.title = "Schedule"
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = Constants.UI.Armadillo
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: Constants.UI.Armadillo
]
}
private func createIndicator() -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView(
style: UIActivityIndicatorView.Style.gray
)
indicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0);
indicator.center = view.center
view.addSubview(indicator)
indicator.bringSubviewToFront(view)
return indicator
}
private func alertUserOfFailure( message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(
title: "Action Failed",
message: message,
preferredStyle: UIAlertController.Style.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertAction.Style.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
@objc func returnToRoot() {
dismiss(animated: true, completion: nil)
}
// MARK: Data Management Functions
@objc func fetchSchedule() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
indicator.startAnimating()
MarttinenClient.sharedInstance().getSchedule() { (scheduleRaw, error) in
if error != nil {
self.alertUserOfFailure(message: "Data download failed.")
} else {
self.appDelegate.stack.performBackgroundBatchOperation { (workerContext) in
// Cleanup any existing data
let DelAllScheduleLineEntities = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "ScheduleLineEntity")
)
do {
try workerContext.execute(DelAllScheduleLineEntities)
}
catch {
self.alertUserOfFailure(message: "Data load failed.")
}
// Clear local properties
self.schedule = [ScheduleLineEntity]()
// We have to clear data in active contexts after performing batch operations
self.appDelegate.stack.reset()
DispatchQueue.main.async {
self.parseAndSaveSchedule(scheduleRaw)
self.tableView.reloadData()
UserDefaults.standard.set(true, forKey: "hasFetchedSchedule")
UserDefaults.standard.set(NSDate().timeIntervalSince1970, forKey: "lastScheduleFetch")
UserDefaults.standard.synchronize()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
}
}
}
private func parseAndSaveSchedule(_ scheduleRaw: [ScheduleLine]) {
for i in 0 ..< scheduleRaw.count {
let scheduleLineRaw = scheduleRaw[i]
let scheduleLineEntity = ScheduleLineEntity(context: self.appDelegate.stack.context)
scheduleLineEntity.sortKey = Int32(i)
scheduleLineEntity.isSunday = scheduleLineRaw.isSunday
scheduleLineEntity.locality = scheduleLineRaw.locality
var titleString = scheduleLineRaw.dateString + ": "
if let status = scheduleLineRaw.status {
titleString = titleString + status
} else if let localityPretty = scheduleLineRaw.localityPretty {
titleString = titleString + localityPretty
}
scheduleLineEntity.title = titleString
var subtitleString = ""
if let missionaries = scheduleLineRaw.missionaries {
subtitleString = subtitleString + missionaries
}
if scheduleLineRaw.with.count > 0 {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(with "
for i in 0 ..< scheduleLineRaw.with.count {
if i != 0 {
subtitleString = subtitleString + " and "
}
subtitleString = subtitleString + scheduleLineRaw.with[i]
}
subtitleString = subtitleString + ")"
}
if let isAM = scheduleLineRaw.am, let isPM = scheduleLineRaw.pm {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
if isAM && isPM {
subtitleString = subtitleString + "(AM & PM)"
} else if isAM {
subtitleString = subtitleString + "(AM Only)"
} else if isPM {
subtitleString = subtitleString + "(PM Only)"
}
}
if let comment = scheduleLineRaw.comment {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(" + comment + ")"
}
scheduleLineEntity.subtitle = subtitleString
self.schedule.append(scheduleLineEntity)
}
self.appDelegate.stack.save()
}
// MARK: Table View Data Source
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return schedule.count
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ScheduleLineTableViewCell"
)!
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
cell.textLabel?.text = scheduleLine.title!
cell.detailTextLabel?.text = scheduleLine.subtitle!
cell.backgroundColor = .white
cell.textLabel?.textColor = Constants.UI.Armadillo
cell.detailTextLabel?.textColor = Constants.UI.Armadillo
if scheduleLine.isSunday {
cell.textLabel?.textColor = .red
cell.detailTextLabel?.textColor = .red
}
return cell
}
override func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
// Only load information if the ScheduleLine refers to a specific locality
guard let key = scheduleLine.locality else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// Protect against missing locality
guard let locality = Directory.directory!.localities[key] else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// If we have location details, load the LocalityView
// Otherwise, jump straight to ContactView
if locality.hasLocationDetails {
let localityViewController = storyboard!.instantiateViewController(
withIdentifier: "LocalityViewController"
) as! LocalityViewController
localityViewController.locality = locality
navigationController!.pushViewController(localityViewController, animated: true)
} else {
let contactViewController = storyboard!.instantiateViewController(
withIdentifier: "ContactViewController"
) as! ContactViewController
contactViewController.locality = locality
navigationController!.pushViewController(contactViewController, animated: true)
}
}
}
| 5fb49468454bc1d0d4428a7a576680f7 | 35.654952 | 111 | 0.560446 | false | false | false | false |
SwiftAndroid/swift | refs/heads/master | stdlib/public/core/ArrayType.swift | apache-2.0 | 2 | //===--- ArrayType.swift - Protocol for Array-like types ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public // @testable
protocol _ArrayProtocol
: RangeReplaceableCollection,
ArrayLiteralConvertible
{
//===--- public interface -----------------------------------------------===//
/// The number of elements the Array stores.
var count: Int { get }
/// The number of elements the Array can store without reallocation.
var capacity: Int { get }
/// `true` if and only if the Array is empty.
var isEmpty: Bool { get }
/// An object that guarantees the lifetime of this array's elements.
var _owner: AnyObject? { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
subscript(index: Int) -> Iterator.Element { get set }
//===--- basic mutations ------------------------------------------------===//
/// Reserve enough space to store minimumCapacity elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
mutating func reserveCapacity(_ minimumCapacity: Int)
/// Operator form of `append(contentsOf:)`.
func += <
S : Sequence where S.Iterator.Element == Iterator.Element
>(lhs: inout Self, rhs: S)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
///
/// - Precondition: `i <= count`.
mutating func insert(_ newElement: Iterator.Element, at i: Int)
/// Remove and return the element at the given index.
///
/// - returns: The removed element.
///
/// - Complexity: Worst case O(N).
///
/// - Precondition: `count > index`.
@discardableResult
mutating func remove(at index: Int) -> Iterator.Element
//===--- implementation detail -----------------------------------------===//
associatedtype _Buffer : _ArrayBufferProtocol
init(_ buffer: _Buffer)
// For testing.
var _buffer: _Buffer { get }
}
| 508f0d1820e19446faab020f7a9e7a6e | 31.397436 | 80 | 0.601504 | false | false | false | false |
Gitliming/Demoes | refs/heads/master | Demoes/Demoes/Common/SQLiteManager.swift | apache-2.0 | 1 | //
// SQLiteManager.swift
// Demoes
//
// Created by 张丽明 on 2017/3/12.
// Copyright © 2017年 xpming. All rights reserved.
//
import UIKit
import FMDB
class SQLiteManager: NSObject {
// 工具单例子
static let SQManager:SQLiteManager = SQLiteManager()
var DB:FMDatabase?
var DBQ:FMDatabaseQueue?
override init() {
super.init()
openDB("Demoes_MyNote.sqlite")
}
// 打开数据库
func openDB(_ name:String?){
let path = getCachePath(name!)
print(path)
DB = FMDatabase(path: path)
DBQ = FMDatabaseQueue(path: path)
guard let db = DB else {print("数据库对象创建失败")
return}
if !db.open(){
print("打开数据库失败")
return
}
if creatTable() {
print("创表成功!!!!")
}
}
// 创建数据库
func creatTable() -> Bool{
let sqlit1 = "CREATE TABLE IF NOT EXISTS T_MyNote( \n" +
"stateid INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
"id TEXT, \n" +
"title TEXT, \n" +
"desc TEXT, \n" +
"creatTime TEXT \n" +
");"
//执行语句
return DB!.executeUpdate(sqlit1, withArgumentsIn: nil)
}
//MARK:-- 拼接路径
func getCachePath(_ fileName:String) -> String{
let path1 = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory
, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path2 = path1! + "/" + fileName
return path2
}
}
| a57d598af572e37612619bfbfa4d2e23 | 25.5 | 103 | 0.554327 | false | false | false | false |
nahive/spotify-notify | refs/heads/master | SpotifyNotify/Interactors/NotificationsInteractor.swift | unlicense | 1 | // NotificationsInteractor.swift
// SpotifyNotify
//
// Created by 先生 on 22/02/2018.
// Copyright © 2018 Szymon Maślanka. All rights reserved.
//
import Cocoa
import ScriptingBridge
#if canImport(UserNotifications)
import UserNotifications
#endif
final class NotificationsInteractor {
private let preferences = UserPreferences()
private let spotifyInteractor = SpotifyInteractor()
private var previousTrack: Track?
private var currentTrack: Track?
func showNotification() {
// return if notifications are disabled
guard preferences.notificationsEnabled else {
print("⚠ notification disabled")
return
}
// return if notifications are disabled when in focus
if spotifyInteractor.isFrontmost && preferences.notificationsDisableOnFocus {
print("⚠ spotify is frontmost")
return
}
previousTrack = currentTrack
currentTrack = spotifyInteractor.currentTrack
// return if previous track is same as previous => play/pause and if it's disabled
guard currentTrack != previousTrack || preferences.notificationsPlayPause else {
print("⚠ spotify is changing from play/pause")
return
}
guard spotifyInteractor.isPlaying else {
print("⚠ spotify is not playing")
return
}
// return if current track is nil
guard let currentTrack = currentTrack else {
print("⚠ spotify has no track available")
return
}
// Create and deliver notifications
let viewModel = NotificationViewModel(track: currentTrack,
showSongProgress: preferences.showSongProgress,
songProgress: spotifyInteractor.playerPosition)
createModernNotification(using: viewModel)
}
/// Called by notification delegate
func handleAction() {
spotifyInteractor.nextTrack()
}
// MARK: - Modern Notfications
/// Use `UserNotifications` to deliver the notification in macOS 10.14 and above
@available(OSX 10.14, *)
private func createModernNotification(using viewModel: NotificationViewModel) {
let notification = UNMutableNotificationContent()
notification.title = viewModel.title
notification.subtitle = viewModel.subtitle
notification.body = viewModel.body
notification.categoryIdentifier = NotificationIdentifier.category
// decide whether to add sound
if preferences.notificationsSound {
notification.sound = .default
}
if preferences.showAlbumArt {
addArtwork(to: notification, using: viewModel)
} else {
deliverModernNotification(identifier: viewModel.identifier, content: notification)
}
}
@available(OSX 10.14, *)
private func addArtwork(to notification: UNMutableNotificationContent, using viewModel: NotificationViewModel) {
guard preferences.showAlbumArt else { return }
viewModel.artworkURL?.asyncImage { [weak self] art in
// Create a mutable copy of the downloaded artwork
var artwork = art
// If user wants round album art, then round the image
if self?.preferences.roundAlbumArt == true {
artwork = art?.applyCircularMask()
}
// Save the artwork to the temporary directory
guard let url = artwork?.saveToTemporaryDirectory(withName: "artwork") else { return }
// Add the attachment to the notification
do {
let attachment = try UNNotificationAttachment(identifier: "artwork", url: url)
notification.attachments = [attachment]
} catch {
print("Error creating attachment: " + error.localizedDescription)
}
// remove previous notification and replace it with one with image
DispatchQueue.main.async {
self?.deliverModernNotification(identifier: viewModel.identifier, content: notification)
}
}
}
/// Deliver notifications using `UNUserNotificationCenter`
@available(OSX 10.14, *)
private func deliverModernNotification(identifier: String, content: UNMutableNotificationContent) {
// Create a request
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
// Remove delivered notifications
notificationCenter.removeAllDeliveredNotifications()
// Deliver current notification
notificationCenter.add(request)
// remove after userset number of seconds if not taken action
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(preferences.notificationsLength)) {
notificationCenter.removeAllDeliveredNotifications()
}
}
}
| 8e349e5d40f7392ca68296fdb170abd7 | 33.762238 | 116 | 0.659425 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Mac/MainWindow/Timeline/TimelineContainerView.swift | mit | 1 | //
// TimelineContainerView.swift
// NetNewsWire
//
// Created by Brent Simmons on 2/13/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
final class TimelineContainerView: NSView {
private var contentViewConstraints: [NSLayoutConstraint]?
var contentView: NSView? {
didSet {
if contentView == oldValue {
return
}
if let currentConstraints = contentViewConstraints {
NSLayoutConstraint.deactivate(currentConstraints)
}
contentViewConstraints = nil
oldValue?.removeFromSuperviewWithoutNeedingDisplay()
if let contentView = contentView {
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
let constraints = constraintsToMakeSubViewFullSize(contentView)
NSLayoutConstraint.activate(constraints)
contentViewConstraints = constraints
}
}
}
}
| 16726a51dd5b36c60922f2c9171eb91c | 22.594595 | 67 | 0.754868 | false | false | false | false |
antonio081014/LeetCode-CodeBase | refs/heads/main | Swift/expression-add-operators.swift | mit | 1 | class Solution {
func addOperators(_ num: String, _ target: Int) -> [String] {
var result = [String]()
let num = Array(num)
func dfs(_ path: String, _ currentIndex: Int, _ value: Int, _ lastValue: Int) {
if currentIndex == num.count {
if value == target {
result.append(path)
}
return
}
var sum = 0
for index in currentIndex ..< num.count {
if num[currentIndex] == Character("0"), index != currentIndex {
return
}
sum = sum * 10 + Int(String(num[index]))!
if currentIndex == 0 {
dfs(path + "\(sum)", index + 1, sum, sum)
} else {
dfs(path + "+\(sum)", index + 1, value + sum, sum)
dfs(path + "-\(sum)", index + 1, value - sum, -sum)
dfs(path + "*\(sum)", index + 1, value - lastValue + lastValue * sum, lastValue * sum)
}
}
}
dfs("", 0, 0, 0)
return result
}
}
| 3ae5cf63374aca938cc6160f9c7a9c2d | 33.852941 | 106 | 0.396624 | false | false | false | false |
zyhndesign/SDX_DG | refs/heads/master | sdxdg/sdxdg/MatchListViewController.swift | apache-2.0 | 1 | //
// MatchListViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/20.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
import AlamofireObjectMapper
class MatchListViewController : UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
var innerClothList:[GarmentModel] = []
var outterClothList:[GarmentModel] = []
var trouserClothList:[GarmentModel] = []
@IBOutlet var innerClothBtn: UIButton!
@IBOutlet var outterClothBtn: UIButton!
@IBOutlet var bottomClothBtn: UIButton!
@IBOutlet var matchCollectionView: UICollectionView!
@IBOutlet var modelView: UIImageView!
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
let clothLayer:UIImageView = UIImageView();
let trousersLayer:UIImageView = UIImageView();
let outClothLayer:UIImageView = UIImageView();
var inClothObject:GarmentModel?
var outClothObject:GarmentModel?
var trouserObject:GarmentModel?
var garmentType:Int = 0
var selectGarmentModelList:[GarmentModel] = []
let refresh = UIRefreshControl.init()
let pageLimit:Int = 10
var inClothPageNum:Int = 0
var outClotPageNum:Int = 0
var trouserPageNum = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
matchCollectionView.register(MatchListCell.self, forCellWithReuseIdentifier:"cell")
matchCollectionView.delegate = self;
matchCollectionView.dataSource = self;
clothLayer.frame = CGRect.init(x: 0, y:0, width: 100, height: 240)
clothLayer.contentMode = UIViewContentMode.scaleAspectFit
outClothLayer.frame = CGRect.init(x: 0, y: 0, width: 100, height: 240)
outClothLayer.contentMode = UIViewContentMode.scaleAspectFit
trousersLayer.frame = CGRect.init(x: 0, y: 00, width: 100, height: 240)
trousersLayer.contentMode = UIViewContentMode.scaleAspectFit
modelView.addSubview(clothLayer)
modelView.addSubview(trousersLayer)
modelView.addSubview(outClothLayer)
refresh.backgroundColor = UIColor.white
refresh.tintColor = UIColor.lightGray
refresh.attributedTitle = NSAttributedString(string:"下拉刷新")
refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged)
self.matchCollectionView.addSubview(refresh)
loadCostumeData(category: 0,limit: 10,offset: 0)
NotificationCenter.default.addObserver(self, selector:#selector(self.updateMatchModel(notifaction:)), name: NSNotification.Name(rawValue: "modelMatch"), object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(self.filterMatch(notifaction:)), name: NSNotification.Name(rawValue: "filterMatch"), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("disppear...")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did appear...")
}
func refreshLoadingData(){
if garmentType == 0{
loadCostumeData(category: 0,limit: pageLimit,offset: pageLimit * inClothPageNum)
}
else if garmentType == 1{
loadCostumeData(category: 1,limit: pageLimit,offset: pageLimit * outClotPageNum)
}
else if garmentType == 2{
loadCostumeData(category: 2,limit: pageLimit,offset: pageLimit * trouserPageNum)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
NotificationCenter.default.removeObserver(self)
}
func updateMatchModel(notifaction: NSNotification){
let garmentModel:GarmentModel = (notifaction.object as? GarmentModel)!
if garmentType == 0{
clothLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
inClothObject = garmentModel
}
else if garmentType == 1{
outClothLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
outClothObject = garmentModel
}
else if garmentType == 2{
trousersLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
trouserObject = garmentModel
}
}
func filterMatch(notifaction: NSNotification){
let garmentDataResultModel:GarmentDataResultModel = (notifaction.object as? GarmentDataResultModel)!
if garmentDataResultModel.resultCode == 1{ //内搭
self.innerClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.innerClothList.append(garmentModel)
}
self.innerClothSelect()
}
else if garmentDataResultModel.resultCode == 2{ //外套
self.outterClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.outterClothList.append(garmentModel)
}
self.outterClothSelect()
}
else if garmentDataResultModel.resultCode == 3{ //下装
self.trouserClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.trouserClothList.append(garmentModel)
}
self.bottomClothSelect()
}
self.matchCollectionView.reloadData()
}
//返回多少个组马春
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//返回多少个cell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if garmentType == 0{
return innerClothList.count
}
else if garmentType == 1{
return outterClothList.count
}
else if garmentType == 2{
return trouserClothList.count
}
return 0
}
//返回自定义的cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MatchListCell
var garmentModel:GarmentModel?
if garmentType == 0{
garmentModel = innerClothList[indexPath.row]
}
else if garmentType == 1{
garmentModel = outterClothList[indexPath.row]
}
else if garmentType == 2{
garmentModel = trouserClothList[indexPath.row]
}
cell.imgView?.af_setImage(withURL: URL.init(string: (garmentModel?.imageUrl3)!)!)
cell.layer.borderWidth = 0.3
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.titleLabel!.text = garmentModel?.hpName
cell.priceLabel!.text = garmentModel?.price
cell.garmentModel = garmentModel
cell.backgroundColor = UIColor.white
return cell
}
//返回cell 上下左右的间距
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
return UIEdgeInsetsMake(5, 5, 5, 5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: (screenWidth - 30)/2, height: screenHeight / 2 - 110)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let view:MerchandiseDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "MerchandiseDetailView") as! MerchandiseDetailViewController
var garmentModel:GarmentModel?
if garmentType == 0{
garmentModel = innerClothList[indexPath.row]
}
else if garmentType == 1{
garmentModel = outterClothList[indexPath.row]
}
else if garmentType == 2{
garmentModel = trouserClothList[indexPath.row]
}
view.hpId = (garmentModel?.id)!
self.navigationController?.pushViewController(view, animated: true)
}
@IBAction func popViewBtnClick(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func filterBtnClick(_ sender: Any) {
//self.dismiss(animated: true, completion: {() -> Void in ( print("complete"))})
//self.performSegue(withIdentifier: "filterView", sender: self)
let view = self.storyboard?.instantiateViewController(withIdentifier: "filterView")
self.navigationController?.pushViewController(view!, animated: true)
}
@IBAction func saveBtnClick(_ sender: Any) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "处理中..."
hud.hide(animated: true, afterDelay: 0.8)
if let cloth = inClothObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "内搭未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
if let cloth = outClothObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "外套未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
if let cloth = trouserObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "裤子未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "BigModelMatch"), object: selectGarmentModelList)
let time: TimeInterval = 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func innerClothBtn(_ sender: Any) {
self.innerClothSelect()
loadCostumeData(category: 0,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
@IBAction func outterClothBtn(_ sender: Any) {
self.outterClothSelect()
loadCostumeData(category: 1,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
@IBAction func bottomClothBtn(_ sender: Any) {
self.bottomClothSelect()
loadCostumeData(category: 2,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
func innerClothSelect(){
innerClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
outterClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
bottomClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 0
}
func outterClothSelect(){
outterClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
innerClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
bottomClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 1
}
func bottomClothSelect(){
bottomClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
innerClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
outterClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 2
}
func loadCostumeData(category:Int, limit:Int, offset:Int){
print("loading data.......")
let parameters:Parameters = ["categoryId":category,"limit":limit,"offset":offset]
Alamofire.request(ConstantsUtil.APP_MATCH_LIST_BY_CATEGORY,method:.get, parameters:parameters).responseObject { (response: DataResponse<GarmentDataResultModel>) in
let garmentResponse = response.result.value
if (garmentResponse?.resultCode == 200){
if (category == 0){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.innerClothList.insert(garmentModel, at: 0)
self.inClothPageNum = self.inClothPageNum + 1
}
}
}
else if (category == 1){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.outterClothList.insert(garmentModel, at: 0)
self.outClotPageNum = self.outClotPageNum + 1
}
}
}
else if (category == 2){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.trouserClothList.insert(garmentModel, at: 0)
self.trouserPageNum = self.trouserPageNum + 1
}
}
}
self.matchCollectionView.reloadData()
self.refresh.endRefreshing()
}
}
}
}
| f820ac997bd9f8c594227a169d4b3920 | 38.505587 | 173 | 0.633812 | false | false | false | false |
project-chip/connectedhomeip | refs/heads/master | examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissioningViewModel.swift | apache-2.0 | 1 | /**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import os.log
class CommissioningViewModel: ObservableObject {
let Log = Logger(subsystem: "com.matter.casting",
category: "CommissioningViewModel")
@Published var udcRequestSent: Bool?;
@Published var commisisoningWindowOpened: Bool?;
@Published var commisisoningComplete: Bool?;
@Published var connectionSuccess: Bool?;
@Published var connectionStatus: String?;
func prepareForCommissioning(selectedCommissioner: DiscoveredNodeData?) {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.openBasicCommissioningWindow(DispatchQueue.main,
commissioningWindowRequestedHandler: { (result: Bool) -> () in
DispatchQueue.main.async {
self.commisisoningWindowOpened = result
}
},
commissioningCompleteCallback: { (result: Bool) -> () in
self.Log.info("Commissioning status: \(result)")
DispatchQueue.main.async {
self.commisisoningComplete = result
}
},
onConnectionSuccessCallback: { (videoPlayer: VideoPlayer) -> () in
DispatchQueue.main.async {
self.connectionSuccess = true
self.connectionStatus = "Connected to \(String(describing: videoPlayer))"
self.Log.info("ConnectionViewModel.verifyOrEstablishConnection.onConnectionSuccessCallback called with \(videoPlayer.nodeId)")
}
},
onConnectionFailureCallback: { (error: MatterError) -> () in
DispatchQueue.main.async {
self.connectionSuccess = false
self.connectionStatus = "Failed to connect to video player!"
self.Log.info("ConnectionViewModel.verifyOrEstablishConnection.onConnectionFailureCallback called with \(error)")
}
},
onNewOrUpdatedEndpointCallback: { (contentApp: ContentApp) -> () in
DispatchQueue.main.async {
self.Log.info("CommissioningViewModel.openBasicCommissioningWindow.onNewOrUpdatedEndpointCallback called with \(contentApp.endpointId)")
}
})
}
// Send User directed commissioning request if a commissioner with a known IP addr was selected
if(selectedCommissioner != nil && selectedCommissioner!.numIPs > 0)
{
sendUserDirectedCommissioningRequest(selectedCommissioner: selectedCommissioner)
}
}
private func sendUserDirectedCommissioningRequest(selectedCommissioner: DiscoveredNodeData?) {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.sendUserDirectedCommissioningRequest(selectedCommissioner!, clientQueue: DispatchQueue.main, udcRequestSentHandler: { (result: Bool) -> () in
self.udcRequestSent = result
})
}
}
}
| ebf4dee7bd8c9641a3c16229f2c0060f | 43.655172 | 173 | 0.617761 | false | false | false | false |
eBardX/XestiMonitors | refs/heads/master | Tests/Mock/MockMotionManager.swift | mit | 1 | //
// MockMotionManager.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-31.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import CoreMotion
@testable import XestiMonitors
internal class MockMotionManager: MotionManagerProtocol {
init() {
self.accelerometerUpdateInterval = 0
self.deviceMotionUpdateInterval = 0
self.gyroUpdateInterval = 0
self.isAccelerometerAvailable = false
self.isDeviceMotionAvailable = false
self.isGyroAvailable = false
self.isMagnetometerAvailable = false
self.magnetometerUpdateInterval = 0
}
var accelerometerUpdateInterval: TimeInterval
var deviceMotionUpdateInterval: TimeInterval
var gyroUpdateInterval: TimeInterval
var magnetometerUpdateInterval: TimeInterval
private(set) var accelerometerData: CMAccelerometerData?
private(set) var deviceMotion: CMDeviceMotion?
private(set) var gyroData: CMGyroData?
private(set) var isAccelerometerAvailable: Bool
private(set) var isDeviceMotionAvailable: Bool
private(set) var isGyroAvailable: Bool
private(set) var isMagnetometerAvailable: Bool
private(set) var magnetometerData: CMMagnetometerData?
func startAccelerometerUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMAccelerometerHandler) {
accelerometerHandler = handler
}
func startDeviceMotionUpdates(using referenceFrame: CMAttitudeReferenceFrame,
to queue: OperationQueue,
withHandler handler: @escaping CMDeviceMotionHandler) {
deviceMotionHandler = handler
}
func startGyroUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMGyroHandler) {
gyroscopeHandler = handler
}
func startMagnetometerUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMMagnetometerHandler) {
magnetometerHandler = handler
}
func stopAccelerometerUpdates() {
accelerometerHandler = nil
}
func stopDeviceMotionUpdates() {
deviceMotionHandler = nil
}
func stopGyroUpdates() {
gyroscopeHandler = nil
}
func stopMagnetometerUpdates() {
magnetometerHandler = nil
}
private var accelerometerHandler: CMAccelerometerHandler?
private var deviceMotionHandler: CMDeviceMotionHandler?
private var gyroscopeHandler: CMGyroHandler?
private var magnetometerHandler: CMMagnetometerHandler?
// MARK: -
func updateAccelerometer(available: Bool) {
isAccelerometerAvailable = available
}
func updateAccelerometer(data: CMAccelerometerData?) {
accelerometerData = data
accelerometerHandler?(data, nil)
}
func updateAccelerometer(error: Error) {
accelerometerData = nil
accelerometerHandler?(nil, error)
}
func updateDeviceMotion(available: Bool) {
isDeviceMotionAvailable = available
}
func updateDeviceMotion(data: CMDeviceMotion?) {
deviceMotion = data
deviceMotionHandler?(data, nil)
}
func updateDeviceMotion(error: Error) {
deviceMotion = nil
deviceMotionHandler?(nil, error)
}
func updateGyroscope(available: Bool) {
isGyroAvailable = available
}
func updateGyroscope(data: CMGyroData?) {
gyroData = data
gyroscopeHandler?(data, nil)
}
func updateGyroscope(error: Error) {
gyroData = nil
gyroscopeHandler?(nil, error)
}
func updateMagnetometer(available: Bool) {
isMagnetometerAvailable = available
}
func updateMagnetometer(data: CMMagnetometerData?) {
magnetometerData = data
magnetometerHandler?(data, nil)
}
func updateMagnetometer(error: Error) {
magnetometerData = nil
magnetometerHandler?(nil, error)
}
}
| e9958b5083f6fdd55e89d37b2f353a67 | 26.363014 | 91 | 0.672841 | false | false | false | false |
jtsmrd/Intrview | refs/heads/master | Models/Spotlight.swift | mit | 1 | //
// Spotlight.swift
// SnapInterview
//
// Created by JT Smrdel on 1/10/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
import CloudKit
class Spotlight {
// MARK: Constants
let publicDatabase = CKContainer.default().publicCloudDatabase
let videoStore = (UIApplication.shared.delegate as! AppDelegate).videoStore
// MARK: Variables
var individualProfileCKRecordName: String?
var businessProfileCKRecordName: String?
var cKRecordName: String?
var videoCKRecordName: String?
var videoKey: String?
var jobTitle: String?
var individualName: String?
var businessName: String?
var viewCount: Int = 0
var optionalQuestions = [String]()
var businessNewFlag: Bool = false
var individualNewFlag: Bool = false
var businessDeleteFlag: Bool = false
var individualDeleteFlag: Bool = false
var createDate: Date?
var daysUntilExpired: Int {
get {
let expireDate = createDate?.addingTimeInterval((60 * 60 * 24 * 7))
return Calendar.current.dateComponents([.day], from: Date.init(), to: expireDate!).day!
}
}
var hoursUntilExpired: Int {
get {
let expireDate = createDate?.addingTimeInterval((60 * 60 * 24 * 7))
return Calendar.current.dateComponents([.hour], from: Date.init(), to: expireDate!).hour!
}
}
// MARK: Initializers
/// Default initializer
init() {
}
init(with cloudKitRecord: CKRecord) {
populate(with: cloudKitRecord)
}
init(with cKRecordName: String) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
}
else if let record = record {
self.populate(with: record)
}
}
}
private func populate(with cKRecord: CKRecord) {
self.cKRecordName = cKRecord.recordID.recordName
self.individualProfileCKRecordName = cKRecord.value(forKey: "individualProfileCKRecordName") as? String
self.businessProfileCKRecordName = cKRecord.value(forKey: "businessProfileCKRecordName") as? String
self.videoCKRecordName = cKRecord.value(forKey: "videoCKRecordName") as? String
self.jobTitle = cKRecord.value(forKey: "jobTitle") as? String
self.individualName = cKRecord.value(forKey: "individualName") as? String
self.businessName = cKRecord.value(forKey: "businessName") as? String
self.createDate = cKRecord.object(forKey: "createDate") as? Date
if let viewCount = cKRecord.value(forKey: "viewCount") as? Int {
self.viewCount = viewCount
}
if let newFlag = cKRecord.value(forKey: "businessNewFlag") as? Int {
businessNewFlag = Bool.init(NSNumber(integerLiteral: newFlag))
}
if let newFlag = cKRecord.value(forKey: "individualNewFlag") as? Int {
individualNewFlag = Bool.init(NSNumber(integerLiteral: newFlag))
}
if let deleteFlag = cKRecord.value(forKey: "businessDeleteFlag") as? Int {
businessDeleteFlag = Bool.init(NSNumber(integerLiteral: deleteFlag))
}
if let deleteFlag = cKRecord.value(forKey: "individualDeleteFlag") as? Int {
individualDeleteFlag = Bool.init(NSNumber(integerLiteral: deleteFlag))
}
}
private func fetch(with cKRecordName: String, completion: @escaping ((CKRecord?, Error?) -> Void)) {
let spotlightCKRecordID = CKRecordID(recordName: cKRecordName)
publicDatabase.fetch(withRecordID: spotlightCKRecordID) { (record, error) in
if let error = error {
completion(nil, error)
}
else if let record = record {
completion(record, nil)
}
}
}
private func create(completion: @escaping (() -> Void)) {
let newRecord = CKRecord(recordType: "Spotlight")
let populatedRecord = setCKRecordValues(for: newRecord)
publicDatabase.save(populatedRecord) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.cKRecordName = record.recordID.recordName
completion()
}
}
}
private func update(cKRecordName: String, completion: @escaping (() -> Void)) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
let updatedRecord = self.setCKRecordValues(for: record)
self.publicDatabase.save(updatedRecord, completionHandler: { (record, error) in
if let error = error {
print(error)
}
completion()
})
}
}
}
private func setCKRecordValues(for record: CKRecord) -> CKRecord {
record.setValue(self.individualProfileCKRecordName, forKey: "individualProfileCKRecordName")
record.setValue(self.businessProfileCKRecordName, forKey: "businessProfileCKRecordName")
record.setValue(self.videoCKRecordName, forKey: "videoCKRecordName")
record.setValue(self.jobTitle, forKey: "jobTitle")
record.setValue(self.individualName, forKey: "individualName")
record.setValue(self.businessName, forKey: "businessName")
record.setValue(self.viewCount, forKey: "viewCount")
record.setObject(self.createDate as CKRecordValue?, forKey: "createDate")
record.setValue(Int.init(NSNumber(booleanLiteral: businessNewFlag)), forKey: "businessNewFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: individualNewFlag)), forKey: "individualNewFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: businessDeleteFlag)), forKey: "businessDeleteFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: individualDeleteFlag)), forKey: "individualDeleteFlag")
return record
}
func fetchVideo(videoCKRecordName: String, completion: @escaping (() -> Void)) {
let videoCKRecordID = CKRecordID(recordName: videoCKRecordName)
publicDatabase.fetch(withRecordID: videoCKRecordID) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
if let videoAsset = record.object(forKey: "video") as? CKAsset {
let videoURL = videoAsset.fileURL
self.videoKey = record.recordID.recordName + ".mov"
self.videoStore.setVideo(videoURL, forKey: self.videoKey!)
completion()
}
}
}
}
func saveVideo(videoURL: URL, completion: @escaping (() -> Void)) {
let videoRecord = CKRecord(recordType: "Video")
let videoAsset = CKAsset(fileURL: videoURL)
videoRecord.setObject(videoAsset, forKey: "video")
publicDatabase.save(videoRecord) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.videoCKRecordName = record.recordID.recordName
self.videoKey = self.videoCKRecordName! + ".mov"
self.videoStore.setVideo(videoURL, forKey: self.videoKey!)
completion()
}
}
}
func forceFetch(with cKRecordName: String, completion: @escaping (() -> Void)) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.populate(with: record)
completion()
}
}
}
func delete() {
let videoRecordID = CKRecordID(recordName: self.videoCKRecordName!)
publicDatabase.delete(withRecordID: videoRecordID) { (recordID, error) in
if let error = error {
print(error)
}
else {
let spotlightRecordID = CKRecordID(recordName: self.cKRecordName!)
self.publicDatabase.delete(withRecordID: spotlightRecordID, completionHandler: { (recordID, error) in
if let error = error {
print(error)
}
})
}
}
}
func save(completion: @escaping (() -> Void)) {
if let recordName = self.cKRecordName {
update(cKRecordName: recordName, completion: {
completion()
})
}
else {
create(completion: {
completion()
})
}
}
}
| ec5bef3e6e7f052a9acffd49e302f04e | 34.860465 | 117 | 0.575443 | false | false | false | false |
XiaHaozheJose/WB | refs/heads/master | WB/WB/Classes/Main/JS_MainViewController.swift | apache-2.0 | 1 | //
// JS_MainViewController.swift
// WB
//
// Created by 浩哲 夏 on 2017/1/3.
// Copyright © 2017年 浩哲 夏. All rights reserved.
//
import UIKit
class JS_MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addchildViewController(childVC: JS_HomeViewController(), title: "首页", imageName: "tabbar_home")
addchildViewController(childVC: JS_DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
addchildViewController(childVC: JS_MessageViewController(), title: "消息", imageName: "tabbar_message_center")
addchildViewController(childVC: JS_ProfileViewController(), title: "我的", imageName: "tabbar_profile")
changeTabBar()
}
func changeTabBar(){
let tabBar = JS_tabBar()
setValue(tabBar, forKey: "tabBar")
}
private func addchildViewController(childVC : UIViewController , title : String , imageName : String){
let childNavVC = UINavigationController.init(rootViewController: childVC)
addChildViewController(childNavVC)
var imageNormal = UIImage.init(named: imageName)
imageNormal = imageNormal?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
childNavVC.tabBarItem.image = imageNormal
var imageSelected = UIImage.init(named: imageName + "_highlighted")
imageSelected = imageSelected?.withRenderingMode(.alwaysOriginal)
childNavVC.tabBarItem.selectedImage = imageSelected
childNavVC.tabBarItem.title = title
}
}
| b6a848f678a83761ba0e3f034d2e5881 | 33.75 | 116 | 0.707652 | false | false | false | false |
Mazy-ma/DemoBySwift | refs/heads/master | CollectionPopView/CollectionPopView/HomeCenterItemCell.swift | apache-2.0 | 1 | //
// HomeCenterItemCell.swift
// CollectionPopView
//
// Created by Mazy on 2017/12/15.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class HomeCenterItemCell: UICollectionViewCell {
var contentText: String? {
didSet {
contentLabel.text = contentText
}
}
private lazy var contentLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
backgroundColor = .randomColor()
layer.cornerRadius = 8
contentLabel.frame = self.bounds
contentLabel.textAlignment = .center
contentLabel.font = UIFont.boldSystemFont(ofSize: 88)
addSubview(contentLabel)
}
}
| 4e206258ef06f8bf2685797cb3ac9fa8 | 21.2 | 61 | 0.613739 | false | false | false | false |
panyam/SwiftHTTP | refs/heads/master | Sources/Handlers/Router.swift | apache-2.0 | 2 | //
// Router.swift
// SwiftHTTP
//
// Created by Sriram Panyam on 12/25/15.
// Copyright © 2015 Sriram Panyam. All rights reserved.
//
import Foundation
public typealias HeaderNameValuePair = (name: String, value: String)
//public class MatchResult
//{
// var route : Route?
// var variables : [String : AnyObject] = [String : AnyObject]()
// var handler : HttpRequestHandler?
//}
//
///**
// * Matcher objects
// */
//public protocol Matcher
//{
// func match(request: HttpRequest, _ result: MatchResult) -> Bool
//}
//
//public class HostMatcher
//{
//}
//
//public class QueryParamMatcher
//{
// /**
// * Matched based on query parameters
// */
// func match(request: HttpRequest, _ result: MatchResult) -> Bool
// {
// }
//}
//
///**
// * Returns a http handler method for a given request.
// */
//public class Router : RouteMatcher
//{
// var routes : [Route] = [Route]()
//
// public init()
// {
// }
//
// public func match(request: HttpRequest, _ result: MatchResult) -> Bool {
// for route in routes {
// if route.match(request, result) {
// return true
// }
// }
// return false
// }
//
// public func handler() -> HttpRequestHandler
// {
// return {(request, response) in
// }
// }
//}
//public class Route : RouteMatcher
//{
// /**
// * Optional name of the route
// */
// var name : String = ""
//
// /**
// */
// private (set) var parentRoute : Route?
// var matchers : [RouteMatcher] = [RouteMatcher]()
//
// public convenience init()
// {
// self.init("", nil)
// }
//
// public init(_ name: String, _ parent : Route?)
// {
// name = n
// parentRoute = parent
// }
//
// func match(request: HttpRequest, result: MatchResult) -> Bool
// {
// for matcher in matchers {
// if matcher.match(reqeust, result: result)
// }
// }
//
// public func Methods(methods: String...) -> Route {
// matchers.append {(request: HttpRequest) -> Bool in
// for method in methods {
// if methods.contains(method) {
// return true
// }
// }
// return false
// }
// return Route(self)
// }
//
// public func Header(values: HeaderNameValuePair...) -> Route {
// matchers.append {(request: HttpRequest) -> Bool in
// for (name, value) in values {
// if let headerValue = request.headers.forKey(name)?.values.first
// {
// if headerValue != value
// {
// return false
// }
// } else {
// return false
// }
// }
// return true
// }
// return Route(self)
// }
//}
| 1db160d4c7ca79423318f6858f3672a3 | 22.102362 | 81 | 0.489775 | false | false | false | false |
coolshubh4/iOS-Demos | refs/heads/master | Click Counter/Click Counter/ViewController.swift | mit | 1 | //
// ViewController.swift
// Click Counter
//
// Created by Shubham Tripathi on 12/07/15.
// Copyright (c) 2015 Shubham Tripathi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var count = 0
var label:UILabel!
var toggle = true
var colorOne = UIColor.yellowColor()
var colorTwo = UIColor.redColor()
var colorArray = [UIColor.yellowColor(), UIColor.redColor(), UIColor.purpleColor(), UIColor.orangeColor()]
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.cyanColor()
//Label
var label = UILabel()
label.frame = CGRectMake(100, 150, 60, 60)
label.text = "0"
self.view.addSubview(label)
self.label = label
//Increment Button
var incrementButton = UIButton()
incrementButton.frame = CGRectMake(100, 250, 60, 60)
incrementButton.setTitle("Inc +", forState: .Normal)
incrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(incrementButton)
incrementButton.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//Decrement Button
var decrementButton = UIButton()
decrementButton.frame = CGRectMake(100, 350, 60, 60)
decrementButton.setTitle("Dec -", forState: .Normal)
decrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(decrementButton)
decrementButton.addTarget(self, action: "decrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//BackgroungColorToggle Button
var toggleColorButton = UIButton()
toggleColorButton.frame = CGRectMake(100, 450, 150, 100)
toggleColorButton.setTitle("ToggleBGColor", forState: .Normal)
toggleColorButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(toggleColorButton)
toggleColorButton.addTarget(self, action: "toggleBGColor", forControlEvents: UIControlEvents.TouchUpInside)
}
func incrementCount() {
self.count++
self.label.text = "\(self.count)"
}
func decrementCount() {
self.count--
self.label.text = "\(self.count)"
}
func toggleBGColor () {
// if toggle {
// self.view.backgroundColor = colorOne
// toggle = false
// } else {
// self.view.backgroundColor = colorTwo
// toggle = true
// }
let randomColor = Int(arc4random_uniform(UInt32(colorArray.count)))
print(randomColor)
self.view.backgroundColor = colorArray[randomColor]
}
}
| a3ce58eae88569fdba6db2bc32c25a64 | 31.482759 | 115 | 0.62845 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | Sources/Modules/AuthModuleDispatcher.swift | apache-2.0 | 1 | //
// AuthModuleDispatcher.swift
// BoxSDK
//
// Created by Daniel Cech on 13/06/2019.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
class AuthModuleDispatcher {
let authQueue = ThreadSafeQueue<AuthActionTuple>(completionQueue: DispatchQueue.main)
var active = false
static var current = 1
func start(action: @escaping AuthActionClosure) {
let currentId = AuthModuleDispatcher.current
AuthModuleDispatcher.current += 1
authQueue.enqueue((id: currentId, action: action)) {
if !self.active {
self.active = true
self.processAction()
}
}
}
func processAction() {
authQueue.dequeue { [weak self] action in
if let unwrappedAction = action {
unwrappedAction.action {
self?.processAction()
}
}
else {
self?.active = false
}
}
}
}
| 4094c9f5eb171f0059ed507859c13537 | 22.857143 | 89 | 0.558882 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Migrator/post_fixit_pass.swift | apache-2.0 | 11 | // RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/post_fixit_pass.swift.result -o /dev/null -F %S/mock-sdk -swift-version 4 %api_diff_data_dir
// RUN: %diff -u %S/post_fixit_pass.swift.expected %t/post_fixit_pass.swift.result
#if swift(>=4.2)
public struct SomeAttribute: RawRepresentable {
public init(rawValue: Int) { self.rawValue = rawValue }
public init(_ rawValue: Int) { self.rawValue = rawValue }
public var rawValue: Int
public typealias RawValue = Int
}
#else
public typealias SomeAttribute = Int
#endif
func foo(_ d: SomeAttribute) {
let i: Int = d
}
| 7ffb10c1328a11611ae0abb3de27b7df | 35.388889 | 208 | 0.696183 | false | false | false | false |
AndreyBaranchikov/Keinex-iOS | refs/heads/master | Keinex/Defaults.swift | mit | 1 | //
// Defaults.swift
// Keinex
//
// Created by Андрей on 07.08.16.
// Copyright © 2016 Keinex. All rights reserved.
//
import Foundation
import UIKit
let userDefaults = UserDefaults.standard
let isiPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
let latestPostValue = "postValue"
//Sources
let sourceUrl:NSString = "SourceUrlDefault"
let sourceUrlKeinexRu:NSString = "https://keinex.ru/wp-json/wp/v2/posts/"
let sourceUrlKeinexCom:NSString = "http://keinex.com/wp-json/wp/v2/posts/"
let autoDelCache:NSString = "none"
| 3b599d5866541f4326ab1ce3863bf6db | 26.4 | 76 | 0.757299 | false | false | false | false |
CoderXiaoming/Ronaldo | refs/heads/master | SaleManager/SaleManager/ComOperation/Model/SAMSaleOrderInfoModel.swift | apache-2.0 | 1 | //
// SAMSaleOrderInfoModel.swift
// SaleManager
//
// Created by apple on 16/12/7.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
class SAMSaleOrderInfoModel: NSObject {
///销售日期
var startDate = "" {
didSet{
startDate = ((startDate == "") ? "---" : startDate)
}
}
///销售金额
var actualMoney = 0.0
///客户名称
var CGUnitName = "" {
didSet{
CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName)
}
}
///销售单号
var billNumber = "" {
didSet{
billNumber = ((billNumber == "") ? "---" : billNumber)
}
}
//MARK: - 辅助属性
let orderStateImageName = "indicater_saleHistory_selected"
}
| d00d9a3aeee3579217ba91b7dc888cbd | 19.222222 | 66 | 0.508242 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/data types/enumerable/CMGiftPokemon.swift | gpl-2.0 | 1 | //
// CMGiftPokemon.swift
// Colosseum Tool
//
// Created by The Steez on 16/08/2018.
//
import Foundation
var kPlusleOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F514
case .JP: return 0x14A83C
case .EU: return 0x150DD8
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D9C8
case .JP: return 0x12B098
case .EU: return 0x131BF4
case .OtherGame: return 0
}
}
}
var kHoohOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F430
case .JP: return 0x14A758
case .EU: return 0x150CF4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D8E4
case .JP: return 0x12AFB8
case .EU: return 0x131B10
case .OtherGame: return 0
}
}
}
var kCelebiOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F200
case .JP: return 0x14A528
case .EU: return 0x150AC4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D6B4
case .JP: return 0x12ADD0
case .EU: return 0x1318E0
case .OtherGame: return 0
}
}
}
var kPikachuOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F310
case .JP: return 0x14A638
case .EU: return 0x150BD4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D7C4
case .JP: return 0x12AEBC
case .EU: return 0x1319F0
case .OtherGame: return 0
}
}
}
let kDistroPokemonSpeciesOffset = 0x02
let kDistroPokemonLevelOffset = 0x07
let kDistroPokemonShininessOffset = 0x5A
let kDukingsPlusleshininessOffset = 0x66
let kNumberOfDistroPokemon = 4
final class CMGiftPokemon: NSObject, XGGiftPokemon, GoDCodable {
var index = 0
var level = 0x0
var species = XGPokemon.index(0)
var move1 = XGMoves.index(0)
var move2 = XGMoves.index(0)
var move3 = XGMoves.index(0)
var move4 = XGMoves.index(0)
var giftType = ""
// unused
var exp = -1
var shinyValue = XGShinyValues.random
private(set) var gender = XGGenders.random
private(set) var nature = XGNatures.random
var usesLevelUpMoves = true
var startOffset : Int {
get {
switch index {
case 0 : return kPlusleOffset
case 1 : return kHoohOffset
case 2 : return kCelebiOffset
default: return kPikachuOffset
}
}
}
init(index: Int) {
super.init()
let dol = XGFiles.dol.data!
self.index = index
let start = startOffset
let species = dol.get2BytesAtOffset(start + kDistroPokemonSpeciesOffset)
self.species = .index(species)
level = dol.getByteAtOffset(start + kDistroPokemonLevelOffset)
let shiny = dol.get2BytesAtOffset(start + (index == 0 ? kDukingsPlusleshininessOffset : kDistroPokemonShininessOffset))
self.shinyValue = XGShinyValues(rawValue: shiny) ?? .random
let moves = self.species.movesForLevel(level)
self.move1 = moves[0]
self.move2 = moves[1]
self.move3 = moves[2]
self.move4 = moves[3]
switch index {
case 0 : self.giftType = "Duking's Plusle"
case 1 : self.giftType = "Mt.Battle Ho-oh"
case 2 : self.giftType = "Agate Celebi"
default : self.giftType = "Agate Pikachu"
}
}
func save() {
let dol = XGFiles.dol.data!
let start = startOffset
dol.replaceByteAtOffset(start + kDistroPokemonLevelOffset, withByte: level)
dol.replace2BytesAtOffset(start + kDistroPokemonSpeciesOffset, withBytes: species.index)
dol.replace2BytesAtOffset(start + (index == 0 ? kDukingsPlusleshininessOffset : kDistroPokemonShininessOffset), withBytes: shinyValue.rawValue)
dol.save()
}
}
extension CMGiftPokemon: XGEnumerable {
var enumerableName: String {
return species.name.string
}
var enumerableValue: String? {
return index.string
}
static var className: String {
return game == .XD ? "Colosseum Gift Pokemon" : "Gift Pokemon"
}
static var allValues: [CMGiftPokemon] {
var values = [CMGiftPokemon]()
for i in 0 ... 3 {
values.append(CMGiftPokemon(index: i))
}
return values
}
}
extension CMGiftPokemon: XGDocumentable {
var documentableName: String {
return (enumerableValue ?? "") + " - " + enumerableName
}
static var DocumentableKeys: [String] {
return ["index", "name", "level", "gender", "nature", "shininess", "moves"]
}
func documentableValue(for key: String) -> String {
switch key {
case "index":
return index.string
case "name":
return species.name.string
case "level":
return level.string
case "gender":
return gender.string
case "nature":
return nature.string
case "shininess":
return shinyValue.string
case "moves":
var text = ""
text += "\n" + move1.name.string
text += "\n" + move2.name.string
text += "\n" + move3.name.string
text += "\n" + move4.name.string
return text
default:
return ""
}
}
}
| 32a61995830c90469f6e64c83afcf809 | 20.858447 | 145 | 0.680593 | false | false | false | false |
aitorbf/Curso-Swift | refs/heads/master | Is It Prime/Is It Prime/ViewController.swift | mit | 1 | //
// ViewController.swift
// Is It Prime
//
// Created by Aitor Baragaño Fernández on 22/9/15.
// Copyright © 2015 Aitor Baragaño Fernández. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var number: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
let numberInt = Int(number.text!)
if numberInt != nil {
let unwrappedNumber = numberInt!
resultLabel.textColor = UIColor.blackColor()
var isPrime = true;
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false;
}
}
}
if isPrime == true {
resultLabel.text = "\(unwrappedNumber) is prime!"
} else {
resultLabel.text = "\(unwrappedNumber) is not prime!"
}
} else {
resultLabel.textColor = UIColor.redColor()
resultLabel.text = "Please enter a number in the box"
}
number.resignFirstResponder()
}
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.
}
}
| e3a97e2c232b99c81502288680290bc0 | 24.0625 | 80 | 0.450374 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Classes/Server Loading/Loaders/CreatePlaylistLoader.swift | gpl-3.0 | 1 | //
// CreatePlaylistLoader.swift
// iSub Beta
//
// Created by Felipe Rolvar on 26/11/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
class CreatePlaylistLoader: ApiLoader, ItemLoader {
private var songs = [Song]()
var playlistName: String
var items: [Item] {
return songs
}
var associatedItem: Item? {
return PlaylistRepository.si.playlist(name: playlistName, serverId: serverId)
}
init(with name: String, and serverId: Int64) {
self.playlistName = name
super.init(serverId: serverId)
}
override func createRequest() -> URLRequest? {
return URLRequest(subsonicAction: .createPlaylist,
serverId: serverId,
parameters: ["name": playlistName,
"songId" : items.map { $0.itemId }])
}
override func processResponse(root: RXMLElement) -> Bool {
songs.removeAll()
root.iterate("playlist.entry") { [weak self] in
guard let serverId = self?.serverId,
let song = Song(rxmlElement: $0, serverId: serverId) else {
return
}
self?.songs.append(song)
}
return true
}
@discardableResult func loadModelsFromDatabase() -> Bool {
guard let playlist = associatedItem as? Playlist else { return false }
playlist.loadSubItems()
songs = playlist.songs
return songs.count > 0
}
// MARK: - Nothing to implement
func persistModels() { }
}
| 60c61bcb856e10a3f52f8f37ec60676f | 27.333333 | 85 | 0.573994 | false | false | false | false |
brokenseal/iOS-exercises | refs/heads/master | FaceSnap/FaceSnap/FilteredImageBuilder.swift | mit | 1 | //
// FilteredImageBuilder.swift
// FaceSnap
//
// Created by Davide Callegari on 28/06/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import Foundation
import CoreImage
import UIKit
private struct PhotoFilter {
static let ColorClamp = "CIColorClamp"
static let ColorControls = "CIColorControls"
static let PhotoEffectIstant = "CIPhotoEffectInstant"
static let PhotoEffectProcess = "CIPhotoEffectProcess"
static let PhotoEffectNoir = "CIPhotoEffectNoir"
static let Sepia = "CISepiaTone"
static func defaultFilters() -> [CIFilter] {
let colorClamp = CIFilter(name: self.ColorClamp)!
colorClamp.setValue(CIVector(x: 0.2, y: 0.2, z: 0.2, w: 0.2), forKey: "inputMinComponents")
colorClamp.setValue(CIVector(x: 0.9, y: 0.9, z: 0.9, w: 0.9), forKey: "inputMaxComponents")
let colorControls = CIFilter(name: self.ColorControls)!
colorControls.setValue(0.1, forKey: kCIInputSaturationKey)
let sepia = CIFilter(name: self.Sepia)!
sepia.setValue(0.7, forKey: kCIInputIntensityKey)
return [
colorClamp,
colorControls,
CIFilter(name: self.PhotoEffectIstant)!,
CIFilter(name: self.PhotoEffectProcess)!,
CIFilter(name: self.PhotoEffectNoir)!,
sepia,
]
}
}
final class FilteredImageBuilder {
private let inputImage: UIImage
init(image: UIImage){
self.inputImage = image
}
func imageWithDefaultFilters() -> [UIImage]{
return image(withFilters: PhotoFilter.defaultFilters())
}
func image(withFilters filters: [CIFilter]) -> [UIImage]{
return filters.map { image(self.inputImage, withFilter: $0) }
}
func image(_ image: UIImage, withFilter filter: CIFilter) -> UIImage {
let inputImage = image.ciImage ?? CIImage(image: image)!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = filter.outputImage!
return UIImage(ciImage: outputImage)
}
}
| 43de28b0c856cf875c7452e6251d2ebf | 31.153846 | 99 | 0.649761 | false | false | false | false |
lionchina/RxSwiftBook | refs/heads/master | RxTableViewWithSection/RxTableViewWithSection/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// RxTableViewWithSection
//
// Created by MaxChen on 04/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import Foundation
import UIKit
import RxCocoa
import RxSwift
import RxDataSources
class ViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var tableviewData: UITableView!
let disposeBag = DisposeBag()
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
override func viewDidLoad() {
super.viewDidLoad()
let dataSource = self.dataSource
let items = Observable.just([
SectionModel(model: "First section", items: [1.0, 2.0, 3.0]),
SectionModel(model: "Second section", items: [2.0, 3.0, 4.0]),
SectionModel(model: "Third section", items: [3.0, 4.0, 5.0])])
dataSource.configureCell = { (_, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
items.bind(to: tableviewData.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableviewData.rx.itemSelected
.map { indexPath in
return (indexPath, dataSource[indexPath])
}
.subscribe(onNext: { indexPath, model in
print("Tapped \(model) @ row \(indexPath)")
})
.disposed(by: disposeBag)
tableviewData.rx.setDelegate(self).disposed(by: disposeBag)
}
}
| c0819d1399d90c1d32e095eae505e456 | 33.74 | 89 | 0.62464 | false | false | false | false |
piwik/piwik-sdk-ios | refs/heads/develop | MatomoTracker/MatomoUserDefaults.swift | mit | 1 | import Foundation
/// MatomoUserDefaults is a wrapper for the UserDefaults with properties
/// mapping onto values stored in the UserDefaults.
/// All getter and setter are sideeffect free and automatically syncronize
/// after writing.
internal struct MatomoUserDefaults {
let userDefaults: UserDefaults
init(suiteName: String?) {
userDefaults = UserDefaults(suiteName: suiteName)!
}
var totalNumberOfVisits: Int {
get {
return userDefaults.integer(forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
userDefaults.synchronize()
}
}
var firstVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.firstVistsTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.firstVistsTimestamp)
userDefaults.synchronize()
}
}
var previousVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.previousVistsTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.previousVistsTimestamp)
userDefaults.synchronize()
}
}
var currentVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.currentVisitTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.currentVisitTimestamp)
userDefaults.synchronize()
}
}
var optOut: Bool {
get {
return userDefaults.bool(forKey: MatomoUserDefaults.Key.optOut)
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.optOut)
userDefaults.synchronize()
}
}
var clientId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.clientID)
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.clientID)
userDefaults.synchronize()
}
}
var forcedVisitorId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.forcedVisitorID)
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.forcedVisitorID)
userDefaults.synchronize()
}
}
var visitorUserId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.visitorUserID);
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.visitorUserID);
userDefaults.synchronize()
}
}
var lastOrder: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.lastOrder) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.lastOrder)
}
}
}
extension MatomoUserDefaults {
public mutating func copy(from userDefaults: UserDefaults) {
totalNumberOfVisits = userDefaults.integer(forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
firstVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.firstVistsTimestamp) as? Date
previousVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.previousVistsTimestamp) as? Date
currentVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.currentVisitTimestamp) as? Date
optOut = userDefaults.bool(forKey: MatomoUserDefaults.Key.optOut)
clientId = userDefaults.string(forKey: MatomoUserDefaults.Key.clientID)
forcedVisitorId = userDefaults.string(forKey: MatomoUserDefaults.Key.forcedVisitorID)
visitorUserId = userDefaults.string(forKey: MatomoUserDefaults.Key.visitorUserID)
lastOrder = userDefaults.object(forKey: MatomoUserDefaults.Key.lastOrder) as? Date
}
}
extension MatomoUserDefaults {
internal struct Key {
static let totalNumberOfVisits = "PiwikTotalNumberOfVistsKey"
static let currentVisitTimestamp = "PiwikCurrentVisitTimestampKey"
static let previousVistsTimestamp = "PiwikPreviousVistsTimestampKey"
static let firstVistsTimestamp = "PiwikFirstVistsTimestampKey"
// Note: To be compatible with previous versions, the clientID key retains its old value,
// even though it is now a misnomer since adding visitorUserID makes it a bit confusing.
static let clientID = "PiwikVisitorIDKey"
static let forcedVisitorID = "PiwikForcedVisitorIDKey"
static let visitorUserID = "PiwikVisitorUserIDKey"
static let optOut = "PiwikOptOutKey"
static let lastOrder = "PiwikLastOrderDateKey"
}
}
| 394829387a5ff5917dd52df7a3b49688 | 36.097744 | 107 | 0.66437 | false | false | false | false |
GTMYang/GTMRefresh | refs/heads/master | GTMRefreshExample/Default/DefaultCollectionViewController.swift | mit | 1 | //
// DefaultCollectionViewController.swift
// PullToRefreshKit
//
// Created by luoyang on 2016/12/8.
// Copyright © 2016年 luoyang. All rights reserved.
//
import Foundation
import UIKit
class DefaultCollectionViewController:UIViewController,UICollectionViewDataSource{
var collectionView:UICollectionView?
override func viewDidLoad() {
self.view.backgroundColor = UIColor.white
self.setUpCollectionView()
self.collectionView?.gtm_addRefreshHeaderView {
[weak self] in
print("excute refreshBlock")
self?.refresh()
}
self.collectionView?.gtm_addLoadMoreFooterView {
[weak self] in
print("excute loadMoreBlock")
self?.loadMore()
}
}
// MARK: Test
func refresh() {
perform(#selector(endRefresing), with: nil, afterDelay: 3)
}
@objc func endRefresing() {
self.collectionView?.endRefreshing(isSuccess: true)
}
func loadMore() {
perform(#selector(endLoadMore), with: nil, afterDelay: 3)
}
@objc func endLoadMore() {
self.collectionView?.endLoadMore(isNoMoreData: true)
}
func setUpCollectionView(){
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = UICollectionView.ScrollDirection.vertical
flowLayout.itemSize = CGSize(width: 100, height: 100)
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
self.collectionView?.backgroundColor = UIColor.white
self.collectionView?.dataSource = self
self.view.addSubview(self.collectionView!)
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 21
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.lightGray
return cell
}
deinit{
print("Deinit of DefaultCollectionViewController")
}
}
| 99f32624adaf92342c0e923d0b720bcd | 31.5 | 121 | 0.665812 | false | false | false | false |
igerry/ProjectEulerInSwift | refs/heads/master | ProjectEulerInSwift/Euler/Problem6.swift | apache-2.0 | 1 | import Foundation
/*
Sum square difference
Problem 6
25164150
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
class Problem6 {
func solution() -> Int {
var sum = 0
var sumSquare = 0
for i in 1...100 {
sum += i
sumSquare += i * i
}
let diff = sum * sum - sumSquare
return diff
}
}
| 5829cd1abb884a0cc4a3208276c5b2c6 | 22.818182 | 133 | 0.597964 | false | false | false | false |
abreis/swift-gissumo | refs/heads/master | scripts/parsers/singles/averageColumn.swift | mit | 1 | /* This script takes a list of statistical data files containing tab-separated values,
* where the first column is a time entry. It then gathers the data in the column
* specified in the second argument and returns an average value.
*
* If a time value is provided as the second argument, only samples that
* occur after that time are recorded.
*/
import Foundation
/*** MEASUREMENT SWIFT3 ***/
// A measurement object: load data into 'samples' and all metrics are obtained as computed properties
struct Measurement {
var samples = [Double]()
mutating func add(point: Double) { samples.append(point) }
var count: Double { return Double(samples.count) }
var sum: Double { return samples.reduce(0,+) }
var mean: Double { return sum/count }
var min: Double { return samples.min()! }
var max: Double { return samples.max()! }
// This returns the maximum likelihood estimator(over N), not the minimum variance unbiased estimator (over N-1)
var variance: Double { return samples.reduce(0,{$0 + pow($1-mean,2)} )/count }
var stdev: Double { return sqrt(variance) }
// Specify the desired confidence level (1-significance) before requesting the intervals
// func confidenceIntervals(confidence: Double) -> Double {}
//var confidence: Double = 0.90
//var confidenceInterval: Double { return 0.0 }
}
/*** ***/
guard 3...4 ~= CommandLine.arguments.count else {
print("usage: \(CommandLine.arguments[0]) [list of data files] [column name or number] [minimum time]")
exit(EXIT_FAILURE)
}
var columnNumber: Int? = nil
var cliColName: String? = nil
if let cliColNum = UInt(CommandLine.arguments[2]) {
columnNumber = Int(cliColNum)-1
} else {
cliColName = CommandLine.arguments[2]
}
// Load minimum sample time
var minTime: Double = 0.0
if CommandLine.arguments.count == 4 {
guard let inMinTime = Double(CommandLine.arguments[3]) else {
print("Error: Invalid minimum time specified.")
exit(EXIT_FAILURE)
}
minTime = inMinTime
}
var statFiles: String
do {
let statFilesURL = NSURL.fileURL(withPath: CommandLine.arguments[1])
_ = try statFilesURL.checkResourceIsReachable()
statFiles = try String(contentsOf: statFilesURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// Process statistics files
var dataMeasurement = Measurement()
for statFile in statFiles.components(separatedBy: .newlines).filter({!$0.isEmpty}) {
// 1. Open and read the statFile into a string
var statFileData: String
do {
let statFileURL = NSURL.fileURL(withPath: statFile)
_ = try statFileURL.checkResourceIsReachable()
statFileData = try String(contentsOf: statFileURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// 2. Break the stat file into lines
var statFileLines: [String] = statFileData.components(separatedBy: .newlines).filter({!$0.isEmpty})
// [AUX] For the very first file, if a column name was specified instead of a column number, find the column number by name.
if columnNumber == nil {
let header = statFileLines.first!
let colNames = header.components(separatedBy: "\t").filter({!$0.isEmpty})
guard let colIndex = colNames.index(where: {$0 == cliColName})
else {
print("ERROR: Can't match column name to a column number.")
exit(EXIT_FAILURE)
}
columnNumber = colIndex
}
// 3. Drop the first line (header)
statFileLines.removeFirst()
// 4. Run through the statFile lines
for statFileLine in statFileLines {
// Split each line by tabs
let statFileLineColumns = statFileLine.components(separatedBy: "\t").filter({!$0.isEmpty})
// First column is time index for the dictionary
// 'columnNumber' column is the data we want
guard let timeEntry = Double(statFileLineColumns[0]),
let dataEntry = Double(statFileLineColumns[columnNumber!]) else {
print("ERROR: Can't interpret time and/or data.")
exit(EXIT_FAILURE)
}
// Push the data into the measurement's samples
if(timeEntry>minTime) {
dataMeasurement.add(point: dataEntry)
}
}
}
// For each sorted entry in the dictionary, print out the mean, median, min, max, std, var, etcetera
print("mean", "count", separator: "\t")
print(dataMeasurement.mean, dataMeasurement.count, separator: "\t")
| 9fd004d783475c2f3cde51b67c8fb720 | 32.173228 | 125 | 0.723 | false | false | false | false |
Ryukie/Ryubo | refs/heads/master | Ryubo/Ryubo/Classes/Model/RYUser.swift | mit | 1 | //
// RYUser.swift
// Ryubo
//
// Created by 王荣庆 on 16/2/16.
// Copyright © 2016年 Ryukie. All rights reserved.
//
import UIKit
class RYUser: NSObject {
///用户id
var id: Int64 = 0
///用户名称
var name: String?
///用户头像地址(中图),50×50像素
var profile_image_url: String?
//计算用户头像的url地址
var headImageURL: NSURL? {
return NSURL(string: profile_image_url ?? "")
}
/// 认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 草根
var verified_type: Int = -1
var verified_type_image: UIImage? {
switch verified_type {
case -1: return nil
case 0: return UIImage(named: "avatar_vip")
case 2,3,5: return UIImage(named: "avatar_enterprise_vip")
case 220: return UIImage(named: "avatar_grassroot")
default : return nil
}
}
/// 会员等级 0-6
var mbrank: Int = 0
var mbrank_image: UIImage? {
if mbrank > 0 && mbrank < 7 {
return UIImage(named: "common_icon_membership_level\(mbrank)")
}
return nil
}
init(dict:[String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
//重写对象的描述信息
override var description: String {
//使用kvc方式 获取对象 的字典信息
let keys = ["name","id","profile_image_url","mbrank","verified_type"]
let dict = self.dictionaryWithValuesForKeys(keys)
return dict.description
}
}
| 6e774d9b7977a99b52de7e7645c1a54c | 24.913793 | 77 | 0.581504 | false | false | false | false |
buscarini/JMSSwiftParse | refs/heads/master | Tests/helpers.swift | mit | 1 | //
// helpers.swift
// JMSSwiftParse
//
// Created by Jose Manuel Sánchez Peñarroja on 19/11/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
public class TestClass {
var requiredString = ""
var optionalString : String?
var email = ""
var requiredUrl : NSURL = NSURL(string : "blah")!
var optionalUrl : NSURL? = NSURL()
var requiredBool = false
var optionalBool : Bool?
var availableString = ""
var requiredInt = 0
var optionalInt : Int? = 0
var requiredDouble = 0.0
var optionalDouble : Double? = 0.0
var date = NSDate()
public init() {
}
}
| e484fa56571e472f9e3777386ab94e61 | 18.709677 | 64 | 0.679214 | false | false | false | false |
Tarovk/Mundus_Client | refs/heads/master | Aldo/Aldo.swift | mit | 2 | //
// Aldo.swift
// Pods
//
// Created by Team Aldo on 29/12/2016.
//
//
import Foundation
import Alamofire
/**
All core URI requests that are being processed by the Aldo Framework.
*/
public enum RequestURI: String {
/// Dummy URI.
case REQUEST_EMPTY = "/"
/// URI to request and authorization token.
case REQUEST_AUTH_TOKEN = "/token"
/// URI template to create a session.
case SESSION_CREATE = "/session/username/%@"
/// URI template to join a session.
case SESSION_JOIN = "/session/join/%@/username/%@"
/// URI to get the information about the session.
case SESSION_INFO = "/session"
/// URI to get the players that have joined the session.
case SESSION_PLAYERS = "/session/players"
/// URI to resume the session.
case SESSION_STATE_PLAY = "/session/play"
/// URI to pause the session.
case SESSION_STATE_PAUSE = "/session/pause"
/// URI to stop and delete the session.
case SESSION_DELETE = "/session/delete"
/// URI to get all players linked to the device.
case PLAYER_ALL = "/player/all"
/// URI to get information of the active player.
case PLAYER_INFO = "/player"
/// URI template to update the username of the active player.
case PLAYER_USERNAME_UPDATE = "/player/username/%@"
/**
Converts the rawValue to one containing regular expression for comparison.
- Returns: A *String* representation as regular expression.
*/
public func regex() -> String {
var regex: String = "(.)+?"
if self == .PLAYER_USERNAME_UPDATE {
regex = "(.)+?$"
}
return "\(self.rawValue.replacingOccurrences(of: "%@", with: regex))$"
}
}
/**
Protocol for sending a request to the Aldo Framework.
*/
public protocol AldoRequester {
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
static func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback?)
}
/**
Class containing static methods to communicate with the Aldo Framework.
*/
public class Aldo: AldoRequester {
/// Keys for data storage
public enum Keys: String {
case AUTH_TOKEN
case SESSION
}
static let storage = UserDefaults.standard
static var hostAddress: String = "127.0.0.1"
static var baseAddress: String = "127.0.0.1"
static let id: String = UIDevice.current.identifierForVendor!.uuidString
/**
Define the address of the server running the Aldo Framework.
- Parameters:
- address: the address of the server running the Aldo Framework
including port and **without** a / at the end.
*/
public class func setHostAddress(address: String) {
if let url = URL(string: address) {
let host = url.host != nil ? url.host! : address
let port = url.port != nil ? ":\(url.port!)" : ""
hostAddress = address
baseAddress = "\(host)\(port)"
}
//hostAddress.asURL().s
//baseAddress =
}
/**
Checks whether the device already has an authorization token or not.
- Returns: *true* if having a token, otherwise *false*.
*/
public class func hasAuthToken() -> Bool {
return storage.object(forKey: Keys.AUTH_TOKEN.rawValue) != nil
}
/**
Checks wether the device has a information about a player in a session.
- Returns: *true* if having information about a player, otherwise *false*.
*/
public class func hasActivePlayer() -> Bool {
return storage.object(forKey: Keys.SESSION.rawValue) != nil
}
/**
Retrieves the storage where the information retrieved from the Aldo Framework is stored.
- Returns: an instance of *UserDefaults*
*/
public class func getStorage() -> UserDefaults {
return storage
}
/**
Retrieves the stored information about an active player.
- Returns: an instance of *Player* if available, otherwise *nil*
*/
public class func getPlayer() -> Player? {
if let objSession = storage.object(forKey: Keys.SESSION.rawValue) {
let sessionData = objSession as! Data
let session: Player = NSKeyedUnarchiver.unarchiveObject(with: sessionData) as! Player
return session
}
return nil
}
/// Stores information about an active player.
public class func setPlayer(player: Player) {
let playerData: Data = NSKeyedArchiver.archivedData(withRootObject: player)
Aldo.getStorage().set(playerData, forKey: Aldo.Keys.SESSION.rawValue)
}
/// Helper method creating the value of the Authorization header used for a request.
class func getAuthorizationHeaderValue() -> String {
let objToken = storage.object(forKey: Keys.AUTH_TOKEN.rawValue)
let token: String = (objToken != nil) ? ":\(objToken as! String)" : ""
var playerId: String = ""
if let player = Aldo.getPlayer() {
playerId = ":\(player.getId())"
}
return "\(id)\(token)\(playerId)"
}
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
open class func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback? = nil) {
let headers = [
"Authorization": getAuthorizationHeaderValue()
]
Alamofire.request("\(hostAddress)\(uri)", method: method,
parameters: parameters, encoding: AldoEncoding(),
headers: headers).responseJSON { response in
var result: NSDictionary = [:]
if let JSON = response.result.value {
result = JSON as! NSDictionary
}
var responseCode: Int = 499
if let httpResponse = response.response {
responseCode = httpResponse.statusCode
}
AldoMainCallback(callback: callback).onResponse(request: uri,
responseCode: responseCode, response: result)
}
}
/**
Opens a websocket connection with the Aldo Framework.
- Parameters:
- path: The path to subscribe to
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
- Returns: An instance of *AldoWebSocket* representing the connection or
*nil* if the connection could not be made.
*/
public class func subscribe(path: String, callback: Callback) -> AldoWebSocket? {
if let url = URL(string: "ws://\(baseAddress)\(path)") {
let socket = AldoWebSocket(path: path, url: url, callback: callback)
socket.connect()
return socket
}
return nil
}
/**
Sends a request to obtain an authorization token.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestAuthToken(callback: Callback? = nil) {
let command: String = RequestURI.REQUEST_AUTH_TOKEN.rawValue
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to create a session.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func createSession(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_CREATE.rawValue, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to join a session.
- Parameters:
- username: The username to be used.
- token: The token to join a session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func joinSession(username: String, token: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_JOIN.rawValue, token, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionInfo(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players in the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionPlayers(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_PLAYERS.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the status of the session.
- Parameters:
- newStatus: The new status of the session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func changeSessionStatus(newStatus: Session.Status, callback: Callback? = nil) {
var command: String = RequestURI.SESSION_STATE_PLAY.rawValue
if newStatus == Session.Status.PAUSED {
command = RequestURI.SESSION_STATE_PAUSE.rawValue
}
request(uri: command, method: .put, parameters: [:], callback: callback)
}
/**
Sends a request to delete the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func deleteSession(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_DELETE.rawValue
request(uri: command, method: .delete, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players linked to the device.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestDevicePlayers(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_ALL.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the player.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestPlayerInfo(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the username of the player.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func updateUsername(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.PLAYER_USERNAME_UPDATE.rawValue, username)
request(uri: command, method: .put, parameters: [:], callback: callback)
}
}
| 5d6f2b2f8a11e079bded308d4f9d2aa3 | 35.206704 | 113 | 0.612251 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01507-swift-constraints-matchcallarguments.swift | apache-2.0 | 12 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension NSSet {
enum b {
struct S : NSManagedObject {
var b : b(T> {
}
struct D : S<T)
}
struct Q<T.e {
}
let h, Any, a<I : T>) {
typealias B {
protocol B {
}
convenience init(Any) -> {
protocol b {
class a: P> Any, x }
}
}
}
}
}
import CoreData
protocol b = e: d where Optional<T> == a(c(2, Any)
var e> Any) -> [Byte]()
let foo as [c] = i((self.<h : d = b() -> ("[1, object2)(c<T>>(m: 1, U.Generator.A: T>, a() -> U) -> {
enum A {
class a<T {
protocol a : a {
extension NSSet {
protocol b {
}
}
func a
| 4bb06c74a3baacc76301b4931f6dbef2 | 17.025 | 101 | 0.614424 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/WebProgressView.swift | gpl-2.0 | 2 | import UIKit
import WebKit
import WordPressShared
/// A view to show progress when loading web pages.
///
/// Since UIWebView doesn't offer any real or estimate loading progress, this
/// shows an initial indication of progress and animates to a full bar when the
/// web view finishes loading.
///
class WebProgressView: UIProgressView {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
@objc func startedLoading() {
alpha = Animation.visibleAlpha
progress = Progress.initial
}
@objc func finishedLoading() {
UIView.animate(withDuration: Animation.longDuration, animations: { [weak self] in
self?.progress = Progress.final
}, completion: { [weak self] _ in
UIView.animate(withDuration: Animation.shortDuration, animations: {
self?.alpha = Animation.hiddenAlhpa
})
})
}
func observeProgress(webView: WKWebView) {
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [.new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView,
let keyPath = keyPath else {
return
}
switch keyPath {
case #keyPath(WKWebView.estimatedProgress):
progress = Float(webView.estimatedProgress)
isHidden = webView.estimatedProgress == 1
default:
assertionFailure("Observed change to web view that we are not handling")
}
}
private func configure() {
progressTintColor = .primary
backgroundColor = .listBackground
progressViewStyle = .bar
}
private enum Progress {
static let initial = Float(0.1)
static let final = Float(1.0)
}
private enum Animation {
static let shortDuration = 0.1
static let longDuration = 0.4
static let visibleAlpha = CGFloat(1.0)
static let hiddenAlhpa = CGFloat(0.0)
}
}
| 6879f9bf199bd3475eae46a0e20c60d3 | 29.931507 | 150 | 0.632861 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/KeyBackup/Setup/Intro/KeyBackupSetupIntroViewController.swift | apache-2.0 | 1 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
protocol KeyBackupSetupIntroViewControllerDelegate: AnyObject {
func keyBackupSetupIntroViewControllerDidTapSetupAction(_ keyBackupSetupIntroViewController: KeyBackupSetupIntroViewController)
func keyBackupSetupIntroViewControllerDidCancel(_ keyBackupSetupIntroViewController: KeyBackupSetupIntroViewController)
}
final class KeyBackupSetupIntroViewController: UIViewController {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var keyBackupLogoImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var setUpButtonBackgroundView: UIView!
@IBOutlet private weak var setUpButton: UIButton!
@IBOutlet private weak var manualExportContainerView: UIView!
@IBOutlet private weak var manualExportInfoLabel: UILabel!
@IBOutlet private weak var manualExportButton: UIButton!
// MARK: Private
private var theme: Theme!
private var isABackupAlreadyExists: Bool = false
private var encryptionKeysExportPresenter: EncryptionKeysExportPresenter?
private var showManualExport: Bool {
return self.encryptionKeysExportPresenter != nil
}
// MARK: Public
weak var delegate: KeyBackupSetupIntroViewControllerDelegate?
// MARK: - Setup
class func instantiate(isABackupAlreadyExists: Bool, encryptionKeysExportPresenter: EncryptionKeysExportPresenter?) -> KeyBackupSetupIntroViewController {
let viewController = StoryboardScene.KeyBackupSetupIntroViewController.initialScene.instantiate()
viewController.theme = ThemeService.shared().theme
viewController.isABackupAlreadyExists = isABackupAlreadyExists
viewController.encryptionKeysExportPresenter = encryptionKeysExportPresenter
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.keyBackupSetupTitle
self.vc_removeBackTitle()
self.setupViews()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.showSkipAlert()
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
let keybackupLogoImage = Asset.Images.keyBackupLogo.image.withRenderingMode(.alwaysTemplate)
self.keyBackupLogoImageView.image = keybackupLogoImage
self.titleLabel.text = VectorL10n.keyBackupSetupIntroTitle
self.informationLabel.text = VectorL10n.keyBackupSetupIntroInfo
let setupTitle = self.isABackupAlreadyExists ? VectorL10n.keyBackupSetupIntroSetupConnectActionWithExistingBackup : VectorL10n.keyBackupSetupIntroSetupActionWithoutExistingBackup
self.setUpButton.setTitle(setupTitle, for: .normal)
self.manualExportInfoLabel.text = VectorL10n.keyBackupSetupIntroManualExportInfo
self.manualExportContainerView.isHidden = !self.showManualExport
self.manualExportButton.setTitle(VectorL10n.keyBackupSetupIntroManualExportAction, for: .normal)
}
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.keyBackupLogoImageView.tintColor = theme.textPrimaryColor
self.titleLabel.textColor = theme.textPrimaryColor
self.informationLabel.textColor = theme.textPrimaryColor
self.setUpButtonBackgroundView.backgroundColor = theme.backgroundColor
theme.applyStyle(onButton: self.setUpButton)
self.manualExportInfoLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onButton: self.manualExportButton)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
private func showSkipAlert() {
let alertController = UIAlertController(title: VectorL10n.keyBackupSetupSkipAlertTitle,
message: VectorL10n.keyBackupSetupSkipAlertMessage,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: VectorL10n.continue, style: .cancel, handler: { action in
}))
alertController.addAction(UIAlertAction(title: VectorL10n.keyBackupSetupSkipAlertSkipAction, style: .default, handler: { action in
self.delegate?.keyBackupSetupIntroViewControllerDidCancel(self)
}))
self.present(alertController, animated: true, completion: nil)
}
// MARK: - Actions
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
@IBAction private func validateButtonAction(_ sender: Any) {
self.delegate?.keyBackupSetupIntroViewControllerDidTapSetupAction(self)
}
@IBAction private func manualExportButtonAction(_ sender: Any) {
self.encryptionKeysExportPresenter?.present(from: self, sourceView: self.manualExportButton)
}
}
| a1dd52319c6947c5c6827842d7a68f32 | 38.78882 | 186 | 0.715267 | false | false | false | false |
jaropawlak/Signal-iOS | refs/heads/master | Signal/src/Models/AccountManager.swift | gpl-3.0 | 1 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
/**
* Signal is actually two services - textSecure for messages and red phone (for calls).
* AccountManager delegates to both.
*/
class AccountManager: NSObject {
let TAG = "[AccountManager]"
let textSecureAccountManager: TSAccountManager
let networkManager: TSNetworkManager
let preferences: OWSPreferences
var pushManager: PushManager {
// dependency injection hack since PushManager has *alot* of dependencies, and would induce a cycle.
return PushManager.shared()
}
required init(textSecureAccountManager: TSAccountManager, preferences: OWSPreferences) {
self.networkManager = textSecureAccountManager.networkManager
self.textSecureAccountManager = textSecureAccountManager
self.preferences = preferences
}
// MARK: registration
@objc func register(verificationCode: String) -> AnyPromise {
return AnyPromise(register(verificationCode: verificationCode))
}
func register(verificationCode: String) -> Promise<Void> {
guard verificationCode.characters.count > 0 else {
let error = OWSErrorWithCodeDescription(.userError,
NSLocalizedString("REGISTRATION_ERROR_BLANK_VERIFICATION_CODE",
comment: "alert body during registration"))
return Promise(error: error)
}
Logger.debug("\(self.TAG) registering with signal server")
let registrationPromise: Promise<Void> = firstly {
self.registerForTextSecure(verificationCode: verificationCode)
}.then {
self.syncPushTokens()
}.recover { (error) -> Promise<Void> in
switch error {
case PushRegistrationError.pushNotSupported(let description):
// This can happen with:
// - simulators, none of which support receiving push notifications
// - on iOS11 devices which have disabled "Allow Notifications" and disabled "Enable Background Refresh" in the system settings.
Logger.info("\(self.TAG) Recovered push registration error. Registering for manual message fetcher because push not supported: \(description)")
return self.registerForManualMessageFetching()
default:
throw error
}
}.then {
self.completeRegistration()
}
registrationPromise.retainUntilComplete()
return registrationPromise
}
private func registerForTextSecure(verificationCode: String) -> Promise<Void> {
return Promise { fulfill, reject in
self.textSecureAccountManager.verifyAccount(withCode:verificationCode,
success:fulfill,
failure:reject)
}
}
private func syncPushTokens() -> Promise<Void> {
Logger.info("\(self.TAG) in \(#function)")
let job = SyncPushTokensJob(accountManager: self, preferences: self.preferences)
job.uploadOnlyIfStale = false
return job.run()
}
private func completeRegistration() {
Logger.info("\(self.TAG) in \(#function)")
self.textSecureAccountManager.didRegister()
}
// MARK: Message Delivery
func updatePushTokens(pushToken: String, voipToken: String) -> Promise<Void> {
return Promise { fulfill, reject in
self.textSecureAccountManager.registerForPushNotifications(pushToken:pushToken,
voipToken:voipToken,
success:fulfill,
failure:reject)
}
}
func registerForManualMessageFetching() -> Promise<Void> {
return Promise { fulfill, reject in
self.textSecureAccountManager.registerForManualMessageFetching(success:fulfill, failure:reject)
}
}
// MARK: Turn Server
func getTurnServerInfo() -> Promise<TurnServerInfo> {
return Promise { fulfill, reject in
self.networkManager.makeRequest(TurnServerInfoRequest(),
success: { (_: URLSessionDataTask, responseObject: Any?) in
guard responseObject != nil else {
return reject(OWSErrorMakeUnableToProcessServerResponseError())
}
if let responseDictionary = responseObject as? [String: AnyObject] {
if let turnServerInfo = TurnServerInfo(attributes:responseDictionary) {
return fulfill(turnServerInfo)
}
Logger.error("\(self.TAG) unexpected server response:\(responseDictionary)")
}
return reject(OWSErrorMakeUnableToProcessServerResponseError())
},
failure: { (_: URLSessionDataTask, error: Error) in
return reject(error)
})
}
}
}
| 238421f4efedb168d5b639663bfb064a | 42.5 | 159 | 0.554553 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | stdlib/public/core/LifetimeManager.swift | apache-2.0 | 4 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@_inlineable
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_inlineable // FIXME(sil-serialize-all)
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Calls the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, that value is also used
/// as the return value of the `withUnsafeMutablePointer(to:_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure.
@_inlineable
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, that value is also used as the return
/// value of the `withUnsafePointer(to:_:)` function. The pointer argument
/// is valid only for the duration of the function's execution.
/// - Returns: The return value, if any, of the `body` closure.
@_inlineable
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
| a7044f20071fa9874fd78b24f513904a | 39.580153 | 80 | 0.674944 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/ViewControllers/TransactionsTableViewController.swift | mit | 1 | //
// TransactionsTableViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class TransactionsTableViewController: UITableViewController, Subscriber, Trackable {
// MARK: - Public
init(currency: Currency, wallet: Wallet?, didSelectTransaction: @escaping ([Transaction], Int) -> Void) {
self.wallet = wallet
self.currency = currency
self.didSelectTransaction = didSelectTransaction
self.showFiatAmounts = Store.state.showFiatAmounts
super.init(nibName: nil, bundle: nil)
}
deinit {
wallet?.unsubscribe(self)
Store.unsubscribe(self)
}
let didSelectTransaction: ([Transaction], Int) -> Void
var filters: [TransactionFilter] = [] {
didSet {
transactions = filters.reduce(allTransactions, { $0.filter($1) })
tableView.reloadData()
}
}
var didScrollToYOffset: ((CGFloat) -> Void)?
var didStopScrolling: (() -> Void)?
// MARK: - Private
var wallet: Wallet? {
didSet {
if wallet != nil {
subscribeToTransactionUpdates()
}
}
}
private let currency: Currency
private let transactionCellIdentifier = "TransactionCellIdentifier"
private var transactions: [Transaction] = []
private var allTransactions: [Transaction] = [] {
didSet { transactions = allTransactions }
}
private var showFiatAmounts: Bool {
didSet { reload() }
}
private var rate: Rate? {
didSet { reload() }
}
private let emptyMessage = UILabel.wrapping(font: .customBody(size: 16.0), color: .grayTextTint)
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TxListCell.self, forCellReuseIdentifier: transactionCellIdentifier)
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableView.automaticDimension
tableView.contentInsetAdjustmentBehavior = .never
let header = SyncingHeaderView(currency: currency)
header.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
tableView.tableHeaderView = header
emptyMessage.textAlignment = .center
emptyMessage.text = S.TransactionDetails.emptyMessage
setupSubscriptions()
updateTransactions()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Store.trigger(name: .didViewTransactions(transactions))
}
private func setupSubscriptions() {
Store.subscribe(self,
selector: { $0.showFiatAmounts != $1.showFiatAmounts },
callback: { [weak self] state in
self?.showFiatAmounts = state.showFiatAmounts
})
Store.subscribe(self,
selector: { [weak self] oldState, newState in
guard let `self` = self else { return false }
return oldState[self.currency]?.currentRate != newState[self.currency]?.currentRate},
callback: { [weak self] state in
guard let `self` = self else { return }
self.rate = state[self.currency]?.currentRate
})
Store.subscribe(self, name: .txMetaDataUpdated("")) { [weak self] trigger in
guard let trigger = trigger else { return }
if case .txMetaDataUpdated(let txHash) = trigger {
_ = self?.reload(txHash: txHash)
}
}
subscribeToTransactionUpdates()
}
private func subscribeToTransactionUpdates() {
wallet?.subscribe(self) { [weak self] event in
guard let `self` = self else { return }
DispatchQueue.main.async {
switch event {
case .balanceUpdated, .transferAdded, .transferDeleted:
self.updateTransactions()
case .transferChanged(let transfer),
.transferSubmitted(let transfer, _):
if let txHash = transfer.hash?.description, self.reload(txHash: txHash) {
break
}
self.updateTransactions()
default:
break
}
}
}
wallet?.subscribeManager(self) { [weak self] event in
guard let `self` = self else { return }
DispatchQueue.main.async {
if case .blockUpdated = event {
self.updateTransactions()
}
}
}
}
// MARK: -
private func reload() {
assert(Thread.isMainThread)
tableView.reloadData()
if transactions.isEmpty {
if emptyMessage.superview == nil {
tableView.addSubview(emptyMessage)
emptyMessage.constrain([
emptyMessage.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
emptyMessage.topAnchor.constraint(equalTo: tableView.topAnchor, constant: E.isIPhone5 ? 50.0 : AccountHeaderView.headerViewMinHeight),
emptyMessage.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -C.padding[2]) ])
}
} else {
emptyMessage.removeFromSuperview()
}
}
private func reload(txHash: String) -> Bool {
assert(Thread.isMainThread)
guard let index = transactions.firstIndex(where: { txHash == $0.hash }) else { return false }
tableView.reload(row: index, section: 0)
return true
}
private func updateTransactions() {
assert(Thread.isMainThread)
if let transfers = wallet?.transfers {
allTransactions = transfers
reload()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return transactionCell(tableView: tableView, indexPath: indexPath)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectTransaction(transactions, indexPath.row)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Cell Builders
extension TransactionsTableViewController {
private func transactionCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: transactionCellIdentifier,
for: indexPath) as? TxListCell
else { assertionFailure(); return UITableViewCell() }
let rate = self.rate ?? Rate.empty
let viewModel = TxListViewModel(tx: transactions[indexPath.row])
cell.setTransaction(viewModel,
showFiatAmounts: showFiatAmounts,
rate: rate,
isSyncing: currency.state?.syncState != .success)
return cell
}
}
extension TransactionsTableViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
didScrollToYOffset?(scrollView.contentOffset.y)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
didStopScrolling?()
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didStopScrolling?()
}
}
| 8445e3f8a0681a84e9cc86107cd32d1c | 33.788793 | 154 | 0.596828 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/Utility/ObfuscationView.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import UIKit
import WireSystem
final class ObfuscationView: UIImageView {
init(icon: StyleKitIcon) {
super.init(frame: .zero)
backgroundColor = .accentDimmedFlat
isOpaque = true
contentMode = .center
setIcon(icon, size: .tiny, color: UIColor.from(scheme: .background))
switch icon {
case .locationPin:
accessibilityLabel = "Obfuscated location message"
case .paperclip:
accessibilityLabel = "Obfuscated file message"
case .photo:
accessibilityLabel = "Obfuscated image message"
case .microphone:
accessibilityLabel = "Obfuscated audio message"
case .videoMessage:
accessibilityLabel = "Obfuscated video message"
case .link:
accessibilityLabel = "Obfuscated link message"
default:
accessibilityLabel = "Obfuscated view"
}
}
@available(*, unavailable)
required init(coder: NSCoder) {
fatal("initWithCoder: not implemented")
}
}
| ca9c3b3e114c10ab515627b95d8088b1 | 32.277778 | 76 | 0.674457 | false | false | false | false |
sersoft-gmbh/XMLWrangler | refs/heads/master | Sources/XMLWrangler/XMLElement+Attributes.swift | apache-2.0 | 1 | /// Describes a type that can turn itself into an `XMLElement.Attributes.Content`
public protocol XMLAttributeContentConvertible {
/// The attribute content of this type.
var xmlAttributeContent: XMLElement.Attributes.Content { get }
}
/// Describes a type that can be created from an `XMLElement.Attributes.Content` instance.
public protocol ExpressibleByXMLAttributeContent {
/// Creates a new instance of the conforming type using the given attribute content.
/// - Parameter xmlAttributeContent: The attribute content from which to create a new instance.
init?(xmlAttributeContent: XMLElement.Attributes.Content)
}
/// Describes a type that can be converted from and to an `XMLElement.Attributes.Content` instance.
public typealias XMLAttributeContentRepresentable = ExpressibleByXMLAttributeContent & XMLAttributeContentConvertible
extension String: XMLAttributeContentRepresentable {
/// inherited
@inlinable
public var xmlAttributeContent: XMLElement.Attributes.Content { .init(self) }
/// inherited
@inlinable
public init(xmlAttributeContent: XMLElement.Attributes.Content) {
self = xmlAttributeContent.rawValue
}
}
extension XMLAttributeContentConvertible where Self: RawRepresentable, RawValue == XMLElement.Attributes.Content.RawValue {
/// inherited
@inlinable
public var xmlAttributeContent: XMLElement.Attributes.Content { .init(rawValue) }
}
extension ExpressibleByXMLAttributeContent where Self: RawRepresentable, Self.RawValue: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(rawValueDescription: xmlAttributeContent.rawValue)
}
}
extension ExpressibleByXMLAttributeContent where Self: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(xmlAttributeContent.rawValue)
}
}
extension ExpressibleByXMLAttributeContent where Self: LosslessStringConvertible, Self: RawRepresentable, Self.RawValue: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(rawValueDescription: xmlAttributeContent.rawValue)
}
}
extension XMLElement {
/// Contains the attributes of an `XMLElement`.
@frozen
public struct Attributes: Equatable {
/// Represents the key of an attribute.
@frozen
public struct Key: RawRepresentable, Hashable, Codable, ExpressibleByStringLiteral, XMLAttributeContentRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias RawValue = String
/// inherited
public typealias StringLiteralType = RawValue
/// inherited
public let rawValue: RawValue
/// inherited
public var description: String { rawValue }
/// inherited
public var debugDescription: String { "\(Self.self)(\(rawValue))" }
/// inherited
public init(rawValue: RawValue) { self.rawValue = rawValue }
/// Creates a new key using the given raw value.
@inlinable
public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
/// inherited
@inlinable
public init(stringLiteral value: StringLiteralType) { self.init(rawValue: value) }
}
/// Represents the content of an attribute.
@frozen
public struct Content: RawRepresentable, Hashable, ExpressibleByStringLiteral, ExpressibleByStringInterpolation, XMLAttributeContentRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias RawValue = String
/// inhertied
public typealias StringLiteralType = RawValue
/// inherited
public let rawValue: RawValue
/// inherited
@inlinable
public var description: String { rawValue }
/// inherited
public var debugDescription: String { "\(Self.self)(\(rawValue))" }
/// inherited
@inlinable
public var xmlAttributeContent: Content { self }
/// inherited
public init(rawValue: RawValue) { self.rawValue = rawValue }
/// Creates a new key using the given raw value.
@inlinable
public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
/// inherited
@inlinable
public init(stringLiteral value: StringLiteralType) { self.init(rawValue: value) }
/// inherited
@inlinable
public init(xmlAttributeContent: Content) {
self = xmlAttributeContent
}
}
@usableFromInline
typealias Storage = Dictionary<Key, Content>
@usableFromInline
var storage: Storage
/// Returns the keys of in this `Attributes`.
@inlinable
public var keys: Keys { .init(storage: storage.keys) }
/// Returns the contents of in this `Attributes`. The `contents` can be mutated.
@inlinable
public var contents: Contents {
get { .init(storage: storage.values) }
set { storage.values = newValue.storage }
}
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// Creates an empty attributes list.
@inlinable
public init() {
self.init(storage: .init())
}
/// Creates an empty attributes list that reserves the given capacity.
@inlinable
public init(minimumCapacity: Int) {
self.init(storage: .init(minimumCapacity: minimumCapacity))
}
/// Creates an attributes list with the given keys and contents.
/// - Parameter keysAndContents: The sequence of unique key and content tuples to initialize from.
/// - Precondition: The keys must be unique. Failure to fulfill this precondition will result in crahes.
@inlinable
public init<S>(uniqueKeysWithContents keysAndContents: S) where S: Sequence, S.Element == (Key, Content) {
self.init(storage: .init(uniqueKeysWithValues: keysAndContents))
}
/// Creates an attributes list with the given keys and contents, using a closure for uniquing keys.
/// - Parameters:
/// - keysAndContents: The sequence of key and content tuples to initialize from.
/// - combine: The closure to use for uniquing keys. The closure is passed the two contents for non-unique keys and should return the content to choose.
/// - Throws: Rethrows errors thrown by `combine`.
@inlinable
public init<S>(_ keysAndContents: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows
where S: Sequence, S.Element == (Key, Content)
{
try self.init(storage: .init(keysAndContents, uniquingKeysWith: combine))
}
/// Returns / sets the content for the given key.
/// When setting nil, the content is removed for the given key.
/// - Parameters key: The key to look up the content for.
/// - Returns: The content for the given key. `nil` if none is found.
@inlinable
public subscript(key: Key) -> Content? {
get { storage[key] }
set { storage[key] = newValue }
}
/// Returns / sets the content for the given key, using a default if the key does not exist.
/// - Parameters:
/// - key: The key to look up the content for.
/// - default: The default value to use if no value exists for the given `key`.
/// - Returns: The content for the given key. `default` if none is found.
@inlinable
public subscript<Default: XMLAttributeContentConvertible>(key: Key, default defaultValue: @autoclosure () -> Default) -> Content {
get { storage[key, default: defaultValue().xmlAttributeContent] }
set { storage[key, default: defaultValue().xmlAttributeContent] = newValue }
}
/// Filters the attributes using the given predicate closure.
/// - Parameter isIncluded: The closure to execute for each element.
/// Should return `true` for elements that should be in the resulting attributes.
/// - Throws: Any error thrown by `isIncluded`.
/// - Returns: The filtered attributes. Only elements for which `isIncluded` returned `true` are contained.
@inlinable
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Self {
try .init(storage: storage.filter(isIncluded))
}
/// Updates the content element for a given key.
/// - Parameters:
/// - content: The new content element to store for `key`.
/// - key: The key for which to update the content element.
/// - Returns: The old element of `key`, if there was one. `nil` otherwise.
@inlinable
@discardableResult
public mutating func updateContent(_ content: Content, forKey key: Key) -> Content? {
storage.updateValue(content, forKey: key)
}
/// Removes the content for a given key.
/// - Parameter key: The key for which to remove the content.
/// - Returns: The old values of `key`, if there was one. `nil` otherwise.
@inlinable
@discardableResult
public mutating func removeContent(forKey key: Key) -> Content? {
storage.removeValue(forKey: key)
}
/// Merges another sequence of key-content-pairs into the receiving attributes.
/// - Parameters:
/// - other: The sequence of key-content-pairs to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
@inlinable
public mutating func merge<S>(_ other: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows
where S: Sequence, S.Element == (Key, Content)
{
try storage.merge(other, uniquingKeysWith: combine)
}
/// Merges another attributes list into the receiving attributes.
/// - Parameters:
/// - other: The other attributes list to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
@inlinable
public mutating func merge(_ other: Self, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows {
try storage.merge(other.storage, uniquingKeysWith: combine)
}
/// Returns the result of merging another sequence of key-content-pairs with the receiving attributes.
/// - Parameters:
/// - other: The sequence of key-content-pairs to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
/// - Returns: The merged attributes list.
@inlinable
public func merging<S>(_ other: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows -> Self
where S: Sequence, S.Element == (Key, Content)
{
try .init(storage: storage.merging(other, uniquingKeysWith: combine))
}
/// Returns the result of merging another attributes list into the receiving attributes.
/// - Parameters:
/// - other: The other attributes list to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
/// - Returns: The merged attributes list.
@inlinable
public func merging(_ other: Self, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows -> Self {
try .init(storage: storage.merging(other.storage, uniquingKeysWith: combine))
}
/// Removes all key-content pairs from the attributes.
/// Calling this method invalidates all indices of the attributes.
/// - Parameter keepCapacity: Whether the attributes should keep its underlying storage capacity. Defaults to `false`.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
storage.removeAll(keepingCapacity: keepCapacity)
}
}
}
extension Dictionary where Key == XMLElement.Attributes.Key, Value == XMLElement.Attributes.Content {
/// Initializes the dictionary using the storage of the given attributes.
/// - Parameter attributes: The `XMLElement.Attributes` whose contents should be contained in the dictionary.
@inlinable
public init(elementsOf attributes: XMLElement.Attributes) {
self = attributes.storage
}
}
extension XMLElement.Attributes: ExpressibleByDictionaryLiteral {
/// inherited
@inlinable
public init(dictionaryLiteral elements: (Key, XMLAttributeContentConvertible)...) {
self.init(storage: .init(uniqueKeysWithValues: elements.lazy.map { ($0, $1.xmlAttributeContent) }))
}
}
extension XMLElement.Attributes: Sequence {
/// inherited
public typealias Element = (key: Key, content: Content)
/// Casts the `Element` tuple to `Storage.Element`. Uses `unsafeBitCast` since the tuples only differ in labels.
@usableFromInline
static func _castElement(_ storageElement: Storage.Element) -> Element {
unsafeBitCast(storageElement, to: Element.self)
}
/// The iterator for iterating over attributes.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next().map(_castElement)
}
}
/// inherited
@inlinable
public var underestimatedCount: Int { storage.underestimatedCount }
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
}
extension XMLElement.Attributes: Collection {
/// The index for attributes.
@frozen
public struct Index: Comparable {
@usableFromInline
let storageIndex: Storage.Index
@usableFromInline
init(base: Storage.Index) {
storageIndex = base
}
/// inherited
@inlinable
public static func <(lhs: Self, rhs: Self) -> Bool {
lhs.storageIndex < rhs.storageIndex
}
}
/// inherited
@inlinable
public var isEmpty: Bool { storage.isEmpty }
/// inherited
@inlinable
public var count: Int { storage.count }
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
Self._castElement(storage[position.storageIndex])
}
}
extension XMLElement.Attributes: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
"""
\(Self.self) [\(storage.count) key/content pair(s)] {
\(storage.map { " \($0.key): \($0.value)" }.joined(separator: "\n"))
}
"""
}
public var debugDescription: String {
"""
\(Self.self) [\(storage.count) key/content pair(s)] {
\(storage.map { " \($0.key): \($0.value.debugDescription)" }.joined(separator: "\n"))
}
"""
}
}
extension XMLElement.Attributes {
/// A collection of keys inside `XMLElement.Attributes`
@frozen
public struct Keys: Collection, Equatable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias Element = XMLElement.Attributes.Key
/// inherited
public typealias Index = XMLElement.Attributes.Index
@usableFromInline
typealias Storage = XMLElement.Attributes.Storage.Keys
/// The iterator for iterating over `XMLElement.Attributes.Keys`.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next()
}
}
@usableFromInline
let storage: Storage
/// inherited
public var description: String { Array(storage).description }
/// inherited
public var debugDescription: String { Array(storage).debugDescription }
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
storage[position.storageIndex]
}
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
}
/// The (mutable) collection of contents for `XMLElement.Attributes`.
@frozen
public struct Contents: Collection, MutableCollection, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias Element = XMLElement.Attributes.Content
/// inherited
public typealias Index = XMLElement.Attributes.Index
@usableFromInline
typealias Storage = XMLElement.Attributes.Storage.Values
/// The iterator for iterating over `XMLElement.Attributes.Contents`.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next()
}
}
@usableFromInline
var storage: Storage
/// inherited
public var description: String { Array(storage).description }
/// inherited
public var debugDescription: String { Array(storage).debugDescription }
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
get { storage[position.storageIndex] }
set { storage[position.storageIndex] = newValue }
}
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
}
}
| c5ef687d3c3257dd54179719300f157b | 35.503497 | 210 | 0.624761 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/IRGen/prespecialized-metadata/struct-outmodule-1argument-1distinct_use-struct-outmodule-othermodule.swift | apache-2.0 | 3 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s7Generic11OneArgumentVy0C07IntegerVGMN" =
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
import Argument
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVy0C07IntegerVGMD")
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( OneArgument(Integer(13)) )
}
doit()
| f1cbfbcead0cee2e53ac8c63e207dcee | 48.03125 | 278 | 0.720204 | false | false | false | false |
carsonmcdonald/PlaygroundExplorer | refs/heads/master | PlaygroundExplorer/BrowseTableViewController.swift | mit | 1 | import Cocoa
class BrowseTableViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var browseTableView : NSTableView!
private var playgroundDataFiles: [String] = []
private var playgroundRepoData: [String:[PlaygroundEntryRepoData]]?
override func viewDidAppear() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
StatusNotification.broadcastStatus("Updating metadata")
Utils.cloneOrUpdatePlaygroundData()
self.playgroundRepoData = Utils.getRepoInformationFromPlaygroundData()
self.loadAndParsePlaygroundData()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.browseTableView.reloadData()
StatusNotification.broadcastStatus("Metadata update complete")
})
})
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 75
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeViewWithIdentifier("BrowseTableCellView", owner: self) as? BrowseTableCellView {
if let playgroundData = self.parseJSONData(self.playgroundDataFiles[row]) {
cell.playgroundData = playgroundData
return cell
}
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
if self.browseTableView.selectedRow >= 0 && self.playgroundDataFiles.count > self.browseTableView.selectedRow {
let playgroundDataFile = self.playgroundDataFiles[self.browseTableView.selectedRow]
if let playgroundData = self.parseJSONData(playgroundDataFile) {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: ["playgroundData":playgroundData])
}
} else {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: nil)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.playgroundDataFiles.count
}
private func loadAndParsePlaygroundData() {
self.playgroundDataFiles.removeAll(keepCapacity: true)
let playgroundRepo = Utils.getPlaygroundRepoDirectory()
let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(playgroundRepo!, error: nil)
if files != nil {
for file in files! {
let filename = file as! String
if let range = filename.rangeOfString(".json") {
if range.endIndex == filename.endIndex {
if let jsonFile = playgroundRepo?.stringByAppendingPathComponent(filename) {
if NSFileManager.defaultManager().fileExistsAtPath(jsonFile) {
self.playgroundDataFiles.append(jsonFile)
}
}
}
}
}
}
}
private func parseJSONData(jsonFile:String) -> PlaygroundEntryData? {
if let jsonData = NSData(contentsOfFile: jsonFile) {
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error:&parseError)
if parseError != nil {
Utils.showErrorAlert("Error parsing json in \(jsonFile): \(parseError)")
} else {
if let playgroundDataDictionary = parsedObject as? NSDictionary {
if let playgroundData = PlaygroundEntryData(jsonData: playgroundDataDictionary) {
if self.playgroundRepoData != nil {
playgroundData.repoDataList = self.playgroundRepoData![jsonFile.lastPathComponent]
}
return playgroundData
} else {
Utils.showErrorAlert("Playground data format incorrect \(jsonFile)")
}
} else {
Utils.showErrorAlert("Root is not a dictionary \(jsonFile)")
}
}
} else {
Utils.showErrorAlert("Couldn't read file \(jsonFile)")
}
return nil
}
}
| b95412019100950bbb79a65cab6bb07f | 38.070866 | 178 | 0.566505 | false | false | false | false |
ludagoo/Perfect | refs/heads/master | PerfectLib/PerfectError.swift | agpl-3.0 | 2 | //
// PerfectError.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// 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 Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
var errno: Int32 {
return linux_errno()
}
#else
import Darwin
#endif
/// Some but not all of the exception types which may be thrown by the system
public enum PerfectError : ErrorType {
/// A network related error code and message.
case NetworkError(Int32, String)
/// A file system related error code and message.
case FileError(Int32, String)
/// A OS level error code and message.
case SystemError(Int32, String)
/// An API exception error message.
case APIError(String)
}
@noreturn
func ThrowFileError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("FileError: \(err) \(msg)")
throw PerfectError.FileError(err, msg)
}
@noreturn
func ThrowSystemError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("SystemError: \(err) \(msg)")
throw PerfectError.SystemError(err, msg)
}
@noreturn
func ThrowNetworkError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("NetworkError: \(err) \(msg)")
throw PerfectError.NetworkError(err, msg)
}
| d8df347b9a0de922b0ce0f7aabca8fd7 | 27.376623 | 92 | 0.735011 | false | false | false | false |
danielpassos/aerogear-ios-oauth2 | refs/heads/master | AeroGearOAuth2/OAuth2Module.swift | apache-2.0 | 1 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
import SafariServices
import AeroGearHttp
/**
Notification constants emitted during oauth authorization flow.
*/
public let AGAppLaunchedWithURLNotification = "AGAppLaunchedWithURLNotification"
public let AGAppDidBecomeActiveNotification = "AGAppDidBecomeActiveNotification"
public let AGAuthzErrorDomain = "AGAuthzErrorDomain"
/**
The current state that this module is in.
- AuthorizationStatePendingExternalApproval: the module is waiting external approval.
- AuthorizationStateApproved: the oauth flow has been approved.
- AuthorizationStateUnknown: the oauth flow is in unknown state (e.g. user clicked cancel).
*/
enum AuthorizationState {
case authorizationStatePendingExternalApproval
case authorizationStateApproved
case authorizationStateUnknown
}
/**
Parent class of any OAuth2 module implementing generic OAuth2 authorization flow.
*/
open class OAuth2Module: AuthzModule {
/**
Gateway to request authorization access.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
let config: Config
open var http: Http
open var oauth2Session: OAuth2Session
var applicationLaunchNotificationObserver: NSObjectProtocol?
var applicationDidBecomeActiveNotificationObserver: NSObjectProtocol?
var state: AuthorizationState
open var webView: OAuth2WebViewController?
open var idToken: String?
open var serverCode: String?
open var customDismiss: Bool = false
/**
Initialize an OAuth2 module.
:param: config the configuration object that setups the module.
:param: session the session that that module will be bound to.
:param: requestSerializer the actual request serializer to use when performing requests.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:returns: the newly initialized OAuth2Module.
*/
public required init(config: Config, session: OAuth2Session? = nil, requestSerializer: RequestSerializer = HttpRequestSerializer(), responseSerializer: ResponseSerializer = JsonResponseSerializer()) {
if (config.accountId == nil) {
config.accountId = "ACCOUNT_FOR_CLIENTID_\(config.clientId)"
}
if (session == nil) {
self.oauth2Session = TrustedPersistentOAuth2Session(accountId: config.accountId!)
} else {
self.oauth2Session = session!
}
self.config = config
if config.webView == .embeddedWebView {
self.webView = OAuth2WebViewController()
self.customDismiss = true
}
if config.webView == .safariViewController {
self.customDismiss = true
}
self.http = Http(baseURL: config.baseURL, requestSerializer: requestSerializer, responseSerializer: responseSerializer)
self.state = .authorizationStateUnknown
}
// MARK: Public API - To be overridden if necessary by OAuth2 specific adapter
/**
Request an authorization code.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func requestAuthorizationCode(completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
// register with the notification system in order to be notified when the 'authorization' process completes in the
// external browser, and the oauth code is available so that we can then proceed to request the 'access_token'
// from the server.
applicationLaunchNotificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AGAppLaunchedWithURLNotification), object: nil, queue: nil, using: { (notification: Notification!) -> Void in
self.extractCode(notification, completionHandler: completionHandler)
if ( self.webView != nil || self.customDismiss) {
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)
}
})
// register to receive notification when the application becomes active so we
// can clear any pending authorization requests which are not completed properly,
// that is a user switched into the app without Accepting or Cancelling the authorization
// request in the external browser process.
applicationDidBecomeActiveNotificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AGAppDidBecomeActiveNotification), object:nil, queue:nil, using: { (note: Notification!) -> Void in
// check the state
if (self.state == .authorizationStatePendingExternalApproval) {
// unregister
self.stopObserving()
// ..and update state
self.state = .authorizationStateUnknown
}
})
// update state to 'Pending'
self.state = .authorizationStatePendingExternalApproval
// calculate final url
var params = "?scope=\(config.scope)&redirect_uri=\(config.redirectURL.urlEncode())&client_id=\(config.clientId)&response_type=code"
if let audienceId = config.audienceId {
params = "\(params)&audience=\(audienceId)"
}
guard let computedUrl = http.calculateURL(baseURL: config.baseURL, url: config.authzEndpoint) else {
let error = NSError(domain:AGAuthzErrorDomain, code:0, userInfo:["NSLocalizedDescriptionKey": "Malformatted URL."])
completionHandler(nil, error)
return
}
if let url = URL(string:computedUrl.absoluteString + params) {
switch config.webView {
case .embeddedWebView:
if self.webView != nil {
self.webView!.targetURL = url
config.webViewHandler(self.webView!, completionHandler)
}
case .externalSafari:
UIApplication.shared.openURL(url)
case .safariViewController:
let safariController = SFSafariViewController(url: url)
config.webViewHandler(safariController, completionHandler)
}
}
}
/**
Request to refresh an access token.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func refreshAccessToken(completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
if let unwrappedRefreshToken = self.oauth2Session.refreshToken {
var paramDict: [String: String] = ["refresh_token": unwrappedRefreshToken, "client_id": config.clientId, "grant_type": "refresh_token"]
if (config.clientSecret != nil) {
paramDict["client_secret"] = config.clientSecret!
}
http.request(method: .post, path: config.refreshTokenEndpoint!, parameters: paramDict as [String : AnyObject]?, completionHandler: { (response, error) in
if (error != nil) {
completionHandler(nil, error)
return
}
if let unwrappedResponse = response as? [String: AnyObject] {
let accessToken: String = unwrappedResponse["access_token"] as! String
let expiration = unwrappedResponse["expires_in"] as! NSNumber
let exp: String = expiration.stringValue
var refreshToken = unwrappedRefreshToken
if let newRefreshToken = unwrappedResponse["refresh_token"] as? String {
refreshToken = newRefreshToken
}
self.oauth2Session.save(accessToken: accessToken, refreshToken: refreshToken, accessTokenExpiration: exp, refreshTokenExpiration: nil, idToken: nil)
completionHandler(unwrappedResponse["access_token"], nil)
}
})
}
}
/**
Exchange an authorization code for an access token.
:param: code the 'authorization' code to exchange for an access token.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func exchangeAuthorizationCodeForAccessToken(code: String, completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
var paramDict: [String: String] = ["code": code, "client_id": config.clientId, "redirect_uri": config.redirectURL, "grant_type":"authorization_code"]
if let unwrapped = config.clientSecret {
paramDict["client_secret"] = unwrapped
}
if let audience = config.audienceId {
paramDict["audience"] = audience
}
http.request(method: .post, path: config.accessTokenEndpoint, parameters: paramDict as [String : AnyObject]?, completionHandler: {(responseObject, error) in
if (error != nil) {
completionHandler(nil, error)
return
}
if let unwrappedResponse = responseObject as? [String: AnyObject] {
let accessToken = self.tokenResponse(unwrappedResponse)
completionHandler(accessToken as AnyObject?, nil)
}
})
}
open func tokenResponse(_ unwrappedResponse: [String: AnyObject]) -> String {
let accessToken: String = unwrappedResponse["access_token"] as! String
let refreshToken: String? = unwrappedResponse["refresh_token"] as? String
let idToken: String? = unwrappedResponse["id_token"] as? String
let serverCode: String? = unwrappedResponse["server_code"] as? String
let expiration = unwrappedResponse["expires_in"] as? NSNumber
let exp: String? = expiration?.stringValue
// expiration for refresh token is used in Keycloak
let expirationRefresh = unwrappedResponse["refresh_expires_in"] as? NSNumber
let expRefresh = expirationRefresh?.stringValue
self.oauth2Session.save(accessToken: accessToken, refreshToken: refreshToken, accessTokenExpiration: exp, refreshTokenExpiration: expRefresh, idToken: idToken)
self.idToken = self.oauth2Session.idToken
self.serverCode = serverCode
return accessToken
}
/**
Gateway to request authorization access.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func requestAccess(completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
if (self.oauth2Session.accessToken != nil && self.oauth2Session.tokenIsNotExpired()) {
// we already have a valid access token, nothing more to be done
completionHandler(self.oauth2Session.accessToken! as AnyObject?, nil)
} else if (self.oauth2Session.refreshToken != nil && self.oauth2Session.refreshTokenIsNotExpired()) {
// need to refresh token
self.refreshAccessToken(completionHandler: completionHandler)
} else {
// ask for authorization code and once obtained exchange code for access token
self.requestAuthorizationCode(completionHandler: completionHandler)
}
}
/**
Gateway to provide authentication using the Authorization Code Flow with OpenID Connect.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func login(completionHandler: @escaping (AnyObject?, OpenIdClaim?, NSError?) -> Void) {
self.requestAccess { (response: AnyObject?, error: NSError?) -> Void in
if (error != nil) {
completionHandler(nil, nil, error)
return
}
var paramDict: [String: String] = [:]
if response != nil {
paramDict = ["access_token": response! as! String]
}
if let userInfoEndpoint = self.config.userInfoEndpoint {
self.http.request(method: .get, path:userInfoEndpoint, parameters: paramDict as [String : AnyObject]?, completionHandler: {(responseObject, error) in
if (error != nil) {
completionHandler(nil, nil, error)
return
}
var openIDClaims: OpenIdClaim?
if let unwrappedResponse = responseObject as? [String: AnyObject] {
openIDClaims = self.makeOpenIdClaim(fromDict: unwrappedResponse)
}
completionHandler(response, openIDClaims, nil)
})
} else {
completionHandler(nil, nil, NSError(domain: "OAuth2Module", code: 0, userInfo: ["OpenID Connect" : "No UserInfo endpoint available in config"]))
return
}
}
}
open func makeOpenIdClaim(fromDict: [String: AnyObject]) -> OpenIdClaim {
return OpenIdClaim(fromDict: fromDict)
}
/**
Request to revoke access.
:param: completionHandler A block object to be executed when the request operation finishes.
*/
open func revokeAccess(completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
// return if not yet initialized
if (self.oauth2Session.accessToken == nil) {
return
}
// return if no revoke endpoint
guard let revokeTokenEndpoint = config.revokeTokenEndpoint else {
return
}
let paramDict: [String:String] = ["token":self.oauth2Session.accessToken!]
http.request(method: .post, path: revokeTokenEndpoint, parameters: paramDict as [String : AnyObject]?, completionHandler: { (response, error) in
if (error != nil) {
completionHandler(nil, error)
return
}
self.oauth2Session.clearTokens()
completionHandler(response as AnyObject?, nil)
})
}
/**
Return any authorization fields.
:returns: a dictionary filled with the authorization fields.
*/
open func authorizationFields() -> [String: String]? {
if (self.oauth2Session.accessToken == nil) {
return nil
} else {
return ["Authorization":"Bearer \(self.oauth2Session.accessToken!)"]
}
}
/**
Returns a boolean indicating whether authorization has been granted.
:returns: true if authorized, false otherwise.
*/
open func isAuthorized() -> Bool {
return self.oauth2Session.accessToken != nil && self.oauth2Session.tokenIsNotExpired()
}
// MARK: Internal Methods
func extractCode(_ notification: Notification, completionHandler: @escaping (AnyObject?, NSError?) -> Void) {
let info = notification.userInfo!
let url: URL? = info[UIApplicationLaunchOptionsKey.url] as? URL
// extract the code from the URL
let queryParamsDict = self.parametersFrom(queryString: url?.query)
let code = queryParamsDict["code"]
// if exists perform the exchange
if (code != nil) {
self.exchangeAuthorizationCodeForAccessToken(code: code!, completionHandler: completionHandler)
// update state
state = .authorizationStateApproved
} else {
guard let errorName = queryParamsDict["error"] else {
let error = NSError(domain:AGAuthzErrorDomain, code:0, userInfo:["NSLocalizedDescriptionKey": "User cancelled authorization."])
completionHandler(nil, error)
return
}
let errorDescription = queryParamsDict["error_description"] ?? "There was an error!"
let error = NSError(domain: AGAuthzErrorDomain, code: 1, userInfo: ["error": errorName, "errorDescription": errorDescription])
completionHandler(nil, error)
}
// finally, unregister
self.stopObserving()
}
func parametersFrom(queryString: String?) -> [String: String] {
var parameters = [String: String]()
if (queryString != nil) {
let parameterScanner: Scanner = Scanner(string: queryString!)
var name: NSString? = nil
var value: NSString? = nil
while (parameterScanner.isAtEnd != true) {
name = nil
parameterScanner.scanUpTo("=", into: &name)
parameterScanner.scanString("=", into:nil)
value = nil
parameterScanner.scanUpTo("&", into:&value)
parameterScanner.scanString("&", into:nil)
if (name != nil && value != nil) {
parameters[name!.removingPercentEncoding!] = value!.removingPercentEncoding
}
}
}
return parameters
}
deinit {
self.stopObserving()
}
func stopObserving() {
// clear all observers
if (applicationLaunchNotificationObserver != nil) {
NotificationCenter.default.removeObserver(applicationLaunchNotificationObserver!)
self.applicationLaunchNotificationObserver = nil
}
if (applicationDidBecomeActiveNotificationObserver != nil) {
NotificationCenter.default.removeObserver(applicationDidBecomeActiveNotificationObserver!)
applicationDidBecomeActiveNotificationObserver = nil
}
}
}
| 22ea8fb091827ba3fa587b970be14fd7 | 41.182243 | 235 | 0.647225 | false | true | false | false |
sdq/rrule.swift | refs/heads/master | rruledemo/rruledemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// rruledemo
//
// Created by sdq on 7/20/16.
// Copyright © 2016 sdq. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var frequency: NSPopUpButton!
@IBOutlet weak var dtstart: NSDatePicker!
@IBOutlet weak var until: NSDatePicker!
@IBOutlet weak var count: NSTextField!
@IBOutlet weak var interval: NSTextField!
@IBOutlet weak var wkst: NSPopUpButton!
@IBOutlet weak var monday: NSButton!
@IBOutlet weak var tuesday: NSButton!
@IBOutlet weak var wednesday: NSButton!
@IBOutlet weak var thursday: NSButton!
@IBOutlet weak var friday: NSButton!
@IBOutlet weak var saturday: NSButton!
@IBOutlet weak var sunday: NSButton!
@IBOutlet weak var byweekno: NSTextField!
@IBOutlet weak var Jan: NSButton!
@IBOutlet weak var Feb: NSButton!
@IBOutlet weak var Mar: NSButton!
@IBOutlet weak var Apr: NSButton!
@IBOutlet weak var May: NSButton!
@IBOutlet weak var Jun: NSButton!
@IBOutlet weak var Jul: NSButton!
@IBOutlet weak var Aug: NSButton!
@IBOutlet weak var Sep: NSButton!
@IBOutlet weak var Oct: NSButton!
@IBOutlet weak var Nov: NSButton!
@IBOutlet weak var Dec: NSButton!
@IBOutlet weak var bymonthday: NSTextField!
@IBOutlet weak var byyearday: NSTextField!
@IBOutlet weak var bysetpos: NSTextField!
@IBOutlet weak var tableview: NSTableView!
var occurenceArray: [Date] = []
let frequencyArray = ["Yearly", "Monthly", "Weekly", "Daily"]
let weekdayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
override func viewDidLoad() {
super.viewDidLoad()
tableview.dataSource = self
tableview.delegate = self
frequency.removeAllItems()
frequency.addItems(withTitles: frequencyArray)
wkst.removeAllItems()
wkst.addItems(withTitles: weekdayArray)
// frequency.indexOfSelectedItem
}
}
extension ViewController {
@IBAction func convert(_ sender: NSButton) {
//frequency
var rrulefrequency: RruleFrequency = .yearly
switch frequency.indexOfSelectedItem {
case 0:
rrulefrequency = .yearly
case 1:
rrulefrequency = .monthly
case 2:
rrulefrequency = .weekly
case 3:
rrulefrequency = .daily
default:
rrulefrequency = .yearly
}
//dtstart
let rruledtstart = dtstart.dateValue
//until
let rruleuntil = until.dateValue
//count
var rrulecount: Int?
if count.integerValue != 0 {
rrulecount = count.integerValue
}
//interval
var rruleinterval: Int = 1
if interval.integerValue != 0 {
rruleinterval = interval.integerValue
}
//wkst
let rrulewkst = wkst.indexOfSelectedItem
//byweekday
var rrulebyweekday: [Int] = []
if sunday.state.rawValue == 1 {
rrulebyweekday.append(1)
}
if monday.state.rawValue == 1 {
rrulebyweekday.append(2)
}
if tuesday.state.rawValue == 1 {
rrulebyweekday.append(3)
}
if wednesday.state.rawValue == 1 {
rrulebyweekday.append(4)
}
if thursday.state.rawValue == 1 {
rrulebyweekday.append(5)
}
if friday.state.rawValue == 1 {
rrulebyweekday.append(6)
}
if saturday.state.rawValue == 1 {
rrulebyweekday.append(7)
}
//byweekno
var rrulebyweekno: [Int] = []
let byweeknostring = byweekno.stringValue
let stringArray = byweeknostring.components(separatedBy: ",")
for x in stringArray {
if let y = Int(x) {
rrulebyweekno.append(y)
}
}
//bymonth
var rrulebymonth: [Int] = []
if Jan.state.rawValue == 1 {
rrulebymonth.append(1)
}
if Feb.state.rawValue == 1 {
rrulebymonth.append(2)
}
if Mar.state.rawValue == 1 {
rrulebymonth.append(3)
}
if Apr.state.rawValue == 1 {
rrulebymonth.append(4)
}
if May.state.rawValue == 1 {
rrulebymonth.append(5)
}
if Jun.state.rawValue == 1 {
rrulebymonth.append(6)
}
if Jul.state.rawValue == 1 {
rrulebymonth.append(7)
}
if Aug.state.rawValue == 1 {
rrulebymonth.append(8)
}
if Sep.state.rawValue == 1 {
rrulebymonth.append(9)
}
if Oct.state.rawValue == 1 {
rrulebymonth.append(10)
}
if Nov.state.rawValue == 1 {
rrulebymonth.append(11)
}
if Dec.state.rawValue == 1 {
rrulebymonth.append(12)
}
//bymonthday
var rrulebymonthday: [Int] = []
let bymonthdaystring = bymonthday.stringValue
let monthdayArray = bymonthdaystring.components(separatedBy: ",")
for x in monthdayArray {
if let y = Int(x) {
rrulebymonthday.append(y)
}
}
//byyearday
var rrulebyyearday: [Int] = []
let byyeardaystring = byyearday.stringValue
let byyeardayArray = byyeardaystring.components(separatedBy: ",")
for x in byyeardayArray {
if let y = Int(x) {
rrulebyyearday.append(y)
}
}
//bysetpos
var rrulebysetpos: [Int] = []
let bysetposstring = bysetpos.stringValue
let bysetposArray = bysetposstring.components(separatedBy: ",")
for x in bysetposArray {
if let y = Int(x) {
rrulebysetpos.append(y)
}
}
let rule = rrule(frequency: rrulefrequency, dtstart: rruledtstart, until: rruleuntil, count: rrulecount, interval: rruleinterval, wkst: rrulewkst, bysetpos: rrulebysetpos, bymonth: rrulebymonth, bymonthday: rrulebymonthday, byyearday: rrulebyyearday, byweekno: rrulebyweekno, byweekday: rrulebyweekday, byhour: [], byminute: [], bysecond: [])
occurenceArray = rule.getOccurrences()
tableview.reloadData()
}
}
extension ViewController: NSTableViewDataSource, NSTableViewDelegate {
func numberOfRows(in tableView: NSTableView) -> Int {
return occurenceArray.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cellView: NSTableCellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView
let item = occurenceArray[row]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = TimeZone.current
let date = formatter.string(from: item)
cellView.textField!.stringValue = date
return cellView
}
}
| 2448f2d3b671f56f1546f9f189a968f4 | 30.740088 | 350 | 0.585149 | false | false | false | false |
cloudinary/cloudinary_ios | refs/heads/master | Cloudinary/Classes/ios/Uploader/CLDImagePreprocessChain.swift | mit | 1 | //
//
// CLDImagePreprocessChain.swift
//
// Copyright (c) 2017 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
/**
The CLDImagePreprocessChain is used to run preprocessing on images before uploading.
It support processing, validations and encoders, all fully customizable.
*/
public class CLDImagePreprocessChain: CLDPreprocessChain<UIImage> {
public override init() {
}
internal override func decodeResource(_ resourceData: Any) throws -> UIImage? {
if let url = resourceData as? URL {
if let resourceData = try? Data(contentsOf: url) {
return UIImage(data: resourceData)
}
} else if let data = resourceData as? Data {
return UIImage(data: data)
}
return nil
}
internal override func verifyEncoder() throws {
if (encoder == nil) {
setEncoder(CLDPreprocessHelpers.defaultImageEncoder)
}
}
}
| 9cec1b9643675a95c20a489545b614fa | 36.925926 | 85 | 0.706543 | false | false | false | false |
Evgeniy-Odesskiy/Bond | refs/heads/master | Bond/iOS/Bond+UITableView.swift | mit | 1 | //
// Bond+UITableView.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension NSIndexSet {
convenience init(array: [Int]) {
let set = NSMutableIndexSet()
for index in array {
set.addIndex(index)
}
self.init(indexSet: set)
}
}
@objc class TableViewDynamicArrayDataSource: NSObject, UITableViewDataSource {
weak var dynamic: DynamicArray<DynamicArray<UITableViewCell>>?
@objc weak var nextDataSource: UITableViewDataSource?
init(dynamic: DynamicArray<DynamicArray<UITableViewCell>>) {
self.dynamic = dynamic
super.init()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.dynamic?.count ?? 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dynamic?[section].count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return self.dynamic?[indexPath.section][indexPath.item] ?? UITableViewCell()
}
// Forwards
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let ds = self.nextDataSource {
return ds.tableView?(tableView, titleForHeaderInSection: section)
} else {
return nil
}
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if let ds = self.nextDataSource {
return ds.tableView?(tableView, titleForFooterInSection: section)
} else {
return nil
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if let ds = self.nextDataSource {
return ds.tableView?(tableView, canEditRowAtIndexPath: indexPath) ?? false
} else {
return false
}
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if let ds = self.nextDataSource {
return ds.tableView?(tableView, canMoveRowAtIndexPath: indexPath) ?? false
} else {
return false
}
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
if let ds = self.nextDataSource {
return ds.sectionIndexTitlesForTableView?(tableView) ?? []
} else {
return []
}
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
if let ds = self.nextDataSource {
return ds.tableView?(tableView, sectionForSectionIndexTitle: title, atIndex: index) ?? index
} else {
return index
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if let ds = self.nextDataSource {
ds.tableView?(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath)
}
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
if let ds = self.nextDataSource {
ds.tableView?(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath)
}
}
}
private class UITableViewDataSourceSectionBond<T>: ArrayBond<UITableViewCell> {
weak var tableView: UITableView?
var section: Int
init(tableView: UITableView?, section: Int, disableAnimation: Bool = false) {
self.tableView = tableView
self.section = section
super.init()
self.didInsertListener = { [unowned self] a, i in
if let tableView: UITableView = self.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.endUpdates()
}
}
}
self.didRemoveListener = { [unowned self] a, i in
if let tableView = self.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.endUpdates()
}
}
}
self.didUpdateListener = { [unowned self] a, i in
if let tableView = self.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.endUpdates()
}
}
}
self.didResetListener = { [weak self] array in
if let tableView = self?.tableView {
tableView.reloadData()
}
}
}
deinit {
self.unbindAll()
}
}
public class UITableViewDataSourceBond<T>: ArrayBond<DynamicArray<UITableViewCell>> {
weak var tableView: UITableView?
private var dataSource: TableViewDynamicArrayDataSource?
private var sectionBonds: [UITableViewDataSourceSectionBond<Void>] = []
public let disableAnimation: Bool
public weak var nextDataSource: UITableViewDataSource? {
didSet(newValue) {
dataSource?.nextDataSource = newValue
}
}
public init(tableView: UITableView, disableAnimation: Bool = false) {
self.disableAnimation = disableAnimation
self.tableView = tableView
super.init()
self.didInsertListener = { [weak self] array, i in
if let s = self {
if let tableView: UITableView = self?.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.insertSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic)
for section in i.sort(<) {
let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section, disableAnimation: disableAnimation)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
s.sectionBonds.insert(sectionBond, atIndex: section)
for var idx = section + 1; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section += 1
}
}
tableView.endUpdates()
}
}
}
}
self.didRemoveListener = { [weak self] array, i in
if let s = self {
if let tableView = s.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.deleteSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic)
for section in i.sort(>) {
s.sectionBonds[section].unbindAll()
s.sectionBonds.removeAtIndex(section)
for var idx = section; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section -= 1
}
}
tableView.endUpdates()
}
}
}
}
self.didUpdateListener = { [weak self] array, i in
if let s = self {
if let tableView = s.tableView {
perform(animated: !disableAnimation) {
tableView.beginUpdates()
tableView.reloadSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic)
for section in i {
let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section, disableAnimation: disableAnimation)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond)
self?.sectionBonds[section].unbindAll()
self?.sectionBonds[section] = sectionBond
}
tableView.endUpdates()
}
}
}
}
self.didResetListener = { [weak self] array in
if let tableView = self?.tableView {
tableView.reloadData()
}
}
}
public func bind(dynamic: DynamicArray<UITableViewCell>) {
bind(DynamicArray([dynamic]))
}
public override func bind(dynamic: Dynamic<Array<DynamicArray<UITableViewCell>>>, fire: Bool, strongly: Bool) {
super.bind(dynamic, fire: false, strongly: strongly)
if let dynamic = dynamic as? DynamicArray<DynamicArray<UITableViewCell>> {
for section in 0..<dynamic.count {
let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: self.tableView, section: section, disableAnimation: disableAnimation)
let sectionDynamic = dynamic[section]
sectionDynamic.bindTo(sectionBond)
sectionBonds.append(sectionBond)
}
dataSource = TableViewDynamicArrayDataSource(dynamic: dynamic)
dataSource?.nextDataSource = self.nextDataSource
tableView?.dataSource = dataSource
tableView?.reloadData()
}
}
deinit {
self.unbindAll()
tableView?.dataSource = nil
self.dataSource = nil
}
}
private var bondDynamicHandleUITableView: UInt8 = 0
extension UITableView /*: Bondable */ {
public var designatedBond: UITableViewDataSourceBond<UITableViewCell> {
if let d: AnyObject = objc_getAssociatedObject(self, &bondDynamicHandleUITableView) {
return (d as? UITableViewDataSourceBond<UITableViewCell>)!
} else {
let bond = UITableViewDataSourceBond<UITableViewCell>(tableView: self, disableAnimation: false)
objc_setAssociatedObject(self, &bondDynamicHandleUITableView, bond, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return bond
}
}
}
private func perform(animated animated: Bool, block: () -> Void) {
if !animated {
UIView.performWithoutAnimation(block)
} else {
block()
}
}
public func ->> <T>(left: DynamicArray<UITableViewCell>, right: UITableViewDataSourceBond<T>) {
right.bind(left)
}
public func ->> (left: DynamicArray<UITableViewCell>, right: UITableView) {
left ->> right.designatedBond
}
public func ->> (left: DynamicArray<DynamicArray<UITableViewCell>>, right: UITableView) {
left ->> right.designatedBond
}
| e279e00202a51e65b2a8a38ebde9220f | 33.926154 | 156 | 0.672804 | false | false | false | false |
AlexanderMazaletskiy/bodyweight-fitness-ios | refs/heads/master | FitForReddit/ContainerViewController.swift | mit | 1 | import UIKit
import QuartzCore
enum SlideOutState {
case BothCollapsed
case LeftPanelExpanded
case RightPanelExpanded
}
let centerPanelExpandedOffset: CGFloat = 60
class ContainerViewController: UIViewController {
var centerNavigationController: UINavigationController!
var centerViewController: CenterViewController!
var currentState: SlideOutState = SlideOutState.BothCollapsed {
didSet {
let shouldShowShadow = currentState != SlideOutState.BothCollapsed
showShadowForCenterViewController(shouldShowShadow)
}
}
var leftViewController: SidePanelViewController?
override func viewDidLoad() {
super.viewDidLoad()
centerViewController = UIStoryboard.centerViewController()
centerViewController.delegate = self
centerNavigationController = UINavigationController(rootViewController: centerViewController)
view.addSubview(centerNavigationController.view)
addChildViewController(centerNavigationController)
centerNavigationController.didMoveToParentViewController(self)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
centerNavigationController.view.addGestureRecognizer(panGestureRecognizer)
}
}
extension ContainerViewController: CenterViewControllerDelegate {
func toggleLeftPanel() {
let notAlreadyExpanded = (currentState != .LeftPanelExpanded)
if notAlreadyExpanded {
addLeftPanelViewController()
}
animateLeftPanel(shouldExpand: notAlreadyExpanded)
}
func toggleRightPanel() {}
func addLeftPanelViewController() {
if leftViewController == nil {
leftViewController = UIStoryboard.leftViewController()
leftViewController!.animals = Animal.allCats()
addChildSidePanelController(leftViewController!)
}
}
func addChildSidePanelController(sidePanelController: SidePanelViewController) {
view.insertSubview(sidePanelController.view, atIndex: 0)
addChildViewController(sidePanelController)
sidePanelController.didMoveToParentViewController(self)
}
func addRightPanelViewController() {}
func animateLeftPanel(#shouldExpand: Bool) {
if (shouldExpand) {
currentState = .LeftPanelExpanded
animateCenterPanelXPosition(targetPosition: CGRectGetWidth(centerNavigationController.view.frame) - centerPanelExpandedOffset)
} else {
animateCenterPanelXPosition(targetPosition: 0) { finished in
self.currentState = .BothCollapsed
self.leftViewController!.view.removeFromSuperview()
self.leftViewController = nil;
}
}
}
func animateRightPanel(#shouldExpand: Bool) {}
func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: {
self.centerNavigationController.view.frame.origin.x = targetPosition
}, completion: completion)
}
func showShadowForCenterViewController(shouldShowShadow: Bool) {
if (shouldShowShadow) {
centerNavigationController.view.layer.shadowOpacity = 0.8
} else {
centerNavigationController.view.layer.shadowOpacity = 0.0
}
}
}
extension ContainerViewController: UIGestureRecognizerDelegate {
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let gestureIsDraggingFromLeftToRight = (recognizer.velocityInView(view).x > 0)
switch(recognizer.state) {
case .Began:
if (currentState == .BothCollapsed) {
if (gestureIsDraggingFromLeftToRight) {
addLeftPanelViewController()
} else {
addRightPanelViewController()
}
showShadowForCenterViewController(true)
}
case .Changed:
recognizer.view!.center.x = recognizer.view!.center.x + recognizer.translationInView(view).x
recognizer.setTranslation(CGPointZero, inView: view)
case .Ended:
if(leftViewController != nil) {
// animate the side panel open or closed based on whether the view has moved more or less than halfway
let hasMovedGreaterThanHalfway = recognizer.view!.center.x > view.bounds.size.width
animateLeftPanel(shouldExpand: hasMovedGreaterThanHalfway)
}
default:
break
}
}
}
private extension UIStoryboard {
class func mainStoryboard() -> UIStoryboard {
return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
}
class func leftViewController() -> SidePanelViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier("LeftViewController") as? SidePanelViewController
}
class func centerViewController() -> CenterViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier("CenterViewController") as? CenterViewController
}
} | 240614789489f975d7746fa873c38f3b | 36.171233 | 144 | 0.672318 | false | false | false | false |
MAARK/Charts | refs/heads/master | ChartsDemo-iOS/Swift/Demos/PiePolylineChartViewController.swift | apache-2.0 | 4 | //
// PiePolylineChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class PiePolylineChartViewController: DemoBaseViewController {
@IBOutlet var chartView: PieChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Pie Poly Line Chart"
self.options = [.toggleValues,
.toggleXValues,
.togglePercent,
.toggleHole,
.animateX,
.animateY,
.animateXY,
.spin,
.drawCenter,
.saveToGallery,
.toggleData]
self.setup(pieChartView: chartView)
chartView.delegate = self
chartView.legend.enabled = false
chartView.setExtraOffsets(left: 20, top: 0, right: 20, bottom: 0)
sliderX.value = 40
sliderY.value = 100
self.slidersValueChanged(nil)
chartView.animate(xAxisDuration: 1.4, easingOption: .easeOutBack)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value))
}
func setDataCount(_ count: Int, range: UInt32) {
let entries = (0..<count).map { (i) -> PieChartDataEntry in
// IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other.
return PieChartDataEntry(value: Double(arc4random_uniform(range) + range / 5),
label: parties[i % parties.count])
}
let set = PieChartDataSet(entries: entries, label: "Election Results")
set.sliceSpace = 2
set.colors = ChartColorTemplates.vordiplom()
+ ChartColorTemplates.joyful()
+ ChartColorTemplates.colorful()
+ ChartColorTemplates.liberty()
+ ChartColorTemplates.pastel()
+ [UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)]
set.valueLinePart1OffsetPercentage = 0.8
set.valueLinePart1Length = 0.2
set.valueLinePart2Length = 0.4
//set.xValuePosition = .outsideSlice
set.yValuePosition = .outsideSlice
let data = PieChartData(dataSet: set)
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = " %"
data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
data.setValueFont(.systemFont(ofSize: 11, weight: .light))
data.setValueTextColor(.black)
chartView.data = data
chartView.highlightValues(nil)
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleXValues:
chartView.drawEntryLabelsEnabled = !chartView.drawEntryLabelsEnabled
chartView.setNeedsDisplay()
case .togglePercent:
chartView.usePercentValuesEnabled = !chartView.usePercentValuesEnabled
chartView.setNeedsDisplay()
case .toggleHole:
chartView.drawHoleEnabled = !chartView.drawHoleEnabled
chartView.setNeedsDisplay()
case .drawCenter:
chartView.drawCenterTextEnabled = !chartView.drawCenterTextEnabled
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 1.4)
case .animateY:
chartView.animate(yAxisDuration: 1.4)
case .animateXY:
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4)
case .spin:
chartView.spin(duration: 2,
fromAngle: chartView.rotationAngle,
toAngle: chartView.rotationAngle + 360,
easingOption: .easeInCubic)
default:
handleOption(option, forChartView: chartView)
}
}
// MARK: - Actions
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
self.updateChartData()
}
}
| 68544228e3ea84fa961080c869049f97 | 33.041379 | 168 | 0.569895 | false | false | false | false |
argent-os/argent-ios | refs/heads/master | app-ios/PasscodeSettingsViewController.swift | mit | 1 | //
// PasscodeSettingsViewController.swift
// PasscodeLockDemo
//
// Created by Yanko Dimitrov on 8/29/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
import PasscodeLock
class PasscodeSettingsViewController: UIViewController {
@IBOutlet weak var blueLabel: UILabel!
@IBOutlet weak var superView: UIView!
@IBOutlet weak var passcodeSwitch: UISwitch!
@IBOutlet weak var changePasscodeButton: UIButton!
@IBOutlet weak var backgroundView: UIView!
private let configuration: PasscodeLockConfigurationType
init(configuration: PasscodeLockConfigurationType) {
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
let repository = UserDefaultsPasscodeRepository()
configuration = PasscodeLockConfiguration(repository: repository)
super.init(coder: aDecoder)
}
// MARK: - View
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
view.backgroundColor = UIColor.whiteColor()
self.navigationController?.navigationBar.tintColor = UIColor.darkBlue()
updatePasscodeView()
}
override func viewDidLoad() {
passcodeSwitch.onTintColor = UIColor.oceanBlue()
backgroundView.backgroundColor = UIColor.offWhite()
self.navigationItem.title = "App Security"
self.navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 17)!,
NSForegroundColorAttributeName: UIColor.darkBlue()
]
changePasscodeButton.layer.cornerRadius = 10
changePasscodeButton.clipsToBounds = true
changePasscodeButton.backgroundColor = UIColor(rgba: "#ffffff")
}
func updatePasscodeView() {
let hasPasscode = configuration.repository.hasPasscode
changePasscodeButton.hidden = !hasPasscode
passcodeSwitch.on = hasPasscode
}
// MARK: - Actions
@IBAction func passcodeSwitchValueChange(sender: AnyObject) {
let passcodeVC: PasscodeLockViewController
if passcodeSwitch.on {
passcodeVC = PasscodeLockViewController(state: .SetPasscode, configuration: configuration)
} else {
passcodeVC = PasscodeLockViewController(state: .RemovePasscode, configuration: configuration)
passcodeVC.successCallback = { lock in
self.passcodeSwitch.on = !self.passcodeSwitch.on
self.changePasscodeButton.hidden = true
lock.repository.deletePasscode()
}
}
presentViewController(passcodeVC, animated: true, completion: nil)
}
@IBAction func changePasscodeButtonTap(sender: AnyObject) {
let repo = UserDefaultsPasscodeRepository()
let config = PasscodeLockConfiguration(repository: repo)
let passcodeLock = PasscodeLockViewController(state: .ChangePasscode, configuration: config)
presentViewController(passcodeLock, animated: true, completion: nil)
}
//Changing Status Bar
override func prefersStatusBarHidden() -> Bool {
return false
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
// This function is called before the segue, use this to make sure the view controller is properly returned to the root view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "homeView") {
let rootViewController = (self.storyboard?.instantiateViewControllerWithIdentifier("RootViewController"))! as UIViewController
self.presentViewController(rootViewController, animated: true, completion: nil)
}
}
} | 09fda30c202ec6bc926a69330aab3c30 | 31.862903 | 139 | 0.658567 | false | true | false | false |
auth0/Lock.iOS-OSX | refs/heads/master | Lock/LoadingView.swift | mit | 2 | // LoadingView.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class LoadingView: UIView, View {
weak var indicator: UIActivityIndicatorView?
var inProgress: Bool {
get {
return self.indicator?.isAnimating ?? false
}
set {
Queue.main.async {
if newValue {
self.indicator?.startAnimating()
} else {
self.indicator?.stopAnimating()
}
}
}
}
// MARK: - Initialisers
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = Style.Auth0.backgroundColor
#if swift(>=4.2)
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
#else
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
#endif
apply(style: Style.Auth0)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(activityIndicator)
constraintEqual(anchor: activityIndicator.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: activityIndicator.centerYAnchor, toAnchor: self.centerYAnchor)
self.indicator = activityIndicator
self.indicator?.startAnimating()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func apply(style: Style) {
self.backgroundColor = style.backgroundColor
self.indicator?.color = style.disabledTextColor
}
}
| 5e7dcd97410132c59d3311ea23a7702c | 35.534247 | 94 | 0.682415 | false | false | false | false |
wolfposd/DynamicFeedback | refs/heads/master | DynamicFeedbackSheets/DynamicFeedbackSheets/Controller/StartUpViewController.swift | gpl-2.0 | 1 | //
// StartUpViewController.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class StartUpViewController: UIViewController, FeedbackSheetManagerDelegate, FeedbackSheetViewControllerDelegate {
// MARK: Properties
let manager = FeedbackSheetManager(baseURL: "http://beeqn.informatik.uni-hamburg.de/feedback/rest.php/")
let sheetID = "3"
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBActions
@IBAction func startFetch(sender: UIButton) {
manager.startFetchingSheetWithID("3")
}
// MARK: FeedbackSheetManagerDelegate
func feedbackSheetManager(manager: FeedbackSheetManager, didFinishFetchingSheet sheet: FeedbackSheet) {
performSegueWithIdentifier("presentFeedbackSheet", sender: sheet)
}
func feedbackSheetManager(manager: FeedbackSheetManager, didPostSheetWithSuccess success: Bool) {
println("Posting successful")
}
func feedbackSheetManager(manager: FeedbackSheetManager, didFailWithError error: NSError) {
println("Error (feedbackSheetManager didFailWithError) \(error)")
}
// MARK: FeedbackSheetViewControllerDelegate
func feedbackSheetViewController(controller: FeedbackSheetViewController, finishedWithResponse response: NSDictionary!) {
// next step: posting response
println("posting \(response)")
manager.postResponseWithSheetID(sheetID, response: response)
}
func feedbackSheetViewController(controller: FeedbackSheetViewController, didFailWithError error: NSError) {
// Error handling
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "presentFeedbackSheet" {
if let navigationController = segue.destinationViewController as? UINavigationController {
if let sheetViewController = navigationController.topViewController as? FeedbackSheetViewController {
sheetViewController.sheet = sender as FeedbackSheet
sheetViewController.delegate = self
}
}
}
}
}
| 93a16f508dd09b834a87f191c2bd9642 | 32.773333 | 125 | 0.684564 | false | false | false | false |
iOS-mamu/SS | refs/heads/master | P/Library/Eureka/Source/Core/BaseRow.swift | mit | 1 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseRow : BaseRowType {
var callbackOnChange: (()->Void)?
var callbackCellUpdate: (()->Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (()->Void)?
var callbackOnCellHighlight: (()->Void)?
var callbackOnCellUnHighlight: (()->Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var _inlineRow: BaseRow?
/// The title will be displayed in the textLabel of the row.
open var title: String?
/// Parameter used when creating the cell for this row.
open var cellStyle = UITableViewCellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
open var tag: String?
/// The untyped cell associated to this row.
open var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
open var baseValue: Any? {
set {}
get { return nil }
}
open static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
open var disabled : Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
open var hidden : Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
open var isDisabled : Bool { return disabledCache }
/// Returns if this row is currently hidden or not
open var isHidden : Bool { return hiddenCache }
/// The section to which this row belongs.
open weak var section: Section?
public required init(tag: String? = nil){
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
/**
Method that is responsible for highlighting the cell.
*/
open func highlightCell() {}
@available(*, unavailable, message: "Deprecated. Use 'highlightCell' instead.")
open func hightlightCell() { highlightCell() }
/**
Method that is responsible for unhighlighting the cell.
*/
open func unhighlightCell() {}
open func prepareForSegue(_ segue: UIStoryboardSegue) {}
/**
Returns the NSIndexPath where this row is in the current form.
*/
public final func indexPath() -> IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.index(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
fileprivate var hiddenCache = false
fileprivate var disabledCache = false {
willSet {
if newValue == true && disabledCache == false {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_ , let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hideRow(self)
}
else{
section?.showRow(self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_ , let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedToFormInSection(_ section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue as? AnyObject ?? NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers(){
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm(){
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(self, rows: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(self, rows: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(self, rows: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(self, rows: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers(){
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(_ rowAnimation: UITableViewRowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath() else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(_ animated: Bool = true) {
guard let indexPath = indexPath(), let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(_ animated: Bool = false) {
guard let indexPath = indexPath(), let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none)
}
}
public func ==(lhs: BaseRow, rhs: BaseRow) -> Bool{
return lhs === rhs
}
| dba491b06ce2f472e7575f70ad72a84a | 34.437984 | 180 | 0.641037 | false | false | false | false |
neoneye/SwiftyFORM | refs/heads/master | Example/Other/PickerViewViewController.swift | mit | 1 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import SwiftyFORM
class PickerViewViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "PickerViews"
builder += SectionHeaderTitleFormItem().title("PickerView")
builder += picker0
builder += picker1
builder += picker2
builder += SectionHeaderTitleFormItem().title("Misc")
builder += summary
builder += randomizeButton
updateSummary()
}
lazy var picker0: PickerViewFormItem = {
let instance = PickerViewFormItem().title("1 component").behavior(.expanded)
instance.pickerTitles = [["0", "1", "2", "3", "4", "5", "6"]]
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var picker1: PickerViewFormItem = {
let instance = PickerViewFormItem().title("2 components")
instance.pickerTitles = [["00", "01", "02", "03"], ["10", "11", "12", "13", "14"]]
instance.humanReadableValueSeparator = " :: "
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var picker2: PickerViewFormItem = {
let instance = PickerViewFormItem().title("3 components")
instance.pickerTitles = [["00", "01", "02", "03"], ["10", "11", "12"], ["20", "21", "22", "23", "24"]]
instance.humanReadableValueSeparator = " % "
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var summary: StaticTextFormItem = StaticTextFormItem().title("Values").value("-")
func updateSummary() {
let v0 = picker0.value
let v1 = picker1.value
let v2 = picker2.value
summary.value = "\(v0) , \(v1) , \(v2)"
}
lazy var randomizeButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title = "Randomize"
instance.action = { [weak self] in
self?.randomize()
}
return instance
}()
func assignRandomValues(_ pickerView: PickerViewFormItem) {
var selectedRows = [Int]()
for rows in pickerView.pickerTitles {
if rows.count > 0 {
selectedRows.append(Int.random(in: 0..<rows.count))
} else {
selectedRows.append(-1)
}
}
pickerView.setValue(selectedRows, animated: true)
}
func randomize() {
assignRandomValues(picker0)
assignRandomValues(picker1)
assignRandomValues(picker2)
updateSummary()
}
}
| 35a280e95fd14e3956de90162295356a | 27.349398 | 104 | 0.678708 | false | false | false | false |
bradhowes/SynthInC | refs/heads/master | SwiftMIDI/Performance.swift | mit | 1 | //
// Performance.swift
// SynthInC
//
// Created by Brad Howes on 6/6/16.
// Copyright © 2016 Brad Howes. All rights reserved.
//
import Foundation
import AVFoundation
public let phraseBeats = ScorePhrases.map { Int($0.duration * 4) }
public struct PerformerStats {
let remainingBeats: Int
let minPhrase: Int
let maxPhrase: Int
public var isDone: Bool { return remainingBeats == Int.max }
public init() {
self.init(remainingBeats: Int.max, minPhrase: Int.max, maxPhrase: Int.min)
}
public init(currentPhrase: Int) {
self.init(remainingBeats: Int.max, minPhrase: currentPhrase, maxPhrase: currentPhrase)
}
public init(remainingBeats: Int, currentPhrase: Int) {
self.init(remainingBeats: remainingBeats, minPhrase: currentPhrase, maxPhrase: currentPhrase)
}
public init(remainingBeats: Int, minPhrase: Int, maxPhrase: Int) {
self.remainingBeats = remainingBeats
self.minPhrase = minPhrase
self.maxPhrase = maxPhrase
}
public func merge(other: PerformerStats) -> PerformerStats {
return PerformerStats(remainingBeats: min(remainingBeats, other.remainingBeats),
minPhrase: min(minPhrase, other.minPhrase),
maxPhrase: max(maxPhrase, other.maxPhrase))
}
public func merge(other: Performer) -> PerformerStats {
return PerformerStats(remainingBeats: min(remainingBeats, other.remainingBeats),
minPhrase: min(minPhrase, other.currentPhrase),
maxPhrase: max(maxPhrase, other.currentPhrase))
}
}
public final class Performer {
private let index: Int
private let rando: Rando
public private(set) var currentPhrase = 0
public private(set) var remainingBeats: Int
public private(set) var played: Int = 0
public private(set) var desiredPlays: Int = 1
public private(set) var playCounts: [Int] = []
public private(set) var duration: MusicTimeStamp = 0.0
public init(index: Int, rando: Rando) {
self.index = index
self.rando = rando
self.remainingBeats = phraseBeats[0]
self.playCounts.reserveCapacity(ScorePhrases.count)
}
public func tick(elapsed: Int, minPhrase: Int, maxPhrase: Int) -> PerformerStats {
if currentPhrase == ScorePhrases.count {
return PerformerStats(currentPhrase: currentPhrase)
}
remainingBeats -= elapsed
if remainingBeats == 0 {
played += 1
let moveProb = currentPhrase == 0 ? 100 :
max(maxPhrase - currentPhrase, 0) * 15 - max(currentPhrase - minPhrase, 0) * 15 +
max(played - desiredPlays + 1, 0) * 100
if rando.passes(threshold: moveProb) {
playCounts.append(played)
duration += MusicTimeStamp(played) * ScorePhrases[currentPhrase].duration
currentPhrase += 1
if currentPhrase == ScorePhrases.count {
return PerformerStats(currentPhrase: currentPhrase)
}
played = 0
desiredPlays = rando.phraseRepetitions(phraseIndex: currentPhrase)
}
remainingBeats = phraseBeats[currentPhrase]
}
return PerformerStats(remainingBeats: remainingBeats, currentPhrase: currentPhrase)
}
public func finish(goal: MusicTimeStamp) {
precondition(playCounts.count == ScorePhrases.count)
guard let lastPhrase = ScorePhrases.last else { return }
while duration + lastPhrase.duration < goal {
playCounts[ScorePhrases.count - 1] += 1
duration += lastPhrase.duration
}
}
}
public protocol PerformanceGenerator {
func generate() -> [Part]
}
public final class BasicPerformanceGenerator : PerformanceGenerator {
var performers: [Performer]
public init(ensembleSize: Int, rando: Rando) {
performers = (0..<ensembleSize).map { Performer(index: $0, rando: rando) }
}
public func generate() -> [Part] {
var stats = performers.reduce(PerformerStats()) { $0.merge(other: $1) }
while !stats.isDone {
stats = performers.map({$0.tick(elapsed: stats.remainingBeats, minPhrase: stats.minPhrase, maxPhrase: stats.maxPhrase)})
.reduce(PerformerStats()) { $0.merge(other: $1) }
}
let goal = performers.compactMap({ $0.duration }).max() ?? 0.0
performers.forEach { $0.finish(goal: goal) }
return performers.map { $0.generatePart() }
}
}
public class Part {
public let index: Int
public let playCounts: [Int]
public let normalizedRunningDurations: [CGFloat]
public init(index: Int, playCounts: [Int], duration: MusicTimeStamp) {
self.index = index
self.playCounts = playCounts
let durations = zip(playCounts, ScorePhrases).map { MusicTimeStamp($0.0) * $0.1.duration }
let elapsed = durations.reduce(into: Array<MusicTimeStamp>()) {
$0.append(($0.last ?? ($0.reserveCapacity(playCounts.count), 0.0).1) + MusicTimeStamp($1))
}
normalizedRunningDurations = elapsed.map { CGFloat($0 / duration) }
}
public init?(data: Data) {
let decoder = NSKeyedUnarchiver(forReadingWith: data)
self.index = decoder.decodeInteger(forKey: "index")
guard let playCounts = decoder.decodeObject(forKey: "playCounts") as? [Int] else { return nil }
guard let normalizedRunningDurations = decoder.decodeObject(forKey: "normalizedRunningDurations") as? [CGFloat] else { return nil }
self.playCounts = playCounts
self.normalizedRunningDurations = normalizedRunningDurations
}
public func encodePerformance() -> Data {
let data = NSMutableData()
let encoder = NSKeyedArchiver(forWritingWith: data)
encoder.encode(index, forKey: "index")
encoder.encode(playCounts, forKey: "playCounts")
encoder.encode(normalizedRunningDurations, forKey: "normalizedRunningDurations")
encoder.finishEncoding()
return data as Data
}
public func timeline() -> String {
let scale = 1.0
return "\(index):" + playCounts.enumerated().map({"\($0.0)" + String(repeating: "-", count: Int(((MusicTimeStamp($0.1) * ScorePhrases[$0.0].duration) / scale).rounded(.up)))}).joined()
}
}
extension Performer {
func generatePart() -> Part {
return Part(index: index, playCounts: playCounts, duration: duration)
}
}
public class Performance {
public let parts: [Part]
public init(perfGen: PerformanceGenerator) {
self.parts = perfGen.generate()
}
public init?(data: Data) {
let decoder = NSKeyedUnarchiver(forReadingWith: data)
guard let configs = decoder.decodeObject(forKey: "parts") as? [Data] else { return nil }
let parts = configs.compactMap{ Part(data: $0) }
guard configs.count == parts.count else { return nil }
self.parts = parts
}
public func encodePerformance() -> Data {
let data = NSMutableData()
let encoder = NSKeyedArchiver(forWritingWith: data)
encoder.encode(parts.map { $0.encodePerformance() }, forKey: "parts")
encoder.finishEncoding()
return data as Data
}
public func playCounts() -> String {
return parts.map({$0.playCounts.map({String($0)}).joined(separator: " ")}).joined(separator: "\n")
}
public func timelines() -> String {
let lines = parts.map { $0.timeline() }
return lines.joined(separator: "\n")
}
}
| aa77b7e49f5ccce2ddb891de980590cf | 35.192488 | 192 | 0.631989 | false | false | false | false |
colemancda/NetworkObjects | refs/heads/develop | Source/Store.swift | mit | 1 | //
// Store.swift
// NetworkObjects
//
// Created by Alsey Coleman Miller on 9/14/15.
// Copyright © 2015 ColemanCDA. All rights reserved.
//
import SwiftFoundation
import CoreModel
public extension CoreModel.Store {
/// Caches the values of a response.
///
/// - Note: Request and Response must be of the same type or this method will do nothing.
func cacheResponse(response: Response, forRequest request: Request, dateCachedAttributeName: String?) throws {
switch (request, response) {
// 404 responses
case let (.Get(resource), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Edit(resource, _), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Delete(resource), .Error(errorStatusCode)):
// delete object from cache if now found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
// standard responses
case (.Get(let resource), .Get(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Edit(resource, _), .Edit(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Create(entityName, _), .Create(let resourceID, var values)):
try self.createCachePlaceholders(values, entityName: entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
let resource = Resource(entityName, resourceID)
try self.create(resource, initialValues: values)
case let (.Delete(resource), .Delete):
if try self.exists(resource) {
try self.delete(resource)
}
case let (.Search(fetchRequest), .Search(resourceIDs)):
for resourceID in resourceIDs {
let resource = Resource(fetchRequest.entityName, resourceID)
// create placeholder resources for results
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
default: break
}
}
}
private extension CoreModel.Store {
/// Resolves relationships in the values and creates placeholder resources.
private func createCachePlaceholders(values: ValuesObject, entityName: String) throws {
guard let entity = self.model[entityName] else { throw StoreError.InvalidEntity }
for (key, value) in values {
switch value {
case let .Relationship(relationshipValue):
guard let relationship = entity.relationships[key] else { throw StoreError.InvalidValues }
switch relationshipValue {
case let .ToOne(resourceID):
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
case let .ToMany(resourceIDs):
for resourceID in resourceIDs {
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
}
default: break
}
}
}
}
| 0a0cb0e07c70a83de85330c7a3ffe28a | 31.941799 | 114 | 0.473338 | false | false | false | false |
Dhvl-Golakiya/DGSnackbar | refs/heads/master | Pod/Classes/DGSnackbar.swift | mit | 1 | //
// DGSnackbar.swift
// DGSnackbar
//
// Created by Dhvl on 03/09/15.
// Copyright (c) 2015 Dhvl. All rights reserved.
//
import UIKit
@objc public class DGSnackbar: UIView {
public var backgroundView: UIView!
public var messageLabel: UILabel!
public var textInsets: UIEdgeInsets!
public var actionButton : UIButton!
public var interval = TimeInterval()
public var dismisTimer = Timer()
var actionBlock : ((DGSnackbar) -> Void)?
var dismissBlock : ((DGSnackbar) -> Void)?
let buttonWidth : CGFloat = 44
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// 3. Setup view from .xib file
setAllViews()
}
func setAllViews() {
self.backgroundView = UIView()
self.backgroundView.frame = self.bounds
self.backgroundView.backgroundColor = UIColor(white: 0.1, alpha: 0.9)
self.backgroundView.layer.cornerRadius = 3
self.backgroundView.clipsToBounds = true
self.addSubview(self.backgroundView)
self.messageLabel = UILabel()
self.messageLabel.frame = self.bounds
self.messageLabel.textColor = UIColor.white
self.messageLabel.backgroundColor = UIColor.clear
self.messageLabel.font = UIFont.systemFont(ofSize: 14)
self.messageLabel.numberOfLines = 0
self.messageLabel.textAlignment = .center;
self.backgroundView.addSubview(self.messageLabel)
self.actionButton = UIButton()
self.actionButton.frame = self.bounds
self.actionButton.titleLabel?.textColor = UIColor.white
self.actionButton.backgroundColor = UIColor.clear
self.actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
self.actionButton.addTarget(self, action: #selector(onActionButtonPressed(button:)), for: UIControlEvents.touchUpInside)
self.backgroundView.addSubview(self.actionButton)
interval = 0
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceOrientationDidChange(sender:)),
name: NSNotification.Name.UIDeviceOrientationDidChange,
object: nil
)
}
@objc func deviceOrientationDidChange(sender: AnyObject?) {
updateView()
}
required convenience public init?(coder aDecoder: NSCoder) {
self.init()
}
func updateView() {
let deviceWidth = UIScreen.main.bounds.width
let constraintSize = CGSize(width: deviceWidth * (260.0 / 320.0), height: CGFloat.greatestFiniteMagnitude)
let textLabelSize = self.messageLabel.sizeThatFits(constraintSize)
self.messageLabel.frame = CGRect(
x: 5,
y: 5,
width: textLabelSize.width,
height: textLabelSize.height
)
self.backgroundView.frame = CGRect(
x: 2,
y: 0,
width: deviceWidth - 4,
height: self.messageLabel.frame.size.height + 10 >= 54 ? self.messageLabel.frame.size.height + 10 : 54
)
self.messageLabel.center = CGPoint(x: self.messageLabel.center.x, y: self.backgroundView.center.y)
self.actionButton.frame = CGRect(
x: deviceWidth - 51,
y: 5,
width: buttonWidth,
height: buttonWidth
)
self.setViewToBottom()
}
public func makeSnackbar(message : String?, actionButtonTitle : String?, interval : TimeInterval , actionButtonBlock : @escaping ((DGSnackbar) -> Void), dismisBlock : @escaping ((DGSnackbar) -> Void))-> (){
self.messageLabel.text = message
self.actionButton.setTitle(actionButtonTitle, for: UIControlState.normal)
self.interval = interval
self.actionBlock = actionButtonBlock
self.dismissBlock = dismisBlock
show()
}
public func makeSnackbar(message : String?, actionButtonImage : UIImage?, interval : TimeInterval , actionButtonBlock : @escaping ((DGSnackbar) -> Void), dismisBlock : @escaping ((DGSnackbar) -> Void))-> (){
let status = UserDefaults.standard.bool(forKey: "DGSnackbar")
if status {
self.dismissSnackBar()
}
self.messageLabel.text = message
self.actionButton.setImage(actionButtonImage, for: UIControlState.normal)
self.interval = interval
self.actionBlock = actionButtonBlock
self.dismissBlock = dismisBlock
show()
}
public func makeSnackbar(message : String?, interval : TimeInterval, dismisBlock : @escaping ((DGSnackbar) -> Void)) -> () {
self.messageLabel.text = message
self.actionButton.setTitle("", for: UIControlState.normal)
self.interval = interval
self.dismissBlock = dismisBlock
show()
}
func setViewToBottom() {
let screenSize = UIScreen.main.bounds.size
self.frame = CGRect(x: 0, y: screenSize.height , width: screenSize.width, height: self.backgroundView.frame.size.height);
}
func showView() {
let screenSize = UIScreen.main.bounds.size
self.frame = CGRect(x: 0, y: screenSize.height - self.backgroundView.frame.size.height - 2, width: screenSize.width, height: self.backgroundView.frame.size.height);
}
override public var window: UIWindow {
for window in UIApplication.shared.windows {
if NSStringFromClass(type(of: window)) == "UITextEffectsWindow" {
return window
}
}
return UIApplication.shared.windows.first!
}
func show() {
DispatchQueue.main.async {
self.updateView()
self.alpha = 0
self.window.addSubview(self)
UIView.animate(
withDuration: 0.2,
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: {
self.showView()
self.alpha = 1
},
completion: nil)
self.dismisTimer = Timer.scheduledTimer(timeInterval: self.interval, target: self, selector: #selector(self.dismissSnackBar), userInfo: nil, repeats: false)
}
}
@objc func dismissSnackBar() {
self.dismisTimer.invalidate()
UIView.animate(
withDuration: 0.0,
delay: 0,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.setViewToBottom()
self.alpha = 0
},
completion: { animation in
self.dismissBlock!(self)
self.removeFromSuperview()
})
}
@objc func onActionButtonPressed(button : UIButton!) {
self.actionBlock!(self)
dismissSnackBar()
}
}
| 106b8902c90f14910efeedb40141a69f | 33.177885 | 211 | 0.599944 | false | false | false | false |
Molbie/Outlaw | refs/heads/master | Sources/Outlaw/Types/Value/Set+Value.swift | mit | 1 | //
// Set+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/9/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public extension Set {
static func mappedValue<Element: Value>(from object: Any) throws -> Set<Element> {
let anyArray: [Element] = try [Element].mappedValue(from: object)
return Set<Element>(anyArray)
}
}
// MARK: -
// MARK: Transforms
public extension Set {
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element) throws -> T) throws -> Set<T> {
let anyArray: [T] = try [Element].mappedValue(from: object, with: transform)
return Set<T>(anyArray)
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element?) throws -> T) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
static func mappedValue<Element: Value, T>(from object: Any, with transform:(Element?) -> T?) throws -> Set<T> {
let anyArray: [T?] = try [Element?].mappedValue(from: object, with: transform)
return Set<T>(anyArray.compactMap { $0 })
}
}
| 556929780026787309208977707195c8 | 34.428571 | 122 | 0.633737 | false | false | false | false |
mozilla-mobile/focus-ios | refs/heads/main | Blockzilla/Pro Tips/ShareTrackersViewController.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 UIKit
import SnapKit
class ShareTrackersViewController: UIViewController {
private let trackerTitle: String
private let shareTap: (UIButton) -> Void
init(trackerTitle: String, shareTap: @escaping (UIButton) -> Void) {
self.trackerTitle = trackerTitle
self.shareTap = shareTap
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var trackerStatsLabel: UILabel = {
let trackerStatsLabel = UILabel()
trackerStatsLabel.font = .footnote14Light
trackerStatsLabel.textColor = .secondaryText
trackerStatsLabel.numberOfLines = 2
trackerStatsLabel.setContentHuggingPriority(.required, for: .horizontal)
trackerStatsLabel.setContentCompressionResistancePriority(.trackerStatsLabelContentCompressionPriority, for: .horizontal)
return trackerStatsLabel
}()
private lazy var shieldLogo: UIImageView = {
let shieldLogo = UIImageView()
shieldLogo.image = .trackingProtectionOn
shieldLogo.tintColor = UIColor.white
return shieldLogo
}()
private lazy var trackerStatsShareButton: UIButton = {
var button = UIButton()
button.setTitleColor(.secondaryText, for: .normal)
button.titleLabel?.font = .footnote14Light
button.titleLabel?.textAlignment = .center
button.setTitle(UIConstants.strings.share, for: .normal)
button.addTarget(self, action: #selector(shareTapped), for: .touchUpInside)
button.titleLabel?.numberOfLines = 0
button.layer.borderColor = UIColor.secondaryText.cgColor
button.layer.borderWidth = 1.0
button.layer.cornerRadius = 4
button.contentEdgeInsets = UIEdgeInsets(top: CGFloat.trackerStatsShareButtonTopBottomPadding, left: CGFloat.trackerStatsShareButtonLeadingTrailingPadding, bottom: CGFloat.trackerStatsShareButtonTopBottomPadding, right: CGFloat.trackerStatsShareButtonLeadingTrailingPadding)
button.setContentCompressionResistancePriority(.required, for: .horizontal)
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [shieldLogo, trackerStatsLabel, trackerStatsShareButton])
stackView.spacing = .shareTrackerStackViewSpacing
stackView.alignment = .center
stackView.axis = .horizontal
return stackView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(stackView)
trackerStatsLabel.text = trackerTitle
shieldLogo.snp.makeConstraints {
$0.size.equalTo(CGFloat.shieldLogoSize)
}
stackView.snp.makeConstraints {
$0.center.equalToSuperview()
$0.leading.greaterThanOrEqualToSuperview().offset(CGFloat.shareTrackersLeadingTrailingOffset)
$0.trailing.lessThanOrEqualToSuperview().offset(CGFloat.shareTrackersLeadingTrailingOffset)
}
}
@objc private func shareTapped(sender: UIButton) {
shareTap(sender)
}
}
fileprivate extension CGFloat {
static let shieldLogoSize: CGFloat = 20
static let trackerStatsShareButtonTopBottomPadding: CGFloat = 10
static let trackerStatsShareButtonLeadingTrailingPadding: CGFloat = 8
static let shareTrackersLeadingTrailingOffset: CGFloat = 16
static let shareTrackerStackViewSpacing: CGFloat = 16
}
fileprivate extension UILayoutPriority {
static let trackerStatsLabelContentCompressionPriority = UILayoutPriority(999)
}
| dda6f1f98d773b3349c35c298fa0291d | 40.655914 | 281 | 0.720444 | false | false | false | false |
theeternalsw0rd/digital-signage-osx | refs/heads/master | Digital Signage/ViewController.swift | mit | 1 | //
// ViewController.swift
// Digital Signage
//
// Created by Micah Bucy on 12/17/15.
// Copyright © 2015 Micah Bucy. All rights reserved.
//
// The MIT License (MIT)
// This file is subject to the terms and conditions defined in LICENSE.md
import Cocoa
import AVKit
import AVFoundation
import CoreGraphics
struct jsonObject: Decodable {
let countdowns: [jsonCountdown]?
let items: [jsonSlideshowItem]
}
struct jsonCountdown: Decodable {
let day: Int
let hour: Int
let minute: Int
let duration: Int
}
struct jsonSlideshowItem: Decodable {
let type: String
let url: String
let md5sum: String
let filesize: Int
let duration: Int?
}
class ViewController: NSViewController {
private var url = NSURL(fileURLWithPath: "")
private var slideshow : [SlideshowItem] = []
private var slideshowLoader : [SlideshowItem] = []
private var countdowns : [Countdown] = []
private var slideshowLength = 0
private var currentSlideIndex = -1
private var timer = Timer()
private var updateTimer = Timer()
private var countdownTimer = Timer()
private var updateReady = false
private var initializing = true
private var animating = false
private var applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].path + "/theeternalsw0rd/Digital Signage"
private let appDelegate = NSApplication.shared.delegate as! AppDelegate
private let downloadQueue = OperationQueue()
private static var playerItemContext = 0
@IBOutlet weak var countdown: NSTextField!
@IBOutlet weak var goButton: NSButton!
@IBOutlet weak var addressBox: NSTextField!
@IBOutlet weak var label: NSTextField!
@IBAction func goButtonAction(_ sender: AnyObject) {
let urlString = self.addressBox.stringValue
UserDefaults.standard.set(urlString, forKey: "url")
self.loadSignage(urlString: urlString)
}
@IBAction func addressBoxAction(_ sender: AnyObject) {
let urlString = self.addressBox.stringValue
UserDefaults.standard.set(urlString, forKey: "url")
self.loadSignage(urlString: urlString)
}
func resetView() {
self.appDelegate.backgroundThread(background: {
while(self.animating) {
usleep(10000)
}
}, completion: {
self.stopSlideshow()
self.stopUpdater()
self.stopCountdowns()
self.countdown.isHidden = true
let urlString = UserDefaults.standard.string(forKey: "url")
self.initializing = true
self.releaseOtherViews(imageView: nil)
self.label.isHidden = false
self.addressBox.isHidden = false
if(urlString != nil) {
self.addressBox.stringValue = urlString!
}
self.addressBox.becomeFirstResponder()
self.goButton.isHidden = false
self.view.needsLayout = true
})
}
private func loadSignage(urlString: String) {
var isDir : ObjCBool = ObjCBool(false)
if(FileManager.default.fileExists(atPath: self.applicationSupport, isDirectory: &isDir)) {
if(!isDir.boolValue) {
let alert = NSAlert()
alert.messageText = "File already exists at caching directory path."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
return
}
}
else {
do {
try FileManager.default.createDirectory(atPath: self.applicationSupport, withIntermediateDirectories: true, attributes: nil)
}
catch let writeErr {
let alert = NSAlert()
alert.messageText = "Could not create caching directory. " + writeErr.localizedDescription
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
return
}
}
if let _url = URLComponents(string: urlString) {
var url = _url
url.scheme = "https"
if let urlString = url.url?.absoluteString {
if let _surl = NSURL(string: urlString) {
self.url = _surl
self.getJSON()
self.setCountdowns()
self.setUpdateTimer()
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
@objc func backgroundUpdate(timer:Timer) {
self.showNextSlide()
}
private func releaseOtherViews(imageView: NSView?) {
for view in self.view.subviews {
// hide views that need to retain properties
if(view != imageView && view != self.countdown && !(view.isHidden)) {
view.removeFromSuperview()
}
}
}
private func playVideo(frameSize: NSSize, boundsSize: NSSize, uri: NSURL) {
DispatchQueue.main.async(execute: { () -> Void in
let videoView = NSView()
videoView.frame.size = frameSize
videoView.bounds.size = boundsSize
videoView.wantsLayer = true
videoView.layerContentsRedrawPolicy = NSView.LayerContentsRedrawPolicy.onSetNeedsDisplay
let player = AVPlayer(url: uri as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resize
videoView.layer = playerLayer
videoView.layer?.backgroundColor = CGColor(red: 0, green: 0, blue: 0, alpha: 0)
self.view.addSubview(videoView, positioned: NSWindow.OrderingMode.below, relativeTo: self.countdown)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: player.currentItem)
player.currentItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &ViewController.playerItemContext)
player.play()
})
}
private func createImageView(image: NSImage, thumbnail: Bool, frameSize: NSSize, boundsSize: NSSize) {
DispatchQueue.main.async(execute: { () -> Void in
let imageView = MyImageView()
imageView.removeConstraints(imageView.constraints)
imageView.translatesAutoresizingMaskIntoConstraints = true
imageView.alphaValue = 0
if(thumbnail) {
imageView.image = image
}
else {
imageView.imageWithSize(image: image, w: frameSize.width, h: frameSize.height)
}
imageView.frame.size = frameSize
imageView.bounds.size = boundsSize
imageView.wantsLayer = true
imageView.layerContentsRedrawPolicy = NSView.LayerContentsRedrawPolicy.onSetNeedsDisplay
self.view.addSubview(imageView, positioned: NSWindow.OrderingMode.below, relativeTo: self.countdown)
self.animating = true
NSAnimationContext.runAnimationGroup(
{ (context) -> Void in
context.duration = 1.0
imageView.animator().alphaValue = 1.0
}, completionHandler: { () -> Void in
self.releaseOtherViews(imageView: imageView)
if(thumbnail) {
let item = self.slideshow[self.currentSlideIndex]
let path = item.path
let uri = NSURL(fileURLWithPath: path)
self.playVideo(frameSize: frameSize, boundsSize: boundsSize, uri: uri)
}
else {
self.setTimer()
}
self.animating = false
}
)
})
}
private func showNextSlide() {
DispatchQueue.main.async(execute: { () -> Void in
self.currentSlideIndex += 1
if(self.currentSlideIndex == self.slideshowLength) {
if(self.updateReady) {
self.updateSlideshow()
self.updateReady = false
return
}
self.currentSlideIndex = 0
}
if(self.slideshow.count == 0) {
if(self.updateReady) {
self.updateSlideshow()
self.updateReady = false
return
}
NSLog("Slideshow is empty at a point when it shouldn't be. Check server json response for properly configured data.")
self.setTimer()
return
}
let item = self.slideshow[self.currentSlideIndex]
let type = item.type
let path = item.path
let frameSize = self.view.frame.size
let boundsSize = self.view.bounds.size
if(type == "image") {
let image = NSImage(contentsOfFile: path)
self.createImageView(image: image!, thumbnail: false, frameSize: frameSize, boundsSize: boundsSize)
}
else if(type == "video") {
let uri = NSURL(fileURLWithPath: path)
let avAsset = AVURLAsset(url: uri as URL)
let avAssetImageGenerator = AVAssetImageGenerator(asset: avAsset)
let time = NSValue(time: CMTimeMake(0, 1))
avAssetImageGenerator.generateCGImagesAsynchronously(forTimes: [time],
completionHandler: {(_, image:CGImage?, _, _, error:Error?) in
if(error == nil) {
self.createImageView(image: NSImage(cgImage: image!, size: frameSize), thumbnail: true, frameSize: frameSize, boundsSize: boundsSize)
}
else {
self.playVideo(frameSize: frameSize, boundsSize: boundsSize, uri: uri)
}
}
)
}
else {
self.setTimer()
}
})
}
@objc func playerDidFinishPlaying(note: NSNotification) {
self.showNextSlide()
NotificationCenter.default.removeObserver(self)
}
private func stopSlideshow() {
DispatchQueue.main.async(execute: {
self.timer.invalidate()
})
}
private func stopUpdater() {
DispatchQueue.main.async(execute: {
self.updateTimer.invalidate()
})
}
private func stopCountdowns() {
DispatchQueue.main.async(execute: {
self.countdownTimer.invalidate()
})
}
private func setCountdowns() {
DispatchQueue.main.async(execute: {
self.countdownTimer.invalidate()
self.countdownTimer = Timer(timeInterval: 0.1, target: self, selector: #selector(self.updateCountdowns), userInfo: nil, repeats: true)
RunLoop.current.add(self.countdownTimer, forMode: RunLoopMode.commonModes)
})
}
private func setUpdateTimer() {
DispatchQueue.main.async(execute: {
self.updateTimer.invalidate()
self.updateTimer = Timer(timeInterval: 30, target: self, selector: #selector(self.update), userInfo: nil, repeats: false)
RunLoop.current.add(self.updateTimer, forMode: RunLoopMode.commonModes)
})
}
private func setTimer() {
DispatchQueue.main.async(execute: {
var duration: Double = 7.0
if(self.slideshow.count > 0) {
let item = self.slideshow[self.currentSlideIndex]
duration = Double(item.duration)
}
self.timer = Timer(timeInterval: duration, target: self, selector: #selector(self.backgroundUpdate), userInfo: nil, repeats: false)
RunLoop.current.add(self.timer, forMode: RunLoopMode.commonModes)
})
}
private func startSlideshow() {
self.showNextSlide()
}
private func downloadItems() {
if(self.downloadQueue.operationCount > 0) {
return
}
self.downloadQueue.isSuspended = true
for item in self.slideshowLoader {
if(FileManager.default.fileExists(atPath: item.path)) {
if(item.status == 1) {
continue
}
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: item.path)
} catch {
NSLog("Could not remove existing file: %@", item.path)
continue
}
let operation = Downloader(item: item)
self.downloadQueue.addOperation(operation)
}
else {
let operation = Downloader(item: item)
self.downloadQueue.addOperation(operation)
}
}
self.appDelegate.backgroundThread(background: {
self.downloadQueue.isSuspended = false
while(self.downloadQueue.operationCount > 0) {
usleep(100000)
}
}, completion: {
if(self.initializing) {
self.initializing = false
self.goButton.isHidden = true
self.addressBox.resignFirstResponder()
self.addressBox.isHidden = true
self.label.isHidden = true
self.view.becomeFirstResponder()
// move cursor works around mac mini 10.13 bug
var cursorPoint = CGPoint(x: 500, y: 500)
if let screen = NSScreen.main {
// work around cursor sometimes getting stuck in visible state
cursorPoint = CGPoint(x: screen.frame.width, y: screen.frame.height)
}
CGWarpMouseCursorPosition(cursorPoint)
if(!(self.view.window?.styleMask)!.contains(NSWindow.StyleMask.fullScreen)) {
self.view.window?.toggleFullScreen(nil)
}
/* should use this but breaks things on mac minis 10.13 and higher
if(!(self.view.isInFullScreenMode)) {
let presOptions: NSApplicationPresentationOptions =
[NSApplicationPresentationOptions.hideDock, NSApplicationPresentationOptions.hideMenuBar, NSApplicationPresentationOptions.disableAppleMenu]
let optionsDictionary = [NSFullScreenModeApplicationPresentationOptions :
presOptions]
self.view.enterFullScreenMode(NSScreen.main()!, withOptions:optionsDictionary)
}
*/
let view = self.view as! MyView
view.trackMouse = true
view.hideCursor()
view.setTimeout()
self.updateSlideshow()
}
else {
self.updateReady = true
}
})
}
private func updateSlideshow() {
self.stopSlideshow()
self.slideshow = self.slideshowLoader
self.slideshowLength = self.slideshow.count
self.currentSlideIndex = -1
self.slideshowLoader = []
self.appDelegate.backgroundThread(
background: {
let items = self.slideshow
do {
let files = try FileManager.default.contentsOfDirectory(atPath: self.applicationSupport)
for file in files {
let filePath = self.applicationSupport + "/" + file
var remove = true
for item in items {
if(file == "json.txt" || item.path == filePath) {
remove = false
break
}
}
if(remove) {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: filePath)
} catch {
NSLog("Could not remove existing file: %@", filePath)
continue
}
}
}
} catch let readErr {
NSLog("Could not read files from caching directory. " + readErr.localizedDescription)
}
}, completion: {
self.setUpdateTimer()
}
)
self.startSlideshow()
}
func getDayOfWeek(date: NSDate)->Int? {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let myComponents = myCalendar?.components(NSCalendar.Unit.weekday, from: date as Date)
let weekDay = myComponents?.weekday
return weekDay
}
@objc func updateCountdowns() {
let date = NSDate()
let currentDay = getDayOfWeek(date: date)
let calendar = NSCalendar.current
let components = calendar.dateComponents([.hour, .minute, .second], from: date as Date)
let hour = components.hour ?? 0
let minute = components.minute ?? 0
let second = components.second ?? 0
let seconds = hour * 3600 + minute * 60 + second
var hide = true
for countdown in self.countdowns {
if(countdown.day != currentDay || countdown.duration > countdown.minute + countdown.hour * 60) {
continue
}
let countdownSeconds = countdown.hour * 3600 + countdown.minute * 60
let difference = countdownSeconds - seconds
if(difference > 0 && difference <= countdown.duration * 60) {
var minuteString = ""
var secondString = ""
hide = false
let minuteDifference = Int(difference / 60)
let secondDifference = difference % 60
if(minuteDifference < 10) {
minuteString = "0" + String(minuteDifference)
}
else {
minuteString = String(minuteDifference)
}
if(secondDifference < 10) {
secondString = "0" + String(secondDifference)
}
else {
secondString = String(secondDifference)
}
self.countdown.stringValue = minuteString + ":" + secondString
break
}
}
self.countdown.isHidden = hide
}
@objc func update() {
self.getJSON()
}
private func generateCountdowns(countdowns: [jsonCountdown]?) {
self.countdowns = []
guard let countdowns = countdowns
else { return }
for countdown in countdowns {
let day = countdown.day
let hour = countdown.hour
let minute = countdown.minute
let duration = countdown.duration
let newCountdown = Countdown(day: day, hour: hour, minute: minute, duration: duration)
self.countdowns.append(newCountdown)
}
}
private func getJSON() {
if(self.updateReady) {
// don't update while previous update in queue
self.setUpdateTimer()
return
}
let jsonLocation = self.applicationSupport + "/json.txt"
let userAgent = "Digital Signage"
let request = NSMutableURLRequest(url: self.url as URL)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
let session = URLSession.shared
let _ = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if error == nil {
if let dumpData = data {
let dumpNSData = NSData(data: dumpData)
do {
var cachedJSON = try JSONDecoder().decode(jsonObject.self, from: dumpData)
if let cachedData = NSData(contentsOfFile: String(describing: jsonLocation)) {
do {
let localCachedJSON = try JSONDecoder().decode(jsonObject.self, from: cachedData as Data)
cachedJSON = localCachedJSON
if(dumpNSData.isEqual(to: cachedData) && !self.initializing) {
self.setUpdateTimer()
NSLog("No changes")
return
}
if (!(dumpNSData.write(toFile: jsonLocation, atomically: true))) {
NSLog("Unable to write to file %@", jsonLocation)
}
} catch let jsonErr {
NSLog("Catch 1: Could not parse json from data. " + jsonErr.localizedDescription)
}
}
else {
if (!(dumpNSData.write(toFile: jsonLocation, atomically: true))) {
NSLog("Unable to write to file %@", jsonLocation)
}
}
do {
let json = try JSONDecoder().decode(jsonObject.self, from: dumpData)
self.generateCountdowns(countdowns: json.countdowns)
let items = json.items
let cachedItems = cachedJSON.items
if(items.count > 0) {
self.slideshowLoader.removeAll()
for item in items {
let itemUrl = item.url
if let itemNSURL = NSURL(string: itemUrl) {
let type = item.type
if let filename = itemNSURL.lastPathComponent {
let cachePath = self.applicationSupport + "/" + filename
let slideshowItem = SlideshowItem(url: itemNSURL as URL, type: type, path: cachePath)
if(type == "image") {
if let duration = item.duration {
slideshowItem.duration = duration
}
}
do {
let fileAttributes : NSDictionary? = try FileManager.default.attributesOfItem(atPath: NSURL(fileURLWithPath: cachePath, isDirectory: false).path!) as NSDictionary?
if let fileSizeNumber = fileAttributes?.fileSize() {
let fileSize = fileSizeNumber
for cachedItem in cachedItems {
if(itemUrl == cachedItem.url) {
if(item.md5sum == cachedItem.md5sum && item.filesize == fileSize) {
slideshowItem.status = 1
}
}
}
}
}
catch {
}
self.slideshowLoader.append(slideshowItem)
}
else {
NSLog("Could not retrieve filename from url: %@", itemUrl)
}
}
else {
continue
}
}
self.downloadItems()
}
} catch let jsonErr {
NSLog("Catch 3: Could not parse json from data. " + jsonErr.localizedDescription)
return
}
} catch let jsonErr {
NSLog("Catch 2: Could not parse json from data. " + jsonErr.localizedDescription)
return
}
}
else {
let alert = NSAlert()
alert.messageText = "Couldn't process data."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
if(self.initializing) {
if let cachedData = NSData(contentsOfFile: String(describing: jsonLocation)) {
do {
let json = try JSONDecoder().decode(jsonObject.self, from: cachedData as Data)
self.generateCountdowns(countdowns: json.countdowns)
let items = json.items
if(items.count > 0) {
for item in items {
let itemUrl = item.url
if let itemNSURL = NSURL(string: itemUrl) {
let type = item.type
if let filename = itemNSURL.lastPathComponent {
let cachePath = self.applicationSupport + "/" + filename
if(FileManager.default.fileExists(atPath: cachePath)) {
let slideshowItem = SlideshowItem(url: itemNSURL as URL, type: type, path: cachePath)
slideshowItem.status = 1
self.slideshowLoader.append(slideshowItem)
}
}
else {
NSLog("Could not retrieve filename from url: %@", itemUrl)
}
}
else {
continue
}
}
self.downloadItems()
}
} catch let jsonErr {
let alert = NSAlert()
alert.messageText = "Could not parse json from data. " + jsonErr.localizedDescription
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "Couldn't load data."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
NSLog("Offline")
self.setUpdateTimer()
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.window?.acceptsMouseMovedEvents = true
self.countdown.isHidden = true
self.countdown.alphaValue = 0.7
}
override func viewDidAppear() {
super.viewDidAppear()
if let urlString = UserDefaults.standard.string(forKey: "url") {
self.loadSignage(urlString: urlString)
}
if(self.addressBox.isDescendant(of: self.view)) {
DispatchQueue.main.async(execute: { () -> Void in
self.addressBox.becomeFirstResponder()
})
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(context == &ViewController.playerItemContext) {
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
break
case .failed:
(object as! AVPlayerItem?)?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &ViewController.playerItemContext)
self.showNextSlide()
break
case .unknown:
(object as! AVPlayerItem?)?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &ViewController.playerItemContext)
self.showNextSlide()
break
}
}
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| 3c0216665fae42712798266562f188b3 | 42.833568 | 211 | 0.495238 | false | false | false | false |
tuanan94/FRadio-ios | refs/heads/xcode8 | SwiftRadio/Libraries/Spring/AsyncImageView.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 James Tang ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class AsyncImageView: UIImageView {
@objc public var placeholderImage : UIImage?
@objc public var url : NSURL? {
didSet {
self.image = placeholderImage
if let urlString = url?.absoluteString {
ImageLoader.sharedLoader.imageForUrl(urlString: urlString) { [weak self] image, url in
if let strongSelf = self {
DispatchQueue.main.async(execute: { () -> Void in
if strongSelf.url?.absoluteString == url {
strongSelf.image = image ?? strongSelf.placeholderImage
}
})
}
}
}
}
}
@objc public func setURL(url: NSURL?, placeholderImage: UIImage?) {
self.placeholderImage = placeholderImage
self.url = url
}
}
| 9df3be4028b025027b235c8feea596aa | 39.666667 | 102 | 0.647059 | false | false | false | false |
balafd/SAC_iOS | refs/heads/master | SAC/Pods/SwiftForms/SwiftForms/cells/FormDateCell.swift | mit | 1 | //
// FormDateCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 22/08/14.
// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
open class FormDateCell: FormValueCell {
// MARK: Properties
fileprivate let datePicker = UIDatePicker()
fileprivate let hiddenTextField = UITextField(frame: CGRect.zero)
fileprivate let defaultDateFormatter = DateFormatter()
// MARK: FormBaseCell
open override func configure() {
super.configure()
contentView.addSubview(hiddenTextField)
hiddenTextField.inputView = datePicker
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(FormDateCell.valueChanged(_:)), for: .valueChanged)
}
open override func update() {
super.update()
if let showsInputToolbar = rowDescriptor?.configuration.cell.showsInputToolbar , showsInputToolbar && hiddenTextField.inputAccessoryView == nil {
hiddenTextField.inputAccessoryView = inputAccesoryView()
}
titleLabel.text = rowDescriptor?.title
if let rowType = rowDescriptor?.type {
switch rowType {
case .date:
datePicker.datePickerMode = .date
defaultDateFormatter.dateStyle = .long
defaultDateFormatter.timeStyle = .none
case .time:
datePicker.datePickerMode = .time
defaultDateFormatter.dateStyle = .none
defaultDateFormatter.timeStyle = .short
default:
datePicker.datePickerMode = .dateAndTime
defaultDateFormatter.dateStyle = .long
defaultDateFormatter.timeStyle = .short
}
}
if let date = rowDescriptor?.value as? Date {
datePicker.date = date
valueLabel.text = getDateFormatter().string(from: date)
}
}
open override class func formViewController(_ formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) {
guard let row = selectedRow as? FormDateCell else { return }
if row.rowDescriptor?.value == nil {
let date = Date()
row.rowDescriptor?.value = date as AnyObject
row.valueLabel.text = row.getDateFormatter().string(from: date)
row.update()
}
row.hiddenTextField.becomeFirstResponder()
}
open override func firstResponderElement() -> UIResponder? {
return hiddenTextField
}
open override class func formRowCanBecomeFirstResponder() -> Bool {
return true
}
// MARK: Actions
@objc internal func valueChanged(_ sender: UIDatePicker) {
rowDescriptor?.value = sender.date as AnyObject
valueLabel.text = getDateFormatter().string(from: sender.date)
update()
}
// MARK: Private interface
fileprivate func getDateFormatter() -> DateFormatter {
guard let dateFormatter = rowDescriptor?.configuration.date.dateFormatter else { return defaultDateFormatter }
return dateFormatter
}
}
| 66012c4bc49b5ebf82d27bb391222aaf | 32.216495 | 153 | 0.624457 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SourceKit/CursorInfo/cursor_symbol_graph.swift | apache-2.0 | 9 | /// Something about x
let x = 1
_ = x
/**
Something about y
*/
private var y: String { return "hello" }
_ = y
/// Something about
/// Foo
struct Foo<T> {
/** Something about bar */
func bar(x: T) where T: Equatable {}
}
Foo<Int>().bar(x: 1)
Foo<String>().bar(x: "hello")
extension Foo where T == Int {
func blah() {
bar(x: 4)
}
}
/// MyEnum doc.
enum MyEnum {
/// Text in a code line with no indicated semantic meaning.
case someCase
}
// RUN: %sourcekitd-test -req=cursor -pos=2:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKX %s
// RUN: %sourcekitd-test -req=cursor -pos=3:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKX %s
// RUN: %sourcekitd-test -req=cursor -pos=8:13 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKY %s
// RUN: %sourcekitd-test -req=cursor -pos=9:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKY %s
// RUN: %sourcekitd-test -req=cursor -pos=13:8 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s
// RUN: %sourcekitd-test -req=cursor -pos=17:1 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s
// RUN: %sourcekitd-test -req=cursor -pos=18:1 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s
// RUN: %sourcekitd-test -req=cursor -pos=20:11 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefix=CHECKFOO %s
// RUN: %sourcekitd-test -req=cursor -pos=15:10 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_GEN %s
// RUN: %sourcekitd-test -req=cursor -pos=17:12 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_INT %s
// RUN: %sourcekitd-test -req=cursor -pos=22:9 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_INT %s
// RUN: %sourcekitd-test -req=cursor -pos=18:15 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKBAR_ALL,CHECKBAR_STR %s
// RUN: %sourcekitd-test -req=cursor -pos=29:10 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple | %FileCheck -check-prefixes=CHECKCASE %s
// CHECKX: SYMBOL GRAPH BEGIN
// CHECKX: {
// CHECKX: "metadata": {
// CHECKX: "formatVersion": {
// CHECKX: "major":
// CHECKX: "minor":
// CHECKX: "patch":
// CHECKX: },
// CHECKX: "generator":
// CHECKX: },
// CHECKX: "module": {
// CHECKX: "name": "cursor_symbol_graph",
// CHECKX: "platform": {
// CHECKX: "architecture":
// CHECKX: "operatingSystem":
// CHECKX: "vendor":
// CHECKX: }
// CHECKX: },
// CHECKX: "relationships": [],
// CHECKX: "symbols": [
// CHECKX: {
// CHECKX: "accessLevel": "internal",
// CHECKX: "declarationFragments": [
// CHECKX: {
// CHECKX: "kind": "keyword",
// CHECKX: "spelling": "let"
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "text",
// CHECKX: "spelling": " "
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "identifier",
// CHECKX: "spelling": "x"
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "text",
// CHECKX: "spelling": ": "
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "typeIdentifier",
// CHECKX: "preciseIdentifier": "s:Si",
// CHECKX: "spelling": "Int"
// CHECKX: }
// CHECKX: ],
// CHECKX: "docComment": {
// CHECKX: "lines": [
// CHECKX: {
// CHECKX: "range": {
// CHECKX: "end": {
// CHECKX: "character": 21,
// CHECKX: "line": 0
// CHECKX: },
// CHECKX: "start": {
// CHECKX: "character": 4,
// CHECKX: "line": 0
// CHECKX: }
// CHECKX: },
// CHECKX: "text": "Something about x"
// CHECKX: }
// CHECKX: ]
// CHECKX: },
// CHECKX: "identifier": {
// CHECKX: "interfaceLanguage": "swift",
// CHECKX: "precise": "s:19cursor_symbol_graph1xSivp"
// CHECKX: },
// CHECKX: "kind": {
// CHECKX: "displayName": "Global Variable",
// CHECKX: "identifier": "swift.var"
// CHECKX: },
// CHECKX: "location": {
// CHECKX: "position": {
// CHECKX: "character": 4,
// CHECKX: "line": 1
// CHECKX: },
// CHECKX: "uri": "{{.*}}cursor_symbol_graph.swift"
// CHECKX: },
// CHECKX: "names": {
// CHECKX: "subHeading": [
// CHECKX: {
// CHECKX: "kind": "keyword",
// CHECKX: "spelling": "let"
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "text",
// CHECKX: "spelling": " "
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "identifier",
// CHECKX: "spelling": "x"
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "text",
// CHECKX: "spelling": ": "
// CHECKX: },
// CHECKX: {
// CHECKX: "kind": "typeIdentifier",
// CHECKX: "preciseIdentifier": "s:Si",
// CHECKX: "spelling": "Int"
// CHECKX: }
// CHECKX: ],
// CHECKX: "title": "x"
// CHECKX: },
// CHECKX: "pathComponents": [
// CHECKX: "x"
// CHECKX: ]
// CHECKX: }
// CHECKX: ]
// CHECKX: }
// CHECKX: SYMBOL GRAPH END
// CHECKY: SYMBOL GRAPH BEGIN
// CHECKY: {
// CHECKY: "metadata": {
// CHECKY: "formatVersion": {
// CHECKY: "major":
// CHECKY: "minor":
// CHECKY: "patch":
// CHECKY: },
// CHECKY: "generator":
// CHECKY: },
// CHECKY: "module": {
// CHECKY: "name": "cursor_symbol_graph",
// CHECKY: "platform": {
// CHECKY: "architecture":
// CHECKY: "operatingSystem":
// CHECKY: "vendor":
// CHECKY: }
// CHECKY: },
// CHECKY: "relationships": [],
// CHECKY: "symbols": [
// CHECKY: {
// CHECKY: "accessLevel": "private",
// CHECKY: {
// CHECKY: "kind": "keyword",
// CHECKY: "spelling": "var"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": " "
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "identifier",
// CHECKY: "spelling": "y"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": ": "
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "typeIdentifier",
// CHECKY: "preciseIdentifier": "s:SS",
// CHECKY: "spelling": "String"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": " { "
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "keyword",
// CHECKY: "spelling": "get"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": " }"
// CHECKY: }
// CHECKY: ],
// CHECKY: "docComment": {
// CHECKY: "lines": [
// CHECKY: {
// CHECKY: "range": {
// CHECKY: "end": {
// CHECKY: "character": 18,
// CHECKY: "line": 5
// CHECKY: },
// CHECKY: "start": {
// CHECKY: "character": 1,
// CHECKY: "line": 5
// CHECKY: }
// CHECKY: },
// CHECKY: "text": "Something about y"
// CHECKY: },
// CHECKY: {
// CHECKY: "range": {
// CHECKY: "end": {
// CHECKY: "character": 1,
// CHECKY: "line": 6
// CHECKY: },
// CHECKY: "start": {
// CHECKY: "character": 1,
// CHECKY: "line": 6
// CHECKY: }
// CHECKY: },
// CHECKY: "text": ""
// CHECKY: }
// CHECKY: ]
// CHECKY: },
// CHECKY: "identifier": {
// CHECKY: "interfaceLanguage": "swift",
// CHECKY: "precise": "s:19cursor_symbol_graph1y33_153B1E8D9396FFABCE21DE5D3EC1833ALLSSvp"
// CHECKY: },
// CHECKY: "kind": {
// CHECKY: "displayName": "Global Variable",
// CHECKY: "identifier": "swift.var"
// CHECKY: },
// CHECKY: "location": {
// CHECKY: "position": {
// CHECKY: "character": 12,
// CHECKY: "line": 7
// CHECKY: },
// CHECKY: "uri": "{{.*}}cursor_symbol_graph.swift"
// CHECKY: },
// CHECKY: "names": {
// CHECKY: "subHeading": [
// CHECKY: {
// CHECKY: "kind": "keyword",
// CHECKY: "spelling": "var"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": " "
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "identifier",
// CHECKY: "spelling": "y"
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "text",
// CHECKY: "spelling": ": "
// CHECKY: },
// CHECKY: {
// CHECKY: "kind": "typeIdentifier",
// CHECKY: "preciseIdentifier": "s:SS",
// CHECKY: "spelling": "String"
// CHECKY: }
// CHECKY: ],
// CHECKY: "title": "y"
// CHECKY: },
// CHECKY: "pathComponents": [
// CHECKY: "y"
// CHECKY: ]
// CHECKY: }
// CHECKY: ]
// CHECKY: }
// CHECKY: SYMBOL GRAPH END
// CHECKFOO: SYMBOL GRAPH BEGIN
// CHECKFOO: {
// CHECKFOO: "metadata": {
// CHECKFOO: "formatVersion": {
// CHECKFOO: "major":
// CHECKFOO: "minor":
// CHECKFOO: "patch":
// CHECKFOO: },
// CHECKFOO: "generator":
// CHECKFOO: },
// CHECKFOO: "module": {
// CHECKFOO: "name": "cursor_symbol_graph",
// CHECKFOO: "platform": {
// CHECKFOO: "architecture":
// CHECKFOO: "operatingSystem":
// CHECKFOO: "vendor":
// CHECKFOO: }
// CHECKFOO: },
// CHECKFOO: "relationships": [
// CHECKFOO: "target": "s:s8SendableP",
// CHECKFOO: "symbols": [
// CHECKFOO: {
// CHECKFOO: "accessLevel": "internal",
// CHECKFOO: "declarationFragments": [
// CHECKFOO: {
// CHECKFOO: "kind": "keyword",
// CHECKFOO: "spelling": "struct"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "text",
// CHECKFOO: "spelling": " "
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "identifier",
// CHECKFOO: "spelling": "Foo"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "text",
// CHECKFOO: "spelling": "<"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "genericParameter",
// CHECKFOO: "spelling": "T"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "text",
// CHECKFOO: "spelling": ">"
// CHECKFOO: }
// CHECKFOO: ],
// CHECKFOO: "docComment": {
// CHECKFOO: "lines": [
// CHECKFOO: {
// CHECKFOO: "range": {
// CHECKFOO: "end": {
// CHECKFOO: "character": 19,
// CHECKFOO: "line": 10
// CHECKFOO: },
// CHECKFOO: "start": {
// CHECKFOO: "character": 4,
// CHECKFOO: "line": 10
// CHECKFOO: }
// CHECKFOO: },
// CHECKFOO: "text": "Something about"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "range": {
// CHECKFOO: "end": {
// CHECKFOO: "character": 7,
// CHECKFOO: "line": 11
// CHECKFOO: },
// CHECKFOO: "start": {
// CHECKFOO: "character": 4,
// CHECKFOO: "line": 11
// CHECKFOO: }
// CHECKFOO: },
// CHECKFOO: "text": "Foo"
// CHECKFOO: }
// CHECKFOO: ]
// CHECKFOO: },
// CHECKFOO: "identifier": {
// CHECKFOO: "interfaceLanguage": "swift",
// CHECKFOO: "precise": "s:19cursor_symbol_graph3FooV"
// CHECKFOO: },
// CHECKFOO: "kind": {
// CHECKFOO: "displayName": "Structure",
// CHECKFOO: "identifier": "swift.struct"
// CHECKFOO: },
// CHECKFOO: "location": {
// CHECKFOO: "position": {
// CHECKFOO: "character": 7,
// CHECKFOO: "line": 12
// CHECKFOO: },
// CHECKFOO: "uri": "{{.*}}cursor_symbol_graph.swift"
// CHECKFOO: },
// CHECKFOO: "names": {
// CHECKFOO: "navigator": [
// CHECKFOO: {
// CHECKFOO: "kind": "identifier",
// CHECKFOO: "spelling": "Foo"
// CHECKFOO: }
// CHECKFOO: ],
// CHECKFOO: "subHeading": [
// CHECKFOO: {
// CHECKFOO: "kind": "keyword",
// CHECKFOO: "spelling": "struct"
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "text",
// CHECKFOO: "spelling": " "
// CHECKFOO: },
// CHECKFOO: {
// CHECKFOO: "kind": "identifier",
// CHECKFOO: "spelling": "Foo"
// CHECKFOO: }
// CHECKFOO: ],
// CHECKFOO: "title": "Foo"
// CHECKFOO: },
// CHECKFOO: "pathComponents": [
// CHECKFOO: "Foo"
// CHECKFOO: ],
// CHECKFOO: "swiftGenerics": {
// CHECKFOO: "parameters": [
// CHECKFOO: {
// CHECKFOO: "depth": 0,
// CHECKFOO: "index": 0,
// CHECKFOO: "name": "T"
// CHECKFOO: }
// CHECKFOO: ]
// CHECKFOO: }
// CHECKFOO: }
// CHECKFOO: ]
// CHECKFOO: }
// CHECKBAR_ALL: SYMBOL GRAPH BEGIN
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "metadata": {
// CHECKBAR_ALL: "formatVersion": {
// CHECKBAR_ALL: "major":
// CHECKBAR_ALL: "minor":
// CHECKBAR_ALL: "patch":
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "generator":
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "module": {
// CHECKBAR_ALL: "name": "cursor_symbol_graph",
// CHECKBAR_ALL: "platform": {
// CHECKBAR_ALL: "architecture":
// CHECKBAR_ALL: "operatingSystem":
// CHECKBAR_ALL: "vendor":
// CHECKBAR_ALL: }
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "relationships": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "memberOf",
// CHECKBAR_ALL: "source": "s:19cursor_symbol_graph3FooV3bar1xyx_tSQRzlF",
// CHECKBAR_ALL: "target": "s:19cursor_symbol_graph3FooV"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ],
// CHECKBAR_ALL: "symbols": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "accessLevel": "internal",
// CHECKBAR_ALL: "declarationFragments": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "keyword",
// CHECKBAR_ALL: "spelling": "func"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": " "
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "identifier",
// CHECKBAR_ALL: "spelling": "bar"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": "("
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "externalParam",
// CHECKBAR_ALL: "spelling": "x"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": ": "
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "typeIdentifier",
// CHECKBAR_GEN: "spelling": "T"
// CHECKBAR_INT: "preciseIdentifier": "s:Si",
// CHECKBAR_INT: "spelling": "Int"
// CHECKBAR_STR: "preciseIdentifier": "s:SS",
// CHECKBAR_STR: "spelling": "String"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_GEN: "spelling": ") "
// CHECKBAR_INT: "spelling": ")"
// CHECKBAR_STR: "spelling": ")"
// CHECKBAR_INT-NOT: where
// CHECKBAR_STR-NOT: where
// CHECKBAR_GEN: },
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "keyword",
// CHECKBAR_GEN: "spelling": "where"
// CHECKBAR_GEN: },
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "text",
// CHECKBAR_GEN: "spelling": " "
// CHECKBAR_GEN: },
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "typeIdentifier",
// CHECKBAR_GEN: "spelling": "T"
// CHECKBAR_GEN: },
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "text",
// CHECKBAR_GEN: "spelling": " : "
// CHECKBAR_GEN: },
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "typeIdentifier",
// CHECKBAR_GEN: "preciseIdentifier": "s:SQ",
// CHECKBAR_GEN: "spelling": "Equatable"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ],
// CHECKBAR_ALL: "docComment": {
// CHECKBAR_ALL: "lines": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "range": {
// CHECKBAR_ALL: "end": {
// CHECKBAR_ALL: "character": 28,
// CHECKBAR_ALL: "line": 13
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "start": {
// CHECKBAR_ALL: "character": 8,
// CHECKBAR_ALL: "line": 13
// CHECKBAR_ALL: }
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "text": "Something about bar "
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ]
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "functionSignature": {
// CHECKBAR_ALL: "parameters": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "declarationFragments": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "identifier",
// CHECKBAR_ALL: "spelling": "x"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": ": "
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "typeIdentifier",
// CHECKBAR_GEN: "spelling": "T"
// CHECKBAR_INT: "preciseIdentifier": "s:Si",
// CHECKBAR_INT: "spelling": "Int"
// CHECKBAR_STR: "preciseIdentifier": "s:SS",
// CHECKBAR_STR: "spelling": "String"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ],
// CHECKBAR_ALL: "name": "x"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ],
// CHECKBAR_ALL: "returns": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": "()"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ]
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "identifier": {
// CHECKBAR_ALL: "interfaceLanguage": "swift",
// CHECKBAR_ALL: "precise": "s:19cursor_symbol_graph3FooV3bar1xyx_tSQRzlF"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "kind": {
// CHECKBAR_ALL: "displayName": "Instance Method",
// CHECKBAR_ALL: "identifier": "swift.method"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "location": {
// CHECKBAR_ALL: "position": {
// CHECKBAR_ALL: "character": 9,
// CHECKBAR_ALL: "line": 14
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "uri": "{{.*}}cursor_symbol_graph.swift"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "names": {
// CHECKBAR_ALL: "subHeading": [
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "keyword",
// CHECKBAR_ALL: "spelling": "func"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": " "
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "identifier",
// CHECKBAR_ALL: "spelling": "bar"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": "("
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "externalParam",
// CHECKBAR_ALL: "spelling": "x"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": ": "
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "typeIdentifier",
// CHECKBAR_GEN: "spelling": "T"
// CHECKBAR_INT: "preciseIdentifier": "s:Si",
// CHECKBAR_INT: "spelling": "Int"
// CHECKBAR_STR: "preciseIdentifier": "s:SS",
// CHECKBAR_STR: "spelling": "String"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: {
// CHECKBAR_ALL: "kind": "text",
// CHECKBAR_ALL: "spelling": ")"
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ],
// CHECKBAR_ALL: "title": "bar(x:)"
// CHECKBAR_ALL: },
// CHECKBAR_ALL: "pathComponents": [
// CHECKBAR_ALL: "Foo",
// CHECKBAR_ALL: "bar(x:)"
// CHECKBAR_GEN: ],
// CHECKBAR_INT-NOT: "swiftGenerics":
// CHECKBAR_STR-NOT: "swiftGenerics":
// CHECKBAR_GEN: "swiftGenerics": {
// CHECKBAR_GEN: "constraints": [
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "kind": "conformance",
// CHECKBAR_GEN: "lhs": "T",
// CHECKBAR_GEN: "rhs": "Equatable"
// CHECKBAR_GEN: }
// CHECKBAR_GEN: ],
// CHECKBAR_GEN: "parameters": [
// CHECKBAR_GEN: {
// CHECKBAR_GEN: "depth": 0,
// CHECKBAR_GEN: "index": 0,
// CHECKBAR_GEN: "name": "T"
// CHECKBAR_GEN: }
// CHECKBAR_GEN: ]
// CHECKBAR_GEN: }
// CHECKBAR_ALL: }
// CHECKBAR_ALL: ]
// CHECKBAR_ALL: }
// CHECKCASE: SYMBOL GRAPH BEGIN
// CHECKCASE: {
// CHECKCASE: "metadata": {
// CHECKCASE: "formatVersion": {
// CHECKCASE: "major":
// CHECKCASE: "minor":
// CHECKCASE: "patch":
// CHECKCASE: },
// CHECKCASE: "generator":
// CHECKCASE: },
// CHECKCASE: "module": {
// CHECKCASE: "name": "cursor_symbol_graph",
// CHECKCASE: "platform":
// CHECKCASE: },
// CHECKCASE: "relationships": [
// CHECKCASE: {
// CHECKCASE: "kind": "memberOf",
// CHECKCASE: "source": "s:19cursor_symbol_graph6MyEnumO8someCaseyA2CmF",
// CHECKCASE: "target": "s:19cursor_symbol_graph6MyEnumO"
// CHECKCASE: }
// CHECKCASE: ],
// CHECKCASE: "symbols": [
// CHECKCASE: {
// CHECKCASE: "accessLevel": "internal",
// CHECKCASE: "declarationFragments": [
// CHECKCASE: {
// CHECKCASE: "kind": "keyword",
// CHECKCASE: "spelling": "case"
// CHECKCASE: },
// CHECKCASE: {
// CHECKCASE: "kind": "text",
// CHECKCASE: "spelling": " "
// CHECKCASE: },
// CHECKCASE: {
// CHECKCASE: "kind": "identifier",
// CHECKCASE: "spelling": "someCase"
// CHECKCASE: }
// CHECKCASE: ],
// CHECKCASE: "docComment": {
// CHECKCASE: "lines": [
// CHECKCASE: {
// CHECKCASE: "range": {
// CHECKCASE: "end": {
// CHECKCASE: "character": 63,
// CHECKCASE: "line": 27
// CHECKCASE: },
// CHECKCASE: "start": {
// CHECKCASE: "character": 8,
// CHECKCASE: "line": 27
// CHECKCASE: }
// CHECKCASE: },
// CHECKCASE: "text": "Text in a code line with no indicated semantic meaning."
// CHECKCASE: }
// CHECKCASE: ]
// CHECKCASE: },
// CHECKCASE: "identifier": {
// CHECKCASE: "interfaceLanguage": "swift",
// CHECKCASE: "precise": "s:19cursor_symbol_graph6MyEnumO8someCaseyA2CmF"
// CHECKCASE: },
// CHECKCASE: "kind": {
// CHECKCASE: "displayName": "Case",
// CHECKCASE: "identifier": "swift.enum.case"
// CHECKCASE: },
// CHECKCASE: "location": {
// CHECKCASE: "position": {
// CHECKCASE: "character": 9,
// CHECKCASE: "line": 28
// CHECKCASE: },
// CHECKCASE: "uri": "{{.*}}cursor_symbol_graph.swift"
// CHECKCASE: },
// CHECKCASE: "names": {
// CHECKCASE: "subHeading": [
// CHECKCASE: {
// CHECKCASE: "kind": "keyword",
// CHECKCASE: "spelling": "case"
// CHECKCASE: },
// CHECKCASE: {
// CHECKCASE: "kind": "text",
// CHECKCASE: "spelling": " "
// CHECKCASE: },
// CHECKCASE: {
// CHECKCASE: "kind": "identifier",
// CHECKCASE: "spelling": "someCase"
// CHECKCASE: }
// CHECKCASE: ],
// CHECKCASE: "title": "MyEnum.someCase"
// CHECKCASE: },
// CHECKCASE: "pathComponents": [
// CHECKCASE: "MyEnum",
// CHECKCASE: "someCase"
// CHECKCASE: ]
// CHECKCASE: }
// CHECKCASE: ]
// CHECKCASE: }
// CHECKCASE: SYMBOL GRAPH END
| d64c35ec8fd036df51d2844677a63353 | 33.93725 | 172 | 0.467441 | false | false | false | false |
shial4/VaporGCM | refs/heads/master | Sources/VaporGCM/GCMPayload.swift | mit | 1 | //
// GCMPayload.swift
// VaporGCM
//
// Created by Shial on 11/04/2017.
//
//
import Foundation
import JSON
///Parameters for gcmPayload messaging by platform
public struct GCMPayload {
// Simple, empty initializer
public init() {}
//Indicates notification title. This field is not visible on iOS phones and tablets.
public var title: String?
//Indicates notification body text.
public var body: String?
//Indicates notification icon.
public var icon: String = "myicon"
//Indicates a sound to play when the device receives the notification.
public var sound: String?
///Indicates whether each notification message results in a new entry on the notification center. If not set, each request creates a new notification. If set, and a notification with the same tag is already being shown, the new notification replaces the existing one in notification center.
public var tag: String?
///Indicates color of the icon, expressed in #rrggbb format
public var color: String?
///The action associated with a user click on the notification.
public var clickAction: String?
///Indicates the key to the body string for localization.
public var bodyLocKey: String?
///Indicates the string value to replace format specifiers in body string for localization.
public var bodyLocArgs: JSON?
///Indicates the key to the title string for localization.
public var titleLocKey: JSON?
///Indicates the string value to replace format specifiers in title string for localization.
public var titleLocArgs: JSON?
public func makeJSON() throws -> JSON {
var payload: [String: NodeRepresentable] = ["icon":icon]
if let value = title {
payload["title"] = value
}
if let value = body {
payload["body"] = value
}
if let value = sound {
payload["sound"] = value
}
if let value = tag {
payload["tag"] = value
}
if let value = color {
payload["color"] = value
}
if let value = clickAction {
payload["click_action"] = value
}
if let value = bodyLocKey {
payload["body_loc_key"] = value
}
if let value = bodyLocArgs {
payload["body_loc_args"] = value
}
if let value = titleLocKey {
payload["title_loc_key"] = value
}
if let value = titleLocArgs {
payload["title_loc_args"] = value
}
let json = JSON(node: try payload.makeNode(in: nil))
return json
}
}
public extension GCMPayload {
public init(message: String) {
self.init()
self.body = message
}
public init(title: String, body: String) {
self.init()
self.title = title
self.body = body
}
}
| 89199caa3e0692821f330efef4d2b05c | 32.195402 | 294 | 0.621537 | false | false | false | false |
randymarsh77/amethyst | refs/heads/master | players/iOS/Sources/AppViewModel.swift | mit | 1 | import AVFoundation
import Foundation
import Async
import Bonjour
import Cancellation
import Crystal
import Fetch
import Scope
import Sockets
import Streams
import Time
import Using
import WKInterop
public class AppModel
{
public init(_ interop: WKInterop) {
_interop = interop
_state = State()
_state.statusMessage = "Idle"
_visualizer = VisualizerViewModel(interop)
_player = V2AudioStreamPlayer()
_ = _interop.registerEventHandler(route: "js.togglePlayPause") {
self.togglePlayPause()
}
_ = _interop.registerEventHandler(route: "js.ready") {
self.publishState()
}
_ = _interop.registerRequestHandler(route: "cover") {
return GetCover()
}
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
tryConnect()
}
private func tryConnect() {
let qSettings = QuerySettings(
serviceType: .Unregistered(identifier: "_crystal-content"),
serviceProtocol: .TCP,
domain: .AnyDomain
)
self.setStatusMessage("Searching for services...")
DispatchQueue.global(qos: .default).async
{
let service = await (Bonjour.FindAll(qSettings)).first
if (service != nil)
{
self.setStatusMessage("Found service, attempting to resolve host...")
await (Bonjour.Resolve(service!))
let endpoint = service!.getEndpointAddress()!
self.setStatusMessage("Resolved host to \(endpoint.host) on port \(endpoint.port)")
let client = TCPClient(endpoint: endpoint)
using ((try! client.tryConnect())!) { (socket: Socket) in
using (socket.createAudioStream()) { (audio: ReadableStream<AudioData>) in
self.setIsPlaying(true)
socket.pong()
_ = audio
.pipe(to: self._player.stream)
// .convert(to: kAudioFormatLinearPCM)
// .pipe(to: self._visualizer.stream)
await (Cancellation(self._playTokenSource!.token))
}}
}
else
{
self.setStatusMessage("No services found :(")
}
}
}
private func togglePlayPause() {
DispatchQueue.main.async {
NSLog("Toggling play state")
if (self._state.isPlaying) {
self.setIsPlaying(false)
} else {
self.tryConnect()
}
}
}
private func setStatusMessage(_ message: String) {
DispatchQueue.main.async {
NSLog("Setting status: %@", message)
self._state.statusMessage = message
self.publishState()
}
}
private func setIsPlaying(_ playing: Bool) {
if (self._state.isPlaying == playing) {
return
}
_playTokenSource?.cancel()
_playTokenSource = CancellationTokenSource()
self._state.isPlaying = playing
DispatchQueue.main.async {
self.publishState()
}
}
private func publishState() {
_interop.publish(route: "swift.set.state", content: _state)
}
private var _interop: WKInterop
private var _state: State
private var _visualizer: VisualizerViewModel
private var _player: V2AudioStreamPlayer
private var _playTokenSource: CancellationTokenSource?
}
func GetCover() -> Task<String>
{
return async { (task: Task<String>) in
let qSettings = QuerySettings(
serviceType: .Unregistered(identifier: "_crystal-meta"),
serviceProtocol: .TCP,
domain: .AnyDomain
)
var result = ""
DispatchQueue.global(qos: .default).async
{
let service = await (Bonjour.FindAll(qSettings)).first
if (service != nil)
{
await (Bonjour.Resolve(service!))
let endpoint = service!.getEndpointAddress()!
let url = "http://\(endpoint.host):\(endpoint.port)/art"
let data = await (Fetch(URL(string: url)!))
if (data != nil) {
result = "data:image/png;base64,\(data!.base64EncodedString())"
}
}
Async.Wake(task)
}
Async.Suspend()
return result
}
}
fileprivate func Cancellation(_ token: CancellationToken) -> Task<Void> {
let task = async {
Async.Suspend()
}
_ = try! token.register {
Async.Wake(task)
}
return task
}
| 1cd3cf4af2f765f4476abf5b112f96c2 | 21.869822 | 87 | 0.687451 | false | false | false | false |
fromkk/Valy | refs/heads/master | Sources/ValyHelper.swift | mit | 1 | //
// ValyHelper.swift
// Validator
//
// Created by Kazuya Ueoka on 2016/11/15.
//
//
import Foundation
@objc public enum ValidatorRule: Int {
case required
case match
case pattern
case alphabet
case digit
case alnum
case number
case minLength
case maxLength
case exactLength
case numericMin
case numericMax
case numericBetween
}
@objc public class Validator: NSObject {
private let shared: AnyValidator = Valy.factory()
@objc(addRule:)
public func add(rule: ValidatorRule) -> Self {
return self.add(rule: rule, value1: nil, value2: nil)
}
@objc(addRule:value:)
public func add(rule: ValidatorRule, value: Any?) -> Self {
return self.add(rule: rule, value1: value, value2: nil)
}
@objc(addRule:value1:value2:)
public func add(rule: ValidatorRule, value1: Any?, value2: Any?) -> Self {
switch rule {
case .required:
self.shared.add(rule: ValyRule.required)
case .match:
guard let match: String = value1 as? String else {
return self
}
self.shared.add(rule: ValyRule.match(match))
case .pattern:
guard let pattern: String = value1 as? String else {
return self
}
self.shared.add(rule: ValyRule.pattern(pattern))
case .alphabet:
self.shared.add(rule: ValyRule.alphabet)
case .digit:
self.shared.add(rule: ValyRule.digit)
case .alnum:
self.shared.add(rule: ValyRule.alnum)
case .number:
self.shared.add(rule: ValyRule.number)
case .minLength:
guard let min: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.minLength(min))
case .maxLength:
guard let max: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.maxLength(max))
case .exactLength:
guard let exact: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.exactLength(exact))
case .numericMin:
guard let min: Double = value1 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericMin(min))
case .numericMax:
guard let max: Double = value1 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericMax(max))
case .numericBetween:
guard let min: Double = value1 as? Double, let max: Double = value2 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericBetween(min: min, max: max))
}
return self
}
@objc(runWithValue:)
public func run(with value: String?) -> Bool {
guard let validatable: AnyValidatable = self.shared as? AnyValidatable else {
return false
}
switch validatable.run(with: value) {
case .success:
return true
case .failure(_):
return false
}
}
}
| acb5b44805a77f5f76fcc276abf4d994 | 26.974138 | 97 | 0.557781 | false | false | false | false |
artursDerkintis/Starfly | refs/heads/master | Starfly/HistoryHit.swift | mit | 1 | //
// HistoryHit.swift
// Starfly
//
// Created by Arturs Derkintis on 3/16/16.
// Copyright © 2016 Starfly. All rights reserved.
//
import Foundation
import CoreData
@objc(HistoryHit)
class HistoryHit: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
var primitiveSectionIdentifier: String?
var primitiveSectionId : String?
var sectionId: String{
get {
return self.time!
}
set {
self.willChangeValueForKey("sectionID")
self.time = newValue
self.didChangeValueForKey("sectionID")
self.primitiveSectionIdentifier = nil
}
}
func setTimeAndDate(){
self.time = DateFormatter.sharedInstance.readableDate(NSDate())
self.arrangeIndex = CFAbsoluteTimeGetCurrent()
}
func getURL() -> NSURL{
if let url = self.urlOfIt{
return NSURL(string: url)!
}
return NSURL(string: "http://about:blank")!
}
lazy var icon : UIImage? = {
if let fav = self.faviconPath{
let iconFileName = (fav as NSString).lastPathComponent
let folder : NSString = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
let iconPath = folder.stringByAppendingPathComponent(iconFileName as String)
if let icon = UIImage(contentsOfFile: iconPath) {
return icon
}
}
return nil
}()
func removeIcon(){
if let fav = self.faviconPath{
let stsAr : NSString? = (fav as NSString).lastPathComponent
let folder : NSString = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
let path = folder.stringByAppendingPathComponent(stsAr! as String)
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func saveFavicon(image : UIImage){
if let data = UIImagePNGRepresentation(image){
let name : String = String(format: "%@.png", randomString(10))
let folder : String = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
if NSFileManager.defaultManager().fileExistsAtPath(folder) == false{
do {
try NSFileManager.defaultManager().createDirectoryAtPath(folder, withIntermediateDirectories: false, attributes: nil)
} catch _ {}
}
let newFilePath = String(format: (folder as NSString).stringByAppendingPathComponent(name))
data.writeToFile(newFilePath, atomically: true)
self.faviconPath = newFilePath
}
}
}
| c97d0989a0b7013b13de39f8afa539aa | 32.517241 | 137 | 0.608025 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/WordPressTest/MediaRequestAuthenticatorTests.swift | gpl-2.0 | 1 | import XCTest
import OHHTTPStubs
@testable import WordPress
class MediaRequestAuthenticatorTests: CoreDataTestCase {
override func setUp() {
super.setUp()
contextManager.useAsSharedInstance(untilTestFinished: self)
}
// MARK: - Utility
func setupAccount(username: String, authToken: String) {
let account = ModelTestHelper.insertAccount(context: mainContext)
account.uuid = UUID().uuidString
account.userID = NSNumber(value: 156)
account.username = username
account.authToken = authToken
contextManager.saveContextAndWait(mainContext)
AccountService(managedObjectContext: mainContext).setDefaultWordPressComAccount(account)
}
fileprivate func stubResponse(forEndpoint endpoint: String, responseFilename filename: String) {
stub(condition: { request in
return (request.url!.absoluteString as NSString).contains(endpoint) && request.httpMethod! == "GET"
}) { _ in
let stubPath = OHPathForFile(filename, type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}
}
// MARK: - Tests
func testPublicSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
func testPublicWPComSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
/// This test only checks that the resulting URL is the origina URL for now. There's no special authentication
/// logic within `MediaRequestAuthenticator` for this case.
///
/// - TODO: consider bringing self-hosted private authentication logic into MediaRequestAuthenticator.
///
func testPrivateSelfHostedSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
func testPrivateWPComSiteAuthentication() {
let authToken = "letMeIn!"
let url = URL(string: "http://www.wordpress.com")!
let expectedURL = URL(string: "https://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .privateWPComSite(authToken: authToken),
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: {
$0.key == "Authorization" && $0.value == "Bearer \(authToken)"
}) ?? false
XCTAssertTrue(hasAuthorizationHeader)
XCTAssertEqual(request.url, expectedURL)
}) { error in
XCTFail("This should not be called")
}
}
func testPrivateAtomicWPComSiteAuthentication() {
let username = "demouser"
let authToken = "letMeIn!"
let siteID = 15567
let url = URL(string: "http://www.wordpress.com")!
let expectedURL = URL(string: "https://www.wordpress.com")!
let expectation = self.expectation(description: "Completion closure called")
setupAccount(username: username, authToken: authToken)
let endpoint = "sites/\(siteID)/atomic-auth-proxy/read-access-cookies"
stubResponse(forEndpoint: endpoint, responseFilename: "atomic-get-authentication-cookie-success.json")
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .privateAtomicWPComSite(siteID: siteID, username: username, authToken: authToken),
onComplete: { request in
expectation.fulfill()
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: {
$0.key == "Authorization" && $0.value == "Bearer \(authToken)"
}) ?? false
XCTAssertTrue(hasAuthorizationHeader)
XCTAssertEqual(request.url, expectedURL)
}) { error in
XCTFail("This should not be called")
}
waitForExpectations(timeout: 0.5)
}
}
| 5988b75e17e7d89835623458e61c9765 | 37.296552 | 129 | 0.625968 | false | true | 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.