repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wikimedia/apps-ios-wikipedia | Wikipedia/Code/WMFTableOfContentsAnimator.swift | 1 | 14677 |
import UIKit
import CocoaLumberjackSwift
// MARK: - Delegate
@objc public protocol WMFTableOfContentsAnimatorDelegate {
func tableOfContentsAnimatorDidTapBackground(_ controller: WMFTableOfContentsAnimator)
}
open class WMFTableOfContentsAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning, UIGestureRecognizerDelegate, WMFTableOfContentsPresentationControllerTapDelegate, Themeable {
fileprivate var theme = Theme.standard
public func apply(theme: Theme) {
self.theme = theme
self.presentationController?.apply(theme: theme)
}
var displaySide = WMFTableOfContentsDisplaySide.left
var displayMode = WMFTableOfContentsDisplayMode.modal
// MARK: - init
public required init(presentingViewController: UIViewController, presentedViewController: UIViewController) {
self.presentingViewController = presentingViewController
self.presentedViewController = presentedViewController
self.isPresenting = true
self.isInteractive = false
presentationGesture = UIPanGestureRecognizer()
super.init()
presentationGesture.addTarget(self, action: #selector(WMFTableOfContentsAnimator.handlePresentationGesture(_:)))
presentationGesture.maximumNumberOfTouches = 1
presentationGesture.delegate = self
self.presentingViewController!.view.addGestureRecognizer(presentationGesture)
}
deinit {
removeDismissalGestureRecognizer()
presentationGesture.removeTarget(self, action: #selector(WMFTableOfContentsAnimator.handlePresentationGesture(_:)))
presentationGesture.view?.removeGestureRecognizer(presentationGesture)
}
weak var presentingViewController: UIViewController?
weak var presentedViewController: UIViewController?
open var gesturePercentage: CGFloat = 0.4
weak open var delegate: WMFTableOfContentsAnimatorDelegate?
fileprivate(set) open var isPresenting: Bool
fileprivate(set) open var isInteractive: Bool
// MARK: - WMFTableOfContentsPresentationControllerTapDelegate
open func tableOfContentsPresentationControllerDidTapBackground(_ controller: WMFTableOfContentsPresentationController) {
delegate?.tableOfContentsAnimatorDidTapBackground(self)
}
// MARK: - UIViewControllerTransitioningDelegate
weak var presentationController: WMFTableOfContentsPresentationController?
open func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
guard presented == self.presentedViewController else {
return nil
}
let presentationController = WMFTableOfContentsPresentationController(presentedViewController: presented, presentingViewController: self.presentingViewController, tapDelegate: self)
presentationController.apply(theme: theme)
presentationController.displayMode = displayMode
presentationController.displaySide = displaySide
self.presentationController = presentationController
return presentationController
}
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard presented == self.presentedViewController else {
return nil
}
self.isPresenting = true
return self
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard dismissed == self.presentedViewController else {
return nil
}
self.isPresenting = false
return self
}
open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.isInteractive {
return self
}else{
return nil
}
}
open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.isInteractive {
return self
}else{
return nil
}
}
// MARK: - UIViewControllerAnimatedTransitioning
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.isPresenting ? 0.5 : 0.8
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresenting {
removeDismissalGestureRecognizer()
addDismissalGestureRecognizer(transitionContext.containerView)
animatePresentationWithTransitionContext(transitionContext)
}
else {
animateDismissalWithTransitionContext(transitionContext)
}
}
var tocMultiplier:CGFloat {
switch displaySide {
case .left:
return -1.0
case .right:
return 1.0
case .center:
fallthrough
default:
return UIApplication.shared.wmf_isRTL ? -1.0 : 1.0
}
}
// MARK: - Animation
func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let presentedController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
let containerView = transitionContext.containerView
// Position the presented view off the top of the container view
var f = transitionContext.finalFrame(for: presentedController)
f.origin.x += f.size.width * tocMultiplier
presentedControllerView.frame = f
containerView.addSubview(presentedControllerView)
animateTransition(self.isInteractive, duration: self.transitionDuration(using: transitionContext), animations: { () -> Void in
var f = presentedControllerView.frame
f.origin.x -= f.size.width * self.tocMultiplier
presentedControllerView.frame = f
}, completion: {(completed: Bool) -> Void in
let cancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!cancelled)
})
}
func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
animateTransition(self.isInteractive, duration: self.transitionDuration(using: transitionContext), animations: { () -> Void in
var f = presentedControllerView.frame
switch self.displaySide {
case .left:
f.origin.x = -1*f.size.width
break
case .right:
fallthrough
case .center:
fallthrough
default:
f.origin.x = transitionContext.containerView.bounds.size.width
}
presentedControllerView.frame = f
}, completion: {(completed: Bool) -> Void in
let cancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!cancelled)
})
}
func animateTransition(_ interactive: Bool, duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?){
if(interactive){
UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(), animations: { () -> Void in
animations()
}, completion: { (completed: Bool) -> Void in
completion?(completed)
})
}else{
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
animations()
}, completion: {(completed: Bool) -> Void in
completion?(completed)
})
}
}
// MARK: - Gestures
private let presentationGesture: UIPanGestureRecognizer
var dismissalGesture: UIPanGestureRecognizer?
func addDismissalGestureRecognizer(_ containerView: UIView) {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(WMFTableOfContentsAnimator.handleDismissalGesture(_:)))
gesture.delegate = self
containerView.addGestureRecognizer(gesture)
dismissalGesture = gesture
}
func removeDismissalGestureRecognizer() {
if let dismissalGesture = dismissalGesture {
dismissalGesture.view?.removeGestureRecognizer(dismissalGesture)
dismissalGesture.removeTarget(self, action: #selector(WMFTableOfContentsAnimator.handleDismissalGesture(_:)))
}
dismissalGesture = nil
}
@objc func handlePresentationGesture(_ gesture: UIScreenEdgePanGestureRecognizer) {
switch(gesture.state) {
case (.began):
self.isInteractive = true
self.presentingViewController?.present(self.presentedViewController!, animated: true, completion: nil)
case (.changed):
let translation = gesture.translation(in: gesture.view)
let transitionProgress = max(min(translation.x * -tocMultiplier / self.presentedViewController!.view.bounds.maxX, 0.99), 0.01)
self.update(transitionProgress)
case (.ended):
self.isInteractive = false
let velocityRequiredToPresent = -gesture.view!.bounds.width * tocMultiplier
let velocityRequiredToDismiss = -velocityRequiredToPresent
let velocityX = gesture.velocity(in: gesture.view).x
if velocityX*velocityRequiredToDismiss > 1 && abs(velocityX) > abs(velocityRequiredToDismiss){
cancel()
return
}
if velocityX*velocityRequiredToPresent > 1 && abs(velocityX) > abs(velocityRequiredToPresent){
finish()
return
}
let progressRequiredToPresent = 0.33
if(self.percentComplete >= CGFloat(progressRequiredToPresent)){
finish()
return
}
cancel()
case (.cancelled):
self.isInteractive = false
cancel()
default :
break
}
}
@objc func handleDismissalGesture(_ gesture: UIScreenEdgePanGestureRecognizer) {
switch(gesture.state) {
case .began:
self.isInteractive = true
self.presentingViewController?.dismiss(animated: true, completion: nil)
case .changed:
let translation = gesture.translation(in: gesture.view)
let transitionProgress = max(min(translation.x * tocMultiplier / self.presentedViewController!.view.bounds.maxX, 0.99), 0.01)
self.update(transitionProgress)
DDLogVerbose("TOC transition progress: \(transitionProgress)")
case .ended:
self.isInteractive = false
let velocityRequiredToPresent = -gesture.view!.bounds.width * tocMultiplier
let velocityRequiredToDismiss = -velocityRequiredToPresent
let velocityX = gesture.velocity(in: gesture.view).x
if velocityX*velocityRequiredToDismiss > 1 && abs(velocityX) > abs(velocityRequiredToDismiss){
finish()
return
}
if velocityX*velocityRequiredToPresent > 1 && abs(velocityX) > abs(velocityRequiredToPresent){
cancel()
return
}
let progressRequiredToDismiss = 0.50
if(self.percentComplete >= CGFloat(progressRequiredToDismiss)){
finish()
return
}
cancel()
case .cancelled:
self.isInteractive = false
cancel()
default :
break
}
}
// MARK: - UIGestureRecognizerDelegate
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard displayMode == .modal else {
return false
}
let isRTL = UIApplication.shared.wmf_isRTL
guard (displaySide == .center) || (isRTL && displaySide == .left) || (!isRTL && displaySide == .right) else {
return false
}
if gestureRecognizer == self.dismissalGesture {
if let translation = self.dismissalGesture?.translation(in: dismissalGesture?.view) {
if (translation.x * tocMultiplier > 0){
return true
} else {
return false
}
} else {
return false
}
} else if gestureRecognizer == self.presentationGesture {
let translation = presentationGesture.translation(in: presentationGesture.view)
let location = presentationGesture.location(in: presentationGesture.view)
let gestureWidth = presentationGesture.view!.frame.width * gesturePercentage
let maxLocation: CGFloat
let isInStartBoundary: Bool
switch displaySide {
case .left:
maxLocation = gestureWidth
isInStartBoundary = maxLocation - location.x > 0
default:
maxLocation = presentationGesture.view!.frame.maxX - gestureWidth
isInStartBoundary = location.x - maxLocation > 0
}
if (translation.x * tocMultiplier < 0) && isInStartBoundary {
return true
} else {
return false
}
} else {
return true
}
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return otherGestureRecognizer.isKind(of: UIScreenEdgePanGestureRecognizer.self)
}
}
| mit | bb816cbfdbeeb199c51b3c7a8db5ff65 | 39.432507 | 248 | 0.642229 | 6.644183 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-outmodule-frozen-othermodule.swift | 3 | 1617 | // 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 -enable-library-evolution
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule -enable-library-evolution
// 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()
| apache-2.0 | 1e7b5c60cf606567583c1845046d621d | 51.16129 | 301 | 0.724181 | 3.340909 | false | false | false | false |
rlopezdiez/RLDNavigationSwift | Classes/RLDNavigationSetup.swift | 1 | 2749 | //
// RLDNavigationSwift
//
// Copyright (c) 2015 Rafael Lopez Diez. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
public struct RLDNavigationSetup {
public var origin:String
public var destination:String
public var properties:[String:AnyObject]?
public var breadcrumbs:[String]?
public var navigationController:UINavigationController
public init(destination:String,
navigationController:UINavigationController) {
self.init(destination:destination,
properties:nil,
breadcrumbs:nil,
navigationController:navigationController)
}
public init(destination:String,
breadcrumbs:[String]?,
navigationController:UINavigationController) {
self.init(destination:destination,
properties:nil,
breadcrumbs:breadcrumbs,
navigationController:navigationController)
}
public init(destination:String,
properties:[String:AnyObject]?,
navigationController:UINavigationController) {
self.init(destination:destination,
properties:properties,
breadcrumbs:nil,
navigationController:navigationController)
}
public init(destination:String,
properties:[String:AnyObject]?,
breadcrumbs:[String]?,
navigationController:UINavigationController) {
let origin = NSStringFromClass(navigationController.topViewController!.dynamicType)
self.init(origin:origin,
destination:destination,
properties:properties,
breadcrumbs:breadcrumbs,
navigationController:navigationController)
}
public init(origin:String,
destination:String,
properties:[String:AnyObject]?,
breadcrumbs:[String]?,
navigationController:UINavigationController) {
self.origin = origin
self.destination = destination
self.properties = properties
self.breadcrumbs = breadcrumbs
self.navigationController = navigationController
}
} | apache-2.0 | d7cc6eae00ac149779d1c9517c5faf4b | 33.375 | 95 | 0.661331 | 5.679752 | false | false | false | false |
tubikstudio/PizzaAnimation | PizzaAnimation/Functionality/Models/TSFoodCategory.swift | 1 | 772 | //
// TSDishItem.swift
// PizzaAnimation
//
// Created by Tubik Studio on 8/4/16.
// Copyright © 2016 Tubik Studio. All rights reserved.
//
import UIKit
class TSFoodCategory {
var title: String
var staticImageName: String
var dynamicImageName: String
var color: UIColor
var foodItems = [FoodItem]()
init(title: String, staticImageName: String, dynamicImageName: String? = nil, color: UIColor) {
self.title = title
self.staticImageName = staticImageName
self.color = color
self.dynamicImageName = dynamicImageName == nil ? staticImageName + "_dynamic" : dynamicImageName!
}
}
class FoodItem {
var title: String
init(title: String) {
self.title = title
}
} | mit | 6a42ae2f26810f57521ef475f8f92777 | 20.444444 | 106 | 0.638132 | 4.015625 | false | false | false | false |
yannickl/DynamicButton | Sources/DynamicButton.swift | 1 | 9132 | /*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.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
/**
Flat design button compounded by several lines to create several symbols like
*arrows*, *checkmark*, *hamburger button*, etc. with animated transitions
between each style changes.
*/
@IBDesignable final public class DynamicButton: UIButton {
let line1Layer = CAShapeLayer()
let line2Layer = CAShapeLayer()
let line3Layer = CAShapeLayer()
let line4Layer = CAShapeLayer()
private var _style: Style = .hamburger
lazy var allLayers: [CAShapeLayer] = {
return [self.line1Layer, self.line2Layer, self.line3Layer, self.line4Layer]
}()
/**
Boolean indicates whether the button can bounce when is touched.
By default the value is set to true.
*/
public var bounceButtonOnTouch: Bool = true
/**
Initializes and returns a dynamic button with the specified style.
You have to think to define its frame because the default one is set to {0, 0, 50, 50}.
- parameter style: The style of the button.
- returns: An initialized view object or nil if the object couldn't be created.
*/
required public init(style: Style) {
super.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
_style = style
setup()
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle and with the Hamburger style by default.
- parameter frame: The frame rectangle for the view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This method uses the frame rectangle to set the center and bounds properties accordingly.
- returns: An initialized view object or nil if the object couldn't be created.
*/
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override func layoutSubviews() {
super.layoutSubviews()
let width = bounds.width - (contentEdgeInsets.left + contentEdgeInsets.right)
let height = bounds.height - (contentEdgeInsets.top + contentEdgeInsets.bottom)
intrinsicSize = min(width, height)
intrinsicOffset = CGPoint(x: contentEdgeInsets.left + (width - intrinsicSize) / 2, y: contentEdgeInsets.top + (height - intrinsicSize) / 2)
setStyle(_style, animated: false)
}
public override func setTitle(_ title: String?, for state: UIControl.State) {
super.setTitle("", for: state)
}
// MARK: - Managing the Button Setup
/// Intrinsic square size
var intrinsicSize = CGFloat(0)
/// Intrinsic square offset
var intrinsicOffset = CGPoint.zero
func setup() {
setTitle("", for: .normal)
clipsToBounds = true
addTarget(self, action: #selector(highlightAction), for: .touchDown)
addTarget(self, action: #selector(highlightAction), for: .touchDragEnter)
addTarget(self, action: #selector(unhighlightAction), for: .touchDragExit)
addTarget(self, action: #selector(unhighlightAction), for: .touchUpInside)
addTarget(self, action: #selector(unhighlightAction), for: .touchCancel)
for sublayer in allLayers {
layer.addSublayer(sublayer)
}
setupLayerPaths()
}
func setupLayerPaths() {
for sublayer in allLayers {
sublayer.fillColor = UIColor.clear.cgColor
sublayer.anchorPoint = CGPoint(x: 0, y: 0)
sublayer.lineJoin = CAShapeLayerLineJoin.round
sublayer.lineCap = CAShapeLayerLineCap.round
sublayer.contentsScale = layer.contentsScale
sublayer.path = UIBezierPath().cgPath
sublayer.lineWidth = lineWidth
sublayer.strokeColor = strokeColor.cgColor
}
setStyle(_style, animated: false)
}
// MARK: - Configuring Buttons
/// The button style. The setter is equivalent to the setStyle(, animated:) method with animated value to false. Defaults to Hamburger.
public var style: Style {
get { return _style }
set (newValue) { setStyle(newValue, animated: false) }
}
/**
Set the style of the button and animate the change if needed.
- parameter style: The style of the button.
- parameter animated: If true the transition between the old style and the new one is animated.
*/
public func setStyle(_ style: Style, animated: Bool) {
_style = style
let center = CGPoint(x: intrinsicOffset.x + intrinsicSize / 2, y: intrinsicOffset.y + intrinsicSize / 2)
let buildable = style.build(center: center, size: intrinsicSize, offset: intrinsicOffset, lineWidth: lineWidth)
applyButtonBuildable(buildable, animated: animated)
}
func applyButtonBuildable(_ buildable: DynamicButtonBuildableStyle, animated: Bool) {
accessibilityValue = buildable.description
for config in buildable.animationConfigurations(line1Layer, layer2: line2Layer, layer3: line3Layer, layer4: line4Layer) {
if animated {
let anim = animationWithKeyPath(config.keyPath, damping: 10)
anim.fromValue = config.layer.path
anim.toValue = config.newValue
config.layer.add(anim, forKey: config.key)
}
else {
config.layer.removeAllAnimations()
}
config.layer.path = config.newValue
}
}
/// Specifies the line width used when stroking the button paths. Defaults to two.
@IBInspectable public var lineWidth: CGFloat = 2 {
didSet { setupLayerPaths() }
}
/// Specifies the color to fill the path's stroked outlines, or nil for no stroking. Defaults to black.
@IBInspectable public var strokeColor: UIColor = .black {
didSet { setupLayerPaths() }
}
/// Specifies the color to fill the path's stroked outlines when the button is highlighted, or nil to use the strokeColor. Defaults to nil.
@IBInspectable public var highlightStokeColor: UIColor? = nil
/// Specifies the color to fill the background when the button is highlighted, or nil to use the backgroundColor. Defaults to nil.
@IBInspectable public var highlightBackgroundColor: UIColor? = nil
// MARK: - Animating Buttons
func animationWithKeyPath(_ keyPath: String, damping: CGFloat = 10, initialVelocity: CGFloat = 0, stiffness: CGFloat = 100) -> CABasicAnimation {
guard #available(iOS 9, *) else {
let basic = CABasicAnimation(keyPath: keyPath)
basic.duration = 0.16
basic.fillMode = CAMediaTimingFillMode.forwards
basic.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
return basic
}
let spring = CASpringAnimation(keyPath: keyPath)
spring.duration = spring.settlingDuration
spring.damping = damping
spring.initialVelocity = initialVelocity
spring.stiffness = stiffness
spring.fillMode = CAMediaTimingFillMode.forwards
spring.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
return spring
}
// MARK: - Action Methods
// Store the background color color variable
var defaultBackgroundColor: UIColor = .clear
@objc func highlightAction() {
defaultBackgroundColor = backgroundColor ?? .clear
backgroundColor = highlightBackgroundColor ?? defaultBackgroundColor
for sublayer in allLayers {
sublayer.strokeColor = (highlightStokeColor ?? strokeColor).cgColor
}
if bounceButtonOnTouch {
let anim = animationWithKeyPath("transform.scale", damping: 20, stiffness: 1000)
anim.isRemovedOnCompletion = false
anim.toValue = 1.2
layer.add(anim, forKey: "scaleup")
}
}
@objc func unhighlightAction() {
backgroundColor = defaultBackgroundColor
for sublayer in allLayers {
sublayer.strokeColor = strokeColor.cgColor
}
let anim = animationWithKeyPath("transform.scale", damping: 100, initialVelocity: 20)
anim.isRemovedOnCompletion = false
anim.toValue = 1
layer.add(anim, forKey: "scaledown")
}
}
| mit | eab3cc606584be9b0c0839396e5afa4d | 34.258687 | 246 | 0.70565 | 4.663943 | false | false | false | false |
audiokit/AudioKit | Sources/AudioKit/Nodes/Playback/PhaseLockedVocoder.swift | 1 | 8705 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// This is a phase locked vocoder. It has the ability to play back an audio
/// file loaded into an ftable like a sampler would. Unlike a typical sampler,
/// mincer allows time and pitch to be controlled separately.
///
public class PhaseLockedVocoder: Node, AudioUnitContainer, Toggleable {
/// Unique four-letter identifier "minc"
public static let ComponentDescription = AudioComponentDescription(generator: "minc")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Parameters
/// Specification for position
public static let positionDef = NodeParameterDef(
identifier: "position",
name: "Position in time. When non-changing it will do a spectral freeze of a the current point in time.",
address: akGetParameterAddress("PhaseLockedVocoderParameterPosition"),
range: 0 ... 1,
unit: .generic,
flags: .default)
/// Position in time. When non-changing it will do a spectral freeze of a the current point in time.
@Parameter public var position: AUValue
/// Specification for amplitude
public static let amplitudeDef = NodeParameterDef(
identifier: "amplitude",
name: "Amplitude.",
address: akGetParameterAddress("PhaseLockedVocoderParameterAmplitude"),
range: 0 ... 1,
unit: .generic,
flags: .default)
/// Amplitude.
@Parameter public var amplitude: AUValue
/// Specification for pitch ratio
public static let pitchRatioDef = NodeParameterDef(
identifier: "pitchRatio",
name: "Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.",
address: akGetParameterAddress("PhaseLockedVocoderParameterPitchRatio"),
range: 0 ... 1_000,
unit: .hertz,
flags: .default)
/// Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
@Parameter public var pitchRatio: AUValue
// MARK: - Audio Unit
/// Internal audio unit for phase locked vocoder
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[PhaseLockedVocoder.positionDef,
PhaseLockedVocoder.amplitudeDef,
PhaseLockedVocoder.pitchRatioDef]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("PhaseLockedVocoderDSP")
}
}
// MARK: - Initialization
/// Initialize this vocoder node
///
/// - Parameters:
/// - file: AVAudioFile to load into memory
/// - position: Position in time. When non-changing it will do a spectral freeze of a the current point in time.
/// - amplitude: Amplitude.
/// - pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
///
public init(
file: AVAudioFile,
position: AUValue = 0,
amplitude: AUValue = 1,
pitchRatio: AUValue = 1
) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
guard let audioUnit = avAudioUnit.auAudioUnit as? AudioUnitType else {
fatalError("Couldn't create audio unit")
}
self.internalAU = audioUnit
self.loadFile(file)
self.position = position
self.amplitude = amplitude
self.pitchRatio = pitchRatio
}
}
internal func loadFile(_ avAudioFile: AVAudioFile) {
Exit: do {
var err: OSStatus = noErr
var theFileLengthInFrames: Int64 = 0
var theFileFormat = AudioStreamBasicDescription()
var thePropertySize: UInt32 = UInt32(MemoryLayout.stride(ofValue: theFileFormat))
var extRef: ExtAudioFileRef?
var theData: UnsafeMutablePointer<CChar>?
var theOutputFormat = AudioStreamBasicDescription()
err = ExtAudioFileOpenURL(avAudioFile.url as CFURL, &extRef)
if err != 0 { Log("ExtAudioFileOpenURL FAILED, Error = \(err)"); break Exit }
// Get the audio data format
guard let externalAudioFileRef = extRef else {
break Exit
}
err = ExtAudioFileGetProperty(externalAudioFileRef,
kExtAudioFileProperty_FileDataFormat,
&thePropertySize,
&theFileFormat)
if err != 0 {
Log("ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = \(err)")
break Exit
}
if theFileFormat.mChannelsPerFrame > 2 {
Log("Unsupported Format, channel count is greater than stereo")
break Exit
}
theOutputFormat.mSampleRate = Settings.sampleRate
theOutputFormat.mFormatID = kAudioFormatLinearPCM
theOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat
theOutputFormat.mBitsPerChannel = UInt32(MemoryLayout<Float>.stride) * 8
theOutputFormat.mChannelsPerFrame = 1 // Mono
theOutputFormat.mBytesPerFrame = theOutputFormat.mChannelsPerFrame * UInt32(MemoryLayout<Float>.stride)
theOutputFormat.mFramesPerPacket = 1
theOutputFormat.mBytesPerPacket = theOutputFormat.mFramesPerPacket * theOutputFormat.mBytesPerFrame
// Set the desired client (output) data format
err = ExtAudioFileSetProperty(externalAudioFileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout.stride(ofValue: theOutputFormat)),
&theOutputFormat)
if err != 0 {
Log("ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = \(err)")
break Exit
}
// Get the total frame count
thePropertySize = UInt32(MemoryLayout.stride(ofValue: theFileLengthInFrames))
err = ExtAudioFileGetProperty(externalAudioFileRef,
kExtAudioFileProperty_FileLengthFrames,
&thePropertySize,
&theFileLengthInFrames)
if err != 0 {
Log("ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = \(err)")
break Exit
}
// Read all the data into memory
let dataSize = UInt32(theFileLengthInFrames) * theOutputFormat.mBytesPerFrame
theData = UnsafeMutablePointer.allocate(capacity: Int(dataSize))
if theData != nil {
var bufferList: AudioBufferList = AudioBufferList()
bufferList.mNumberBuffers = 1
bufferList.mBuffers.mDataByteSize = dataSize
bufferList.mBuffers.mNumberChannels = theOutputFormat.mChannelsPerFrame
bufferList.mBuffers.mData = UnsafeMutableRawPointer(theData)
// Read the data into an AudioBufferList
var ioNumberFrames: UInt32 = UInt32(theFileLengthInFrames)
err = ExtAudioFileRead(externalAudioFileRef, &ioNumberFrames, &bufferList)
if err == noErr {
// success
let data = UnsafeMutablePointer<Float>(
bufferList.mBuffers.mData?.assumingMemoryBound(to: Float.self)
)
internalAU?.setWavetable(data: data, size: Int(ioNumberFrames))
} else {
// failure
theData?.deallocate()
theData = nil // make sure to return NULL
Log("Error = \(err)"); break Exit
}
}
}
}
/// Start the node
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | 89f93a21414030fce5ba61906dc851c7 | 40.452381 | 118 | 0.602298 | 5.897696 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Extensions/API/APIExtensions.swift | 1 | 823 | //
// APIExtensions.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 11/27/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import RealmSwift
extension API {
static func current(realm: Realm? = Realm.current) -> API? {
guard
let auth = AuthManager.isAuthenticated(realm: realm),
let host = auth.apiHost?.httpServerURL() ?? auth.apiHost
else {
return nil
}
let api = API(host: host, version: Version(auth.serverVersion) ?? .zero)
api.userId = auth.userId
api.authToken = auth.token
api.language = AppManager.language
return api
}
static func server(index: Int) -> API? {
let realm = DatabaseManager.databaseInstace(index: index)
return current(realm: realm)
}
}
| mit | 24c0824edbeb8e65c72def5aa040a546 | 24.6875 | 80 | 0.608273 | 4.089552 | false | false | false | false |
auth0/Lock.iOS-OSX | Lock/ClassicRouter.swift | 1 | 10317 | // ClassicRouter.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 Foundation
import Auth0
struct ClassicRouter: Router {
weak var controller: LockViewController?
let user = User()
let lock: Lock
var observerStore: ObserverStore { return self.lock.observerStore }
init(lock: Lock, controller: LockViewController) {
self.controller = controller
self.lock = lock
}
var root: Presentable? {
let connections = self.lock.connections
guard !connections.isEmpty else {
self.lock.logger.debug("No connections configured. Loading application info from Auth0...")
let baseURL = self.lock.options.configurationBaseURL ?? self.lock.authentication.url
let interactor = CDNLoaderInteractor(baseURL: baseURL, clientId: self.lock.authentication.clientId)
return ConnectionLoadingPresenter(loader: interactor, navigator: self, dispatcher: lock.observerStore, options: self.lock.options)
}
let whitelistForActiveAuth = self.lock.options.enterpriseConnectionUsingActiveAuth
switch (connections.database, connections.oauth2, connections.enterprise) {
// Database root
case (.some(let database), let oauth2, let enterprise):
guard self.lock.options.allow != [.ResetPassword] && self.lock.options.initialScreen != .resetPassword else { return forgotPassword }
let authentication = self.lock.authentication
let webAuthInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
let interactor = DatabaseInteractor(connection: database, authentication: authentication, webAuthentication: webAuthInteractor, user: self.user, options: self.lock.options, dispatcher: lock.observerStore)
let presenter = DatabasePresenter(interactor: interactor, connection: database, navigator: self, options: self.lock.options)
if !oauth2.isEmpty {
let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
presenter.authPresenter = AuthPresenter(connections: oauth2, interactor: interactor, customStyle: self.lock.style.oauth2)
}
if !enterprise.isEmpty {
let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
let interactor = EnterpriseDomainInteractor(connections: connections, user: self.user, authentication: authInteractor)
presenter.enterpriseInteractor = interactor
}
return presenter
// Single Enterprise with active auth support (e.g. AD)
case (nil, let oauth2, let enterprise) where oauth2.isEmpty && enterprise.hasJustOne(andIn: whitelistForActiveAuth):
guard let connection = enterprise.first else { return nil }
return enterpriseActiveAuth(connection: connection, domain: connection.domains.first)
// Single Enterprise with support for passive auth only (web auth) and some social connections
case (nil, let oauth2, let enterprise) where enterprise.hasJustOne(andNotIn: whitelistForActiveAuth):
guard let connection = enterprise.first else { return nil }
let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
let connections: [OAuth2Connection] = oauth2 + [connection]
return AuthPresenter(connections: connections, interactor: authInteractor, customStyle: self.lock.style.oauth2)
// Social connections only
case (nil, let oauth2, let enterprise) where enterprise.isEmpty:
let interactor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
let presenter = AuthPresenter(connections: oauth2, interactor: interactor, customStyle: self.lock.style.oauth2)
return presenter
// Multiple enterprise connections and maybe some social
case (nil, let oauth2, let enterprise) where !enterprise.isEmpty:
let authInteractor = Auth0OAuth2Interactor(authentication: self.lock.authentication, dispatcher: lock.observerStore, options: self.lock.options, nativeHandlers: self.lock.nativeHandlers)
let interactor = EnterpriseDomainInteractor(connections: connections, user: self.user, authentication: authInteractor)
let presenter = EnterpriseDomainPresenter(interactor: interactor, navigator: self, options: self.lock.options)
if !oauth2.isEmpty {
presenter.authPresenter = AuthPresenter(connections: connections.oauth2, interactor: authInteractor, customStyle: self.lock.style.oauth2)
}
return presenter
// Not supported connections configuration
default:
return nil
}
}
var forgotPassword: Presentable? {
let connections = self.lock.connections
guard !connections.isEmpty else {
exit(withError: UnrecoverableError.clientWithNoConnections)
return nil
}
let interactor = DatabasePasswordInteractor(connections: connections, authentication: self.lock.authentication, user: self.user, dispatcher: lock.observerStore)
let presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: self, options: self.lock.options)
presenter.customLogger = self.lock.logger
return presenter
}
func multifactor(withToken mfaToken: String? = nil) -> Presentable? {
let connections = self.lock.connections
guard let database = connections.database else {
exit(withError: UnrecoverableError.missingDatabaseConnection)
return nil
}
let authentication = self.lock.authentication
let interactor = MultifactorInteractor(user: self.user, authentication: authentication, connection: database, options: self.lock.options, dispatcher: lock.observerStore, mfaToken: mfaToken)
let presenter = MultifactorPresenter(interactor: interactor, connection: database, navigator: self)
presenter.customLogger = self.lock.logger
return presenter
}
func enterpriseActiveAuth(connection: EnterpriseConnection, domain: String?) -> Presentable? {
let authentication = self.lock.authentication
let interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: self.user, options: self.lock.options, dispatcher: lock.observerStore)
let presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: self.lock.options, domain: domain)
presenter.customLogger = self.lock.logger
return presenter
}
func onBack() {
guard let current = self.controller?.routes.back() else { return }
self.user.reset()
let style = self.lock.style
self.lock.logger.debug("Back pressed. Showing \(current)")
switch current {
case .forgotPassword:
self.controller?.present(self.forgotPassword, title: current.title(withStyle: style))
case .root:
self.controller?.present(self.root, title: style.hideTitle ? nil : style.title)
default:
break
}
}
func navigate(_ route: Route) {
let presentable: Presentable?
switch route {
case .root where self.controller?.routes.current != .root:
presentable = self.root
case .forgotPassword:
presentable = self.forgotPassword
case .multifactor:
presentable = self.multifactor()
case .multifactorWithToken(let token):
presentable = self.multifactor(withToken: token)
case .enterpriseActiveAuth(let connection, let domain):
presentable = self.enterpriseActiveAuth(connection: connection, domain: domain)
case .unrecoverableError(let error):
presentable = self.unrecoverableError(for: error)
default:
self.lock.logger.warn("Ignoring navigation \(route)")
return
}
self.lock.logger.debug("Navigating to \(route)")
self.controller?.routes.go(route)
self.controller?.present(presentable, title: route.title(withStyle: self.lock.style))
}
}
private extension Array where Element: OAuth2Connection {
func hasJustOne(andIn list: [String]) -> Bool {
guard let connection = self.first, self.count == 1 else { return false }
return list.contains(connection.name)
}
func hasJustOne(andNotIn list: [String]) -> Bool {
guard let connection = self.first, self.count == 1 else { return false }
return !list.contains(connection.name)
}
}
| mit | 1299d093c2e269c10ebe446e9bb1bcd2 | 55.377049 | 216 | 0.706892 | 4.960096 | false | false | false | false |
avaidyam/Parrot | MochaUI/PreviewController.swift | 1 | 9174 | import AppKit
import Mocha
import Quartz
/* TODO: NSPopover.title/addTitlebar(animated: ...)? */
/* TODO: Use NSPressGestureRecognizer if no haptic support. */
/* TODO: Maybe support tear-off popover-windows? */
//let preview = PreviewController(for: self.view, with: .file(URL(fileURLWithPath: pathToFile), nil))
//preview.delegate = self // not required
/// Provides content for a `PreviewController` dynamically.
public protocol PreviewControllerDelegate: class {
/// Return the content for the previewing controller, depending on where
/// the user began the previewing within the `parentView`. If `nil` is
/// returned from this method, previewing is disabled.
func previewController(_: PreviewController, contentAtPoint: CGPoint) -> PreviewController.ContentType?
}
/// The `PreviewController` handles user interactions with previewing indications.
/// The functionality is similar to dictionary or Safari link force touch lookup.
public class PreviewController: NSObject, NSPopoverDelegate, NSGestureRecognizerDelegate {
/// Describes the content to be previewed by the controller for a given interaction.
public enum ContentType {
///
case view(NSViewController)
/// The content is a `file://` URL, optionally with a preview size.
/// If no size is specified (`nil`), `PreviewController.defaultSize` is used.
case file(URL, CGSize?)
}
/// If no size is provided for a `ContentType.file(_, _)`, this value is used.
public static var defaultSize = CGSize(width: 512, height: 512)
/// Create a `QLPreviewView`-containing `NSViewController` to support files.
private static func previewer(for item: QLPreviewItem, size: CGSize?) -> NSViewController {
let vc = NSViewController()
let rect = NSRect(origin: .zero, size: size ?? PreviewController.defaultSize)
let ql = QLPreviewView(frame: rect, style: .normal)!
ql.previewItem = item
vc.view = ql
return vc
}
/// If the `delegate` is not set, the `content` set will be used for previewing,
/// applicable to the whole `bounds` of the `parentView`.
///
/// If both `delegate` and `content` are `nil`, previewing is disabled.
public var content: ContentType? = nil
/// Provides content for previewing controller dynamically.
///
/// If both `delegate` and `content` are `nil`, previewing is disabled.
public weak var delegate: PreviewControllerDelegate? = nil
/// The view that should be registered for previewing; this is not the view
/// that is contained within the preview itself.
public weak var parentView: NSView? = nil {
willSet {
self.parentView?.removeGestureRecognizer(self.gesture)
}
didSet {
self.parentView?.addGestureRecognizer(self.gesture)
}
}
/// Whether the user is currently interacting the preview; that is, the user
/// is engaged in a force touch interaction to display the preview.
public private(set) var interacting: Bool = false
/// Whether the preview is visible; setting this property manually bypasses
/// the user interaction to display the preview regardless.
///
/// When setting `isVisible = true`, the `delegate` is not consulted. Use
/// `content` to specify the preview content.
///
/// Setting `isVisible` while the user is currently interacting is a no-op.
public var isVisible: Bool {
get { return self.popover.isShown }
set {
switch newValue {
case false:
guard self.popover.isShown, !self.interacting else { return }
self.popover.performClose(nil)
case true:
guard !self.popover.isShown, !self.interacting else { return }
guard let view = self.parentView else {
fatalError("PreviewController.parentView was not set, isVisible=true failed.")
}
guard let content = self.content else { return }
// Set the contentView here to maintain only a short-term reference.
switch content {
case .view(let vc):
self.popover.contentViewController = vc
case .file(let url, let size):
self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size)
}
self.popover.show(relativeTo: view.bounds, of: view, preferredEdge: .minY)
}
}
}
/// The popover used to contain and animate the preview content.
private lazy var popover: NSPopover = {
let popover = NSPopover()
popover.behavior = .semitransient
popover.delegate = self
//popover.positioningOptions = .keepTopStable
return popover
}()
/// The gesture recognizer used to handle user interaction for previewing.
private lazy var gesture: PressureGestureRecognizer = {
let gesture = PressureGestureRecognizer(target: self, action: #selector(self.gesture(_:)))
gesture.delegate = self
//gesture.behavior = .primaryAccelerator
return gesture
}()
/// Create a `PreviewController` with a provided `parentView` and `content`.
public init(for view: NSView? = nil, with content: ContentType? = nil) {
super.init()
self.commonInit(view, content) // rebound to call property observers
}
private func commonInit(_ view: NSView? = nil, _ content: ContentType? = nil) {
self.parentView = view
self.content = content
}
@objc dynamic private func gesture(_ sender: PressureGestureRecognizer) {
switch sender.state {
case .possible: break // ignore
case .began:
guard !self.popover.isShown, !self.interacting else { return }
// Begin interaction animation:
self.interacting = true
let point = sender.location(in: self.parentView)
self.popover._private._beginPredeepAnimationAgainstPoint(point, inView: self.parentView)
case .changed:
guard self.popover.isShown, self.interacting else { return }
// Update interaction animation, unless stage 2 (deep press):
guard sender.stage != 2 else { fallthrough }
self.popover._private._doPredeepAnimation(withProgress: Double(sender.stage == 2 ? 1.0 : sender.pressure))
case .ended:
guard self.popover.isShown, self.interacting else { return }
// Complete interaction animation, only if stage 2 (deep press):
guard sender.stage == 2 else { fallthrough }
self.interacting = false
self.popover._private._completeDeepAnimation()
case .failed, .cancelled:
guard self.popover.isShown, self.interacting else { return }
// Cancel interaction animation:
self.interacting = false
self.popover._private._cancelPredeepAnimation()
}
}
public func popoverDidClose(_ notification: Notification) {
self.interacting = false
// Clear the contentView here to maintain only a short-term reference.
self.popover.contentViewController = nil
}
public func gestureRecognizerShouldBegin(_ sender: NSGestureRecognizer) -> Bool {
/// If there exists a `delegate`, request its dynamic content.
/// Otherwise, possibly use the static `content` property.
func effectiveContent(_ point: CGPoint) -> ContentType? {
guard let delegate = self.delegate else {
return self.content
}
return delegate.previewController(self, contentAtPoint: point)
}
// Because `self.popover.behavior = .semitransient`, if the preview is
// currently visible, allow the click to passthrough to the `parentView`.
// This allows the "second click" to be the actual commit action.
guard !self.popover.isShown else { return false }
let content = effectiveContent(sender.location(in: self.parentView))
guard content != nil else { return false }
// Set the contentView here to maintain only a short-term reference.
switch content! {
case .view(let vc):
self.popover.contentViewController = vc
case .file(let url, let size):
self.popover.contentViewController = PreviewController.previewer(for: url as NSURL, size: size)
}
return true
}
// TODO:
/*
public func gestureRecognizer(_ sender: NSGestureRecognizer, shouldAttemptToRecognizeWith event: NSEvent) -> Bool {
if sender is NSPressGestureRecognizer {
return !event.associatedEventsMask.contains(.pressure)
} else if sender is PressureGestureRecognizer {
return event.associatedEventsMask.contains(.pressure)
}
return false
}
*/
}
| mpl-2.0 | a5ce13f719c59aeb7be79c170fe8266c | 42.070423 | 119 | 0.63462 | 5.093837 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | Roshambo App/Roshambo App/ViewController.swift | 1 | 1535 | //
// ViewController.swift
// Roshambo App
//
// Created by Reinaldo Verdugo on 8/10/16.
// Copyright © 2016 Reinaldo Verdugo. All rights reserved.
//
import UIKit
enum Move : Int {
case Rock = 0
case Paper
case Scissors
}
class ViewController: UIViewController {
func generateRandomMove () -> Move {
let value = Int(arc4random_uniform(3))
return Move(rawValue: value)!
}
@IBAction func rockAction(_ sender: AnyObject) {
let nextController = storyboard?.instantiateViewController(withIdentifier: "second") as! SecondViewController
nextController.playerMove = .Rock
nextController.opponentMove = generateRandomMove()
// present(nextController, animated: true, completion: nil)
self.navigationController?.pushViewController(nextController, animated: true)
}
@IBAction func paperAction(_ sender: AnyObject) {
performSegue(withIdentifier: "paperAction", sender: self)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nextController = segue.destination as! SecondViewController
nextController.opponentMove = generateRandomMove()
if segue.identifier == "paperAction" {
nextController.playerMove = .Paper
} else if segue.identifier == "scissorsAction" {
nextController.playerMove = .Scissors
}
}
}
| mit | bb8c1cb17ff4507cb41db5821f98fc51 | 27.943396 | 117 | 0.672751 | 4.869841 | false | false | false | false |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/Classes/Tools/Constant.swift | 1 | 432 | //
// Constant.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/7.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
// 屏幕宽高
let screenW = UIScreen.main.bounds.width
let screenH = UIScreen.main.bounds.height
// 状态栏高度
let statusBarH:CGFloat = 20.0
// 导航栏高度
let navBarH:CGFloat = 44.0
// 底部工具栏高度
let tabBarH:CGFloat = 44.0
// 菜单高度
let menuH:CGFloat = 35
| mit | ad6950e0dcc238540c6c9697eee23fb4 | 13.92 | 45 | 0.683646 | 2.702899 | false | false | false | false |
mirego/PinLayout | Example/PinLayoutSample/UI/Menu/MenuViewController.swift | 1 | 5232 | // Copyright (c) 2017 Luc Dion
// 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
enum PageType: Int {
case intro
case adjustToContainer
case tableView
case collectionView
case animations
case autoAdjustingSize
case safeArea
case relativePositions
case between
case form
case wrapContent
case autoSizing
case tableViewWithReadable
case introRTL
case introObjC
case count
var title: String {
switch self {
case .intro: return "Introduction Example"
case .adjustToContainer: return "Adjust to Container Size"
case .tableView: return "UITableView with Variable Cell's Height"
case .collectionView: return "UICollectionView Example"
case .animations: return "Animation Example"
case .autoAdjustingSize: return "Auto Adjusting Size"
case .safeArea: return "SafeArea & readableMargins"
case .relativePositions: return "Relative Positioning"
case .between: return "Between Example"
case .form: return "Form Example"
case .wrapContent: return "wrapContent Example"
case .autoSizing: return "Auto Sizing"
case .tableViewWithReadable: return "UITableView using readableMargins"
case .introRTL: return "Right-to-left Language Support"
case .introObjC: return "Objective-C PinLayout Example"
case .count: return ""
}
}
var viewController: UIViewController {
switch self {
case .intro:
return IntroViewController(pageType: self)
case .adjustToContainer:
return AdjustToContainerViewController(pageType: self)
case .tableView:
return TableViewExampleViewController(pageType: self)
case .collectionView:
return CollectionViewExampleViewController(pageType: self)
case .safeArea:
let tabbarController = UITabBarController()
tabbarController.title = self.title
tabbarController.setViewControllers([SafeAreaViewController(), SafeAreaAndMarginsViewController()], animated: false)
return tabbarController
case .animations:
return AnimationsViewController(pageType: self)
case .autoAdjustingSize:
return AutoAdjustingSizeViewController(pageType: self)
case .relativePositions:
return RelativeViewController(pageType: self)
case .between:
return BetweenViewController(pageType: self)
case .form:
return FormViewController(pageType: self)
case .wrapContent:
return WrapContentViewController(pageType: self)
case .autoSizing:
return AutoSizingViewController()
case .tableViewWithReadable:
return TableViewReadableContentViewController(pageType: self)
case .introRTL:
return IntroRTLViewController(pageType: self)
case .introObjC:
return IntroObjectiveCViewController()
case .count:
return UIViewController()
}
}
}
class MenuViewController: UIViewController {
private var mainView: MenuView {
return self.view as! MenuView
}
init() {
super.init(nibName: nil, bundle: nil)
title = "PinLayout Examples"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = MenuView()
mainView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
// didSelect(pageType: .intro)
}
}
// MARK: MenuViewDelegate
extension MenuViewController: MenuViewDelegate {
func didSelect(pageType: PageType) {
navigationController?.pushViewController(pageType.viewController, animated: true)
}
}
| mit | 9262039076f9b9a39796921dffe24fa7 | 37.755556 | 128 | 0.659786 | 5.247743 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/TopBarUIView.swift | 1 | 3859 | //
// TopBarUIView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 19.5.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// This view is used for basic navigation and info display on multiple different views
// The bar also provides access to P2P and other sharing options
@IBDesignable class TopBarUIView: CustomXibView
{
// OUTLETS ------------------
@IBOutlet weak var leftSideButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var userView: TopUserView!
// ATTRIBUTES --------------
// This will be called each time connection view is closed
var connectionCompletionHandler: (() -> ())?
private weak var viewController: UIViewController?
private var leftSideAction: (() -> ())?
private var avatar: Avatar?
private var info: AvatarInfo?
// LOAD ----------------------
override init(frame: CGRect)
{
super.init(frame: frame)
setupXib(nibName: "TopBar")
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
setupXib(nibName: "TopBar")
}
// ACTIONS ------------------
@IBAction func leftSideButtonPressed(_ sender: Any)
{
leftSideAction?()
}
@IBAction func connectButtonPressed(_ sender: Any)
{
guard let viewController = viewController else
{
print("ERROR: Cannot display connect VC without a view controller")
return
}
performConnect(using: viewController)
}
@IBAction func userViewTapped(_ sender: Any)
{
guard let viewController = viewController else
{
print("ERROR: Cannot display user view without a view controller")
return
}
guard let avatar = avatar, let info = info else
{
print("ERROR: No user data to edit")
return
}
viewController.displayAlert(withIdentifier: EditAvatarVC.identifier, storyBoardId: "MainMenu")
{
($0 as! EditAvatarVC).configureForEdit(avatar: avatar, avatarInfo: info) { _, _ in self.updateUserView() }
}
}
// OTHER METHODS --------------
// Localisation added automatically
func configure(hostVC: UIViewController, title: String, leftButtonText: String? = nil, leftButtonAction: (() -> ())? = nil)
{
viewController = hostVC
titleLabel.text = NSLocalizedString(title, comment: "A title shown in the top bar")
if let leftButtonText = leftButtonText.map({ NSLocalizedString($0, comment: "A button text in the top bar") })
{
leftSideButton.setTitle(leftButtonText, for: .normal)
leftSideButton.isHidden = false
self.leftSideAction = leftButtonAction
leftSideButton.isEnabled = leftButtonAction != nil
}
else
{
leftSideButton.isHidden = true
}
updateUserView()
}
func setLeftButtonAction(_ action: @escaping () -> ())
{
leftSideAction = action
leftSideButton.isEnabled = true
}
func performConnect(using viewController: UIViewController)
{
if let completionHandler = connectionCompletionHandler
{
viewController.displayAlert(withIdentifier: ConnectionVC.identifier, storyBoardId: "Common")
{
($0 as! ConnectionVC).configure(completion: completionHandler)
}
}
else
{
viewController.displayAlert(withIdentifier: ConnectionVC.identifier, storyBoardId: "Common")
}
}
func updateUserView()
{
var foundUserData = false
// Sets up the user view
if let projectId = Session.instance.projectId, let avatarId = Session.instance.avatarId
{
do
{
if let project = try Project.get(projectId), let avatar = try Avatar.get(avatarId), let info = try avatar.info()
{
self.avatar = avatar
self.info = info
userView.configure(projectName: project.name, username: avatar.name, image: info.image ?? #imageLiteral(resourceName: "userIcon"))
foundUserData = true
}
}
catch
{
print("ERROR: Failed to load user information for the top bar. \(error)")
}
}
userView.isHidden = !foundUserData
}
}
| mit | e314f69163dc2e178afa3ad1f49eb904 | 23.417722 | 135 | 0.686884 | 3.816024 | false | false | false | false |
ArshAulakh59/ArchitectureSample | ArchitectureSample/CustomManagement/ViewModels/DogsDataSource.swift | 1 | 1095 | //
// DogsDataSource.swift
// ArchitectureSample
//
// Created by Arsh Aulakh on 2016-10-16.
// Copyright © 2016 Bhouse. All rights reserved.
//
import UIKit
class DogsDataSource: NSObject, DataSourceProtocol {
internal var title: String {
return Pet.Dogs.value
}
}
extension DogsDataSource {
//MARK: Configure Table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 81
}
@objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self)) as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: String(describing: UITableView.self))
}
cell?.textLabel?.text = "Dog \(indexPath.row)"
return cell!
}
@objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
| mit | fc4f90b9ccfda141c83414d2967dc1bd | 31.176471 | 140 | 0.691042 | 4.735931 | false | false | false | false |
zisko/swift | stdlib/public/core/ValidUTF8Buffer.swift | 1 | 6965 | //===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Stores valid UTF8 inside an unsigned integer.
//
// Actually this basic type could be used to store any UInt8s that cannot be
// 0xFF
//
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct _ValidUTF8Buffer<Storage: UnsignedInteger & FixedWidthInteger> {
public typealias Element = Unicode.UTF8.CodeUnit
internal typealias _Storage = Storage
@_versioned
internal var _biasedBits: Storage
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_biasedBits: Storage) {
self._biasedBits = _biasedBits
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_containing e: Element) {
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits = Storage(truncatingIfNeeded: e &+ 1)
}
}
extension _ValidUTF8Buffer : Sequence {
public typealias SubSequence = Slice<_ValidUTF8Buffer>
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator : IteratorProtocol, Sequence {
@_inlineable // FIXME(sil-serialize-all)
public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits }
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
if _biasedBits == 0 { return nil }
defer { _biasedBits >>= 8 }
return Element(truncatingIfNeeded: _biasedBits) &- 1
}
@_versioned // FIXME(sil-serialize-all)
internal var _biasedBits: Storage
}
@_inlineable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _ValidUTF8Buffer : Collection {
@_fixed_layout // FIXME(sil-serialize-all)
public struct Index : Comparable {
@_versioned
internal var _biasedBits: Storage
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits }
@_inlineable // FIXME(sil-serialize-all)
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits == rhs._biasedBits
}
@_inlineable // FIXME(sil-serialize-all)
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits > rhs._biasedBits
}
}
@_inlineable // FIXME(sil-serialize-all)
public var startIndex : Index {
return Index(_biasedBits: _biasedBits)
}
@_inlineable // FIXME(sil-serialize-all)
public var endIndex : Index {
return Index(_biasedBits: 0)
}
@_inlineable // FIXME(sil-serialize-all)
public var count : Int {
return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3
}
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty : Bool {
return _biasedBits == 0
}
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
_debugPrecondition(i._biasedBits != 0)
return Index(_biasedBits: i._biasedBits >> 8)
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(i: Index) -> Element {
return Element(truncatingIfNeeded: i._biasedBits) &- 1
}
}
extension _ValidUTF8Buffer : BidirectionalCollection {
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count
_debugPrecondition(offset != 0)
return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8))
}
}
extension _ValidUTF8Buffer : RandomAccessCollection {
public typealias Indices = DefaultIndices<_ValidUTF8Buffer>
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
_debugPrecondition(_isValid(i))
_debugPrecondition(_isValid(j))
return (
i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount
) &>> 3
}
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let startOffset = distance(from: startIndex, to: i)
let newOffset = startOffset + n
_debugPrecondition(newOffset >= 0)
_debugPrecondition(newOffset <= count)
return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3))
}
}
extension _ValidUTF8Buffer : RangeReplaceableCollection {
@_inlineable // FIXME(sil-serialize-all)
public init() {
_biasedBits = 0
}
@_inlineable // FIXME(sil-serialize-all)
public var capacity: Int {
return _ValidUTF8Buffer.capacity
}
@_inlineable // FIXME(sil-serialize-all)
public static var capacity: Int {
return Storage.bitWidth / Element.bitWidth
}
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func append(_ e: Element) {
_debugPrecondition(count + 1 <= capacity)
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits |= Storage(e &+ 1) &<< (count &<< 3)
}
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
@discardableResult
public mutating func removeFirst() -> Element {
_debugPrecondition(!isEmpty)
let result = Element(truncatingIfNeeded: _biasedBits) &- 1
_biasedBits = _biasedBits._fullShiftRight(8)
return result
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal func _isValid(_ i: Index) -> Bool {
return i == endIndex || indices.contains(i)
}
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(_isValid(target.lowerBound))
_debugPrecondition(_isValid(target.upperBound))
var r = _ValidUTF8Buffer()
for x in self[..<target.lowerBound] { r.append(x) }
for x in replacement { r.append(x) }
for x in self[target.upperBound...] { r.append(x) }
self = r
}
}
extension _ValidUTF8Buffer {
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) {
_debugPrecondition(count + other.count <= capacity)
_biasedBits |= Storage(
truncatingIfNeeded: other._biasedBits) &<< (count &<< 3)
}
}
extension _ValidUTF8Buffer {
@_inlineable // FIXME(sil-serialize-all)
public static var encodedReplacementCharacter : _ValidUTF8Buffer {
return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01)
}
}
| apache-2.0 | b3f2fa7f34432598400bce9b6b97b9dd | 30.09375 | 80 | 0.655276 | 4.16318 | false | false | false | false |
PangeaSocialNetwork/PangeaGallery | PangeaMediaPicker/ImagePicker/BrowserCell.swift | 1 | 868 | //
// BrowserCell.swift
// PangeaMediaPicker
//
// Created by Roger Li on 2017/8/31.
// Copyright © 2017年 Roger Li. All rights reserved.
//
import UIKit
class BrowserCell: UICollectionViewCell {
// Animation time
let animationTime = 0.5
@IBOutlet var bigImage: UIImageView!
var firstIndex:IndexPath = []
internal func setImageWithImage(_ image: UIImage, defaultImage: UIImage) {
self.setBigImageTheSizeOfThe(image, defaultImage:defaultImage)
}
func setBigImageTheSizeOfThe(_ bImage: UIImage, defaultImage: UIImage) {
self.bigImage.image = bImage
}
func indexPath() -> IndexPath? {
if let collectionView = self.superview as? UICollectionView {
let indexPath = collectionView.indexPath(for: self)
return indexPath
} else {
return nil
}
}
}
| mit | 93011ef41c56cfd3f9970fa4fd2b4726 | 24.441176 | 78 | 0.654335 | 4.346734 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/swift_helpers/String+CryptoExtensions.swift | 1 | 1986 | //
// String+CryptoExtensions.swift
// CDAKit
//
// Created by Eric Whitley on 12/17/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
//import Foundation
//import CommonCrypto
//http://stackoverflow.com/questions/25424831/cant-convert-nsdata-to-nsstring-in-swift
//extension String {
// func md5(string string: String) -> [UInt8] {
// var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
// if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
// CC_MD5(data.bytes, CC_LONG(data.length), &digest)
// }
//
// return digest
// }
//
// func md5(string: String) -> NSData {
// let digest = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))!
// if let data :NSData = string.dataUsingEncoding(NSUTF8StringEncoding) {
// CC_MD5(data.bytes, CC_LONG(data.length),
// UnsafeMutablePointer<UInt8>(digest.mutableBytes))
// }
// return digest
// }
//
// func md5Digest(string: NSString) -> NSString {
// let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
// var hash = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
// CC_MD5(data.bytes, CC_LONG(data.length), &hash)
// let resstr = NSMutableString()
// for byte in hash {
// resstr.appendFormat("%02hhx", byte)
// }
// return resstr
// }
// func hnk_MD5String() -> String {
// if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
// {
// if let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH)) {
// let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
// CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
// let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: result.length)
// let MD5 = NSMutableString()
// for c in resultEnumerator {
// MD5.appendFormat("%02x", c)
// }
// return MD5 as String
// }
// }
// return ""
// }
//}
| mit | c796e91372492324adee3c68d59f116e | 30.015625 | 109 | 0.636776 | 3.358714 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Helpers/syncengine/ZMUser+ExpirationTimeFormatting.swift | 1 | 2538 | ////
// Wire
// Copyright (C) 2018 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 WireDataModel
fileprivate extension TimeInterval {
var hours: Double {
return self / 3600
}
var minutes: Double {
return self / 60
}
}
final class WirelessExpirationTimeFormatter {
static let shared = WirelessExpirationTimeFormatter()
private let numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
return formatter
}()
func string(for user: UserType) -> String? {
return string(for: user.expiresAfter)
}
func string(for interval: TimeInterval) -> String? {
guard interval > 0 else { return nil }
let (hoursLeft, minutesLeft) = (interval.hours, interval.minutes)
guard hoursLeft < 2 else { return localizedHours(floor(hoursLeft) + 1) }
if hoursLeft > 1 {
let extraMinutes = minutesLeft - 60
return localizedHours(extraMinutes > 30 ? 2 : 1.5)
}
switch minutesLeft {
case 45...Double.greatestFiniteMagnitude: return localizedHours(1)
case 30..<45: return localizedMinutes(45)
case 15..<30: return localizedMinutes(30)
default: return localizedMinutes(15)
}
}
private func localizedMinutes(_ minutes: Double) -> String {
return "guest_room.expiration.less_than_minutes_left".localized(args: String(format: "%.0f", minutes))
}
private func localizedHours(_ hours: Double) -> String {
let localizedHoursString = numberFormatter.string(from: NSNumber(value: hours)) ?? "\(hours)"
return "guest_room.expiration.hours_left".localized(args: localizedHoursString)
}
}
extension UserType {
var expirationDisplayString: String? {
return WirelessExpirationTimeFormatter.shared.string(for: self)
}
}
| gpl-3.0 | a92f53426b0ece09325ad9cb870756eb | 31.538462 | 110 | 0.680457 | 4.516014 | false | false | false | false |
benlangmuir/swift | test/Interop/SwiftToCxx/properties/setter-in-cxx.swift | 2 | 8880 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Properties -clang-header-expose-public-decls -emit-clang-header-path %t/properties.h
// RUN: %FileCheck %s < %t/properties.h
// RUN: %check-interop-cxx-header-in-clang(%t/properties.h)
public struct FirstSmallStruct {
public var x: UInt32
}
// CHECK: class FirstSmallStruct final {
// CHECK: public:
// CHECK: inline FirstSmallStruct(FirstSmallStruct &&) = default;
// CHECK-NEXT: inline uint32_t getX() const;
// CHECK-NEXT: inline void setX(uint32_t value);
// CHECK-NEXT: private:
public struct LargeStruct {
public var x1, x2, x3, x4, x5, x6: Int
}
// CHECK: class LargeStruct final {
// CHECK: public:
// CHECK: inline LargeStruct(LargeStruct &&) = default;
// CHECK-NEXT: inline swift::Int getX1() const;
// CHECK-NEXT: inline void setX1(swift::Int value);
// CHECK-NEXT: inline swift::Int getX2() const;
// CHECK-NEXT: inline void setX2(swift::Int value);
// CHECK-NEXT: inline swift::Int getX3() const;
// CHECK-NEXT: inline void setX3(swift::Int value);
// CHECK-NEXT: inline swift::Int getX4() const;
// CHECK-NEXT: inline void setX4(swift::Int value);
// CHECK-NEXT: inline swift::Int getX5() const;
// CHECK-NEXT: inline void setX5(swift::Int value);
// CHECK-NEXT: inline swift::Int getX6() const;
// CHECK-NEXT: inline void setX6(swift::Int value);
// CHECK-NEXT: private:
public struct LargeStructWithProps {
public var storedLargeStruct: LargeStruct
public var storedSmallStruct: FirstSmallStruct
}
// CHECK: class LargeStructWithProps final {
// CHECK-NEXT: public:
// CHECK: inline LargeStruct getStoredLargeStruct() const;
// CHECK-NEXT: inline void setStoredLargeStruct(const LargeStruct& value);
// CHECK-NEXT: inline FirstSmallStruct getStoredSmallStruct() const;
// CHECK-NEXT: inline void setStoredSmallStruct(const FirstSmallStruct& value);
public final class PropertiesInClass {
public var storedInt: Int32
init(_ x: Int32) {
storedInt = x
}
public var computedInt: Int {
get {
return Int(storedInt) + 2
} set {
storedInt = Int32(newValue - 2)
}
}
}
// CHECK: class PropertiesInClass final : public swift::_impl::RefCountedClass {
// CHECK: using RefCountedClass::operator=;
// CHECK-NEXT: inline int32_t getStoredInt();
// CHECK-NEXT: inline void setStoredInt(int32_t value);
// CHECK-NEXT: inline swift::Int getComputedInt();
// CHECK-NEXT: inline void setComputedInt(swift::Int newValue);
public func createPropsInClass(_ x: Int32) -> PropertiesInClass {
return PropertiesInClass(x)
}
public struct SmallStructWithProps {
public var storedInt: UInt32
public var computedInt: Int {
get {
return Int(storedInt) + 2
} set {
storedInt = UInt32(newValue - 2)
}
}
public var largeStructWithProps: LargeStructWithProps {
get {
return LargeStructWithProps(storedLargeStruct: LargeStruct(x1: computedInt * 2, x2: 1, x3: 2, x4: 3, x5: 4, x6: 5),
storedSmallStruct:FirstSmallStruct(x: 0xFAE))
} set {
print("SET: \(newValue.storedLargeStruct), \(newValue.storedSmallStruct)")
}
}
}
// CHECK: class SmallStructWithProps final {
// CHECK: public:
// CHECK: inline SmallStructWithProps(SmallStructWithProps &&) = default;
// CHECK-NEXT: inline uint32_t getStoredInt() const;
// CHECK-NEXT: inline void setStoredInt(uint32_t value);
// CHECK-NEXT: inline swift::Int getComputedInt() const;
// CHECK-NEXT: inline void setComputedInt(swift::Int newValue);
// CHECK-NEXT: inline LargeStructWithProps getLargeStructWithProps() const;
// CHECK-NEXT: inline void setLargeStructWithProps(const LargeStructWithProps& newValue);
// CHECK-NEXT: private:
public func createSmallStructWithProps() -> SmallStructWithProps {
return SmallStructWithProps(storedInt: 21)
}
public func createFirstSmallStruct(_ x: UInt32) -> FirstSmallStruct {
return FirstSmallStruct(x: x)
}
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::setX(uint32_t value) {
// CHECK-NEXT: return _impl::$s10Properties16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::setX1(swift::Int value) {
// CHECK-NEXT: return _impl::$s10Properties11LargeStructV2x1Sivs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline LargeStruct LargeStructWithProps::getStoredLargeStruct() const {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties20LargeStructWithPropsV06storedbC0AA0bC0Vvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStructWithProps::setStoredLargeStruct(const LargeStruct& value) {
// CHECK-NEXT: return _impl::$s10Properties20LargeStructWithPropsV06storedbC0AA0bC0Vvs(_impl::_impl_LargeStruct::getOpaquePointer(value), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStructWithProps::getStoredSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Properties_uint32_t_0_4(result, _impl::$s10Properties20LargeStructWithPropsV011storedSmallC0AA05FirstgC0Vvg(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStructWithProps::setStoredSmallStruct(const FirstSmallStruct& value) {
// CHECK-NEXT: return _impl::$s10Properties20LargeStructWithPropsV011storedSmallC0AA05FirstgC0Vvs(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_impl::_impl_FirstSmallStruct::getOpaquePointer(value)), _getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline int32_t PropertiesInClass::getStoredInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline void PropertiesInClass::setStoredInt(int32_t value) {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC9storedInts5Int32Vvs(value, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int PropertiesInClass::getComputedInt() {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivg(::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK-NEXT: inline void PropertiesInClass::setComputedInt(swift::Int newValue) {
// CHECK-NEXT: return _impl::$s10Properties0A7InClassC11computedIntSivs(newValue, ::swift::_impl::_impl_RefCountedClass::getOpaquePointer(*this));
// CHECK-NEXT: }
// CHECK: inline uint32_t SmallStructWithProps::getStoredInt() const {
// CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV9storedInts6UInt32Vvg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline void SmallStructWithProps::setStoredInt(uint32_t value) {
// CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV9storedInts6UInt32Vvs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int SmallStructWithProps::getComputedInt() const {
// CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV11computedIntSivg(_impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline void SmallStructWithProps::setComputedInt(swift::Int newValue) {
// CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV11computedIntSivs(newValue, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStructWithProps SmallStructWithProps::getLargeStructWithProps() const {
// CHECK-NEXT: return _impl::_impl_LargeStructWithProps::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s10Properties20SmallStructWithPropsV05largecdE0AA05LargecdE0Vvg(result, _impl::swift_interop_passDirect_Properties_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void SmallStructWithProps::setLargeStructWithProps(const LargeStructWithProps& newValue) {
// CHECK-NEXT: return _impl::$s10Properties20SmallStructWithPropsV05largecdE0AA05LargecdE0Vvs(_impl::_impl_LargeStructWithProps::getOpaquePointer(newValue), _getOpaquePointer());
// CHECK-NEXT: }
| apache-2.0 | ddaffb47a286b1f872315e4a50aa00e6 | 48.333333 | 234 | 0.728716 | 3.913618 | false | false | false | false |
RichardAtDP/jbsignup | Sources/App/Models/lessons.swift | 1 | 3529 | //
// lessons.swift
// jbsignup
//
// Created by Richard on 2017-07-30.
//
import Foundation
import Vapor
import FluentProvider
final class lesson: Model {
var lessonId: String
var familyId: String
var dancerId: String
let storage = Storage()
init(lessonId:String, familyId:String, dancerId:String) throws {
self.lessonId = lessonId
self.familyId = familyId
self.dancerId = dancerId
}
init(row: Row) throws {
lessonId = try row.get("lessonId")
familyId = try row.get("familyId")
dancerId = try row.get("dancerId")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("lessonId", lessonId)
try row.set("familyId", familyId)
try row.set("dancerId", dancerId)
return row
}
}
extension lesson: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { lesson in
lesson.id()
lesson.string("lessonId")
lesson.string("familyId")
lesson.string("dancerId")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension lesson: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
lessonId: json.get("lessonId"),
familyId: json.get("familyId"),
dancerId: json.get("dancerId")
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("lessonId", lessonId)
try json.set("familyId", familyId)
try json.set("dancerId", dancerId)
return json
}
}
extension lesson: Timestampable { }
extension lesson: ResponseRepresentable { }
func saveLesson(proData:Content, familyid:String) throws {
// Swift freaks if it receives a string rather than an array, so make arrays.
var lessonList = [Node]()
var frequency = [Node]()
var dancerId = [Node]()
if proData["lesson"]!.array == nil {
lessonList = [proData["lesson"]!.string!.makeNode(in: nil)]
dancerId = [proData["dancer"]!.string!.makeNode(in: nil)]
} else {
lessonList = proData["lesson"]!.array!
dancerId = proData["dancer"]!.array!
}
// Go through each item and save or update
var i = 0
for chosenLesson in lessonList {
let query = try lesson.makeQuery()
try query.filter("lessonId",.equals,chosenLesson.string!)
try query.filter("dancerId",.equals,dancerId[i].string!)
try query.filter("familyId",.equals,familyid)
if try query.count() == 0 {
// New
let Lesson = try lesson(lessonId:chosenLesson.string!, familyId:familyid, dancerId:dancerId[i].string!)
try Lesson.save()
} else {
// Update existing
let Lesson = try lesson.find(query.first()?.id)
Lesson?.lessonId = chosenLesson.string!
Lesson?.dancerId = dancerId[i].string!
Lesson?.familyId = familyid
try Lesson?.save()
}
i += 1
}
}
| mit | adb7d3276bc1107f0f49486e2de91038 | 23.171233 | 119 | 0.525645 | 4.775372 | false | false | false | false |
semiroot/SwiftyConstraints | Tests/SC208HelperTest.swift | 1 | 1282 | //
// SC201Top.swift
// SwiftyConstraints
//
// Created by Hansmartin Geiser on 15/04/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import XCTest
@testable import SwiftyConstraints
class SC208HelperTests: SCTest {
func test00Update() {
let superview = SCTestView()
let subview1 = SCTestView()
let subview2 = SCTestView()
let subview3 = SCTestView()
let swiftyConstraints = superview.swiftyConstraints()
swiftyConstraints
.attach(subview1)
.attach(subview2)
.attach(subview3)
.updateConstraints()
XCTAssertTrue(superview.layoutIfCalled, "Constraint update failed on superview")
XCTAssertTrue(subview1.layoutIfCalled, "Constraint update failed on subview")
XCTAssertTrue(subview2.layoutIfCalled, "Constraint update failed on subview")
XCTAssertTrue(subview3.layoutIfCalled, "Constraint update failed on subview")
}
func test01execute() {
let superview = SCView()
let subview = SCView()
let swiftyConstraints = superview.swiftyConstraints()
swiftyConstraints
.attach(subview)
.execute({ (view) in
XCTAssertEqual(subview, view, "Wrong view passed to execute closure")
XCTAssertTrue(true, "?")
})
}
}
| mit | 25e441ca9c1a22664fbc04101d463b97 | 24.62 | 84 | 0.688525 | 4.726937 | false | true | false | false |
inspace-io/Social-Service-Browser | Sources/SocialServiceBrowserConfigurator.swift | 1 | 4527 | //
// SocialServiceBrowserConfigurator.swift
// Social Service Browser
//
// Created by Michal Zaborowski on 27.09.2017.
// Copyright © 2017 Inspace. All rights reserved.
//
import UIKit
public enum SocialServiceBrowserSelectionMode {
case select
case download(maxSelectedItemsCount: Int)
var maxSelectedItemsCount: Int {
switch self {
case .select: return 1
case .download(let count): return count
}
}
}
public enum SocialServiceBrowserDisplayMode {
case list
case grid
}
public protocol SocialServiceBrowserViewControllerUIConfigurable {
var displayMode: SocialServiceBrowserDisplayMode { get }
var backBarButtonItem: UIBarButtonItem { get }
var closeBarButtonItem: UIBarButtonItem { get }
var importBarButtonItem: UIBarButtonItem { get }
func registerCells(for collectionView: UICollectionView)
func reusableIdentifierForCell(`in` displayMode: SocialServiceBrowserDisplayMode) -> String
func reusableIdentifierForHeader(`in` displayMode: SocialServiceBrowserDisplayMode) -> String
}
extension SocialServiceBrowserViewControllerUIConfigurable {
public var backBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
}
public var closeBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(title: "Close", style: .plain, target: nil, action: nil)
}
public var importBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(title: "Import", style: .plain, target: nil, action: nil)
}
}
public protocol SocialServiceBrowserViewControllerConfigurable {
var client: SocialServiceBrowserClient { get }
var parentNode: SocialServiceBrowerNode? { get }
var selectionMode: SocialServiceBrowserSelectionMode { get }
func newConfiguration(with parentNode: SocialServiceBrowerNode) -> SocialServiceBrowserViewControllerConfigurable
}
public struct SocialServiceBrowserConfigurator: SocialServiceBrowserViewControllerConfigurable, SocialServiceBrowserViewControllerUIConfigurable {
public let selectionMode: SocialServiceBrowserSelectionMode
public let displayMode: SocialServiceBrowserDisplayMode = .grid
public let client: SocialServiceBrowserClient
public let parentNode: SocialServiceBrowerNode?
public init(client: SocialServiceBrowserClient, parentNode: SocialServiceBrowerNode? = nil, selectionMode: SocialServiceBrowserSelectionMode = .select) {
self.client = client
self.parentNode = parentNode
self.selectionMode = selectionMode
}
public func registerCells(for collectionView: UICollectionView) {
collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserGridCollectionViewCell.self),
bundle: Bundle(for: SocialServiceBrowserGridCollectionViewCell.self)),
forCellWithReuseIdentifier: reusableIdentifierForCell(in: .grid))
collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserCollectionReusableView.self),
bundle: Bundle(for: SocialServiceBrowserCollectionReusableView.self)),
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: reusableIdentifierForHeader(in: .grid))
collectionView.register(UINib(nibName: String(describing: SocialServiceBrowserListCollectionViewCell.self),
bundle: Bundle(for: SocialServiceBrowserListCollectionViewCell.self)),
forCellWithReuseIdentifier: reusableIdentifierForCell(in: .list))
}
public func reusableIdentifierForCell(in displayMode: SocialServiceBrowserDisplayMode) -> String {
if displayMode == .list {
return String(describing: SocialServiceBrowserListCollectionViewCell.self)
}
return String(describing: SocialServiceBrowserGridCollectionViewCell.self)
}
public func reusableIdentifierForHeader(in displayMode: SocialServiceBrowserDisplayMode) -> String {
return String(describing: SocialServiceBrowserCollectionReusableView.self)
}
public func newConfiguration(with parentNode: SocialServiceBrowerNode) -> SocialServiceBrowserViewControllerConfigurable {
return SocialServiceBrowserConfigurator(client: client, parentNode: parentNode)
}
}
| apache-2.0 | beaad0d3e37b33f6c74d29b1bb51dbd2 | 43.811881 | 157 | 0.733098 | 6.626647 | false | true | false | false |
Pyroh/Fluor | Fluor/Views/LinkButton.swift | 1 | 2793 | //
// LinkButton.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
import SmoothOperators
final class LinkButton: NSButton {
@IBInspectable var url: String?
private var actualURL: URL? {
guard let url = url else { return nil }
return URL(string: url)
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setupAppearance()
createAction()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupAppearance()
createAction()
}
private func setupAppearance() {
isBordered = false
imagePosition = .noImage
alternateTitle = title
var attributes = attributedTitle.fontAttributes(in: .init(location: 0, length: attributedTitle.length))
attributes[.foregroundColor] = NSColor.linkColor
attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
let newAttributedTitle = NSAttributedString(string: title, attributes: attributes)
attributedTitle = newAttributedTitle
attributedAlternateTitle = newAttributedTitle
}
private func createAction() {
target = self
action = #selector(openURL(_:))
}
override func resetCursorRects() {
super.resetCursorRects()
self.addCursorRect(self.bounds, cursor: .pointingHand)
}
@IBAction func openURL(_ sender: Any?){
guard !!url else { return }
guard let destinationURL = actualURL else { return assertionFailure("\(self.url!) is not a valid URL.") }
NSWorkspace.shared.open(destinationURL)
}
}
| mit | 86f1a8a624824f08245e404587512d91 | 33.060976 | 113 | 0.679198 | 4.709949 | false | false | false | false |
niceb5y/DRSTm | DRST manager/InfoViewController.swift | 1 | 2263 | //
// InfoViewController.swift
// DRST manager
//
// Created by 김승호 on 2016. 1. 30..
// Copyright © 2016년 Seungho Kim. All rights reserved.
//
import UIKit
import SafariServices
import DRSTKit
class InfoViewController: UITableViewController {
let dk = DataKit()
@IBOutlet weak var accountSwitch: UISwitch!
@IBOutlet weak var notificationSwitch: UISwitch!
@IBOutlet weak var iCloudSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
accountSwitch.setOn(dk.dualAccountEnabled, animated: false)
notificationSwitch.setOn(dk.notificationEnabled, animated: false)
iCloudSwitch.setOn(dk.iCloudEnabled, animated: false)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).section == 1 {
if (indexPath as NSIndexPath).row == 0 {
let vc = SFSafariViewController(url: URL(string: "https://twitter.com/deresuteborder")!)
self.present(vc, animated: true, completion: nil)
}
if (indexPath as NSIndexPath).row == 1 {
let vc = SFSafariViewController(url: URL(string: "https://twitter.com/imas_ml_td_t")!)
self.present(vc, animated: true, completion: nil)
}
} else if (indexPath as NSIndexPath).section == 2 {
if (indexPath as NSIndexPath).row == 0 {
let url = URL(string: "mailto:[email protected]?subject=%EB%8B%B9%EC%8B%A0%EC%9D%B4%20%EC%96%B4%EC%A7%B8%EC%84%9C%20%EA%B0%9C%EB%B0%9C%EC%9E%90%EC%9D%B8%EA%B1%B0%EC%A3%A0%3F")
UIApplication.shared.openURL(url!)
}
}
}
@IBAction func accountSwitchTouched(_ sender: AnyObject) {
dk.dualAccountEnabled = accountSwitch.isOn
}
@IBAction func notificationSwitchTouched(_ sender: AnyObject) {
dk.notificationEnabled = notificationSwitch.isOn
if notificationSwitch.isOn {
let notificationSettings = UIUserNotificationSettings(types: UIUserNotificationType.sound.union(UIUserNotificationType.alert), categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationSettings)
UIApplication.shared.registerForRemoteNotifications()
DRSTNotification.register()
} else {
DRSTNotification.clear()
}
}
@IBAction func iCloudSwitchTouched(_ sender: AnyObject) {
dk.iCloudEnabled = iCloudSwitch.isOn
}
}
| mit | 815e836bba644787271aa6c2fdd0e27f | 34.777778 | 185 | 0.737356 | 3.516381 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSObjCRuntime.swift | 1 | 11239 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFCompareLessThan = CFComparisonResult.compareLessThan
internal let kCFCompareEqualTo = CFComparisonResult.compareEqualTo
internal let kCFCompareGreaterThan = CFComparisonResult.compareGreaterThan
#endif
internal enum _NSSimpleObjCType : UnicodeScalar {
case ID = "@"
case Class = "#"
case Sel = ":"
case Char = "c"
case UChar = "C"
case Short = "s"
case UShort = "S"
case Int = "i"
case UInt = "I"
case Long = "l"
case ULong = "L"
case LongLong = "q"
case ULongLong = "Q"
case Float = "f"
case Double = "d"
case Bitfield = "b"
case Bool = "B"
case Void = "v"
case Undef = "?"
case Ptr = "^"
case CharPtr = "*"
case Atom = "%"
case ArrayBegin = "["
case ArrayEnd = "]"
case UnionBegin = "("
case UnionEnd = ")"
case StructBegin = "{"
case StructEnd = "}"
case Vector = "!"
case Const = "r"
}
extension Int {
init(_ v: _NSSimpleObjCType) {
self.init(UInt8(ascii: v.rawValue))
}
}
extension Int8 {
init(_ v: _NSSimpleObjCType) {
self.init(Int(v))
}
}
extension String {
init(_ v: _NSSimpleObjCType) {
self.init(v.rawValue)
}
}
extension _NSSimpleObjCType {
init?(_ v: UInt8) {
self.init(rawValue: UnicodeScalar(v))
}
init?(_ v: String?) {
if let rawValue = v?.unicodeScalars.first {
self.init(rawValue: rawValue)
} else {
return nil
}
}
}
// mapping of ObjC types to sizes and alignments (note that .Int is 32-bit)
// FIXME use a generic function, unfortuantely this seems to promote the size to 8
private let _NSObjCSizesAndAlignments : Dictionary<_NSSimpleObjCType, (Int, Int)> = [
.ID : ( MemoryLayout<AnyObject>.size, MemoryLayout<AnyObject>.alignment ),
.Class : ( MemoryLayout<AnyClass>.size, MemoryLayout<AnyClass>.alignment ),
.Char : ( MemoryLayout<CChar>.size, MemoryLayout<CChar>.alignment ),
.UChar : ( MemoryLayout<UInt8>.size, MemoryLayout<UInt8>.alignment ),
.Short : ( MemoryLayout<Int16>.size, MemoryLayout<Int16>.alignment ),
.UShort : ( MemoryLayout<UInt16>.size, MemoryLayout<UInt16>.alignment ),
.Int : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ),
.UInt : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ),
.Long : ( MemoryLayout<Int32>.size, MemoryLayout<Int32>.alignment ),
.ULong : ( MemoryLayout<UInt32>.size, MemoryLayout<UInt32>.alignment ),
.LongLong : ( MemoryLayout<Int64>.size, MemoryLayout<Int64>.alignment ),
.ULongLong : ( MemoryLayout<UInt64>.size, MemoryLayout<UInt64>.alignment ),
.Float : ( MemoryLayout<Float>.size, MemoryLayout<Float>.alignment ),
.Double : ( MemoryLayout<Double>.size, MemoryLayout<Double>.alignment ),
.Bool : ( MemoryLayout<Bool>.size, MemoryLayout<Bool>.alignment ),
.CharPtr : ( MemoryLayout<UnsafePointer<CChar>>.size, MemoryLayout<UnsafePointer<CChar>>.alignment)
]
internal func _NSGetSizeAndAlignment(_ type: _NSSimpleObjCType,
_ size : inout Int,
_ align : inout Int) -> Bool {
guard let sizeAndAlignment = _NSObjCSizesAndAlignments[type] else {
return false
}
size = sizeAndAlignment.0
align = sizeAndAlignment.1
return true
}
public func NSGetSizeAndAlignment(_ typePtr: UnsafePointer<Int8>,
_ sizep: UnsafeMutablePointer<Int>?,
_ alignp: UnsafeMutablePointer<Int>?) -> UnsafePointer<Int8> {
let type = _NSSimpleObjCType(UInt8(typePtr.pointee))!
var size : Int = 0
var align : Int = 0
if !_NSGetSizeAndAlignment(type, &size, &align) {
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is defined as returning a non-optional value.
fatalError("invalid type encoding")
}
sizep?.pointee = size
alignp?.pointee = align
return typePtr.advanced(by: 1)
}
public enum ComparisonResult : Int {
case orderedAscending = -1
case orderedSame
case orderedDescending
internal static func _fromCF(_ val: CFComparisonResult) -> ComparisonResult {
if val == kCFCompareLessThan {
return .orderedAscending
} else if val == kCFCompareGreaterThan {
return .orderedDescending
} else {
return .orderedSame
}
}
}
/* Note: QualityOfService enum is available on all platforms, but it may not be implemented on all platforms. */
public enum NSQualityOfService : Int {
/* UserInteractive QoS is used for work directly involved in providing an interactive UI such as processing events or drawing to the screen. */
case userInteractive
/* UserInitiated QoS is used for performing work that has been explicitly requested by the user and for which results must be immediately presented in order to allow for further user interaction. For example, loading an email after a user has selected it in a message list. */
case userInitiated
/* Utility QoS is used for performing work which the user is unlikely to be immediately waiting for the results. This work may have been requested by the user or initiated automatically, does not prevent the user from further interaction, often operates at user-visible timescales and may have its progress indicated to the user by a non-modal progress indicator. This work will run in an energy-efficient manner, in deference to higher QoS work when resources are constrained. For example, periodic content updates or bulk file operations such as media import. */
case utility
/* Background QoS is used for work that is not user initiated or visible. In general, a user is unaware that this work is even happening and it will run in the most efficient manner while giving the most deference to higher QoS work. For example, pre-fetching content, search indexing, backups, and syncing of data with external systems. */
case background
/* Default QoS indicates the absence of QoS information. Whenever possible QoS information will be inferred from other sources. If such inference is not possible, a QoS between UserInitiated and Utility will be used. */
case `default`
}
public struct NSSortOptions: OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let concurrent = NSSortOptions(rawValue: UInt(1 << 0))
public static let stable = NSSortOptions(rawValue: UInt(1 << 4))
}
public struct NSEnumerationOptions: OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let concurrent = NSEnumerationOptions(rawValue: UInt(1 << 0))
public static let reverse = NSEnumerationOptions(rawValue: UInt(1 << 1))
}
public typealias Comparator = (Any, Any) -> ComparisonResult
public let NSNotFound: Int = Int.max
internal func NSRequiresConcreteImplementation(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("\(fn) must be overriden in subclass implementations", file: file, line: line)
}
internal func NSUnimplemented(_ fn: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
#if os(Android)
NSLog("\(fn) is not yet implemented. \(file):\(line)")
#endif
fatalError("\(fn) is not yet implemented", file: file, line: line)
}
internal func NSInvalidArgument(_ message: String, method: String = #function, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError("\(method): \(message)", file: file, line: line)
}
internal struct _CFInfo {
// This must match _CFRuntimeBase
var info: UInt32
var pad : UInt32
init(typeID: CFTypeID) {
// This matches what _CFRuntimeCreateInstance does to initialize the info value
info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80)))
pad = 0
}
init(typeID: CFTypeID, extra: UInt32) {
info = UInt32((UInt32(typeID) << 8) | (UInt32(0x80)))
pad = extra
}
}
#if os(OSX) || os(iOS)
private let _SwiftFoundationModuleName = "SwiftFoundation"
#else
private let _SwiftFoundationModuleName = "Foundation"
#endif
/**
Returns the class name for a class. For compatibility with Foundation on Darwin,
Foundation classes are returned as unqualified names.
Only top-level Swift classes (Foo.bar) are supported at present. There is no
canonical encoding for other types yet, except for the mangled name, which is
neither stable nor human-readable.
*/
public func NSStringFromClass(_ aClass: AnyClass) -> String {
let aClassName = String(reflecting: aClass)._bridgeToObjectiveC()
let components = aClassName.components(separatedBy: ".")
guard components.count == 2 else {
fatalError("NSStringFromClass: \(String(reflecting: aClass)) is not a top-level class")
}
if components[0] == _SwiftFoundationModuleName {
return components[1]
} else {
return String(describing: aClassName)
}
}
/**
Returns the class metadata given a string. For compatibility with Foundation on Darwin,
unqualified names are looked up in the Foundation module.
Only top-level Swift classes (Foo.bar) are supported at present. There is no
canonical encoding for other types yet, except for the mangled name, which is
neither stable nor human-readable.
*/
public func NSClassFromString(_ aClassName: String) -> AnyClass? {
let aClassNameWithPrefix : String
let components = aClassName._bridgeToObjectiveC().components(separatedBy: ".")
switch components.count {
case 1:
guard !aClassName.hasPrefix("_Tt") else {
NSLog("*** NSClassFromString(\(aClassName)): cannot yet decode mangled class names")
return nil
}
aClassNameWithPrefix = _SwiftFoundationModuleName + "." + aClassName
break
case 2:
aClassNameWithPrefix = aClassName
break
default:
NSLog("*** NSClassFromString(\(aClassName)): nested class names not yet supported")
return nil
}
return _typeByName(aClassNameWithPrefix) as? AnyClass
}
| apache-2.0 | de76f6466395c326d685c2a3d8f0f354 | 38.85461 | 571 | 0.64463 | 4.627007 | false | false | false | false |
natecook1000/swift | test/Constraints/iuo.swift | 10 | 4765 | // RUN: %target-typecheck-verify-swift
func basic() {
var i: Int! = 0
let _: Int = i
i = 7
}
func takesIUOs(i: Int!, j: inout Int!) -> Int {
j = 7
return i
}
struct S {
let i: Int!
var j: Int!
let k: Int
var m: Int
var n: Int! {
get {
return m
}
set {
m = newValue
}
}
var o: Int! {
willSet {
m = newValue
}
didSet {
m = oldValue
}
}
func fn() -> Int! { return i }
static func static_fn() -> Int! { return 0 }
subscript(i: Int) -> Int! {
set {
m = newValue
}
get {
return i
}
}
init(i: Int!, j: Int!, k: Int, m: Int) {
self.i = i
self.j = j
self.k = k
self.m = m
}
init!() {
i = 0
j = 0
k = 0
m = 0
}
}
func takesStruct(s: S) {
let _: Int = s.i
let _: Int = s.j
var t: S! = s
t.j = 7
}
var a: (Int, Int)! = (0, 0)
a.0 = 42
var s: S! = S(i: nil, j: 1, k: 2, m: 3)
_ = s.i
let _: Int = s.j
_ = s.k
s.m = 7
s.j = 3
let _: Int = s[0]
struct T {
let i: Float!
var j: Float!
func fn() -> Float! { return i }
}
func overloaded() -> S { return S(i: 0, j: 1, k: 2, m: 3) }
func overloaded() -> T { return T(i: 0.5, j: 1.5) }
let _: Int = overloaded().i
func cflow(i: Int!, j: inout Bool!, s: S) {
let k: Int? = i
let m: Int = i
let b: Bool! = i == 0
if i == 7 {
if s.i == 7 {
}
}
let _ = b ? i : k
let _ = b ? i : m
let _ = b ? j : b
let _ = b ? s.j : s.k
if b {}
if j {}
let _ = j ? 7 : 0
}
func forcedResultInt() -> Int! {
return 0
}
let _: Int = forcedResultInt()
func forcedResult() -> Int! {
return 0
}
func forcedResult() -> Float! {
return 0
}
func overloadedForcedResult() -> Int {
return forcedResult()
}
func forceMemberResult(s: S) -> Int {
return s.fn()
}
func forceStaticMemberResult() -> Int {
return S.static_fn()
}
func overloadedForceMemberResult() -> Int {
return overloaded().fn()
}
func overloadedForcedStructResult() -> S! { return S(i: 0, j: 1, k: 2, m: 3) }
func overloadedForcedStructResult() -> T! { return T(i: 0.5, j: 1.5) }
let _: S = overloadedForcedStructResult()
let _: Int = overloadedForcedStructResult().i
func id<T>(_ t: T) -> T { return t }
protocol P { }
extension P {
func iuoResult(_ b: Bool) -> Self! { }
static func iuoResultStatic(_ b: Bool) -> Self! { }
}
func cast<T : P>(_ t: T) {
let _: (T) -> (Bool) -> T? = id(T.iuoResult as (T) -> (Bool) -> T?)
let _: (Bool) -> T? = id(T.iuoResult(t) as (Bool) -> T?)
let _: T! = id(T.iuoResult(t)(true))
let _: (Bool) -> T? = id(t.iuoResult as (Bool) -> T?)
let _: T! = id(t.iuoResult(true))
let _: T = id(t.iuoResult(true))
let _: (Bool) -> T? = id(T.iuoResultStatic as (Bool) -> T?)
let _: T! = id(T.iuoResultStatic(true))
}
class rdar37241550 {
public init(blah: Float) { fatalError() }
public convenience init() { fatalError() }
public convenience init!(with void: ()) { fatalError() }
static func f(_ fn: () -> rdar37241550) {}
static func test() {
f(rdar37241550.init) // no error, the failable init is not applicable
}
}
class B {}
class D : B {
var i: Int!
}
func coerceToIUO(d: D?) -> B {
return d as B! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToOptional(b: B?) -> D? {
return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToObject(b: B?) -> D {
return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToObjectIUOMember(b: B?) -> Int {
return (b as! D!).i // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedUnwrapViaForcedCast(b: B?) -> B {
return b as! B! // expected-warning {{forced cast from 'B?' to 'B' only unwraps optionals; did you mean to use '!'?}}
// expected-warning@-1 {{using '!' here is deprecated and will be removed in a future release}}
}
func conditionalDowncastToOptional(b: B?) -> D? {
return b as? D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func conditionalDowncastToObject(b: B?) -> D {
return b as? D! // expected-error {{value of optional type 'D?' must be unwrapped}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
// expected-warning@-3 {{using '!' here is deprecated and will be removed in a future release}}
}
// Ensure that we select the overload that does *not* involve forcing an IUO.
func sr6988(x: Int?, y: Int?) -> Int { return x! }
func sr6988(x: Int, y: Int) -> Float { return Float(x) }
var x: Int! = nil
var y: Int = 2
let r = sr6988(x: x, y: y)
let _: Int = r
| apache-2.0 | 22aeea5153f91f03b4f8b9ecb24522c7 | 19.991189 | 119 | 0.571039 | 2.900183 | false | false | false | false |
naveenrana1309/NRControls | NRControls/Classes/NRControls.swift | 1 | 14341 | //
// NRControls.swift
//
//
// Created by Naveen Rana on 21/08/16.
// Developed by Naveen Rana. All rights reserved.
//
import Foundation
import MessageUI
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
/// This completionhandler use for call back image picker controller delegates.
public typealias ImagePickerControllerCompletionHandler = (_ controller: UIImagePickerController, _ info: [UIImagePickerController.InfoKey: Any]) -> Void
/// This completionhandler use for call back mail controller delegates.
public typealias MailComposerCompletionHandler = (_ result:MFMailComposeResult ,_ error: NSError?) -> Void
/// This completionhandler use for call back alert(Alert) controller delegates.
public typealias AlertControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int) -> Void
/// This completionhandler use for call back alert(ActionSheet) controller delegates.
public typealias AlertTextFieldControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int, _ text: String) -> Void
/// This completionhandler use for call back of selected image using image picker controller delegates.
public typealias CompletionImagePickerController = (_ selectedImage: UIImage?) -> Void
/// This completionhandler use for call back of selected url using DocumentPicker controller delegates.
public typealias DocumentPickerCompletionHandler = (_ selectedDocuments: [URL]?) -> Void
/// This class is used for using a common controls like alert, action sheet and imagepicker controller with proper completion Handlers.
open class NRControls: NSObject,UIImagePickerControllerDelegate,MFMailComposeViewControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate{
/// This completionhandler use for call back image picker controller delegates.
var imagePickerControllerHandler: ImagePickerControllerCompletionHandler?
/// This completionhandler use for call back mail controller delegates.
var mailComposerCompletionHandler: MailComposerCompletionHandler?
/// This completionhandler use for call back mail controller delegates.
var documentPickerCompletionHandler: DocumentPickerCompletionHandler?
///Shared instance
public static let sharedInstance = NRControls()
/**
This function is used for taking a picture from iphone camera or camera roll.
- Parameters:
- viewController: Source viewcontroller from which you want to present this popup.
- completionHandler: This completion handler will give you image or nil.
*/
//MARK: UIImagePickerController
open func takeOrChoosePhoto(_ viewController: UIViewController, completionHandler: @escaping CompletionImagePickerController) {
let actionSheetController: UIAlertController = UIAlertController(title: "", message: "Choose photo", preferredStyle: .actionSheet)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
//Just dismiss the action sheet
completionHandler(nil)
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
//Create and add a second option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .default) { action -> Void in
self.openImagePickerController(.camera, isVideo: false, inViewController: viewController) { (controller, info) -> Void in
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
completionHandler(image)
}
}
actionSheetController.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose from library", style: .default) { action -> Void in
self.openImagePickerController(.photoLibrary, isVideo: false, inViewController: viewController) { (controller, info) -> Void in
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
completionHandler(image)
}
}
actionSheetController.addAction(choosePictureAction)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) {
// In this case the device is an iPad.
if let popoverController = actionSheetController.popoverPresentationController {
popoverController.sourceView = viewController.view
popoverController.sourceRect = viewController.view.bounds
}
}
viewController.present(actionSheetController, animated: true, completion: nil)
}
/**
This function is used open image picker controller.
- Parameters:
- sourceType: PhotoLibrary, Camera, SavedPhotosAlbum
- inViewController: Source viewcontroller from which you want to present this imagecontroller.
- isVideo: if you want to capture video then set it to yes, by default value is false.
- completionHandler: Gives you the call back with Imagepickercontroller and information about image.
*/
open func openImagePickerController(_ sourceType: UIImagePickerController.SourceType, isVideo: Bool = false, inViewController:UIViewController, completionHandler: @escaping ImagePickerControllerCompletionHandler)-> Void {
self.imagePickerControllerHandler = completionHandler
let controller = UIImagePickerController()
controller.allowsEditing = false
controller.delegate = self;
if UIImagePickerController.isSourceTypeAvailable(sourceType){
controller.sourceType = sourceType
}
else
{
print("this source type not supported in this device")
}
if (UI_USER_INTERFACE_IDIOM() == .pad) { //iPad support
// In this case the device is an iPad.
if let popoverController = controller.popoverPresentationController {
popoverController.sourceView = inViewController.view
popoverController.sourceRect = inViewController.view.bounds
}
}
inViewController.present(controller, animated: true, completion: nil)
}
//MARK: UIImagePickerController Delegates
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("didFinishPickingMediaWithInfo")
self.imagePickerControllerHandler!(picker, info)
picker.dismiss(animated: true, completion: nil)
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
/**
This function is used for open Mail Composer.
- Parameters:
- recipientsEmailIds: email ids of recipents for you want to send emails.
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- subject: Subject of mail.
- message: body of mail.
- attachment: optional this is nsdata of video/photo or any other document.
- completionHandler: Gives you the call back with result and error if any.
*/
//MARK: MFMailComposeViewController
open func openMailComposerInViewController(_ recipientsEmailIds:[String], viewcontroller: UIViewController, subject: String = "", message: String = "" ,attachment: Data? = nil,completionHandler: @escaping MailComposerCompletionHandler){
if !MFMailComposeViewController.canSendMail() {
print("No mail configured. please configure your mail first")
return()
}
self.mailComposerCompletionHandler = completionHandler
let mailComposerViewController = MFMailComposeViewController()
mailComposerViewController.mailComposeDelegate = self
mailComposerViewController.setSubject(subject)
mailComposerViewController.setMessageBody(message, isHTML: true)
mailComposerViewController.setToRecipients(recipientsEmailIds)
if let _ = attachment {
if (attachment!.count>0)
{
mailComposerViewController.addAttachmentData(attachment!, mimeType: "image/jpeg", fileName: "attachment.jpeg")
}
}
viewcontroller.present(mailComposerViewController, animated: true, completion:nil)
}
//MARK: MFMailComposeViewController Delegates
open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion:nil)
if self.mailComposerCompletionHandler != nil {
self.mailComposerCompletionHandler!(result, error as NSError?)
}
}
//MARK: AlertController
/**
This function is used for open Alert View.
- Parameters:
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController and index of selected button .
*/
open func openAlertViewFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for element in buttonsTitlesArray {
let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!)
}
})
alertController.addAction(action)
}
viewController.present(alertController, animated: true, completion: nil)
}
/**
This function is used for open Action Sheet.
- Parameters:
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController and index of selected button .
*/
open func openActionSheetFromViewController(_ viewController: UIViewController, title: String, message: String, buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for element in buttonsTitlesArray {
let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!)
}
})
alertController.addAction(action)
}
viewController.present(alertController, animated: true, completion: nil)
}
/**
This function is used for openAlertView with textfield.
- Parameters:
- viewcontroller: source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert.
- placeHolder: placeholder of the textfield.
- isSecure: true if you want texfield secure, by default is false.
- isNumberKeyboard: true if keyboard is of type numberpad, .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController,index and text of textfield.
*/
open func openAlertViewWithTextFieldFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", placeHolder: String = "", isSecure: Bool = false, buttonsTitlesArray: [String], isNumberKeyboard: Bool = false, completionHandler: AlertTextFieldControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for element in buttonsTitlesArray {
let action: UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
if let _ = alertController.textFields , alertController.textFields?.count > 0 , let text = alertController.textFields?.first?.text {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!, text)
}
}
})
alertController.addAction(action)
}
alertController.addTextField { (textField : UITextField!) -> Void in
textField.isSecureTextEntry = isSecure
textField.placeholder = placeHolder
if isNumberKeyboard {
textField.keyboardType = .numberPad
}
else {
textField.keyboardType = .emailAddress
}
}
viewController.present(alertController, animated: false, completion: nil)
}
}
| mit | c5721df66c1916cf91a4694c96434642 | 42.326284 | 312 | 0.66669 | 5.965474 | false | false | false | false |
OlliePoole/SimplePageViewController | SimplePageViewController.swift | 1 | 3259 |
import Foundation
import UIKit
protocol SimplePageViewControllerDelegate {
func simplePageViewController(pageViewController: SimplePageViewController, didMoveToPage page: UIViewController)
}
class SimplePageViewController : UIPageViewController {
var customViewControllers : Array<UIViewController>
/// Allows the page vew controlller to manage a page control
var pageControl : UIPageControl?
var pageDelegate: SimplePageViewControllerDelegate?
/**
Initalises a new UIPageViewController and sets the view controllers passsed as a
parameter to the datasource
- parameter viewControllers: The view controllers included in the UIPageViewController
*/
init(withViewControllers viewControllers : Array<UIViewController>) {
// Initalise the properties
self.customViewControllers = viewControllers
// Call the super designated initaliser
super.init(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
// Set the UIPageViewController view controllers and default settings
setViewControllers([customViewControllers[0]], direction: .Forward, animated: true, completion: nil)
dataSource = self
delegate = self
}
required init?(coder aDecoder: NSCoder) {
self.customViewControllers = Array<UIViewController>()
super.init(coder: aDecoder)
}
func moveToViewController(atIndex index: Int, direction: UIPageViewControllerNavigationDirection) {
assert(index < customViewControllers.count, "Index out of bounds")
let newViewController = customViewControllers[index]
setViewControllers([newViewController], direction: direction, animated: true, completion: nil)
}
}
extension SimplePageViewController : UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var nextViewController: UIViewController?
if let index = customViewControllers.indexOf(viewController) {
pageControl?.currentPage = index
if index != customViewControllers.count - 1 {
nextViewController = customViewControllers[index + 1]
}
}
return nextViewController
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var nextViewController: UIViewController?
if let index = customViewControllers.indexOf(viewController) {
pageControl?.currentPage = index
if index != 0 {
nextViewController = customViewControllers[index - 1]
}
}
return nextViewController
}
}
extension SimplePageViewController : UIPageViewControllerDelegate {
func pageViewController(pageViewController: UIPageViewController,
didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let viewController = pageViewController.viewControllers?.first {
pageDelegate?.simplePageViewController(self, didMoveToPage: viewController)
}
}
}
| apache-2.0 | ec96d71f6309b77111f1f65262de988a | 32.947917 | 144 | 0.73857 | 6.531062 | false | false | false | false |
nakiostudio/EasyPeasy | EasyPeasy/DimensionAttribute+UIKit.swift | 1 | 3576 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
/**
DimensionAttribute extension adding some convenience methods to operate with
UIKit elements as `UIViews` or `UILayoutGuides`
*/
public extension DimensionAttribute {
/**
Establishes a relationship between the dimension attribute
applied to the `UIView` and the reference `UIView` passed as
parameter.
It's also possible to link this relationship to a particular
attribute of the `view` parameter by supplying `attribute`.
- parameter view: The reference view
- parameter attribute: The attribute of `view` we are establishing the
relationship to
- returns: The current `Attribute` instance
*/
@discardableResult func like(_ view: UIView, _ attribute: ReferenceAttribute? = nil) -> Self {
self.referenceItem = view
self.referenceAttribute = attribute
return self
}
/**
Establishes a relationship between the dimension attribute
applied to the `UIView` and the reference `UILayoutGuide`
passed as parameter.
It's also possible to link this relationship to a particular
attribute of the `layoutGuide` parameter by supplying `attribute`.
- parameter layoutGuide: The reference `UILayoutGuide`
- parameter attribute: The attribute of `layoutGuide` we are establishing
the relationship to
- returns: The current `Attribute` instance
*/
@available (iOS 9.0, *)
@discardableResult func like(_ layoutGuide: UILayoutGuide, _ attribute: ReferenceAttribute? = nil) -> Self {
self.referenceItem = layoutGuide
self.referenceAttribute = attribute
return self
}
}
/**
Size extension adding some convenience methods to let this CompoundAttribute
operate with UIKit elements like `UIViews` or `UILayoutGuides`
*/
public extension Size {
/**
Establishes a relationship between the dimension attribute
applied to the `UIView` and the reference `UIView` passed as
parameter.
- parameter view: The reference view
- returns: The current `CompoundAttribute` instance
*/
@discardableResult func like(_ view: UIView) -> Self {
self.referenceItem = view
for attr in self.attributes {
attr.referenceItem = view
}
return self
}
/**
Establishes a relationship between the dimension attribute
applied to the `UIView` and the reference `UILayoutGuide`
passed as parameter.
- parameter layoutGuide: The reference `UILayoutGuide`
- returns: The current `CompoundAttribute` instance
*/
@available (iOS 9.0, *)
@discardableResult func like(_ layoutGuide: UILayoutGuide) -> Self {
self.referenceItem = layoutGuide
for attr in self.attributes {
attr.referenceItem = layoutGuide
}
return self
}
}
#endif
| mit | 7cf6c9909cc095725196f21b9c164ed3 | 34.405941 | 112 | 0.665268 | 5.266568 | false | false | false | false |
Yoloabdo/CS-193P | Phsychoic/Phsychoic/MainViewController.swift | 1 | 1280 | //
// ViewController.swift
// Phsychoic
//
// Created by abdelrahman mohamed on 2/5/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
struct segues {
static let happiness = "happy"
static let sadness = "sad"
static let meh = "meh"
static let fourth = "nothing"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destination = segue.destinationViewController
if let navcon = destination as? UINavigationController {
destination = navcon.visibleViewController!
}
if let hvc = destination as? HappinessViewController{
if let identfier = segue.identifier{
switch identfier{
case segues.happiness:
hvc.happiness = 100
case segues.sadness:
hvc.happiness = 0
case segues.fourth:
hvc.happiness = 20
default:
hvc.happiness = 50
}
}
}
}
@IBAction func movenoth(sender: UIButton) {
performSegueWithIdentifier(segues.fourth, sender: nil)
}
}
| mit | a6941eb00f00d54dd97b767f4bff0775 | 26.212766 | 81 | 0.563722 | 5.157258 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_03/samplecode/iOS/RecChar/RecChar/ViewController.swift | 1 | 6131 | //
// ViewController.swift
// hogee
//
// Created by sonson on 2017/07/26.
// Copyright © 2017年 sonson. All rights reserved.
//
import UIKit
import CoreML
extension MLMultiArray {
var maxIndex: Int {
var max: Double = 0
var index = -1
for j in 0..<self.count {
let x = self[[NSNumber(value: j)]]
if max < x.doubleValue {
max = x.doubleValue
index = j
}
}
return index
}
func imageAsString(width: Int, height: Int) -> String {
var buffer = ""
for x in 0..<width {
for y in 0..<height {
let xx = NSNumber(value: x)
let yy = NSNumber(value: y)
buffer = buffer.appendingFormat("%02x", Int(self[[0, xx, yy]].doubleValue*255))
}
buffer = buffer.appendingFormat("\n")
}
return buffer
}
}
class ViewController: UIViewController {
let model = KerasMNIST()
static let width: Int = 28
static let height: Int = 28
@IBOutlet var imageView: UIImageView!
@IBOutlet var textLabel: UILabel!
var pixelBuffer32bit: [CUnsignedChar] = [CUnsignedChar](repeating: 0, count: ViewController.width * ViewController.height * 4)
private func creatCGImage(pointer: UnsafeMutableRawPointer?, width: Int, height: Int, bytesPerRow: Int) -> CGImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
.union(CGBitmapInfo.byteOrder32Little)
guard let context = CGContext(data: pointer, width: (width), height: (height), bitsPerComponent: 8, bytesPerRow: (bytesPerRow), space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return nil }
return context.makeImage()
}
func updateImage() {
guard let cgImage = creatCGImage(pointer: &pixelBuffer32bit, width: ViewController.width, height: ViewController.height, bytesPerRow: 4 * ViewController.width) else { return }
imageView.image = UIImage(cgImage: cgImage)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self.view)
if imageView.frame.contains(location) {
let locationInImageView = imageView.convert(location, from: self.view)
let x = locationInImageView.x / imageView.frame.size.width
let y = locationInImageView.y / imageView.frame.size.height
let ix = Int(x * CGFloat(ViewController.width))
let iy = Int(y * CGFloat(ViewController.height))
let w = 1
let l = ix - w > 0 ? ix - w : 0
let r = ix + w < ViewController.width ? ix + w : ViewController.width - 1
let t = iy - w > 0 ? iy - w : 0
let b = iy + w < ViewController.height ? iy + w : ViewController.height - 1
for xx in l..<r {
for yy in t..<b {
pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 0] = 255
pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 1] = 255
pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 2] = 255
pixelBuffer32bit[4 * xx + 4 * yy * ViewController.width + 3] = 255
}
}
updateImage()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
do {
let input = try MLMultiArray(shape: [1, NSNumber(value: ViewController.width), NSNumber(value: ViewController.height)], dataType: .double)
for x in 0..<ViewController.width {
for y in 0..<ViewController.height {
let xx = NSNumber(value: x)
let yy = NSNumber(value: y)
input[[0, xx, yy]] = NSNumber(value: Double(pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1]) / 255 )
}
}
print(input.imageAsString(width: ViewController.width, height: ViewController.height))
let result = try model.prediction(image: input)
let index = result.digit.maxIndex
textLabel.text = "\(index)"
} catch {
print(error)
}
for x in 0..<ViewController.width {
for y in 0..<ViewController.height {
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 0] = 255
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1] = 0
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 2] = 0
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 3] = 0
}
}
updateImage()
}
func testMNIST() {
do {
let count = 1000
var trueCount = 0
for i in 0..<count {
let label = try loadLabel(index: i)
let image = try loadImage(index: i)
let result = try model.prediction(image: image)
if label == result.digit.maxIndex {
trueCount += 1
}
}
print("\(Double(trueCount) / Double(count) * 100)")
} catch {
print(error)
}
}
override func viewDidLoad() {
super.viewDidLoad()
//testMNIST()
for x in 0..<ViewController.width {
for y in 0..<ViewController.height {
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 0] = 255
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 1] = 0
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 2] = 0
pixelBuffer32bit[4 * y + 4 * x * ViewController.width + 3] = 0
}
}
updateImage()
}
}
| mit | 8f5274ba3e206ac37a937c8532849ebe | 37.540881 | 207 | 0.542755 | 4.515844 | false | false | false | false |
rcach/Tasks | TODO/UserStoryListViewController.swift | 1 | 2258 | import Cocoa
class UserStoryListViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var tableView: NSTableView!
// TODO: Make this an unowned reference once you can specify memory management on Swift protocol object references.
var navigatorOptional: Navigator?
var userStories = [UserStory]()
override func viewDidLoad() {
reload()
}
func reload() {
clearSelection()
userStories.removeAll(keepCapacity: true)
tableView.reloadData()
loadDataFromJIRA()
}
func clearSelection() {
tableView.deselectAll(self)
}
func disableList() {
tableView.enabled = false
}
func enableList() {
tableView.enabled = true
}
func loadDataFromJIRA() {
navigatorOptional?.disableNavigation()
disableList()
getUserStories() { result in
// TODO: Handle this better.
if self.view.superview == nil { return }
self.navigatorOptional?.enableNavigation()
self.enableList()
switch result {
case let .Error(error):
// TODO: Indicate error to user.
println(error)
case let .Value(userStories):
self.userStories = userStories
self.tableView.reloadData()
}
}
}
}
extension UserStoryListViewController {
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView!) -> Int {
return userStories.count
}
// MARK: NSTableViewDelegate
func tableView(tableView: NSTableView!, viewForTableColumn tableColumn: NSTableColumn!, row: Int) -> NSView! {
if let reusableCellView = tableView.makeViewWithIdentifier(tableColumn.identifier, owner: self) as? NSTableCellView {
var titleTextField = reusableCellView.textField
titleTextField.stringValue = userStories[row].summary
return reusableCellView
}
return nil
}
func tableView(tableView: NSTableView!, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet!) -> NSIndexSet! {
if let navigator = navigatorOptional {
if proposedSelectionIndexes.count > 0 {
navigator.navigateToUserStoryTaskList(userStories[proposedSelectionIndexes.firstIndex])
}
}
return proposedSelectionIndexes
}
}
| apache-2.0 | 4e1df0de6fdbbc2a9d69b4de9154ab26 | 27.225 | 134 | 0.702391 | 5.214781 | false | false | false | false |
josherick/DailySpend | DailySpend/Expense+CoreDataClass.swift | 1 | 11366 | //
// Expense+CoreDataClass.swift
// DailySpend
//
// Created by Josh Sherick on 3/22/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import Foundation
import CoreData
@objc(Expense)
class Expense: NSManagedObject {
func json(jsonIds: [NSManagedObjectID: Int]) -> [String: Any]? {
var jsonObj = [String: Any]()
if let amount = amount {
let num = amount as NSNumber
jsonObj["amount"] = num
} else {
Logger.debug("couldn't unwrap amount in Expense")
return nil
}
if let shortDescription = shortDescription {
jsonObj["shortDescription"] = shortDescription
} else {
Logger.debug("couldn't unwrap shortDescription in Expense")
return nil
}
if let notes = notes {
jsonObj["notes"] = notes
}
if let transactionDay = transactionDay {
let num = transactionDay.start.gmtDate.timeIntervalSince1970 as NSNumber
jsonObj["transactionDate"] = num
} else {
Logger.debug("couldn't unwrap transactionDate in Expense")
return nil
}
if let dateCreated = dateCreated {
let num = dateCreated.timeIntervalSince1970 as NSNumber
jsonObj["dateCreated"] = num
} else {
Logger.debug("couldn't unwrap dateCreated in Expense")
return nil
}
if let imgs = sortedImages {
var jsonImgs = [[String: Any]]()
for image in imgs {
if let jsonImg = image.json() {
jsonImgs.append(jsonImg)
} else {
Logger.debug("couldn't unwrap jsonImg in Expense")
return nil
}
}
jsonObj["images"] = jsonImgs
}
if let goal = goal {
var goalJsonIds = [Int]()
if let jsonId = jsonIds[goal.objectID] {
goalJsonIds.append(jsonId)
} else {
Logger.debug("a goal didn't have an associated jsonId in Expense")
return nil
}
jsonObj["goal"] = goalJsonIds
} else {
Logger.debug("couldn't unwrap goal in Expense")
return nil
}
return jsonObj
}
func serialize(jsonIds: [NSManagedObjectID: Int]) -> Data? {
if let jsonObj = self.json(jsonIds: jsonIds) {
let serialization = try? JSONSerialization.data(withJSONObject: jsonObj)
return serialization
}
return nil
}
class func create(context: NSManagedObjectContext,
json: [String: Any],
jsonIds: [Int: NSManagedObjectID]) -> Expense? {
let expense = Expense(context: context)
if let amount = json["amount"] as? NSNumber {
let decimal = Decimal(amount.doubleValue)
if decimal <= 0 {
Logger.debug("amount less than 0 in Expense")
return nil
}
expense.amount = decimal
} else {
Logger.debug("couldn't unwrap amount in Expense")
return nil
}
if let shortDescription = json["shortDescription"] as? String {
if shortDescription.count == 0 {
Logger.debug("shortDescription empty in Expense")
return nil
}
expense.shortDescription = shortDescription
} else {
Logger.debug("couldn't unwrap shortDescription in Expense")
return nil
}
if let notes = json["notes"] as? String {
expense.notes = notes
}
if let jsonImgs = json["images"] as? [[String: Any]] {
for jsonImg in jsonImgs {
if let image = Image.create(context: context, json: jsonImg) {
image.expense = expense
} else {
Logger.debug("couldn't create image in Expense")
return nil
}
}
}
if let transactionDate = json["transactionDate"] as? NSNumber {
let date = Date(timeIntervalSince1970: transactionDate.doubleValue)
let calDay = CalendarDay(dateInDay: GMTDate(date));
if date != calDay.start.gmtDate {
Logger.debug("transactionDate after today in Expense")
return nil
}
expense.transactionDay = calDay
} else {
Logger.debug("coulnd't unwrap transactionDate in Expense")
return nil
}
if let dateCreated = json["dateCreated"] as? NSNumber {
let date = Date(timeIntervalSince1970: dateCreated.doubleValue)
if date > Date() {
Logger.debug("dateCreated after today in Expense")
return nil
}
expense.dateCreated = date
} else {
Logger.debug("couldn't unwrap dateCreated in Expense")
return nil
}
if let goalJsonIds = json["goals"] as? Array<Int> {
if goalJsonIds.count > 1 {
Logger.debug("there were multiple goals associated with an Expense")
return nil
}
for goalJsonId in goalJsonIds {
if let objectID = jsonIds[goalJsonId],
let goal = context.object(with: objectID) as? Goal {
expense.goal = goal
} else {
Logger.debug("a goal didn't have an associated objectID in Expense")
return nil
}
}
} else {
Logger.debug("couldn't unwrap goals in Expense")
return nil
}
return expense
}
/**
* Accepts all members of Expense. If the passed variables, attached to
* corresponding variables on an Expense object, will form a valid
* object, this function will assign the passed variables to this object
* and return `(valid: true, problem: nil)`. Otherwise, this function will
* return `(valid: false, problem: ...)` with problem set to a user
* readable string describing why this adjustment wouldn't be valid.
*/
func propose(
amount: Decimal?? = nil,
shortDescription: String?? = nil,
transactionDay: CalendarDay?? = nil,
notes: String?? = nil,
dateCreated: Date?? = nil,
goal: Goal? = nil
) -> (valid: Bool, problem: String?) {
let _amount = amount ?? self.amount
let _shortDescription = shortDescription ?? self.shortDescription
let _transactionDay = transactionDay ?? self.transactionDay
let _notes = notes ?? self.notes
let _dateCreated = dateCreated ?? self.dateCreated
let _goal = goal ?? self.goal
if _amount == nil || _amount! == 0 {
return (false, "This expense must have an amount specified.")
}
if _transactionDay == nil {
return (false, "This expense must have a transaction date.")
}
if _dateCreated == nil {
return (false, "The expense must have a date created.")
}
if _goal == nil {
return (false, "This expense must be associated with a goal.")
}
if _goal!.start != nil && _transactionDay!.start.gmtDate < _goal!.start!.gmtDate {
return (false, "This expense must be after it's associated goal's start date.")
}
if _goal!.exclusiveEnd != nil && _transactionDay!.start.gmtDate < _goal!.exclusiveEnd!.gmtDate {
return (false, "This expense must be before it's associated goal's end date.")
}
if _goal!.isRecurring {
let mostRecentPeriodEnd = _goal!.mostRecentPeriod()?.end?.gmtDate
if mostRecentPeriodEnd == nil ||
_transactionDay!.start.gmtDate > mostRecentPeriodEnd! {
return (false, "This expense must be created no later than end the most recent period for this goal.")
}
}
self.amount = _amount
self.shortDescription = _shortDescription
self.transactionDay = _transactionDay
self.notes = _notes
self.dateCreated = _dateCreated
self.goal = _goal
return (true, nil)
}
class func get(context: NSManagedObjectContext,
predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil,
fetchLimit: Int = 0) -> [Expense]? {
let fetchRequest: NSFetchRequest<Expense> = Expense.fetchRequest()
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
fetchRequest.fetchLimit = fetchLimit
let expenseResults = try? context.fetch(fetchRequest)
return expenseResults
}
// Accessor functions (for Swift 3 classes)
var amount: Decimal? {
get {
return amount_ as Decimal?
}
set {
if newValue != nil {
amount_ = NSDecimalNumber(decimal: newValue!)
} else {
amount_ = nil
}
}
}
var transactionDay: CalendarDay? {
get {
if let date = transactionDate_ {
return CalendarDay(dateInDay: GMTDate(date as Date))
} else {
return nil
}
}
set {
if newValue != nil {
transactionDate_ = newValue!.start.gmtDate as NSDate
} else {
transactionDate_ = nil
}
}
}
var dateCreated: Date? {
get {
return dateCreated_ as Date?
}
set {
if newValue != nil {
dateCreated_ = newValue! as NSDate
} else {
dateCreated_ = nil
}
}
}
var shortDescription: String? {
get {
return shortDescription_
}
set {
shortDescription_ = newValue
}
}
var notes: String? {
get {
return notes_
}
set {
notes_ = newValue
}
}
/**
* Expenses can currently only be associated with one goal. This is that
* goal, if it exists.
*/
var goal: Goal? {
get {
return goal_
}
set {
goal_ = newValue
}
}
/**
* `images` sorted in a deterministic way.
*/
var sortedImages: [Image]? {
if let img = images {
return img.sorted(by: { $0.dateCreated! < $1.dateCreated! })
} else {
return nil
}
}
var images: Set<Image>? {
get {
return images_ as! Set?
}
set {
if newValue != nil {
images_ = NSSet(set: newValue!)
} else {
images_ = nil
}
}
}
}
| mit | bf44ac48fba0545ee4bbd2891892ca19 | 30.569444 | 118 | 0.511835 | 5.330675 | false | false | false | false |
335g/FingerTree | Example1.playground/Contents.swift | 1 | 2522 |
import FingerTree
//
// Example(1) Priority Queue
// reference (https://hackage.haskell.org/package/fingertree-0.1.1.0/docs/Data-PriorityQueue-FingerTree.html)
//
enum Ent<V: Equatable>: Equatable {
case Entry(UInt, V)
}
func == <V: Equatable> (lhs: Ent<V>, rhs: Ent<V>) -> Bool {
switch (lhs, rhs) {
case let (.Entry(p1, v1), .Entry(p2, v2)):
return p1 == p2 && v1 == v2
}
}
enum Prio<V: Equatable>: Equatable {
case NoPriority
case Priority(UInt, V)
}
func == <V: Equatable> (lhs: Prio<V>, rhs: Prio<V>) -> Bool {
switch (lhs, rhs) {
case (.NoPriority, .NoPriority):
return true
case let (.Priority(p1, v1), .Priority(p2, v2)):
return p1 == p2 && v1 == v2
default:
return false
}
}
extension Prio: Monoid {
static var mempty: Prio { return .NoPriority }
func mappend(other: Prio) -> Prio {
switch (self, other) {
case (.NoPriority, .NoPriority):
return .NoPriority
case (.NoPriority, .Priority(_)):
return other
case (.Priority(_), .NoPriority):
return self
case let (.Priority(x, _), .Priority(y, _)):
if x <= y {
return self
}else {
return other
}
}
}
}
extension Ent: Measurable {
typealias MeasuredValue = Prio<V>
func measure() -> Prio<V> {
switch self {
case let .Entry(p, v):
return .Priority(p, v)
}
}
}
class PriorityQueue<V: Equatable> {
var tree: FingerTree<Prio<V>, Ent<V>>
init(_ ent: Ent<V>){
self.tree = FingerTree.single(ent)
}
func add(ent: Ent<V>) {
self.tree = tree |> ent
}
var highestPriorityEntry: Ent<V>? {
switch self.measure() {
case .NoPriority:
return nil
case let .Priority(p, v):
return .Entry(p, v)
}
}
// var minView: (V, PriorityQueue)? {
//
// }
var minViewWithKey: ((UInt, V), PriorityQueue)? {
switch tree {
case .Empty:
return nil
default:
let prio = tree.measure()
switch prio {
case let .Priority(k, v):
switch tree.split({ p in
switch p {
case .NoPriority:
return false
case let .Priority(k_, _):
return k_ <= k
}
})
}
}
}
}
extension PriorityQueue: Measurable {
typealias MeasuredValue = Prio<V>
func measure() -> Prio<V> {
return tree.measure()
}
}
let queue = PriorityQueue(.Entry(100, "a"))
queue.add(.Entry(120, "b"))
queue.add(.Entry(140, "c"))
queue.highestPriorityEntry
queue.add(.Entry(80, "d"))
queue.add(.Entry(90, "e"))
queue.highestPriorityEntry
switch queue.tree {
case let .Deep(_, pre, m, suf):
pre
m
suf
default:
()
}
//queue.pull()
queue.highestPriorityEntry
| mit | dd5a2ae363807b284be25e2974bfa5a6 | 17.014286 | 111 | 0.616574 | 2.783664 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Home/Wallpapers/v1/UI/WallpaperSelectorViewModel.swift | 2 | 8419 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
private struct WallpaperSelectorItem {
let wallpaper: Wallpaper
let collection: WallpaperCollection
}
public enum WallpaperSelectorError: Error {
case itemNotFound
}
class WallpaperSelectorViewModel {
enum WallpaperSelectorLayout: Equatable {
case compact
case regular
// The maximum number of items to display in the whole section
var maxItemsToDisplay: Int {
switch self {
case .compact: return 6
case .regular: return 8
}
}
// The maximum number of items to display per row
var itemsPerRow: Int {
switch self {
case .compact: return 3
case .regular: return 4
}
}
// The maximum number of seasonal items to display
var maxNumberOfSeasonalItems: Int {
switch self {
case .compact: return 3
case .regular: return 5
}
}
}
private var wallpaperManager: WallpaperManagerInterface
private var availableCollections: [WallpaperCollection]
private var wallpaperItems = [WallpaperSelectorItem]()
var openSettingsAction: (() -> Void)
var sectionLayout: WallpaperSelectorLayout = .compact // We use the compact layout as default
var selectedIndexPath: IndexPath?
var numberOfWallpapers: Int {
return wallpaperItems.count
}
init(wallpaperManager: WallpaperManagerInterface = WallpaperManager(), openSettingsAction: @escaping (() -> Void)) {
self.wallpaperManager = wallpaperManager
self.availableCollections = wallpaperManager.availableCollections
self.openSettingsAction = openSettingsAction
setupWallpapers()
selectedIndexPath = initialSelectedIndexPath
}
func updateSectionLayout(for traitCollection: UITraitCollection) {
if traitCollection.horizontalSizeClass == .compact {
sectionLayout = .compact
} else {
sectionLayout = .regular
}
setupWallpapers()
}
func cellViewModel(for indexPath: IndexPath) -> WallpaperCellViewModel? {
guard let wallpaperItem = wallpaperItems[safe: indexPath.row] else {
return nil
}
return cellViewModel(for: wallpaperItem.wallpaper,
collectionType: wallpaperItem.collection.type,
number: indexPath.row)
}
func downloadAndSetWallpaper(at indexPath: IndexPath, completion: @escaping (Result<Void, Error>) -> Void) {
guard let wallpaperItem = wallpaperItems[safe: indexPath.row] else {
completion(.failure(WallpaperSelectorError.itemNotFound))
return
}
let wallpaper = wallpaperItem.wallpaper
let setWallpaperBlock = { [weak self] in
self?.updateCurrentWallpaper(for: wallpaperItem) { result in
if case .success = result {
self?.selectedIndexPath = indexPath
}
completion(result)
}
}
if wallpaper.needsToFetchResources {
wallpaperManager.fetchAssetsFor(wallpaper) { result in
switch result {
case .success:
setWallpaperBlock()
case .failure:
completion(result)
}
}
} else {
setWallpaperBlock()
}
}
func sendImpressionTelemetry() {
TelemetryWrapper.recordEvent(category: .action,
method: .view,
object: .onboardingWallpaperSelector,
value: nil,
extras: nil)
}
func sendDismissImpressionTelemetry() {
TelemetryWrapper.recordEvent(category: .action,
method: .close,
object: .onboardingWallpaperSelector,
value: nil,
extras: nil)
}
func removeAssetsOnDismiss() {
wallpaperManager.removeUnusedAssets()
}
}
private extension WallpaperSelectorViewModel {
var initialSelectedIndexPath: IndexPath? {
if let index = wallpaperItems.firstIndex(where: {$0.wallpaper == wallpaperManager.currentWallpaper}) {
return IndexPath(row: index, section: 0)
}
return nil
}
func setupWallpapers() {
wallpaperItems = []
let classicCollection = availableCollections.first { $0.type == .classic }
let seasonalCollection = availableCollections.first { $0.type == .limitedEdition }
let seasonalItems = collectWallpaperItems(for: seasonalCollection,
maxNumber: sectionLayout.maxNumberOfSeasonalItems)
let maxNumberOfClassic = sectionLayout.maxItemsToDisplay - seasonalItems.count
let classicItems = collectWallpaperItems(for: classicCollection,
maxNumber: maxNumberOfClassic)
wallpaperItems.append(contentsOf: classicItems)
wallpaperItems.append(contentsOf: seasonalItems)
}
func collectWallpaperItems(for collection: WallpaperCollection?, maxNumber: Int) -> [WallpaperSelectorItem] {
guard let collection = collection else { return [] }
var wallpapers = [WallpaperSelectorItem]()
for wallpaper in collection.wallpapers {
if wallpapers.count < maxNumber {
wallpapers.append(WallpaperSelectorItem(wallpaper: wallpaper,
collection: collection))
} else {
break
}
}
return wallpapers
}
func cellViewModel(for wallpaper: Wallpaper,
collectionType: WallpaperCollectionType,
number: Int
) -> WallpaperCellViewModel {
let a11yId = "\(AccessibilityIdentifiers.Onboarding.Wallpaper.card)_\(number)"
var a11yLabel: String
switch collectionType {
case .classic:
a11yLabel = "\(String.Onboarding.ClassicWallpaper) \(number + 1)"
case .limitedEdition:
a11yLabel = "\(String.Onboarding.LimitedEditionWallpaper) \(number + 1)"
}
let cellViewModel = WallpaperCellViewModel(image: wallpaper.thumbnail,
a11yId: a11yId,
a11yLabel: a11yLabel)
return cellViewModel
}
func updateCurrentWallpaper(for wallpaperItem: WallpaperSelectorItem,
completion: @escaping (Result<Void, Error>) -> Void) {
wallpaperManager.setCurrentWallpaper(to: wallpaperItem.wallpaper) { [weak self] result in
guard let extra = self?.telemetryMetadata(for: wallpaperItem) else {
completion(result)
return
}
TelemetryWrapper.recordEvent(category: .action,
method: .tap,
object: .onboardingWallpaperSelector,
value: .wallpaperSelected,
extras: extra)
completion(result)
}
}
func telemetryMetadata(for item: WallpaperSelectorItem) -> [String: String] {
var metadata = [String: String]()
metadata[TelemetryWrapper.EventExtraKey.wallpaperName.rawValue] = item.wallpaper.id
let wallpaperTypeKey = TelemetryWrapper.EventExtraKey.wallpaperType.rawValue
switch item.wallpaper.type {
case .defaultWallpaper:
metadata[wallpaperTypeKey] = "default"
case .other:
switch item.collection.type {
case .classic:
metadata[wallpaperTypeKey] = item.collection.type.rawValue
case .limitedEdition:
metadata[wallpaperTypeKey] = item.collection.id
}
}
return metadata
}
}
| mpl-2.0 | 430fa29762bf8f06c4d54706c78b5c91 | 35.133047 | 120 | 0.581779 | 5.875087 | false | false | false | false |
sammyd/VT_InAppPurchase | prototyping/GreenGrocer/GreenGrocer/ShoppingListViewController.swift | 13 | 3476 | /*
* Copyright (c) 2015 Razeware LLC
*
* 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 ShoppingListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var nameLabel: MultilineLabelThatWorks!
@IBOutlet weak var dateLabel: MultilineLabelThatWorks!
@IBOutlet weak var totalCostLabel: UILabel!
var dataStore : DataStore?
var shoppingList : ShoppingList? {
didSet {
updateViewForShoppingList()
}
}
private static var dateFormatter : NSDateFormatter = {
let df = NSDateFormatter()
df.dateStyle = .ShortStyle
return df
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
configureTableView(tableView)
updateViewForShoppingList()
}
}
extension ShoppingListViewController {
private func updateViewForShoppingList() {
if let shoppingList = shoppingList {
nameLabel?.text = shoppingList.name
dateLabel?.text = self.dynamicType.dateFormatter.stringFromDate(shoppingList.date)
totalCostLabel?.text = "$\(shoppingList.products.reduce(0){ $0 + $1.price })"
}
tableView?.reloadData()
}
private func configureTableView(tableView: UITableView) {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.dataSource = self
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView?.backgroundColor = UIColor.clearColor()
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 49, right: 0)
tableView.separatorStyle = .None
}
}
extension ShoppingListViewController : UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shoppingList?.products.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath)
if let cell = cell as? ProductTableViewCell {
cell.product = shoppingList?.products[indexPath.row]
}
cell.backgroundView?.backgroundColor = UIColor.clearColor()
cell.backgroundColor = UIColor.clearColor()
cell.contentView.backgroundColor = UIColor.clearColor()
return cell
}
} | mit | ee8b8e6ffef4b54e2dd4747d468d39de | 35.6 | 107 | 0.742808 | 5.044993 | false | false | false | false |
MatrixHero/FlowSlideMenu | FlowSlideMenuCore/LLFlowSlideMenuVC.swift | 1 | 20670 | //
// LLFlowSlideMenuVC
//
// Created by LL on 15/10/31.
// Copyright © 2015 LL. All rights reserved.
//
import UIKit
import QuartzCore
public class LLFlowSlideMenuVC : UIViewController, UIGestureRecognizerDelegate ,LLFlowCurveViewDelegate
{
public enum SlideAction {
case Open
case Close
}
struct PanInfo {
var action: SlideAction
var shouldBounce: Bool
var velocity: CGFloat
}
// MARK: -
// MARK: parms
public var leftViewController: UIViewController?
public var mainViewController: UIViewController?
public var opacityView = UIView()
public var mainContainerView = UIView()
public var leftContainerView = LLFlowCurveView()
public var leftPanGesture: UIPanGestureRecognizer?
public var leftTapGetsture: UITapGestureRecognizer?
private var curContext = 0
// MARK: -
// MARK: lifecycle
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public convenience init(mainViewController: UIViewController,leftViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
initView()
self.leftContainerView.addObserver(self, forKeyPath: "frame", options: .New, context: &curContext)
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &curContext {
if let newValue : CGRect = change?[NSKeyValueChangeNewKey]?.CGRectValue{
self.leftContainerView.updatePointKVO(self.leftContainerView.frame.size.width + newValue.origin.x, orientation: Orientation.Left)
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
leftContainerView.hidden = true
coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.closeLeftNonAnimation()
self.leftContainerView.hidden = false
if self.leftPanGesture != nil && self.leftPanGesture != nil {
self.removeLeftGestures()
self.addLeftGestures()
}
})
}
public override func viewWillLayoutSubviews() {
setUpViewController(mainContainerView, targetViewController: mainViewController)
setUpViewController(leftContainerView, targetViewController: leftViewController,slideview: true)
}
deinit {
self.leftContainerView.removeObserver(self, forKeyPath: "frame", context: &curContext)
}
// MARK: -
// MARK: private funs
func initView() {
mainContainerView = UIView(frame: view.bounds)
mainContainerView.backgroundColor = UIColor.clearColor()
mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
view.insertSubview(mainContainerView, atIndex: 0)
var opacityframe: CGRect = view.bounds
let opacityOffset: CGFloat = 0
opacityframe.origin.y = opacityframe.origin.y + opacityOffset
opacityframe.size.height = opacityframe.size.height - opacityOffset
opacityView = UIView(frame: opacityframe)
opacityView.backgroundColor = FlowSlideMenuOptions.opacityViewBackgroundColor
opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
opacityView.layer.opacity = 0.0
view.insertSubview(opacityView, atIndex: 1)
var leftFrame: CGRect = view.bounds
leftFrame.size.width = FlowSlideMenuOptions.leftViewWidth + FlowCurveOptions.waveMargin
leftFrame.origin.x = leftMinOrigin();
let leftOffset: CGFloat = 0
leftFrame.origin.y = leftFrame.origin.y + leftOffset
leftFrame.size.height = leftFrame.size.height - leftOffset
leftContainerView = LLFlowCurveView(frame: leftFrame)
leftContainerView.backgroundColor = UIColor.clearColor()
leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
leftContainerView.delegate = self
view.insertSubview(leftContainerView, atIndex: 2)
addLeftGestures()
}
private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) {
if let viewController = targetViewController {
addChildViewController(viewController)
viewController.view.frame = targetView.bounds
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func setUpViewController(targetView: UIView, targetViewController: UIViewController?, slideview:Bool) {
if let viewController = targetViewController {
addChildViewController(viewController)
if(slideview)
{
viewController.view.frame = CGRectMake(0,0,slideViewWidth(),targetView.bounds.height)
}else
{
viewController.view.frame = targetView.bounds
}
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func removeViewController(viewController: UIViewController?) {
if let _viewController = viewController {
_viewController.willMoveToParentViewController(nil)
_viewController.view.removeFromSuperview()
_viewController.removeFromParentViewController()
}
}
private func leftMinOrigin() -> CGFloat {
return -FlowSlideMenuOptions.leftViewWidth - FlowCurveOptions.waveMargin
}
private func slideViewWidth() -> CGFloat {
return FlowSlideMenuOptions.leftViewWidth
}
private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{
var leftBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
let bezelWidth: CGFloat = FlowSlideMenuOptions.leftBezelWidth
CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(leftBezelRect, point)
}
private func addLeftGestures() {
if (leftViewController != nil) {
if leftPanGesture == nil {
leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:")
leftPanGesture!.delegate = self
view.addGestureRecognizer(leftPanGesture!)
}
}
}
private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo {
let thresholdVelocity: CGFloat = 1000.0
let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + FlowSlideMenuOptions.pointOfNoReturnWidth
let leftOrigin: CGFloat = leftContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open;
if velocity.x >= thresholdVelocity {
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if velocity.x <= (-1.0 * thresholdVelocity) {
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
public func isTagetViewController() -> Bool {
// Function to determine the target ViewController
// Please to override it if necessary
return true
}
private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{
return isLeftOpen() || FlowSlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point)
}
private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(leftContainerView.frame, point)
}
private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect {
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
let minOrigin: CGFloat = leftMinOrigin()
let maxOrigin: CGFloat = 0.0
var newFrame: CGRect = toFrame
if newOrigin < minOrigin {
newOrigin = minOrigin
} else if newOrigin > maxOrigin {
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func setOpenWindowLevel() {
if (FlowSlideMenuOptions.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelStatusBar + 1
}
})
}
}
private func setCloseWindowLebel() {
if (FlowSlideMenuOptions.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelNormal
}
})
}
}
public func isLeftOpen() -> Bool {
return leftContainerView.frame.origin.x == 0.0
}
public func isLeftHidden() -> Bool {
return leftContainerView.frame.origin.x <= leftMinOrigin()
}
public func closeLeftWithVelocity(velocity: CGFloat) {
leftContainerView.close()
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = 0.0
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.enableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
strongSelf.leftViewController?.view.alpha = 0
}
}
}
public override func openLeft (){
setOpenWindowLevel()
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated:false)
openLeftFakeAnimation()
self.leftContainerView.openAll()
}
public func updatePointTimer()
{
print(self.leftContainerView.frame.origin.x)
}
public override func closeLeft (){
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
closeLeftWithVelocity(0.0)
setCloseWindowLebel()
}
public func openLeftFakeAnimation()
{
var frame = leftContainerView.frame;
frame.origin.x = 0;
self.leftContainerView.frame = frame
self.opacityView.layer.opacity = Float(FlowSlideMenuOptions.contentViewOpacity)
let duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(FlowSlideMenuOptions.contentViewScale, FlowSlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.disableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
}
public func openLeftWithVelocity(velocity: CGFloat) {
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = 0.0
var frame = leftContainerView.frame;
frame.origin.x = finalXOrigin;
var duration: NSTimeInterval = Double(FlowSlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = Float(FlowSlideMenuOptions.contentViewOpacity)
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(FlowSlideMenuOptions.contentViewScale, FlowSlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.disableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
self.leftContainerView.open()
}
private func applyLeftContentViewScale() {
let openedLeftRatio: CGFloat = getOpenedLeftRatio()
let scale: CGFloat = 1.0 - ((1.0 - FlowSlideMenuOptions.contentViewScale) * openedLeftRatio);
mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func getOpenedLeftRatio() -> CGFloat {
let width: CGFloat = leftContainerView.frame.size.width
let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin()
return currentPosition / width
}
// MARK: -
// MARK: public funs
public func removeLeftGestures() {
if leftPanGesture != nil {
view.removeGestureRecognizer(leftPanGesture!)
leftPanGesture = nil
}
}
public func closeLeftNonAnimation(){
setCloseWindowLebel()
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
leftContainerView.frame = frame
opacityView.layer.opacity = 0.0
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
enableContentInteraction()
self.leftContainerView.animating = false
}
private func disableContentInteraction() {
mainContainerView.userInteractionEnabled = false
}
private func enableContentInteraction() {
mainContainerView.userInteractionEnabled = true
}
// MARK: -
// MARK: handleLeftPanGesture funs
struct LeftPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) {
if !isTagetViewController() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
LeftPanState.wasHiddenAtStartOfPan = isLeftHidden()
LeftPanState.wasOpenAtStartOfPan = isLeftOpen()
self.leftContainerView.start()
LeftPanState.frameAtStartOfPan = leftContainerView.frame
LeftPanState.startPointOfPan = panGesture.locationInView(self.view)
leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true)
setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
let translation: CGPoint = panGesture.translationInView(panGesture.view)
leftContainerView.updatePoint(CGPointMake(translation.x, translation.y + LeftPanState.startPointOfPan.y), orientation: Orientation.Left)
leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan)
applyLeftContentViewScale()
case UIGestureRecognizerState.Ended:
let velocity:CGPoint = panGesture.velocityInView(panGesture.view)
let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(true, animated: true)
}
openLeftWithVelocity(panInfo.velocity)
} else {
if LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(false, animated: true)
}
closeLeftWithVelocity(panInfo.velocity)
setCloseWindowLebel()
}
default:
break
}
}
// MARK: -
// MARK: UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
let point: CGPoint = touch.locationInView(view)
if gestureRecognizer == leftPanGesture {
return slideLeftForGestureRecognizer(gestureRecognizer, point: point)
} else if gestureRecognizer == leftTapGetsture {
return isLeftOpen() && !isPointContainedWithinLeftRect(point)
}
return true
}
// MARK: -
// MARK: LLFlowCurveViewDelegate
public func flowViewStartAnimation(flow:LLFlowCurveView)
{
leftViewController?.view.alpha = 0.0
}
public func flowViewEndAnimation(flow:LLFlowCurveView)
{
UIView.animateWithDuration(0.3) { () -> Void in
self.leftViewController?.view.alpha = 1
}
}
}
// MARK: -
// MARK: UIViewController extension
extension UIViewController {
public func slideMenuController() -> LLFlowSlideMenuVC? {
var viewController: UIViewController? = self
while viewController != nil {
if viewController is LLFlowSlideMenuVC {
return viewController as? LLFlowSlideMenuVC
}
viewController = viewController?.parentViewController
}
return nil;
}
public func addLeftBarButtonWithImage(buttonImage: UIImage) {
let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft")
navigationItem.leftBarButtonItem = leftButton;
}
public func openLeft() {
slideMenuController()?.openLeft()
}
public func closeLeft() {
slideMenuController()?.closeLeft()
}
// Please specify if you want menu gesuture give priority to than targetScrollView
public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) {
guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else {
return
}
for recognizer in recognizers where recognizer is UIPanGestureRecognizer {
targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer)
}
}
} | mit | 1e474bc6e075a5942e7e47fe52e99dbe | 36.650273 | 164 | 0.642605 | 6.107861 | false | false | false | false |
twobitlabs/Nimble | Sources/Nimble/Matchers/PostNotification.swift | 27 | 2520 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
#if canImport(Darwin)
private var token: AnyObject?
#else
private var token: NSObjectProtocol?
#endif
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
// swiftlint:disable:next line_length
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] notification in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(notification)
}
}
deinit {
#if canImport(Darwin)
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
#else
if let token = self.token as? AnyObject {
self.notificationCenter.removeObserver(token)
}
#endif
}
}
private let mainThread = pthread_self()
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter = .default)
-> Predicate<Any>
where T: Matcher, T.ValueType == [Notification]
{
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let failureMessage = FailureMessage()
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return PredicateResult(bool: match, message: failureMessage.toExpectationMessage())
}
}
| apache-2.0 | 3a30de0e3abef04db9b150056ce2f196 | 34.492958 | 125 | 0.66746 | 5.502183 | false | false | false | false |
nvzqz/Sage | Benchmark/main.swift | 1 | 1449 | import Foundation
extension Int {
static func random(from value: Int) -> Int {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
return Int(arc4random_uniform(UInt32(value)))
#elseif os(Linux)
srand(.init(time(nil)))
return Int(rand() % .init(value))
#else
fatalError("Unknown OS")
#endif
}
}
extension Array {
var random: Element? {
return !self.isEmpty ? self[.random(from: count)] : nil
}
}
var info = [(time: Double, count: Double)]()
for _ in 1...20 {
var count = 0.0
let game = Game()
#if swift(>=3)
let start = Date()
#else
let start = NSDate()
#endif
do {
while let move = game.availableMoves().random {
count += 1
try game.execute(uncheckedMove: move)
}
} catch {
print(error)
break
}
#if swift(>=3)
let time = Date().timeIntervalSince(start)
#else
let time = NSDate().timeIntervalSinceDate(start)
#endif
info.append((time, count))
}
let perSec = info.map(/)
let averageSecs = perSec.reduce(0) { $0 + $1 } / Double(info.count)
let averageMoves = info.reduce(0) { $0 + $1.1 } / Double(info.count)
let multiplier = 1 / (info.reduce(0) { $0 + $1.0 } / Double(info.count))
print("Benchmark: 1 move in \(averageSecs) seconds")
print("Benchmark: \(averageMoves * multiplier) moves in 1 seconds")
| apache-2.0 | 9298170137ac892ce9f0fb61410a6c5a | 23.559322 | 72 | 0.559696 | 3.534146 | false | false | false | false |
krevis/MIDIApps | Applications/SysExLibrarian/RecordController.swift | 1 | 3844 | /*
Copyright (c) 2002-2021, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Cocoa
class RecordController: NSObject {
init(mainWindowController: MainWindowController, midiController: MIDIController) {
self.mainWindowController = mainWindowController
self.midiController = midiController
super.init()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: API for main window controller
func beginRecording() {
guard let window = mainWindowController?.window else { return }
if topLevelObjects == nil {
guard Bundle.main.loadNibNamed(self.nibName, owner: self, topLevelObjects: &topLevelObjects) else { fatalError("couldn't load nib") }
}
progressIndicator.startAnimation(nil)
updateIndicators(status: MIDIController.MessageListenStatus(messageCount: 0, bytesRead: 0, totalBytesRead: 0))
window.beginSheet(sheetWindow, completionHandler: nil)
observeMIDIController()
tellMIDIControllerToStartRecording()
}
// MARK: Actions
@IBAction func cancelRecording(_ sender: Any?) {
midiController?.cancelMessageListen()
stopObservingMIDIController()
progressIndicator.stopAnimation(nil)
mainWindowController?.window?.endSheet(sheetWindow)
}
// MARK: To be implemented in subclasses
var nibName: String {
fatalError("must override in subclass")
}
func tellMIDIControllerToStartRecording() {
fatalError("must override in subclass")
}
func updateIndicators(status: MIDIController.MessageListenStatus) {
fatalError("must override in subclass")
}
// MARK: May be overridden in subclasses
func observeMIDIController() {
NotificationCenter.default.addObserver(self, selector: #selector(readStatusChanged(_:)), name: .readStatusChanged, object: midiController)
}
func stopObservingMIDIController() {
NotificationCenter.default.removeObserver(self, name: .readStatusChanged, object: midiController)
}
// MARK: To be used by subclasses
weak var mainWindowController: MainWindowController?
weak var midiController: MIDIController?
@IBOutlet var sheetWindow: NSPanel!
@IBOutlet var progressIndicator: NSProgressIndicator!
@IBOutlet var progressMessageField: NSTextField!
@IBOutlet var progressBytesField: NSTextField!
lazy var waitingForSysexMessage = NSLocalizedString("Waiting for SysEx message…", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when waiting for sysex")
lazy var receivingSysexMessage = NSLocalizedString("Receiving SysEx message…", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when receiving sysex")
func updateIndicatorsImmediatelyIfScheduled() {
if scheduledProgressUpdate {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.privateUpdateIndicators), object: nil)
scheduledProgressUpdate = false
privateUpdateIndicators()
}
}
// MARK: Private
private var topLevelObjects: NSArray?
private var scheduledProgressUpdate = false
@objc private func privateUpdateIndicators() {
guard let status = midiController?.messageListenStatus else { return }
updateIndicators(status: status)
scheduledProgressUpdate = false
}
@objc private func readStatusChanged(_ notification: Notification) {
if !scheduledProgressUpdate {
self.perform(#selector(self.privateUpdateIndicators), with: nil, afterDelay: 5.0 / 60.0)
scheduledProgressUpdate = true
}
}
}
| bsd-3-clause | c9d13ec79b0374ed29bd17485347e69e | 31.820513 | 178 | 0.709375 | 5.423729 | false | false | false | false |
rxwei/cuda-swift | Sources/NVRTC/Error.swift | 1 | 1691 | //
// Error.swift
// CUDA
//
// Created by Richard Wei on 10/16/16.
//
//
import CNVRTC
public struct CompilerError : Error {
public enum Kind : UInt32 {
case outOfMemory = 1
case programCreationFailure = 2
case invalidInput = 3
case invalidProgram = 4
case invalidOption = 5
case compilationError = 6
case builtinOperationFailure = 7
case noNameExpressionsAfterCompilation = 8
case noLoweredNamesBeforeCompilation = 9
case nameExpressionNotValid = 10
case internalError = 11
/// Invalid text encoding of input
/// - Note: Not part of CUDA libraries
case invalidEncoding
init(_ nvrtcError: nvrtcResult) {
self.init(rawValue: nvrtcError.rawValue)!
}
}
public let kind: Kind
public let log: String?
public init(kind: Kind, log: String? = nil) {
self.kind = kind
self.log = log
}
init(result: nvrtcResult, log: String? = nil) {
self.kind = Kind(result)
self.log = log
}
}
extension CompilerError : CustomStringConvertible {
public var description: String {
return log ?? String(describing: kind)
}
}
@inline(__always)
func ensureSuccess(_ result: nvrtcResult) throws {
guard result == NVRTC_SUCCESS else {
throw CompilerError(kind: .init(result))
}
}
@inline(__always)
func forceSuccess(_ result: nvrtcResult) {
guard result == NVRTC_SUCCESS else {
fatalError(String(describing: CompilerError(kind: .init(result))))
}
}
prefix operator !!
@inline(__always)
prefix func !!(result: nvrtcResult) {
forceSuccess(result)
}
| mit | adab230493d8bc83e7d0edc85a53a671 | 20.679487 | 74 | 0.623891 | 4.12439 | false | false | false | false |
AugustRush/Stellar | Sources/UIView+AnimateBehavior.swift | 1 | 27197 | //
// UIView+AnimateBehavior.swift
// StellarDemo
//
// Created by AugustRush on 6/21/16.
// Copyright © 2016 August. All rights reserved.
//
import UIKit
extension UIView: DriveAnimateBehaviors {
func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior {
let mainType = type.mainType
let subType = type.subType
return createDynamicBehavior(withStyle: mainType, subType: subType, step: step)
}
//MARK: Basic
fileprivate func createDynamicBehavior(withStyle style: AnimationStyle, subType: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch subType {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .opacity(let o):
let from = self.layer.opacity
let to = o
let render = {(o: Float) in
self.layer.opacity = o
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .tintColor(let color):
let from = self.tintColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .textColor(let color):
switch self {
case let label as UILabel:
let from = label.textColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
label.textColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case let textView as UITextView:
let from = textView.textColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
textView.textColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
default:
fatalError("This object has not textColor property!")
}
default:
fatalError("Unsupport this animation type!")
}
return behavior
}
//MARK: Private methods
fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior {
let item = DynamicItemBasic(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.duration = step.duration
item.timingFunction = step.timing.easing()
item.delay = step.delay
item.repeatCount = step.repeatCount
item.autoreverses = step.autoreverses
return push
}
fileprivate func snapBehavior<T: Vectorial>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let snap = item.snapBehavior(point, damping: damping)
item.behavior = snap
return snap
}
fileprivate func attachmentBehavior<T: Vectorial>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency)
item.behavior = attachment
return attachment
}
fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItemGravity(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.magnitude = magnitude
return push
}
}
| mit | 0712a7b773370e0974cc686a03b4452d | 44.326667 | 163 | 0.53916 | 4.847772 | false | false | false | false |
ioswpf/CalendarKit | CalendarKit/CKExtensions.swift | 1 | 1330 | //
// CKExtensions.swift
// demo
//
// Created by wpf on 2017/3/20.
// Copyright © 2017年 wpf. All rights reserved.
//
import Foundation
extension Bundle {
class func ckBundle() -> Bundle? {
guard let path = Bundle(for: CalendarKit.self).path(forResource: "CalendarKit", ofType: "bundle") ,
let bundle = Bundle(path: path) else {
return nil
}
return bundle
}
class func ckLocalizeString(key: String, value: String? = nil) -> String? {
guard var language = NSLocale.preferredLanguages.first else {
return nil
}
if language.hasPrefix("en") {
language = "en"
} else if language.hasPrefix("zh") {
if language.range(of: "Hans") != nil {
language = "zh-Hans"
} else {
language = "zh-Hant"
}
} else {
language = "en"
}
guard let path = Bundle.ckBundle()?.path(forResource: language, ofType: "lproj") ,
let bundle = Bundle(path: path) else {
return nil
}
let v = bundle.localizedString(forKey: key, value: value, table: nil)
return Bundle.main.localizedString(forKey: key, value: v, table: nil)
}
}
| mit | 3cc3e830b409ea48182451d0cde5640b | 24.519231 | 107 | 0.522984 | 4.280645 | false | false | false | false |
NikolaiRuhe/SwiftDigest | SwiftDigestTests/MD5DigestTests.swift | 1 | 2599 | import SwiftDigest
import XCTest
class MD5Tests: XCTestCase {
func testEmpty() {
XCTAssertEqual(
Data().md5,
MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")
)
}
func testData() {
XCTAssertEqual(
MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")?.data,
Data([212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126,])
)
}
func testBytes() {
XCTAssertEqual(
"\(MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!.bytes)",
"(212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126)"
)
}
func testFox1() {
let input = "The quick brown fox jumps over the lazy dog"
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "9e107d9d372bb6826bd81d3542a419d6")
)
}
func testFox2() {
let input = "The quick brown fox jumps over the lazy dog."
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "e4d909c290d0fb1ca068ffaddf22cbd0")
)
}
func testTwoFooterChunks() {
let input = Data(count: 57)
XCTAssertEqual(
input.md5,
MD5Digest(rawValue: "ab9d8ef2ffa9145d6c325cefa41d5d4e")
)
}
func test4KBytes() {
var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100)
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "7052292b1c02ae4b0b35fabca4fbd487")
)
}
func test4MBytes() {
var input = String(repeating: "The quick brown fox jumps over the lazy dog.", count: 100000)
XCTAssertEqual(
input.utf8.md5,
MD5Digest(rawValue: "f8a4ffa8b1c902f072338caa1e4482ce")
)
}
func testRecursive() {
XCTAssertEqual(
"".utf8.md5.description.utf8.md5.description.utf8.md5.description.utf8.md5,
MD5Digest(rawValue: "5a8dccb220de5c6775c873ead6ff2e43")
)
}
func testEncoding() {
let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!
let json = String(bytes: try! JSONEncoder().encode([sut]), encoding: .utf8)!
XCTAssertEqual(json, "[\"\(sut)\"]")
}
func testDecoding() {
let sut = MD5Digest(rawValue: "d41d8cd98f00b204e9800998ecf8427e")!
let json = Data("[\"\(sut)\"]".utf8)
let digest = try! JSONDecoder().decode(Array<MD5Digest>.self, from: json).first!
XCTAssertEqual(digest, sut)
}
}
| mit | a4ed55ae9917bda6c2bcf849d68bc656 | 28.873563 | 100 | 0.586764 | 3.397386 | false | true | false | false |
CoderXpert/Weather | Weather/CurrentWeatherForecastViewModel.swift | 1 | 8287 | //
// CurrentWeatherForecastViewModel.swift
// Weather
//
// Created by Adnan Aftab on 3/8/16.
// Copyright © 2016 CX. All rights reserved.
//
import Foundation
import CoreLocation
class CurrentWeatherForecastViewModel {
//: Private properties
private var forecastsItems:[Forecast]?
private var forecast:Forecast?
private let locationManager = LocationManager()
private let forecastClient = ForecastClient()
private var location : CLLocation?
private var isLoadingCurrentWeatherData : Bool = false
private var isLoadingForecastData : Bool = false
init() {
startLocationService()
}
// This method will start locationServices and will set delegate method to self
private func startLocationService() {
locationManager.delegate = self
locationManager.requestLocation()
}
private func postNotification(notif:String){
dispatch_async(dispatch_get_main_queue(), {
NSNotificationCenter.defaultCenter().postNotificationName(notif, object: .None)
})
}
private func getCurrentWeatherData (){
guard isLoadingCurrentWeatherData == false else { return }
guard let loc = location else { return }
isLoadingCurrentWeatherData = true
self.postNotification(ForecastViewModelNotificaitons.StartLoadingCurrentWeatherInfo.rawValue)
forecastClient.getCurrentWeatherWithLocation(loc) { (forecast, error) in
self.isLoadingCurrentWeatherData = false
guard error == .None else {
//Post error notification
self.postNotification(ForecastViewModelNotificaitons.GotNoCurrentWeatherData.rawValue)
return
}
guard let fc = forecast else {
// Post no forecast notification
self.postNotification(ForecastViewModelNotificaitons.GotNoCurrentWeatherData.rawValue)
return
}
self.forecast = fc
self.postNotification(ForecastViewModelNotificaitons.GotNewCurrentWeatherData.rawValue)
}
}
private func getForecastData() {
guard isLoadingForecastData == false else { return }
guard let loc = location else { return }
isLoadingForecastData = true
forecastClient.getForecastsWithLocation(loc) { (forecasts, error) in
self.isLoadingForecastData = false
guard error == .None else {
self.postNotification(ForecastViewModelNotificaitons.GotNoForecasts.rawValue)
return
}
guard let fcs = forecasts else {
self.postNotification(ForecastViewModelNotificaitons.GotNoForecasts.rawValue)
return
}
self.isLoadingForecastData = false
self.forecastsItems = fcs
self.postNotification(ForecastViewModelNotificaitons.GotNewForecastData.rawValue)
}
}
private func getCurrentWeatherAndForecastData() {
guard let _ = location else { return }
getCurrentWeatherData()
getForecastData()
}
}
//: ViewModel protocol implementation
extension CurrentWeatherForecastViewModel : CurrentWeatherForecastViewModelType {
//: Current Weather
var currentLocationName:String{
get{
guard let fc = forecast else {
return ""
}
return fc.location
}
}
var lastUpdateDateAndTimeString:String {
get{
guard let fc = forecast else {
return ""
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyy MM:HH"
return dateFormatter.stringFromDate(fc.date)
}
}
var currentTemperatureString:String {
get{
guard let fc = forecast else {
return ""
}
return fc.localizedTemperatureString
}
}
var currentMaxTemperatureString:String {
get{
guard let fc = forecast else {
return ""
}
return fc.localizedMaxTemperatureString
}
}
var currentMinTemperatureString:String {
get{
guard let fc = forecast else {
return ""
}
return fc.localizedMinTemeratureString
}
}
var currentWeatherConditionIconText:String {
get{
guard let fc = forecast else {
return ""
}
return fc.iconText
}
}
var currentWeatherConditionText:String {
get{
guard let fc = forecast else {
return ""
}
return fc.weatherConditionText
}
}
//: Forecasts
var totalNumberOfTodaysForecasts:Int {
get {
guard let fcs = forecastsItems else {
return 0
}
return fcs.forecastForToday().count
}
}
var totalNumberOfFutureForecastsExcludingToday:Int {
get {
guard let fcs = forecastsItems else {
return 0
}
return fcs.forecastExcludingToday().count
}
}
func todayForecastTemperatureStringForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastForToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return fc.localizedTemperatureString
}
func todayForecastShortDateTimeStringForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastForToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return fc.date.shortTime()
}
func todayForecastWeatherConditionIconTextForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastForToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return fc.iconText
}
func futureForecastTemperatureStringForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastExcludingToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return fc.localizedTemperatureString
}
func futureForecastShortDateTimeStringForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastExcludingToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return "\(fc.date.dayAndMonth())\n\(fc.date.shortTime())"
}
func futureForecastWeatherConditionIconTextForIndex(index:Int) -> String? {
guard index >= 0 else { return .None }
guard let fcs = forecastsItems else {
return .None
}
let tfcs = fcs.forecastExcludingToday()
guard tfcs.count > 0 && index <= tfcs.count else {
return .None
}
let fc = tfcs[index]
return fc.iconText
}
func updateWeatherData() {
getCurrentWeatherAndForecastData()
}
}
//: Extension which will implement LocationManagerDelegate method
extension CurrentWeatherForecastViewModel : LocationManagerDelegate {
func locationDidUpdate(service: LocationManager, location: CLLocation) {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.location = location
self.getCurrentWeatherAndForecastData()
}
}
}
| apache-2.0 | e49198a0d0330487ec4796b38198c5c4 | 31.622047 | 102 | 0.592083 | 5.483786 | false | false | false | false |
KeisukeSoma/RSSreader | RSSReader/View10.swift | 1 | 3162 | //
// View10.swift
// RSSReader
//
// Created by mikilab on 2015/06/19.
// Copyright (c) 2015年 susieyy. All rights reserved.
//
import UIKit
class View10: UITableViewController, MWFeedParserDelegate {
var items = [MWFeedItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
request()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func request() {
let URL = NSURL(string: "http://news.livedoor.com/topics/rss/ent.xml")
let feedParser = MWFeedParser(feedURL: URL);
feedParser.delegate = self
feedParser.parse()
}
func feedParserDidStart(parser: MWFeedParser) {
SVProgressHUD.show()
self.items = [MWFeedItem]()
}
func feedParserDidFinish(parser: MWFeedParser) {
SVProgressHUD.dismiss()
self.tableView.reloadData()
}
func feedParser(parser: MWFeedParser, didParseFeedInfo info: MWFeedInfo) {
print(info)
self.title = info.title
}
func feedParser(parser: MWFeedParser, didParseFeedItem item: MWFeedItem) {
print(item)
self.items.append(item)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCell")
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.items[indexPath.row] as MWFeedItem
let con = KINWebBrowserViewController()
let URL = NSURL(string: item.link)
con.loadURL(URL)
self.navigationController?.pushViewController(con, animated: true)
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let item = self.items[indexPath.row] as MWFeedItem
cell.textLabel?.text = item.title
cell.textLabel?.font = UIFont.systemFontOfSize(14.0)
cell.textLabel?.numberOfLines = 0
let projectURL = item.link.componentsSeparatedByString("?")[0]
let imgURL: NSURL? = NSURL(string: projectURL + "/cover_image?style=200x200#")
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
// cell.imageView?.setImageWithURL(imgURL, placeholderImage: UIImage(named: "logo.png"))
}
}
| mit | aeb7afc03c34b0d4945b9a21aef84b14 | 31.244898 | 118 | 0.658544 | 4.914463 | false | false | false | false |
thiagotmb/TBHourMinutePickerView | TBHourMinutePickerView/NSDateComponents+Manager.swift | 1 | 969 | //
// NSDateComponents+Manager.swift
// TBHourMinutePickerView
//
// Created by Thiago-Bernardes on 1/26/16.
// Copyright © 2016 TMB. All rights reserved.
//
extension NSDateComponents{
static func dateComponentsFrom(originalDate: NSDate) -> NSDateComponents {
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.locale = NSLocale.currentLocale()
let timeZone: NSTimeZone = NSTimeZone.localTimeZone()
cal.timeZone = timeZone
var convertedDateComponents = NSDateComponents()
convertedDateComponents.timeZone = timeZone
if !originalDate.isEqual(nil){
convertedDateComponents = cal.components( [.Year, .Month, .Day, .Hour, .Minute], fromDate: originalDate)
}
else {
convertedDateComponents = cal.components( [.Year, .Month, .Day, .Hour, .Minute], fromDate: NSDate())
}
return convertedDateComponents
}
}
| mit | 84c220c002b715843c292ea9bb70ce0d | 36.230769 | 116 | 0.676653 | 4.989691 | false | false | false | false |
itssofluffy/NanoMessage | Sources/NanoMessage/Core/SymbolProperty.swift | 1 | 2708 | /*
SymbolProperty.swift
Copyright (c) 2016, 2017 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import ISFLibrary
import FNVHashValue
/// Nanomsg symbol.
public struct SymbolProperty {
public let namespace: SymbolPropertyNamespace
public let name: String
public let value: CInt
public let type: SymbolPropertyType
public let unit: SymbolPropertyUnit
public init(namespace: CInt,
name: String,
value: CInt,
type: CInt,
unit: CInt) {
self.namespace = SymbolPropertyNamespace(rawValue: namespace)
self.name = name
self.value = value
self.type = SymbolPropertyType(rawValue: type)
self.unit = SymbolPropertyUnit(rawValue: unit)
}
}
extension SymbolProperty: Hashable {
public var hashValue: Int {
return fnv1a(typeToBytes(namespace) + typeToBytes(value))
}
}
extension SymbolProperty: Comparable {
public static func <(lhs: SymbolProperty, rhs: SymbolProperty) -> Bool {
return ((lhs.namespace.rawValue < rhs.namespace.rawValue) ||
(lhs.namespace.rawValue == rhs.namespace.rawValue && lhs.value < rhs.value))
}
}
extension SymbolProperty: Equatable {
public static func ==(lhs: SymbolProperty, rhs: SymbolProperty) -> Bool {
return (lhs.namespace == rhs.namespace && lhs.value == rhs.value)
}
}
extension SymbolProperty: CustomDebugStringConvertible {
public var debugDescription: String {
return "namespace: \(namespace), name: \(name), value: \(value), type: \(type), unit: \(unit)"
}
}
| mit | fa5f8383f5ea6de78ae3ba3d835320f2 | 37.685714 | 102 | 0.694239 | 4.79292 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Transactions/Types/LocalizedOperationObject.swift | 1 | 2617 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import RealmSwift
import TrustCore
final class LocalizedOperationObject: Object, Decodable {
@objc dynamic var from: String = ""
@objc dynamic var to: String = ""
@objc dynamic var contract: String? = .none
@objc dynamic var type: String = ""
@objc dynamic var value: String = ""
@objc dynamic var name: String? = .none
@objc dynamic var symbol: String? = .none
@objc dynamic var decimals: Int = 18
convenience init(
from: String,
to: String,
contract: String?,
type: String,
value: String,
symbol: String?,
name: String?,
decimals: Int
) {
self.init()
self.from = from
self.to = to
self.contract = contract
self.type = type
self.value = value
self.symbol = symbol
self.name = name
self.decimals = decimals
}
enum LocalizedOperationObjectKeys: String, CodingKey {
case from
case to
case type
case value
case contract
}
convenience required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LocalizedOperationObjectKeys.self)
let from = try container.decode(String.self, forKey: .from)
let to = try container.decode(String.self, forKey: .to)
guard
let fromAddress = EthereumAddress(string: from),
let toAddress = EthereumAddress(string: to) else {
let context = DecodingError.Context(codingPath: [LocalizedOperationObjectKeys.from,
LocalizedOperationObjectKeys.to, ],
debugDescription: "Address can't be decoded as a TrustKeystore.Address")
throw DecodingError.dataCorrupted(context)
}
let type = try container.decode(OperationType.self, forKey: .type)
let value = try container.decode(String.self, forKey: .value)
let contract = try container.decode(ERC20Contract.self, forKey: .contract)
self.init(from: fromAddress.description,
to: toAddress.description,
contract: contract.address,
type: type.rawValue,
value: value,
symbol: contract.symbol,
name: contract.name,
decimals: contract.decimals
)
}
var operationType: OperationType {
return OperationType(string: type)
}
}
| gpl-3.0 | 60da331df068320882511bbca78dd8f6 | 32.987013 | 124 | 0.584639 | 5.01341 | false | false | false | false |
daisuke310vvv/TopTabBarView | TopTabBarViewExample/TopTabBarViewExample/ViewController.swift | 1 | 2004 | //
// ViewController.swift
// TopTabBarViewExample
//
// Created by SatoDaisuke on 7/21/15.
// Copyright (c) 2015 com.daisukeSato. All rights reserved.
//
import UIKit
import TopTabBarView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor()
let item1 = TopTabBarItem(title: "Hot", color: UIColor(red: 2/255, green: 174/255, blue: 220/255, alpha: 1))
let item2 = TopTabBarItem(title: "Social", color: UIColor(red: 255/255, green: 212/255, blue: 100/255, alpha: 1))
let item3 = TopTabBarItem(title: "Politics", color: UIColor(red: 18/255, green: 83/255, blue: 164/255, alpha: 1))
let item4 = TopTabBarItem(title: "Business", color: UIColor(red: 47/255, green: 205/255, blue: 180/255, alpha: 1))
let item5 = TopTabBarItem(title: "Entertaiment", color: UIColor(red: 251/255, green: 168/255, blue: 72/255, alpha: 1))
let item6 = TopTabBarItem(title: "Tech", color: UIColor(red: 12/255, green: 85/255, blue: 93/255, alpha: 1))
let item7 = TopTabBarItem(title: "Media", color: UIColor(red: 2/255, green: 150/255, blue: 200/255, alpha: 1))
let item8 = TopTabBarItem(title: "Comedy", color: UIColor(red: 255/255, green: 83/255, blue: 200/255, alpha: 1))
let topTabBarView = TopTabBarView(
frame: CGRectMake(
0,
UIApplication.sharedApplication().statusBarFrame.height,
self.view.frame.width,
44
),
items: [item1,item2,item3,item4,item5,item6,item7,item8]
)
topTabBarView.delegate = self
self.view.addSubview(topTabBarView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | f8334388d74bc70058bc45dec12f2b40 | 39.08 | 126 | 0.629242 | 3.817143 | false | false | false | false |
NorthernRealities/ColorSenseRainbow | ColorSenseRainbow/RainbowHexadecimalStringSeeker.swift | 1 | 2725 | //
// RainbowHexadecimalSeeker.swift
// ColorSenseRainbow
//
// Created by Reid Gravelle on 2015-04-23.
// Copyright (c) 2015 Northern Realities Inc. All rights reserved.
//
import AppKit
class RainbowHexadecimalStringSeeker: Seeker {
override init () {
super.init()
var error : NSError?
var regex: NSRegularExpression?
// Swift
let commonSwiftRegex = "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*hexString:\\s*\"#?([0-9a-fA-F]{6})\"\\s*"
do {
regex = try NSRegularExpression ( pattern: commonSwiftRegex + ",\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)", options: [])
} catch let error1 as NSError {
error = error1
regex = nil
}
if regex == nil {
print ( "Error creating Swift Rainbow hexidecimal string with alpha regex = \(error?.localizedDescription)" )
} else {
regexes.append( regex! )
}
do {
regex = try NSRegularExpression ( pattern: commonSwiftRegex + "\\)", options: [])
} catch let error1 as NSError {
error = error1
regex = nil
}
if regex == nil {
print ( "Error creating Swift Rainbow hexidecimal string without alpha regex = \(error?.localizedDescription)" )
} else {
regexes.append( regex! )
}
}
override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? {
if ( ( match.numberOfRanges == 2 ) || ( match.numberOfRanges == 3 ) ) {
var alphaValue : CGFloat = 1.0
let matchString = stringFromRange( match.range, line: line )
let hexString = stringFromRange( match.rangeAtIndex( 1 ), line: line )
var capturedStrings = [ matchString, hexString ]
if ( match.numberOfRanges == 3 ) {
let alphaString = stringFromRange( match.rangeAtIndex( 2 ), line: line )
alphaValue = CGFloat ( (alphaString as NSString).doubleValue )
capturedStrings.append( alphaString )
}
var color = NSColor ( hexString: hexString )
if ( alphaValue != 1.0 ) {
color = color.colorWithAlphaComponent( alphaValue )
}
var searchResult = SearchResult ( color: color, textCheckingResult: match, capturedStrings: capturedStrings )
searchResult.creationType = .RainbowHexString
return searchResult
}
return nil
}
}
| mit | dd75ce9d7c7e4f70c47b57e7946d5abd | 31.440476 | 135 | 0.531376 | 5.141509 | false | false | false | false |
achimk/Cars | CarsApp/Repositories/Cars/Models/CarIdentityModel.swift | 1 | 374 | //
// CarIdentityModel.swift
// CarsApp
//
// Created by Joachim Kret on 30/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
struct CarIdentityModel: Equatable {
let id: String
init(_ id: String) {
self.id = id
}
}
func ==(lhs: CarIdentityModel, rhs: CarIdentityModel) -> Bool {
return lhs.id == rhs.id
}
| mit | a60d1ec4c402a48e94e8e96776674ffc | 16.761905 | 63 | 0.640751 | 3.586538 | false | false | false | false |
kopto/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationBallZigZagDeflect.swift | 1 | 3754 | //
// KRActivityIndicatorAnimationBallZigZagDeflect.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class KRActivityIndicatorAnimationBallZigZagDeflect: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.75
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize)
// Circle 1 animation
let animation = CAKeyframeAnimation(keyPath:"transform")
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
animation.duration = duration
animation.repeatCount = HUGE
animation.autoreverses = true
animation.isRemovedOnCompletion = false
// Draw circle 1
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
// Circle 2 animation
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
// Draw circle 2
circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
}
func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: NSColor, animation: CAAnimation) {
let circle = KRActivityIndicatorShape.circle.layerWith(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 22d522081b5d01c5bd90a7529b774af1 | 49.053333 | 160 | 0.686201 | 4.837629 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/AddContactModalController.swift | 1 | 7785 | //
// AddContactModalController.swift
// Telegram
//
// Created by keepcoder on 10/04/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import SwiftSignalKit
import Postbox
private struct AddContactState : Equatable {
let firstName: String
let lastName: String
let phoneNumber: String
let errors: [InputDataIdentifier : InputDataValueError]
init(firstName: String, lastName: String, phoneNumber: String, errors: [InputDataIdentifier : InputDataValueError]) {
self.firstName = firstName
self.lastName = lastName
self.phoneNumber = phoneNumber
self.errors = errors
}
func withUpdatedError(_ error: InputDataValueError?, for key: InputDataIdentifier) -> AddContactState {
var errors = self.errors
if let error = error {
errors[key] = error
} else {
errors.removeValue(forKey: key)
}
return AddContactState(firstName: self.firstName, lastName: self.lastName, phoneNumber: self.phoneNumber, errors: errors)
}
func withUpdatedFirstName(_ firstName: String) -> AddContactState {
return AddContactState(firstName: firstName, lastName: self.lastName, phoneNumber: self.phoneNumber, errors: self.errors)
}
func withUpdatedLastName(_ lastName: String) -> AddContactState {
return AddContactState(firstName: self.firstName, lastName: lastName, phoneNumber: self.phoneNumber, errors: self.errors)
}
func withUpdatedPhoneNumber(_ phoneNumber: String) -> AddContactState {
return AddContactState(firstName: self.firstName, lastName: self.lastName, phoneNumber: phoneNumber, errors: self.errors)
}
}
private let _id_input_first_name = InputDataIdentifier("_id_input_first_name")
private let _id_input_last_name = InputDataIdentifier("_id_input_last_name")
private let _id_input_phone_number = InputDataIdentifier("_id_input_phone_number")
private func addContactEntries(state: AddContactState) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.firstName), error: state.errors[_id_input_first_name], identifier: _id_input_first_name, mode: .plain, data: InputDataRowData(viewType: .firstItem), placeholder: nil, inputPlaceholder: strings().contactsFirstNamePlaceholder, filter: { $0 }, limit: 255))
index += 1
entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.lastName), error: state.errors[_id_input_last_name], identifier: _id_input_last_name, mode: .plain, data: InputDataRowData(viewType: .innerItem), placeholder: nil, inputPlaceholder: strings().contactsLastNamePlaceholder, filter: { $0 }, limit: 255))
index += 1
entries.append(InputDataEntry.input(sectionId: sectionId, index: index, value: .string(state.phoneNumber), error: state.errors[_id_input_phone_number], identifier: _id_input_phone_number, mode: .plain, data: InputDataRowData(viewType: .lastItem), placeholder: nil, inputPlaceholder: strings().contactsPhoneNumberPlaceholder, filter: { text in
return text.trimmingCharacters(in: CharacterSet(charactersIn: "0987654321+ ").inverted)
}, limit: 30))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func AddContactModalController(_ context: AccountContext) -> InputDataModalController {
let initialState = AddContactState(firstName: "", lastName: "", phoneNumber: "", errors: [:])
let statePromise = ValuePromise(initialState, ignoreRepeated: false)
let stateValue = Atomic(value: initialState)
let updateState: ((AddContactState) -> AddContactState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let dataSignal = statePromise.get() |> map { state in
return addContactEntries(state: state)
}
var close: (() -> Void)?
var shouldMakeNextResponderAfterTransition: InputDataIdentifier? = nil
let controller = InputDataController(dataSignal: dataSignal |> map { InputDataSignalValue(entries: $0) }, title: strings().contactsAddContact, validateData: { data in
return .fail(.doSomething { f in
let state = stateValue.with {$0}
var fields: [InputDataIdentifier : InputDataValidationFailAction] = [:]
if state.firstName.isEmpty {
fields[_id_input_first_name] = .shake
shouldMakeNextResponderAfterTransition = _id_input_first_name
}
if state.phoneNumber.isEmpty {
fields[_id_input_phone_number] = .shake
if shouldMakeNextResponderAfterTransition == nil {
shouldMakeNextResponderAfterTransition = _id_input_phone_number
}
updateState {
$0.withUpdatedError(InputDataValueError(description: strings().contactsPhoneNumberInvalid, target: .data), for: _id_input_phone_number)
}
}
if !fields.isEmpty {
f(.fail(.fields(fields)))
} else {
_ = (showModalProgress(signal: context.engine.contacts.importContact(firstName: state.firstName, lastName: state.lastName, phoneNumber: state.phoneNumber), for: context.window) |> deliverOnMainQueue).start(next: { peerId in
if let peerId = peerId {
context.bindings.rootNavigation().push(ChatController(context: context, chatLocation: .peer(peerId)))
close?()
} else {
updateState {
$0.withUpdatedError(InputDataValueError(description: strings().contactsPhoneNumberNotRegistred, target: .data), for: _id_input_phone_number)
}
}
})
}
updateState {
$0
}
})
}, updateDatas: { data in
updateState { state in
return state
.withUpdatedFirstName(data[_id_input_first_name]?.stringValue ?? "")
.withUpdatedLastName(data[_id_input_last_name]?.stringValue ?? "")
.withUpdatedPhoneNumber(formatPhoneNumber(data[_id_input_phone_number]?.stringValue ?? ""))
.withUpdatedError(nil, for: _id_input_first_name)
.withUpdatedError(nil, for: _id_input_last_name)
.withUpdatedError(nil, for: _id_input_phone_number)
}
return .none
}, afterDisappear: {
}, afterTransaction: { controller in
if let identifier = shouldMakeNextResponderAfterTransition {
controller.makeFirstResponderIfPossible(for: identifier)
}
shouldMakeNextResponderAfterTransition = nil
})
let modalInteractions = ModalInteractions(acceptTitle: strings().modalOK, accept: { [weak controller] in
controller?.validateInputValues()
}, drawBorder: true, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions, size: NSMakeSize(300, 300))
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
close = { [weak modalController] in
modalController?.close()
}
return modalController
}
| gpl-2.0 | 4262c03aa768a42ef6ecba5c57b494a2 | 42.005525 | 350 | 0.648124 | 5.07101 | false | false | false | false |
annecruz/MDCSwipeToChoose | Examples/SwiftLikedOrNope/SwiftLikedOrNope/ChoosePersonView.swift | 3 | 4990 | //
// ChoosePersonView.swift
// SwiftLikedOrNope
//
// Copyright (c) 2014 to present, Richard Burdish @rjburdish
//
// 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 ChoosePersonView: MDCSwipeToChooseView {
let ChoosePersonViewImageLabelWidth:CGFloat = 42.0;
var person: Person!
var informationView: UIView!
var nameLabel: UILabel!
var carmeraImageLabelView:ImagelabelView!
var interestsImageLabelView: ImagelabelView!
var friendsImageLabelView: ImagelabelView!
init(frame: CGRect, person: Person, options: MDCSwipeToChooseViewOptions) {
super.init(frame: frame, options: options)
self.person = person
if let image = self.person.Image {
self.imageView.image = image
}
self.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
UIViewAutoresizing.FlexibleBottomMargin
self.imageView.autoresizingMask = self.autoresizingMask
constructInformationView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func constructInformationView() -> Void{
let bottomHeight:CGFloat = 60.0
let bottomFrame:CGRect = CGRectMake(0,
CGRectGetHeight(self.bounds) - bottomHeight,
CGRectGetWidth(self.bounds),
bottomHeight);
self.informationView = UIView(frame:bottomFrame)
self.informationView.backgroundColor = UIColor.whiteColor()
self.informationView.clipsToBounds = true
self.informationView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleTopMargin]
self.addSubview(self.informationView)
constructNameLabel()
constructCameraImageLabelView()
constructInterestsImageLabelView()
constructFriendsImageLabelView()
}
func constructNameLabel() -> Void{
let leftPadding:CGFloat = 12.0
let topPadding:CGFloat = 17.0
let frame:CGRect = CGRectMake(leftPadding,
topPadding,
floor(CGRectGetWidth(self.informationView.frame)/2),
CGRectGetHeight(self.informationView.frame) - topPadding)
self.nameLabel = UILabel(frame:frame)
self.nameLabel.text = "\(person.Name), \(person.Age)"
self.informationView .addSubview(self.nameLabel)
}
func constructCameraImageLabelView() -> Void{
var rightPadding:CGFloat = 10.0
let image:UIImage = UIImage(named:"camera")!
self.carmeraImageLabelView = buildImageLabelViewLeftOf(CGRectGetWidth(self.informationView.bounds), image:image, text:person.NumberOfPhotos.stringValue)
self.informationView.addSubview(self.carmeraImageLabelView)
}
func constructInterestsImageLabelView() -> Void{
let image: UIImage = UIImage(named: "book")!
self.interestsImageLabelView = self.buildImageLabelViewLeftOf(CGRectGetMinX(self.carmeraImageLabelView.frame), image: image, text:person.NumberOfPhotos.stringValue)
self.informationView.addSubview(self.interestsImageLabelView)
}
func constructFriendsImageLabelView() -> Void{
let image:UIImage = UIImage(named:"group")!
self.friendsImageLabelView = buildImageLabelViewLeftOf(CGRectGetMinX(self.interestsImageLabelView.frame), image:image, text:"No Friends")
self.informationView.addSubview(self.friendsImageLabelView)
}
func buildImageLabelViewLeftOf(x:CGFloat, image:UIImage, text:String) -> ImagelabelView{
let frame:CGRect = CGRect(x:x-ChoosePersonViewImageLabelWidth, y: 0,
width: ChoosePersonViewImageLabelWidth,
height: CGRectGetHeight(self.informationView.bounds))
let view:ImagelabelView = ImagelabelView(frame:frame, image:image, text:text)
view.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin
return view
}
}
| mit | afb5f913040112568d28f6d5b44e70ee | 43.553571 | 172 | 0.715631 | 4.955313 | false | false | false | false |
Darshanptl7500/GPlaceAPI-Swift | GPlaceAPI/GPPlaceSearchRequest.swift | 1 | 4216 | //
// GPPlaceSearchRequest.swift
// GPlaceAPI-Swift
//
// Created by Darshan Patel on 7/23/15.
// Copyright (c) 2015 Darshan Patel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Darshan Patel
//
// 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 CoreLocation
import Alamofire
class GPPlaceSearchRequest {
typealias GooglePlaceSearchHandler = (GPPlaceSearchResponse?, NSError?)->Void
var location: CLLocationCoordinate2D!
var radius: Int!
var rankby: GPRankBy!
var keyword: String?
var language: String?
var minprice: Int?
var maxprice: Int?
var name: String?
var opennow: Bool?
var types:[String]?
var pagetoken: String?
init (location: CLLocationCoordinate2D) {
self.location = location;
self.radius = 1000
self.minprice = -1
self.maxprice = -1
self.rankby = .GPRankByProminence
}
func params() -> Dictionary<String, AnyObject> {
var dicParams = Dictionary<String, AnyObject>()
dicParams["key"] = GPlaceAPISetup.sharedInstance.Api_Key
dicParams["location"] = "\(self.location.latitude),\(self.location.longitude)"
if let opRadius = self.radius
{
dicParams["radius"] = "\(self.radius)";
}
if let opKeyWord = self.keyword
{
dicParams["keyword"] = self.keyword;
}
if self.maxprice != -1
{
dicParams["maxprice"] = "\(self.maxprice)";
}
if self.minprice != -1
{
dicParams["maxprice"] = "\(self.minprice)";
}
if let opName = self.name
{
dicParams["name"] = self.name
}
if self.opennow == true
{
dicParams["opennow"] = "\(self.opennow)"
}
if let language = self.language
{
dicParams["language"] = language
}
if let opPageToken = self.pagetoken
{
dicParams["pagetoken"] = self.pagetoken
}
dicParams["rankBy"] = self.rankby.rawValue
if let opTypes = self.types
{
if opTypes.count > 0
{
dicParams["types"] = join("|", opTypes)
}
}
return dicParams
}
func doFetchPlaces(handler : GooglePlaceSearchHandler)
{
Alamofire.request(.GET, "\(GPlaceConstants.kAPI_PLACES_URL)nearbysearch/json", parameters: self.params(), encoding: .URL).responseJSON(options: .AllowFragments) { (request, response, data, error) -> Void in
if error == nil
{
var gpResponse = GPPlaceSearchResponse(attributes: data as! Dictionary)
handler(gpResponse, error)
}else
{
handler(nil, error)
}
}
}
} | mit | 9d70af44f9c944a5eef8479696cd9194 | 27.687075 | 214 | 0.570209 | 4.684444 | false | false | false | false |
andrewBatutin/SwiftYamp | SwiftYamp/WebSocketServer/WebsocketConnection.swift | 1 | 6176 | //
// WebsocketConnection.swift
// SwiftYamp
//
// Created by Andrey Batutin on 6/19/17.
// Copyright © 2017 Andrey Batutin. All rights reserved.
//
import Foundation
import Starscream
import CocoaLumberjack
public class WebSocketConnection: YampConnection, YampMessageConnection, YampConnectionCallback, YampDataCallback{
public var onConnect: ((Void)->Void)?
public var onClose: ((String, CloseCodeType)->Void)?
public var onRedirect: ((Void) -> String)?
public var onEvent: ((EventFrame)->Void)?
public var onResponse: ((ResponseFrame)->Void)?
public var onPong: ((Data?) -> Void)?
var onDataReceived: ((Data?) -> Void)?
var onDataSend: ((Data?) -> Void)?
private var data:Data = Data()
public var versionSupported:[UInt16] = [0x01]
public private(set) var webSocket:WebSocket?
public init?(url: String){
guard let serverUrl = URL(string: url) else {
return nil
}
webSocket = self.setupTransport(url: serverUrl)
}
private func setupTransport(url: URL) -> WebSocket{
let webSocket = WebSocket(url: url)
webSocket.onData = self.incomingDataHandler()
webSocket.onConnect = { [unowned self] in
let handshakeFrame = HandshakeFrame(version: self.versionSupported.last ?? 0x1)
self.sendFrame(frame: handshakeFrame)
}
webSocket.onDisconnect = {[unowned self] (error)in
let c = CloseFrame(closeCode: .Unknown, message: error?.localizedDescription)
self.closeReceived(frame: c)
}
return webSocket
}
private func incomingDataHandler() -> ((Data) -> Void)?{
self.data = Data()
return { [unowned self] (data: Data) in
self.data.append(data)
do{
let frame:YampTypedFrame = try deserialize(data: self.data) as! YampTypedFrame
self.onDataReceived?(self.data)
self.handleFrame(frame: frame)
self.data = Data()
}catch(let exp){
DDLogWarn(exp.localizedDescription)
}
}
}
func handleFrame(frame:YampTypedFrame){
switch frame.frameType {
case .Handshake:
self.handshakeReceived(frame: frame as! HandshakeFrame)
case .Close:
let closeFrame:CloseFrame = frame as! CloseFrame
self.closeReceived(frame: closeFrame)
case .Ping:
let pingFrame = frame as! PingFrame
let pongFrame = PingFrame(ack: true, size:UInt8(pingFrame.payload.characters.count), payload: pingFrame.payload)
self.sendFrame(frame: pongFrame)
case .Event:
self.onEvent?(frame as! EventFrame)
case .Response:
self.onResponse?(frame as! ResponseFrame)
default:
DDLogInfo("we've got some unxpected frame \(frame.frameType)")
}
}
func handshakeReceived(frame: HandshakeFrame){
let v = frame.version
if let str = self.onRedirect?() {
self.cancel(reason: str, closeCode: .Redirect)
self.onClose?("Redirect to \(str)", .Redirect)
return
}
if ( self.versionSupported.contains(v) ){
self.onConnect?()
} else {
self.cancel(reason: "Version Not Supported", closeCode: .VersionNotSupported)
self.onClose?("Version Not Supported", .VersionNotSupported)
}
}
func closeReceived(frame: CloseFrame){
self.onClose?(frame.message, frame.closeCode)
switch frame.closeCode {
case .Timeout:
self.disconnect()
case .Redirect:
self.reconnect(url: frame.message)
default:
DDLogInfo("close with code \(frame.closeCode)")
}
}
public func reconnect(url: String){
self.disconnect()
guard let serverUrl = URL(string: url) else {
return
}
self.webSocket = self.setupTransport(url: serverUrl)
self.connect()
}
private func disconnect(){
self.webSocket?.disconnect()
}
public func connect() {
webSocket?.connect()
}
public func cancel(reason: String?, closeCode: CloseCodeType) {
let closeFrame = CloseFrame(closeCode: closeCode, message: reason)
self.sendFrame(frame: closeFrame)
}
func sendFrame(frame: YampFrame) {
do{
let data = try frame.toData()
self.onDataSend?(data)
webSocket?.write(data: data)
}catch(let exp){
DDLogError(exp.localizedDescription)
}
}
public func sendPing(payload: String?){
let size = payload?.characters.count ?? 0
let frame = PingFrame(ack: false, size: UInt8(size), payload: payload)
self.sendFrame(frame: frame)
}
public func sendData(uri: String, data: Data) {
let h = UserMessageHeaderFrame(uid: messageUuid(), size: UInt8(uri.characters.count), uri: uri)
let b = UserMessageBodyFrame(size: UInt32(data.count), body: data.toByteArray())
let r = RequestFrame(header: h, body: b)
self.sendFrame(frame: r)
}
public func sendEvent(uri: String, message: String){
guard let data = message.data(using: .utf8) else {
DDLogError("Error converting string to data")
return
}
let h = UserMessageHeaderFrame(uid: messageUuid(), size: UInt8(uri.characters.count), uri: uri)
let b = UserMessageBodyFrame(size: UInt32(data.count), body: data.toByteArray())
let r = EventFrame(header: h, body: b)
self.sendFrame(frame: r)
}
public func sendMessage(uri: String, message: String) {
guard let data = message.data(using: .utf8) else {
DDLogError("Error converting string to data")
return
}
self.sendData(uri: uri, data: data)
}
public func timeout(){
self.onClose?("Timeout", .Timeout)
self.cancel(reason: "Timeout", closeCode: .Timeout)
}
}
| mit | 7463999a0c43fa1b59eb6ef4f8a199ef | 32.743169 | 124 | 0.595789 | 4.497451 | false | false | false | false |
tamasoszko/sandbox-ios | Jazzy/Jazzy/PlayLists.swift | 1 | 4822 | //
// PlayListItem.swift
// Jazzy
//
// Created by Oszkó Tamás on 07/11/15.
// Copyright © 2015 Oszi. All rights reserved.
//
import Foundation
public class PlayListItem : NSObject {
let date : NSDate
let title : String
let artist : String
init(date : NSDate, title : String, artist : String) {
self.date = date
self.title = title
self.artist = artist
}
override public func isEqual(object: AnyObject?) -> Bool {
if let rhs = object as? PlayListItem {
return title == rhs.title && artist == rhs.artist
}
return false
}
}
class PlayListParser {
let string : String
let dateFormatter = NSDateFormatter()
init(data: NSData) {
self.string = String(data: data, encoding: NSUTF8StringEncoding)!
self.dateFormatter.dateFormat = "HH:mm"
self.dateFormatter.defaultDate = NSDate()
}
func parse() -> [PlayListItem] {
let regexp = try! NSRegularExpression(pattern: "<td>(.*)</td>\n *<td>(.*)</td>\n *<td>(.*)</td>", options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regexp.matchesInString(string, options: NSMatchingOptions.ReportProgress, range: NSRange(location: 0, length: string.characters.count))
var items = [PlayListItem]()
let nsString: NSString = string as NSString
for match in matches {
if match.numberOfRanges == 4 {
let dataStr = nsString.substringWithRange(match.rangeAtIndex(1))
let artist = nsString.substringWithRange(match.rangeAtIndex(2))
let title = nsString.substringWithRange(match.rangeAtIndex(3))
let item = PlayListItem(date: dateFormatter.dateFromString(dataStr)!, title: title, artist: artist)
items.append(item)
}
}
return items
}
}
class PlayListDownloader {
let url : NSURL
var maxCount = 10
init(url: NSURL) {
self.url = url
}
func download(completion : ([PlayListItem]?, NSError?) -> Void) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (_data: NSData?, _resp: NSURLResponse?, _error: NSError?) -> Void in
if let error = _error {
completion(nil, error)
return
}
completion(self.items(_data!), nil)
}
task.resume()
}
private func items(data: NSData) -> [PlayListItem] {
let parser = PlayListParser(data: data)
let allItems = parser.parse().sort ({
$0.date.compare($1.date) == NSComparisonResult.OrderedDescending
})
var items = [PlayListItem]()
for var i = 0; i < min(self.maxCount, allItems.count); i++ {
items.append(allItems[i])
}
return items
}
}
public class PlayListUpdater : NSObject {
let ItemChangedNotification = "PlayListItemChanged"
let updatePeriod = 15.0
var currentPlayListItem : PlayListItem?
var timer : NSTimer?
let downloader : PlayListDownloader
init(url: NSURL) {
self.downloader = PlayListDownloader(url: url)
}
public func startUpdate() {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if self.timer == nil {
self.timer = NSTimer.scheduledTimerWithTimeInterval(self.updatePeriod, target: self, selector:"onTimer:", userInfo: nil, repeats: false)
}
}
}
public func stopUpdate() {
if let timer = self.timer {
timer.invalidate()
self.timer = nil
}
}
private func restartTimer() {
if self.timer != nil {
self.timer = nil
startUpdate()
}
}
func onTimer(timer:NSTimer!) {
doUpdate()
}
private func doUpdate() {
downloader.download { (items: [PlayListItem]?, error: NSError?) -> Void in
if let error = error {
NSLog("Error downloading playlist \(error)")
return;
}
self.processPlayList(items)
self.restartTimer()
}
}
private func processPlayList(items: [PlayListItem]?) {
let item = valid(items?.first)
if currentPlayListItem != item {
currentPlayListItem = item
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: ItemChangedNotification, object: currentPlayListItem))
}
}
private func valid(item: PlayListItem?) -> PlayListItem? {
if let item = item {
if item.date.timeIntervalSinceNow > -450 {
return item
}
}
return nil;
}
}
| apache-2.0 | 50476863e77648f8b8496d2b8db2723f | 28.206061 | 158 | 0.575846 | 4.74311 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Background/Crypto/MXBackgroundCryptoV2.swift | 1 | 3489 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
#if DEBUG
import MatrixSDKCrypto
/// An implementation of `MXBackgroundCrypto` which uses [matrix-rust-sdk](https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto)
/// under the hood.
class MXBackgroundCryptoV2: MXBackgroundCrypto {
enum Error: Swift.Error {
case missingCredentials
}
private let machine: MXCryptoMachine
private let log = MXNamedLog(name: "MXBackgroundCryptoV2")
init(credentials: MXCredentials, restClient: MXRestClient) throws {
guard
let userId = credentials.userId,
let deviceId = credentials.deviceId
else {
throw Error.missingCredentials
}
// `MXCryptoMachine` will load the same store as the main application meaning that background and foreground
// sync services have access to the same data / keys. Possible race conditions are handled internally.
machine = try MXCryptoMachine(
userId: userId,
deviceId: deviceId,
restClient: restClient,
getRoomAction: { [log] _ in
log.error("The background crypto should not be accessing rooms")
return nil
}
)
}
func handleSyncResponse(_ syncResponse: MXSyncResponse) {
let toDeviceCount = syncResponse.toDevice?.events.count ?? 0
log.debug("Handling new sync response with \(toDeviceCount) to-device event(s)")
do {
_ = try machine.handleSyncResponse(
toDevice: syncResponse.toDevice,
deviceLists: syncResponse.deviceLists,
deviceOneTimeKeysCounts: syncResponse.deviceOneTimeKeysCount ?? [:],
unusedFallbackKeys: syncResponse.unusedFallbackKeys
)
} catch {
log.error("Failed handling sync response", context: error)
}
}
func canDecryptEvent(_ event: MXEvent) -> Bool {
if !event.isEncrypted {
return true
}
guard
let _ = event.content["sender_key"] as? String,
let _ = event.content["session_id"] as? String
else {
return false
}
do {
// Rust-sdk does not expose api to see if we have a given session key yet (will be added in the future)
// so for the time being to find out if we can decrypt we simply perform the (more expensive) decryption
_ = try machine.decryptRoomEvent(event)
return true
} catch {
return false
}
}
func decryptEvent(_ event: MXEvent) throws {
let decrypted = try machine.decryptRoomEvent(event)
let result = try MXEventDecryptionResult(event: decrypted)
event.setClearData(result)
}
}
#endif
| apache-2.0 | a82d3f6acc9767eaf9a02c5f3c6cbb7c | 33.89 | 156 | 0.627974 | 4.799175 | false | false | false | false |
dev-gao/GYPageViewController | Example/GYPageViewController/ViewController.swift | 1 | 4614 | //
// ViewController.swift
// GYPageViewController
//
// Created by GaoYu on 16/6/12.
// Copyright © 2016年 GaoYu. All rights reserved.
//
import UIKit
class ViewController: UITableViewController ,GYPageViewControllerDataSource, GYPageViewControllerDelegate {
@objc var pageControllers:Array<UIViewController>!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Demo"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomCell")
}
//MARK: - UITableViewDelegate, UITableViewDataSource
override func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath)
if indexPath.row == 0 {
cell.textLabel?.text = "GYTapPageViewController"
} else if indexPath.row == 1 {
cell.textLabel?.text = "GYPageViewController"
} else if indexPath.row == 2 {
cell.textLabel?.text = "UIPageViewController"
}
cell.setSelected(false, animated: false)
return cell
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
var titlesArray:Array<String> = Array<String>()
var pageControllers:Array<TestChildViewController> = Array<TestChildViewController>()
let colorStep:CGFloat = 1/4
for i in 0...20 {
titlesArray.append("tab \(i)")
let tabVc = TestChildViewController()
tabVc.pageIndex = i
tabVc.view.backgroundColor = UIColor(red: colorStep * CGFloat((i + 1) % 2), green: colorStep * CGFloat((i + 1) % 3), blue: colorStep * CGFloat((i + 1) % 5), alpha: 1)
let label = UILabel(frame: CGRect(x:100,y:100,width:100,height:100))
label.backgroundColor = UIColor.gray
label.text = "tab \(i)"
label.textAlignment = .center
tabVc.view.addSubview(label)
pageControllers.append(tabVc)
}
self.pageControllers = pageControllers
let vc = GYTabPageViewController(pageTitles: titlesArray)
vc.delegate = self
vc.dataSource = self
vc.showPageAtIndex(2, animated: false)
self.navigationController?.pushViewController(vc, animated: true)
} else if indexPath.row == 1 {
} else if indexPath.row == 2 {
var titlesArray:Array<String> = Array<String>()
var pageControllers:Array<TestChildViewController> = Array<TestChildViewController>()
let colorStep:CGFloat = 1/4
for i in 0...20 {
titlesArray.append("tab \(i)")
let tabVc = TestChildViewController()
tabVc.pageIndex = i
tabVc.view.backgroundColor = UIColor(red: colorStep * CGFloat((i + 1) % 2), green: colorStep * CGFloat((i + 1) % 3), blue: colorStep * CGFloat((i + 1) % 5), alpha: 1)
let label = UILabel(frame: CGRect(x:100,y:100,width:100,height:100))
label.backgroundColor = UIColor.gray
label.text = "tab \(i)"
label.textAlignment = .center
tabVc.view.addSubview(label)
pageControllers.append(tabVc)
}
self.pageControllers = pageControllers
let vc = TestPageViewController(pageTitles: titlesArray, pageControllers: pageControllers)
vc.showPageAtIndex(index: 2, animated: false)
self.navigationController?.pushViewController(vc, animated: true)
}
}
//MARK: - GYPageViewControllerDataSource & GYPageViewControllerDelegate
@objc func gy_pageViewController(_: GYPageViewController, controllerAtIndex index: Int) -> UIViewController! {
return self.pageControllers[index]
}
@objc func numberOfControllers(_: GYPageViewController) -> Int {
return self.pageControllers.count
}
}
| mit | df131f78611d9422713559f335f4205b | 40.169643 | 184 | 0.589677 | 5.204289 | false | true | false | false |
ChrisMyrants/Wires | Sources/Logging.swift | 1 | 558 | public enum Preferences {
public static var logActive: Bool = false
public static var logSeparator: String? = nil
}
enum Log {
static let prefix = "WiresLog"
static let separator = "------"
static let interfix = " --> "
static func with(context: Any, text: String) {
guard Preferences.logActive else { return }
let preseparator = Preferences.logSeparator.map { $0 + "\n" } ?? ""
let postseparator = Preferences.logSeparator.map { "\n" + $0 } ?? ""
print(preseparator + prefix + interfix + "\(context)" + interfix + text + postseparator)
}
}
| mit | b1a3438f3275686eac738689ab9bda61 | 31.823529 | 90 | 0.670251 | 3.402439 | false | false | false | false |
343max/WorldTime | WorldTime/LocationEditorViewController.swift | 1 | 2731 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import UIKit
protocol LocationEditorDelegate: class {
func locationEditorDidEditLocation(index: Int, newLocation: Location)
}
class LocationEditorViewController: UITableViewController {
var index = 0
var location: Location! {
didSet {
self.delegate?.locationEditorDidEditLocation(index: index, newLocation: location)
if isViewLoaded {
update(location: location)
}
}
}
weak var delegate: LocationEditorDelegate?
@IBOutlet weak var locationNameTextField: UITextField!
@IBOutlet weak var timeZoneCell: UITableViewCell!
static func fromXib(location: Location, index: Int) -> LocationEditorViewController {
let storyboard = UIStoryboard(name: "LocationEditorViewController", bundle: nil)
guard let viewController = storyboard.instantiateInitialViewController() as? LocationEditorViewController else {
fatalError("no LocationEditorViewController")
}
viewController.location = location
viewController.index = index
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
locationNameTextField.delegate = self
update(location: location)
}
func update(location: Location) {
locationNameTextField.text = location.name
timeZoneCell.textLabel?.text = location.timeZone.pseudoLocalizedName
timeZoneCell.detailTextLabel?.text = location.timeZone.localizedName(for: .standard, locale: Locale.current)
}
}
extension LocationEditorViewController: TimeZonePickerDelegate {
func timeZonePicker(_ timeZonePicker: TimeZonePicker, didSelect timeZone: TimeZone) {
location.timeZone = timeZone
}
}
extension LocationEditorViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if let name = textField.text, !name.isEmpty {
self.location.name = name
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
extension LocationEditorViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath as IndexPath)
if cell == timeZoneCell {
let timeZonePicker = TimeZonePicker(timeZone: location.timeZone)
timeZonePicker.delegate = self
let navigationController = UINavigationController(rootViewController: timeZonePicker)
self.present(navigationController, animated: true, completion: nil)
}
}
}
| mit | 49f36b1b44d74896261318287129e45b | 33.56962 | 120 | 0.701575 | 5.619342 | false | false | false | false |
mozilla-mobile/firefox-ios | Shared/RemoteDevices.swift | 2 | 918 | // 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 SwiftyJSON
public protocol RemoteDevices {
func replaceRemoteDevices(_ remoteDevices: [RemoteDevice]) -> Success
}
open class RemoteDevice {
public let id: String?
public let name: String
public let type: String?
public let isCurrentDevice: Bool
public let lastAccessTime: Timestamp?
public let availableCommands: JSON?
public init(id: String?, name: String, type: String?, isCurrentDevice: Bool, lastAccessTime: Timestamp?, availableCommands: JSON?) {
self.id = id
self.name = name
self.type = type
self.isCurrentDevice = isCurrentDevice
self.lastAccessTime = lastAccessTime
self.availableCommands = availableCommands
}
}
| mpl-2.0 | b60707e9ee4fce506864342e35a650c7 | 33 | 136 | 0.704793 | 4.613065 | false | false | false | false |
sambatech/player_sdk_ios_sample_app | SBPlayerSample/Helpers.swift | 1 | 5439 | //
// Commons.swift
// TesteMobileIOS
//
// Created by Leandro Zanol on 3/8/16.
// Copyright © 2016 Sambatech. All rights reserved.
//
import Foundation
import UIKit
class Helpers {
static let settings = NSDictionary.init(contentsOfFile: Bundle.main.path(forResource: "Configs", ofType: "plist")!)! as! [String:String]
static func requestURL<T>(_ url: String, _ callback: ((T?) -> Void)?) {
guard let urlObj = URL(string: url) else {
print("\(type(of: self)) Error: Invalid URL format: \(url)")
return
}
requestURL(URLRequest(url: urlObj), callback)
}
static func requestURL(_ url: String) {
requestURL(url, nil as ((Data?) -> Void)?)
}
static func requestURL<T>(_ urlRequest: URLRequest, _ callback: ((T?) -> Void)?) {
let requestTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
let reqText = "\n\(urlRequest.url?.absoluteString ?? "")\nMethod: \(urlRequest.httpMethod ?? "")\nHeader: \(String(describing: urlRequest.allHTTPHeaderFields))"
if let error = error {
print("\(type(of: self)) Error: \(error.localizedDescription)\(reqText)")
callback?(nil)
return
}
guard let response = response as? HTTPURLResponse else {
print("\(type(of: self)) Error: No response from server.\(reqText)")
callback?(nil)
return
}
guard case 200..<300 = response.statusCode else {
print("\(type(of: self)) Error: Invalid server response (\(response)).\(reqText)")
callback?(nil)
return
}
guard let data = data else {
print("\(type(of: self)) Error: Unable to get data.\(reqText)")
callback?(nil)
return
}
switch T.self {
case is String.Type:
if let text = String(data: data, encoding: String.Encoding.utf8) {
callback?(text as? T)
}
else {
print("\(type(of: self)) Error: Unable to get text response.\(reqText)")
callback?(nil)
}
case is Data.Type:
callback?(data as? T)
default:
callback?(nil)
}
}
requestTask.resume()
}
static func requestURL(_ urlRequest: URLRequest) {
requestURL(urlRequest, nil as ((Data?) -> Void)?)
}
static func requestURLJson(_ url: String, _ callback: @escaping (AnyObject?) -> Void) {
requestURL(url) { (data: Data?) in
var jsonOpt: AnyObject?
do {
if let data = data {
jsonOpt = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
}
else {
print("\(type(of: self)) Error getting JSON data.")
}
}
catch {
print("\(type(of: self)) Error parsing JSON string.")
}
callback(jsonOpt)
}
}
}
extension UIColor {
convenience init(_ rgba: UInt) {
let t = rgba > 0xFFFFFF ? 3 : 2
var array = [CGFloat](repeating: 1.0, count: 4)
var n: UInt
for i in 0...t {
n = UInt((t - i)*8)
array[i] = CGFloat((rgba & 0xFF << n) >> n)/255.0
}
self.init(red: array[0], green: array[1], blue: array[2], alpha: array[3])
}
}
public extension UIImage {
/**
Tint, Colorize image with given tint color<br><br>
This is similar to Photoshop's "Color" layer blend mode<br><br>
This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br>
white will stay white and black will stay black as the lightness of the image is preserved<br><br>
<img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/>
**To**
<img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/>
- parameter tintColor: UIColor
- returns: UIImage
*/
public func tintPhoto(_ tintColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
context.setBlendMode(.normal)
UIColor.black.setFill()
context.fill(rect)
// draw original image
context.setBlendMode(.normal)
context.draw(self.cgImage!, in: rect)
// tint image (loosing alpha) - the luminosity of the original image is preserved
context.setBlendMode(.color)
tintColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(self.cgImage!, in: rect)
}
}
/**
Tint Picto to color
- parameter fillColor: UIColor
- returns: UIImage
*/
public func tintPicto(_ fillColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw tint color
context.setBlendMode(.normal)
fillColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(self.cgImage!, in: rect)
}
}
/**
Modified Image Context, apply modification on image
- parameter draw: (CGContext, CGRect) -> Void)
- returns: UIImage
*/
fileprivate func modifiedImage(_ draw: (CGContext, CGRect) -> Void) -> UIImage {
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext! = UIGraphicsGetCurrentContext()
assert(context != nil)
// correctly rotate image
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
draw(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| apache-2.0 | 32a8748aeb568f645d1285e74dc05d79 | 26.054726 | 163 | 0.661273 | 3.535761 | false | false | false | false |
vendelal/wave | AudioKit/Instrument.swift | 1 | 2184 | //
// Instrument.swift
// AudioKit
//
// Created by Matthew Russo on 11/12/15.
// Copyright © 2015 AudioKit. All rights reserved.
//
class FMSynth: AKInstrument {
var frequency = AKInstrumentProperty(value: 440, minimum: 150, maximum: 740)
var carrierMultiplier = AKInstrumentProperty(value: 0.5, minimum: 0.0, maximum: 1.0)
var modulationIndex = AKInstrumentProperty(value: 0.5, minimum: 0.0, maximum: 1.0)
var amplitude = AKInstrumentProperty(value: 0.25, minimum: 0.0, maximum: 0.5)
override init() {
super.init()
let fmOscillator = AKFMOscillator()
fmOscillator.baseFrequency = frequency
fmOscillator.carrierMultiplier = carrierMultiplier
fmOscillator.modulationIndex = modulationIndex
fmOscillator.amplitude = amplitude
setAudioOutput(fmOscillator)
}
}
class touchInstrument: AKInstrument {
// INSTRUMENT CONTROLS =====================================================
var frequency = AKInstrumentProperty(value: 440, minimum: 1.0, maximum: 880)
var carrierMultiplier = AKInstrumentProperty(value: 1.0, minimum: 0.0, maximum: 2.0)
var modulatingMultiplier = AKInstrumentProperty(value: 1, minimum: 0, maximum: 2)
var modulationIndex = AKInstrumentProperty(value: 15, minimum: 0, maximum: 30)
var amplitude = AKInstrumentProperty(value: 0.1, minimum: 0, maximum: 0.2)
// INSTRUMENT DEFINITION ===================================================
override init() {
super.init()
addProperty(frequency)
addProperty(amplitude)
addProperty(carrierMultiplier)
addProperty(modulatingMultiplier)
addProperty(modulationIndex)
let fmOscillator = AKFMOscillator(
waveform: AKTable.standardSineWave(),
baseFrequency: frequency,
carrierMultiplier: carrierMultiplier,
modulatingMultiplier: modulatingMultiplier,
modulationIndex: modulationIndex,
amplitude: amplitude
)
setAudioOutput(fmOscillator)
}
}
| mit | 5b1a5b4c32f108e702790c9c4c8f6192 | 32.075758 | 91 | 0.614292 | 5.197619 | false | false | false | false |
jfrowies/iEMI | iEMI/BalanceViewController.swift | 1 | 10505 | //
// BalanceViewController.swift
// iEMI
//
// Created by Fer Rowies on 2/6/15.
// Copyright (c) 2015 Rowies. All rights reserved.
//
import UIKit
class BalanceViewController: NetworkActivityViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var creditBalanceView: CreditBalanceView!
private var refreshControl: UIRefreshControl!
private var _transactions: [Transaction]?
private var transactions : [Transaction] {
get {
return _transactions ?? [Transaction]()
}
set {
_transactions = newValue
for transaction in self.transactions {
if transaction.isKindOfClass(Debit) {
let debit = transaction as! Debit
let parking = Parking(number: debit.number, year: debit.year, serie: debit.serie)
parkingInformationService.detail(parking, completion: { [weak self, debit] (result) -> Void in
do {
let parkingInfo: ParkingGeneral = try result()
if let amount = parkingInfo.fareAmount {
self?.debitAmounts[debit.number] = Float(amount)
}
self?.tableView.reloadData()
} catch {
}
})
}
}
}
}
private var debitAmounts = [String:Float]()
private var parkingSelected: Parking?
private var sectionItemCount = [Int]()
private var sectionFirstItem = [Int]()
private var balance = 0.0
let service: AccountEMIService = AccountEMIService()
let parkingInformationService: ParkingInformationEMIService = ParkingInformationEMIService()
let licensePlateSotrage = LicensePlate()
private let kCreditBalanceHeaderViewNibName = "CreditBalanceHeaderView"
private let kCreditBalanceHeaderViewReuseId = "CreditBalanceHeaderViewReuseId"
private let kBalanceCellDefaultHeight: CGFloat = 62.0
private let kBalanceHeaderDefaultHeight: CGFloat = 30.0
//MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
refresh(self)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(BalanceViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
refreshControl.tintColor = UIColor.orangeGlobalTintColor()
refreshControl.backgroundColor = UIColor.lightGrayBackgroundColor()
tableView.addSubview(refreshControl)
let nib = UINib(nibName: kCreditBalanceHeaderViewNibName, bundle: nil)
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: kCreditBalanceHeaderViewReuseId)
let tableViewInsets = UIEdgeInsetsMake(0.0, 0.0, (self.tabBarController?.tabBar.frame.size.height)!, 0.0)
tableView.contentInset = tableViewInsets
tableView.scrollIndicatorInsets = tableViewInsets
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if refreshControl.refreshing {
refreshControl.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: -
func reloadData(patente patente: String) {
self.reloadTableHeaderData(patente: patente)
self.reloadTableData(patente: patente)
}
func reloadTableData(patente patente: String) {
service.balance(licensePlate: patente) { [unowned self] (result) -> Void in
do {
let transactions = try result()
self.transactions = transactions
self.tableView.reloadData()
self.refreshControl.endRefreshing()
if transactions.count == 0 {
self.tableView.hidden = true
} else {
self.tableView.hidden = false
}
self.hideLoadingView(animated: true)
} catch let error{
self.tableView.hidden = false
self.showError(error as NSError)
}
}
}
private let kCreditBalanceText = NSLocalizedString("Credit balance", comment: "Credit balancen title text")
private let kCreditBalanceSeparator = ": "
private let kCreditBalanceSign = " $"
private let kUnknownCreditBalance = NSLocalizedString("Unknown", comment: "Unknown credit balance")
func reloadTableHeaderData(patente licensePlate: String) {
service.accountBalance(licensePlate: licensePlate) { [unowned self] (result) -> Void in
do {
let currentBalance = try result()
self.balance = currentBalance
let creditBalanceString = String(format: "%.2f", currentBalance)
self.creditBalanceView?.creditBalanceLabel.text = self.kCreditBalanceText + self.kCreditBalanceSeparator + creditBalanceString + self.kCreditBalanceSign
} catch let error{
self.creditBalanceView?.creditBalanceLabel.text = self.kCreditBalanceText + self.kCreditBalanceSeparator + self.kUnknownCreditBalance
self.balance = 0.0
self.showError(error as NSError)
}
}
}
private let kErrorText = NSLocalizedString("Error loading balance, please try again later.", comment: "error loading balance text")
func showError(error: NSError?) {
print("Error: \(error)")
self.showErrorView(kErrorText, animated:false)
}
//MARK: - IBAction
private let kLoadingCreditText = NSLocalizedString("Loading balance", comment: "loading credit balance text")
@IBAction func refresh(sender:AnyObject) {
if let currentLicensePlate = licensePlateSotrage.currentLicensePlate {
if !(sender.isEqual(self.refreshControl)) {
self.showLoadingView(kLoadingCreditText, animated:false)
}
self.reloadData(patente:currentLicensePlate)
}
}
//MARK: - UITableViewDelegate implementation
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
self.sectionItemCount.removeAll(keepCapacity: false)
self.sectionFirstItem.removeAll(keepCapacity: false)
var sections = 0;
var date: String = "";
var index: Int = 0;
for mov: Transaction in self.transactions {
let timestamp: String = mov.timestamp
let subDate = timestamp.substringToIndex(timestamp.startIndex.advancedBy(10))
if (!(date == subDate)) {
date = subDate
self.sectionItemCount.append(0)
self.sectionFirstItem.append(index)
sections += 1
}
self.sectionItemCount[sections - 1] = self.sectionItemCount[sections - 1] + 1
index += 1
}
return sections
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sectionItemCount[section]
}
private let kCreditCellReuseId = "creditoCell"
private let kDebitCellReuseId = "consumoCell"
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let movimiento = self.transactions[self.sectionFirstItem[indexPath.section] + indexPath.row]
if movimiento.isKindOfClass(Credit) {
let cell = self.tableView.dequeueReusableCellWithIdentifier(kCreditCellReuseId, forIndexPath: indexPath) as! CreditoTableViewCell
cell.credito = movimiento as! Credit
return cell
}
if movimiento.isKindOfClass(Debit) {
let cell = self.tableView.dequeueReusableCellWithIdentifier(kDebitCellReuseId, forIndexPath: indexPath) as! ConsumoTableViewCell
let debit = movimiento as! Debit
if let debitAmount = self.debitAmounts[debit.number] {
debit.amount = String(format: "%0.2f", debitAmount)
}
cell.debit = debit
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if let debit = self.transactions[self.sectionFirstItem[indexPath.section] + indexPath.row] as? Debit {
self.parkingSelected = Parking(number: debit.number, year: debit.year, serie: debit.serie)
}else{
return nil
}
return indexPath
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return kBalanceCellDefaultHeight
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(kCreditBalanceHeaderViewReuseId) as? CreditBalanceHeaderView
let mov = self.transactions[self.sectionFirstItem[section]];
let timestamp: String = mov.timestamp
let subDate = timestamp.substringToIndex(timestamp.startIndex.advancedBy(10))
let nsDate = NSDate(dateString: subDate)
headerView?.sectionTitleLabel.text = nsDate.formattedDateString()
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return kBalanceHeaderDefaultHeight
}
// MARK: - Navigation
private let kShowParkingInformationSegueId = "showParkingInformation"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == kShowParkingInformationSegueId {
let dvc = segue.destinationViewController as! ParkingInformationViewController
dvc.parking = self.parkingSelected
}
}
}
| apache-2.0 | b5999856c83c1d95f46fc1c12c372db3 | 37.339416 | 168 | 0.630842 | 5.558201 | false | false | false | false |
max9631/Piskvorky | Piškvorky/MenuWindow.swift | 1 | 2772 | //
// MenuWindow.swift
// Piškvorky
//
// Created by Adam Salih on 03/06/15.
// Copyright (c) 2015 Adam Salih. All rights reserved.
//
import UIKit
class MenuWindow: UIViewController {
@IBOutlet weak var textLabel: UILabel!
var currentWindow:WindowManager!
override init() {
super.init(nibName: "MenuWindow", bundle: nil)
}
override func viewDidLoad() {
self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)
self.view.backgroundColor = blue
self.textLabel.frame.origin.x = (UIScreen.mainScreen().bounds.width / 2) - (textLabel.frame.width / 2)
self.textLabel.frame.origin.y = (UIScreen.mainScreen().bounds.height / 4) - (textLabel.frame.height / 2)
let notcen = NSNotificationCenter.defaultCenter()
notcen.addObserver(self, selector: "segue:", name: "segueToAnotherScreen", object: nil)
let mainMenu = MainMenu()
notcen.postNotificationName("segueToAnotherScreen", object: mainMenu, userInfo: ["smer":"nahoru"])
}
func segue(notification:NSNotification){
UIView.animateWithDuration(0.6, animations: {
self.textLabel.alpha = 0
})
let window = notification.object as WindowManager
self.view.addSubview(window.getView())
self.currentWindow = window
let dic = notification.userInfo as [String:String]
if dic["color"] == "white"{
self.view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.9)
}else{
UIView.animateWithDuration(0.5, animations: {
self.view.backgroundColor = blue
})
self.prepareForAppear(windows: window.windowsObjects(), smer: dic["smer"]!)
}
window.makeAppear(titleLabel: self.textLabel)
}
func prepareForAppear(#windows:[UIView], smer: String){
if smer == "nahoru"{
for view in windows{
view.frame.origin.y = UIScreen.mainScreen().bounds.height
}
}else if smer == "dolu"{
for view in windows{
view.frame.origin.y = -(view.frame.height)
}
}else if smer == "doleva"{
for view in windows{
view.frame.origin.x = UIScreen.mainScreen().bounds.width
}
}else if smer == "doprava"{
for view in windows{
view.frame.origin.x = -(view.frame.width)
}
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
@objc protocol WindowManager {
func makeAppear(#titleLabel:UILabel)
func windowsObjects() -> [UIView]
func getView() -> UIView
} | gpl-2.0 | 1d3d40fbe11a83b7b04568f998a54c5f | 33.65 | 132 | 0.601949 | 4.185801 | false | false | false | false |
lecksfrawen/HeaderDLHamburgerMenuTest | DLHamburguerMenu/DLDemoMenuViewController.swift | 1 | 2081 | //
// DLDemoMenuViewController.swift
// DLHamburguerMenu
//
// Created by Nacho on 5/3/15.
// Copyright (c) 2015 Ignacio Nieto Carvajal. All rights reserved.
//
import UIKit
class DLDemoMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// outlets
@IBOutlet weak var tableView: UITableView!
// data
let segues = ["Mi Perfil", "Notificaciones", "Valorar", "Más aplicaciones","Acerca de la app", "Cerrar sesión"]
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad desde VC inicial")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITableViewDelegate&DataSource methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return segues.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath)
cell.textLabel?.text = segues[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let nvc = self.mainNavigationController()
if let hamburguerViewController = self.findHamburguerViewController() {
hamburguerViewController.hideMenuViewControllerWithCompletion({ () -> Void in
nvc.visibleViewController!.performSegueWithIdentifier(self.segues[indexPath.row], sender: nil)
hamburguerViewController.contentViewController = nvc
})
}
}
// MARK: - Navigation
func mainNavigationController() -> DLHamburguerNavigationController {
return self.storyboard?.instantiateViewControllerWithIdentifier("DLDemoNavigationViewController") as! DLHamburguerNavigationController
}
}
| mit | 69e353eba6870102922582cb1a5311d3 | 34.844828 | 142 | 0.695046 | 5.471053 | false | false | false | false |
wildthink/BagOfTricks | BagOfTricks/SpeechController.swift | 1 | 4199 | //
// SpeechController.swift
// SpeechRecognition
//
// Created by Stephen Anthony on 24/11/2016.
// Copyright © 2016 Darjeeling Apps. All rights reserved.
//
import Foundation
import Speech
/// The class used to control speech recognition sessions.
@available(iOS 10.0, *)
open class SpeechController {
private static let inputNodeBus: AVAudioNodeBus = 0
/// The speech recogniser used by the controller to record the user's speech.
private let speechRecogniser = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
/// The current speech recognition request. Created when the user wants to begin speech recognition.
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
/// The current speech recognition task. Created when the user wants to begin speech recognition.
private var recognitionTask: SFSpeechRecognitionTask?
/// The audio engine used to record input from the microphone.
private let audioEngine = AVAudioEngine()
/// The delegate of the receiver.
public var delegate: SpeechControllerDelegate?
public init () {
}
/// Begins a new speech recording session.
///
/// - Throws: Errors thrown by the creation of the speech recognition session
open func startRecording() throws {
guard speechRecogniser.isAvailable else {
// Speech recognition is unavailable, so do not attempt to start.
return
}
if let recognitionTask = recognitionTask {
// We have a recognition task still running, so cancel it before starting a new one.
recognitionTask.cancel()
self.recognitionTask = nil
}
guard SFSpeechRecognizer.authorizationStatus() == .authorized else {
SFSpeechRecognizer.requestAuthorization({ _ in })
return
}
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let inputNode = audioEngine.inputNode, let recognitionRequest = recognitionRequest else {
throw SpeechControllerError.noAudioInput
}
recognitionTask = speechRecogniser.recognitionTask(with: recognitionRequest) { [unowned self] result, error in
if let result = result {
self.delegate?.speechController(self, didRecogniseText: result.bestTranscription.formattedString)
}
if result?.isFinal ?? (error != nil) {
inputNode.removeTap(onBus: SpeechController.inputNodeBus)
}
}
let recordingFormat = inputNode.outputFormat(forBus: SpeechController.inputNodeBus)
inputNode.installTap(onBus: SpeechController.inputNodeBus, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
try audioEngine.start()
}
/// Ends the current speech recording session.
open func stopRecording() {
audioEngine.stop()
recognitionRequest?.endAudio()
}
}
/// The protocol to conform to for delegates of `SpeechController`.
@available(iOS 10.0, *)
public protocol SpeechControllerDelegate {
/// The message sent when the user's speech has been transcribed. Will be called with partial results of the current recording session.
///
/// - Parameters:
/// - speechController: The controller sending the message.
/// - text: The text transcribed from the user's speech.
func speechController(_ speechController: SpeechController, didRecogniseText text: String)
}
/// The error types vended by `SpeechController` if it cannot create an audio recording session.
///
/// - noAudioInput: No audio input connection could be created.
public enum SpeechControllerError: Error {
case noAudioInput
}
| mit | e1295b565d6b29543af3207914b8d4ee | 37.87037 | 160 | 0.683182 | 5.560265 | false | false | false | false |
KiiPlatform/thing-if-iOSSample | SampleProject/OnBoardViewController.swift | 1 | 2107 | //
// OnBoardViewController.swift
// SampleProject
//
// Created by Yongping on 8/24/15.
// Copyright © 2015 Kii Corporation. All rights reserved.
//
import UIKit
import ThingIFSDK
class OnBoardViewController: KiiBaseTableViewController {
@IBOutlet weak var thingTypeTextField: UITextField!
@IBOutlet weak var vendorThingID: UITextField!
@IBOutlet weak var thingPassTextField: UITextField!
@IBOutlet weak var thingIDTextField: UITextField!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func tapOnboardWithVendorThingID(sender: AnyObject) {
if let vendorThingID = vendorThingID.text, thingPassword = thingPassTextField.text {
showActivityView(true)
self.iotAPI?.onboard(vendorThingID, thingPassword: thingPassword, thingType: thingTypeTextField.text, thingProperties: nil, completionHandler: { (target, error) -> Void in
if target != nil {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
self.showActivityView(false)
}else {
self.showAlert("Onboard Failed", error: error, completion: { () -> Void in
self.showActivityView(false)
})
}
})
}
}
@IBAction func tapOnBoardWithThingID(sender: AnyObject) {
if let thingID = thingIDTextField.text, thingPassword = thingPassTextField.text {
showActivityView(true)
self.iotAPI?.onboard(thingID, thingPassword: thingPassword, completionHandler: { (target, error) -> Void in
if target != nil {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
self.showActivityView(false)
}else {
self.showAlert("Onboard Failed", error: error, completion: { () -> Void in
self.showActivityView(false)
})
}
})
}
}
} | mit | 6f8bb2aad939788d363619c85190abb7 | 38.018519 | 183 | 0.615385 | 5.225806 | false | false | false | false |
OscarSwanros/swift | test/SILGen/complete_object_init.swift | 3 | 2082 | // RUN: %target-swift-frontend %s -emit-silgen -enable-sil-ownership | %FileCheck %s
struct X { }
class A {
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A
// CHECK: bb0([[SELF_META:%[0-9]+]] : @trivial $@thick A.Type):
// CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A
// CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A
// CHECK: return [[RESULT]] : $A
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : @owned $A):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A }
// CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var A }
// CHECK: [[PB:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: store [[SELF_PARAM]] to [init] [[PB]] : $*A
// CHECK: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*A
// CHECK: [[BORROWED_SELFP:%.*]] = begin_borrow [[SELFP]]
// CHECK: [[INIT:%[0-9]+]] = class_method [[BORROWED_SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A
// CHECK: store [[INIT_RESULT]] to [init] [[PB]] : $*A
// CHECK: [[RESULT:%[0-9]+]] = load [copy] [[PB]] : $*A
// CHECK: destroy_value [[UNINIT_SELF]] : ${ var A }
// CHECK: return [[RESULT]] : $A
convenience init() {
self.init(x: X())
}
init(x: X) { }
}
| apache-2.0 | 290adae440aa5de3a3ce2e647aa3e34b | 56.833333 | 161 | 0.551393 | 2.776 | false | false | false | false |
OscarSwanros/swift | validation-test/Sema/type_checker_perf/slow/rdar18800950.swift | 4 | 496 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
// Mixed Float and Double arithmetic
func rdar18800950(v: Float) -> Double {
let c1: Float = 1.0
let c2 = 2.0
let r = v / c1
let _ = (c2 * 2 * (3 * (1 - c1 / v) - 4) * r + 5) * (c2 * 2 * (3 * (1 - c1 / v) - 4) * r + 5)
// expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}}
}
| apache-2.0 | 9c4f87933551b679c6b72f75ec66bf22 | 44.090909 | 152 | 0.637097 | 2.97006 | false | false | false | false |
LDlalala/LDZBLiving | LDZBLiving/LDZBLiving/Classes/Main/Protocal/Emitterable.swift | 1 | 2225 | //
// Emitterable.swift
// Emittering-粒子运动
//
// Created by 李丹 on 17/8/11.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
protocol Emitterable : class {
}
// MARK:- 添加协议方法,只要继承自这个协议,那么就可以实现协议
extension Emitterable where Self : UIViewController { // 给一个限制条件
func startEmittering(_ point : CGPoint) {
// 创建发射器
let emitter = CAEmitterLayer()
// 设置发射器位置
emitter.emitterPosition = point
// 开启三维效果
emitter.preservesDepth = true
// 创建粒子,并设置栗子相关属性
var cells = [CAEmitterCell]()
for i in 0..<10 {
let cell = CAEmitterCell()
// 设置速度
cell.velocity = 150
cell.velocityRange = 100
// 设置栗子大小
cell.scale = 0.7
cell.scaleRange = 0.3
// 设置栗子方向c
cell.emissionLatitude = CGFloat(-M_PI_2)
cell.emissionRange = CGFloat(M_PI_2 / 6)
// 设置栗子旋转
cell.spin = CGFloat(M_PI_2)
cell.spinRange = CGFloat(M_PI_2 / 2)
// 设置栗子每秒弹出的个数
cell.birthRate = 2
// 设置生命时间
cell.lifetime = 7
cell.lifetimeRange = 1.5
// 设置内容图片
cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
cells.append(cell)
}
// 将栗子设置到发射器中
emitter.emitterCells = cells
// 将发射器的layer添加到父类的layer中
view.layer.addSublayer(emitter)
}
func stopEmittering() {
view.layer.sublayers?.filter({$0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer()
/*
for layer in view.layer.sublayers! {
if layer.isKind(of: CAEmitterLayer.self) {
layer.removeFromSuperlayer()
}
}
*/
}
}
| mit | 3c54d099ed4b08b1fe68a0062f285959 | 22.518072 | 104 | 0.492316 | 4.271335 | false | false | false | false |
TMTBO/TTARefresher | TTARefresher/Classes/Footer/Auto/TTARefresherAutoStateFooter.swift | 1 | 2093 | //
// TTARefresherAutoStateFooter.swift
// Pods
//
// Created by TobyoTenma on 11/05/2017.
//
//
import UIKit
open class TTARefresherAutoStateFooter: TTARefresherAutoFooter {
open lazy var stateLabel: UILabel = {
let label = UILabel.TTARefresher.refresherLabel()
self.addSubview(label)
return label
}()
var stateTitles = [TTARefresherState: String]()
var labelLeftInset = TTARefresherLabelConst.labelLeftInset
open override var state: TTARefresherState {
didSet {
if state == oldValue { return }
if stateLabel.isHidden && state == .refreshing {
stateLabel.text = nil
} else {
stateLabel.text = stateTitles[state]
}
}
}
}
// MARK: - Public Method
extension TTARefresherAutoStateFooter {
public func set(title: String, for state: TTARefresherState) {
stateTitles[state] = title
stateLabel.text = stateTitles[self.state]
}
}
// MARK: - Private Methods
extension TTARefresherAutoStateFooter {
func didClickStateLabel() {
guard state == .idle else { return }
beginRefreshing()
}
}
// MARK: - Override Methods
extension TTARefresherAutoStateFooter {
override open func prepare() {
super.prepare()
labelLeftInset = TTARefresherLabelConst.labelLeftInset
set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.idle), for: .idle)
set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.refreshing), for: .refreshing)
set(title: Bundle.TTARefresher.localizedString(for: TTARefresherAutoFooterText.noMoreData), for: .noMoreData)
stateLabel.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(didClickStateLabel))
stateLabel.addGestureRecognizer(tap)
}
override open func placeSubviews() {
super.placeSubviews()
if stateLabel.constraints.count != 0 { return }
stateLabel.frame = bounds
}
}
| mit | 6cbab5e0f8a542d33e4cf5895ae2b5d3 | 28.069444 | 117 | 0.666507 | 4.983333 | false | false | false | false |
CoderAzreal/AZQrCodeScanController | AZQrCodeScanController/AZQrCodeScanController-Swift/AZSwiftQrCodeScanView.swift | 1 | 4565 | //
// AZSwiftQrCodeScanView.swift
// AZQrCodeScanController
//
// Created by tianfengyu on 2017/6/13.
// Copyright © 2017年 Azreal. All rights reserved.
//
import UIKit
class AZSwiftQrCodeScanView: UIView {
var topCoverView = UIView()
var leftCoverView = UIView()
var rightCoverView = UIView()
var bottomCoverView = UIView()
fileprivate var scanFrame: CGRect!
var scanImageView: UIImageView! // 扫码框
var scanLine: UIImageView! // 扫码线
var introduceLabel: UILabel! // 提示文字label
enum AZTimerState {
case move
case stop
}
/// 扫码线移动方向
private enum LineMoveDirect {
case up
case down
}
var timer: DispatchSourceTimer!
var timerState = AZTimerState.move
private var lineDirection = LineMoveDirect.down
convenience init(scanFrame: CGRect) {
self.init(frame: CGRect(x: 0, y: 0, width: AZ_screenWidth, height: AZ_screenHeight))
configCoverView()
self.scanFrame = scanFrame
resetCoverViewFrame()
configScanUI()
configTimer()
}
/// 扫码线移动
private func configTimer() {
timer = DispatchSource.makeTimerSource(flags: .strict, queue: .main)
timer.scheduleRepeating(deadline: .now(), interval: .milliseconds(10))
weak var wkSelf = self
timer.setEventHandler {
var lineFrame = wkSelf!.scanLine.frame
switch wkSelf!.timerState {
case .move:
switch wkSelf!.lineDirection {
case .up:
lineFrame.origin.y -= 1
case .down:
lineFrame.origin.y += 1
}
case .stop:
lineFrame.origin.y = wkSelf!.scanFrame.origin.y
}
wkSelf?.scanLine.frame = lineFrame
if lineFrame.origin.y >= wkSelf!.scanFrame.origin.y + wkSelf!.scanFrame.width - lineFrame.size.height {
wkSelf!.lineDirection = .up
} else if lineFrame.origin.y <= wkSelf!.scanFrame.origin.y {
wkSelf!.lineDirection = .down
}
}
timer.resume()
}
/// 扫码框/扫码线/介绍文字
private func configScanUI() {
let bundlePath = Bundle(for: classForCoder).path(forResource: "AZQrCode", ofType: "bundle")!
let captureBundle = Bundle(path: bundlePath)!
scanImageView = UIImageView(frame: scanFrame)
let bgPath = captureBundle.path(forResource: "scan_bg_pic@2x", ofType: "png")!
scanImageView.image = UIImage(contentsOfFile: bgPath)
addSubview(scanImageView)
scanLine = UIImageView(frame: CGRect(x: scanFrame.origin.x, y: scanFrame.origin.y
, width: scanFrame.width, height: 2))
let linePath = captureBundle.path(forResource: "scan_line@2x", ofType: "png")!
scanLine.image = UIImage(contentsOfFile: linePath)
addSubview(scanLine)
introduceLabel = UILabel(frame: CGRect(x: scanFrame.origin.x, y: scanFrame.origin.y+scanFrame.size.height+20, width: scanFrame.width, height: 40))
introduceLabel.numberOfLines = 0
introduceLabel.textAlignment = .center
introduceLabel.text = "将二维码/条码放入框内,即可自动扫描。"
introduceLabel.textColor = .white
introduceLabel.font = UIFont.systemFont(ofSize: 14)
addSubview(introduceLabel)
}
/// 配置coverView
private func configCoverView() {
for item in [topCoverView, leftCoverView, bottomCoverView, rightCoverView] {
item.backgroundColor = UIColor(white: 0, alpha: 0.4)
addSubview(item)
}
}
/// 设置遮罩层位置
private func resetCoverViewFrame() {
leftCoverView.frame = CGRect(x: 0, y: 0, width: scanFrame.origin.x, height: AZ_screenHeight)
topCoverView.frame = CGRect(x: scanFrame.origin.x, y: 0, width: AZ_screenWidth, height: scanFrame.origin.y)
rightCoverView.frame = CGRect(x: scanFrame.origin.x, y: scanFrame.height+scanFrame.origin.y, width: AZ_screenWidth, height: AZ_screenHeight)
bottomCoverView.frame = CGRect(x: scanFrame.width+scanFrame.origin.x, y: scanFrame.origin.y, width: AZ_screenWidth, height: scanFrame.height)
}
override init(frame: CGRect) { super.init(frame: frame) }
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
| mit | 7b1c1ca691ce59f1541c79b7368648c8 | 36.033333 | 154 | 0.621062 | 4.395648 | false | false | false | false |
taku33/FolioReaderPlus | Source/EPUBCore/FRHighlight.swift | 1 | 6934 | //
// FRHighlight.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 26/08/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
enum HighlightStyle: Int {
case Yellow
case Green
case Blue
case Pink
case Underline
init () { self = .Yellow }
/**
Return HighlightStyle for CSS class.
*/
static func styleForClass(className: String) -> HighlightStyle {
switch className {
case "highlight-yellow":
return .Yellow
case "highlight-green":
return .Green
case "highlight-blue":
return .Blue
case "highlight-pink":
return .Pink
case "highlight-underline":
return .Underline
default:
return .Yellow
}
}
/**
Return CSS class for HighlightStyle.
*/
static func classForStyle(style: Int) -> String {
switch style {
case HighlightStyle.Yellow.rawValue:
return "highlight-yellow"
case HighlightStyle.Green.rawValue:
return "highlight-green"
case HighlightStyle.Blue.rawValue:
return "highlight-blue"
case HighlightStyle.Pink.rawValue:
return "highlight-pink"
case HighlightStyle.Underline.rawValue:
return "highlight-underline"
default:
return "highlight-yellow"
}
}
/**
Return CSS class for HighlightStyle.
*/
static func colorForStyle(style: Int, nightMode: Bool = false) -> UIColor {
switch style {
case HighlightStyle.Yellow.rawValue:
return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.Green.rawValue:
return UIColor(red: 192/255, green: 237/255, blue: 114/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.Blue.rawValue:
return UIColor(red: 173/255, green: 216/255, blue: 255/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.Pink.rawValue:
return UIColor(red: 255/255, green: 176/255, blue: 202/255, alpha: nightMode ? 0.9 : 1)
case HighlightStyle.Underline.rawValue:
return UIColor(red: 240/255, green: 40/255, blue: 20/255, alpha: nightMode ? 0.6 : 1)
default:
return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1)
}
}
}
class FRHighlight: NSObject {
var id: String!
var content: String!
var contentPre: String!
var contentPost: String!
var date: NSDate!
var page: NSNumber!
var bookId: String!
var type: HighlightStyle!
/**
Match a highlight on string.
*/
static func matchHighlight(text: String!, andId id: String) -> FRHighlight? {
let pattern = "<highlight id=\"\(id)\" onclick=\".*?\" class=\"(.*?)\">((.|\\s)*?)</highlight>"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count))
let str = (text as NSString)
print("patternは\(pattern)")
print("regexは\(regex)")
print("matchesは\(matches)")
print("strは\(str)")
let mapped = matches.map { (match) -> FRHighlight in
print("matchは\(match)")
var contentPre = str.substringWithRange(NSRange(location: match.range.location-kHighlightRange, length: kHighlightRange))
var contentPost = str.substringWithRange(NSRange(location: match.range.location + match.range.length, length: kHighlightRange))
// Normalize string before save
if contentPre.rangeOfString(">") != nil {
let regex = try! NSRegularExpression(pattern: "((?=[^>]*$)(.|\\s)*$)", options: [])
let searchString = regex.firstMatchInString(contentPre, options: .ReportProgress, range: NSRange(location: 0, length: contentPre.characters.count))
if searchString!.range.location != NSNotFound {
contentPre = (contentPre as NSString).substringWithRange(searchString!.range)
}
}
if contentPost.rangeOfString("<") != nil {
let regex = try! NSRegularExpression(pattern: "^((.|\\s)*?)(?=<)", options: [])
let searchString = regex.firstMatchInString(contentPost, options: .ReportProgress, range: NSRange(location: 0, length: contentPost.characters.count))
if searchString!.range.location != NSNotFound {
contentPost = (contentPost as NSString).substringWithRange(searchString!.range)
}
}
let highlight = FRHighlight()
highlight.id = id //ランダム文字列
highlight.type = HighlightStyle.styleForClass(str.substringWithRange(match.rangeAtIndex(1)))
highlight.content = str.substringWithRange(match.rangeAtIndex(2))
print("contentは\(highlight.content)")
print("contentPreは\(contentPre)")
print("contentPostは\(contentPost)")
highlight.contentPre = contentPre
highlight.contentPost = contentPost
highlight.page = currentPageNumber
highlight.bookId = (kBookId as NSString).stringByDeletingPathExtension
return highlight
}
return mapped.first
}
static func makeBookMarkFRHighlight(id: String) -> FRHighlight? {
let highlight = FRHighlight()
highlight.id = id //ランダム文字列
highlight.contentPre = FolioReader.sharedInstance.readerCenter.getCurrentChapterName()
//これらは章単位でなくページ単位
let currentPage = FolioReader.sharedInstance.readerCenter.pageIndicatorView.currentPage
let currentTotalPages = FolioReader.sharedInstance.readerCenter.pageIndicatorView.totalPages
highlight.content = "\(currentPage)/\(currentTotalPages)" //4/24など
highlight.contentPost = "\(currentPage)/\(currentTotalPages)" //初めて保存する場合なのでcontentと同じ
highlight.page = currentPageNumber
highlight.bookId = (kBookId as NSString).stringByDeletingPathExtension
return highlight
}
static func removeById(highlightId: String) -> String? {
let currentPage = FolioReader.sharedInstance.readerCenter.currentPage
if let removedId = currentPage.webView.js("removeHighlightById('\(highlightId)')") {
return removedId
} else {
print("Error removing Higlight from page")
return nil
}
}
} | bsd-3-clause | 3fd628a6f4dca67736b7efa6d0578ac8 | 37.353933 | 165 | 0.59874 | 4.903736 | false | false | false | false |
mr-ndrw/PulsingButtons | Pulsing Buttons/PulsingButtonsViewController.swift | 1 | 3753 | //
// PulsingButtonsViewController.swift
// Pulsing Buttons
//
// Created by Andrew Torski on 24/06/15.
// Copyright (c) 2015 Andrew Torski. All rights reserved.
//
import UIKit
class PulsingButtonsViewController: UIViewController {
var pulsingButtons2DArray : [[PulsingButtonView]] = []
/// Number of buttons in a row.
var numberOfButtonsInRow : Int = 9
/// Number of buttons in a column.
var numberOfButtonsInColumn : Int = 4
override func viewDidLoad() {
super.viewDidLoad()
var pointsMatrix : [CGPoint] = getPointArray( numberOfRows: numberOfButtonsInRow,
numberOfColumns: numberOfButtonsInColumn,
screenMargin: CGFloat(40.0))
for point in pointsMatrix {
var frame = CGRect(center: point, size: CGSize(width: 40.0, height: 40.0))
var currentColor = UIColor(redInt: 255, greenInt: 209, blueInt: 220, alpha: 1.0)
var pulsingButton : PulsingButtonView = PulsingButtonView(frame: frame, currentColor: currentColor)
self.view.addSubview(pulsingButton)
}
// Do any additional setup after loading the view.
}
func getPointArray(#numberOfRows: Int, numberOfColumns: Int, screenMargin: CGFloat) -> [CGPoint]{
// 2. find extremeCornerPoint1 by taking width and height and adding screenMargin to them
var extremePointUpperLeftCorner : CGPoint = CGPoint(x: screenMargin, y: screenMargin)
// 3. get deMarginalizedHeight by subtracting 2*screenMargin
// get deMarginalizedWidth by subtracting
let screenHeight : CGFloat = self.view.bounds.height
let screenWidth : CGFloat = self.view.bounds.width
let demarginalizedHeight : CGFloat = screenHeight - (2 * screenMargin)
let demarginalizedWidth : CGFloat = screenWidth - (2 * screenMargin)
// 4. get pointXDifference by dividing demarginalizedHeight by numberOfRows - 1
// get pointYDifference by diding demarginalizedWidth by numberOfColumns - 1
/*
We're subtracting
*/
let pointXDifference : CGFloat = demarginalizedWidth / CGFloat(numberOfColumns - 1)
let pointYDifference : CGFloat = demarginalizedHeight / CGFloat(numberOfRows - 1)
// 5. create an array of points
var pointArray : [CGPoint] = []
// 6. populate the array
var currentX : CGFloat = extremePointUpperLeftCorner.x
var currentY : CGFloat = extremePointUpperLeftCorner.y
for rowNumber in 0..<numberOfRows {
for columnNumber in 0..<numberOfColumns {
var newPoint : CGPoint = CGPoint(x: currentX, y: currentY)
pointArray.append(newPoint)
currentX += pointXDifference
}
// default currentX, since we're changing rows and going back to left edge
currentX = extremePointUpperLeftCorner.x
currentY += pointYDifference
}
return pointArray
}
func UIColorFromRGB(rgb: Int, alpha: Float) -> UIColor {
let red = CGFloat(Float(((rgb>>16) & 0xFF)) / 255.0)
let green = CGFloat(Float(((rgb>>8) & 0xFF)) / 255.0)
let blue = CGFloat(Float(((rgb>>0) & 0xFF)) / 255.0)
let alpha = CGFloat(alpha)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | ae3a079e1ff655f650e43026714621e6 | 39.793478 | 115 | 0.609379 | 4.970861 | false | false | false | false |
qRoC/Loobee | Sources/Loobee/Library/AssertionConcern/Assertion/GreaterThanAssertions.swift | 1 | 2084 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
/// The default message in notifications from `greaterThan` assertions.
@usableFromInline internal let kGreaterThanDefaultMessage: StaticString = """
The value is not greater than boundary value.
"""
/// Determines if the `value` is greater than given limit value.
@inlinable
public func assert<T: Comparable>(
_ value: T,
greaterThan boundaryValue: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value <= boundaryValue) {
return .create(
message: message() ?? kGreaterThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is greater than given limit value.
@inlinable
public func assert<T1: BinaryInteger, T2: BinaryInteger>(
_ value: T1,
greaterThan boundaryValue: T2,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value <= boundaryValue) {
return .create(
message: message() ?? kGreaterThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is greater than given limit value.
///
/// - Note: This is ambiguity breaker.
@inlinable
public func assert<T: BinaryInteger>(
_ value: T,
greaterThan boundaryValue: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value <= boundaryValue) {
return .create(
message: message() ?? kGreaterThanDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
| mit | d3e5e6d00a6d2df37c441159ddb612a5 | 27.547945 | 77 | 0.645393 | 4.33264 | false | false | false | false |
serieuxchat/SwiftySRP | SwiftySRP/SRPConfigurationGenericImpl.swift | 1 | 5337 | //
// SRPConfigurationGenericImpl.swift
// SwiftySRP
//
// Created by Sergey A. Novitsky on 17/03/2017.
// Copyright © 2017 Flock of Files. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// Implementation: configuration for SRP algorithms (see the spec. above for more information about the meaning of parameters).
struct SRPConfigurationGenericImpl<BigIntType: SRPBigIntProtocol>: SRPConfiguration
{
typealias PrivateValueFunc = () -> BigIntType
/// A large safe prime per SRP spec. (Also see: https://tools.ietf.org/html/rfc5054#appendix-A)
public var modulus: Data {
return _N.serialize()
}
/// A generator modulo N. (Also see: https://tools.ietf.org/html/rfc5054#appendix-A)
public var generator: Data {
return _g.serialize()
}
/// A large safe prime per SRP spec.
let _N: BigIntType
/// A generator modulo N
let _g: BigIntType
/// Hash function to be used.
let digest: DigestFunc
/// Function to calculate HMAC
let hmac: HMacFunc
/// Custom function to generate 'a'
let _aFunc: PrivateValueFunc?
/// Custom function to generate 'b'
let _bFunc: PrivateValueFunc?
/// Create a configuration with the given parameters.
///
/// - Parameters:
/// - N: The modulus (large safe prime) (per SRP spec.)
/// - g: The group generator (per SRP spec.)
/// - digest: Hash function to be used in intermediate calculations and to derive a single shared key from the shared secret.
/// - hmac: HMAC function to be used when deriving multiple shared keys from a single shared secret.
/// - aFunc: (ONLY for testing purposes) Custom function to generate the client private value.
/// - bFunc: (ONLY for testing purposes) Custom function to generate the server private value.
init(N: BigIntType,
g: BigIntType,
digest: @escaping DigestFunc = CryptoAlgorithm.SHA256.digestFunc(),
hmac: @escaping HMacFunc = CryptoAlgorithm.SHA256.hmacFunc(),
aFunc: PrivateValueFunc?,
bFunc: PrivateValueFunc?)
{
_N = BigIntType(N)
_g = BigIntType(g)
self.digest = digest
self.hmac = hmac
_aFunc = aFunc
_bFunc = bFunc
}
/// Check if configuration is valid.
/// Currently only requires the size of the prime to be >= 256 and the g to be greater than 1.
/// - Throws: SRPError if invalid.
func validate() throws
{
guard _N.bitWidth >= 256 else { throw SRPError.configurationPrimeTooShort }
guard _g > BigIntType(1) else { throw SRPError.configurationGeneratorInvalid }
}
/// Generate a random private value less than the given value N and at least half the bit size of N
///
/// - Parameter N: The value determining the range of the random value to generate.
/// - Returns: Randomly generate value.
public static func generatePrivateValue(N: BigIntType) -> BigIntType
{
// Suppose that N is 8 bits wide
// Then min bits == 4
let minBits = N.bitWidth / 2
guard minBits > 0 else { return BigIntType.randomInteger(lessThan: BigIntType(2)) }
// Smallest number with 4 bits is 2^(4-1) = 8
let minBitsNumber = BigIntType(2).power(minBits - 1)
let random = minBitsNumber + BigIntType.randomInteger(lessThan: N - minBitsNumber)
return random
}
/// Function to calculate parameter a (per SRP spec above)
func _a() -> BigIntType
{
if let aFunc = _aFunc
{
return aFunc()
}
return type(of: self).generatePrivateValue(N: _N)
}
/// Function to calculate parameter a (per SRP spec above)
func clientPrivateValue() -> Data
{
return _a().serialize()
}
/// Function to calculate parameter b (per SRP spec above)
func _b() -> BigIntType
{
if let bFunc = _bFunc
{
return bFunc()
}
return type(of: self).generatePrivateValue(N: _N)
}
/// Function to calculate parameter b (per SRP spec above)
func serverPrivateValue() -> Data
{
return _b().serialize()
}
}
| mit | 7676f6ed9fbbdcd139b2c278bf583846 | 35.547945 | 131 | 0.650112 | 4.491582 | false | true | false | false |
ivanbruel/SwipeIt | SwipeIt/ViewModels/Link/LinkSwipeViewModel.swift | 1 | 5440 | //
// SubredditLinkListViewModel.swift
// Reddit
//
// Created by Ivan Bruel on 09/05/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import Foundation
import RxSwift
// MARK: Properties and initializer
class LinkSwipeViewModel {
// MARK: Private Properties
private let _title: String
private let path: String
private let subredditOnly: Bool
private let user: User
private let accessToken: AccessToken
private let linkListings: Variable<[LinkListing]> = Variable([])
private let _viewModels: Variable<[LinkItemViewModel]> = Variable([])
private let _listingType: Variable<ListingType> = Variable(.Hot)
private var disposeBag = DisposeBag()
private let _loadingState = Variable<LoadingState>(.Normal)
// MARK: Initializer
init(user: User, accessToken: AccessToken, title: String, path: String, subredditOnly: Bool) {
self.user = user
self.accessToken = accessToken
self._title = title
self.path = path
self.subredditOnly = subredditOnly
}
convenience init(user: User, accessToken: AccessToken, subreddit: Subreddit) {
self.init(user: user, accessToken: accessToken, title: subreddit.displayName,
path: subreddit.path, subredditOnly: true)
}
convenience init(user: User, accessToken: AccessToken, multireddit: Multireddit) {
self.init(user: user, accessToken: accessToken, title: multireddit.name,
path: multireddit.path, subredditOnly: false)
}
}
// MARK: Private Observables
extension LinkSwipeViewModel {
private var userObservable: Observable<User> {
return .just(user)
}
private var accessTokenObservable: Observable<AccessToken> {
return .just(accessToken)
}
private var afterObservable: Observable<String?> {
return linkListings.asObservable()
.map { $0.last?.after }
}
private var listingTypeObservable: Observable<ListingType> {
return _listingType.asObservable()
}
private var pathObservable: Observable<String> {
return .just(path)
}
private var subredditOnlyObservable: Observable<Bool> {
return .just(subredditOnly)
}
private var request: Observable<LinkListing> {
return Observable
.combineLatest(listingTypeObservable, afterObservable, accessTokenObservable,
pathObservable) { ($0, $1, $2, $3) }
.take(1)
.doOnNext { [weak self] _ in
self?._loadingState.value = .Loading
}.flatMap {
(listingType: ListingType, after: String?, accessToken: AccessToken, path: String) in
Network.request(RedditAPI.LinkListing(token: accessToken.token,
path: path, listingPath: listingType.path, listingTypeRange: listingType.range?.rawValue,
after: after))
}.observeOn(SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
.mapObject(LinkListing)
.observeOn(MainScheduler.instance)
}
}
// MARK: Public API
extension LinkSwipeViewModel {
var viewModels: Observable<[LinkItemViewModel]> {
return _viewModels.asObservable()
}
var loadingState: Observable<LoadingState> {
return _loadingState.asObservable()
}
var listingTypeName: Observable<String> {
return _listingType.asObservable()
.map { $0.name }
}
func viewModelForIndex(index: Int) -> LinkItemViewModel? {
return _viewModels.value.get(index)
}
func requestLinks() {
guard _loadingState.value != .Loading else { return }
Observable
.combineLatest(request, userObservable, accessTokenObservable, subredditOnlyObservable) {
($0, $1, $2, $3)
}.take(1)
.subscribe { [weak self] event in
guard let `self` = self else { return }
switch event {
case let .Next(linkListing, user, accessToken, subredditOnly):
self.linkListings.value.append(linkListing)
let viewModels = LinkSwipeViewModel.viewModelsFromLinkListing(linkListing,
user: user, accessToken: accessToken, subredditOnly: subredditOnly)
viewModels.forEach { $0.preloadData() }
self._loadingState.value = self._viewModels.value.count > 0 ? .Normal : .Empty
self._viewModels.value += viewModels
if viewModels.count <= 4 {
self.requestLinks()
}
case .Error:
self._loadingState.value = .Error
default: break
}
}.addDisposableTo(disposeBag)
}
func setListingType(listingType: ListingType) {
guard listingType != _listingType.value else { return }
_listingType.value = listingType
refresh()
}
func refresh() {
linkListings.value = []
_viewModels.value = []
disposeBag = DisposeBag()
_loadingState.value = .Normal
requestLinks()
}
}
// MARK: Helpers
extension LinkSwipeViewModel {
private static func viewModelsFromLinkListing(linkListing: LinkListing, user: User,
accessToken: AccessToken, subredditOnly: Bool)
-> [LinkItemViewModel] {
return linkListing.links
.filter { !$0.stickied }
.filter { !Globals.hideVotedPosts || $0.vote == .None }
.filter { $0.type == .Image || $0.type == .GIF }
.map { LinkItemViewModel.viewModelFromLink($0, user: user, accessToken: accessToken,
subredditOnly: subredditOnly)
}
}
}
// MARK: TitledViewModel
extension LinkSwipeViewModel: TitledViewModel {
var title: Observable<String> {
return .just(_title)
}
}
| mit | b7a143d5f81fc1bcd5fbff96312d39e7 | 29.385475 | 99 | 0.677698 | 4.498759 | false | false | false | false |
rmclea21/Flappy-Santa | FlappyBird/Resources/SKTUtils/SKTAudio.swift | 15 | 2871 | /*
* Copyright (c) 2013-2014 Razeware LLC
*
* 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 AVFoundation
/**
* Audio player that uses AVFoundation to play looping background music and
* short sound effects. For when using SKActions just isn't good enough.
*/
public class SKTAudio {
public var backgroundMusicPlayer: AVAudioPlayer?
public var soundEffectPlayer: AVAudioPlayer?
public class func sharedInstance() -> SKTAudio {
return SKTAudioInstance
}
public func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}
//var error: NSError? = nil
backgroundMusicPlayer = try? AVAudioPlayer(contentsOfURL: url!)
if let player = backgroundMusicPlayer {
player.numberOfLoops = -1
player.prepareToPlay()
player.play()
} else {
//print("Could not create audio player: \(error!)")
}
}
public func pauseBackgroundMusic() {
if let player = backgroundMusicPlayer {
if player.playing {
player.pause()
}
}
}
public func resumeBackgroundMusic() {
if let player = backgroundMusicPlayer {
if !player.playing {
player.play()
}
}
}
public func playSoundEffect(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}
soundEffectPlayer = try? AVAudioPlayer(contentsOfURL: url!)
if let player = soundEffectPlayer {
player.numberOfLoops = 0
player.prepareToPlay()
player.play()
} else {
print("Could not create audio player: error")
}
}
}
private let SKTAudioInstance = SKTAudio()
| mit | d29049f0a0b59e62e5c9cacefbda26f6 | 31.258427 | 80 | 0.699756 | 4.65316 | false | false | false | false |
weareopensource/Sample-iOS_Swift_GetStarted | StepOne/APIController.swift | 2 | 3305 | //
// ViewController.swift
// StepOne
//
// Created by WeAreOpenSource.me on 24/04/2015.
// Copyright (c) 2015 WeAreOpenSource.me rights reserved.
//
// tuto : http://jamesonquave.com/blog/developing-ios-8-apps-using-swift-animations-audio-and-custom-table-view-cells/
import Foundation
/**************************************************************************************************/
// Protocol
/**************************************************************************************************/
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
}
/**************************************************************************************************/
// Class
/**************************************************************************************************/
class APIController {
/*************************************************/
// Main
/*************************************************/
// Var
/*************************/
var delegate: APIControllerProtocol
// init
/*************************/
init(delegate: APIControllerProtocol) {
self.delegate = delegate
}
/*************************************************/
// Functions
/*************************************************/
func get(path: String) {
let url = NSURL(string: path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
if let results: NSArray = jsonResult["results"] as? NSArray {
self.delegate.didReceiveAPIResults(results)
}
}
})
// The task is just an object with all these properties set
// In order to actually make the web request, we need to "resume"
task.resume()
}
func searchItunesFor(searchTerm: String) {
// The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Now escape anything else that isn't URL-friendly
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album"
get(urlPath)
}
}
func lookupAlbum(collectionId: Int) {
get("https://itunes.apple.com/lookup?id=\(collectionId)&entity=song")
}
}
| mit | 0f2b14493306c6fc4b4e68482512c07f | 37.430233 | 167 | 0.496218 | 5.976492 | false | false | false | false |
hgani/ganiweb-ios | ganiweb/Classes/HtmlForm/GHtmlFormScreen.swift | 1 | 3965 | import Eureka
import GaniLib
open class GHtmlFormScreen: GFormScreen {
public private(set) var htmlForm: HtmlForm!
private var section: Section!
// lazy fileprivate var refresher: GRefreshControl = {
// return GRefreshControl().onValueChanged {
// self.onRefresh()
// }
// }()
private var autoRefresh = false
// This is especially important for detecting if the user is still logged in everytime the form screen
// is opened.
public func refreshOnAppear() -> Self {
self.autoRefresh = true
return self
}
open override func viewDidLoad() {
super.viewDidLoad()
_ = self.leftBarButton(item: GBarButtonItem()
.title("Cancel")
.onClick {
self.launch.confirm("Changes will be discarded. Are you sure?", title: nil, handler: {
// https://stackoverflow.com/questions/39576314/dealloc-a-viewcontroller-warning
DispatchQueue.main.async {
_ = self.nav.pop()
}
})
})
// appendRefreshControl()
setupForm()
}
open override func viewWillAppear(_ animated: Bool) {
if autoRefresh {
onRefresh()
}
super.viewWillAppear(animated)
}
private func setupForm() {
//self.tableView?.contentInset = UIEdgeInsetsMake(-16, 0, -16, 0) // Eureka-specific requirements
self.section = Section()
form += [section]
setupHeader(height: 0) { _ in
// This is just to remove the gap at the top
}
self.htmlForm = HtmlForm(form: form, onSubmitSucceeded: { result in
if self.onSubmitted(result: result) {
// TODO: Ideally we should only reset the values, not remove the fields.
self.form.allSections.last?.removeAll()
}
else {
if let message = result["message"].string {
self.indicator.show(error: message)
}
else if let message = result["error"].string { // Devise uses "error" key
self.indicator.show(error: message)
}
}
})
}
//
// private func appendRefreshControl() {
// tableView?.addSubview(refresher)
//
// // Eureka-specific requirements
// refresher.snp.makeConstraints { (make) -> Void in
// make.top.equalTo(4)
// make.centerX.equalTo(tableView!)
// }
// }
private func setupHeaderFooter(height: Int, populate: @escaping (GHeaderFooterView) -> Void) -> HeaderFooterView<GHeaderFooterView> {
var headerFooter = HeaderFooterView<GHeaderFooterView>(.class)
headerFooter.height = { self.htmlForm.rendered ? CGFloat(height) : 0 }
headerFooter.onSetupView = { view, section in
view.paddings(t: 15, l: 20, b: 15, r: 20).clearViews()
populate(view)
}
return headerFooter
}
public func setupHeader(height: Int, populate: @escaping (GHeaderFooterView) -> Void) {
section.header = setupHeaderFooter(height: height, populate: populate)
}
public func setupFooter(height: Int, populate: @escaping (GHeaderFooterView) -> Void) {
section.footer = setupHeaderFooter(height: height, populate: populate)
}
public func loadForm(path: String) {
htmlForm.load(path, indicator: refresher, onSuccess: {
// Allow subclass to populate header/footer, i.e. when htmlForm has been rendered.
// E.g. `if !self.htmlForm.rendered { return }`
self.section.reload()
self.onLoaded()
})
}
open func onLoaded() {
// To be overidden
}
open func onSubmitted(result: Json) -> Bool {
// To be overidden
return true
}
}
| mit | 532d83155f56b24e86eadcfebe17e835 | 32.601695 | 137 | 0.568726 | 4.697867 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Controllers/Preferences/Notifications/NotificationsPreferencesViewController.swift | 1 | 4555 | //
// NotificationsPreferencesViewController.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 05.03.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
final class NotificationsPreferencesViewController: BaseTableViewController {
private let viewModel = NotificationsPreferencesViewModel()
var subscription: Subscription? {
didSet {
guard let subscription = subscription else {
return
}
viewModel.currentPreferences = NotificationPreferences(
desktopNotifications: subscription.desktopNotifications,
disableNotifications: subscription.disableNotifications,
emailNotifications: subscription.emailNotifications,
audioNotificationValue: subscription.audioNotificationValue,
desktopNotificationDuration: subscription.desktopNotificationDuration,
audioNotifications: subscription.audioNotifications,
hideUnreadStatus: subscription.hideUnreadStatus,
mobilePushNotifications: subscription.mobilePushNotifications
)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = viewModel.title
viewModel.enableModel.value.bind { [unowned self] _ in
let updates = self.viewModel.tableUpdatesAfterStateChange()
DispatchQueue.main.async {
self.tableView.beginUpdates()
self.tableView.insertSections(updates.insertions, with: .fade)
self.tableView.deleteSections(updates.deletions, with: .fade)
self.tableView.endUpdates()
}
}
viewModel.isSaveButtonEnabled.bindAndFire { enabled in
DispatchQueue.main.async {
self.navigationItem.rightBarButtonItem?.isEnabled = enabled
}
}
viewModel.updateModel(subscription: subscription)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: viewModel.saveButtonTitle, style: .done, target: self, action: #selector(saveSettings))
}
@objc private func saveSettings() {
guard let subscription = subscription else {
Alert(key: "alert.update_notifications_preferences_save_error").present()
return
}
let saveNotificationsRequest = SaveNotificationRequest(rid: subscription.rid, notificationPreferences: viewModel.notificationPreferences)
API.current()?.fetch(saveNotificationsRequest) { [weak self] response in
guard let self = self else { return }
switch response {
case .resource:
self.viewModel.updateCurrentPreferences()
self.alertSuccess(title: self.viewModel.saveSuccessTitle)
case .error:
Alert(key: "alert.update_notifications_preferences_save_error").present()
}
}
}
}
extension NotificationsPreferencesViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(in: section)
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.titleForHeader(in: section)
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return viewModel.titleForFooter(in: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let settingModel = viewModel.settingModel(for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: settingModel.type.rawValue, for: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let settingModel = viewModel.settingModel(for: indexPath)
guard var cell = cell as? NotificationsCellProtocol else {
fatalError("Could not dequeue reusable cell with type \(settingModel.type.rawValue)")
}
cell.cellModel = settingModel
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.beginUpdates()
viewModel.openPicker(for: indexPath)
tableView.endUpdates()
}
}
| mit | f11f6ef0ada5f6ef5a7708bc9b3b27bb | 37.268908 | 154 | 0.673913 | 5.629172 | false | false | false | false |
darrinhenein/firefox-ios | Client/Frontend/Reader/ReaderMode.swift | 1 | 13046 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
let ReaderModeProfileKeyStyle = "readermode.style"
enum ReaderModeMessageType: String {
case StateChange = "ReaderModeStateChange"
case PageEvent = "ReaderPageEvent"
}
enum ReaderPageEvent: String {
case PageShow = "PageShow"
}
enum ReaderModeState: String {
case Available = "Available"
case Unavailable = "Unavailable"
case Active = "Active"
}
enum ReaderModeTheme: String {
case Light = "light"
case Dark = "dark"
case Sepia = "sepia"
}
enum ReaderModeFontType: String {
case Serif = "serif"
case SansSerif = "sans-serif"
}
enum ReaderModeFontSize: Int {
case Smallest = 1
case Small
case Normal = 3
case Large = 4
case Largest = 5
}
struct ReaderModeStyle {
var theme: ReaderModeTheme
var fontType: ReaderModeFontType
var fontSize: ReaderModeFontSize
/// Encode the style to a JSON dictionary that can be passed to ReaderMode.js
func encode() -> String {
return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).toString(pretty: false)
}
/// Encode the style to a dictionary that can be stored in the profile
func encode() -> [String:AnyObject] {
return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]
}
init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) {
self.theme = theme
self.fontType = fontType
self.fontSize = fontSize
}
/// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded.
init?(dict: [String:AnyObject]) {
let themeRawValue = dict["theme"] as? String
let fontTypeRawValue = dict["fontType"] as? String
let fontSizeRawValue = dict["fontSize"] as? Int
if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil {
return nil
}
let theme = ReaderModeTheme(rawValue: themeRawValue!)
let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!)
let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!)
if theme == nil || fontType == nil || fontSize == nil {
return nil
}
self.theme = theme!
self.fontType = fontType!
self.fontSize = fontSize!
}
}
let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: .Normal)
let domainPrefixes = ["www.", "mobile.", "m."]
private func simplifyDomain(domain: String) -> String {
for prefix in domainPrefixes {
if domain.hasPrefix(prefix) {
return domain.substringFromIndex(advance(domain.startIndex, countElements(prefix)))
}
}
return domain
}
/// This struct captures the response from the Readability.js code.
struct ReadabilityResult {
var domain = ""
var url = ""
var content = ""
var title = ""
var credits = ""
init?(object: AnyObject?) {
if let dict = object as? NSDictionary {
if let uri = dict["uri"] as? NSDictionary {
if let url = uri["spec"] as? String {
self.url = url
}
if let host = uri["host"] as? String {
self.domain = host
}
}
if let content = dict["content"] as? String {
self.content = content
}
if let title = dict["title"] as? String {
self.title = title
}
if let credits = dict["byline"] as? String {
self.credits = credits
}
} else {
return nil
}
}
}
/// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate
protocol ReaderModeDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser)
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser)
}
private let ReaderModeNamespace = "_firefox_ReaderMode"
class ReaderMode: BrowserHelper {
var delegate: ReaderModeDelegate?
private weak var browser: Browser?
var state: ReaderModeState = ReaderModeState.Unavailable
private var originalURL: NSURL?
var activateImmediately: Bool = false
class func name() -> String {
return "ReaderMode"
}
required init?(browser: Browser) {
self.browser = browser
// This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related.
if let path = NSBundle.mainBundle().pathForResource("Readability", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
// This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode.
if let path = NSBundle.mainBundle().pathForResource("ReaderMode", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "readerModeMessageHandler"
}
private func handleReaderPageEvent(readerPageEvent: ReaderPageEvent) {
switch readerPageEvent {
case .PageShow:
delegate?.readerMode(self, didDisplayReaderizedContentForBrowser: browser!)
}
}
private func handleReaderModeStateChange(state: ReaderModeState) {
self.state = state
delegate?.readerMode(self, didChangeReaderModeState: state, forBrowser: browser!)
if activateImmediately && state == ReaderModeState.Available {
enableReaderMode()
activateImmediately = false
}
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
println("DEBUG: readerModeMessageHandler message: \(message.body)")
if let msg = message.body as? Dictionary<String,String> {
if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") {
switch messageType {
case .PageEvent:
if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") {
handleReaderPageEvent(readerPageEvent)
}
break
case .StateChange:
if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") {
handleReaderModeStateChange(readerModeState)
}
break
}
}
}
}
func enableReaderMode() {
if state == ReaderModeState.Available {
browser!.webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
println("DEBUG: mozReaderize object=\(object != nil) error=\(error)")
if error == nil && object != nil {
if let readabilityResult = ReadabilityResult(object: object) {
if let html = self.generateReaderContent(readabilityResult, initialStyle: self.style) {
self.state = ReaderModeState.Active
self.originalURL = self.browser!.webView.URL
if let readerModeURL = ReaderMode.encodeURL(self.browser!.webView.URL) {
self.browser!.webView.loadHTMLString(html, baseURL: readerModeURL)
}
return
}
}
}
// TODO What do we do in case of errors? At this point we actually did show the button, so the user does expect some feedback I think.
})
}
}
func disableReaderMode() {
if state == ReaderModeState.Active {
state = ReaderModeState.Available
self.browser!.webView.loadRequest(NSURLRequest(URL: originalURL!))
originalURL = nil
}
}
var style: ReaderModeStyle = DefaultReaderModeStyle {
didSet {
if state == ReaderModeState.Active {
browser!.webView.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode()))", completionHandler: {
(object, error) -> Void in
return
})
}
}
}
private func generateReaderContent(readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? {
if let stylePath = NSBundle.mainBundle().pathForResource("Reader", ofType: "css") {
if let css = NSString(contentsOfFile: stylePath, encoding: NSUTF8StringEncoding, error: nil) {
if let tmplPath = NSBundle.mainBundle().pathForResource("Reader", ofType: "html") {
if let tmpl = NSMutableString(contentsOfFile: tmplPath, encoding: NSUTF8StringEncoding, error: nil) {
tmpl.replaceOccurrencesOfString("%READER-CSS%", withString: css,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-STYLE%", withString: initialStyle.encode(),
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-DOMAIN%", withString: simplifyDomain(readabilityResult.domain),
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-URL%", withString: readabilityResult.url,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-TITLE%", withString: readabilityResult.title,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-CREDITS%", withString: readabilityResult.credits,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%READER-CONTENT%", withString: readabilityResult.content,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
tmpl.replaceOccurrencesOfString("%WEBSERVER-BASE%", withString: WebServer.sharedInstance.base,
options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length))
return tmpl
}
}
}
}
return nil
}
class func isReaderModeURL(url: NSURL) -> Bool {
if let absoluteString = url.absoluteString {
return absoluteString.hasPrefix("about:reader?url=")
}
return false
}
class func decodeURL(url: NSURL) -> NSURL? {
if let absoluteString = url.absoluteString {
if absoluteString.hasPrefix("about:reader?url=") {
let encodedURL = absoluteString.substringFromIndex(advance(absoluteString.startIndex, 17))
if let decodedURL = encodedURL.stringByRemovingPercentEncoding {
return NSURL(string: decodedURL)
}
}
}
return nil
}
class func encodeURL(url: NSURL?) -> NSURL? {
if let absoluteString = url?.absoluteString {
if let encodedURL = absoluteString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {
if let aboutReaderURL = NSURL(string: "about:reader?url=\(encodedURL)") {
return aboutReaderURL
}
}
}
return nil
}
} | mpl-2.0 | 69069ee233208e12f25a684248ce5470 | 39.64486 | 172 | 0.613751 | 5.637857 | false | false | false | false |
OSzhou/MyTestDemo | PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTP.git--6392294032632002019/Sources/Routing.swift | 1 | 17824 | //
// Routing.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-11.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
/// Function which receives request and response objects and generates content.
public typealias RequestHandler = (HTTPRequest, HTTPResponse) -> ()
/// Object which maps uris to handler.
/// RouteNavigators are given to the HTTPServer to control its content generation.
public protocol RouteNavigator: CustomStringConvertible {
/// Given an array of URI path components and HTTPRequest, return the handler or nil if there was none.
func findHandlers(pathComponents components: [String], webRequest: HTTPRequest) -> [RequestHandler]?
}
public extension RouteNavigator {
func findHandler(pathComponents: [String], webRequest: HTTPRequest) -> RequestHandler? {
return findHandlers(pathComponents: pathComponents, webRequest: webRequest)?.last
}
}
public extension RouteNavigator {
/// Given a URI and HTTPRequest, return the handler or nil if there was none.
func findHandler(uri: String, webRequest: HTTPRequest) -> RequestHandler? {
return findHandler(pathComponents: uri.routePathComponents, webRequest: webRequest)
}
/// Given a URI and HTTPRequest, return the handler or nil if there was none.
func findHandlers(uri: String, webRequest: HTTPRequest) -> [RequestHandler]? {
return findHandlers(pathComponents: uri.routePathComponents, webRequest: webRequest)
}
}
// The url variable key under which the remaining path in a trailing wild card will be placed.
public let routeTrailingWildcardKey = "_trailing_wildcard_"
/// Combines a method, uri and handler
public struct Route {
public let methods: [HTTPMethod]
public let uri: String
public let handler: RequestHandler
/// A single method, a uri and handler.
public init(method: HTTPMethod, uri: String, handler: @escaping RequestHandler) {
self.methods = [method]
self.uri = uri
self.handler = handler
}
/// An array of methods, a uri and handler.
public init(methods: [HTTPMethod], uri: String, handler: @escaping RequestHandler) {
self.methods = methods
self.uri = uri
self.handler = handler
}
/// A uri and a handler on any method.
public init(uri: String, handler: @escaping RequestHandler) {
self.methods = HTTPMethod.allMethods
self.uri = uri
self.handler = handler
}
}
/// A group of routes. Add one or more routes to this object then call its navigator property to get the RouteNavigator.
/// Can be created with a baseUri. All routes which are added will have their URIs prefixed with this value.
public struct Routes {
var routes = [Route]()
var moreRoutes = [Routes]()
let baseUri: String
let handler: RequestHandler?
/// Initialize with no baseUri.
public init(handler: RequestHandler? = nil) {
self.baseUri = ""
self.handler = handler
}
/// Initialize with a baseUri.
public init(baseUri: String, handler: RequestHandler? = nil) {
self.baseUri = Routes.sanitizeUri(baseUri)
self.handler = handler
}
/// Initialize with a array of Route.
public init(_ routes: [Route]) {
self.baseUri = ""
self.handler = nil
add(routes)
}
/// Initialize with a baseUri and array of Route.
public init(baseUri: String, routes: [Route]) {
self.baseUri = Routes.sanitizeUri(baseUri)
self.handler = nil
add(routes)
}
/// Add all the routes in the Routes object to this one.
public mutating func add(_ routes: Routes) {
moreRoutes.append(routes)
}
/// Add all the routes in the Routes array to this one.
public mutating func add(_ routes: [Route]) {
for route in routes {
add(route)
}
}
/// Add one Route to this object.
public mutating func add(_ route: Route, routes vroots: Route...) {
routes.append(route)
vroots.forEach { add($0) }
}
/// Add the given method, uri and handler as a route.
public mutating func add(method: HTTPMethod, uri: String, handler: @escaping RequestHandler) {
add(Route(method: method, uri: uri, handler: handler))
}
/// Add the given method, uris and handler as a route.
public mutating func add(method: HTTPMethod, uris: [String], handler: @escaping RequestHandler) {
uris.forEach {
add(method: method, uri: $0, handler: handler)
}
}
/// Add the given uri and handler as a route.
/// This will add the route for all standard methods.
public mutating func add(uri: String, handler: @escaping RequestHandler) {
add(Route(uri: uri, handler: handler))
}
/// Add the given method, uris and handler as a route.
/// This will add the route for all standard methods.
public mutating func add(uris: [String], handler: @escaping RequestHandler) {
for uri in uris {
add(uri: uri, handler: handler)
}
}
static func sanitizeUri(_ uri: String) -> String {
let endSlash = uri.hasSuffix("/")
let split = uri.characters.split(separator: "/").map(String.init)
let ret = "/" + split.joined(separator: "/") + (endSlash ? "/" : "")
return ret
}
struct Navigator: RouteNavigator {
let map: [HTTPMethod:RouteNode]
var description: String {
var s = ""
for (method, root) in self.map {
s.append("\n\(method):\n\(root.description)")
}
return s
}
func findHandlers(pathComponents components: [String], webRequest: HTTPRequest) -> [RequestHandler]? {
let method = webRequest.method
guard !components.isEmpty, let root = self.map[method] else {
return nil
}
var g = components.makeIterator()
if components[0] == "/" {
_ = g.next()
}
guard let handlers = root.findHandler(currentComponent: "", generator: g, webRequest: webRequest) else {
return nil
}
return handlers.flatMap { $0 }
}
}
private func formatException(route r: String, error: Error) -> String {
return "\(error) - \(r)"
}
}
extension Routes {
/// Return the RouteNavigator for this object.
public var navigator: RouteNavigator {
guard let map = try? nodeMap() else {
return Navigator(map: [:])
}
return Navigator(map: map)
}
func nodeMap() throws -> [HTTPMethod:RouteNode] {
var working = [HTTPMethod:RouteNode]()
let paths = self.paths(baseUri: "")
for (method, uris) in paths {
let root = RouteNode()
working[method] = root
for path in uris {
let uri = Routes.sanitizeUri(path.path)
let handler = path.handler
let terminal = path.terminal
var gen = uri.routePathComponents.makeIterator()
if uri.hasPrefix("/") {
_ = gen.next()
}
let node = try root.getNode(gen)
node.terminal = terminal
node.handler = handler
}
}
return working
}
struct PathHandler {
let path: String
let handler: RequestHandler
let terminal: Bool
}
func paths(baseUri: String = "") -> [HTTPMethod:[PathHandler]] {
var paths = [HTTPMethod:[PathHandler]]()
let newBaseUri = baseUri + self.baseUri
moreRoutes.forEach {
let newp = $0.paths(baseUri: newBaseUri)
paths = merge(newp, into: paths)
}
routes.forEach {
route in
let uri = newBaseUri + "/" + route.uri
var newpaths = [HTTPMethod:[PathHandler]]()
route.methods.forEach {
method in
newpaths[method] = [PathHandler(path: uri, handler: route.handler, terminal: true)]
}
paths = merge(newpaths, into: paths)
}
if let handler = self.handler {
for (key, value) in paths {
paths[key] = value + [PathHandler(path: newBaseUri, handler: handler, terminal: false)]
}
}
return paths
}
func merge(_ dict: [HTTPMethod:[PathHandler]], into: [HTTPMethod:[PathHandler]]) -> [HTTPMethod:[PathHandler]] {
var ret = into
for (key, value) in dict {
if var fnd = ret[key] {
fnd.append(contentsOf: value)
ret[key] = fnd
} else {
ret[key] = value
}
}
return ret
}
}
extension Routes {
// Add all the routes in the Routes object to this one.
@available(*, deprecated, message: "Use Routes.add(_:Routes)")
public mutating func add(routes: Routes) {
for route in routes.routes {
self.add(route)
}
}
}
extension String {
var routePathComponents: [String] {
return self.filePathComponents
// let components = self.characters.split(separator: "/").map(String.init)
// return components
}
}
private enum RouteException: Error {
case invalidRoute
}
private enum RouteItemType {
case wildcard, trailingWildcard, variable(String), path, trailingSlash
init(_ comp: String) {
if comp == "*" {
self = .wildcard
} else if comp == "**" {
self = .trailingWildcard
} else if comp == "/" {
self = .trailingSlash
} else if comp.characters.count >= 3 && comp[comp.startIndex] == "{" && comp[comp.index(before: comp.endIndex)] == "}" {
self = .variable(comp[comp.index(after: comp.startIndex)..<comp.index(before: comp.endIndex)])
} else {
self = .path
}
}
}
class RouteNode {
typealias ComponentGenerator = IndexingIterator<[String]>
var handler: RouteMap.RequestHandler?
var trailingWildCard: RouteNode?
var wildCard: RouteNode?
var variables = [RouteNode]()
var subNodes = [String:RouteNode]()
var terminal = true // an end point. not an intermediary
func descriptionTabbed(_ tabCount: Int) -> String {
var s = ""
if let _ = self.handler {
s.append("/+h\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
func appendToHandlers(_ handlers: [RouteMap.RequestHandler?]) -> [RouteMap.RequestHandler?] {
// terminal handlers are not included in chaining
if terminal {
return handlers
}
return [handler] + handlers
}
func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? {
var m = generator
if let p = m.next() {
// variables
for node in self.variables {
if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
// paths
if let node = self.subNodes[p.lowercased()] {
if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
// wildcard
if let node = self.wildCard {
if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
// trailing wildcard
if let node = self.trailingWildCard {
if let h = node.findHandler(currentComponent: p, generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
} else if let handler = self.handler {
if terminal {
return [handler]
}
return nil
} else {
// wildcards
if let node = self.wildCard {
if let h = node.findHandler(currentComponent: "", generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
// trailing wildcard
if let node = self.trailingWildCard {
if let h = node.findHandler(currentComponent: "", generator: m, webRequest: webRequest) {
return appendToHandlers(h)
}
}
}
return nil
}
func getNode(_ ing: ComponentGenerator) throws -> RouteNode {
var g = ing
if let comp = g.next() {
let routeType = RouteItemType(comp)
let node: RouteNode
switch routeType {
case .wildcard:
if wildCard == nil {
wildCard = RouteWildCard()
}
node = wildCard!
case .trailingWildcard:
guard nil == g.next() else {
throw RouteException.invalidRoute
}
if trailingWildCard == nil {
trailingWildCard = RouteTrailingWildCard()
}
node = trailingWildCard!
case .trailingSlash:
guard nil == g.next() else {
throw RouteException.invalidRoute
}
node = RouteTrailingSlash()
subNodes[comp] = node
case .path:
let compLower = comp.lowercased()
if let existing = subNodes[compLower] {
node = existing
} else {
node = RoutePath(name: compLower)
subNodes[compLower] = node
}
case .variable(let name):
let dups = variables.flatMap { $0 as? RouteVariable }.filter { $0.name == name }
if dups.isEmpty {
let varble = RouteVariable(name: name)
variables.append(varble)
node = varble
} else {
node = dups[0]
}
}
return try node.getNode(g)
} else {
return self
}
}
}
extension RouteNode: CustomStringConvertible {
var description: String {
return self.descriptionTabbed(0)
}
private func putTabs(_ count: Int) -> String {
var s = ""
for _ in 0..<count {
s.append("\t")
}
return s
}
func descriptionTabbedInner(_ tabCount: Int) -> String {
var s = ""
for (_, node) in self.subNodes {
s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
for node in self.variables {
s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
if let node = self.wildCard {
s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
if let node = self.trailingWildCard {
s.append("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
return s
}
}
class RoutePath: RouteNode {
let name: String
init(name: String) {
self.name = name
}
override func descriptionTabbed(_ tabCount: Int) -> String {
var s = "/\(self.name)"
if let _ = self.handler {
s.append("+h\n")
} else {
s.append("\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
// RoutePaths don't need to perform any special checking.
// Their path is validated by the fact that they exist in their parent's `subNodes` dict.
}
class RouteWildCard: RouteNode {
override func descriptionTabbed(_ tabCount: Int) -> String {
var s = "/*"
if let _ = self.handler {
s.append("+h\n")
} else {
s.append("\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
}
class RouteTrailingWildCard: RouteWildCard {
override func descriptionTabbed(_ tabCount: Int) -> String {
var s = "/**"
if let _ = self.handler {
s.append("+h\n")
} else {
s.append("\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? {
let trailingVar = "/\(curComp)" + generator.map { "/" + $0 }.joined(separator: "")
webRequest.urlVariables[routeTrailingWildcardKey] = trailingVar
if let handler = self.handler {
return [handler]
}
return nil
}
}
class RouteTrailingSlash: RouteNode {
override func descriptionTabbed(_ tabCount: Int) -> String {
var s = "/"
if let _ = self.handler {
s.append("+h\n")
} else {
s.append("\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? {
var m = generator
guard curComp == "/", nil == m.next(), let handler = self.handler else {
return nil
}
return [handler]
}
}
class RouteVariable: RouteNode {
let name: String
init(name: String) {
self.name = name
}
override func descriptionTabbed(_ tabCount: Int) -> String {
var s = "/{\(self.name)}"
if let _ = self.handler {
s.append("+h\n")
} else {
s.append("\n")
}
s.append(self.descriptionTabbedInner(tabCount))
return s
}
override func findHandler(currentComponent curComp: String, generator: ComponentGenerator, webRequest: HTTPRequest) -> [RouteMap.RequestHandler?]? {
if let h = super.findHandler(currentComponent: curComp, generator: generator, webRequest: webRequest) {
if let decodedComponent = curComp.stringByDecodingURL {
webRequest.urlVariables[self.name] = decodedComponent
} else {
webRequest.urlVariables[self.name] = curComp
}
return h
}
return nil
}
}
// -- old --
// ALL code below this is obsolete but remains to provide compatability 1.0 based solutions.
// For 1.0 compatability only.
public var compatRoutes: Routes?
// Holds the registered routes.
@available(*, deprecated, message: "Use new Routes API instead")
public struct RouteMap: CustomStringConvertible {
public typealias RequestHandler = (HTTPRequest, HTTPResponse) -> ()
public var description: String {
return compatRoutes?.navigator.description ?? "no routes"
}
public subscript(path: String) -> RequestHandler? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
guard let handler = newValue else {
return
}
if nil == compatRoutes {
compatRoutes = Routes()
}
compatRoutes?.add(method: .get, uri: path, handler: handler)
}
}
public subscript(paths: [String]) -> RequestHandler? {
get {
return nil
}
set {
for path in paths {
self[path] = newValue
}
}
}
public subscript(method: HTTPMethod, path: String) -> RequestHandler? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
guard let handler = newValue else {
return
}
if nil == compatRoutes {
compatRoutes = Routes()
}
compatRoutes?.add(method: method, uri: path, handler: handler)
}
}
public subscript(method: HTTPMethod, paths: [String]) -> RequestHandler? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
for path in paths {
self[method, path] = newValue
}
}
}
}
@available(*, deprecated, message: "Use new Routes API instead")
public struct Routing {
static public var Routes = RouteMap()
private init() {}
}
| apache-2.0 | fdf62f6fc983b1ed559d2dd2794f5fb2 | 26.004545 | 149 | 0.670258 | 3.608625 | false | false | false | false |
prolificinteractive/Yoshi | Yoshi/Yoshi/Utility/Color.swift | 1 | 1263 | //
// Color.swift
// Yoshi
//
// Created by Christopher Jones on 2/9/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
/**
A color object
*/
struct Color {
/// The red value.
let red: UInt8
/// The green value
let green: UInt8
/// The blue value.
let blue: UInt8
/// The alpha value.
let alpha: Float
/**
Initializes a new color.
- parameter red: The red component.
- parameter green: The green component.
- parameter blue: The blue component.
- parameter alpha: The alpha channel. By default, this is 1.0.
*/
init(_ red: UInt8, _ green: UInt8, _ blue: UInt8, alpha: Float = 1.0) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
/**
Generates a UIColor.
- returns: The UIColor value.
*/
func toUIColor() -> UIColor {
let rFloat = CGFloat(red)
let gFloat = CGFloat(green)
let bFloat = CGFloat(blue)
let maxValue = CGFloat(UInt8.max)
return UIColor(red: (rFloat / maxValue),
green: (gFloat / maxValue),
blue: (bFloat / maxValue),
alpha: CGFloat(alpha))
}
}
| mit | 24b84b16514780916f3accff77ee8952 | 20.758621 | 75 | 0.547544 | 3.956113 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/iOS Collection/Business/Business/Extension/ExtensionViewController.swift | 1 | 2724 | //
// ExtensionViewController.swift
// Business
//
// Created by 朱双泉 on 2018/12/7.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
import MobileCoreServices
class ExtensionViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Extension"
let d = UserDefaults(suiteName: "group.business")
print(d?.value(forKey: "key") ?? "")
}
@IBAction func actionButtonClick(_ sender: UIButton) {
let image = UIImage(named: "Castiel")!
let vc = UIActivityViewController(activityItems: [image, "Castiel"], applicationActivities: nil)
weak var weakImageView = self.imageView
vc.completionWithItemsHandler = { (activityType, complete, returnedItems, activityError) in
if activityError == nil {
if complete == true && returnedItems != nil {
for item in returnedItems! {
if let item = item as? NSExtensionItem {
for provider in item.attachments! {
if provider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
provider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil, completionHandler: { (img, error) in
OperationQueue.main.addOperation {
if let strongImageView = weakImageView {
if let img = img as? UIImage {
strongImageView.image = img
}
}
}
})
} else if provider.hasItemConformingToTypeIdentifier(kUTTypeText as String) {
provider.loadItem(forTypeIdentifier: kUTTypeText as String, options: nil, completionHandler: { (text, error) in
guard error == nil else {
print(error!)
return
}
print(text!)
})
}
}
}
}
}
} else {
print(activityError!)
}
}
present(vc, animated: true, completion: nil)
}
}
| mit | e76ba9742ce1290c04838211accfb49e | 42.822581 | 147 | 0.447552 | 6.7925 | false | false | false | false |
FlameTinary/weiboSwift | weiboSwift/weiboSwift/Classes/Main/BaseTableViewController.swift | 1 | 1582 | //
// BaseTableViewController.swift
// weiboSwift
//
// Created by 田宇 on 16/4/25.
// Copyright © 2016年 Tinary. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController {
var visibleView : VisibleView?
var login = true
override func loadView() {
if login {
super.loadView()
} else {
visibleView = VisibleView.visibleView()
view = visibleView
}
//添加导航条按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(BaseTableViewController.registerButtonClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(BaseTableViewController.loginButtonClick))
//visible界面按钮的点击
visibleView?.registerButton.addTarget(self, action: #selector(BaseTableViewController.registerButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
visibleView?.loginButton.addTarget(self, action: #selector(BaseTableViewController.loginButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
}
//注册按钮点击方法
@objc private func registerButtonClick(){
print("注册")
}
@objc private func loginButtonClick(){
print("登录")
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit | 6de703bb1964fbf05ede899bb7005627 | 26.053571 | 184 | 0.656766 | 5.391459 | false | false | false | false |
duliodenis/gallery | Gallery/Gallery/ViewController.swift | 1 | 8083 | //
// ViewController.swift
// Gallery
//
// Created by Dulio Denis on 4/5/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
import CoreData
import StoreKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SKProductsRequestDelegate, SKPaymentTransactionObserver {
@IBOutlet weak var collectionView: UICollectionView!
var gallery = [Art]()
var products = [SKProduct]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
updateGallery()
if gallery.count == 0 {
createArt("Mona Lisa", imageName: "mona-lisa.jpg", productIdentifier: "", purchased: true)
createArt("The Starry Night", imageName: "starry-night.jpg", productIdentifier: "StarryNight", purchased: false)
createArt("The Scream", imageName: "the-scream.jpg", productIdentifier: "Scream", purchased: false)
createArt("The Persistence of Memory", imageName: "the-persistence-of-memory-1931.jpg", productIdentifier: "PersistenceOfMemory", purchased: false)
updateGallery()
collectionView.reloadData()
}
requestProductsForSale()
}
// MARK: IAP Functions / StoreKit Delegate Methods
func requestProductsForSale() {
let ids: Set<String> = ["StarryNight", "Scream", "PersistenceOfMemory"]
let productsRequest = SKProductsRequest(productIdentifiers: ids)
productsRequest.delegate = self
productsRequest.start()
}
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
print("Received requested products")
print("Products Ready: \(response.products.count)")
print("Invalid Products: \(response.invalidProductIdentifiers.count)")
for product in response.products {
print("Product: \(product.productIdentifier), Price: \(product.price)")
}
products = response.products
collectionView.reloadData()
}
func unlockProduct(productIdentifier: String) {
for art in gallery {
if art.productIdentifier == productIdentifier {
art.purchased = 1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext
do {
try context.save()
} catch{}
collectionView.reloadData()
}
}
}
@IBAction func restorePurchase(sender: AnyObject) {
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
// MARK: Payment Transaction Observer Delegate Method
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchased:
print("Purchased")
unlockProduct(transaction.payment.productIdentifier)
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Failed:
print("Failed")
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Restored:
print("Restored")
unlockProduct(transaction.payment.productIdentifier)
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
// Keep in the Queue
case .Purchasing:
print("Purchasing")
case .Deferred:
print("Deferred")
}
}
}
// MARK: Core Data Function
func createArt(title: String, imageName: String, productIdentifier: String, purchased: Bool) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext
if let entity = NSEntityDescription.entityForName("Art", inManagedObjectContext: context) {
let art = NSManagedObject(entity: entity, insertIntoManagedObjectContext: context) as! Art
art.title = title
art.imageName = imageName
art.productIdentifier = productIdentifier
art.purchased = NSNumber(bool: purchased)
}
do {
try context.save()
} catch{}
}
func updateGallery() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext
let fetch = NSFetchRequest(entityName: "Art")
do {
let artPieces = try context.executeFetchRequest(fetch)
self.gallery = artPieces as! [Art]
} catch {}
}
// MARK: Collection View Delegate Methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.gallery.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ArtCollectionViewCell", forIndexPath: indexPath) as! ArtCollectionViewCell
let art = gallery[indexPath.row]
cell.imageView.image = UIImage(named: art.imageName!)
cell.titleLabel.text = art.title!
for subview in cell.imageView.subviews {
subview.removeFromSuperview()
}
if art.purchased!.boolValue {
cell.purchaseLabel.hidden = true
} else {
cell.purchaseLabel.hidden = false
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurView = UIVisualEffectView(effect: blurEffect)
cell.layoutIfNeeded()
blurView.frame = cell.imageView.bounds
cell.imageView.addSubview(blurView)
// Tie Store Product to Gallery Item
for product in products {
if product.productIdentifier == art.productIdentifier {
// Show Local Currency for IAP
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = product.priceLocale
if let price = formatter.stringFromNumber(product.price) {
cell.purchaseLabel.text = "Buy for \(price)"
}
}
}
}
return cell
}
// When the user taps an item in the collection view that hasn't been purchased - add the product to the payment queue
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let art = gallery[indexPath.row]
if !art.purchased!.boolValue {
for product in products {
if product.productIdentifier == art.productIdentifier {
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment)
}
}
}
}
// MARK: Collection View Layout Delegate Methods
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width - 80, height: collectionView.bounds.size.height - 40)
}
}
| mit | 144bd1479bc84417c0c432a6d13bb405 | 35.736364 | 187 | 0.609874 | 6.146008 | false | false | false | false |
stuartbreckenridge/UISearchControllerWithSwift | SearchController/ViewController.swift | 1 | 3959 | //
// ViewController.swift
// SearchController
//
// Created by Stuart Breckenridge on 17/8/14.
// Copyright (c) 2014 Stuart Breckenridge. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var countryTable: UITableView!
var searchArray = [String]() {
didSet {
NotificationCenter.default.post(name: NSNotification.Name.init("searchResultsUpdated"), object: searchArray)
}
}
lazy var countrySearchController: UISearchController = ({
// Display search results in a separate view controller
let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
let alternateController = storyBoard.instantiateViewController(withIdentifier: "aTV") as! AlternateTableViewController
let controller = UISearchController(searchResultsController: alternateController)
//let controller = UISearchController(searchResultsController: nil)
controller.hidesNavigationBarDuringPresentation = false
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .minimal
controller.searchResultsUpdater = self
controller.searchBar.sizeToFit()
return controller
})()
override func viewDidLoad() {
super.viewDidLoad()
definesPresentationContext = true
// Configure navigation item to display search controller.
navigationItem.searchController = countrySearchController
navigationItem.hidesSearchBarWhenScrolling = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
switch countrySearchController.isActive {
case true:
return searchArray.count
case false:
return countries.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = countryTable.dequeueReusableCell(withIdentifier: "Cell") as! SearchTableViewCell
cell.textLabel?.text = ""
cell.textLabel?.attributedText = NSAttributedString(string: "")
switch countrySearchController.isActive {
case true:
cell.configureCell(with: countrySearchController.searchBar.text!, cellText: searchArray[indexPath.row])
return cell
case false:
cell.textLabel?.text! = countries[indexPath.row]
return cell
}
}
}
extension ViewController: UITableViewDelegate
{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension ViewController: UISearchResultsUpdating
{
func updateSearchResults(for searchController: UISearchController)
{
if searchController.searchBar.text?.utf8.count == 0 {
searchArray = countries
countryTable.reloadData()
} else {
searchArray.removeAll(keepingCapacity: false)
let range = searchController.searchBar.text!.startIndex ..< searchController.searchBar.text!.endIndex
var searchString = String()
searchController.searchBar.text?.enumerateSubstrings(in: range, options: .byComposedCharacterSequences, { (substring, substringRange, enclosingRange, success) in
searchString.append(substring!)
searchString.append("*")
})
let searchPredicate = NSPredicate(format: "SELF LIKE[cd] %@", searchString)
searchArray = countries.filter({ searchPredicate.evaluate(with: $0) })
countryTable.reloadData()
}
}
}
| mit | 500d3af0b0de1fefb6b7a49150b85dfc | 34.666667 | 173 | 0.672392 | 6.007587 | false | false | false | false |
XWJACK/PageKit | Sources/CycleContainer.swift | 1 | 2233 | //
// CycleContainer.swift
//
// Copyright (c) 2017 Jack
//
// 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
open class CycleContainer: ReuseContainer {
open override var contentSize: CGSize { return CGSize(width: scrollView.frame.width * CGFloat(numberOfPages) * 2,
height: scrollView.frame.height) }
private var realIndex: Int = 0
open override func reloadData() {
super.reloadData()
}
open override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
// scrollView.setContentOffset(<#T##contentOffset: CGPoint##CGPoint#>, animated: false)
switching(toIndex: 1, animated: false)
}
// open override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// let index = super.index(withOffset: scrollView.contentOffset.x)
// if index == 0 {
// if realIndex == 0 { realIndex = numberOfPages - 1 }
// else { realIndex -= 1 }
// } else if index == 2 { realIndex = (realIndex + 1) % numberOfPages }
// switching(toIndex: 1, animated: false)
// }
}
| mit | 4081de3b5eada51b5009fde9bff9fe8c | 44.571429 | 117 | 0.684729 | 4.57582 | false | false | false | false |
natemann/PlaidClient | PlaidClient/PlaidTransaction.swift | 1 | 2701 | //
// PlaidStructs.swift
// Budget
//
// Created by Nathan Mann on 11/5/14.
// Copyright (c) 2014 Nate. All rights reserved.
//
import Foundation
public struct PlaidTransaction {
public let account: String
public let id: String
public let pendingID: String?
public let amount: NSDecimalNumber
public let date: Date
public let pending: Bool
public let type: [String : String]
public let categoryID: String?
public let category: [String]?
public let name: String
public let address: String?
public let city: String?
public let state: String?
public let zip: String?
public let latitude: String?
public let longitude: String?
public init(transaction: [String : Any]) {
let meta = transaction["meta"] as! [String : Any]
let location = meta["location"] as? [String : Any]
let coordinates = location?["coordinates"] as? [String : Any]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
account = transaction["_account"]! as! String
id = transaction["_id"]! as! String
pendingID = transaction["_pendingTransaction"] as? String
amount = NSDecimalNumber(value: transaction["amount"] as! Double).roundTo(2).multiplying(by: NSDecimalNumber(value: -1.0)) //Plaid stores withdraws as positves and deposits as negatives
date = formatter.date(from: transaction["date"] as! String)!
pending = transaction["pending"]! as! Bool
type = transaction["type"]! as! [String : String]
categoryID = transaction["category_id"] as? String
category = transaction["category"] as? [String]
name = transaction["name"]! as! String
address = location?["address"] as? String
city = location?["city"] as? String
state = location?["state"] as? String
zip = location?["zip"] as? String
latitude = coordinates?["lat"] as? String
longitude = coordinates?["lng"] as? String
}
}
extension PlaidTransaction: Equatable {}
public func ==(lhs: PlaidTransaction, rhs: PlaidTransaction) -> Bool {
return lhs.id == lhs.id
}
protocol Roundable {
func roundTo(_ places: Int16) -> NSDecimalNumber
}
extension NSDecimalNumber: Roundable {
func roundTo(_ places: Int16) -> NSDecimalNumber {
return self.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .plain, scale: places, raiseOnExactness: true, raiseOnOverflow: true, raiseOnUnderflow: true,raiseOnDivideByZero: true))
}
}
| mit | b0a97eef3fcc347d845b8a1177269461 | 31.154762 | 207 | 0.623473 | 4.377634 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/Model/Repos/ObjRepos.swift | 1 | 16888 | //
// ObjRepos.swift
// BeeFun
//
// Created by wenghengcong on 16/1/23.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import Foundation
import ObjectMapper
/*
{
"id": 3739481,
"name": "ZXingObjC",
"full_name": "TheLevelUp/ZXingObjC",
"owner": {
"login": "TheLevelUp",
"id": 1521628,
"avatar_url": "https://avatars3.githubusercontent.com/u/1521628?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/TheLevelUp",
"html_url": "https://github.com/TheLevelUp",
"followers_url": "https://api.github.com/users/TheLevelUp/followers",
"following_url": "https://api.github.com/users/TheLevelUp/following{/other_user}",
"gists_url": "https://api.github.com/users/TheLevelUp/gists{/gist_id}",
"starred_url": "https://api.github.com/users/TheLevelUp/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/TheLevelUp/subscriptions",
"organizations_url": "https://api.github.com/users/TheLevelUp/orgs",
"repos_url": "https://api.github.com/users/TheLevelUp/repos",
"events_url": "https://api.github.com/users/TheLevelUp/events{/privacy}",
"received_events_url": "https://api.github.com/users/TheLevelUp/received_events",
"type": "Organization",
"site_admin": false
},
"private": false,
"html_url": "https://github.com/TheLevelUp/ZXingObjC",
"description": "An Objective-C Port of ZXing",
"fork": false,
"url": "https://api.github.com/repos/TheLevelUp/ZXingObjC",
"forks_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/forks",
"keys_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/teams",
"hooks_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/hooks",
"issue_events_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues/events{/number}",
"events_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/events",
"assignees_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/assignees{/user}",
"branches_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/branches{/branch}",
"tags_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/tags",
"blobs_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/statuses/{sha}",
"languages_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/languages",
"stargazers_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/stargazers",
"contributors_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/contributors",
"subscribers_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/subscribers",
"subscription_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/subscription",
"commits_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/contents/{+path}",
"compare_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/merges",
"archive_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/downloads",
"issues_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/issues{/number}",
"pulls_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/pulls{/number}",
"milestones_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/milestones{/number}",
"notifications_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/labels{/name}",
"releases_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/releases{/id}",
"deployments_url": "https://api.github.com/repos/TheLevelUp/ZXingObjC/deployments",
"created_at": "2012-03-16T14:09:18Z",
"updated_at": "2018-05-02T02:14:07Z",
"pushed_at": "2018-04-18T07:42:30Z",
"git_url": "git://github.com/TheLevelUp/ZXingObjC.git",
"ssh_url": "[email protected]:TheLevelUp/ZXingObjC.git",
"clone_url": "https://github.com/TheLevelUp/ZXingObjC.git",
"svn_url": "https://github.com/TheLevelUp/ZXingObjC",
"homepage": "",
"size": 187508,
"stargazers_count": 2644,
"watchers_count": 2644,
"language": "Objective-C",
"has_issues": true,
"has_projects": false,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 666,
"mirror_url": null,
"archived": false,
"open_issues_count": 21,
"license": {
"key": "apache-2.0",
"name": "Apache License 2.0",
"spdx_id": "Apache-2.0",
"url": "https://api.github.com/licenses/apache-2.0"
},
"forks": 666,
"open_issues": 21,
"watchers": 2644,
"default_branch": "master",
"permissions": {
"admin": false,
"push": false,
"pull": true
}
}
*/
public class ObjRepos: NSObject, Mappable {
//1
var archive_url: String?
var assignees_url: String?
var blobs_url: String?
var branches_url: String?
var clone_url: String?
var collaborators_url: String?
var comments_url: String?
var commits_url: String?
var compare_url: String?
var contents_url: String?
//11
var contributors_url: String?
var created_at: String?
var default_branch: String?
var deployments_url: String?
var cdescription: String? //description同关键字冲突,加c前缀
var downloads_url: String?
var events_url: String?
var fork: Bool?
var forks: Int?
var forks_count: Int?
//21
var forks_url: String?
var full_name: String?
var git_commits_url: String?
var git_refs_url: String?
var git_tags_url: String?
var git_url: String?
var has_downloads: Bool?
var has_projects: Bool?
var has_issues: Bool?
var has_pages: Bool?
var has_wiki: Bool?
//31
var homepage: String?
var hooks_url: String?
var html_url: String?
var id: Int?
var issue_comment_url: String?
var issue_events_url: String?
var issues_url: String?
var keys_url: String?
var labels_url: String?
var language: String?
//41
var languages_url: String?
var merges_url: String?
var milestones_url: String?
var mirror_url: String?
var name: String?
var notifications_url: String?
var open_issues: Int?
var open_issues_count: Int?
var owner: ObjUser?
var star_owner: String?
var permissions: ObjPermissions?
//51
var cprivate: Bool? //private同关键字冲突,加c前缀
var pulls_url: String?
var pushed_at: String?
var releases_url: String?
var size: Int?
var ssh_url: String?
var stargazers_count: Int?
var stargazers_url: String?
var statuses_url: String?
var subscribers_url: String?
//61
var subscription_url: String?
var svn_url: String?
var tags_url: String?
var teams_url: String?
var trees_url: String?
var updated_at: String?
var url: String?
var watchers: Int?
var watchers_count: Int?
var subscribers_count: Int?
//以下字段为单独增加
var star_tags: [String]?
var star_lists: [String]?
/// 是否订阅该项目
var watched: Bool? = false
/// 是否关注该项目
var starred: Bool? = false
/// 关注该repo的时间,从网络请求中截取
var starred_at: String?
/// Trending中
var trending_star_text: String? /// star
var trending_fork_text: String? /// star
var trending_star_interval_text: String? /// 200 stars this week
var trending_showcase_update_text: String? ///Updated Jul 5, 2017
var score: Double? //搜索得分
struct ReposKey {
static let archiveUrlKey = "archive_url"
static let assigneesUrlKey = "assignees_url"
static let blobsUrlKey = "blobs_url"
static let branchesUrlKey = "branches_url"
static let cloneUrlKey = "clone_url"
static let collaboratorsUrlKey = "collaborators_url"
static let commentsUrlKey = "comments_url"
static let commitsUrlKey = "commits_url"
static let compareUrlKey = "compare_url"
static let contentsUrlKey = "contents_url"
static let contributorsUrlKey = "contributors_url"
static let createdAtKey = "created_at"
static let defaultBranchKey = "default_branch"
static let deploymentsUrlKey = "deployments_url"
static let descriptionKey = "description"
static let downloadsUrlKey = "downloads_url"
static let eventsUrlKey = "events_url"
static let forkKey = "fork"
static let forksKey = "forks"
static let forksCountKey = "forks_count"
static let forksUrlKey = "forks_url"
static let fullNameKey = "full_name"
static let gitCommitsUrlKey = "git_commits_url"
static let gitRefsUrlKey = "git_refs_url"
static let gitTagsUrlKey = "git_tags_url"
static let gitUrlKey = "git_url"
static let hasDownloadsKey = "has_downloads"
static let hasProjects = "has_projects"
static let hasIssuesKey = "has_issues"
static let hasPagesKey = "has_pages"
static let hasWikiKey = "has_wiki"
static let homepageKey = "homepage"
static let hooksUrlKey = "hooks_url"
static let htmlUrlKey = "html_url"
static let idKey = "id"
static let issueCommentUrlKey = "issue_comment_url:"
static let issueEventsUrlKey = "issue_events_url"
static let issuesUrlKey = "issues_url"
static let keysUrlKey = "keys_url"
static let labelsUrlKey = "labels_url"
static let languageKey = "language"
static let languagesUrlKey = "languages_url"
static let mergesUrlKey = "merges_url"
static let milestonesUrlKey = "milestones_url"
static let mirrorUrlKey = "mirror_url"
static let nameKey = "name"
static let notificationsUrlKey = "notifications_url"
static let openIssuesKey = "open_issues"
static let openIssuesCountKey = "open_issues_count"
static let ownerKey = "owner"
static let starOwnerKey = "star_owner"
static let permissionsKey = "permissions"
static let privateKey = "private"
static let pullsUrlKey = "pulls_url"
static let pushedAtKey = "pushed_at"
static let releasesUrlKey = "releases_url"
static let sizeKey = "size"
static let sshUrley = "ssh_url"
static let stargazersCountKey = "stargazers_count"
static let stargazersUrlKey = "stargazers_url"
static let statusesUrlKey = "statuses_url"
static let subscribersUrlKey = "subscribers_url"
static let subscriptionUrlKey = "subscription_url"
static let svnUrlKey = "svn_url"
static let tagsUrlKey = "tags_url"
static let teamsUrlKey = "teams_url"
static let treesUrlKey = "trees_url:"
static let updatedAtKey = "updated_at"
static let urlKey = "url"
static let watchersKey = "watchers"
static let watchersCountKey = "watchers_count"
static let subscribersCountKey = "subscribers_count"
static let starTagsKey = "star_tags"
static let starListKey = "star_lists"
static let watchedKey = "watched"
static let scoreKey = "score"
static let starred_atKey = "starred_at"
static let trending_star_textKey = "trending_star_text"
static let trending_fork_textKey = "trending_fork_text"
static let trending_star_interval_textKey = "trending_star_interval_text"
static let trending_showcase_update_textKey = "trending_showcase_update_text"
}
// MARK: init and mapping
required public init?(map: Map) {
}
override init() {
super.init()
}
public func mapping(map: Map) {
// super.mapping(map)
archive_url <- map[ReposKey.archiveUrlKey]
assignees_url <- map[ReposKey.assigneesUrlKey]
blobs_url <- map[ReposKey.blobsUrlKey]
branches_url <- map[ReposKey.branchesUrlKey]
clone_url <- map[ReposKey.cloneUrlKey]
collaborators_url <- map[ReposKey.collaboratorsUrlKey]
comments_url <- map[ReposKey.commentsUrlKey]
commits_url <- map[ReposKey.commitsUrlKey]
compare_url <- map[ReposKey.compareUrlKey]
contents_url <- map[ReposKey.contentsUrlKey]
contributors_url <- map[ReposKey.contributorsUrlKey]
created_at <- map[ReposKey.createdAtKey]
default_branch <- map[ReposKey.defaultBranchKey]
deployments_url <- map[ReposKey.deploymentsUrlKey]
cdescription <- map[ReposKey.descriptionKey]
downloads_url <- map[ReposKey.downloadsUrlKey]
events_url <- map[ReposKey.eventsUrlKey]
fork <- map[ReposKey.forkKey]
forks <- map[ReposKey.forksKey]
forks_count <- map[ReposKey.forksCountKey]
forks_url <- map[ReposKey.forksUrlKey]
full_name <- map[ReposKey.fullNameKey]
git_commits_url <- map[ReposKey.gitCommitsUrlKey]
git_refs_url <- map[ReposKey.gitRefsUrlKey]
git_tags_url <- map[ReposKey.gitTagsUrlKey]
git_url <- map[ReposKey.gitUrlKey]
has_downloads <- map[ReposKey.hasDownloadsKey]
has_projects <- map[ReposKey.hasProjects]
has_issues <- map[ReposKey.hasIssuesKey]
has_pages <- map[ReposKey.hasPagesKey]
has_wiki <- map[ReposKey.hasWikiKey]
homepage <- map[ReposKey.homepageKey]
hooks_url <- map[ReposKey.hooksUrlKey]
html_url <- map[ReposKey.htmlUrlKey]
id <- map[ReposKey.idKey]
issue_comment_url <- map[ReposKey.issueCommentUrlKey]
issue_events_url <- map[ReposKey.issueEventsUrlKey]
issues_url <- map[ReposKey.issuesUrlKey]
keys_url <- map[ReposKey.keysUrlKey]
labels_url <- map[ReposKey.labelsUrlKey]
language <- map[ReposKey.languageKey]
languages_url <- map[ReposKey.languagesUrlKey]
merges_url <- map[ReposKey.mergesUrlKey]
milestones_url <- map[ReposKey.milestonesUrlKey]
mirror_url <- map[ReposKey.mirrorUrlKey]
name <- map[ReposKey.nameKey]
notifications_url <- map[ReposKey.notificationsUrlKey]
open_issues <- map[ReposKey.openIssuesKey]
open_issues_count <- map[ReposKey.openIssuesCountKey]
owner <- map[ReposKey.ownerKey]
star_owner <- map[ReposKey.starOwnerKey]
permissions <- map[ReposKey.permissionsKey]
cprivate <- map[ReposKey.privateKey]
pulls_url <- map[ReposKey.pullsUrlKey]
pushed_at <- map[ReposKey.pushedAtKey]
releases_url <- map[ReposKey.releasesUrlKey]
size <- map[ReposKey.sizeKey]
ssh_url <- map[ReposKey.sshUrley]
stargazers_count <- map[ReposKey.stargazersCountKey]
stargazers_url <- map[ReposKey.stargazersUrlKey]
statuses_url <- map[ReposKey.statusesUrlKey]
subscribers_url <- map[ReposKey.subscribersUrlKey]
subscription_url <- map[ReposKey.subscriptionUrlKey]
svn_url <- map[ReposKey.svnUrlKey]
tags_url <- map[ReposKey.gitTagsUrlKey]
teams_url <- map[ReposKey.teamsUrlKey]
trees_url <- map[ReposKey.treesUrlKey]
updated_at <- map[ReposKey.updatedAtKey]
url <- map[ReposKey.urlKey]
watchers <- map[ReposKey.watchersKey]
watchers_count <- map[ReposKey.watchersCountKey]
subscribers_count <- map[ReposKey.subscribersCountKey]
score <- map[ReposKey.scoreKey]
starred_at <- map[ReposKey.starred_atKey]
star_tags <- map[ReposKey.starTagsKey]
star_lists <- map[ReposKey.starListKey]
trending_fork_text <- map[ReposKey.trending_fork_textKey]
trending_star_text <- map[ReposKey.trending_star_textKey]
trending_star_interval_text <- map[ReposKey.trending_star_interval_textKey]
trending_showcase_update_text <- map[ReposKey.trending_showcase_update_textKey]
}
}
| mit | d08841cba5f86bb3cd2c5c3634d727b3 | 39.383133 | 114 | 0.662271 | 3.735012 | false | false | false | false |
x331275955/- | xiong-练习微博(视频)/xiong-练习微博(视频)/Models/UserAccount.swift | 1 | 4079 | //
// UserAccount.swift
// xiong-练习微博(视频)
//
// Created by 王晨阳 on 15/9/14.
// Copyright © 2015年 IOS. All rights reserved.
//
import UIKit
class UserAccount: NSObject, NSCoding {
// MARK: - 成员属性:
// 用于调用access_token,接口获取授权后的access token。
var access_token : String?
// 授权过期时间
var expiresDate : NSDate?
// 当前授权用户的UID。
var uid : String?
// 友好显示名称
var name : String?
// 用户的头像(大图180*180)
var avatar_large : String?
// access_token的生命周期,单位是秒数。
var expires_in : NSTimeInterval = 0
// 用户是否登录
class var userLogon: Bool {
return UserAccount.loadAccount() != nil
}
// MARK:- KVC字典转模型
init(dict:[String:AnyObject]){
// 调用父类的init方法
super.init()
setValuesForKeysWithDictionary(dict)
expiresDate = NSDate(timeIntervalSinceNow: expires_in)
UserAccount.userAccount = self
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
// MARK:- 获取:对象描述信息.
override var description: String {
let properties = ["access_token","expires_in","uid","expiresDate", "name", "avatar_large"]
return "\(dictionaryWithValuesForKeys(properties))"
}
// 保存用户账号
private func saveAccount(){
NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
}
//MARK:- 加载用户信息
func loadUserInfo(finished:(error: NSError?) -> ()){
NetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in
if let dict = result{
// 设置用户信息
self.name = dict["name"] as? String
self.avatar_large = dict["avatar_large"] as? String
// TODO: 保存用户信息
print("5.(UserAccount)保存用户信息",self.name,self.avatar_large)
// 保存用户信息
self.saveAccount()
}
finished(error: nil)
}
}
// MARK:- 载入用户信息, 先判断账户是否为空,是否过期
// 静态的用户账户属性
private static var userAccount: UserAccount?
class func loadAccount() -> UserAccount? {
// 如果账户为空从本地加载
if userAccount == nil{
userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
}
// 判断是否过期
if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{
// 如果过期,设置为空
userAccount = nil
}
return userAccount
}
// MARK:- 归档和解档的方法
/// 保存归档文件的路径
static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/account.Plist")
// 归档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(expiresDate, forKey: "expiresDate")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
}
// 解档
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeDoubleForKey("expires_in")
expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
uid = aDecoder.decodeObjectForKey("uid") as? String
name = aDecoder.decodeObjectForKey("name") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
}
}
| mit | bc80dfba132931bf442e4845dffe69bb | 29.857143 | 176 | 0.607298 | 4.567164 | false | false | false | false |
EZ-NET/CodePiece | ESTwitter/Data/Entity/MediaEntity.swift | 1 | 1149 | //
// Media.swift
// CodePiece
//
// Created by Tomohiro Kumagai on H27/11/15.
// Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//
public struct MediaEntity : HasIndices {
public struct Size {
public var width: Int
public var height: Int
public var resize: String
}
public var idStr: String
public var mediaUrlHttps: TwitterUrl
public var expandedUrl: TwitterUrl
public var id: UInt64
public var sizes: [String : Size]
public var displayUrl: String
public var type: String
public var indices: Indices
public var mediaUrl: TwitterUrl
public var url: TwitterUrl
}
extension MediaEntity : EntityUnit {
var displayText: String {
displayUrl
}
}
extension MediaEntity : Decodable {
enum CodingKeys : String, CodingKey {
case idStr = "id_str"
case mediaUrlHttps = "media_url_https"
case expandedUrl = "expanded_url"
case id
case sizes
case displayUrl = "display_url"
case type
case indices
case mediaUrl = "media_url"
case url
}
}
extension MediaEntity.Size : Decodable {
enum CodingKeys : String, CodingKey {
case width = "w"
case height = "h"
case resize
}
}
| gpl-3.0 | 280eb07bbe782b0cce4cc9d2465c1b68 | 17.126984 | 57 | 0.704028 | 3.300578 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CheckoutCompleteFreePayload.swift | 1 | 5694 | //
// CheckoutCompleteFreePayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `checkoutCompleteFree` mutation.
open class CheckoutCompleteFreePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CheckoutCompleteFreePayload
/// The updated checkout object.
@discardableResult
open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutCompleteFreePayloadQuery {
let subquery = CheckoutQuery()
subfields(subquery)
addField(field: "checkout", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutCompleteFreePayloadQuery {
let subquery = CheckoutUserErrorQuery()
subfields(subquery)
addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutCompleteFreePayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `checkoutCompleteFree` mutation.
open class CheckoutCompleteFreePayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CheckoutCompleteFreePayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "checkout":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue)
}
return try Checkout(fields: value)
case "checkoutUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CheckoutUserError(fields: $0) }
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CheckoutCompleteFreePayload.self, field: fieldName, value: fieldValue)
}
}
/// The updated checkout object.
open var checkout: Storefront.Checkout? {
return internalGetCheckout()
}
func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? {
return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout?
}
/// The list of errors that occurred from executing the mutation.
open var checkoutUserErrors: [Storefront.CheckoutUserError] {
return internalGetCheckoutUserErrors()
}
func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] {
return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError]
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `checkoutUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "checkout":
if let value = internalGetCheckout() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutUserErrors":
internalGetCheckoutUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 03e4131f373ddd373abbb493e27d29a9 | 35.974026 | 137 | 0.729715 | 4.386749 | false | false | false | false |
matthew-compton/Photorama | Photorama/Photo.swift | 1 | 825 | //
// Photo.swift
// Photorama
//
// Created by Matthew Compton on 10/22/15.
// Copyright © 2015 Big Nerd Ranch. All rights reserved.
//
import UIKit
import CoreData
class Photo: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
var image: UIImage?
override func awakeFromInsert() {
super.awakeFromInsert()
title = ""
photoID = ""
remoteURL = NSURL()
photoKey = NSUUID().UUIDString
dateTaken = NSDate()
}
func addTagObject(tag: NSManagedObject) {
let currentTags = mutableSetValueForKey("tags")
currentTags.addObject(tag)
}
func removeTagObject(tag: NSManagedObject) {
let currentTags = mutableSetValueForKey("tags")
currentTags.removeObject(tag)
}
}
| apache-2.0 | 020280fe7b4f8127b0a6ca0abd4cba01 | 21.27027 | 72 | 0.63835 | 4.430108 | false | false | false | false |
DoubleSha/BitcoinSwift | BitcoinSwift/Models/BlockHeader.swift | 1 | 4719 | //
// BlockHeader.swift
// BitcoinSwift
//
// Created by Kevin Greene on 9/28/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: BlockHeader, right: BlockHeader) -> Bool {
return left.version == right.version &&
left.previousBlockHash == right.previousBlockHash &&
left.merkleRoot == right.merkleRoot &&
left.timestamp == right.timestamp &&
left.compactDifficulty == right.compactDifficulty &&
left.nonce == right.nonce
}
public protocol BlockHeaderParameters {
var blockVersion: UInt32 { get }
}
public struct BlockHeader: Equatable {
public let version: UInt32
public let previousBlockHash: SHA256Hash
public let merkleRoot: SHA256Hash
public let timestamp: NSDate
public let compactDifficulty: UInt32
public let nonce: UInt32
static private let largestDifficulty = BigInteger(1) << 256
private var cachedHash: SHA256Hash?
public init(params: BlockHeaderParameters,
previousBlockHash: SHA256Hash,
merkleRoot: SHA256Hash,
timestamp: NSDate,
compactDifficulty: UInt32,
nonce: UInt32) {
self.init(version: params.blockVersion,
previousBlockHash: previousBlockHash,
merkleRoot: merkleRoot,
timestamp: timestamp,
compactDifficulty: compactDifficulty,
nonce: nonce)
}
public init(version: UInt32,
previousBlockHash: SHA256Hash,
merkleRoot: SHA256Hash,
timestamp: NSDate,
compactDifficulty: UInt32,
nonce: UInt32) {
self.version = version
self.previousBlockHash = previousBlockHash
self.merkleRoot = merkleRoot
self.timestamp = timestamp
self.compactDifficulty = compactDifficulty
self.nonce = nonce
}
/// Calculated from the information in the block header. It does not include the transactions.
/// https://en.bitcoin.it/wiki/Block_hashing_algorithm
public var hash: SHA256Hash {
// TODO: Don't recalculate this every time.
return SHA256Hash(data: bitcoinData.SHA256Hash().SHA256Hash().reversedData)
}
/// The difficulty used to create this block. This is the uncompressed form of the
/// compactDifficulty property.
public var difficulty: BigInteger {
let compactDifficultyData = NSMutableData()
compactDifficultyData.appendUInt32(compactDifficulty, endianness: .BigEndian)
return BigInteger(compactData: compactDifficultyData)
}
/// The work represented by this block.
/// Work is defined as the number of tries needed to solve a block in the average case.
/// Consider a difficulty target that covers 5% of all possible hash values. Then the work of the
/// block will be 20. As the difficulty gets lower, the amount of work goes up.
public var work: BigInteger {
return BlockHeader.largestDifficulty / (difficulty + BigInteger(1))
}
}
extension BlockHeader: BitcoinSerializable {
public var bitcoinData: NSData {
let data = NSMutableData()
data.appendUInt32(version)
data.appendData(previousBlockHash.bitcoinData)
data.appendData(merkleRoot.bitcoinData)
data.appendDateAs32BitUnixTimestamp(timestamp)
data.appendUInt32(compactDifficulty)
data.appendUInt32(nonce)
return data
}
public static func fromBitcoinStream(stream: NSInputStream) -> BlockHeader? {
let version = stream.readUInt32()
if version == nil {
Logger.warn("Failed to parse version from BlockHeader")
return nil
}
let previousBlockHash = SHA256Hash.fromBitcoinStream(stream)
if previousBlockHash == nil {
Logger.warn("Failed to parse previousBlockHash from BlockHeader")
return nil
}
let merkleRoot = SHA256Hash.fromBitcoinStream(stream)
if merkleRoot == nil {
Logger.warn("Failed to parse merkleRoot from BlockHeader")
return nil
}
let timestamp = stream.readDateFrom32BitUnixTimestamp()
if timestamp == nil {
Logger.warn("Failed to parse timestamp from BlockHeader")
return nil
}
let compactDifficulty = stream.readUInt32()
if compactDifficulty == nil {
Logger.warn("Failed to parse compactDifficulty from BlockHeader")
return nil
}
let nonce = stream.readUInt32()
if nonce == nil {
Logger.warn("Failed to parse nonce from BlockHeader")
return nil
}
return BlockHeader(version: version!,
previousBlockHash: previousBlockHash!,
merkleRoot: merkleRoot!,
timestamp: timestamp!,
compactDifficulty: compactDifficulty!,
nonce: nonce!)
}
}
| apache-2.0 | 2e0454aa821f93c4a4e4c2b2947c1d62 | 32.707143 | 99 | 0.68256 | 4.956933 | false | false | false | false |
iException/CSStickyHeaderFlowLayout | Project/SwiftDemo/SwiftDemo/CollectionParallaxHeader.swift | 2 | 977 | //
// CollectionParallaxHeader.swift
// SwiftDemo
//
// Created by James Tang on 16/7/15.
// Copyright © 2015 James Tang. All rights reserved.
//
import UIKit
class CollectionParallaxHeader: UICollectionReusableView {
private var imageView : UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.lightGrayColor()
self.clipsToBounds = true
let bounds = CGRectMake(0, 0, CGRectGetMaxX(frame), CGRectGetMaxY(frame))
let imageView = UIImageView(frame: bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.image = UIImage(named: "success-baby")
self.imageView = imageView
self.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.frame = self.bounds
}
}
| mit | 995fad60baafc957d3f789d599059b25 | 23.4 | 81 | 0.667008 | 4.647619 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.