repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
debugsquad/metalic | refs/heads/master | metalic/Model/Main/MMain.swift | mit | 1 | import Foundation
class MMain
{
let items:[MMainItem]
var state:MMainState
weak var current:MMainItem!
weak var itemHome:MMainItemHome!
init()
{
state = MMainStateOptions()
var items:[MMainItem] = []
let itemHome:MMainItemHome = MMainItemHome(index:items.count)
current = itemHome
self.itemHome = itemHome
items.append(itemHome)
let itemStore:MMainItemStore = MMainItemStore(index:items.count)
items.append(itemStore)
self.items = items
}
//MARK: public
func pushed()
{
state = MMainStatePushed()
}
func poped()
{
state = MMainStateOptions()
}
}
| c5e0dc95ee2d1fe5f4e55bad602d2d76 | 18.945946 | 72 | 0.571816 | false | false | false | false |
ashfurrow/RxSwift | refs/heads/master | Rx.playground/Pages/Combining_Observables.xcplaygroundpage/Contents.swift | mit | 2 | //: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
## Combination operators
Operators that work with multiple source Observables to create a single Observable.
*/
/*:
### `startWith`
emit a specified sequence of items before beginning to emit the items from the source Observable

[More info in reactive.io website]( http://reactivex.io/documentation/operators/startwith.html )
*/
example("startWith") {
let subscription = sequenceOf(4, 5, 6, 7, 8, 9)
.startWith(3)
.startWith(2)
.startWith(1)
.startWith(0)
.subscribe {
print($0)
}
}
/*:
### `combineLatest`
when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function

[More info in reactive.io website]( http://reactivex.io/documentation/operators/combinelatest.html )
*/
example("combineLatest 1") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
_ = combineLatest(intOb1, intOb2) {
"\($0) \($1)"
}
.subscribe {
print($0)
}
intOb1.on(.Next("A"))
intOb2.on(.Next(1))
intOb1.on(.Next("B"))
intOb2.on(.Next(2))
}
//: To produce output, at least one element has to be received from each sequence in arguements.
example("combineLatest 2") {
let intOb1 = just(2)
let intOb2 = sequenceOf(0, 1, 2, 3, 4)
_ = combineLatest(intOb1, intOb2) {
$0 * $1
}
.subscribe {
print($0)
}
}
//: Combine latest has versions with more than 2 arguments.
example("combineLatest 3") {
let intOb1 = just(2)
let intOb2 = sequenceOf(0, 1, 2, 3)
let intOb3 = sequenceOf(0, 1, 2, 3, 4)
_ = combineLatest(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
.subscribe {
print($0)
}
}
//: Combinelatest version that allows combining sequences with different types.
example("combineLatest 4") {
let intOb = just(2)
let stringOb = just("a")
_ = combineLatest(intOb, stringOb) {
"\($0) " + $1
}
.subscribe {
print($0)
}
}
//: `combineLatest` extension method for Array of `ObservableType` conformable types
//: The array must be formed by `Observables` of the same type.
example("combineLatest 5") {
let intOb1 = just(2)
let intOb2 = sequenceOf(0, 1, 2, 3)
let intOb3 = sequenceOf(0, 1, 2, 3, 4)
_ = [intOb1, intOb2, intOb3].combineLatest { intArray -> Int in
Int((intArray[0] + intArray[1]) * intArray[2])
}
.subscribe { (event: Event<Int>) -> Void in
print(event)
}
}
/*:
### `zip`
combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

[More info in reactive.io website](http://reactivex.io/documentation/operators/zip.html)
*/
example("zip 1") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
_ = zip(intOb1, intOb2) {
"\($0) \($1)"
}
.subscribe {
print($0)
}
intOb1.on(.Next("A"))
intOb2.on(.Next(1))
intOb1.on(.Next("B"))
intOb1.on(.Next("C"))
intOb2.on(.Next(2))
}
example("zip 2") {
let intOb1 = just(2)
let intOb2 = sequenceOf(0, 1, 2, 3, 4)
_ = zip(intOb1, intOb2) {
$0 * $1
}
.subscribe {
print($0)
}
}
example("zip 3") {
let intOb1 = sequenceOf(0, 1)
let intOb2 = sequenceOf(0, 1, 2, 3)
let intOb3 = sequenceOf(0, 1, 2, 3, 4)
_ = zip(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
.subscribe {
print($0)
}
}
/*:
### `merge`
combine multiple Observables into one by merging their emissions

[More info in reactive.io website]( http://reactivex.io/documentation/operators/merge.html )
*/
example("merge 1") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
_ = sequenceOf(subject1, subject2)
.merge()
.subscribeNext { int in
print(int)
}
subject1.on(.Next(20))
subject1.on(.Next(40))
subject1.on(.Next(60))
subject2.on(.Next(1))
subject1.on(.Next(80))
subject1.on(.Next(100))
subject2.on(.Next(1))
}
example("merge 2") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
_ = sequenceOf(subject1, subject2)
.merge(maxConcurrent: 2)
.subscribe {
print($0)
}
subject1.on(.Next(20))
subject1.on(.Next(40))
subject1.on(.Next(60))
subject2.on(.Next(1))
subject1.on(.Next(80))
subject1.on(.Next(100))
subject2.on(.Next(1))
}
/*:
### `switchLatest`
convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables

[More info in reactive.io website]( http://reactivex.io/documentation/operators/switch.html )
*/
example("switchLatest") {
let var1 = Variable(0)
let var2 = Variable(200)
// var3 is like an Observable<Observable<Int>>
let var3 = Variable(var1)
let d = var3
.switchLatest()
.subscribe {
print($0)
}
var1.value = 1
var1.value = 2
var1.value = 3
var1.value = 4
var3.value = var2
var2.value = 201
var1.value = 5
var1.value = 6
var1.value = 7
}
//: [Index](Index) - [Next >>](@next)
| 44f4ad4e674e05fd7dfbdbb09c2ec4bf | 20.910714 | 182 | 0.601304 | false | true | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieGraphics/SVGContext/SVGEffect/SVGTileEffect.swift | mit | 1 | //
// SVGTileEffect.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public struct SVGTileEffect: SVGEffectElement {
public var region: Rect = .null
public var regionUnit: SVGEffect.RegionUnit = .objectBoundingBox
public var source: SVGEffect.Source
public var sources: [SVGEffect.Source] {
return [source]
}
public init(source: SVGEffect.Source = .source) {
self.source = source
}
public func visibleBound(_ sources: [SVGEffect.Source: Rect]) -> Rect? {
return nil
}
}
extension SVGTileEffect {
public var xml_element: SDXMLElement {
var filter = SDXMLElement(name: "feTile")
switch self.source {
case .source: filter.setAttribute(for: "in", value: "SourceGraphic")
case .sourceAlpha: filter.setAttribute(for: "in", value: "SourceAlpha")
case let .reference(uuid): filter.setAttribute(for: "in", value: uuid.uuidString)
}
return filter
}
}
| 374a51e14564eb51437a77c95ee54423 | 34.52459 | 89 | 0.686202 | false | false | false | false |
maranathApp/GojiiFramework | refs/heads/master | GojiiFrameWork/UIImageViewExtensions.swift | mit | 1 | //
// CGFloatExtensions.swift
// GojiiFrameWork
//
// Created by Stency Mboumba on 01/06/2017.
// Copyright © 2017 Stency Mboumba. All rights reserved.
//
import UIKit
// MARK: - Extension UIImageView BSFramework
public extension UIImageView {
/* --------------------------------------------------------------------------- */
// MARK: - Initilizers ( init )
/* --------------------------------------------------------------------------- */
/**
Initialize with internal image ( with image or not if imageName = nil )
- parameter frame: CGRect
- parameter imageName: String? / Name of image in Asset
- parameter contentMode: UIViewContentMode ( default = ScaleAspectFit )
- returns: UIImageView
*/
public convenience init (frame: CGRect, imageName: String?, contentMode:UIViewContentMode = .scaleAspectFit) {
guard let hasImgName = imageName, let hasImage = UIImage (named: hasImgName) else {
self.init (frame: frame)
self.contentMode = contentMode
return
}
self.init (frame: frame,image: hasImage, contentMode: contentMode)
}
/**
Initialize with internal image
- parameter frame: CGRect
- parameter image: String / Name of image in Asset
- parameter contentMode: UIViewContentMode ( default = ScaleAspectFit )
- returns: UIImageView
*/
public convenience init (frame: CGRect, image: UIImage, contentMode:UIViewContentMode = .scaleAspectFit) {
self.init (frame: frame)
self.image = image
self.contentMode = contentMode
}
/**
Initialize, Download a image on a server
Can set a default image
When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation
- parameter frame: CGRect
- parameter nsurl: NSURL
- parameter defaultImage: String? / default image (default = nil)
- parameter contentMode: UIViewContentMode (default = .ScaleAspectFit)
- parameter succesDownload: ()->()?
- parameter errorDownload: (UIImageBSError)->()?
- returns: UIImageView
*/
public convenience init (
frame: CGRect,
nsurl:NSURL,
defaultImage:NSData? = nil,
contentMode:UIViewContentMode = .scaleAspectFit,
succesDownload:(()->())? = nil,
errorDownload:((_ error:UIImageViewBSError)->())? = nil) {
if let hasImageString = defaultImage, let hasImage = UIImage(data: hasImageString as Data) {
self.init(frame: frame, image: hasImage, contentMode: contentMode)
} else {
self.init(frame: frame)
self.contentMode = contentMode
}
self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload)
}
/**
Initialize, Download a image on a server
Can set a default image
When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation
- parameter frame: CGRect
- parameter nsurl: NSURL
- parameter defaultImage: String? / default image (default = nil)
- parameter contentMode: UIViewContentMode (default = .ScaleAspectFit)
- parameter succesDownload: ()->()?
- parameter errorDownload: (UIImageBSError)->()?
- returns: UIImageView
*/
public convenience init (
frame: CGRect,
nsurl:NSURL,
defaultImage:String? = nil,
contentMode:UIViewContentMode = .scaleAspectFit,
succesDownload:(()->())? = nil,
errorDownload:((_ error:UIImageViewBSError)->())? = nil) {
self.init(frame: frame, imageName: defaultImage, contentMode: contentMode)
self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload)
}
/**
Initialize, Download a image on a server
Can set a default image
When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation
- parameter frame: CGRect
- parameter url: String Url
- parameter defaultImage: String? / default image (default = nil)
- parameter contentMode: UIViewContentMode (default = .ScaleAspectFit)
- parameter succesDownload: ()->()?
- parameter errorDownload: (UIImageBSError)->()?
- returns: UIImageView
*/
public convenience init (
frame: CGRect,
url:String,
defaultImage:String? = nil,
contentMode:UIViewContentMode = .scaleAspectFit,
succesDownload:(()->())? = nil,
errorDownload:((_ error:UIImageViewBSError)->())? = nil
) {
self.init(frame: frame, imageName: defaultImage, contentMode: contentMode)
guard let nsurl = NSURL (string: url) else {
errorDownload?(UIImageViewBSError.Nil(errorIs: "URLString is nil"))
return
}
self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload)
}
/* --------------------------------------------------------------------------- */
// MARK: - Download image for server
/* --------------------------------------------------------------------------- */
/**
Download image for server
When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation
Or directly if succesDownload = nil
succesDownload (imageView = self / UIImageView , donwloadedImage = UIImage / image downloaded)
- parameter url: NSURL
- parameter succesDownload: (imageView = self / UIImageView , donwloadedImage = UIImage / image downloaded)->()
- parameter errorDownload: ()->() / Call when error
*/
public func imageWithUrl(
url:NSURL,
succesDownload:(()->())? = nil,
errorDownload:((_ error:UIImageViewBSError)->())? = nil
) {
NSData.getDataFromNSURL(urL: url as URL) {
(data, error) in
DispatchQueue.main.sync(execute: {
guard error == nil, let hasData = data, let hasImage = UIImage(data: hasData) else {
if error != nil {
errorDownload?(UIImageViewBSError.NSURL(errorIs: error.debugDescription)
)
} else {
errorDownload?(UIImageViewBSError.NSData(errorIs:"NSData Error : data not have image")
)
}
return
}
succesDownload?()
self.image = hasImage
// Update the UI on the main thread.
})
}
}
/* --------------------------------------------------------------------------- */
// MARK: - UIImageView → TintColor
/* --------------------------------------------------------------------------- */
/**
Tint picto with color
- parameter color: UIColor
*/
public func tintPicto(color:UIColor) {
if let imageToChange = self.image?.withRenderingMode(.alwaysTemplate) {
self.image = imageToChange
self.tintColor = color
}
}
/**
Tint Photo with 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>
- parameter color: UIColor
*/
public func tintPhoto(color:UIColor) {
if let imageToChange = self.image?.tintPhoto(tintColor: color) {
self.image = imageToChange
}
}
}
/* --------------------------------------------------------------------------- */
// MARK: - UIImageViewBSError UIImageView Extensions
/* --------------------------------------------------------------------------- */
/**
Enum for Debug BSError
- Error: Error of any kind
- Nil: Error Nil Object
- NSData: Error NSData
- NSURL: Error NSUrl
- JSON: Error JSon
*/
public enum UIImageViewBSError: Error, CustomStringConvertible {
case Error(whereIs:String,funcIs:String, errorIs:String)
case Nil(errorIs:String)
case NSData(errorIs:String)
case NSURL(errorIs:String)
/// A textual representation / Mark CustomStringConvertible
public var description: String {
switch self {
case .Error(let whereIs,let funcIs, let errorString) : return "[\(whereIs)][\(funcIs)] \(errorString)"
case .Nil(let errorString) : return "\(errorString)"
case .NSData(let errorString) : return "\(errorString)"
case .NSURL(let errorString) : return "\(errorString)"
}
}
/**
Print Error
*/
// func print() { printObject("[BSFramework][UIImageView extension] \(self.description)") }
}
| f2c06b1be08d3547cf2564cd7d86d1d9 | 35.900763 | 135 | 0.54096 | false | false | false | false |
seanwoodward/IBAnimatable | refs/heads/master | IBAnimatable/PinchInteractiveAnimator.swift | mit | 1 | //
// Created by Jake Lin on 4/26/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class PinchInteractiveAnimator: InteractiveAnimator {
private var startScale: CGFloat = 0
override func createGestureRecognizer() -> UIGestureRecognizer {
let gestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
return gestureRecognizer
}
override func shouldBeginProgress(gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gestureRecognizer = gestureRecognizer as? UIPinchGestureRecognizer else {
return false
}
switch interactiveGestureType {
case let .Pinch(direction):
switch direction {
case .Close:
return gestureRecognizer.velocity < 0
case .Open:
return gestureRecognizer.velocity > 0
default:
return true
}
default:
return false
}
}
override func calculateProgress(gestureRecognizer: UIGestureRecognizer) -> (progress: CGFloat, shouldFinishInteractiveTransition: Bool) {
guard let gestureRecognizer = gestureRecognizer as? UIPinchGestureRecognizer,
_ = gestureRecognizer.view?.superview else {
return (0, false)
}
if gestureRecognizer.state == .Began {
startScale = gestureRecognizer.scale
}
var progress: CGFloat
let _: CGFloat
switch interactiveGestureType {
case let .Pinch(direction):
switch direction {
case .Close:
progress = 1.0 - gestureRecognizer.scale / startScale
case .Open:
let scaleFator: CGFloat = 1.2 // To make the pinch open gesture more natural 😓
progress = gestureRecognizer.scale / scaleFator - 1.0
default:
// For both `.Close` and `.Open`
progress = abs(1.0 - gestureRecognizer.scale / startScale)
}
default:
return (0, false)
}
progress = min(max(progress, 0), 0.99)
// Finish the transition when pass the threathold
let shouldFinishInteractiveTransition = progress > 0.5
return (progress, shouldFinishInteractiveTransition)
}
}
| f3d2d186f5658d653d410fedb3298c86 | 29.112676 | 139 | 0.674462 | false | false | false | false |
leytzher/LemonadeStand_v2 | refs/heads/master | LemonadeStandv2/Balance.swift | gpl-2.0 | 1 | //
// Balance.swift
// LemonadeStandv2
//
// Created by Leytzher on 1/24/15.
// Copyright (c) 2015 Leytzher. All rights reserved.
//
import Foundation
import UIKit
class Balance{
var money = 0.0
var lemons = 0
var iceCubes = 0
var lemonsUsed = 0
var iceCubesUsed = 0
var lemonsInCart = 0
var iceCubesInCart = 0
var inStock = 0
}
| 532bae38886e9ee503672053ca123003 | 14.636364 | 53 | 0.686047 | false | false | false | false |
madoffox/Stretching | refs/heads/master | Stretching/Stretching/CalendarActivation.swift | mit | 1 | //
// CalendarVC.swift
// Stretching
//
// Created by Admin on 31.01.17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
import EventKit
var savedEventId : String = ""
func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate as Date
event.endDate = endDate as Date
event.calendar = eventStore.defaultCalendarForNewEvents
event.calendar.title = "Sport"
do {
try eventStore.save(event, span: .thisEvent)
savedEventId = event.eventIdentifier
} catch {
print("Bad things happened")
}
}
func addEvent(title: String,startDate: NSDate,endDate: NSDate) {
let eventStore = EKEventStore()
if (EKEventStore.authorizationStatus(for: .event) != EKAuthorizationStatus.authorized) {
eventStore.requestAccess(to: .event, completion: {
granted, error in
createEvent(eventStore: eventStore, title: title, startDate: startDate, endDate: endDate)
})
} else {
createEvent(eventStore: eventStore, title: title, startDate: startDate, endDate: endDate)
}
}
func retrieveEventDates()->[Date]{
let eventStore = EKEventStore()
var eventsDates = [Date]()
let calendars = eventStore.calendars(for: .event)
for calendar in calendars{
if(calendar.title == "Sport"){
let ThreeMonthAgo = NSDate(timeIntervalSinceNow: -3*30*24*3600)
let predicate = eventStore.predicateForEvents(withStart: ThreeMonthAgo as Date, end: Date(), calendars: [calendar])
let events = eventStore.events(matching: predicate)
for event in events {
eventsDates.append(event.endDate)
print(event.title)
}
break
}
}
return eventsDates
}
| 5ec2bcef18cf8bf0c99c98166cb6450c | 24.365854 | 127 | 0.599038 | false | false | false | false |
Hidebush/McBlog | refs/heads/master | McBlog/McBlog/Classes/Module/Home/Refresh/YHRefreshConrol.swift | mit | 1 | //
// YHRefreshConrol.swift
// McBlog
//
// Created by admin on 16/5/6.
// Copyright © 2016年 郭月辉. All rights reserved.
//
import UIKit
private let refreshViewOffset: CGFloat = -60
class YHRefreshConrol: UIRefreshControl {
override init() {
super.init()
setUpUI()
addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}
override func endRefreshing() {
super.endRefreshing()
refreshView.stopLoading()
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if frame.origin.y > 0 {
return
}
if refreshing {
refreshView.startLoading()
}
if frame.origin.y < refreshViewOffset && !refreshView.rotateFlag {
refreshView.rotateFlag = true
} else if frame.origin.y > refreshViewOffset && refreshView.rotateFlag {
refreshView.rotateFlag = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeObserver(self, forKeyPath: "frame")
}
private func setUpUI() {
tintColor = UIColor.clearColor()
addSubview(refreshView)
refreshView.frame = CGRectMake((UIScreen.mainScreen().bounds.size.width - 160.0) * 0.5-15, 0, 160, 60)
}
private lazy var refreshView: YHRefreshView = YHRefreshView.refreshView()
}
class YHRefreshView: UIView {
private var rotateFlag: Bool = false {
didSet {
rotateIconAnim()
}
}
@IBOutlet weak var rotateIcon: UIImageView!
@IBOutlet weak var tipView: UIView!
@IBOutlet weak var loadingIcon: UIImageView!
class func refreshView() -> YHRefreshView {
return NSBundle.mainBundle().loadNibNamed("YHRefreshView", owner: nil, options: nil).last as! YHRefreshView
}
private func rotateIconAnim() {
let angel = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
UIView.animateWithDuration(0.25) {
self.rotateIcon.transform = CGAffineTransformRotate(self.rotateIcon.transform, angel)
}
}
private func startLoading() {
tipView.hidden = true
if layer.animationForKey("loadingAnim") != nil {
return
}
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2*M_PI
anim.repeatCount = MAXFLOAT
anim.removedOnCompletion = false
anim.duration = 1
loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
}
private func stopLoading() {
tipView.hidden = false
loadingIcon.layer.removeAllAnimations()
}
} | bde9925e189c0eed5b914b8b79f9902b | 28.161616 | 157 | 0.617464 | false | false | false | false |
kaltura/playkit-ios | refs/heads/develop | Classes/Events/EventsPayloads/PKAdInfo.swift | agpl-3.0 | 1 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
/// The position type of the ad according to the content timeline.
@objc public enum AdPositionType: Int, CustomStringConvertible {
case preRoll
case midRoll
case postRoll
public var description: String {
switch self {
case .preRoll: return "preRoll"
case .midRoll: return "midRoll"
case .postRoll: return "postRoll"
}
}
}
/// `PKAdInfo` represents ad information.
@objc public class PKAdInfo: NSObject {
@objc public var duration: TimeInterval
@objc public var title: String
/// The position of the pod in the content in seconds. Pre-roll returns 0,
/// post-roll returns -1 and mid-rolls return the scheduled time of the pod.
@objc public var timeOffset: TimeInterval
@objc public var adDescription: String
@objc public var isSkippable: Bool
@objc public var contentType: String
@objc public var adId: String
/// The source ad server information included in the ad response.
@objc public var adSystem: String
@objc public var height: Int
@objc public var width: Int
/// Total number of ads in the pod this ad belongs to. Will be 1 for standalone ads.
@objc public var totalAds: Int
/// The position of this ad within an ad pod. Will be 1 for standalone ads.
@objc public var adPosition: Int
@objc public var isBumper: Bool
// The index of the pod, where pre-roll pod is 0, mid-roll pods are 1 .. N
// and the post-roll is -1.
@objc public var podIndex: Int
// The bitrate of the selected creative.
@objc public var mediaBitrate: Int
// The CreativeId for the ad.
@objc public var creativeId: String
// The Advertiser Name for the ad.
@objc public var advertiserName: String
@objc public var adPlayHead: TimeInterval
@objc public var skipTimeOffset: TimeInterval
@objc public var creativeAdId: String?
@objc public var dealId: String?
@objc public var surveyUrl: String?
@objc public var traffickingParams: String?
@objc public var adIndexInPod: Int
@objc public var podCount: Int
@objc public var adPodTimeOffset: TimeInterval
/// returns the position type of the ad (pre, mid, post)
@objc public var positionType: AdPositionType {
if timeOffset > 0 {
return .midRoll
} else if timeOffset < 0 {
return .postRoll
} else {
return .preRoll
}
}
@objc public init(adDescription: String,
adDuration: TimeInterval,
title: String,
isSkippable: Bool,
contentType: String,
adId: String,
adSystem: String,
height: Int,
width: Int,
totalAds: Int,
adPosition: Int,
timeOffset: TimeInterval,
isBumper: Bool,
podIndex: Int,
mediaBitrate: Int,
creativeId: String,
advertiserName: String,
adPlayHead: TimeInterval,
skipTimeOffset: TimeInterval,
creativeAdId: String?,
dealId: String?,
surveyUrl: String?,
traffickingParams: String?,
adIndexInPod: Int,
podCount: Int,
adPodTimeOffset: TimeInterval) {
self.adDescription = adDescription
self.duration = adDuration
self.title = title
self.isSkippable = isSkippable
self.contentType = contentType
self.adId = adId
self.adSystem = adSystem
self.height = height
self.width = width
self.totalAds = totalAds
self.adPosition = adPosition
self.timeOffset = timeOffset
self.isBumper = isBumper
self.podIndex = podIndex
self.mediaBitrate = mediaBitrate
self.creativeId = creativeId
self.advertiserName = advertiserName
self.adPlayHead = adPlayHead
self.skipTimeOffset = skipTimeOffset
self.creativeAdId = creativeAdId
self.dealId = dealId
self.surveyUrl = surveyUrl
self.traffickingParams = traffickingParams
self.adIndexInPod = adIndexInPod
self.podCount = podCount
self.adPodTimeOffset = adPodTimeOffset
}
public override var description: String {
let info = "adDescription: \(adDescription)\n" +
"duration: \(duration)\n" +
"title: \(title)\n" +
"isSkippable: \(isSkippable)\n" +
"contentType: \(contentType)\n" +
"adId: \(adId)\n" +
"adSystem: \(adSystem)\n" +
"height: \(height)\n" +
"width: \(width)\n" +
"totalAds: \(totalAds)\n" +
"adPosition: \(adPosition)\n" +
"timeOffset: \(timeOffset)\n" +
"isBumper: \(isBumper)\n" +
"podIndex: \(podIndex)\n" +
"mediaBitrate: \(mediaBitrate)\n" +
"positionType: \(positionType)\n" +
"creativeId: \(creativeId)\n" +
"advertiserName: \(advertiserName)\n" +
"adPlayHead: \(adPlayHead)\n" +
"skipTimeOffset: \(skipTimeOffset)\n" +
"creativeAdId: \(creativeAdId ?? "")\n" +
"dealId: \(dealId ?? "")\n" +
"surveyUrl: \(surveyUrl ?? "")\n" +
"traffickingParams: \(traffickingParams ?? "")\n" +
"adIndexInPod: \(adIndexInPod)\n" +
"podCount: \(podCount)\n" +
"adPodTimeOffset: \(adPodTimeOffset)\n"
return info
}
}
| cda8285924ea08e2f9fa2adf785abe5d | 34.4 | 102 | 0.581921 | false | false | false | false |
lojals/DoorsConcept | refs/heads/master | DoorConcept/Controllers/Buildings/BuildingsInteractor.swift | mit | 1 | //
// BuildingsInteractor.swift
// DoorConcept
//
// Created by Jorge Raul Ovalle Zuleta on 3/21/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
import CoreData
typealias FetchCompletionHandler = ((data:[AnyObject]?,error:String?)->Void)?
class BuildingsInteractor {
private let managedObjectContext:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
init(){}
/**
Retrieve all the buildings created. TODO: Retrieve just the permited by the current user.
- parameter completion: completion description (data = [Building], error = error description)
*/
func getBuildings(completion:FetchCompletionHandler){
let fetchRequest = NSFetchRequest(entityName: "Building")
do{
let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult
let fetchBuilding = fetchResults.finalResult as! [Building]
completion!(data:fetchBuilding, error: nil)
}catch{
completion!(data:nil,error: "CoreData error!")
}
}
/**
Add a new Building
- parameter user: user adding the Building
- parameter name: Building name
- parameter avatar: Avatar image name index (0-4) (building_[index].png)
*/
func saveBuilding(user:User, name:String, avatar:String){
let build1 = NSEntityDescription.insertNewObjectForEntityForName("Building", inManagedObjectContext: managedObjectContext) as! Building
build1.owner = user
build1.buildingName = name
build1.buildingAvatar = avatar
build1.buildingCreatedAt = NSDate()
do{
try managedObjectContext.save()
}catch{
print("Some error inserting Building")
}
}
/**
Delete building from the db
- parameter building: valid building
*/
func deleteBuilding(building:Building){
if UserService.sharedInstance.currentUser! == building.owner!{
managedObjectContext.deleteObject(building)
do{
try managedObjectContext.save()
}catch{
print("Some error deleting Door")
}
}else{
//Not yet implemented un UI
print("That's not your building")
}
}
}
| 0f9fd349f3c1b7a8bf245f8e3dcccbc4 | 32.081081 | 157 | 0.63031 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | RiotSwiftUI/Modules/Common/Util/ClearViewModifier.swift | apache-2.0 | 1 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
@available(iOS 14.0, *)
extension ThemableTextField {
func showClearButton(text: Binding<String>, alignement: VerticalAlignment = .center) -> some View {
return modifier(ClearViewModifier(alignment: alignement, text: text))
}
}
@available(iOS 14.0, *)
extension ThemableTextEditor {
func showClearButton(text: Binding<String>, alignement: VerticalAlignment = .top) -> some View {
return modifier(ClearViewModifier(alignment: alignement, text: text))
}
}
/// `ClearViewModifier` aims to add a clear button (e.g. `x` button) on the right side of any text editing view
@available(iOS 14.0, *)
struct ClearViewModifier: ViewModifier
{
// MARK: - Properties
let alignment: VerticalAlignment
// MARK: - Bindings
@Binding var text: String
// MARK: - Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: - Public
public func body(content: Content) -> some View
{
HStack(alignment: alignment) {
content
if !text.isEmpty {
Button(action: {
self.text = ""
}) {
Image(systemName: "xmark.circle.fill")
.renderingMode(.template)
.foregroundColor(theme.colors.quarterlyContent)
}
.padding(EdgeInsets(top: alignment == .top ? 8 : 0, leading: 0, bottom: alignment == .bottom ? 8 : 0, trailing: 8))
}
}
}
}
| 0a1a481ea6be59cc7eec3f42b0364642 | 30.746269 | 131 | 0.630465 | false | false | false | false |
CoderLiLe/Swift | refs/heads/master | 扩展/main.swift | mit | 1 | //
// main.swift
// 扩展
//
// Created by LiLe on 2017/9/28.
// Copyright © 2017年 itcast. All rights reserved.
//
import Foundation
/*
扩展: 就是给一个现存类, 结构体, 枚举或者协议添加新的属性或着方法的语法, 无需目标源码, 就可以把想要的代码加到目标上面
但有一些限制条件需要说明:
1.不能添加一个已经存在的方法或者属性;
2.添加的属性不能是存储属性, 只能是计算属性;
格式:
extension 某个先有类型 {
// 增加新的功能
}
*/
// 1.扩展计算属性
class Transport {
var scope: String
init(scope: String) {
self.scope = scope
}
}
extension Transport {
var extProperty: String {
get {
return scope
}
}
}
var myTran = Transport(scope: "✈️")
print(myTran.extProperty)
// 2.扩展构造器
class ChinaTransport {
var price = 30
var scope: String
init(scope: String) {
self.scope = scope
}
}
extension ChinaTransport {
convenience init(price: Int, scope: String) {
self.init(scope: scope)
self.price = price
}
}
var myTran1 = ChinaTransport(scope: "歼9")
var myTran2 = ChinaTransport(price: 5000000, scope: "歼10")
// 3.扩展方法
// 扩展整数类型
extension Int {
func calculateDouble() -> Int {
return self * 2
}
}
var i = 3
print(i.calculateDouble())
// 扩展下标
// 我们还可以通过扩展下标的方法来增强类的功能,比如扩展整数类型,使整数类型可以通过下标返回整数的倍数
extension Int {
subscript(num: Int) -> Int {
return self * num;
}
}
print(10[3])
| e70f25e21978303d88da0b89a7d15627 | 15.481013 | 64 | 0.613671 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK | refs/heads/master | Evrythng-iOS/Credentials.swift | apache-2.0 | 1 | //
// Credentials.swift
// EvrythngiOS
//
// Created by JD Castro on 26/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
import Moya_SwiftyJSONMapper
import SwiftyJSON
public final class Credentials: ALSwiftyJSONAble {
public var jsonData: JSON?
public var evrythngUser: String?
public var evrythngApiKey: String?
public var activationCode: String?
public var email: String?
public var password: String?
public var status: CredentialStatus?
public init?(jsonData: JSON) {
self.jsonData = jsonData
self.evrythngUser = jsonData["evrythngUser"].string
self.evrythngApiKey = jsonData["evrythngApiKey"].string
self.activationCode = jsonData["activationCode"].string
self.email = jsonData["email"].string
self.password = jsonData["password"].string
self.status = CredentialStatus(rawValue: jsonData["status"].stringValue)
}
public init(email: String, password: String) {
self.email = email
self.password = password
}
}
public enum CredentialStatus: String{
case Active = "active"
case Inactive = "inactive"
case Anonymous = "anonymous"
}
| f50601cc7aa0a7eab4ed6837088f1d0d | 26.044444 | 80 | 0.675431 | false | false | false | false |
swift8/anim-app | refs/heads/master | KLAnimDemo/KLAnimDemo/Classes/Extension/StringExtension.swift | apache-2.0 | 1 | //
// StringUtils.swift
// KLAnimDemo 字符串工具类
//
// Created by 浩 胡 on 15/6/22.
// Copyright (c) 2015年 siyan. All rights reserved.
//
import Foundation
extension String {
// 分割字符
func split(s:String)->[String] {
if s.isEmpty {
var x = [String]()
for y in self {
x.append(String(y))
}
return x
}
return self.componentsSeparatedByString(s)
}
// 去掉左右空格
func trim()->String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
// 是否包含字符串
func has(s:String)->Bool {
if (self.rangeOfString(s) != nil) {
return true
} else {
return false
}
}
// 重复字符串
func repeat(times: Int) -> String{
var result = ""
for i in 0...times {
result += self
}
return result
}
// 反转
func reverse()-> String {
var s = self.split("").reverse()
var x = ""
for y in s{
x += y
}
return x
}
} | 2807e186ec575814075e72e3b7cc4121 | 17.45 | 92 | 0.482821 | false | false | false | false |
weikz/Mr-Ride-iOS | refs/heads/master | Mr-Ride-iOS/HistoryViewController.swift | mit | 1 | //
// HistoryViewController.swift
// Mr-Ride-iOS
//
// Created by 張瑋康 on 2016/6/8.
// Copyright © 2016年 Appworks School Weikz. All rights reserved.
//
import UIKit
import CoreData
import Charts
class HistoryViewController: UIViewController {
@IBOutlet weak var lineChartView: LineChartView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var sideMenuButton: UIBarButtonItem!
private let runDataModel = RunDataModel()
private var runDataStructArray: [RunDataModel.runDataStruct] = []
private var runDataSortedByTime: [String: [RunDataModel.runDataStruct]] = [:]
private var headers: [String] = []
enum CellStatus {
case recordCell
case gap
}
var cellStatus: CellStatus = .gap
}
// MARK: - View LifeCycle
extension HistoryViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupSideMenu()
setupBackground()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
clearData()
prepareTableViewData()
setupChart()
}
}
// MARK: - Setup
extension HistoryViewController {
func setupBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.MRLightblueColor().CGColor, UIColor.pineGreen50Color().CGColor]
gradientLayer.locations = [0.5, 1]
gradientLayer.frame = view.frame
self.view.layer.insertSublayer(gradientLayer, atIndex: 1)
}
func setupSideMenu() {
if self.revealViewController() != nil {
sideMenuButton.target = self.revealViewController()
sideMenuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
}
// MARK: - TableViewDataSource and Delegate
extension HistoryViewController: UITableViewDelegate, UITableViewDataSource {
private func setupTableView() {
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = .clearColor()
let cellNib = UINib(nibName: "RunDataTableViewCell", bundle: nil)
tableView.registerNib(cellNib, forCellReuseIdentifier: "RunDataTableViewCell")
let gapCellNib = UINib(nibName: "RunDataTableViewGapCell", bundle: nil)
tableView.registerNib(gapCellNib, forCellReuseIdentifier: "RunDataTableViewGapCell")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
for header in headers {
// first and last return gap cell
if indexPath.row == 0 || indexPath.row == runDataSortedByTime[header]!.count + 1 {
cellStatus = .gap
let cell = tableView.dequeueReusableCellWithIdentifier("RunDataTableViewGapCell", forIndexPath: indexPath) as! RunDataTableViewGapCell
return cell
} else {
cellStatus = .recordCell
let cell = tableView.dequeueReusableCellWithIdentifier("RunDataTableViewCell", forIndexPath: indexPath) as! RunDataTableViewCell
cell.runDataStruct = runDataSortedByTime[header]![indexPath.row - 1]
cell.setup()
return cell
}
}
return UITableViewCell()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// the number of sections
return headers.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// the number of rows
return runDataSortedByTime[headers[section]]!.count + 2
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// the height
if cellStatus == .recordCell {
return 59
} else if cellStatus == .gap {
return 10
} else {
print("Something Wrong in HistoryView Cell's Height")
return 59
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 24
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let statisticViewController = self.storyboard?.instantiateViewControllerWithIdentifier("StatisticViewController") as! StatisticViewController
for header in headers {
statisticViewController.runDataStruct = runDataSortedByTime[header]![indexPath.row - 1]
}
navigationController?.pushViewController(statisticViewController, animated: true)
}
}
// MARK: - Data
extension HistoryViewController {
private func prepareTableViewData() {
runDataStructArray = runDataModel.getData()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM, YYYY"
for runDataStruct in runDataStructArray {
let header = dateFormatter.stringFromDate(runDataStruct.date!)
if runDataSortedByTime.keys.contains(header) {
runDataSortedByTime[header]?.append(runDataStruct)
} else {
runDataSortedByTime[header] = []
runDataSortedByTime[header]?.append(runDataStruct)
}
if !headers.contains(header) {
headers.append(header)
}
}
dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() }
}
private func clearData() {
runDataStructArray = []
runDataSortedByTime = [:]
headers = []
}
}
// MARK: - Chart
extension HistoryViewController {
private func setupChart() {
var distanceArray: [Double] = []
var dateArray: [String] = []
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd"
for runDataStruct in runDataStructArray {
distanceArray.append(runDataStruct.distance!)
dateArray.append(dateFormatter.stringFromDate(runDataStruct.date!))
}
var dataEntries:[ChartDataEntry] = []
for i in 0..<distanceArray.count {
let dataEntry = ChartDataEntry(value: distanceArray[i], xIndex: i)
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "")
lineChartDataSet.fillColor = UIColor.blueColor()
lineChartDataSet.drawFilledEnabled = true
lineChartDataSet.drawCirclesEnabled = false
lineChartDataSet.drawValuesEnabled = false
lineChartDataSet.drawCubicEnabled = true
lineChartDataSet.lineWidth = 0.0
//Gradient Fill
let gradientColors = [UIColor.MRLightblueColor().CGColor, UIColor.MRTurquoiseBlue().CGColor]
let colorLocations:[CGFloat] = [0.0, 0.05]
let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradientColors, colorLocations)
lineChartDataSet.fill = ChartFill.fillWithLinearGradient(gradient!, angle: 90.0)
lineChartDataSet.drawFilledEnabled = true
let lineChartData = LineChartData(xVals: dateArray, dataSet: lineChartDataSet)
lineChartView.data = lineChartData
lineChartData.setDrawValues(false)
lineChartView.backgroundColor = UIColor.clearColor()
lineChartView.drawGridBackgroundEnabled = false
lineChartView.rightAxis.labelTextColor = .clearColor()
lineChartView.rightAxis.gridColor = .whiteColor()
lineChartView.leftAxis.enabled = false
lineChartView.xAxis.gridColor = .clearColor()
lineChartView.xAxis.labelTextColor = .whiteColor()
lineChartView.xAxis.labelPosition = .Bottom
lineChartView.xAxis.axisLineColor = .whiteColor()
lineChartView.legend.enabled = false
lineChartView.descriptionText = ""
lineChartView.userInteractionEnabled = false
lineChartView.leftAxis.drawAxisLineEnabled = false
lineChartView.rightAxis.drawAxisLineEnabled = false
lineChartView.leftAxis.drawLabelsEnabled = false
lineChartView.rightAxis.drawLabelsEnabled = false
lineChartView.rightAxis.drawGridLinesEnabled = false
lineChartView.leftAxis.gridColor = UIColor.whiteColor()
}
}
| a68f19ea1e3bf2232c570dcedbdd72a7 | 32.522901 | 150 | 0.644313 | false | false | false | false |
dzt/MobilePassport | refs/heads/master | ios/ios/ImageLoader/Diskcached.swift | mit | 1 | //
// Diskcached.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 12/21/14.
// Copyright © 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
extension String {
func escape() -> String {
let str = CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
self,
nil,
"!*'\"();:@&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return str as String
}
}
public class Diskcached {
var storedData = [NSURL: NSData]()
class Directory {
init() {
createDirectory()
}
private func createDirectory() {
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(path) {
return
}
do {
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
var path: String {
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
let directoryName = "swift.imageloader.diskcached"
return cacheDirectory + "/" + directoryName
}
}
let directory = Directory()
private let _subscriptQueue = dispatch_queue_create("swift.imageloader.queues.diskcached.subscript", DISPATCH_QUEUE_CONCURRENT)
private let _ioQueue = dispatch_queue_create("swift.imageloader.queues.diskcached.set", DISPATCH_QUEUE_SERIAL)
}
extension Diskcached {
public class func removeAllObjects() {
Diskcached().removeAllObjects()
}
func removeAllObjects() {
let manager = NSFileManager.defaultManager()
for subpath in manager.subpathsAtPath(directory.path) ?? [] {
let path = directory.path + "/" + subpath
do {
try manager.removeItemAtPath(path)
} catch _ {
}
}
}
private func objectForKey(aKey: NSURL) -> NSData? {
if let data = storedData[aKey] {
return data
}
return NSData(contentsOfFile: _path(aKey.absoluteString))
}
private func _path(name: String) -> String {
return directory.path + "/" + name.escape()
}
private func setObject(anObject: NSData, forKey aKey: NSURL) {
storedData[aKey] = anObject
let block: () -> Void = {
anObject.writeToFile(self._path(aKey.absoluteString), atomically: false)
self.storedData[aKey] = nil
}
dispatch_async(_ioQueue, block)
}
}
// MARK: ImageLoaderCacheProtocol
extension Diskcached: ImageLoaderCache {
public subscript (aKey: NSURL) -> NSData? {
get {
var data : NSData?
dispatch_sync(_subscriptQueue) {
data = self.objectForKey(aKey)
}
return data
}
set {
dispatch_barrier_async(_subscriptQueue) {
self.setObject(newValue!, forKey: aKey)
}
}
}
}
| 6c6c3537e843e995bdb2436c2697c3f3 | 24.958678 | 131 | 0.581344 | false | false | false | false |
WangCrystal/actor-platform | refs/heads/master | actor-apps/app-ios/ActorCore/Config.swift | mit | 1 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class Config {
var endpoints = [String]()
var mixpanel: String? = nil
var hockeyapp: String? = nil
var mint: String? = nil
var enableCommunity: Bool = false
var pushId: Int? = nil
init() {
let path = NSBundle.mainBundle().pathForResource("app", ofType: "json")
let text: String
let parsedObject: AnyObject?
do {
text = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
parsedObject = try NSJSONSerialization.JSONObjectWithData(text.asNS.dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSJSONReadingOptions.AllowFragments)
} catch _ {
fatalError("Unable to load config")
}
if let configData = parsedObject as? NSDictionary {
if let endpoints = configData["endpoints"] as? NSArray {
for endpoint in endpoints {
self.endpoints.append(endpoint as! String)
}
}
if let mixpanel = configData["mixpanel"] as? String {
self.mixpanel = mixpanel
}
if let hockeyapp = configData["hockeyapp"] as? String {
self.hockeyapp = hockeyapp
}
if let mint = configData["mint"] as? String {
self.mint = mint
}
if let enableCommunity = configData["community"] as? Bool {
self.enableCommunity = enableCommunity
}
if let pushId = configData["push_id"] as? Int {
self.pushId = pushId
}
}
}
} | cc979ec2ffc9e9bdcb80ac8bfd622690 | 32.392157 | 121 | 0.552291 | false | true | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/Model/LinearEquations/Landing/MLinearEquations.swift | mit | 1 | import Foundation
class MLinearEquations
{
private(set) var items:[MLinearEquationsItem]
private weak var controller:CLinearEquations?
init(controller:CLinearEquations)
{
self.controller = controller
items = []
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.loadFromDb()
}
}
//MARK: private
private func loadFromDb()
{
DManager.sharedInstance?.fetchData(
entityName:DProject.entityName)
{ [weak self] (fetched) in
if let fetched:[DProject] = fetched as? [DProject]
{
var items:[MLinearEquationsItem] = []
for project:DProject in fetched
{
let item:MLinearEquationsItem = MLinearEquationsItem(
project:project)
items.append(item)
}
self?.items = items
self?.sortItems()
}
else
{
self?.items = []
}
self?.finishLoading()
}
}
private func sortItems()
{
items.sort
{ (itemA:MLinearEquationsItem, itemB:MLinearEquationsItem) -> Bool in
let before:Bool = itemA.project.created > itemB.project.created
return before
}
}
private func finishLoading()
{
DispatchQueue.main.async
{ [weak self] in
self?.controller?.modelLoaded()
}
}
}
| 6763be1cb8c11a10e7bfc488a9e230a7 | 23.328571 | 77 | 0.479154 | false | false | false | false |
saitjr/STLoadingGroup | refs/heads/master | demo/STLoadingGroup/classes/Loading/STSubmitLoading.swift | mit | 1 | //
// STCycleLoadView.swift
// STCycleLoadView-SubmitButton
//
// Created by TangJR on 1/4/16.
// Copyright © 2016. All rights reserved.
//
/*
The MIT License (MIT)
Copyright (c) 2016 saitjr
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 STSubmitLoading: UIView {
fileprivate let cycleLayer: CAShapeLayer = CAShapeLayer()
internal var isLoading: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
override func didMoveToWindow() {
super.didMoveToWindow()
updateUI()
}
}
extension STSubmitLoading {
fileprivate func setupUI() {
cycleLayer.lineCap = kCALineCapRound
cycleLayer.lineJoin = kCALineJoinRound
cycleLayer.lineWidth = lineWidth
cycleLayer.fillColor = UIColor.clear.cgColor
cycleLayer.strokeColor = loadingTintColor.cgColor
cycleLayer.strokeEnd = 0
layer.addSublayer(cycleLayer)
}
fileprivate func updateUI() {
cycleLayer.bounds = bounds
cycleLayer.position = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
cycleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
}
}
extension STSubmitLoading: STLoadingConfig {
var animationDuration: TimeInterval {
return 1
}
var lineWidth: CGFloat {
return 4
}
var loadingTintColor: UIColor {
return .white
}
}
extension STSubmitLoading: STLoadingable {
internal func startLoading() {
guard !isLoading else {
return
}
isLoading = true
self.alpha = 1
let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimation.fromValue = 0
strokeEndAnimation.toValue = 0.25
strokeEndAnimation.fillMode = kCAFillModeForwards
strokeEndAnimation.isRemovedOnCompletion = false
strokeEndAnimation.duration = animationDuration / 4.0
cycleLayer.add(strokeEndAnimation, forKey: "strokeEndAnimation")
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0
rotateAnimation.toValue = M_PI * 2
rotateAnimation.duration = animationDuration
rotateAnimation.beginTime = CACurrentMediaTime() + strokeEndAnimation.duration
rotateAnimation.repeatCount = Float.infinity
cycleLayer.add(rotateAnimation, forKey: "rotateAnimation")
}
internal func stopLoading(finish: STEmptyCallback? = nil) {
guard isLoading else {
return
}
let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimation.toValue = 1
strokeEndAnimation.fillMode = kCAFillModeForwards
strokeEndAnimation.isRemovedOnCompletion = false
strokeEndAnimation.duration = animationDuration * 3.0 / 4.0
cycleLayer.add(strokeEndAnimation, forKey: "catchStrokeEndAnimation")
UIView.animate(withDuration: 0.3, delay: strokeEndAnimation.duration, options: UIViewAnimationOptions(), animations: { () -> Void in
self.alpha = 0
}, completion: { _ in
self.cycleLayer.removeAllAnimations()
self.isLoading = false
finish?()
})
}
}
| 1a45e51551ea777c99739ef1597635c5 | 31.892857 | 140 | 0.670793 | false | false | false | false |
jdspoone/Recipinator | refs/heads/master | RecipeBook/AppDelegate.swift | mit | 1 | /*
Written by Jeff Spooner
*/
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
// Instantiate the main window
window = UIWindow(frame: UIScreen.main.bounds)
// Create a CoreDataController and get the managed object context
let coreDataController = CoreDataController()
let managedObjectContext = coreDataController.getManagedObjectContext()
// Embed the recipe table view controller in a navigation view controller, and set that as the root view controller
let navigationViewController = UINavigationController(rootViewController: SearchViewController(context: managedObjectContext))
navigationViewController.navigationBar.isTranslucent = false
self.window!.rootViewController = navigationViewController
// Make the window key and visible
window!.makeKeyAndVisible()
return true
}
}
| 884b8ccf52e72fda4060cd73e8f3accd | 28.947368 | 142 | 0.733743 | false | false | false | false |
terietor/GTForms | refs/heads/master | Source/Forms/FormSegmentedPicker.swift | mit | 1 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
import GTSegmentedControl
private class SegmentedControlLabelView<L: UILabel>: ControlLabelView<L> {
let segmentedControl = SegmentedControl()
override init() {
super.init()
self.control = self.segmentedControl
configureView() { (label, control) in
label.snp.makeConstraints() { make in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(0.4)
make.top.equalTo(self)
make.bottom.equalTo(self)
} // end label
control.snp.makeConstraints() { make in
make.centerY.equalTo(label.snp.centerY).priority(UILayoutPriorityDefaultLow)
make.right.equalTo(self)
make.left.equalTo(label.snp.right).offset(10)
make.height.lessThanOrEqualTo(self)
} // end control
} // end configureView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class FormSegmentedPicker: BaseResultForm<String> {
private let segmentedControlView = SegmentedControlLabelView()
public var segmentedControl: SegmentedControl {
return self.segmentedControlView.segmentedControl
}
public init(text: String, items: [String], itemsPerRow: Int = 3) {
super.init()
self.text = text
self.segmentedControlView.segmentedControl.items = items
self.segmentedControlView.segmentedControl.itemsPerRow = itemsPerRow
self.segmentedControlView.controlLabel.text = self.text
self.segmentedControlView.segmentedControl.valueDidChange = { result in
self.updateResult(result)
}
}
public override func formView() -> UIView {
return self.segmentedControlView
}
}
| 3c4a4df98df28aafc5ec27bd2add8a1c | 34.681818 | 92 | 0.666561 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/nested_types_referencing_nested_functions.swift | apache-2.0 | 1 |
// RUN: %target-swift-frontend -module-name nested_types_referencing_nested_functions -emit-silgen -enable-sil-ownership %s | %FileCheck %s
do {
func foo() { bar(2) }
func bar<T>(_: T) { foo() }
class Foo {
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo {
init() {
foo()
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> ()
func zim() {
foo()
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C4zangyyxlF : $@convention(method) <T> (@in_guaranteed T, @guaranteed Foo) -> ()
func zang<T>(_ x: T) {
bar(x)
}
// CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> ()
deinit {
foo()
}
}
let x = Foo()
x.zim()
x.zang(1)
_ = Foo.zim
_ = Foo.zang as (Foo) -> (Int) -> ()
_ = x.zim
_ = x.zang as (Int) -> ()
}
| 7eb8d88dd90bbb5ff519a21e6f5cb545 | 30.411765 | 162 | 0.60206 | false | false | false | false |
frootloops/swift | refs/heads/master | stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift | apache-2.0 | 1 | //===--- SwiftReflectionTest.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides infrastructure for introspecting type information in a
// remote swift executable by swift-reflection-test, using pipes and a
// request-response protocol to communicate with the test tool.
//
//===----------------------------------------------------------------------===//
// FIXME: Make this work with Linux
import MachO
import Darwin
let RequestInstanceKind = "k"
let RequestInstanceAddress = "i"
let RequestReflectionInfos = "r"
let RequestReadBytes = "b"
let RequestSymbolAddress = "s"
let RequestStringLength = "l"
let RequestDone = "d"
let RequestPointerSize = "p"
internal func debugLog(_ message: String) {
#if DEBUG_LOG
fputs("Child: \(message)\n", stderr)
fflush(stderr)
#endif
}
public enum InstanceKind : UInt8 {
case None
case Object
case Existential
case ErrorExistential
case Closure
}
/// Represents a section in a loaded image in this process.
internal struct Section {
/// The absolute start address of the section's data in this address space.
let startAddress: UnsafeRawPointer
/// The size of the section in bytes.
let size: UInt
}
/// Holds the addresses and sizes of sections related to reflection
internal struct ReflectionInfo : Sequence {
/// The name of the loaded image
internal let imageName: String
/// Reflection metadata sections
internal let fieldmd: Section?
internal let assocty: Section?
internal let builtin: Section?
internal let capture: Section?
internal let typeref: Section?
internal let reflstr: Section?
internal func makeIterator() -> AnyIterator<Section?> {
return AnyIterator([
fieldmd,
assocty,
builtin,
capture,
typeref,
reflstr
].makeIterator())
}
}
#if arch(x86_64) || arch(arm64)
typealias MachHeader = mach_header_64
#else
typealias MachHeader = mach_header
#endif
/// Get the location and size of a section in a binary.
///
/// - Parameter name: The name of the section
/// - Parameter imageHeader: A pointer to the Mach header describing the
/// image.
/// - Returns: A `Section` containing the address and size, or `nil` if there
/// is no section by the given name.
internal func getSectionInfo(_ name: String,
_ imageHeader: UnsafePointer<MachHeader>) -> Section? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var size: UInt = 0
let address = getsectiondata(imageHeader, "__TEXT", name, &size)
guard let nonNullAddress = address else { return nil }
guard size != 0 else { return nil }
return Section(startAddress: nonNullAddress, size: size)
}
/// Get the Swift Reflection section locations for a loaded image.
///
/// An image of interest must have the following sections in the __DATA
/// segment:
/// - __swift3_fieldmd
/// - __swift3_assocty
/// - __swift3_builtin
/// - __swift3_capture
/// - __swift3_typeref
/// - __swift3_reflstr (optional, may have been stripped out)
///
/// - Parameter i: The index of the loaded image as reported by Dyld.
/// - Returns: A `ReflectionInfo` containing the locations of all of the
/// needed sections, or `nil` if the image doesn't contain all of them.
internal func getReflectionInfoForImage(atIndex i: UInt32) -> ReflectionInfo? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let header = unsafeBitCast(_dyld_get_image_header(i),
to: UnsafePointer<MachHeader>.self)
let imageName = _dyld_get_image_name(i)!
let fieldmd = getSectionInfo("__swift3_fieldmd", header)
let assocty = getSectionInfo("__swift3_assocty", header)
let builtin = getSectionInfo("__swift3_builtin", header)
let capture = getSectionInfo("__swift3_capture", header)
let typeref = getSectionInfo("__swift3_typeref", header)
let reflstr = getSectionInfo("__swift3_reflstr", header)
return ReflectionInfo(imageName: String(validatingUTF8: imageName)!,
fieldmd: fieldmd,
assocty: assocty,
builtin: builtin,
capture: capture,
typeref: typeref,
reflstr: reflstr)
}
internal func sendBytes<T>(from address: UnsafePointer<T>, count: Int) {
var source = address
var bytesLeft = count
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
while bytesLeft > 0 {
let bytesWritten = fwrite(source, 1, bytesLeft, stdout)
fflush(stdout)
guard bytesWritten > 0 else {
fatalError("Couldn't write to parent pipe")
}
bytesLeft -= bytesWritten
source = source.advanced(by: bytesWritten)
}
}
/// Send the address of an object to the parent.
internal func sendAddress(of instance: AnyObject) {
debugLog("BEGIN \(#function)")
defer { debugLog("END \(#function)") }
var address = Unmanaged.passUnretained(instance).toOpaque()
sendBytes(from: &address, count: MemoryLayout<UInt>.size)
}
/// Send the `value`'s bits to the parent.
internal func sendValue<T>(_ value: T) {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value = value
sendBytes(from: &value, count: MemoryLayout<T>.size)
}
/// Read a word-sized unsigned integer from the parent.
internal func readUInt() -> UInt {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value: UInt = 0
fread(&value, MemoryLayout<UInt>.size, 1, stdin)
return value
}
/// Send all known `ReflectionInfo`s for all images loaded in the current
/// process.
internal func sendReflectionInfos() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let infos = (0..<_dyld_image_count()).flatMap(getReflectionInfoForImage)
var numInfos = infos.count
debugLog("\(numInfos) reflection info bundles.")
precondition(numInfos >= 1)
sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size)
for info in infos {
debugLog("Sending info for \(info.imageName)")
for section in info {
sendValue(section?.startAddress)
sendValue(section?.size ?? 0)
}
}
}
internal func printErrnoAndExit() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let errorCString = strerror(errno)!
let message = String(validatingUTF8: errorCString)! + "\n"
let bytes = Array(message.utf8)
fwrite(bytes, 1, bytes.count, stderr)
fflush(stderr)
exit(EXIT_FAILURE)
}
/// Retrieve the address and count from the parent and send the bytes back.
internal func sendBytes() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let count = Int(readUInt())
debugLog("Parent requested \(count) bytes from \(address)")
var totalBytesWritten = 0
var pointer = UnsafeMutableRawPointer(bitPattern: address)
while totalBytesWritten < count {
let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout))
fflush(stdout)
if bytesWritten == 0 {
printErrnoAndExit()
}
totalBytesWritten += bytesWritten
pointer = pointer?.advanced(by: bytesWritten)
}
}
/// Send the address of a symbol loaded in this process.
internal func sendSymbolAddress() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let name = readLine()!
name.withCString {
let handle = UnsafeMutableRawPointer(bitPattern: Int(-2))!
let symbol = dlsym(handle, $0)
let symbolAddress = unsafeBitCast(symbol, to: UInt.self)
sendValue(symbolAddress)
}
}
/// Send the length of a string to the parent.
internal func sendStringLength() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let cString = UnsafePointer<CChar>(bitPattern: address)!
let count = String(validatingUTF8: cString)!.utf8.count
sendValue(count)
}
/// Send the size of this architecture's pointer type.
internal func sendPointerSize() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size)
sendValue(pointerSize)
}
/// Hold an `instance` and wait for the parent to query for information.
///
/// This is the main "run loop" of the test harness.
///
/// The parent will necessarily need to:
/// - Get the addresses of all of the reflection sections for any swift dylibs
/// that are loaded, where applicable.
/// - Get the address of the `instance`
/// - Get the pointer size of this process, which affects assumptions about the
/// the layout of runtime structures with pointer-sized fields.
/// - Read raw bytes out of this process's address space.
///
/// The parent sends a Done message to indicate that it's done
/// looking at this instance. It will continue to ask for instances,
/// so call doneReflecting() when you don't have any more instances.
internal func reflect(instanceAddress: UInt, kind: InstanceKind) {
while let command = readLine(strippingNewline: true) {
switch command {
case String(validatingUTF8: RequestInstanceKind)!:
sendValue(kind.rawValue)
case String(validatingUTF8: RequestInstanceAddress)!:
sendValue(instanceAddress)
case String(validatingUTF8: RequestReflectionInfos)!:
sendReflectionInfos()
case String(validatingUTF8: RequestReadBytes)!:
sendBytes()
case String(validatingUTF8: RequestSymbolAddress)!:
sendSymbolAddress()
case String(validatingUTF8: RequestStringLength)!:
sendStringLength()
case String(validatingUTF8: RequestPointerSize)!:
sendPointerSize()
case String(validatingUTF8: RequestDone)!:
return
default:
fatalError("Unknown request received: '\(Array(command.utf8))'!")
}
}
}
/// Reflect a class instance.
///
/// This reflects the stored properties of the immediate class.
/// The superclass is not (yet?) visited.
public func reflect(object: AnyObject) {
defer { _fixLifetime(object) }
let address = Unmanaged.passUnretained(object).toOpaque()
let addressValue = UInt(bitPattern: address)
reflect(instanceAddress: addressValue, kind: .Object)
}
/// Reflect any type at all by boxing it into an existential container (an `Any`)
///
/// Given a class, this will reflect the reference value, and not the contents
/// of the instance. Use `reflect(object:)` for that.
///
/// This function serves to exercise the projectExistential function of the
/// SwiftRemoteMirror API.
///
/// It tests the three conditions of existential layout:
///
/// ## Class existentials
///
/// For example, a `MyClass as Any`:
/// ```
/// [Pointer to class instance]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type fits in the 3-word buffer
///
/// For example, a `(1, 2) as Any`:
/// ```
/// [Tuple element 1: Int]
/// [Tuple element 2: Int]
/// [-Empty_]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type has to be allocated into a
/// heap buffer.
///
/// For example, a `LargeStruct<T> as Any`:
/// ```
/// [Pointer to unmanaged heap container] --> [Large struct]
/// [-Empty-]
/// [-Empty-]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// The test doesn't care about the witness tables - we only care
/// about what's in the buffer, so we always put these values into
/// an Any existential.
public func reflect<T>(any: T) {
let any: Any = any
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size)
anyPointer.initialize(to: any)
let anyPointerValue = UInt(bitPattern: anyPointer)
reflect(instanceAddress: anyPointerValue, kind: .Existential)
anyPointer.deallocate()
}
// Reflect an `Error`, a.k.a. an "error existential".
//
// These are always boxed on the heap, with the following layout:
//
// - Word 0: Metadata Pointer
// - Word 1: 2x 32-bit reference counts
//
// If Objective-C interop is available, an Error is also an
// `NSError`, and so has:
//
// - Word 2: code (NSInteger)
// - Word 3: domain (NSString *)
// - Word 4: userInfo (NSDictionary *)
//
// Then, always follow:
//
// - Word 2 or 5: Instance type metadata pointer
// - Word 3 or 6: Instance witness table for conforming
// to `Swift.Error`.
//
// Following that is the instance that conforms to `Error`,
// rounding up to its alignment.
public func reflect<T: Error>(error: T) {
let error: Error = error
let errorPointerValue = unsafeBitCast(error, to: UInt.self)
reflect(instanceAddress: errorPointerValue, kind: .ErrorExistential)
}
/// Wraps a thick function with arity 0.
struct ThickFunction0 {
var function: () -> Void
}
/// Wraps a thick function with arity 1.
struct ThickFunction1 {
var function: (Int) -> Void
}
/// Wraps a thick function with arity 2.
struct ThickFunction2 {
var function: (Int, String) -> Void
}
/// Wraps a thick function with arity 3.
struct ThickFunction3 {
var function: (Int, String, AnyObject?) -> Void
}
struct ThickFunctionParts {
var function: UnsafeRawPointer
var context: Optional<UnsafeRawPointer>
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping () -> Void) {
let fn = UnsafeMutablePointer<ThickFunction0>.allocate(
capacity: MemoryLayout<ThickFunction0>.size)
fn.initialize(to: ThickFunction0(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int) -> Void) {
let fn =
UnsafeMutablePointer<ThickFunction1>.allocate(
capacity: MemoryLayout<ThickFunction1>.size)
fn.initialize(to: ThickFunction1(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction2>.allocate(
capacity: MemoryLayout<ThickFunction2>.size)
fn.initialize(to: ThickFunction2(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String, AnyObject?) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction3>.allocate(
capacity: MemoryLayout<ThickFunction3>.size)
fn.initialize(to: ThickFunction3(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Call this function to indicate to the parent that there are
/// no more instances to look at.
public func doneReflecting() {
reflect(instanceAddress: UInt(InstanceKind.None.rawValue), kind: .None)
}
/* Example usage
public protocol P {
associatedtype Index
var startIndex: Index { get }
}
public struct Thing : P {
public let startIndex = 1010
}
public enum E<T: P> {
case B(T)
case C(T.Index)
}
public class A<T: P> : P {
public let x: T?
public let y: T.Index
public let b = true
public let t = (1, 1.0)
private let type: NSObject.Type
public let startIndex = 1010
public init(x: T) {
self.x = x
self.y = x.startIndex
self.type = NSObject.self
}
}
let instance = A(x: A(x: Thing()))
reflect(A(x: Thing()))
*/
| 5d56fdff529f4da79e1030a9b466b8be | 30.409867 | 87 | 0.686885 | false | false | false | false |
esttorhe/SlackTeamExplorer | refs/heads/master | SlackTeamExplorer/SlackTeamCoreDataProxy/Models/Member.swift | mit | 1 |
// Native Frameworks
import CoreData
import Foundation
/// Member `NSManagedObject` model.
@objc(Member)
public class Member : NSManagedObject {
// Basic properties
@NSManaged public var membersIdentifier: String?
@NSManaged public var realName: String?
@NSManaged public var color: String?
@NSManaged public var name: String
// Timezones
@NSManaged public var tzLabel: String
@NSManaged public var tz: String
@NSManaged public var tzOffset: Int32
// Customization Flags
@NSManaged public var isUltraRestricted: Bool
@NSManaged public var isOwner: Bool
@NSManaged public var isPrimaryOwner: Bool
@NSManaged public var isRestricted: Bool
@NSManaged public var has2FA: Bool
@NSManaged public var hasFiles: Bool
@NSManaged public var devared: Bool
@NSManaged public var isNot: Bool
@NSManaged public var isAdmin: Bool
// Relations
@NSManaged public var profile: Profile?
/**
Inserts a new `Member` entity to the `context` provided initialized with the `json`.
- :param: context The `NSManagedObjectContext` where the new `Member` entity will be inserted.
- :param: json A `[NSObject:AnyObject?]` dictionary with the `JSON` schema used to seed the `Member` instance
- :returns: A fully initialized `Member` instance with the values read from the `json` provided.
*/
public static func memberInContext(context: NSManagedObjectContext, json:[NSObject:AnyObject?]) -> Member? {
if let member = NSEntityDescription.insertNewObjectForEntityForName("Member", inManagedObjectContext: context) as? Member {
if let id = json["id"] as? String {
member.membersIdentifier = id
}
if let isUltraRestricted = json["is_ultra_restricted"] as? Bool {
member.isUltraRestricted = isUltraRestricted
}
if let realName = json["real_name"] as? String {
member.realName = realName
}
if let isOwner = json["is_owner"] as? Bool {
member.isOwner = isOwner
}
if let tzLabel = json["tz_label"] as? String {
member.tzLabel = tzLabel
}
if let tz = json["tz"] as? String {
member.tz = tz
}
if let isRestricted = json["is_restricted"] as? Bool {
member.isRestricted = isRestricted
}
if let has2FA = json["has2fa"] as? Bool {
member.has2FA = has2FA
}
if let hasFiles = json["has_files"] as? Bool {
member.hasFiles = hasFiles
}
if let color = json["color"] as? String {
member.color = color
}
if let devared = json["devared"] as? Bool {
member.devared = devared
}
if let tzOffset = json["tz_offset"] as? Int32 {
member.tzOffset = tzOffset
}
if let isNot = json["is_not"] as? Bool {
member.isNot = isNot
}
if let isAdmin = json["is_admin"] as? Bool {
member.isAdmin = isAdmin
}
if let name = json["name"] as? String {
member.name = name
}
if let jsonProfile = json["profile"] as? Dictionary<NSObject, AnyObject> {
member.profile = Profile.profileInContext(context, json: jsonProfile)
}
return member
}
return nil
}
} | afb3ee3507b297dad3aee576bd511f5f | 32.587719 | 131 | 0.543103 | false | false | false | false |
dulingkang/Socket | refs/heads/master | SocketSwift/SocketDemo/PacketManager.swift | mit | 1 | //
// PacketManager.swift
// SocketDemo
//
// Created by dulingkang on 16/1/6.
// Copyright © 2016年 dulingkang. All rights reserved.
//
import UIKit
enum PacketType: Int {
case SPT_NONE = 0, SPT_STATUS, SPT_CMD, SPT_LOG, SPT_FILE_START, SPT_FILE_SENDING
}
enum PacketJson: String {
case fileLen, fileName
}
protocol PacketManagerDelegate {
func updateImage(image: UIImage)
}
class PacketManager: NSObject {
static let sharedInstance = PacketManager()
var delegate: PacketManagerDelegate?
var bufferData = NSMutableData()
var fileLen: Int = 0
var fileOnceLen: Int = 0
var fileName: String = ""
var needSave = false
var fileData = NSMutableData()
override init() {}
func handleBufferData(data: NSData) {
if data.length != 0 {
bufferData.appendData(data)
}
let headerData = bufferData.subdataWithRange(NSMakeRange(0, headerLength))
if headerData.length == 0 {
return
}
let payloadLength = parseHeader(headerData).payloadLength
if bufferData.length == payloadLength + headerLength {
self.processCompletePacket(bufferData)
bufferData = NSMutableData()
} else if bufferData.length > payloadLength + headerLength {
let contentData = bufferData.subdataWithRange(NSMakeRange(headerLength, payloadLength))
self.processCompletePacket(contentData)
let leftData = bufferData.subdataWithRange(NSMakeRange(payloadLength + headerLength, bufferData.length - payloadLength - headerLength))
bufferData = NSMutableData()
bufferData.appendData(leftData)
self.handleBufferData(NSData())
}
}
func parseHeader(headerData: NSData) -> (spt: Int, payloadLength: Int) {
let stream: NSInputStream = NSInputStream(data: headerData)
stream.open()
var buffer = [UInt8](count: 4, repeatedValue: 0)
var index: Int = 0
var spt: Int = 0
var payloadLength: Int = 0
while stream.hasBytesAvailable {
stream.read(&buffer, maxLength: buffer.count)
let sum: Int = Int(buffer[0]) + Int(buffer[1]) + Int(buffer[2]) + Int(buffer[3])
if index == 0 {
if sum != 276 {
return (0,0)
}
}
if index == 1 {
spt = sum
}
if index == 2 {
payloadLength = sum
}
index++
print("buffer:", buffer)
}
return (spt, payloadLength)
}
func parseJsonBody(bodyData: NSData) -> NSDictionary? {
do {
let parsedObject = try NSJSONSerialization.JSONObjectWithData(bodyData, options: NSJSONReadingOptions.AllowFragments)
print("parsedObject:", parsedObject)
return parsedObject as? NSDictionary
} catch {
print("parse error")
}
return nil
}
func processCompletePacket(data: NSData) {
let headerData = data.subdataWithRange(NSMakeRange(0, headerLength))
let spt = parseHeader(headerData).spt
let payloadLength = parseHeader(headerData).payloadLength
let leftData = data.subdataWithRange(NSMakeRange(headerLength, payloadLength))
let type: PacketType = PacketType(rawValue: spt)!
switch type {
case .SPT_NONE:
break
case .SPT_STATUS:
break
case .SPT_CMD:
break
case .SPT_LOG:
break
case .SPT_FILE_START:
let dict: NSDictionary = self.parseJsonBody(leftData)!
fileLen = dict.valueForKey(PacketJson.fileLen.rawValue) as! Int
fileName = dict.valueForKey(PacketJson.fileName.rawValue) as! String
if fileName.suffix() != "jpg" {
needSave = true
}
case .SPT_FILE_SENDING:
fileOnceLen = fileOnceLen + payloadLength
if !needSave {
fileData.appendData(leftData)
if fileOnceLen == fileLen {
self.delegate?.updateImage(UIImage.init(data: fileData)!)
}
}
}
}
} | 9d6d0c0226ee628de31d7ba34606aa7d | 30.637681 | 147 | 0.573883 | false | false | false | false |
appcompany/SwiftSky | refs/heads/master | Sources/SwiftSky/Storm.swift | mit | 1 | //
// Storm.swift
// SwiftSky
//
// Created by Luca Silverentand on 11/04/2017.
// Copyright © 2017 App Company.io. All rights reserved.
//
import Foundation
import CoreLocation
extension CLLocation {
func destinationBy(_ distance: CLLocationDistance, direction: CLLocationDirection) -> CLLocation {
let earthRadius = 6372.7976
let angularDistance = (distance / 1000) / earthRadius
let originLatRad = self.coordinate.latitude * (.pi / 180)
let originLngRad = self.coordinate.longitude * (.pi / 180)
let directionRad = direction * (.pi / 180)
let destinationLatRad = asin(
sin(originLatRad) * cos(angularDistance) +
cos(originLatRad) * sin(angularDistance) *
cos(directionRad))
let destinationLngRad = originLngRad + atan2(
sin(directionRad) * sin(angularDistance) * cos(originLatRad),
cos(angularDistance) - sin(originLatRad) * sin(destinationLatRad))
let destinationLat: CLLocationDegrees = destinationLatRad * (180 / .pi)
let destinationLng: CLLocationDegrees = destinationLngRad * (180 / .pi)
return CLLocation(latitude: destinationLat, longitude: destinationLng)
}
}
/// Contains a `Bearing` and `Distance` describing the location of a storm
public struct Storm {
/// `Bearing` from requested location where a storm can be found
public let bearing : Bearing?
/// `Distance` from requested location where a storm can be found
public let distance : Distance?
/// ``
public let location : CLLocation?
var hasData : Bool {
if bearing != nil { return true }
if distance != nil { return true }
return false
}
init(bearing: Bearing?, distance: Distance?, origin: CLLocation?) {
self.bearing = bearing
self.distance = distance
if bearing == nil || distance == nil || origin == nil {
self.location = nil
} else {
self.location = origin?.destinationBy(Double(distance!.value(as: .meter)), direction: Double(bearing!.degrees))
}
}
}
| d4042f307afc95d13aced5e4ca76e8fd | 33.3125 | 123 | 0.621129 | false | false | false | false |
megavolt605/CNLUIKitTools | refs/heads/master | CNLUIKitTools/CNLUIT+UIColor.swift | mit | 1 | //
// CNLUIT+UIColor.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
import CNLFoundationTools
public extension UIColor {
public class func colorWithInt(red: UInt, green: UInt, blue: UInt, alpha: UInt) -> UIColor {
let r = CGFloat(red) / 255.0
let g = CGFloat(green) / 255.0
let b = CGFloat(blue) / 255.0
let a = CGFloat(alpha) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: a)
}
public class func colorWith(hex: UInt) -> UIColor {
let red = hex % 0x100
let green = (hex >> 8) % 0x100
let blue = (hex >> 16) % 0x100
let alpha = (hex >> 24) % 0x100
return UIColor.colorWithInt(red: red, green: green, blue: blue, alpha: alpha)
}
public class func colorWith(string: String?, reverse: Bool = false) -> UIColor? {
if let stringColor = string, let reversedColor = UInt(stringColor, radix: 16) {
if reverse {
let color1 = (reversedColor & 0x000000FF) << 16
let color2 = (reversedColor & 0x00FF0000) >> 16
let color3 = reversedColor & 0xFF00FF00
return UIColor.colorWith(hex: color1 | color2 | color3)
} else {
return UIColor.colorWith(hex: reversedColor)
}
}
return nil
}
public func hexIntVaue(reversed: Bool = false) -> UInt {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
if getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
let hexRed = UInt(255.0 * red)
let hexGreen = UInt(255.0 * green) << 8
let hexBlue = UInt(255.0 * blue) << 16
let hexAlpha = UInt(255.0 * alpha) << 24
let color = hexRed | hexGreen | hexBlue | hexAlpha
if reversed {
let reversedColor1 = (color & 0x000000FF) << 16
let reversedColor2 = (color & 0x00FF0000) >> 16
let reversedColor3 = color & 0xFF00FF00
return reversedColor1 | reversedColor2 | reversedColor3
} else {
return color
}
}
// opaque black by default
return 0xFF000000
}
public func hexValue(reversed: Bool = false) -> String {
let value = hexIntVaue(reversed: reversed)
return String(format: "%08x", value)
}
}
/*
extension UIColor: CNLDictionaryDecodable {
public static func decodeValue(_ any: Any) -> Self? {
if let value = any as? UInt {
return self.colorWith(hex: value)
}
return nil
}
public func encodeValue() -> Any? { return hexValue() }
}
*/
| 86a35e243bbff28fdfbb6ec2912a0e7f | 31.862069 | 96 | 0.552641 | false | false | false | false |
tectijuana/patrones | refs/heads/master | Bloque1SwiftArchivado/PracticasSwift/SandovalChristopher/programa1.swift | gpl-3.0 | 1 | /*
Nombre del programa: Suma de dos n numeros
nombre: Sandoval Lizarraga Chritopher
*/
//Importación de librerías
import Foundation
//declaración de constantes
let val1 = 5
let val2 = -5
//variable donde se guarda la suma de los 2 valores
var suma = 0
//suma de los 2 valores
suma = val1 + val2
print("Suma de 2 valores")
print("\n\(val1)\(val2) = \(suma)")
//Bloque de control para indicar si la suma es positiva, negativa o 0
if suma < 0
{print("La suma es negativa")}
else if suma == 0
{print("La suma es igual a 0")}
else
{print("La suma es positiva")} | d9a3b3c2a93d4993170efd894ed606d1 | 19.344828 | 70 | 0.672326 | false | false | false | false |
andrelind/Breeze | refs/heads/master | Breeze/BreezeStore+Saving.swift | mit | 1 | //
// BreezeStore+Saving.swift
// Breeze
//
// Created by André Lind on 2014-08-11.
// Copyright (c) 2014 André Lind. All rights reserved.
//
import Foundation
public typealias BreezeSaveBlock = (BreezeContextType) -> Void
public typealias BreezeErrorBlock = (NSError?) -> Void
extension BreezeStore {
// MARK: Save in Main
public class func saveInMain(changes: BreezeSaveBlock) {
let moc = BreezeStore.contextForType(.Main)
moc.performBlock {
changes(.Main)
var error: NSError?
moc.save(&error)
if error != nil {
println("Breeze - Error saving main context: \(error!)")
}
}
}
public class func saveInMainWaiting(changes: BreezeSaveBlock) {
let moc = BreezeStore.contextForType(.Main)
moc.performBlockAndWait { () -> Void in
changes(.Main)
var error: NSError?
moc.save(&error)
if error != nil {
println("Breeze - Error saving main context: \(error!)")
}
}
}
// MARK: Save in Background
public class func saveInBackground(changes: BreezeSaveBlock) {
saveInBackground(changes, completion: nil)
}
public class func saveInBackground(changes: BreezeSaveBlock, completion: BreezeErrorBlock?) {
let moc = BreezeStore.contextForType(.Background)
moc.performBlock { () -> Void in
changes(.Background)
var error: NSError?
moc.save(&error)
if error != nil {
println("Breeze - Error saving background context: \(error!)")
}
if completion != nil {
dispatch_async(dispatch_get_main_queue()) {
completion!(error)
}
}
}
}
}
| 0a9b50515f4e7ae781a40c2f3f5b531f | 25.253521 | 97 | 0.559013 | false | false | false | false |
ludoded/ReceiptBot | refs/heads/master | Pods/Material/Sources/iOS/ToolbarController.swift | lgpl-3.0 | 2 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the ToolbarController.
This is the recommended method of accessing the ToolbarController
through child UIViewControllers.
*/
public var toolbarController: ToolbarController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is ToolbarController {
return viewController as? ToolbarController
}
viewController = viewController?.parent
}
return nil
}
}
@objc(ToolbarControllerDelegate)
public protocol ToolbarControllerDelegate {
/// Delegation method that executes when the floatingViewController will open.
@objc
optional func toolbarControllerWillOpenFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController will close.
@objc
optional func toolbarControllerWillCloseFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController did open.
@objc
optional func toolbarControllerDidOpenFloatingViewController(toolbarController: ToolbarController)
/// Delegation method that executes when the floatingViewController did close.
@objc
optional func toolbarControllerDidCloseFloatingViewController(toolbarController: ToolbarController)
}
@objc(ToolbarController)
open class ToolbarController: StatusBarController {
/**
A Display value to indicate whether or not to
display the rootViewController to the full view
bounds, or up to the toolbar height.
*/
open var toolbarDisplay = Display.partial {
didSet {
layoutSubviews()
}
}
/// Reference to the Toolbar.
@IBInspectable
open let toolbar = Toolbar()
/// Internal reference to the floatingViewController.
private var internalFloatingViewController: UIViewController?
/// Delegation handler.
open weak var delegate: ToolbarControllerDelegate?
/// A floating UIViewController.
open var floatingViewController: UIViewController? {
get {
return internalFloatingViewController
}
set(value) {
if let v = internalFloatingViewController {
v.view.layer.rasterizationScale = Screen.scale
v.view.layer.shouldRasterize = true
delegate?.toolbarControllerWillCloseFloatingViewController?(toolbarController: self)
internalFloatingViewController = nil
UIView.animate(withDuration: 0.5,
animations: { [weak self] in
guard let s = self else {
return
}
v.view.center.y = 2 * s.view.bounds.height
s.toolbar.alpha = 1
s.rootViewController.view.alpha = 1
}) { [weak self] _ in
guard let s = self else {
return
}
v.willMove(toParentViewController: nil)
v.view.removeFromSuperview()
v.removeFromParentViewController()
v.view.layer.shouldRasterize = false
s.isUserInteractionEnabled = true
s.toolbar.isUserInteractionEnabled = true
DispatchQueue.main.async { [weak self] in
guard let s = self else {
return
}
s.delegate?.toolbarControllerDidCloseFloatingViewController?(toolbarController: s)
}
}
}
if let v = value {
// Add the noteViewController! to the view.
addChildViewController(v)
v.view.frame = view.bounds
v.view.center.y = 2 * view.bounds.height
v.view.isHidden = true
view.insertSubview(v.view, aboveSubview: toolbar)
v.view.layer.zPosition = 1500
v.didMove(toParentViewController: self)
v.view.isHidden = false
v.view.layer.rasterizationScale = Screen.scale
v.view.layer.shouldRasterize = true
view.layer.rasterizationScale = Screen.scale
view.layer.shouldRasterize = true
internalFloatingViewController = v
isUserInteractionEnabled = false
toolbar.isUserInteractionEnabled = false
delegate?.toolbarControllerWillOpenFloatingViewController?(toolbarController: self)
UIView.animate(withDuration: 0.5,
animations: { [weak self, v = v] in
guard let s = self else {
return
}
v.view.center.y = s.view.bounds.height / 2
s.toolbar.alpha = 0.5
s.rootViewController.view.alpha = 0.5
}) { [weak self, v = v] _ in
guard let s = self else {
return
}
v.view.layer.shouldRasterize = false
s.view.layer.shouldRasterize = false
DispatchQueue.main.async { [weak self] in
guard let s = self else {
return
}
s.delegate?.toolbarControllerDidOpenFloatingViewController?(toolbarController: s)
}
}
}
}
}
open override func layoutSubviews() {
super.layoutSubviews()
let y = Application.shouldStatusBarBeHidden || statusBar.isHidden ? 0 : statusBar.height
toolbar.y = y
toolbar.width = view.width
switch toolbarDisplay {
case .partial:
let h = y + toolbar.height
rootViewController.view.y = h
rootViewController.view.height = view.height - h
case .full:
rootViewController.view.frame = view.bounds
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
prepareStatusBar()
prepareToolbar()
}
}
extension ToolbarController {
/// Prepares the statusBar.
fileprivate func prepareStatusBar() {
shouldHideStatusBarOnRotation = false
}
/// Prepares the toolbar.
fileprivate func prepareToolbar() {
toolbar.depthPreset = .depth1
view.addSubview(toolbar)
}
}
| 9982d3e555fa9a1cfa9cdc25eda3be0a | 36.34375 | 110 | 0.63682 | false | false | false | false |
fromkk/SlackFeedback | refs/heads/master | FeedbackSlack/FeedbackSlack.swift | mit | 1 | //
// FeedbackSlack.swift
// SlackTest
//
// Created by Ueoka Kazuya on 2016/08/21.
// Copyright © 2016年 fromKK. All rights reserved.
//
import Foundation
@objc open class FeedbackSlack: NSObject {
@objc public let slackToken: String
@objc public let slackChannel: String
@objc open var enabled: Bool = true
@objc open var options: String?
@objc var subjects: [String]?
private init(slackToken: String, slackChannel: String, subjects: [String]? = nil) {
self.slackToken = slackToken
self.slackChannel = slackChannel
self.subjects = subjects
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(FeedbackSlack.screenshotNotification(_:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
}
@objc public static var shared: FeedbackSlack?
private lazy var sharedWindow: UIWindow = {
let result: UIWindow = UIWindow(frame: UIApplication.shared.keyWindow?.bounds ?? UIScreen.main.bounds)
return result
}()
@objc public static func setup(_ slackToken: String, slackChannel: String, subjects: [String]? = nil) -> FeedbackSlack? {
if let feedback: FeedbackSlack = shared {
return feedback
}
shared = FeedbackSlack(slackToken: slackToken, slackChannel: slackChannel, subjects: subjects)
return shared
}
private var feedbacking: Bool = false
@objc func screenshotNotification(_ notification: Notification) {
guard let window: UIWindow = UIApplication.shared.delegate?.window!, !self.feedbacking, self.enabled else {
return
}
self.feedbacking = true
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) { [unowned self] in
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0.0)
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let viewController: FeedbackSlackViewController = FeedbackSlackViewController.instantitate()
viewController.image = image
self.sharedWindow.isHidden = false
self.sharedWindow.rootViewController = viewController
self.sharedWindow.alpha = 0.0
self.sharedWindow.makeKeyAndVisible()
UIView.animate(withDuration: 0.33, animations: { [unowned self] in
self.sharedWindow.alpha = 10.0
})
}
}
func close() {
DispatchQueue.main.async { [unowned self] in
self.sharedWindow.alpha = 1.0
UIView.animate(withDuration: 0.33, animations: { [unowned self] in
self.sharedWindow.alpha = 0.0
}) { [unowned self] (finished: Bool) in
self.sharedWindow.isHidden = true
self.feedbacking = false
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
}
}
}
}
| 61ab95def4e213c4718a28c2252db959 | 38.269231 | 183 | 0.651322 | false | false | false | false |
lee5783/TLMonthYearPicker | refs/heads/master | Classes/TLMonthYearPickerView.swift | mit | 1 | //
// TLMonthYearPickerView.swift
// TLMonthYearPicker
//
// Created by lee5783 on 12/22/16.
// Copyright © 2016 lee5783. All rights reserved.
//
import UIKit
/// enum MonthYearPickerMode
///
/// - monthAndYear: Show month and year components
/// - year: Show year only
public enum MonthYearPickerMode: Int {
case monthAndYear = 0
case year = 1
}
/// Maximum year constant
fileprivate let kMaximumYears = 5000
/// Minimum year constant
fileprivate let kMinimumYears = 1
public protocol TLMonthYearPickerDelegate: NSObjectProtocol {
/// Delegate: notify picker date changed
///
/// - Parameters:
/// - picker: return picker instant
/// - date: return picker date value
func monthYearPickerView(picker: TLMonthYearPickerView, didSelectDate date: Date)
}
public class TLMonthYearPickerView: UIControl, UIPickerViewDataSource, UIPickerViewDelegate {
/// Set picker mode: monthAndYear or year only
fileprivate var _mode: MonthYearPickerMode = .monthAndYear
public var monthYearPickerMode: MonthYearPickerMode {
get {
return self._mode
}
set(value) {
self._mode = value
self._picker?.reloadAllComponents()
self.setDate(date: self.date, animated: false)
}
}
/// Locale value, default is device locale
fileprivate var _locale: Locale?
var locale: Locale! {
get {
if self._locale != nil {
return self._locale!
} else {
return Locale.current
}
}
set(value) {
self._locale = value
self.calendar.locale = value
}
}
/// Calendar value, default is device calendar
fileprivate var _calendar: Calendar!
public var calendar: Calendar! {
get {
if self._calendar != nil {
return self._calendar
} else {
var calendar = Calendar.current
calendar.locale = self.locale
return calendar
}
}
set(value) {
self._calendar = value
self._locale = value.locale
self.initPickerData()
}
}
/// Picker text color, default is black color
public var textColor: UIColor = UIColor.black {
didSet(value) {
self._picker?.reloadAllComponents()
}
}
/// Picker font, default is system font with size 16
public var font: UIFont = UIFont.systemFont(ofSize: 16) {
didSet(value) {
self._picker?.reloadAllComponents()
}
}
/// Get/Set Picker background color
public override var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set(value) {
super.backgroundColor = value
self._picker?.backgroundColor = value
}
}
/// Current picker value
public var date: Date!
/// Delegate
public weak var delegate: TLMonthYearPickerDelegate?
/// Maximum date
fileprivate var _minimumDate: Date?
public var minimumDate: Date? {
get {
return self._minimumDate
}
set(value) {
self._minimumDate = value
if let date = value {
let components = self.calendar.dateComponents([.year, .month], from: date)
_minimumYear = components.year!
_minimumMonth = components.month!
} else {
_minimumYear = -1
_minimumMonth = -1
}
self._picker?.reloadAllComponents()
}
}
/// Mimimum date
fileprivate var _maximumDate: Date?
public var maximumDate: Date? {
get {
return self._maximumDate
}
set(value) {
self._maximumDate = value
if let date = value {
let components = self.calendar.dateComponents([.year, .month], from: date)
_maximumYear = components.year!
_maximumMonth = components.month!
} else {
_maximumYear = -1
_maximumMonth = -1
}
self._picker?.reloadAllComponents()
}
}
//MARK: - Internal variables
/// UIPicker
var _picker: UIPickerView!
/// month year array values
fileprivate var _months: [String] = []
fileprivate var _years: [String] = []
/// Store caculated value of minimum year-month and maximum year-month
fileprivate var _minimumYear = -1
fileprivate var _maximumYear = -1
fileprivate var _minimumMonth = -1
fileprivate var _maximumMonth = -1
override init(frame: CGRect) {
super.init(frame: frame)
self.initView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initView()
}
/// Initial view
/// Setup Picker and Picker data
internal func initView() {
self._picker = UIPickerView(frame: self.bounds)
self._picker.showsSelectionIndicator = true
self._picker.delegate = self
self._picker.dataSource = self
self._picker.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self._picker.translatesAutoresizingMaskIntoConstraints = true
self.addSubview(self._picker)
self.clipsToBounds = true
self.initPickerData()
self.date = Date()
self._picker.reloadAllComponents()
}
/// Setup picker data
internal func initPickerData() {
//list of month
let dateFormatter = DateFormatter()
dateFormatter.locale = self.locale
self._months = dateFormatter.monthSymbols
dateFormatter.dateFormat = "yyyy"
var components = DateComponents()
self._years.removeAll()
for year in kMinimumYears...kMaximumYears {
components.year = year
if let date = self.calendar.date(from: components) {
self._years.append(dateFormatter.string(from: date))
}
}
}
/// Set picker date to UI
override public func didMoveToSuperview() {
super.didMoveToSuperview()
self.setDate(date: self.date, animated: false)
}
override public func layoutSubviews() {
super.layoutSubviews()
self._picker?.frame = self.bounds
}
//MARK: - Public function
/// Set date to picker
///
/// - Parameters:
/// - date: the date user choose
/// - animated: display UI animate or not
func setDate(date: Date, animated: Bool) {
// Extract the month and year from the current date value
let components = self.calendar.dateComponents([.year, .month], from: date)
let month = components.month!
let year = components.year!
self.date = date
if self.monthYearPickerMode == .year {
self._picker.selectRow(year - kMinimumYears, inComponent: 0, animated: animated)
} else {
self._picker.selectRow(year - kMinimumYears, inComponent: 1, animated: animated)
self._picker.selectRow(month - 1, inComponent: 0, animated: animated)
}
}
//MARK: - Implement UIPickerViewDataSource, UIPickerViewDelegate
/// - Parameters:
/// - Parameter pickerView
/// - Returns: return 2 if pickerMode is monthAndYear, otherwise return 1
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return self.monthYearPickerMode == .year ? 1 : 2
}
/// - Parameters:
/// - pickerView
/// - component
/// - Returns: return number of row
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if self.monthYearPickerMode == .year {
return self._years.count
} else {
if component == 0 {
return self._months.count
} else {
return self._years.count
}
}
}
/// - Parameters:
/// - pickerView
/// - row
/// - component
/// - Returns: display string of specific row in specific component
public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let isSelectYear = self.monthYearPickerMode == .year || component == 1
var shouldDisable = false
if isSelectYear {
let year = row + kMinimumYears
if (self._maximumDate != nil && year > _maximumYear) || (self._minimumDate != nil && year < _minimumYear)
{
shouldDisable = true
}
} else {
let month = row + 1
let components = self.calendar.dateComponents([.year], from: self.date)
let year = components.year!
if (self._maximumDate != nil && year > _maximumYear)
|| (year == _maximumYear && month > _maximumMonth)
|| (self._minimumDate != nil && year < _minimumYear)
|| (year == _minimumYear && month < _minimumMonth) {
shouldDisable = true
}
}
var text = ""
if self.monthYearPickerMode == .year {
text = self._years[row]
} else {
if component == 0 {
text = self._months[row]
} else {
text = self._years[row]
}
}
var color = self.textColor
if shouldDisable {
color = color.withAlphaComponent(0.5)
}
return NSAttributedString(string: text, attributes: [
.font: self.font,
.foregroundColor: color
])
}
/// - Parameters:
/// - pickerView
/// - row
/// - component
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let date = self.dateFromSelection() {
var targetDate = date
if let minimumDate = self._minimumDate {
if minimumDate.compare(date) == .orderedDescending {
targetDate = minimumDate
}
}
if let maximumDate = self._maximumDate {
if maximumDate.compare(date) == .orderedAscending {
targetDate = maximumDate
}
}
self.setDate(date: targetDate, animated: true)
self.delegate?.monthYearPickerView(picker: self, didSelectDate: targetDate)
if self.monthYearPickerMode == .monthAndYear {
self._picker.reloadComponent(0)
}
}
}
/// Compare only month and year value
///
/// - Parameters:
/// - date1: first date you want to compare
/// - date2: second date you want to compare
/// - Returns: ComparisonResult
fileprivate func compareMonthAndYear(date1: Date, date2: Date) -> ComparisonResult {
let components1 = self.calendar.dateComponents([.year, .month], from: date1)
let components2 = self.calendar.dateComponents([.year, .month], from: date2)
if let date1Compare = self.calendar.date(from: components1),
let date2Compare = self.calendar.date(from: components2) {
return date1Compare.compare(date2Compare)
} else {
return date1.compare(date2)
}
}
/// Caculate date of current picker
///
/// - Returns: Date
fileprivate func dateFromSelection() -> Date? {
var month = 1
var year = 1
if self.monthYearPickerMode == .year {
year = self._picker.selectedRow(inComponent: 0) + kMinimumYears
} else {
month = self._picker.selectedRow(inComponent: 0) + 1
year = self._picker.selectedRow(inComponent: 1) + kMinimumYears
}
var components = DateComponents()
components.month = month
components.year = year
components.day = 1
components.timeZone = TimeZone(secondsFromGMT: 0)
return self.calendar.date(from: components)
}
}
| 36a2fd89d6627024cd44484530dbbb9f | 30.034739 | 140 | 0.556888 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/DebugInfo/mangling.swift | apache-2.0 | 25 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// Type:
// Swift.Dictionary<Swift.Int64, Swift.String>
func markUsed<T>(_ t: T) {}
// Variable:
// mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String>
// CHECK: !DIGlobalVariable(name: "myDict",
// CHECK-SAME: linkageName: "$s8mangling6myDictSDys5Int64VSSGvp",
// CHECK-SAME: line: [[@LINE+6]]
// CHECK-SAME: type: ![[DT_CONTAINER:[0-9]+]]
// CHECK: ![[DT_CONTAINER]] = !DICompositeType({{.*}}elements: ![[DT_ELTS:[0-9]+]]
// CHECK: ![[DT_ELTS]] = !{![[DT_MEMBER:[0-9]+]]}
// CHECK: ![[DT_MEMBER]] = !DIDerivedType(tag: DW_TAG_member, {{.*}}baseType: ![[DT:[0-9]+]]
// CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary"
var myDict = Dictionary<Int64, String>()
myDict[12] = "Hello!"
// mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple1",
// CHECK-SAME: linkageName: "$s8mangling8myTuple1SS4Name_s5Int64V2Idtvp",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT1:[0-9]+]]
// CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS4Name_s5Int64V2IdtD"
var myTuple1 : (Name: String, Id: Int64) = ("A", 1)
// mangling.myTuple2 : (Swift.String, Id : Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple2",
// CHECK-SAME: linkageName: "$s8mangling8myTuple2SS_s5Int64V2Idtvp",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT2:[0-9]+]]
// CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64V2IdtD"
var myTuple2 : ( String, Id: Int64) = ("B", 2)
// mangling.myTuple3 : (Swift.String, Swift.Int64)
// CHECK: !DIGlobalVariable(name: "myTuple3",
// CHECK-SAME: linkageName: "$s8mangling8myTuple3SS_s5Int64Vtvp",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: type: ![[TT3:[0-9]+]]
// CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64VtD"
var myTuple3 : ( String, Int64) = ("C", 3)
markUsed(myTuple1.Id)
markUsed(myTuple2.Id)
markUsed({ $0.1 }(myTuple3))
| b5ae60f2e5ce2fd486c1a91dd070039d | 47.022222 | 97 | 0.612217 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | refs/heads/master | nRF Toolbox/CommonViews/NordicButton.swift | bsd-3-clause | 1 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
struct NordicButtonConfigurator {
var isHidden: Bool = false
var normalTitle: String
var style: NordicButton.Style = .default
}
class NordicButton: UIButton {
struct Style: RawRepresentable, Equatable {
let rawValue: Int
static let `default` = Style(rawValue: 1)
static let mainAction = Style(rawValue: 2)
static let destructive = Style(rawValue: 3)
var tintColor: UIColor {
switch self {
case .mainAction: return .white
case .destructive: return .nordicRed
case .default: return .nordicLake
default: return UIColor.Text.systemText
}
}
var bgColor: UIColor {
switch self {
case .default, .destructive: return .clear
case .mainAction: return .nordicLake
default: return .clear
}
}
var borderColor: UIColor {
switch self {
case .destructive: return .nordicRed
case .mainAction, .default: return .nordicLake
default: return .clear
}
}
}
override var isEnabled: Bool {
didSet {
setupBrandView()
}
}
var style: Style = .default {
didSet {
tintColor = style.tintColor
borderColor = style.borderColor
self.setupBrandView()
}
}
var normalTitle: String? {
get { title(for: .normal) }
set { setTitle(newValue, for: .normal) }
}
override init(frame: CGRect) {
super.init(frame: frame)
setupBrandView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupBrandView()
}
override func awakeFromNib() {
super.awakeFromNib()
style = .default
}
private func setupBrandView() {
cornerRadius = 4
borderWidth = 1
guard isEnabled else {
setTitleColor(UIColor.Text.inactive, for: .normal)
borderColor = UIColor.Text.inactive
backgroundColor = .clear
return
}
borderColor = style.borderColor
setTitleColor(style.tintColor, for: .normal)
backgroundColor = style.bgColor
}
override func draw(_ rect: CGRect) {
super.draw(rect)
cornerRadius = 4
layer.masksToBounds = true
}
func apply(configurator: NordicButtonConfigurator) {
isHidden = configurator.isHidden
setTitle(configurator.normalTitle, for: .normal)
style = configurator.style
}
}
| b6775c336851e01afd8ab88cc625d34d | 30.167883 | 84 | 0.633958 | false | false | false | false |
miktap/pepe-p06 | refs/heads/master | PePeP06/PePeP06Tests/TasoClientTests.swift | mit | 1 | //
// TasoClientTests.swift
// PePeP06Tests
//
// Created by Mikko Tapaninen on 24/12/2017.
//
import Quick
import Nimble
import ObjectMapper
import SwiftyBeaver
@testable import PePeP06
class TasoClientTests: QuickSpec {
override func spec() {
describe("Taso") {
var tasoClient: TasoClient!
beforeEach {
tasoClient = TasoClient()
tasoClient.initialize()
sleep(1)
}
describe("getTeam") {
it("gets PePe team") {
var teamListing: TasoTeamListing?
tasoClient.getTeam(team_id: "141460", competition_id: "lsfs1718", category_id: "FP12")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
teamListing = TasoTeamListing(JSONString: message!)
}
expect(teamListing?.team.team_name).toEventually(equal("PePe"), timeout: 3)
}
}
describe("getCompetitions") {
it("gets lsfs1718 competition") {
var competitionListing: TasoCompetitionListing?
tasoClient.getCompetitions()!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
competitionListing = TasoCompetitionListing(JSONString: message!)
}
expect(competitionListing?.competitions!).toEventually(containElementSatisfying({$0.competition_id == "lsfs1718"}), timeout: 3)
}
}
describe("getCategories") {
it("gets category FP12") {
var categoryListing: TasoCategoryListing?
tasoClient.getCategories(competition_id: "lsfs1718")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
categoryListing = TasoCategoryListing(JSONString: message!)
}
expect(categoryListing?.categories).toEventually(containElementSatisfying({$0.category_id == "FP12"}), timeout: 3)
}
}
describe("getClub") {
it("gets club 3077") {
var clubListing: TasoClubListing?
tasoClient.getClub()!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
clubListing = TasoClubListing(JSONString: message!)
}
expect(clubListing?.club?.club_id).toEventually(equal("3077"), timeout: 3)
}
}
describe("getPlayer") {
it("gets player Jimi") {
var playerListing: TasoPlayerListing?
tasoClient.getPlayer(player_id: "290384")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
playerListing = TasoPlayerListing(JSONString: message!)
}
expect(playerListing?.player?.first_name).toEventually(equal("Jimi"), timeout: 3)
}
}
describe("getGroup") {
it("gets group with team standings") {
var groupListing: TasoGroupListing?
tasoClient.getGroup(competition_id: "lsfs1718", category_id: "FP12", group_id: "1")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
groupListing = TasoGroupListing(JSONString: message!)
}
expect(groupListing?.group?.teams).toNotEventually(beNil(), timeout: 3)
}
}
}
}
}
| aa14940fef9b79b6284085f411332f38 | 40.927273 | 147 | 0.460104 | false | false | false | false |
GoogleCloudPlatform/ios-docs-samples | refs/heads/master | screensaver/GCPLife/GCPLifeView.swift | apache-2.0 | 1 | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Cocoa
import ScreenSaver
let stepDuration = 1.0
let fadeDuration = 0.5
let cellSize:CGFloat = 128.0
let host = "storage.googleapis.com"
let bucket = "gcp-screensaver.appspot.com"
class GCPLifeView: ScreenSaverView {
var gridViews:[[NSImageView]]!
var grid:[[Int]]!
var newgrid:[[Int]]!
var imageNames:[String]!
var timer:Timer!
var history:[String: Int]!
override init?(frame: NSRect, isPreview: Bool) {
super.init(frame: frame, isPreview: isPreview)
startRunning()
}
required init?(coder: NSCoder) {
super.init(coder:coder)
startRunning()
}
override func resizeSubviews(withOldSize oldSize: NSSize) {
buildGrid()
randomizeGrid()
renderGrid()
}
override func draw(_ dirtyRect: NSRect) {
NSColor(white: 0.2, alpha: 1).set()
NSRectFill(bounds)
}
func startRunning() {
animationTimeInterval = 1/30.0
// Prepare the display in case there is no network connection.
buildGrid()
renderGrid()
// Fetch the icon list and start animating.
fetchIconList {
self.buildGrid()
self.renderGrid()
self.timer = Timer.scheduledTimer(timeInterval: stepDuration,
target: self,
selector: #selector(self.tick),
userInfo: nil,
repeats: true)
}
}
func buildGrid() {
let bundle = Bundle(for: type(of: self))
history = [String: Int]()
if gridViews != nil {
for views in gridViews {
for view in views {
view.removeFromSuperview()
}
}
}
let cellWidth = cellSize * sqrt(3) / 2
let centerX = (bounds.size.width - cellSize) * 0.5
let centerY = (bounds.size.height - cellSize) * 0.5
let rows:Int = Int(bounds.size.height/cellSize * 0.5 + 0.5)
let cols:Int = Int(bounds.size.width/cellWidth * 0.5 + 0.5)
var i:Int = 0
grid = []
newgrid = []
gridViews = []
for r in -rows...rows {
grid.append([])
newgrid.append([])
gridViews.append([])
for c in -cols...cols {
let cellX:CGFloat = centerX + CGFloat(c) * cellSize * sqrt(3) / 2
var cellY:CGFloat = centerY + CGFloat(r) * cellSize
let odd:Bool = abs(c) % 2 == 1
if odd {
cellY -= 0.5 * cellSize
}
let imageFrame = NSRect(x : cellX,
y : cellY,
width: cellSize,
height: cellSize)
let view = NSImageView.init(frame: imageFrame)
addSubview(view)
if r == 0 && c == 0 {
let imageName = "Logo_Cloud_512px_Retina.png"
let imagePath = bundle.pathForImageResource(imageName)!
let image = NSImage.init(contentsOfFile: imagePath)
view.image = image
grid[r+rows].append(1)
newgrid[r+rows].append(1)
// Expand the logo image slightly to match the product icon sizes.
let ds = -0.05*cellSize
view.frame = view.frame.insetBy(dx: ds, dy: ds)
} else {
if let imageNames = imageNames {
let imageName = imageNames[i % imageNames.count]
i = i + 1
fetchImage(view, name:imageName)
}
grid[r+rows].append(0)
newgrid[r+rows].append(0)
}
gridViews[r+rows].append(view)
}
}
}
func renderGrid() {
let rows = grid.count
let cols = grid[0].count
for r in 0..<rows {
for c in 0..<cols {
let gridView = gridViews[r][c]
if grid[r][c] == 0 {
if newgrid[r][c] == 0 {
gridView.alphaValue = 0
gridView.isHidden = true
} else {
gridView.alphaValue = 0
gridView.isHidden = false
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = fadeDuration
gridView.animator().alphaValue = 1
}, completionHandler: {
})
}
} else {
if newgrid[r][c] == 0 {
gridView.alphaValue = 1
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = fadeDuration
gridView.animator().alphaValue = 0
}, completionHandler: {
gridView.isHidden = true
})
} else {
gridView.isHidden = false
gridView.alphaValue = 1
}
}
}
}
}
func tick() {
updateGrid()
renderGrid()
}
func randomizeGrid() {
history = [String: Int]()
let rows = grid.count
let cols = grid[0].count
for r in 0..<rows {
for c in 0..<cols {
let diceRoll = Int(arc4random_uniform(6) + 1)
if diceRoll > 5 {
newgrid[r][c] = 1
} else {
newgrid[r][c] = 0
}
grid[r][c] = 0
}
}
// The center cell should always be alive.
newgrid[rows/2][cols/2] = 1
grid[rows/2][cols/2] = 1
}
// Compute a signature for the current grid.
// This will allow us to detect repeats (and cycles).
func signature() -> String {
let data = NSMutableData()
var i = 0
var v:UInt64 = 0
let rows = grid.count
let cols = grid[0].count
for r in 0..<rows {
for c in 0..<cols {
if grid[r][c] != 0 {
v = v | UInt64(UInt64(1) << UInt64(i))
}
i = i + 1
if i == 64 {
data.append(&v, length: MemoryLayout.size(ofValue: v))
i = 0
v = 0
}
}
}
if i > 0 {
data.append(&v, length: MemoryLayout.size(ofValue: v))
}
return data.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0))
}
func updateGrid() {
// First check for repetitions.
let s = signature()
if let x = history[s] {
if (x == 3) {
randomizeGrid()
return
}
history[s] = x + 1
} else {
history[s] = 1
}
// Compute new grid state.
let rows = grid.count
let cols = grid[0].count
grid = newgrid
newgrid = []
for r in 0..<rows {
newgrid.append([])
for c in 0..<cols {
// Count the neighbors of cell (r,c).
var alive = grid[r][c]
var count = 0
for rr in -1...1 {
for cc in -1...1 {
if rr == 0 && cc == 0 {
// Don't count the center cell.
} else {
// Wrap coordinates around the grid edges.
var rrr = (r + rr)
if rrr >= rows {
rrr = rrr - rows
} else if rrr < 0 {
rrr = rrr + rows
}
var ccc = (c + cc)
if ccc >= cols {
ccc = ccc - cols
} else if ccc < 0 {
ccc = ccc + cols
}
count += grid[rrr][ccc]
}
}
}
// Compute the new cell liveness following
// https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
if (alive == 0) {
if (count == 3) {
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
alive = 1
} else {
alive = 0
}
} else {
if (count == 2) || (count == 3) {
// Any live cell with two or three live neighbours lives on to the next generation.
alive = 1
} else {
// Any live cell with fewer than two live neighbours dies, as if caused by under-population.
// Any live cell with more than three live neighbours dies, as if by over-population.
alive = 0
}
}
// Arbitrarily keep the center cell alive always.
if r == rows/2 && c == cols/2 {
alive = 1
}
newgrid[r].append(alive)
}
}
}
func fetchIconList(_ continuation:@escaping ()->()) {
var urlComponents = URLComponents()
urlComponents.scheme = "https";
urlComponents.host = host
urlComponents.path = "/" + bucket + "/icons.txt"
if let url = urlComponents.url {
let request = URLRequest(url:url)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if let error = error {
NSLog("error \(error)")
}
else if let data = data {
DispatchQueue.main.async {
if let content = String.init(data: data, encoding: String.Encoding.utf8) {
self.imageNames = content.components(separatedBy: CharacterSet.whitespacesAndNewlines)
self.imageNames.removeLast()
continuation()
}
}
} else {
DispatchQueue.main.async {
self.imageNames = []
continuation()
}
}
})
task.resume()
}
}
func fetchImage(_ imageView:NSImageView, name:String) {
var urlComponents = URLComponents()
urlComponents.scheme = "https";
urlComponents.host = host
urlComponents.path = "/" + bucket + "/" + name
if let url = urlComponents.url {
let request = URLRequest(url:url)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if let error = error {
NSLog("error \(error)")
}
else if let data = data {
DispatchQueue.main.async {
imageView.image = NSImage(data: data)
}
} else {
NSLog("failed to load \(name)")
DispatchQueue.main.async {
imageView.image = nil;
}
}
})
task.resume()
}
}
}
| fdd7c75a186c468750de2c6c9f091861 | 27.669444 | 105 | 0.536963 | false | false | false | false |
dbruzzone/wishing-tree | refs/heads/master | iOS/Type/Type/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// Type
//
// Created by Davide Bruzzone on 11/29/15.
// Copyright © 2015 Bitwise Samurai. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.bitwisesamurai.Type" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Type", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 4d381cc4d0820411a26cb60049f46af3 | 53.900901 | 291 | 0.71956 | false | false | false | false |
DroidsOnRoids/PhotosHelper | refs/heads/master | Example/PhotosHelper/ViewController.swift | mit | 1 | //
// ViewController.swift
// PhotosHelper
//
// Created by Andrzej Filipowicz on 12/03/2015.
// Copyright (c) 2015 Andrzej Filipowicz. All rights reserved.
//
import UIKit
import AVFoundation
import PhotosHelper
let padding: CGFloat = 10.0
class ViewController: UIViewController {
var captureSession: AVCaptureSession?
var captureLayer: AVCaptureVideoPreviewLayer?
let output = AVCaptureStillImageOutput()
override func viewDidLoad() {
super.viewDidLoad()
setupCamera()
setupUI()
}
func setupUI() {
view.clipsToBounds = true
let captureButton = UIButton()
captureButton.setTitle("take a picture", forState: .Normal)
captureButton.sizeToFit()
captureButton.addTarget(self, action: #selector(ViewController.takePicture(_:)), forControlEvents: .TouchUpInside)
captureButton.center = CGPoint(x: view.frame.midX, y: view.frame.height - captureButton.frame.midY - padding)
view.addSubview(captureButton)
}
func setupCamera() {
captureSession = AVCaptureSession()
guard let captureSession = captureSession else { return }
captureSession.beginConfiguration()
setDeviceInput()
if captureSession.canSetSessionPreset(AVCaptureSessionPresetHigh) {
captureSession.sessionPreset = AVCaptureSessionPresetHigh
}
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
captureLayer = AVCaptureVideoPreviewLayer(session: captureSession)
captureLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
captureLayer?.frame = view.bounds
guard let captureLayer = captureLayer else { return }
view.layer.addSublayer(captureLayer)
captureSession.commitConfiguration()
captureSession.startRunning()
}
private func setDeviceInput(back: Bool = true) {
guard let captureSession = captureSession else { return }
if let input = captureSession.inputs.first as? AVCaptureInput {
captureSession.removeInput(input)
}
let device = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
.filter {$0.position == (back ? .Back : .Front)}
.first as? AVCaptureDevice ?? AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
guard let input = try? AVCaptureDeviceInput(device: device) else { return }
if captureSession.canAddInput(input) {
captureSession.addInput(input)
}
}
func takePicture(sender: AnyObject) {
let connection = output.connectionWithMediaType(AVMediaTypeVideo)
output.captureStillImageAsynchronouslyFromConnection(connection) { [weak self] buffer, error in
guard let `self` = self where error == nil else { return }
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
guard let image = UIImage(data: imageData) else { return }
PhotosHelper.saveImage(image, toAlbum: "Example Album") { success, _ in
guard success else { return }
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Photo taken", message: "Open Photos.app to see that an album with your photo was created.", preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
}
}
| 7a0a0cdf53112e68b4afc2ddf43966be | 35.028302 | 173 | 0.637601 | false | false | false | false |
CodePath2017Group4/travel-app | refs/heads/master | RoadTripPlanner/AlbumCell.swift | mit | 1 | //
// AlbumCell.swift
// RoadTripPlanner
//
// Created by Nanxi Kang on 10/14/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import Parse
class AlbumCell: UITableViewCell {
@IBOutlet weak var albumImage: UIImageView!
@IBOutlet weak var albumLabel: UILabel!
@IBOutlet weak var tripLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var createdByLabel: UILabel!
@IBOutlet weak var deleteViewTrailing: NSLayoutConstraint!
@IBOutlet weak var deleteView: UIView!
var delegate: DeleteAlbumDelegate?
var albumIndex: IndexPath?
var album: Album?
var panRecognizer: UIPanGestureRecognizer?
func displayAlbum(album: Album) {
hideDelete()
if (self.album == nil) {
self.album = Album()
}
self.album!.updated(copyFrom: album)
albumImage.image = UIImage(named: "album-default")
albumImage.contentMode = .scaleAspectFit
if (album.photos.count > 0) {
album.photos[0].getDataInBackground(block: { (data, error) -> Void in
if (error == nil) {
if let data = data {
DispatchQueue.main.async {
self.albumImage.image = UIImage(data: data)
self.albumImage.contentMode = .scaleAspectFill
}
}
}
})
}
albumLabel.text = album.albumName
print("set owner")
if let owner = album.owner {
owner.fetchInBackground(block: { (object, error) in
if error == nil {
DispatchQueue.main.async {
let realOwner = object as! PFUser
self.createdByLabel.text = realOwner.username
}
} else {
log.error("Error fetching album owner: \(error!)")
}
})
}
print("set trip")
if let trip = album.trip {
trip.fetchInBackground(block: { (object, error) in
if error == nil {
DispatchQueue.main.async {
let realTrip = object as! Trip
if let date = realTrip.date {
self.dateLabel.text = Utils.formatDate(date: date)
} else {
self.dateLabel.text = "unknown"
}
self.tripLabel.text = realTrip.name
}
} else {
log.error("Error fetching trip: \(error!)")
}
})
}
}
func hideDelete() {
deleteViewTrailing.constant = -deleteView.frame.width
}
func showDelete() {
deleteViewTrailing.constant = 0
}
override func awakeFromNib() {
super.awakeFromNib()
self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panThisCell))
self.panRecognizer!.delegate = self
self.contentView.addGestureRecognizer(self.panRecognizer!)
}
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@IBAction func panThisCell(_ sender: UIPanGestureRecognizer) {
// Absolute (x,y) coordinates in parent view (parentView should be
// the parent view of the tray)
let point = sender.location(in: self)
if sender.state == .began {
print("Gesture began at: \(point)")
} else if sender.state == .changed {
let velocity = sender.velocity(in: self)
if (velocity.x < 0) {
// LEFT
UIView.animate(withDuration: 0.5, animations: self.showDelete)
} else if (velocity.x > 0){
// RIGHT
UIView.animate(withDuration: 0.5, animations: self.hideDelete)
}
} else if sender.state == .ended {
print("Gesture ended at: \(point)")
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func deleteAlbumTapped(_ sender: Any) {
guard self.delegate != nil && self.album != nil && self.albumIndex != nil else {
return
}
self.delegate!.deleteAlbum(album: self.album!, indexPath: self.albumIndex!)
}
}
| 6f3816805e2aac5a0938e2ba0c035ecd | 32.811594 | 166 | 0.534076 | false | false | false | false |
ibm-bluemix-mobile-services/bluemix-pushnotifications-swift-sdk | refs/heads/master | Sources/PushNotifications.swift | apache-2.0 | 2 | /*
* Copyright 2016 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SimpleHttpClient
/**
The type of callback to send with PushNotifications requests.
*/
public typealias PushNotificationsCompletionHandler = (_ data: Data?,_ status: Int?,_ error: PushNotificationsError?) -> Void
/**
Used to send Push notifications via a IBM Cloud Push Notifications service.
*/
public class PushNotifications {
/// The IBM Cloud region where the Push Notifications service is hosted.
public struct Region {
public static let US_SOUTH = "us-south"
public static let UK = "eu-gb"
public static let SYDNEY = "au-syd"
public static let FRANKFURT = "eu-de"
public static let US_EAST = "us-east"
public static let JP_TOK = "jp-tok"
}
internal var headers = [String: String]()
private var httpResource = HttpResource(schema: "", host: "")
private var httpBulkResource = HttpResource(schema: "", host: "")
private var pushApiKey = ""
private var pushAppRegion = ""
// used to test in test zone and dev zone
public static var overrideServerHost = "";
/**
Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service.
- parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted.
- parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to.
- parameter pushAppSecret: The appSecret credential required for Push Notifications service authorization.
*/
public init(pushRegion: String, pushAppGuid: String, pushAppSecret: String) {
headers = ["appSecret": pushAppSecret, "Content-Type": "application/json"]
if(PushNotifications.overrideServerHost.isEmpty){
var pushHost = pushRegion+".imfpush.cloud.ibm.com"
httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages")
httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk")
}else{
let url = URL(string: PushNotifications.overrideServerHost)
httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages")
httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk")
}
}
/**
Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service.
- parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted.
- parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to.
- parameter pushApiKey: The ApiKey credential required for Push Notifications service authorization.
*/
public init(pushApiKey:String, pushAppGuid: String, pushRegion: String) {
self.pushApiKey = pushApiKey
self.pushAppRegion = pushRegion
if(PushNotifications.overrideServerHost.isEmpty) {
let pushHost = pushRegion+".imfpush.cloud.ibm.com"
httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages")
httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk")
} else {
let url = URL(string: PushNotifications.overrideServerHost)
httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages")
httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk")
}
}
/**
This method will get an iam auth token from the server and add it to the request header. Get Auth token before calling any send methods.
- parameter completionHandler: Returns true if there is token with token string
*/
public func getAuthToken(completionHandler: @escaping (_ hasToken:Bool?, _ tokenValue: String) -> Void) {
if (pushApiKey != "" && pushAppRegion != "") {
var regionString = pushAppRegion;
var pushHost = "iam."
if (!PushNotifications.overrideServerHost.isEmpty) {
let url = URL(string: PushNotifications.overrideServerHost)
let domain = url?.host
if let splitStringArray = domain?.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true) {
regionString = String(splitStringArray[1])
}
pushHost = pushHost + regionString
}
else{
pushHost = pushHost + "cloud.ibm.com"
}
let iamHttpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/identity/token")
var data:Data?
let dataString = "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=\(pushApiKey)"
data = dataString.data(using: .ascii, allowLossyConversion: true)
let iamHeaders = ["Content-Type":"application/x-www-form-urlencoded","Accept":"application/json"]
HttpClient.post(resource: iamHttpResource, headers: iamHeaders, data: data) { (error, status, headers, data) in
//completionHandler?(data,status,PushNotificationsError.from(httpError: error))
if(status == 200) {
let dataJson = try! JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
let tokenString = dataJson["access_token"] as? String
if !(tokenString?.isEmpty)! {
self.headers = ["Authorization": "Bearer " + tokenString!, "Content-Type": "application/json"]
}
completionHandler(true, tokenString!)
} else {
print("Error While getting the token", error ?? "")
completionHandler(false, "")
}
}
} else {
print("Error : Pass valid Apikey and app region")
completionHandler(false, "")
}
}
/**
Send the Push notification.
- parameter notificiation: The push notification to send.
- paramter completionHandler: The callback to be executed when the send request completes.
*/
public func send(notification: Notification, completionHandler: PushNotificationsCompletionHandler?) {
guard let requestBody = notification.jsonFormat else {
completionHandler?(nil,500,PushNotificationsError.InvalidNotification)
return
}
guard let data = try? JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) else{
completionHandler?(nil,500,PushNotificationsError.InvalidNotification)
return
}
HttpClient.post(resource: httpResource, headers: headers, data: data) { (error, status, headers, data) in
completionHandler?(data,status,PushNotificationsError.from(httpError: error))
}
}
/**
Send Bulk Push notification.
- parameter notificiation: Array of push notification payload to send.
- paramter completionHandler: The callback to be executed when the send request completes.
*/
public func sendBulk(notification: [Notification], completionHandler: PushNotificationsCompletionHandler?) {
var dataArray = [[String:Any]]()
for notif in notification {
guard let requestBody = notif.jsonFormat else {
completionHandler?(nil,500,PushNotificationsError.InvalidNotification)
return
}
dataArray.append(requestBody)
}
guard let data = try? JSONSerialization.data(withJSONObject: dataArray, options: .prettyPrinted) else{
completionHandler?(nil,500,PushNotificationsError.InvalidNotification)
return
}
HttpClient.post(resource: httpBulkResource, headers: headers, data: data) { (error, status, headers, data) in
completionHandler?(data,status,PushNotificationsError.from(httpError: error))
}
}
}
| 85c0c6cd7a171d3805b6472aee9268d0 | 45.86 | 155 | 0.636897 | false | false | false | false |
alblue/swift | refs/heads/master | test/Syntax/round_trip_parse_gen.swift | apache-2.0 | 2 | // RUN: rm -rf %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds
// RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds
// RUN: %swift-syntax-test -input-source-filename %s -eof > %t
// RUN: diff -u %s %t
// RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump
// RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t
// RUN: diff -u %s %t
import ABC
import A.B.C
@objc import A.B
@objc import typealias A.B
import struct A.B
#warning("test warning")
#error("test error")
#if Blah
class C {
func bar(_ a: Int) {}
func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 }
func bar2(a: Int, b: Int, c:Int) -> Int { return 1 }
func bar3(a: Int) -> Int { return 1 }
func bar4(_ a: Int) -> Int { return 1 }
func foo() {
var a = /*comment*/"ab\(x)c"/*comment*/
var b = /*comment*/+2/*comment*/
bar(1)
bar(+10)
bar(-10)
bar1(-1.1)
bar1(1.1)
var f = /*comments*/+0.1/*comments*/
foo()
_ = "🙂🤗🤩🤔🤨"
}
func foo1() {
_ = bar2(a:1, b:2, c:2)
_ = bar2(a:1 + 1, b:2 * 2 + 2, c:2 + 2)
_ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3)
_ = bar3(a : bar3(a: bar3(a: 1)))
_ = bar4(bar4(bar4(1)))
_ = [:]
_ = []
_ = [1, 2, 3, 4]
_ = [1:1, 2:2, 3:3, 4:4]
_ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)]
_ = ["a": bar3(a:1), "b": bar3(a:1), "c": bar3(a:1), "d": bar3(a:1)]
foo(nil, nil, nil)
_ = type(of: a).self
_ = A -> B.C<Int>
_ = [(A) throws -> B]()
}
func boolAnd() -> Bool { return true && false }
func boolOr() -> Bool { return true || false }
func foo2() {
_ = true ? 1 : 0
_ = (true ? 1 : 0) ? (true ? 1 : 0) : (true ? 1 : 0)
_ = (1, 2)
_ = (first: 1, second: 2)
_ = (1)
_ = (first: 1)
if !true {
return
}
}
func foo3() {
_ = [Any]()
_ = a.a.a
_ = a.b
_ = 1.a
(1 + 1).a.b.foo
_ = a as Bool || a as! Bool || a as? Bool
_ = a is Bool
_ = self
_ = Self
}
func superExpr() {
_ = super.foo
super.bar()
super[12] = 1
super.init()
}
func implictMember() {
_ = .foo
_ = .foo(x: 12)
_ = .foo { 12 }
_ = .foo[12]
_ = .foo.bar
}
init() {}
@objc private init(a: Int)
init!(a: Int) {}
init?(a: Int) {}
public init(a: Int) throws {}
@objc deinit {}
private deinit {}
internal subscript(x: Int) -> Int { get {} set {} }
subscript() -> Int { return 1 }
var x: Int {
address { fatalError() }
unsafeMutableAddress { fatalError() }
}
}
protocol PP {
associatedtype A
associatedtype B: Sequence
associatedtype C = Int
associatedtype D: Sequence = [Int]
associatedtype E: Sequence = [[Int]] where A.Element : Sequence
private associatedtype F
@objc associatedtype G
}
#endif
#if blah
typealias A = Any
#elseif blahblah
typealias B = (Array<Array<Any>>.Element, x: Int)
#else
typealias C = [Int]
#endif
typealias D = [Int: String]
typealias E = Int?.Protocol
typealias F = [Int]!.Type
typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> ()
typealias H = () rethrows -> ()
typealias I = (A & B<C>) -> C & D
typealias J = inout @autoclosure () -> Int
typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> ()
@objc private typealias T<a,b> = Int
@objc private typealias T<a,b>
class Foo {
let bar: Int
}
class Bar: Foo {
var foo: Int = 42
}
class C<A, B> where A: Foo, B == Bar {}
@available(*, unavailable)
private class C {}
struct foo {
struct foo {
struct foo {
func foo() {
}
}
}
struct foo {}
}
struct foo {
@available(*, unavailable)
struct foo {}
public class foo {
@available(*, unavailable)
@objc(fooObjc)
private static func foo() {}
@objc(fooObjcBar:baz:)
private static func foo(bar: String, baz: Int)
}
}
struct S<A, B, C, @objc D> where A:B, B==C, A : C, B.C == D.A, A.B: C.D {}
private struct S<A, B>: Base where A: B {
private struct S: A, B {}
}
protocol P: class {}
func foo(_ _: Int,
a b: Int = 3 + 2,
_ c: Int = 2,
d _: Int = true ? 2: 3,
@objc e: X = true,
f: inout Int,
g: Int...) throws -> [Int: String] {}
func foo(_ a: Int) throws -> Int {}
func foo( a: Int) rethrows -> Int {}
struct C {
@objc
@available(*, unavailable)
private static override func foo<a, b, c>(a b: Int, c: Int) throws -> [Int] where a==p1, b:p2 { ddd }
func rootView() -> Label {}
static func ==() -> bool {}
static func !=<a, b, c>() -> bool {}
}
@objc
private protocol foo : bar where A==B {}
protocol foo { func foo() }
private protocol foo{}
@objc
public protocol foo where A:B {}
#if blah
func tryfoo() {
try foo()
try! foo()
try? foo()
try! foo().bar().foo().bar()
}
#else
func closure() {
_ = {[weak a,
unowned(safe) self,
b = 3,
unowned(unsafe) c = foo().bar] in
}
_ = {[] in }
_ = { [] a, b, _ -> Int in
return 2
}
_ = { [] (a: Int, b: Int, _: Int) -> Int in
return 2
}
_ = { [] a, b, _ throws -> Int in
return 2
}
_ = { [] (a: Int, _ b: Int) throws -> Int in
return 2
}
_ = { a, b in }
_ = { (a, b) in }
_ = {}
_ = { s1, s2 in s1 > s2 }
_ = { $0 > $1 }
}
#endif
func postfix() {
foo()
foo() {}
foo {}
foo.bar()
foo.bar() {}
foo.bar {}
foo[]
foo[1]
foo[] {}
foo[1] {}
foo[1][2,x:3]
foo?++.bar!(baz).self
foo().0
foo<Int>.bar
foo<Int>()
foo.bar<Int>()
foo(x:y:)()
foo(x:)<Int> { }
_ = .foo(x:y:)
_ = x.foo(x:y:)
_ = foo(&d)
_ = <#Placeholder#> + <#T##(Int) -> Int#>
}
#if blah
#else
#endif
class C {
var a: Int {
@objc mutating set(value) {}
mutating get { return 3 }
@objc didSet {}
willSet(newValue){ }
}
var a : Int {
return 3
}
}
protocol P {
var a: Int { get set }
var a: Int {}
}
private final class D {
@objc
static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int)
let (a, b) = (1,2), _ = 4 {}
func patternTests() {
for let (x, _) in foo {}
for var x: Int in foo {}
}
}
do {
switch foo {
case let a: break
case let a as Int: break
case let (a, b): break
case (let a, var b): break
case is Int: break
case let .bar(x): break
case MyEnum.foo: break
case let a as Int: break
case let a?: break
}
}
func statementTests() {
do {
} catch (var x, let y) {
} catch where false {
} catch let e where e.foo == bar {
} catch {
}
repeat { } while true
LABEL: repeat { } while false
while true { }
LABEL: while true { }
LABEL: do {}
LABEL: switch foo {
case 1:
fallthrough
case 2:
break LABEL
case 3:
break
}
for a in b {
defer { () }
if c {
throw MyError()
continue
} else {
continue LABEL
}
}
if
foo,
let a = foo,
let b: Int = foo,
var c = foo,
case (let v, _) = foo,
case (let v, _): (Int, Int) = foo {
} else if foo {
} else {
}
guard let a = b else {}
for var i in foo where i.foo {}
for case is Int in foo {}
switch Foo {
case n1:
break
case n2, n3l:
break
#if FOO
case let (x, y) where !x, n3l where false:
break
#elseif BAR
case let y:
break
#else
case .foo(let x):
break
#endif
default:
break
}
switch foo {
case 1, 2, 3: break
default: break
}
switch foo {
case 1, 2, 3: break
@unknown default: break
}
switch foo {
case 1, 2, 3: break
@unknown case _: break
}
switch foo {
case 1, 2, 3: break
// This is rejected in Sema, but should be preserved by Syntax.
@unknown case (42, -42) where 1 == 2: break
@garbage case 0: break
@garbage(foobar) case -1: break
}
}
// MARK: - ExtensionDecl
extension ext {
var s: Int {
return 42
}
}
@available(*, unavailable)
fileprivate extension ext {}
extension ext : extProtocol {}
extension ext where A == Int, B: Numeric {}
extension ext.a.b {}
func foo() {
var a = "abc \(foo()) def \(a + b + "a \(3)") gh"
var a = """
abc \( foo() + bar() )
de \(3 + 3 + "abc \(foo()) def")
fg
"""
}
func keypath() {
_ = \a.?.b
_ = \a.b.c
_ = \a.b[1]
_ = \.a.b
_ = \Array<Int>.[]
_ = #keyPath(a.b.c)
}
func objcSelector() {
_ = [
#selector(getter: Foo.bar),
#selector(setter: Foo.Bar.baz),
#selector(Foo.method(x:y:)),
#selector(foo[42].bar(x)),
#selector({ [x] in return nil })
]
}
func objectLiterals() {
#fileLiteral(a)
#colorLiteral(a, b)
#imageLiteral(a, b, c)
#column
#file
#function
#dsohandle
}
enum E1 : String {
case foo = 1
case bar = "test", baz(x: Int, String) = 12
indirect case qux(E1)
indirect private enum E2<T>: String where T: SomeProtocol {
case foo, bar, baz
}
}
precedencegroup FooPrecedence {
higherThan: DefaultPrecedence, UnknownPrecedence
assignment: false
associativity: none
}
precedencegroup BarPrecedence {}
precedencegroup BazPrecedence {
associativity: left
assignment: true
associativity: right
lowerThan: DefaultPrecedence
}
infix operator<++>:FooPrecedence
prefix operator..<<
postfix operator <-
func higherOrderFunc() {
let x = [1,2,3]
x.reduce(0, +)
}
if #available(iOS 11, macOS 10.11.2, *) {}
@_specialize(where T == Int)
@_specialize(exported: true, where T == String)
public func specializedGenericFunc<T>(_ t: T) -> T {
return t
}
protocol Q {
func g()
var x: String { get }
func f(x:Int, y:Int) -> Int
#if FOO_BAR
var conditionalVar: String
#endif
}
struct S : Q, Equatable {
@_implements(Q, f(x:y:))
func h(x:Int, y:Int) -> Int {
return 6
}
@_implements(Equatable, ==(_:_:))
public static func isEqual(_ lhs: S, _ rhs: S) -> Bool {
return false
}
@_implements(P, x)
var y: String
@_implements(P, g())
func h() {}
@available(*, deprecated: 1.2, message: "ABC")
fileprivate(set) var x: String
}
struct ReadModify {
var st0 = ("a", "b")
var rm0: (String, String) {
_read { yield (("a", "b")) }
_modify { yield &st0 }
}
var rm1: (String, String) {
_read { yield (st0) }
}
}
@_alignment(16) public struct float3 { public var x, y, z: Float }
#sourceLocation(file: "otherFile.swift", line: 5)
func foo() {}
#sourceLocation()
"abc \( } ) def"
| e5737f001ed7ee76c6f90245c7b2784b | 17.705357 | 105 | 0.537757 | false | false | false | false |
crossroadlabs/reSwiftInception | refs/heads/master | reSwift/Controllers/TrendingListVC.swift | bsd-3-clause | 1 | //
// TrendingListVC.swift
// reSwift
//
// Created by Roman Stolyarchuk on 10/16/17.
// Copyright © 2017 Crossroad Labs s.r.o. All rights reserved.
//
import UIKit
class TrendingListVC: UIViewController {
@IBOutlet weak var languagesBtn: UIButton!
@IBOutlet weak var segmentFilter: UISegmentedControl!
@IBOutlet weak var trendingTV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
trendingTV.delegate = self
trendingTV.dataSource = self
trendingTV.register(UINib(nibName: "SearchCell", bundle: nil), forCellReuseIdentifier: "SearchCell")
segmentFilter.sendActions(for: .valueChanged)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func segmentedControlAction(sender: UISegmentedControl) {
if(sender.selectedSegmentIndex == 0)
{
print("DAILY")
}
else if(sender.selectedSegmentIndex == 1)
{
print("WEEKLY")
}
else if(sender.selectedSegmentIndex == 2)
{
print("MONTHLY")
}
}
@IBAction func languageBtnAction(sender: UIButton) {
print("Language button pressed")
}
}
extension TrendingListVC: UITableViewDelegate,UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell") as? SearchCell {
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let repoVC = UIStoryboard(name: "Repositories", bundle: nil).instantiateViewController(withIdentifier: "RepositoriesController") as? RepositoriesController {
self.navigationController?.pushViewController(repoVC, animated: true)
}
}
}
| 847bd6c81f808ba04eccccc2ddf4885b | 29.277778 | 168 | 0.654128 | false | false | false | false |
Pacific3/P3UIKit | refs/heads/master | Sources/Extensions/UIImage.swift | mit | 1 | //
// UIImage.swift
// P3UIKit
//
// Created by Oscar Swanros on 6/17/16.
// Copyright © 2016 Pacific3. All rights reserved.
//
#if os(iOS) || os(tvOS)
public typealias P3Image = UIImage
#else
public typealias P3Image = NSImage
#endif
public extension P3Image {
class func p3_fromImageNameConvertible<I: ImageNameConvertible>(imageNameConvertible: I) -> P3Image? {
#if os(iOS) || os(tvOS)
return P3Image(
named: imageNameConvertible.imageName,
in: imageNameConvertible.bundle,
compatibleWith: nil
)
#else
guard let imagePath = imageNameConvertible.bundle.pathForImageResource(imageNameConvertible.imageName) else {
return nil
}
return P3Image(contentsOfFile: imagePath)
#endif
}
}
#if os(iOS) || os(tvOS)
public extension P3Image {
class func p3_imageWithColor(color: P3Color) -> P3Image? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func p3_imageWithColor<C: ColorConvertible>(color: C) -> P3Image? {
return p3_imageWithColor(color: color.color())
}
class func p3_roundedImageWithColor(color: P3Color, size: CGSize) -> P3Image? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let circleBezierPath = UIBezierPath(rect: rect)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
circleBezierPath.fill()
let bezierImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return bezierImage
}
class func p3_roundedImageWithColor<C: ColorConvertible>(color: C, size: CGSize) -> P3Image? {
return p3_roundedImageWithColor(color: color.color(), size: size)
}
class func p3_roundedImageWithColor(color: P3Color) -> P3Image? {
return p3_roundedImageWithColor(color: color, size: CGSize(width: 1, height: 1))
}
class func p3_roundedImageWithColor<C: ColorConvertible>(color: C) -> P3Image? {
return p3_roundedImageWithColor(color: color, size: CGSize(width: 1, height: 1))
}
}
#endif
| 58c689b834c7cacf639404311c8f38ed | 33.580247 | 121 | 0.592288 | false | false | false | false |
IvanVorobei/RateApp | refs/heads/master | SPRateApp - project/SPRateApp/sparrow/ui/controls/buttons/SPLinesCircleButtonsView.swift | mit | 2 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPLinesCircleButtonsView: UIView {
fileprivate var minSpace: CGFloat = 15
var items = [UIButton]()
init(frame: CGRect = CGRect.zero, buttons: [UIButton]) {
super.init(frame: frame)
commonInit()
self.addButtons(buttons)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
func addButtons(_ buttons: [UIButton]) {
for button in buttons {
self.items.append(button)
self.addSubview(button)
}
}
fileprivate func commonInit() {
self.backgroundColor = UIColor.clear
}
override public func layoutSubviews() {
super.layoutSubviews()
let counts: CGFloat = CGFloat(self.items.count)
var sideSize = self.frame.height
var space = (self.frame.width - (sideSize * counts)) / (counts - 1)
if (space < self.minSpace) {
sideSize = (self.frame.width - (self.minSpace * (counts - 1))) / counts
space = self.minSpace
}
var xItemPosition: CGFloat = 0
let yItemPosition: CGFloat = (self.frame.height / 2) - (sideSize / 2)
for view in self.subviews {
view.frame = CGRect.init(
x: xItemPosition,
y: yItemPosition,
width: sideSize,
height: sideSize
)
xItemPosition = xItemPosition + sideSize + space
}
}
}
| 8386e832b8206074392efa68e037bb79 | 35.675676 | 83 | 0.646279 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/Concurrency/TaskSleepDuration.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
@available(SwiftStdlib 5.7, *)
extension Task where Success == Never, Failure == Never {
@available(SwiftStdlib 5.7, *)
internal static func _sleep(
until seconds: Int64, _ nanoseconds: Int64,
tolerance: Duration?,
clock: _ClockID
) async throws {
// Allocate storage for the storage word.
let wordPtr = UnsafeMutablePointer<Builtin.Word>.allocate(capacity: 1)
// Initialize the flag word to "not started", which means the continuation
// has neither been created nor completed.
Builtin.atomicstore_seqcst_Word(
wordPtr._rawValue, SleepState.notStarted.word._builtinWordValue)
do {
// Install a cancellation handler to resume the continuation by
// throwing CancellationError.
try await withTaskCancellationHandler {
let _: () = try await withUnsafeThrowingContinuation { continuation in
while true {
let state = SleepState(loading: wordPtr)
switch state {
case .notStarted:
// The word that describes the active continuation state.
let continuationWord =
SleepState.activeContinuation(continuation).word
// Try to swap in the continuation word.
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
wordPtr._rawValue,
state.word._builtinWordValue,
continuationWord._builtinWordValue)
if !Bool(_builtinBooleanLiteral: won) {
// Keep trying!
continue
}
// Create a task that resumes the continuation normally if it
// finishes first. Enqueue it directly with the delay, so it fires
// when we're done sleeping.
let sleepTaskFlags = taskCreateFlags(
priority: nil, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: false,
addPendingGroupTaskUnconditionally: false)
let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {
onSleepWake(wordPtr)
}
let toleranceSeconds: Int64
let toleranceNanoseconds: Int64
if let components = tolerance?.components {
toleranceSeconds = components.seconds
toleranceNanoseconds = components.attoseconds / 1_000_000_000
} else {
toleranceSeconds = 0
toleranceNanoseconds = -1
}
_enqueueJobGlobalWithDeadline(
seconds, nanoseconds,
toleranceSeconds, toleranceNanoseconds,
clock.rawValue, Builtin.convertTaskToJob(sleepTask))
return
case .activeContinuation, .finished:
fatalError("Impossible to have multiple active continuations")
case .cancelled:
fatalError("Impossible to have cancelled before we began")
case .cancelledBeforeStarted:
// Finish the continuation normally. We'll throw later, after
// we clean up.
continuation.resume()
return
}
}
}
} onCancel: {
onSleepCancel(wordPtr)
}
// Determine whether we got cancelled before we even started.
let cancelledBeforeStarted: Bool
switch SleepState(loading: wordPtr) {
case .notStarted, .activeContinuation, .cancelled:
fatalError("Invalid state for non-cancelled sleep task")
case .cancelledBeforeStarted:
cancelledBeforeStarted = true
case .finished:
cancelledBeforeStarted = false
}
// We got here without being cancelled, so deallocate the storage for
// the flag word and continuation.
wordPtr.deallocate()
// If we got cancelled before we even started, through the cancellation
// error now.
if cancelledBeforeStarted {
throw _Concurrency.CancellationError()
}
} catch {
// The task was cancelled; propagate the error. The "on wake" task is
// responsible for deallocating the flag word and continuation, if it's
// still running.
throw error
}
}
/// Suspends the current task until the given deadline within a tolerance.
///
/// If the task is canceled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
///
/// try await Task.sleep(until: .now + .seconds(3), clock: .continuous)
///
@available(SwiftStdlib 5.7, *)
public static func sleep<C: Clock>(
until deadline: C.Instant,
tolerance: C.Instant.Duration? = nil,
clock: C
) async throws {
try await clock.sleep(until: deadline, tolerance: tolerance)
}
/// Suspends the current task for the given duration on a continuous clock.
///
/// If the task is cancelled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
///
/// try await Task.sleep(for: .seconds(3))
///
/// - Parameter duration: The duration to wait.
@available(SwiftStdlib 5.7, *)
public static func sleep(for duration: Duration) async throws {
try await sleep(until: .now + duration, clock: .continuous)
}
}
| 21ceeb5a60bda6642ebde8ced286c3fe | 36.25625 | 80 | 0.609294 | false | false | false | false |
tscholze/nomster-ios | refs/heads/master | Nomster/RESTLoader.swift | mit | 1 | //
// RESTLoader.swift
// Nomster
//
// Created by Klaus Meyer on 06.03.15.
// Copyright (c) 2015 Tobias Scholze. All rights reserved.
//
import Foundation
class RESTLoader {
let ApiBase = "http://localhost:3000"
func get(ressource: NSString) -> NSArray {
let url: NSURL! = NSURL(string: "\(ApiBase)/\(ressource)")
let data: NSData? = NSData(contentsOfURL: url)
var results: NSArray = NSArray()
if (data != nil) {
results = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
}
return results
}
}
| adcb4e04a3c20fe1ecbdf37d96fff00d | 22.142857 | 140 | 0.632716 | false | false | false | false |
pedrovsn/2reads | refs/heads/master | reads2/reads2/BuscarTableViewController.swift | mit | 1 | //
// BuscarTableViewController.swift
// reads2
//
// Created by Student on 11/29/16.
// Copyright © 2016 Student. All rights reserved.
//
import UIKit
class BuscarTableViewController: UITableViewController {
@IBOutlet var tableViewSearch: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let searchController = UISearchController(searchResultsController: nil)
var filteredLivros = [Livro]()
var livros:[Livro] = [Livro]()
var searchActive : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
self.livros = Livro.getList()
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredLivros = livros.filter { livro in
return livro.titulo!.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredLivros.count
}
return self.livros.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuscarTableViewCell
let livro: Livro
if searchController.active && searchController.searchBar.text != "" {
livro = filteredLivros[indexPath.row]
} else {
livro = livros[indexPath.row]
}
cell.titulo.text = livro.titulo
cell.autor.text = livro.autor
cell.foto.image = UIImage(named: livro.imagem!)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension BuscarTableViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
} | b01d27c135886266e92fa2e07fcb9d5c | 31.986486 | 158 | 0.668101 | false | false | false | false |
mikeash/SwiftObserverSet | refs/heads/master | ObserverSet/ObserverSet.swift | bsd-3-clause | 1 | //
// ObserverSet.swift
// ObserverSet
//
// Created by Mike Ash on 1/22/15.
// Copyright (c) 2015 Mike Ash. All rights reserved.
//
import Foundation
public class ObserverSetEntry<Parameters> {
private weak var object: AnyObject?
private let f: AnyObject -> Parameters -> Void
private init(object: AnyObject, f: AnyObject -> Parameters -> Void) {
self.object = object
self.f = f
}
}
public class ObserverSet<Parameters>: CustomStringConvertible {
// Locking support
private var queue = dispatch_queue_create("com.mikeash.ObserverSet", nil)
private func synchronized(f: Void -> Void) {
dispatch_sync(queue, f)
}
// Main implementation
private var entries: [ObserverSetEntry<Parameters>] = []
public init() {}
public func add<T: AnyObject>(object: T, _ f: T -> Parameters -> Void) -> ObserverSetEntry<Parameters> {
let entry = ObserverSetEntry<Parameters>(object: object, f: { f($0 as! T) })
synchronized {
self.entries.append(entry)
}
return entry
}
public func add(f: Parameters -> Void) -> ObserverSetEntry<Parameters> {
return self.add(self, { ignored in f })
}
public func remove(entry: ObserverSetEntry<Parameters>) {
synchronized {
self.entries = self.entries.filter{ $0 !== entry }
}
}
public func notify(parameters: Parameters) {
var toCall: [Parameters -> Void] = []
synchronized {
for entry in self.entries {
if let object: AnyObject = entry.object {
toCall.append(entry.f(object))
}
}
self.entries = self.entries.filter{ $0.object != nil }
}
for f in toCall {
f(parameters)
}
}
// MARK: CustomStringConvertible
public var description: String {
var entries: [ObserverSetEntry<Parameters>] = []
synchronized {
entries = self.entries
}
let strings = entries.map{
entry in
(entry.object === self
? "\(entry.f)"
: "\(entry.object) \(entry.f)")
}
let joined = strings.joinWithSeparator(", ")
return "\(Mirror(reflecting: self).description): (\(joined))"
}
}
| 86872f04fefce19add486732d10fa6ab | 25.445652 | 108 | 0.548705 | false | false | false | false |
Rdxer/SwiftQRCode | refs/heads/master | Mobile/iOS/Beta/Pods/SwiftQRCode/QRCode/Source/QRCode.swift | apache-2.0 | 3 | //
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
public class QRCode: NSObject, AVCaptureMetadataOutputObjectsDelegate {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// auto remove sub layers when detection completed
var autoRemoveSubLayers: Bool
/// completion call back
var completedCallBack: ((stringValue: String) -> ())?
/// the scan rect, default is the bounds of the scan view, can modify it if need
public var scanFrame: CGRect = CGRectZero
/// init function
///
/// - returns: the scanner object
public override init() {
self.lineWidth = 4
self.strokeColor = UIColor.greenColor()
self.maxDetectedCount = 20
self.autoRemoveSubLayers = false
super.init()
}
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(autoRemoveSubLayers: Bool, lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.greenColor(), maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
self.autoRemoveSubLayers = autoRemoveSubLayers
}
deinit {
if session.running {
session.stopRunning()
}
removeAllLayers()
}
// MARK: - Generate QRCode Image
/// generate image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25) -> UIImage? {
return generateImage(stringValue, avatarImage: avatarImage, avatarScale: avatarScale, color: CIColor(color: UIColor.blackColor()), backColor: CIColor(color: UIColor.whiteColor()))
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor, backColor: CIColor) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransformMakeScale(10, 10)
let transformedImage = qrFilter.outputImage!.imageByApplyingTransform(transform)
let image = UIImage(CIImage: transformedImage)
if avatarImage != nil {
return insertAvatarImage(image, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
// MARK: - Video Scan
/// prepare scan
///
/// - parameter view: the scan view, the preview layer and the drawing layer will be insert into this view
/// - parameter completion: the completion call back
public func prepareScan(view: UIView, completion:(stringValue: String)->()) {
scanFrame = view.bounds
completedCallBack = completion
currentDetectedCount = 0
setupSession()
setupLayers(view)
}
/// start scan
public func startScan() {
if session.running {
print("the capture session is running")
return
}
session.startRunning()
}
/// stop scan
public func stopScan() {
if !session.running {
print("the capture session is running")
return
}
session.stopRunning()
}
func setupLayers(view: UIView) {
drawLayer.frame = view.bounds
view.layer.insertSublayer(drawLayer, atIndex: 0)
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, atIndex: 0)
}
func setupSession() {
if session.running {
print("the capture session is running")
return
}
if !session.canAddInput(videoInput) {
print("can not add input device")
return
}
if !session.canAddOutput(dataOutput) {
print("can not add output device")
return
}
session.addInput(videoInput)
session.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes;
dataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
}
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
clearDrawLayer()
for dataObject in metadataObjects {
if let codeObject = dataObject as? AVMetadataMachineReadableCodeObject,
obj = previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as? AVMetadataMachineReadableCodeObject {
if CGRectContainsRect(scanFrame, obj.bounds) {
if currentDetectedCount++ > maxDetectedCount {
session.stopRunning()
completedCallBack!(stringValue: codeObject.stringValue)
if autoRemoveSubLayers {
removeAllLayers()
}
}
// transform codeObject
drawCodeCorners(previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as! AVMetadataMachineReadableCodeObject)
}
}
}
}
public func removeAllLayers() {
previewLayer.removeFromSuperlayer()
drawLayer.removeFromSuperlayer()
}
func clearDrawLayer() {
if drawLayer.sublayers == nil {
return
}
for layer in drawLayer.sublayers! {
layer.removeFromSuperlayer()
}
}
func drawCodeCorners(codeObject: AVMetadataMachineReadableCodeObject) {
if codeObject.corners.count == 0 {
return
}
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.path = createPath(codeObject.corners).CGPath
drawLayer.addSublayer(shapeLayer)
}
func createPath(points: NSArray) -> UIBezierPath {
let path = UIBezierPath()
var point = CGPoint()
var index = 0
CGPointMakeWithDictionaryRepresentation((points[index++] as! CFDictionary), &point)
path.moveToPoint(point)
while index < points.count {
CGPointMakeWithDictionaryRepresentation((points[index++] as! CFDictionary), &point)
path.addLineToPoint(point)
}
path.closePath()
return path
}
/// previewLayer
lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
return layer
}()
/// drawLayer
lazy var drawLayer = CALayer()
/// session
lazy var session = AVCaptureSession()
/// input
lazy var videoInput: AVCaptureDeviceInput? = {
if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) {
return try? AVCaptureDeviceInput(device: device)
}
return nil
}()
/// output
lazy var dataOutput = AVCaptureMetadataOutput()
} | ef3c2070dd89388db43119c30e4ba7a0 | 33.367347 | 187 | 0.611798 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Analytics/Sources/AnalyticsKit/Providers/Nabu/Model/Context/Screen.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
#if canImport(UIKit)
import UIKit
struct Screen: Encodable {
let width = Double(UIScreen.main.bounds.width)
let height = Double(UIScreen.main.bounds.height)
let density = Double(UIScreen.main.scale)
}
#endif
#if canImport(AppKit)
import AppKit
struct Screen: Encodable {
let width = Double(NSScreen.main!.frame.width)
let height = Double(NSScreen.main!.frame.height)
let density = Double(1)
}
#endif
| d79851545d368188e9fef6685eb57639 | 21.173913 | 62 | 0.729412 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/AssistantV1/Models/Workspace.swift | mit | 2 | /**
* Copyright IBM Corporation 2018
*
* 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
/** Workspace. */
public struct Workspace: Decodable {
/// The name of the workspace.
public var name: String
/// The language of the workspace.
public var language: String
/// The timestamp for creation of the workspace.
public var created: String?
/// The timestamp for the last update to the workspace.
public var updated: String?
/// The workspace ID.
public var workspaceID: String
/// The description of the workspace.
public var description: String?
/// Any metadata related to the workspace.
public var metadata: [String: JSON]?
/// Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
public var learningOptOut: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case language = "language"
case created = "created"
case updated = "updated"
case workspaceID = "workspace_id"
case description = "description"
case metadata = "metadata"
case learningOptOut = "learning_opt_out"
}
}
| 353ef5bca1baeefe05488dc915fdca16 | 31.931034 | 217 | 0.695812 | false | false | false | false |
kazuhiro4949/EditDistance | refs/heads/master | iOS Example/iOS Example/CollectionViewController.swift | mit | 1 | //
// CollectionViewController.swift
//
// Copyright © 2017年 Kazuhiro Hayashi. All rights reserved.
//
import UIKit
import EditDistance
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
var source = [0, 1, 2, 3, 4, 5]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return source.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
return cell
}
@IBAction func rightBarButtonItemDidTap(_ sender: UIBarButtonItem) {
let newSource = Array(0..<Int(arc4random() % 50)).shuffled()
let container = source.diff.compare(to: newSource)
source = Array(newSource)
collectionView?.diff.performBatchUpdates(with: container, completion: nil)
}
}
| 14aa929ad4abfffb8b18c14b95819b03 | 28.043478 | 130 | 0.701347 | false | false | false | false |
1amageek/Toolbar | refs/heads/master | Example/AnimationViewController.swift | mit | 1 | //
// AnimationViewController.swift
// Example
//
// Created by 1amageek on 2018/01/18.
// Copyright © 2018年 Stamp Inc. All rights reserved.
//
import UIKit
class AnimationViewController: UIViewController {
var item0: ToolbarItem?
var item1: ToolbarItem?
var toolbar: Toolbar?
override func viewDidLoad() {
super.viewDidLoad()
let button: UIButton = UIButton(type: .system)
button.setTitle("Animation Button", for: UIControl.State.normal)
self.view.addSubview(button)
button.sizeToFit()
button.center = self.view.center
button.addTarget(self, action: #selector(hide0), for: UIControl.Event.touchUpInside)
let toolbar: Toolbar = Toolbar()
self.view.addSubview(toolbar)
if #available(iOS 11.0, *) {
toolbar.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
toolbar.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 100).isActive = true
} else {
toolbar.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor, constant: 100).isActive = true
}
self.item0 = ToolbarItem(title: "Button", target: nil, action: nil)
self.item1 = ToolbarItem(image: #imageLiteral(resourceName: "instagram"), target: nil, action: nil)
self.item1?.contentSize = CGSize(width: 50, height: 100)
toolbar.setItems([self.item0!, self.item1!], animated: false)
}
@objc func hide0() {
self.item0?.setHidden(!self.item0!.isHidden, animated: true)
}
@objc func hide1() {
self.item0?.setHidden(!self.item1!.isHidden, animated: true)
}
}
| cee307d5d0a0e80d3bc354c709a16fb2 | 33.489796 | 121 | 0.656805 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01922-getselftypeforcontainer.swift | apache-2.0 | 11 | // 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
// RUN: not %target-swift-frontend %s -parse
let x {
var b = 1][Any) -> Self {
f(")) {
let i(x) {
}
let v: A, self.A> Any) -> {
func c] = [unowned self] {
return { self.f == A<B : Any) -> : AnyObject, 3] == {
var d {
}
}
}
}
return z: NSObject {
func x: B, range.<T, U) -> () {
})
}
}
protocol b {
func a
typealias d: a {
| 1e6f387403e75c7ef369a6a7006622ec | 22.068966 | 78 | 0.641256 | false | false | false | false |
GYLibrary/GPRS | refs/heads/master | OznerGPRS/View/WaterPurifierHeadCircleView.swift | mit | 1 | //
// WaterPurifierHeadCircleView.swift
// OzneriFamily
//
// Created by 赵兵 on 2016/10/15.
// Copyright © 2016年 net.ozner. All rights reserved.
//
import UIKit
class WaterPurifierHeadCircleView: UIView {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
private var lastAngle:[CGFloat]=[0,0]//lastAngle=0需要动画,否则不需要动画
private var currentAngle:[CGFloat]=[0,0]
private var currentLayer:[CAGradientLayer]=[]
override func draw(_ rect: CGRect) {
super.draw(rect)
for layer in currentLayer {
layer.removeFromSuperlayer()
}
currentLayer=[]
//第1条背景线
let context=UIGraphicsGetCurrentContext()
context!.setAllowsAntialiasing(true);
context!.setLineWidth(2);
context!.setStrokeColor(UIColor.lightGray.cgColor);
context?.addArc(center: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-5, startAngle: -CGFloat(M_PI), endAngle: 0, clockwise: false)//clockwise顺时针
context!.strokePath()
if currentAngle[0] != 0 {
//第2条背景线
context!.setAllowsAntialiasing(true);
context!.setLineWidth(2);
context!.setStrokeColor(UIColor(white: 1, alpha: 0.8).cgColor);
context?.addArc(center: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-20, startAngle: -CGFloat(M_PI), endAngle: 0, clockwise: false)//clockwise顺时针
context!.strokePath()
}
//TDS线
for i in 0...1 {
let shapeLayer=CAShapeLayer()
shapeLayer.path=UIBezierPath(arcCenter: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-5-CGFloat(i*15), startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI)+CGFloat(M_PI)*currentAngle[i], clockwise: true).cgPath
shapeLayer.lineCap="round"//圆角
shapeLayer.lineWidth=10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.purple.cgColor
if lastAngle[i] == 0 {
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.duration = 5.0;
drawAnimation.repeatCount = 0;
drawAnimation.isRemovedOnCompletion = false;
drawAnimation.fromValue = 0;
drawAnimation.toValue = 10;
drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
shapeLayer.add(drawAnimation, forKey: "drawCircleAnimation")
}
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = [
UIColor(colorLiteralRed: 9.0/255, green: 142.0/255, blue: 254.0/255, alpha: 1.0).cgColor,
UIColor(colorLiteralRed: 134.0/255, green: 102.0/255, blue: 255.0/255, alpha: 1.0).cgColor,
UIColor(colorLiteralRed: 215.0/255, green: 67.0/255, blue: 113.0/255, alpha: 1.0).cgColor
];
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.mask=shapeLayer
currentLayer.append(gradientLayer)
self.layer.addSublayer(gradientLayer)
}
lastAngle=currentAngle
}
func updateCircleView(angleBefore:CGFloat,angleAfter:CGFloat){
currentAngle=[angleBefore,angleAfter]
if currentAngle != lastAngle {
self.setNeedsDisplay()
}
}
}
| 0681666fcfb9a023100d1f56b3d18092 | 40.988764 | 255 | 0.610918 | false | false | false | false |
darthpelo/DARCartList | refs/heads/master | DARCartList/ViewController.swift | mit | 1 | //
// ViewController.swift
// DARCartList
//
// Created by Alessio Roberto on 19/02/15.
// Copyright (c) 2015 Alessio Roberto. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "ProductCell"
private var listResult = [Product]()
private var selectedProduct: Product?
func productForIndexPath(indexPath: NSIndexPath) -> Product {
return listResult[indexPath.row]
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Cart"
requestCartList()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func showAlert() {
let alertController = UIAlertController(title: "Attention", message: "Connection error occurred", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
println(action)
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: { () -> Void in
})
}
private func requestCartList() {
DARCartListAPI.sharedInstance.requestCartItems().continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock: {
(task) -> AnyObject! in
if (task.error() != nil) {
self.showAlert()
} else {
self.listResult = task.result() as! [(Product)]
self.collectionView?.reloadData()
}
return nil
})
}
@IBAction func refreshList(sender: UIBarButtonItem) {
// TODO: add pull to refresh function to the CollectionView
requestCartList()
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ProductDetailSegue" {
let detail = segue.destinationViewController as! DARProductDetailViewController
detail.product = selectedProduct
}
}
// MARK: UICollectionView
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listResult.count
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var cellSize: CGSize;
let collectionViewWidth = collectionView.frame.size.width;
let newCellWidth = collectionViewWidth / 2
cellSize = CGSizeMake(newCellWidth - 1.0, newCellWidth - 1.0);
return cellSize;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// TODO: improve CollectionViewCell cache managment
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ProductCell
let product = productForIndexPath(indexPath)
cell.activityIndicator.stopAnimating()
cell.productNameLabel.text = product.name
let price = product.price / 100
cell.productPriceLabel.text = "\(price)€"
if product.image != nil {
cell.productImage.image = product.image
return cell
}
cell.activityIndicator.startAnimating()
product.loadImage { (productPhoto, error) -> Void in
cell.activityIndicator.stopAnimating()
if error != nil {
return
}
if productPhoto.image == nil {
return
}
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ProductCell {
cell.productImage.image = product.image
}
}
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedProduct = self.productForIndexPath(indexPath)
self.performSegueWithIdentifier("ProductDetailSegue", sender: self)
}
}
| 8872fee8b32f29f295608afbea3fe5ca | 31.9375 | 139 | 0.616066 | false | false | false | false |
cathy810218/onebusaway-iphone | refs/heads/develop | OneBusAway/ui/onboarding/OnboardingViewController.swift | apache-2.0 | 1 | //
// OnboardingViewController.swift
// org.onebusaway.iphone
//
// Created by Aaron Brethorst on 4/3/17.
// Copyright © 2017 OneBusAway. All rights reserved.
//
import PMKCoreLocation
import UIKit
import SnapKit
@objc protocol OnboardingDelegate {
func onboardingControllerRequestedAuthorization(_ onboardingController: OnboardingViewController)
}
@objc class OnboardingViewController: UIViewController {
let stackView = UIStackView.init()
@objc weak var delegate: OnboardingDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("onboarding_controller.title", comment: "Title of the Onboarding Controller. 'Welcome to OneBusAway!'")
self.view.backgroundColor = UIColor.white
self.stackView.axis = .vertical
self.stackView.spacing = OBATheme.defaultPadding
let imageView = UIImageView.init(image: #imageLiteral(resourceName: "infoheader"))
imageView.contentMode = .scaleAspectFit
let topView = UIView.init()
self.stackView.addArrangedSubview(topView)
topView.backgroundColor = OBATheme.obaGreen
topView.clipsToBounds = true
topView.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.left.right.equalToSuperview()
make.bottom.equalToSuperview().offset(-OBATheme.defaultPadding)
}
topView.snp.makeConstraints { make in
make.height.equalTo(160)
}
let titleLabel = UILabel.init()
titleLabel.textAlignment = .center
titleLabel.text = self.title
titleLabel.font = OBATheme.subtitleFont
self.stackView.addArrangedSubview(titleLabel)
let bodyTextView = UITextView.init()
self.stackView.addArrangedSubview(bodyTextView)
bodyTextView.text = NSLocalizedString("onboarding_controller.body_text", comment: "Body text of the Onboarding Controller.")
bodyTextView.isSelectable = false
bodyTextView.isEditable = false
bodyTextView.textAlignment = .left
bodyTextView.font = OBATheme.bodyFont
bodyTextView.snp.makeConstraints { make in
make.left.equalTo(OBATheme.defaultMargin)
make.right.equalTo(-OBATheme.defaultMargin)
}
let button = UIButton.init()
button.setTitleColor(OBATheme.obaGreen, for: .normal)
button.addTarget(self, action: #selector(showLocationPrompt), for: .touchUpInside)
self.stackView.addArrangedSubview(button)
button.setTitle(NSLocalizedString("onboarding_controller.request_location_permissions_button", comment: "Bottom button on the Onboarding Controller"), for: .normal)
button.titleLabel?.font = OBATheme.titleFont
button.snp.makeConstraints { make in
make.height.greaterThanOrEqualTo(44)
make.width.equalToSuperview()
}
self.view.addSubview(self.stackView)
self.stackView.snp.makeConstraints { make in
make.top.right.left.equalToSuperview()
make.bottom.equalToSuperview().offset(-60)
}
}
@objc func showLocationPrompt() {
self.delegate?.onboardingControllerRequestedAuthorization(self)
}
}
| 3feedf24e6297e5e3b3a06e16c485ae9 | 36.709302 | 172 | 0.694727 | false | false | false | false |
regexident/Gestalt | refs/heads/master | GestaltDemo/Views/StageDesignView.swift | mpl-2.0 | 1 | //
// StageDesignView.swift
// GestaltDemo
//
// Created by Vincent Esche on 5/15/18.
// Copyright © 2018 Vincent Esche. All rights reserved.
//
import UIKit
import Gestalt
@IBDesignable
class StageDesignView: UIView {
@IBOutlet private var lightView: UIImageView?
@IBOutlet private var fixtureView: UIImageView?
@IBOutlet private var shadowView: UIImageView?
override func awakeFromNib() {
super.awakeFromNib()
self.observe(theme: \ApplicationTheme.custom.stageDesign)
}
}
extension StageDesignView: Themeable {
typealias Theme = StageDesignViewTheme
func apply(theme: Theme) {
UIView.performWithoutAnimation {
self.backgroundColor = theme.backgroundColor
self.shadowView?.layer.opacity = theme.shadowOpacity
}
UIView.animate(withDuration: 5.0, animations: {
self.lightView?.layer.opacity = theme.lightOpacity
})
self.lightView?.image = theme.lightImage
self.fixtureView?.image = theme.fixtureImage
self.shadowView?.image = theme.shadowImage
}
}
| 59fe3bf0ba49c696f1d423bb156a2182 | 24.767442 | 65 | 0.6787 | false | false | false | false |
Hearsayer/YLCycleScrollView | refs/heads/master | Source/YLCycleScrollView.swift | mit | 1 | //
// YLCycleScrollView.swift
// YLCycleScrollView
//
// Created by he on 2017/4/7.
// Copyright © 2017年 he. All rights reserved.
//
import UIKit
import Kingfisher
@objc public protocol CycleScrollViewDelegate {
func cycleScrollView(_ cycleScrollView: YLCycleScrollView, didTap index: Int, data: YLCycleModel)
}
public enum IndicatiorPositionType {
case right
case middle
case left
}
let margin: CGFloat = 10
let indicatorWidth: CGFloat = 120
let indicatorHeight: CGFloat = 30
public class YLCycleScrollView: UIView {
/// 代理
public weak var delegate: CycleScrollViewDelegate?
/// 图片内容模式
public var imageContentMode: UIViewContentMode = .scaleToFill {
didSet {
for imageView in imageViews {
imageView.contentMode = imageContentMode
}
}
}
/// 占位图片(用来当iamgeView还没将图片显示出来时,显示的图片)
public var placeholderImage: UIImage? {
didSet {
resetImageViewSource()
}
}
/// 数据源,URL字符串
public var dataSource : [YLCycleModel]? {
didSet {
guard let dataSource = dataSource, dataSource.count > 0 else { return }
resetImageViewSource()
//设置页控制器
configurePageController()
}
}
/// 滚动间隔时间,默认3秒
public var intervalTime: TimeInterval = 3 {
didSet {
invalidate()
configureAutoScrollTimer(intervalTime)
}
}
/// 分页控件位置
public var indicatiorPosition: IndicatiorPositionType = .middle {
didSet {
for imageView in scrollerView.subviews as! [YLCycleImageView] {
switch indicatiorPosition {
case .left:
imageView.textLabelPosition = .right
case .middle:
imageView.textLabelPosition = .none
case .right:
imageView.textLabelPosition = .left
}
}
switch indicatiorPosition {
case .left:
pageControl.frame = CGRect(x: margin, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight)
case .right:
pageControl.frame = CGRect(x: scrollerViewWidth - indicatorWidth - margin, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight)
case .middle:
pageControl.frame = CGRect(x: (scrollerViewWidth - indicatorWidth) * 0.5, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight)
}
}
}
/// 分页控件圆点颜色
public var pageIndicatorTintColor: UIColor? {
didSet {
pageControl.pageIndicatorTintColor = pageIndicatorTintColor
}
}
/// 分页控件当前圆点颜色
public var currentPageIndicatorTintColor: UIColor? {
didSet {
pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor
}
}
/// 是否显示底部阴影栏
public var isShowDimBar: Bool = false {
didSet {
for view in scrollerView.subviews as! [YLCycleImageView] {
view.isShowDimBar = isShowDimBar
}
}
}
/// 当前展示的图片索引
fileprivate var currentIndex : Int = 0
/// 图片辅助属性,把传进来的URL字符串转成URL对象
// fileprivate lazy var imagesURL = [URL]()
/// 用于轮播的左中右三个image(不管几张图片都是这三个imageView交替使用)
fileprivate lazy var leftImageView: YLCycleImageView = YLCycleImageView()
fileprivate lazy var middleImageView: YLCycleImageView = YLCycleImageView()
fileprivate lazy var rightImageView: YLCycleImageView = YLCycleImageView()
fileprivate var imageViews: [YLCycleImageView] {
return [leftImageView, middleImageView, rightImageView]
}
/// 放置imageView的滚动视图
private lazy var scrollerView = UIScrollView()
/// scrollView的宽
fileprivate var scrollerViewWidth: CGFloat = 0
/// scrollView的高
fileprivate var scrollerViewHeight: CGFloat = 0
/// 页控制器(小圆点)
fileprivate lazy var pageControl = UIPageControl()
/// 自动滚动计时器
fileprivate var autoScrollTimer: Timer?
public init(frame: CGRect, placeholder: UIImage? = nil) {
super.init(frame: frame)
scrollerViewWidth = frame.size.width
scrollerViewHeight = frame.size.height
//设置scrollerView
configureScrollerView()
//设置加载指示图片
// configurePlaceholder(placeholder)
//设置imageView
configureImageView()
//设置自动滚动计时器
configureAutoScrollTimer()
backgroundColor = UIColor.black
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 设置scrollerView
private func configureScrollerView(){
scrollerView.frame = CGRect(x: 0,y: 0, width: scrollerViewWidth, height: scrollerViewHeight)
// scrollerView.backgroundColor = UIColor.red
scrollerView.delegate = self
scrollerView.contentSize = CGSize(width: scrollerViewWidth * 3, height: 0)
//滚动视图内容区域向左偏移一个view的宽度
scrollerView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0)
scrollerView.showsVerticalScrollIndicator = false
scrollerView.showsHorizontalScrollIndicator = false
scrollerView.isPagingEnabled = true
scrollerView.bounces = false
addSubview(scrollerView)
}
/// 设置占位图片图片
// private func configurePlaceholder(_ placeholder: UIImage?){
// //这里使用ImageHelper将文字转换成图片,作为加载指示符
// if placeholder == nil {
//
// let font = UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightMedium)
// let size = CGSize(width: scrollerViewWidth, height: scrollerViewHeight)
// placeholderImage = UIImage(text: "图片加载中...", font:font, color:UIColor.white, size:size)!
// } else {
// placeholderImage = placeholder
// }
// }
/// 设置imageView
func configureImageView(){
for (i, imageView) in imageViews.enumerated() {
imageView.frame = CGRect(x: CGFloat(i) * scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight)
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:))))
scrollerView.addSubview(imageView)
}
// leftImageView.frame = CGRect(x: 0, y: 0, width: scrollerViewWidth, height: scrollerViewHeight)
// middleImageView.frame = CGRect(x: scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight)
// rightImageView.frame = CGRect(x: 2 * scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight)
//
//设置初始时左中右三个imageView的图片(分别时数据源中最后一张,第一张,第二张图片)
resetImageViewSource()
// scrollerView.addSubview(leftImageView)
// scrollerView.addSubview(middleImageView)
// scrollerView.addSubview(rightImageView)
// leftImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:))))
// middleImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:))))
// rightImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:))))
}
@objc private func imageTap(tap: UITapGestureRecognizer) {
if dataSource != nil && dataSource!.count > 0 && currentIndex < dataSource!.count {
delegate?.cycleScrollView(self, didTap: currentIndex, data: dataSource![currentIndex])
}
}
/// 设置页控制器
private func configurePageController() {
pageControl.frame = CGRect(x: (scrollerViewWidth - indicatorWidth) * 0.5, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight)
pageControl.numberOfPages = dataSource?.count ?? 0
pageControl.isUserInteractionEnabled = false
addSubview(pageControl)
}
/// 设置自动滚动计时器
fileprivate func configureAutoScrollTimer(_ time: TimeInterval = 3) {
autoScrollTimer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(letItScroll), userInfo: nil, repeats: true)
}
fileprivate func invalidate() {
autoScrollTimer?.invalidate()
autoScrollTimer = nil
}
/// 计时器时间一到,滚动一张图片
@objc fileprivate func letItScroll(){
let offset = CGPoint(x: 2 * scrollerViewWidth, y: 0)
scrollerView.setContentOffset(offset, animated: true)
}
/// 每当滚动后重新设置各个imageView的图片
fileprivate func resetImageViewSource() {
guard let dataSource = dataSource, dataSource.count > 0 else { return }
let first = dataSource.first
let last = dataSource.last
//当前显示的是第一张图片
if currentIndex == 0 {
setupImageView(leftImageView, image: last?.url, text: last?.text)
setupImageView(middleImageView, image: first?.url, text: first?.text)
let rightImageIndex = (dataSource.count) > 1 ? 1 : 0 //保护
setupImageView(rightImageView, image: dataSource[rightImageIndex].url, text: dataSource[rightImageIndex].text)
}
//当前显示的是最好一张图片
else if currentIndex == dataSource.count - 1 {
setupImageView(leftImageView, image: dataSource[currentIndex - 1].url, text: dataSource[currentIndex - 1].text)
setupImageView(middleImageView, image: last?.url, text: last?.text)
setupImageView(rightImageView, image: first?.url, text: first?.text)
}
//其他情况
else{
setupImageView(leftImageView, image: dataSource[currentIndex-1].url, text: dataSource[currentIndex-1].text)
setupImageView(middleImageView, image: dataSource[currentIndex].url, text: dataSource[currentIndex].text)
setupImageView(rightImageView, image: dataSource[currentIndex+1].url, text: dataSource[currentIndex+1].text)
}
}
private func setupImageView(_ imageView: YLCycleImageView, image: URL?, text: String?) {
imageView.kf.setImage(with: image, placeholder: placeholderImage, options: [.transition(.fade(1))])
imageView.text = text
}
}
// MARK: - UIScrollViewDelegate
extension YLCycleScrollView: UIScrollViewDelegate {
// 自动滚动
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
guard let dataSource = dataSource, dataSource.count > 0 else { return }
//获取当前偏移量
let offset = scrollView.contentOffset.x
//如果向左滑动(显示下一张)
if (offset >= scrollerViewWidth * 2) {
//还原偏移量
scrollView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0)
//视图索引+1
currentIndex = currentIndex + 1
if currentIndex == dataSource.count { currentIndex = 0 }
}
//如果向右滑动(显示上一张)
if offset <= 0 {
//还原偏移量
scrollView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0)
//视图索引-1
currentIndex = currentIndex - 1
if currentIndex == -1 { currentIndex = dataSource.count - 1 }
}
//重新设置各个imageView的图片
resetImageViewSource()
//设置页控制器当前页码
pageControl.currentPage = currentIndex
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating(scrollView)
}
//手动拖拽滚动开始
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating(scrollView)
//使自动滚动计时器失效(防止用户手动移动图片的时候这边也在自动滚动)
invalidate()
}
//手动拖拽滚动结束
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//重新启动自动滚动计时器
configureAutoScrollTimer()
scrollViewWillBeginDecelerating(scrollView)
}
}
| d60e39de7d1730d9c777f0310ad494c3 | 33.911357 | 179 | 0.619773 | false | false | false | false |
HTWDD/HTWDresden-iOS | refs/heads/develop | HTWDD/Core/Base Classes/DataSource/ErrorViews.swift | gpl-2.0 | 2 | //
// ErrorCell.swift
// HTWDD
//
// Created by Benjamin Herzog on 04/03/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
/// Use to display an error in the collection view.
class ErrorCollectionCell: CollectionViewCell {
/// Setting the error String will replace the labels string with the given one.
var error: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
private let label = UILabel()
override func initialSetup() {
self.contentView.backgroundColor = .red
self.label.frame = self.contentView.bounds
self.label.textColor = .white
self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.label.numberOfLines = 0
self.label.font = UIFont.systemFont(ofSize: 10)
self.contentView.add(self.label)
}
}
class ErrorSupplementaryView: CollectionReusableView {
/// Setting the error String will replace the labels string with the given one.
var error: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
private let label = UILabel()
override func initialSetup() {
self.backgroundColor = .red
self.label.frame = self.bounds
self.label.textColor = .white
self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.label.numberOfLines = 0
self.label.font = UIFont.systemFont(ofSize: 10)
self.add(self.label)
}
}
class ErrorTableCell: TableViewCell {
/// Setting the error String will replace the labels string with the given one.
var error: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
private let label = UILabel()
override func initialSetup() {
self.contentView.backgroundColor = .red
self.label.frame = self.contentView.bounds
self.label.textColor = .white
self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.label.numberOfLines = 0
self.label.font = UIFont.systemFont(ofSize: 10)
self.contentView.add(self.label)
}
}
| 93210be0314e114c6561dee55923d59a | 25.337209 | 83 | 0.618543 | false | false | false | false |
yoonapps/QPXExpressWrapper | refs/heads/master | QPXExpressWrapper/Classes/TripsDataAirport.swift | mit | 1 | //
// TripsDataAirport.swift
// Flights
//
// Created by Kyle Yoon on 3/5/16.
// Copyright © 2016 Kyle Yoon. All rights reserved.
//
import Foundation
import Gloss
public struct TripsDataAirport: Decodable {
public let kind: String?
public let code: String?
public let city: String?
public let name: String?
public init?(json: JSON) {
guard let kind: String = "kind" <~~ json else {
return nil
}
self.kind = kind
self.code = "code" <~~ json
self.city = "city" <~~ json
self.name = "name" <~~ json
}
}
//TODO: Equatable protocol
extension TripsDataAirport: Equatable {}
public func ==(lhs: TripsDataAirport, rhs: TripsDataAirport) -> Bool {
return lhs.kind == rhs.kind &&
lhs.code == rhs.code &&
lhs.city == rhs.city &&
lhs.name == rhs.name
}
| 79759f3e6ed9bf17566668b24a23a2a5 | 20.95 | 70 | 0.58656 | false | false | false | false |
lotpb/iosSQLswift | refs/heads/master | mySQLswift/LeadUserController.swift | gpl-2.0 | 1 | //
// LeadUserController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/2/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Parse
class LeadUserController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cellHeadtitle = UIFont.systemFontOfSize(20, weight: UIFontWeightBold)
let cellHeadsubtitle = UIFont.systemFontOfSize(18, weight: UIFontWeightLight)
let cellHeadlabel = UIFont.systemFontOfSize(18, weight: UIFontWeightRegular)
let ipadtitle = UIFont.systemFontOfSize(20, weight: UIFontWeightRegular)
let ipadsubtitle = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let ipadlabel = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let cellsubtitle = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let celllabel = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let headtitle = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
@IBOutlet weak var tableView: UITableView?
var _feedItems : NSMutableArray = NSMutableArray()
var _feedheadItems : NSMutableArray = NSMutableArray()
var filteredString : NSMutableArray = NSMutableArray()
var objects = [AnyObject]()
var pasteBoard = UIPasteboard.generalPasteboard()
var refreshControl: UIRefreshControl!
var emptyLabel : UILabel?
var objectId : NSString?
var leadDate : NSString?
var postBy : NSString?
var comments : NSString?
var formController : NSString?
//var selectedImage : UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle(formController as? String, forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.estimatedRowHeight = 110
self.tableView!.rowHeight = UITableViewAutomaticDimension
self.tableView!.backgroundColor = UIColor.whiteColor()
tableView!.tableFooterView = UIView(frame: .zero)
self.automaticallyAdjustsScrollViewInsets = false
self.parseData()
//self.selectedImage = UIImage(named:"profile-rabbit-toy.png")
if (self.formController == "Blog") {
self.comments = "90 percent of my picks made $$$. The stock whisper has traded over 1000 traders worldwide"
}
let shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector())
let buttons:NSArray = [shareButton]
self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem]
self.refreshControl = UIRefreshControl()
refreshControl.backgroundColor = UIColor.clearColor()
refreshControl.tintColor = UIColor.blackColor()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: #selector(LeadUserController.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView!.addSubview(refreshControl)
emptyLabel = UILabel(frame: self.view.bounds)
emptyLabel!.textAlignment = NSTextAlignment.Center
emptyLabel!.textColor = UIColor.lightGrayColor()
emptyLabel!.text = "You have no customer data :)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//navigationController?.hidesBarsOnSwipe = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor(white:0.45, alpha:1.0)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//navigationController?.hidesBarsOnSwipe = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - refresh
func refreshData(sender:AnyObject)
{
self.tableView!.reloadData()
self.refreshControl?.endRefreshing()
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return _feedItems.count ?? 0
}
//return foundUsers.count
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
if tableView == self.tableView {
cellIdentifier = "Cell"
} else {
cellIdentifier = "UserFoundCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! CustomTableCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.blogsubtitleLabel!.textColor = UIColor.grayColor()
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
cell.blogtitleLabel!.font = ipadtitle
cell.blogsubtitleLabel!.font = ipadsubtitle
cell.blogmsgDateLabel!.font = ipadlabel
cell.commentLabel!.font = ipadlabel
} else {
cell.blogtitleLabel!.font = Font.celltitle
cell.blogsubtitleLabel!.font = cellsubtitle
cell.blogmsgDateLabel!.font = celllabel
cell.commentLabel!.font = celllabel
}
let dateStr : String
let dateFormatter = NSDateFormatter()
if (self.formController == "Blog") {
dateStr = (_feedItems[indexPath.row] .valueForKey("MsgDate") as? String)!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
} else {
dateStr = (_feedItems[indexPath.row] .valueForKey("Date") as? String)!
dateFormatter.dateFormat = "yyyy-MM-dd"
}
let date:NSDate = dateFormatter.dateFromString(dateStr)as NSDate!
dateFormatter.dateFormat = "MMM dd, yyyy"
if (self.formController == "Blog") {
cell.blogtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("PostBy") as? String
cell.blogsubtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("Subject") as? String
cell.blogmsgDateLabel!.text = dateFormatter.stringFromDate(date)as String!
var CommentCount:Int? = _feedItems[indexPath.row] .valueForKey("CommentCount")as? Int
if CommentCount == nil {
CommentCount = 0
}
cell.commentLabel?.text = "\(CommentCount!)"
} else {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
cell.blogtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("LastName") as? String
cell.blogsubtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("City") as? String
cell.blogmsgDateLabel!.text = dateFormatter.stringFromDate(date)as String!
var CommentCount:Int? = _feedItems[indexPath.row] .valueForKey("Amount")as? Int
if CommentCount == nil {
CommentCount = 0
}
cell.commentLabel?.text = formatter.stringFromNumber(CommentCount!)
}
cell.actionBtn.tintColor = UIColor.lightGrayColor()
let imagebutton : UIImage? = UIImage(named:"Upload50.png")!.imageWithRenderingMode(.AlwaysTemplate)
cell.actionBtn .setImage(imagebutton, forState: .Normal)
//actionBtn .addTarget(self, action: "shareButton:", forControlEvents: UIControlEvents.TouchUpInside)
cell.replyButton.tintColor = UIColor.lightGrayColor()
let replyimage : UIImage? = UIImage(named:"Commentfilled.png")!.imageWithRenderingMode(.AlwaysTemplate)
cell.replyButton .setImage(replyimage, forState: .Normal)
//cell.replyButton .addTarget(self, action: "replyButton:", forControlEvents: UIControlEvents.TouchUpInside)
if !(cell.commentLabel.text! == "0") {
cell.commentLabel.textColor = UIColor.lightGrayColor()
} else {
cell.commentLabel.text! = ""
}
if (cell.commentLabel.text! == "") {
cell.replyButton.tintColor = UIColor.lightGrayColor()
} else {
cell.replyButton.tintColor = UIColor.redColor()
}
let myLabel:UILabel = UILabel(frame: CGRectMake(10, 10, 50, 50))
if (self.formController == "Leads") {
myLabel.text = "Cust"
} else if (self.formController == "Customer") {
myLabel.text = "Lead"
} else if (self.formController == "Blog") {
myLabel.text = "Blog"
}
myLabel.backgroundColor = UIColor(red: 0.02, green: 0.75, blue: 1.0, alpha: 1.0)
myLabel.textColor = UIColor.whiteColor()
myLabel.textAlignment = NSTextAlignment.Center
myLabel.layer.masksToBounds = true
myLabel.font = headtitle
myLabel.layer.cornerRadius = 25.0
myLabel.userInteractionEnabled = true
cell.addSubview(myLabel)
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 180.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vw = UIView()
vw.backgroundColor = UIColor(white:0.90, alpha:1.0)
//tableView.tableHeaderView = vw
let myLabel4:UILabel = UILabel(frame: CGRectMake(10, 70, self.tableView!.frame.size.width-20, 50))
let myLabel5:UILabel = UILabel(frame: CGRectMake(10, 105, self.tableView!.frame.size.width-20, 50))
let myLabel6:UILabel = UILabel(frame: CGRectMake(10, 140, self.tableView!.frame.size.width-20, 50))
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
myLabel4.font = cellHeadtitle
myLabel5.font = cellHeadsubtitle
myLabel6.font = cellHeadlabel
} else {
myLabel4.font = cellHeadtitle
myLabel5.font = cellHeadsubtitle
myLabel6.font = cellHeadlabel
}
let myLabel1:UILabel = UILabel(frame: CGRectMake(10, 15, 50, 50))
myLabel1.numberOfLines = 0
myLabel1.backgroundColor = UIColor.whiteColor()
myLabel1.textColor = UIColor.blackColor()
myLabel1.textAlignment = NSTextAlignment.Center
myLabel1.layer.masksToBounds = true
myLabel1.text = String(format: "%@%d", "Count\n", _feedItems.count)
myLabel1.font = headtitle
myLabel1.layer.cornerRadius = 25.0
myLabel1.userInteractionEnabled = true
vw.addSubview(myLabel1)
let separatorLineView1 = UIView(frame: CGRectMake(10, 75, 50, 2.5))
separatorLineView1.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView1)
let myLabel2:UILabel = UILabel(frame: CGRectMake(80, 15, 50, 50))
myLabel2.numberOfLines = 0
myLabel2.backgroundColor = UIColor.whiteColor()
myLabel2.textColor = UIColor.blackColor()
myLabel2.textAlignment = NSTextAlignment.Center
myLabel2.layer.masksToBounds = true
myLabel2.text = String(format: "%@%d", "Active\n", _feedheadItems.count)
myLabel2.font = headtitle
myLabel2.layer.cornerRadius = 25.0
myLabel2.userInteractionEnabled = true
vw.addSubview(myLabel2)
let separatorLineView2 = UIView(frame: CGRectMake(80, 75, 50, 2.5))
separatorLineView2.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView2)
let myLabel3:UILabel = UILabel(frame: CGRectMake(150, 15, 50, 50))
myLabel3.numberOfLines = 0
myLabel3.backgroundColor = UIColor.whiteColor()
myLabel3.textColor = UIColor.blackColor()
myLabel3.textAlignment = NSTextAlignment.Center
myLabel3.layer.masksToBounds = true
myLabel3.text = "Active"
myLabel3.font = headtitle
myLabel3.layer.cornerRadius = 25.0
myLabel3.userInteractionEnabled = true
vw.addSubview(myLabel3)
myLabel4.numberOfLines = 1
myLabel4.backgroundColor = UIColor.clearColor()
myLabel4.textColor = UIColor.blackColor()
myLabel4.layer.masksToBounds = true
myLabel4.text = self.postBy as? String
vw.addSubview(myLabel4)
myLabel5.numberOfLines = 0
myLabel5.backgroundColor = UIColor.clearColor()
myLabel5.textColor = UIColor.blackColor()
myLabel5.layer.masksToBounds = true
myLabel5.text = self.comments as? String
vw.addSubview(myLabel5)
if (self.formController == "Leads") || (self.formController == "Customer") {
var dateStr = self.leadDate as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date:NSDate = dateFormatter.dateFromString(dateStr!) as NSDate!
dateFormatter.dateFormat = "MMM dd, yyyy"
dateStr = dateFormatter.stringFromDate(date)as String!
var newString6 : String
if (self.formController == "Leads") {
newString6 = String(format: "%@%@", "Lead since ", dateStr!)
myLabel6.text = newString6
} else if (self.formController == "Customer") {
newString6 = String(format: "%@%@", "Customer since ", dateStr!)
myLabel6.text = newString6
} else if (self.formController == "Blog") {
newString6 = String(format: "%@%@", "Member since ", (self.leadDate as? String)!)
myLabel6.text = newString6
}
}
myLabel6.numberOfLines = 1
myLabel6.backgroundColor = UIColor.clearColor()
myLabel6.textColor = UIColor.blackColor()
myLabel6.layer.masksToBounds = true
//myLabel6.text = newString6
vw.addSubview(myLabel6)
let separatorLineView3 = UIView(frame: CGRectMake(150, 75, 50, 2.5))
separatorLineView3.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView3)
return vw
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - Content Menu
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if (action == #selector(NSObject.copy(_:))) {
return true
}
return false
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
pasteBoard.string = cell!.textLabel?.text
}
// MARK: - Parse
func parseData() {
if (self.formController == "Leads") {
let query = PFQuery(className:"Customer")
query.limit = 1000
query.whereKey("LastName", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Leads")
query1.limit = 1
query1.whereKey("objectId", equalTo:self.objectId!)
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.orderByDescending("createdAt")
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.comments = object!.objectForKey("Coments") as! String
self.leadDate = object!.objectForKey("Date") as! String
self.tableView!.reloadData()
} else {
print("Error")
}
}
} else if (self.formController == "Customer") {
let query = PFQuery(className:"Leads")
query.limit = 1000
query.whereKey("LastName", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Customer")
query1.limit = 1
query1.whereKey("objectId", equalTo:self.objectId!)
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.orderByDescending("createdAt")
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.comments = object!.objectForKey("Comments") as! String
self.leadDate = object!.objectForKey("Date") as! String
self.tableView!.reloadData()
} else {
print("Error")
}
}
} else if (self.formController == "Blog") {
let query = PFQuery(className:"Blog")
query.limit = 1000
query.whereKey("PostBy", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1:PFQuery = PFUser.query()!
query1.whereKey("username", equalTo:self.postBy!)
query1.limit = 1
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.postBy = object!.objectForKey("username") as! String
/*
let dateStr = (object!.objectForKey("createdAt") as? NSDate)!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let createAtString = dateFormatter.stringFromDate(dateStr)as String!
self.leadDate = createAtString */
/*
if let imageFile = object!.objectForKey("imageFile") as? PFFile {
imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
self.selectedImage = UIImage(data: imageData!)
self.tableView!.reloadData()
}
} */
}
}
}
}
// MARK: - Segues
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| 1d36de32eb097e2020b180aefa03d257 | 41.011152 | 160 | 0.60092 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/SourceKit/InterfaceGen/gen_swift_module.swift | apache-2.0 | 10 | import swift_mod_syn
func f(s : inout [Int]) {
s.sort()
}
// RUN: rm -rf %t.mod
// RUN: mkdir -p %t.mod
// RUN: %swift -emit-module -o %t.mod/swift_mod.swiftmodule %S/Inputs/swift_mod.swift -parse-as-library
// RUN: %sourcekitd-test -req=interface-gen -module swift_mod -- -I %t.mod > %t.response
// RUN: diff -u %s.response %t.response
// RUN: %sourcekitd-test -req=module-groups -module swift_mod -- -I %t.mod | %FileCheck -check-prefix=GROUP-EMPTY %s
// GROUP-EMPTY: <GROUPS>
// GROUP-EMPTY-NEXT: <\GROUPS>
// RUN: %swift -emit-module -o %t.mod/swift_mod_syn.swiftmodule %S/Inputs/swift_mod_syn.swift -parse-as-library
// RUN: %sourcekitd-test -req=interface-gen-open -module swift_mod_syn -- -I %t.mod == -req=cursor -pos=4:7 %s -- %s -I %t.mod | %FileCheck -check-prefix=SYNTHESIZED-USR1 %s
// SYNTHESIZED-USR1: s:FesRxs17MutableCollectionxs22RandomAccessCollectionWxPs10Collection8Iterator7Element_s10ComparablerS_4sortFT_T_::SYNTHESIZED::s:Sa
// RUN: %sourcekitd-test -req=interface-gen-open -module Swift -synthesized-extension \
// RUN: == -req=find-usr -usr "s:FesRxs17MutableCollectionxs22RandomAccessCollectionWxPs10Collection8Iterator7Element_s10ComparablerS_4sortFT_T_::SYNTHESIZED::s:Sa" | %FileCheck -check-prefix=SYNTHESIZED-USR2 %s
// SYNTHESIZED-USR2-NOT: USR NOT FOUND
// RUN: %sourcekitd-test -req=interface-gen-open -module Swift \
// RUN: == -req=find-usr -usr "s:FesRxs17MutableCollectionxs22RandomAccessCollectionWxPs10Collection8Iterator7Element_s10ComparablerS_4sortFT_T_::SYNTHESIZED::USRDOESNOTEXIST" | %FileCheck -check-prefix=SYNTHESIZED-USR3 %s
// SYNTHESIZED-USR3-NOT: USR NOT FOUND
| a0b8d77698525e37dee1df43e9426894 | 59.222222 | 223 | 0.741697 | false | true | false | false |
iOS-mamu/SS | refs/heads/master | P/genstrings.swift | mit | 1 | #!/usr/bin/swift
import Foundation
class GenStrings {
let fileManager = NSFileManager.defaultManager()
let acceptedFileExtensions = ["swift"]
let excludedFolderNames = ["Carthage"]
let excludedFileNames = ["genstrings.swift"]
var regularExpresions = [String:NSRegularExpression]()
let localizedRegex = "(?<=\")([^\"]*)(?=\".(localized|localizedFormat))|(?<=(Localized|NSLocalizedString)\\(\")([^\"]*?)(?=\")"
enum GenstringsError:ErrorType {
case Error
}
// Performs the genstrings functionality
func perform() {
let rootPath = NSURL(fileURLWithPath:fileManager.currentDirectoryPath)
let allFiles = fetchFilesInFolder(rootPath)
// We use a set to avoid duplicates
var localizableStrings = Set<String>()
for filePath in allFiles {
let stringsInFile = localizableStringsInFile(filePath)
localizableStrings = localizableStrings.union(stringsInFile)
}
// We sort the strings
let sortedStrings = localizableStrings.sort({ $0 < $1 })
var processedStrings = String()
for string in sortedStrings {
processedStrings.appendContentsOf("\"\(string)\" = \"\(string)\"; \n")
}
print(processedStrings)
}
// Applies regex to a file at filePath.
func localizableStringsInFile(filePath: NSURL) -> Set<String> {
if let fileContentsData = NSData(contentsOfURL: filePath), let fileContentsString = NSString(data: fileContentsData, encoding: NSUTF8StringEncoding) {
do {
let localizedStringsArray = try regexMatches(localizedRegex, string: fileContentsString as String).map({fileContentsString.substringWithRange($0.range)})
return Set(localizedStringsArray)
} catch {}
}
return Set<String>()
}
//MARK: Regex
func regexWithPattern(pattern: String) throws -> NSRegularExpression {
var safeRegex = regularExpresions
if let regex = safeRegex[pattern] {
return regex
}
else {
do {
let currentPattern: NSRegularExpression
currentPattern = try NSRegularExpression(pattern: pattern, options:NSRegularExpressionOptions.CaseInsensitive)
safeRegex.updateValue(currentPattern, forKey: pattern)
self.regularExpresions = safeRegex
return currentPattern
}
catch {
throw GenstringsError.Error
}
}
}
func regexMatches(pattern: String, string: String) throws -> [NSTextCheckingResult] {
do {
let internalString = string
let currentPattern = try regexWithPattern(pattern)
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
let nsString = internalString as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = currentPattern.matchesInString(internalString, options: [], range: stringRange)
return matches
}
catch {
throw GenstringsError.Error
}
}
//MARK: File manager
func fetchFilesInFolder(rootPath: NSURL) -> [NSURL] {
var files = [NSURL]()
do {
let directoryContents = try fileManager.contentsOfDirectoryAtURL(rootPath, includingPropertiesForKeys: [], options: .SkipsHiddenFiles)
for urlPath in directoryContents {
if let stringPath = urlPath.path, lastPathComponent = urlPath.lastPathComponent, pathExtension = urlPath.pathExtension {
var isDir : ObjCBool = false
if fileManager.fileExistsAtPath(stringPath, isDirectory:&isDir) {
if isDir {
if !excludedFolderNames.contains(lastPathComponent) {
let dirFiles = fetchFilesInFolder(urlPath)
files.appendContentsOf(dirFiles)
}
} else {
if acceptedFileExtensions.contains(pathExtension) && !excludedFileNames.contains(lastPathComponent) {
files.append(urlPath)
}
}
}
}
}
} catch {}
return files
}
}
let genStrings = GenStrings()
genStrings.perform()
| 650bdb31da7d52ce9974b370447db01f | 38.834783 | 169 | 0.592884 | false | false | false | false |
summer-wu/WordPress-iOS | refs/heads/buildAndLearn5.5 | WordPress/Classes/ViewRelated/Notifications/Views/NoteTableHeaderView.swift | gpl-2.0 | 1 | import Foundation
/**
* @class NoteTableHeaderView
* @brief This class renders a view with top and bottom separators, meant to be used as UITableView
* section header in NotificationsViewController.
*/
@objc public class NoteTableHeaderView : UIView
{
// MARK: - Public Properties
public var title: String? {
set {
// For layout reasons, we need to ensure that the titleLabel uses an exact Paragraph Height!
let unwrappedTitle = newValue?.uppercaseStringWithLocale(NSLocale.currentLocale()) ?? String()
let attributes = Style.sectionHeaderRegularStyle
titleLabel.attributedText = NSAttributedString(string: unwrappedTitle, attributes: attributes)
setNeedsLayout()
}
get {
return titleLabel.text
}
}
public var separatorColor: UIColor? {
set {
layoutView.bottomColor = newValue ?? UIColor.clearColor()
layoutView.topColor = newValue ?? UIColor.clearColor()
}
get {
return layoutView.bottomColor
}
}
// MARK: - Convenience Initializers
public convenience init() {
self.init(frame: CGRectZero)
}
required override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK - Private Helpers
private func setupView() {
NSBundle.mainBundle().loadNibNamed("NoteTableHeaderView", owner: self, options: nil)
addSubview(contentView)
// Make sure the Outlets are loaded
assert(contentView != nil)
assert(layoutView != nil)
assert(imageView != nil)
assert(titleLabel != nil)
// Layout
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
pinSubviewToAllEdges(contentView)
// Background + Separators
backgroundColor = UIColor.clearColor()
layoutView.backgroundColor = Style.sectionHeaderBackgroundColor
layoutView.bottomVisible = true
layoutView.topVisible = true
}
// MARK: - Aliases
typealias Style = WPStyleGuide.Notifications
// MARK: - Static Properties
public static let headerHeight = CGFloat(26)
// MARK: - Outlets
@IBOutlet private var contentView: UIView!
@IBOutlet private var layoutView: NoteSeparatorsView!
@IBOutlet private var imageView: UIImageView!
@IBOutlet private var titleLabel: UILabel!
}
| b6a8a2b15230ec5635798705dc6f5cc3 | 28.73913 | 106 | 0.610746 | false | false | false | false |
LeonClover/DouYu | refs/heads/master | DouYuZB/DouYuZB/Classes/Main/ViewModel/BaseViewModel.swift | mit | 1 | //
// BaseViewModel.swift
// DouYuZB
//
// Created by Leon on 2017/8/3.
// Copyright © 2017年 pingan. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroup: [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData: Bool, URLString: String, parameters: [String : Any]? = nil, finishedCallback: @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in
guard let resultDict = result as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
//MARK: 判断是否是分组数据
if isGroupData{
for dict in dataArray{
self.anchorGroup.append(AnchorGroup(dict: dict))
}
}else {
let group = AnchorGroup()
for dict in dataArray{
group.anchors.append(AnchorModel(dict: dict))
}
self.anchorGroup.append(group)
}
finishedCallback()
}
}
}
| 42de715bf0efcc0d07ff7c3d6fd5fc42 | 30.27027 | 136 | 0.554019 | false | false | false | false |
ingresse/ios-sdk | refs/heads/dev | IngresseSDK/Services/User/Requests/UserTransactionsRequest.swift | mit | 1 | //
// Copyright © 2022 Ingresse. All rights reserved.
//
import Alamofire
public struct UserTransactionsRequest: Encodable {
public let usertoken: String
public let status: String?
public let pageSize: Int?
public let page: Int?
public init(userToken: String) {
self.usertoken = userToken
self.status = nil
self.pageSize = nil
self.page = nil
}
public init(userToken: String,
status: Self.Status?,
pageSize: Int?,
page: Int?) {
self.usertoken = userToken
self.status = status?.rawValue
self.pageSize = pageSize
self.page = page
}
public init(userToken: String,
status: [Self.Status]?,
pageSize: Int?,
page: Int?) {
self.usertoken = userToken
self.status = status?
.map {$0.rawValue}
.joined(separator: ",")
self.pageSize = pageSize
self.page = page
}
public enum Status: String, Encodable {
case approved = "approved"
case authorized = "authorized"
case declined = "declined"
case error = "error"
case manualReview = "manual review"
case pending = "pending"
case refund = "refund"
}
}
| 469c38540737f5c37858dbfc5fd49f15 | 23.727273 | 51 | 0.535294 | false | false | false | false |
TH-Brandenburg/University-Evaluation-iOS | refs/heads/master | Pods/AKPickerView-Swift/AKPickerView/AKPickerView.swift | apache-2.0 | 2 | //
// AKPickerView.swift
// AKPickerView
//
// Created by Akio Yasui on 1/29/15.
// Copyright (c) 2015 Akkyie Y. All rights reserved.
//
import UIKit
/**
Styles of AKPickerView.
- Wheel: Style with 3D appearance like UIPickerView.
- Flat: Flat style.
*/
public enum AKPickerViewStyle {
case Wheel
case Flat
}
// MARK: - Protocols
// MARK: AKPickerViewDataSource
/**
Protocols to specify the number and type of contents.
*/
@objc public protocol AKPickerViewDataSource {
func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int
optional func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String
optional func pickerView(pickerView: AKPickerView, imageForItem item: Int) -> UIImage
}
// MARK: AKPickerViewDelegate
/**
Protocols to specify the attitude when user selected an item,
and customize the appearance of labels.
*/
@objc public protocol AKPickerViewDelegate: UIScrollViewDelegate {
optional func pickerView(pickerView: AKPickerView, didSelectItem item: Int)
optional func pickerView(pickerView: AKPickerView, marginForItem item: Int) -> CGSize
optional func pickerView(pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int)
}
// MARK: - Private Classes and Protocols
// MARK: AKCollectionViewLayoutDelegate
/**
Private. Used to deliver the style of the picker.
*/
private protocol AKCollectionViewLayoutDelegate {
func pickerViewStyleForCollectionViewLayout(layout: AKCollectionViewLayout) -> AKPickerViewStyle
}
// MARK: AKCollectionViewCell
/**
Private. A subclass of UICollectionViewCell used in AKPickerView's collection view.
*/
private class AKCollectionViewCell: UICollectionViewCell {
var label: UILabel!
var imageView: UIImageView!
var font = UIFont.systemFontOfSize(UIFont.systemFontSize())
var highlightedFont = UIFont.systemFontOfSize(UIFont.systemFontSize())
var _selected: Bool = false {
didSet(selected) {
let animation = CATransition()
animation.type = kCATransitionFade
animation.duration = 0.15
self.label.layer.addAnimation(animation, forKey: "")
self.label.font = self.selected ? self.highlightedFont : self.font
}
}
func initialize() {
self.layer.doubleSided = false
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.label = UILabel(frame: self.contentView.bounds)
self.label.backgroundColor = UIColor.clearColor()
self.label.textAlignment = .Center
self.label.textColor = UIColor.grayColor()
self.label.numberOfLines = 1
self.label.lineBreakMode = .ByTruncatingTail
self.label.highlightedTextColor = UIColor.blackColor()
self.label.font = self.font
self.label.autoresizingMask = [.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleBottomMargin, .FlexibleRightMargin]
self.contentView.addSubview(self.label)
self.imageView = UIImageView(frame: self.contentView.bounds)
self.imageView.backgroundColor = UIColor.clearColor()
self.imageView.contentMode = .Center
self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.contentView.addSubview(self.imageView)
}
init() {
super.init(frame: CGRectZero)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
}
// MARK: AKCollectionViewLayout
/**
Private. A subclass of UICollectionViewFlowLayout used in the collection view.
*/
private class AKCollectionViewLayout: UICollectionViewFlowLayout {
var delegate: AKCollectionViewLayoutDelegate!
var width: CGFloat!
var midX: CGFloat!
var maxAngle: CGFloat!
func initialize() {
self.sectionInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
self.scrollDirection = .Horizontal
self.minimumLineSpacing = 0.0
}
override init() {
super.init()
self.initialize()
}
required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
private override func prepareLayout() {
let visibleRect = CGRect(origin: self.collectionView!.contentOffset, size: self.collectionView!.bounds.size)
self.midX = CGRectGetMidX(visibleRect);
self.width = CGRectGetWidth(visibleRect) / 2;
self.maxAngle = CGFloat(M_PI_2);
}
private override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
private override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
if let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes {
switch self.delegate.pickerViewStyleForCollectionViewLayout(self) {
case .Flat:
return attributes
case .Wheel:
let distance = CGRectGetMidX(attributes.frame) - self.midX;
let currentAngle = self.maxAngle * distance / self.width / CGFloat(M_PI_2);
var transform = CATransform3DIdentity;
transform = CATransform3DTranslate(transform, -distance, 0, -self.width);
transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0);
transform = CATransform3DTranslate(transform, 0, 0, self.width);
attributes.transform3D = transform;
attributes.alpha = fabs(currentAngle) < self.maxAngle ? 1.0 : 0.0;
return attributes;
}
}
return nil
}
private func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
switch self.delegate.pickerViewStyleForCollectionViewLayout(self) {
case .Flat:
return super.layoutAttributesForElementsInRect(rect)
case .Wheel:
var attributes = [AnyObject]()
if self.collectionView!.numberOfSections() > 0 {
for i in 0 ..< self.collectionView!.numberOfItemsInSection(0) {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
attributes.append(self.layoutAttributesForItemAtIndexPath(indexPath)!)
}
}
return attributes
}
}
}
// MARK: AKPickerViewDelegateIntercepter
/**
Private. Used to hook UICollectionViewDelegate and throw it AKPickerView,
and if it conforms to UIScrollViewDelegate, also throw it to AKPickerView's delegate.
*/
private class AKPickerViewDelegateIntercepter: NSObject, UICollectionViewDelegate {
weak var pickerView: AKPickerView?
weak var delegate: UIScrollViewDelegate?
init(pickerView: AKPickerView, delegate: UIScrollViewDelegate?) {
self.pickerView = pickerView
self.delegate = delegate
}
private override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? {
if self.pickerView!.respondsToSelector(aSelector) {
return self.pickerView
} else if self.delegate != nil && self.delegate!.respondsToSelector(aSelector) {
return self.delegate
} else {
return nil
}
}
private override func respondsToSelector(aSelector: Selector) -> Bool {
if self.pickerView!.respondsToSelector(aSelector) {
return true
} else if self.delegate != nil && self.delegate!.respondsToSelector(aSelector) {
return true
} else {
return super.respondsToSelector(aSelector)
}
}
}
// MARK: - AKPickerView
// TODO: Make these delegate conformation private
/**
Horizontal picker view. This is just a subclass of UIView, contains a UICollectionView.
*/
public class AKPickerView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AKCollectionViewLayoutDelegate {
// MARK: - Properties
// MARK: Readwrite Properties
/// Readwrite. Data source of picker view.
public weak var dataSource: AKPickerViewDataSource? = nil
/// Readwrite. Delegate of picker view.
public weak var delegate: AKPickerViewDelegate? = nil {
didSet(delegate) {
self.intercepter.delegate = delegate
}
}
/// Readwrite. A font which used in NOT selected cells.
public lazy var font = UIFont.systemFontOfSize(20)
/// Readwrite. A font which used in selected cells.
public lazy var highlightedFont = UIFont.boldSystemFontOfSize(20)
/// Readwrite. A color of the text on NOT selected cells.
@IBInspectable public lazy var textColor: UIColor = UIColor.darkGrayColor()
/// Readwrite. A color of the text on selected cells.
@IBInspectable public lazy var highlightedTextColor: UIColor = UIColor.blackColor()
/// Readwrite. A float value which indicates the spacing between cells.
@IBInspectable public var interitemSpacing: CGFloat = 0.0
/// Readwrite. The style of the picker view. See AKPickerViewStyle.
public var pickerViewStyle = AKPickerViewStyle.Wheel
/// Readwrite. A float value which determines the perspective representation which used when using AKPickerViewStyle.Wheel style.
@IBInspectable public var viewDepth: CGFloat = 1000.0 {
didSet {
self.collectionView.layer.sublayerTransform = self.viewDepth > 0.0 ? {
var transform = CATransform3DIdentity;
transform.m34 = -1.0 / self.viewDepth;
return transform;
}() : CATransform3DIdentity;
}
}
/// Readwrite. A boolean value indicates whether the mask is disabled.
@IBInspectable public var maskDisabled: Bool! = nil {
didSet {
self.collectionView.layer.mask = self.maskDisabled == true ? nil : {
let maskLayer = CAGradientLayer()
maskLayer.frame = self.collectionView.bounds
maskLayer.colors = [
UIColor.clearColor().CGColor,
UIColor.blackColor().CGColor,
UIColor.blackColor().CGColor,
UIColor.clearColor().CGColor]
maskLayer.locations = [0.0, 0.33, 0.66, 1.0]
maskLayer.startPoint = CGPointMake(0.0, 0.0)
maskLayer.endPoint = CGPointMake(1.0, 0.0)
return maskLayer
}()
}
}
// MARK: Readonly Properties
/// Readonly. Index of currently selected item.
public private(set) var selectedItem: Int = 0
/// Readonly. The point at which the origin of the content view is offset from the origin of the picker view.
public var contentOffset: CGPoint {
get {
return self.collectionView.contentOffset
}
}
// MARK: Private Properties
/// Private. A UICollectionView which shows contents on cells.
private var collectionView: UICollectionView!
/// Private. An intercepter to hook UICollectionViewDelegate then throw it picker view and its delegate
private var intercepter: AKPickerViewDelegateIntercepter!
/// Private. A UICollectionViewFlowLayout used in picker view's collection view.
private var collectionViewLayout: AKCollectionViewLayout {
let layout = AKCollectionViewLayout()
layout.delegate = self
return layout
}
// MARK: - Functions
// MARK: View Lifecycle
/**
Private. Initializes picker view's subviews and friends.
*/
private func initialize() {
self.collectionView?.removeFromSuperview()
self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.collectionViewLayout)
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.backgroundColor = UIColor.clearColor()
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast
self.collectionView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
self.collectionView.dataSource = self
self.collectionView.registerClass(
AKCollectionViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self))
self.addSubview(self.collectionView)
self.intercepter = AKPickerViewDelegateIntercepter(pickerView: self, delegate: self.delegate)
self.collectionView.delegate = self.intercepter
self.maskDisabled = self.maskDisabled == nil ? false : self.maskDisabled
}
public init() {
super.init(frame: CGRectZero)
self.initialize()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
public required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
deinit {
self.collectionView.delegate = nil
}
// MARK: Layout
public override func layoutSubviews() {
super.layoutSubviews()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 {
self.collectionView.collectionViewLayout = self.collectionViewLayout
self.scrollToItem(self.selectedItem, animated: false)
}
self.collectionView.layer.mask?.frame = self.collectionView.bounds
}
public override func intrinsicContentSize() -> CGSize {
return CGSizeMake(UIViewNoIntrinsicMetric, max(self.font.lineHeight, self.highlightedFont.lineHeight))
}
// MARK: Calculation Functions
/**
Private. Used to calculate bounding size of given string with picker view's font and highlightedFont
:param: string A NSString to calculate size
:returns: A CGSize which contains given string just.
*/
private func sizeForString(string: NSString) -> CGSize {
let size = string.sizeWithAttributes([NSFontAttributeName: self.font])
let highlightedSize = string.sizeWithAttributes([NSFontAttributeName: self.highlightedFont])
return CGSize(
width: ceil(max(size.width, highlightedSize.width)),
height: ceil(max(size.height, highlightedSize.height)))
}
/**
Private. Used to calculate the x-coordinate of the content offset of specified item.
:param: item An integer value which indicates the index of cell.
:returns: An x-coordinate of the cell whose index is given one.
*/
private func offsetForItem(item: Int) -> CGFloat {
var offset: CGFloat = 0
for i in 0 ..< item {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cellSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAtIndexPath: indexPath)
offset += cellSize.width
}
let firstIndexPath = NSIndexPath(forItem: 0, inSection: 0)
let firstSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAtIndexPath: firstIndexPath)
let selectedIndexPath = NSIndexPath(forItem: item, inSection: 0)
let selectedSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAtIndexPath: selectedIndexPath)
offset -= (firstSize.width - selectedSize.width) / 2.0
return offset
}
// MARK: View Controls
/**
Reload the picker view's contents and styles. Call this method always after any property is changed.
*/
public func reloadData() {
self.invalidateIntrinsicContentSize()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 {
self.selectItem(self.selectedItem, animated: false, notifySelection: false)
}
}
/**
Move to the cell whose index is given one without selection change.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
public func scrollToItem(item: Int, animated: Bool = false) {
switch self.pickerViewStyle {
case .Flat:
self.collectionView.scrollToItemAtIndexPath(
NSIndexPath(
forItem: item,
inSection: 0),
atScrollPosition: .CenteredHorizontally,
animated: animated)
case .Wheel:
self.collectionView.setContentOffset(
CGPoint(
x: self.offsetForItem(item),
y: self.collectionView.contentOffset.y),
animated: animated)
}
}
/**
Select a cell whose index is given one and move to it.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
public func selectItem(item: Int, animated: Bool = false) {
self.selectItem(item, animated: animated, notifySelection: true)
}
/**
Private. Select a cell whose index is given one and move to it, with specifying whether it calls delegate method.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
:param: notifySelection True if the delegate method should be called, false if not.
*/
private func selectItem(item: Int, animated: Bool, notifySelection: Bool) {
self.collectionView.selectItemAtIndexPath(
NSIndexPath(forItem: item, inSection: 0),
animated: animated,
scrollPosition: .None)
self.scrollToItem(item, animated: animated)
self.selectedItem = item
if notifySelection {
self.delegate?.pickerView?(self, didSelectItem: item)
}
}
// MARK: Delegate Handling
/**
Private.
*/
private func didEndScrolling() {
switch self.pickerViewStyle {
case .Flat:
let center = self.convertPoint(self.collectionView.center, toView: self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(center) {
self.selectItem(indexPath.item, animated: true, notifySelection: true)
}
case .Wheel:
if let numberOfItems = self.dataSource?.numberOfItemsInPickerView(self) {
for i in 0 ..< numberOfItems {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cellSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAtIndexPath: indexPath)
if self.offsetForItem(i) + cellSize.width / 2 > self.collectionView.contentOffset.x {
self.selectItem(i, animated: true, notifySelection: true)
break
}
}
}
}
}
// MARK: UICollectionViewDataSource
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 ? 1 : 0
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource != nil ? self.dataSource!.numberOfItemsInPickerView(self) : 0
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(AKCollectionViewCell.self), forIndexPath: indexPath) as! AKCollectionViewCell
if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) {
cell.label.text = title
cell.label.textColor = self.textColor
cell.label.highlightedTextColor = self.highlightedTextColor
cell.label.font = self.font
cell.font = self.font
cell.highlightedFont = self.highlightedFont
cell.label.bounds = CGRect(origin: CGPointZero, size: self.sizeForString(title))
if let delegate = self.delegate {
delegate.pickerView?(self, configureLabel: cell.label, forItem: indexPath.item)
if let margin = delegate.pickerView?(self, marginForItem: indexPath.item) {
cell.label.frame = CGRectInset(cell.label.frame, -margin.width, -margin.height)
}
}
} else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) {
cell.imageView.image = image
}
cell._selected = (indexPath.item == self.selectedItem)
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size = CGSizeMake(self.interitemSpacing, collectionView.bounds.size.height)
if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) {
size.width += self.sizeForString(title).width
if let margin = self.delegate?.pickerView?(self, marginForItem: indexPath.item) {
size.width += margin.width * 2
}
} else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) {
size.width += image.size.width
}
return size
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0.0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0.0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let number = self.collectionView(collectionView, numberOfItemsInSection: section)
let firstIndexPath = NSIndexPath(forItem: 0, inSection: section)
let firstSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAtIndexPath: firstIndexPath)
let lastIndexPath = NSIndexPath(forItem: number - 1, inSection: section)
let lastSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAtIndexPath: lastIndexPath)
return UIEdgeInsetsMake(
0, (collectionView.bounds.size.width - firstSize.width) / 2,
0, (collectionView.bounds.size.width - lastSize.width) / 2
)
}
// MARK: UICollectionViewDelegate
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.selectItem(indexPath.item, animated: true)
}
// MARK: UIScrollViewDelegate
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.delegate?.scrollViewDidEndDecelerating?(scrollView)
self.didEndScrolling()
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
if !decelerate {
self.didEndScrolling()
}
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
self.delegate?.scrollViewDidScroll?(scrollView)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.collectionView.layer.mask?.frame = self.collectionView.bounds
CATransaction.commit()
}
// MARK: AKCollectionViewLayoutDelegate
private func pickerViewStyleForCollectionViewLayout(layout: AKCollectionViewLayout) -> AKPickerViewStyle {
return self.pickerViewStyle
}
}
| d4d7fdbdd0ec1bb38df623b384d5b861 | 35.204283 | 182 | 0.75455 | false | false | false | false |
zhangchn/swelly | refs/heads/master | swelly/Connection.swift | gpl-2.0 | 1 | //
// Connection.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import AppKit
enum ConnectionProtocol {
case ssh
case telnet
}
extension Notification.Name {
static let connectionDidConnect = Notification.Name(rawValue: "conn_did_connect")
static let connectionDidDisconnect = Notification.Name(rawValue: "conn_did_disconn")
}
class Connection : NSObject, PTYDelegate {
var icon: NSImage?
var processing: Bool = false
private var _lastTouchDate : Date?
var lastTouchDate : Date? { get { return _lastTouchDate } }
var connected: Bool! {
didSet {
if connected! {
icon = NSImage(named: "online.pdf")
} else {
resetMessageCount()
icon = NSImage(named: "offline.pdf")
}
}
}
var terminal: Terminal! {
didSet {
terminal.connection = self
terminalFeeder.terminal = terminal
}
}
var terminalFeeder = TerminalFeeder()
var pty: PTY?
var site: Site
var userName: String!
var messageDelegate = MessageDelegate()
var messageCount: Int = 0
init(site: Site){
self.site = site
}
func setup() {
if !site.isDummy {
pty = PTY(proxyAddress: site.proxyAddress, proxyType: site.proxyType)
pty!.delegate = self
_ = pty!.connect(addr: site.address, connectionProtocol: site.connectionProtocol, userName: userName)
}
}
// PTY Delegate
func ptyWillConnect(_ pty: PTY) {
processing = true
connected = false
icon = NSImage(named: "waiting.pdf")
}
func ptyDidConnect(_ pty: PTY) {
processing = false
connected = true
Thread.detachNewThread {
autoreleasepool { [weak self] () in
self?.login()
}
}
NotificationCenter.default.post(name: .connectionDidConnect, object: self)
}
func pty(_ pty: PTY, didRecv data: Data) {
terminalFeeder.feed(data: data, connection: self)
}
func pty(_ pty: PTY, willSend data: Data) {
_lastTouchDate = Date()
}
func ptyDidClose(_ pty: PTY) {
processing = false
connected = false
terminalFeeder.clearAll()
terminal.clearAll()
NotificationCenter.default.post(name: .connectionDidDisconnect, object: self)
}
func close() {
pty?.close()
}
func reconnect() {
pty?.close()
_ = pty?.connect(addr: site.address, connectionProtocol: site.connectionProtocol, userName: userName)
resetMessageCount()
}
func sendMessage(msg: Data) {
pty?.send(data:msg)
}
func sendMessage(_ keys: [NSEvent.SpecialKey]) {
sendMessage(msg: Data(keys.map { UInt8($0.rawValue) }))
}
func sendAntiIdle() {
// 6 zeroed bytes:
let message = Data(count: 6)
sendMessage(msg: message)
}
func login() {
//let account = addr.utf8
switch site.connectionProtocol {
case .ssh:
if terminalFeeder.cursorX > 2, terminalFeeder.grid[terminalFeeder.cursorY][terminalFeeder.cursorX - 2].byte == "?".utf8.first! {
sendMessage(msg: "yes\r".data(using: .ascii)!)
sleep(1)
}
case .telnet:
while terminalFeeder.cursorY <= 3 {
sleep(1)
sendMessage(msg: userName!.data(using: .utf8)!)
sendMessage(msg: Data([0x0d]))
}
}
let service = "Welly".data(using: .utf8)
service?.withUnsafeBytes() { (buffer : UnsafeRawBufferPointer) in
let accountData = (userName! + "@" + site.address).data(using: .utf8)!
accountData.withUnsafeBytes() {(buffer2 : UnsafeRawBufferPointer) in
var len = UInt32(0)
var pass : UnsafeMutableRawPointer? = nil
let serviceNamePtr = buffer.baseAddress!.assumingMemoryBound(to: Int8.self)
let accountNamePtr = buffer2.baseAddress!.assumingMemoryBound(to: Int8.self)
if noErr == SecKeychainFindGenericPassword(nil, UInt32(service!.count), serviceNamePtr, UInt32(accountData.count), accountNamePtr, &len, &pass, nil) {
sendMessage(msg: Data(bytes: pass!, count: Int(len)))
sendMessage(msg: Data([0x0d]))
SecKeychainItemFreeContent(nil, pass)
}
}
}
}
func send(text: String, delay microsecond: Int = 0) {
let s = text.replacingOccurrences(of: "\n", with: "\r")
var data = Data()
let encoding = site.encoding
for ch in s.utf16 {
var buf = [UInt8](repeating:0, count: 2)
if ch < 0x007f {
buf[0] = UInt8(ch)
data.append(&buf, count: 1)
} else {
if CFStringIsSurrogateHighCharacter(ch) ||
CFStringIsSurrogateLowCharacter(ch) {
buf[0] = 0x3f
buf[1] = 0x3f
} else {
let code = encode(ch, to: encoding)
if code != 0 {
buf[0] = UInt8(code >> 8)
buf[1] = UInt8(code & 0xff)
} else {
if (ch == 8943 && encoding == .gbk) {
// hard code for the ellipsis
buf[0] = 0xa1
buf[1] = 0xad
} else if ch != 0 {
buf[0] = 0x20
buf[1] = 0x20
}
}
}
data.append(&buf, count: 2)
}
}
// Now send the message
if microsecond == 0 {
// send immediately
sendMessage(msg: data)
} else {
// send with delay
for i in 0..<data.count {
sendMessage(msg: data.subdata(in: i..<(i+1)))
usleep(useconds_t(microsecond))
}
}
}
func increaseMessageCount(value: Int) {
guard value > 0 else {
return
}
let config = GlobalConfig.sharedInstance
NSApp.requestUserAttention(config.shouldRepeatBounce ? .criticalRequest : .informationalRequest)
config.messageCount += value
messageCount += value
// self.objectCount = messageCount
}
func resetMessageCount() {
guard messageCount > 0 else {return}
GlobalConfig.sharedInstance.messageCount -= messageCount
messageCount = 0
//TODO:
//self.objectCount = 0
}
func didReceive(newMessage: String, from caller: String) {
//
}
}
| 522628b8884e1eb22ba8d1057c9d9e86 | 30.337838 | 166 | 0.521345 | false | false | false | false |
MKGitHub/UIPheonix | refs/heads/master | Demo/Shared/Views/Collection View/SimpleViewAnimationModelCVCell.swift | apache-2.0 | 1 | /**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
final class SimpleViewAnimationModelCVCell:UIPBaseCollectionViewCell
{
// MARK: Private IB Outlet
@IBOutlet private weak var ibLeftSpaceConstraint:NSLayoutConstraint!
// MARK: Private Member
public var pSimpleViewAnimationModel:SimpleViewAnimationModel!
// MARK:- UICollectionViewCell
override func prepareForReuse()
{
super.prepareForReuse()
}
// MARK:- UIPBaseCollectionViewCell/UIPBaseCollectionViewCellProtocol
override func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
{
// save model for later
pSimpleViewAnimationModel = model as? SimpleViewAnimationModel
animateUI()
// return view size
return UIPCellSize(replaceWidth:true, width:collectionView.bounds.size.width,
replaceHeight:false, height:0)
}
// MARK:- Private IB Action
@IBAction func animateButtonAction(_ sender:AnyObject)
{
#if os(iOS) || os(tvOS)
self.layoutIfNeeded() // #1. Make sure all frames are at the starting position.
UIView.animate(withDuration:1.0)
{
[weak self] in
if let self = self
{
self.pSimpleViewAnimationModel.pAnimationState = !self.pSimpleViewAnimationModel.pAnimationState
self.animateUI()
self.layoutIfNeeded() // #2. Layout again to update the frames/constraints.
}
}
#elseif os(macOS)
self.view.layoutSubtreeIfNeeded() // #1. Make sure all frames are at the starting position.
NSAnimationContext.runAnimationGroup(
{
[weak self] (context) in
context.duration = 1.0
if let self = self
{
self.pSimpleViewAnimationModel.pAnimationState = !self.pSimpleViewAnimationModel.pAnimationState
self.animateUI()
self.view.layoutSubtreeIfNeeded() // #2. Layout again to update the frames/constraints.
}
},
completionHandler:nil)
#endif
}
// MARK:- Private
private func animateUI()
{
#if os(iOS)
self.ibLeftSpaceConstraint?.constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.bounds.width - 70 - 8) : 8
#elseif os(tvOS)
self.ibLeftSpaceConstraint?.constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.bounds.width - 150 - 16) : 16
#elseif os(macOS)
self.ibLeftSpaceConstraint?.animator().constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.view.bounds.width - 70 - 8) : 8
#endif
}
}
| cc0d29194405431569b1384d544dcceb | 29.658333 | 145 | 0.634955 | false | false | false | false |
zhiquan911/CHKLineChart | refs/heads/master | CHKLineChart/CHKLineChart/Classes/CHAxisModel.swift | mit | 2 | //
// YAxis.swift
// CHKLineChart
//
// Created by Chance on 16/8/31.
// Copyright © 2016年 Chance. All rights reserved.
//
import Foundation
import UIKit
/**
Y轴显示的位置
- Left: 左边
- Right: 右边
- None: 不显示
*/
public enum CHYAxisShowPosition {
case left, right, none
}
/// 坐标轴辅助线样式风格
///
/// - none: 不显示
/// - dash: 虚线
/// - solid: 实线
public enum CHAxisReferenceStyle {
case none
case dash(color: UIColor, pattern: [NSNumber])
case solid(color: UIColor)
}
/**
* Y轴数据模型
*/
public struct CHYAxis {
public var max: CGFloat = 0 //Y轴的最大值
public var min: CGFloat = 0 //Y轴的最小值
public var ext: CGFloat = 0.00 //上下边界溢出值的比例
public var baseValue: CGFloat = 0 //固定的基值
public var tickInterval: Int = 4 //间断显示个数
public var pos: Int = 0
public var decimal: Int = 2 //约束小数位
public var isUsed = false
/// 辅助线样式
public var referenceStyle: CHAxisReferenceStyle = .dash(color: UIColor(white: 0.2, alpha: 1), pattern: [5])
}
/**
* X轴数据模型
*/
public struct CHXAxis {
public var tickInterval: Int = 6 //间断显示个数
/// 辅助线样式
public var referenceStyle: CHAxisReferenceStyle = .none
}
| d06909ae9bcde729bf027f15b97e6f67 | 18.292308 | 111 | 0.582137 | false | false | false | false |
melling/ios_topics | refs/heads/master | GameClock/GameClock/AppDelegate.swift | cc0-1.0 | 1 | //
// AppDelegate.swift
// GameClock
//
// Created by Michael Mellinger on 11/24/17.
// Copyright © 2017 h4labs. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "GameClock")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| dfc723893858bed0fd3d6ff7a0d2574a | 48.408602 | 285 | 0.685963 | false | false | false | false |
laurentVeliscek/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Filters/Low Pass Filter/AKLowPassFilter.swift | mit | 2 | //
// AKLowPassFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's LowPassFilter Audio Unit
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public class AKLowPassFilter: AKNode, AKToggleable {
private let cd = AudioComponentDescription(
componentType: kAudioUnitType_Effect,
componentSubType: kAudioUnitSubType_LowPassFilter,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0)
internal var internalEffect = AVAudioUnitEffect()
internal var internalAU: AudioUnit = nil
private var mixer: AKMixer
/// Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
public var cutoffFrequency: Double = 6900 {
didSet {
if cutoffFrequency < 10 {
cutoffFrequency = 10
}
if cutoffFrequency > 22050 {
cutoffFrequency = 22050
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_CutoffFrequency,
kAudioUnitScope_Global, 0,
Float(cutoffFrequency), 0)
}
}
/// Resonance (dB) ranges from -20 to 40 (Default: 0)
public var resonance: Double = 0 {
didSet {
if resonance < -20 {
resonance = -20
}
if resonance > 40 {
resonance = 40
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_Resonance,
kAudioUnitScope_Global, 0,
Float(resonance), 0)
}
}
/// Dry/Wet Mix (Default 100)
public var dryWetMix: Double = 100 {
didSet {
if dryWetMix < 0 {
dryWetMix = 0
}
if dryWetMix > 100 {
dryWetMix = 100
}
inputGain?.volume = 1 - dryWetMix / 100
effectGain?.volume = dryWetMix / 100
}
}
private var lastKnownMix: Double = 100
private var inputGain: AKMixer?
private var effectGain: AKMixer?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
// MARK: - Initialization
/// Initialize the low pass filter node
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 6900,
resonance: Double = 0) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
inputGain = AKMixer(input)
inputGain!.volume = 0
mixer = AKMixer(inputGain!)
effectGain = AKMixer(input)
effectGain!.volume = 1
internalEffect = AVAudioUnitEffect(audioComponentDescription: cd)
super.init()
AudioKit.engine.attachNode(internalEffect)
internalAU = internalEffect.audioUnit
AudioKit.engine.connect((effectGain?.avAudioNode)!, to: internalEffect, format: AudioKit.format)
AudioKit.engine.connect(internalEffect, to: mixer.avAudioNode, format: AudioKit.format)
avAudioNode = mixer.avAudioNode
AudioUnitSetParameter(internalAU, kLowPassParam_CutoffFrequency, kAudioUnitScope_Global, 0, Float(cutoffFrequency), 0)
AudioUnitSetParameter(internalAU, kLowPassParam_Resonance, kAudioUnitScope_Global, 0, Float(resonance), 0)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
if isStopped {
dryWetMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
if isPlaying {
lastKnownMix = dryWetMix
dryWetMix = 0
isStarted = false
}
}
}
| 0f2e6cb317ec697482ddf11a6f9b4563 | 30.126761 | 130 | 0.58914 | false | false | false | false |
OlesenkoViktor/VOChart | refs/heads/master | VOChart.framework/PrivateHeaders/VOChartView.swift | mit | 1 | //
// VOChartView.swift
// Stock
//
// Created by VOlesenko on 1/21/16.
// Copyright © 2016 VOlesenko. All rights reserved.
//
import UIKit
@IBDesignable public class VOChartView: UIView {
// MARK: - Public propertys
/// Data for ChartView. Interface Builder does not support connecting to an outlet in a Swift file when the outlet’s type is a protocol. So temporary this object type is AnyObject
@IBOutlet public var dataSourceObject: AnyObject!
/// Color for line. Default is black
@IBInspectable public var defaultLineColor: UIColor = UIColor.blackColor()
/// Determines to show the labels on the left side of chart
@IBInspectable public var showLeftLabels: Bool = false
/// Color for grid. Default is lightGray
@IBInspectable public var gridColor: UIColor = UIColor.lightGrayColor()
/// Determines to show the vertical Grid
@IBInspectable public var showVerticalGrid: Bool = true
/// Distance between vertical lines of grid. Min value is 3
@IBInspectable public var gridXOffset: CGFloat = 60.0 {
didSet {
if gridXOffset < 3 {gridXOffset = 3}
}
}
/// Determines to show the horizontal Grid
@IBInspectable public var showHorizontalGrid: Bool = false
/// Distance between horizontal lines of grid. Min value is 3
@IBInspectable public var gridYOffset: CGFloat = 60.0 {
didSet {
if gridYOffset < 3 {gridYOffset = 3}
}
}
/// Determines to show the signs
@IBInspectable public var showValues: Bool = true
/// Determines to show dots on lines
@IBInspectable public var showDots: Bool = true
/// Determines to show the popup view with detail values
@IBInspectable public var showPopupOnTouch: Bool = false
/// Determines color for popup background. Default is clearColor
@IBInspectable public var popupBackgound: UIColor = UIColor.clearColor()
/**
Reloads all of the data for the chart view.
Call this method to reload all of the items in the chart view. This causes the chart view to discard any currently visible items and redisplay them.
*/
public func reloadData() {
valuesArray.removeAll()
colorsArray.removeAll()
guard dataSource != nil else {
return
}
let numberOfLines = dataSource!.chartViewNumberOfLines(self)
assert(numberOfLines >= 0, "Number of lines must be positive or equal zero")
for var lineIndex = 0; lineIndex < numberOfLines; lineIndex++ {
valuesArray.append(dataSource!.chartView(self, valuesForLine: lineIndex))
}
self.setNeedsDisplay()
}
// MARK: - Private variables
private var dataSource: VOChartViewDataSource? { return dataSourceObject as? VOChartViewDataSource }
private var valuesArray = [[CGFloat]]()
private var colorsArray = [UIColor]()
private var popupView: VOChartPopupView?
private var leftLabelsWidth: CGFloat = 0 {
didSet {
leftLabelFrame = CGRectMake(0, 0, leftLabelsWidth, frame.height)
chartFrame = CGRectMake(leftLabelFrame.width, 0, frame.width - leftLabelFrame.width, frame.height)
}
}
private var leftLabelFrame: CGRect = CGRectZero
private var chartFrame: CGRect = CGRectZero
override public func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Draw
override public func drawRect(rect: CGRect) {
self.reloadData()
if showLeftLabels {
self.drawLeftLabels()
}
self.drawGrid()
#if TARGET_INTERFACE_BUILDER
self.drawTestLine()
#endif
self.drawLines()
}
/**
Calculate distance between X values
- returns: Offset between X values
*/
private func calculateXoffset() -> CGFloat {
var XvalueCount = 0
for array in valuesArray {
if array.count > XvalueCount { XvalueCount = array.count }
}
return (frame.width - leftLabelsWidth) / CGFloat(XvalueCount - 1)
}
/**
Calculate distance between Y values
- returns: Offset between Y values
*/
private func calculateYoffset() -> (offset: CGFloat, maxValue: CGFloat) {
var maxValue: CGFloat = valuesArray.first?.first ?? 0
for array in valuesArray {
for number in array {
if number > maxValue { maxValue = number }
}
}
return (frame.height / maxValue, maxValue)
}
/**
Calculate leftLabels frame and display values for horizontal grid
*/
private func drawLeftLabels() {
let maxValue = calculateYoffset().maxValue
let decimalOffset: CGFloat = 20
let maxValueString = NSString(format: (maxValue == floor(maxValue) ? "%.0f" : "%.2f"), maxValue)
let font = UIFont.systemFontOfSize(12)
let labelSize = maxValueString.sizeWithAttributes([NSFontAttributeName : font])
leftLabelsWidth = labelSize.width + decimalOffset
let labelsCount = CGFloat(frame.height / gridYOffset)
let valuePerLabel = maxValue / labelsCount
for var labelIndex: CGFloat = 0; labelIndex < labelsCount; ++labelIndex {
let value = valuePerLabel * labelIndex
self.drawValue(value, forPoint: CGPointMake(0, frame.height - (labelSize.height / 2) - (labelIndex * gridYOffset)), color: self.gridColor)
}
}
/**
Display horizontal and vertical grid with defined color
*/
private func drawGrid() {
let gridLine = UIBezierPath()
gridLine.lineWidth = 1
if showVerticalGrid {
for var x: CGFloat = leftLabelsWidth; x < frame.width; x += gridXOffset {
gridLine.moveToPoint(CGPoint(x: x, y: 0))
gridLine.addLineToPoint(CGPoint(x: x, y: frame.height))
}
}
if showHorizontalGrid {
for var y = frame.height; y > 0; y -= gridYOffset {
gridLine.moveToPoint(CGPoint(x: leftLabelsWidth, y: y))
gridLine.addLineToPoint(CGPoint(x: frame.width, y: y))
}
}
self.gridColor.setStroke()
gridLine.stroke()
}
/**
Add test line for Interface builder testing
*/
private func drawTestLine() {
let lineValues: [CGFloat] = [14, 04, 22, 12, 27]
let xOffset = (frame.width - leftLabelsWidth) / CGFloat(lineValues.count - 1)
let yOffset = frame.height / 27
let path = UIBezierPath()
path.lineWidth = 1
self.defaultLineColor.setStroke()
for var i = 0; i < lineValues.count; ++i {
let value = lineValues[i] * yOffset
let point = CGPoint(x: leftLabelsWidth + CGFloat(i) * xOffset, y: frame.height - value)
path.empty ? path.moveToPoint(point) : path.addLineToPoint(point)
if showDots {
self.drawDotInPoint(point, color: self.defaultLineColor)
}
if showValues {
drawValue(lineValues[i], forPoint: point, color: self.defaultLineColor)
}
}
path.stroke()
}
/**
Display lines from delegate
*/
private func drawLines() {
let xOffset = calculateXoffset()
let yOffset = calculateYoffset().offset
for var lineIndex = 0; lineIndex < valuesArray.count; lineIndex++ {
let path = UIBezierPath()
path.lineWidth = 1
let lineColor = dataSource!.chartView(self, colorForLine: lineIndex) ?? self.defaultLineColor
colorsArray.append(lineColor)
lineColor.setStroke()
let lineValues = valuesArray[lineIndex]
for var i = 0; i < lineValues.count; ++i {
let value = lineValues[i] * yOffset
let point = CGPoint(x: leftLabelsWidth + CGFloat(i) * xOffset, y: frame.height - value)
if path.empty {
path.moveToPoint(point)
} else {
path.addLineToPoint(point)
}
if showDots {
self.drawDotInPoint(point, color: lineColor)
}
if showValues {
drawValue(lineValues[i], forPoint: point, color: lineColor)
}
}
path.stroke()
}
}
/**
Display dots on lines if allowed
- parameter point: Point, where dot will be displayed
- parameter color: Color for dot
*/
private func drawDotInPoint(point: CGPoint, color: UIColor) {
color.setFill()
UIBezierPath(ovalInRect: CGRectMake(point.x - 2, point.y - 2, 4, 4)).fill()
}
private func drawValue(value: CGFloat, var forPoint point: CGPoint, color: UIColor) {
let string: NSString = NSString(format: (value == floor(value) ? "%.0f" : "%.2f"), value)
let font = UIFont.systemFontOfSize(12)
let attributes = [NSFontAttributeName : font,
NSForegroundColorAttributeName : color]
let stringSize = string.sizeWithAttributes(attributes)
if point.x + stringSize.width >= frame.width - leftLabelsWidth {
point.x = frame.width - leftLabelsWidth - stringSize.width
}
if point.y + stringSize.height >= frame.height {
point.y = frame.height - stringSize.height
}
string.drawAtPoint(point, withAttributes: attributes)
}
// MARK: - Touches
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
popupView = VOChartPopupView()
popupView?.backgroundColor = popupBackgound
self.addSubview(popupView!)
self.updatePopup(getPointFromTouch(touches.first!))
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.updatePopup(getPointFromTouch(touches.first!))
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
popupView?.removeFromSuperview()
}
override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
popupView?.removeFromSuperview()
}
/**
Get touch coordinate limited by chart frame
- parameter touch: Original touch
- returns: Touch coordinate in chartFrame with limitations
*/
private func getPointFromTouch(touch: UITouch) -> CGPoint {
let touchPoint = touch.locationInView(self)
let x = touchPoint.x < chartFrame.origin.x ? chartFrame.origin.x : (touchPoint.x > frame.width ? frame.width : touchPoint.x)
let y = touchPoint.y < 0 ? 0 : (touchPoint.y > frame.height ? frame.height : touchPoint.y)
return CGPointMake(x, y)
}
/**
Get line values for selected Y point
- parameter point: Touch point
- returns: Array of lines values for selected Y coordinate
*/
private func valuesForPoint(point: CGPoint) -> [CGFloat]{
var values = [CGFloat]()
let xOffset = calculateXoffset()
let fromIndex = Int((point.x - leftLabelsWidth) / xOffset)
for var lineValues in valuesArray
{
if fromIndex + 1 < lineValues.count {
let fromValue = lineValues[fromIndex]
let toValue = lineValues[fromIndex + 1]
let valuePerPixel = (toValue - fromValue) / xOffset
let fromPoint = CGFloat(fromIndex) * xOffset
let value = fromValue + (point.x - fromPoint) * valuePerPixel
values.append(value)
} else {
values.append(0)
}
}
return values
}
/**
Update char popup with new position and values
- parameter touchPoint: Touch coordinate for new values observing
*/
private func updatePopup(touchPoint: CGPoint) {
popupView!.colors = colorsArray
popupView?.values = valuesForPoint(touchPoint)
let x = touchPoint.x + popupView!.size.width > frame.width ? frame.width - popupView!.size.width : touchPoint.x
let y = touchPoint.y + popupView!.size.height > frame.height ? frame.height - popupView!.size.height : touchPoint.y
popupView?.frame = CGRectMake(x, y, popupView!.size.width, popupView!.size.height)
}
}
| 5612572e876c5897dbd7d9ad9c490d41 | 32.253102 | 183 | 0.584807 | false | false | false | false |
Foild/PagingMenuController | refs/heads/master | Example/PagingMenuControllerDemo/GistsViewController.swift | mit | 1 | //
// GistsViewController.swift
// PagingMenuControllerDemo
//
// Created by Yusuke Kita on 5/10/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
class GistsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var gists = [[String: AnyObject]]()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// let url = NSURL(string: "https://api.github.com/gists/public")
// let request = NSURLRequest(URL: url!)
// let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
//
// let task = session.dataTaskWithRequest(request) { [unowned self] data, response, error in
// let result = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as! [[String: AnyObject]]
// self.gists = result
//
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.tableView.reloadData()
// })
// }
// task.resume()
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gists.count
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let gist = gists[indexPath.row]
cell.textLabel?.text = gist["description"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController
navigationController?.pushViewController(detailViewController, animated: true)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
}
| c6e74572201ba39190ad412d985e7b65 | 35.967213 | 135 | 0.662971 | false | false | false | false |
laurenyew/Stanford_cs193p_iOS_Application_Development | refs/heads/master | Spring_2017_iOS10_Swift/Calculator/Calculator/Graph/CalculatorGraphView.swift | mit | 1 | //
// CalculatorGraphView.swift
// Calculator
//
// Created by laurenyew on 12/13/17.
// Copyright © 2017 CS193p. All rights reserved.
//
import UIKit
@IBDesignable
class CalculatorGraphView: UIView
{
@IBInspectable
var scale: CGFloat = 40 {didSet {setNeedsDisplay()}}
@IBInspectable
var axesColor: UIColor = UIColor.blue {didSet {setNeedsDisplay()}}
@IBInspectable
var graphColor: UIColor = UIColor.red
// Center of the graph being viewed on the screen
// Used for calculating path via scale for each part of screen
var graphViewCenter: CGPoint{
return center
}
// Saved Origin of the function (changes propagate to the view here)
var originRelativeToGraphViewCenter: CGPoint = CGPoint.zero {didSet{setNeedsDisplay()}}
// Calculated origin of function
// Used for main logic, can be set to update the view's origin
var origin: CGPoint{
get{
var funcOrigin = originRelativeToGraphViewCenter
funcOrigin.x += graphViewCenter.x
funcOrigin.y += graphViewCenter.y
return funcOrigin
}
set{
var funcOrigin = newValue
funcOrigin.x -= graphViewCenter.x
funcOrigin.y -= graphViewCenter.y
originRelativeToGraphViewCenter = funcOrigin
}
}
//Graphing function: returns value Y for given value X for a given function
//If this value is changed, redraw
var graphFunctionY: ((Double) -> Double?)? {didSet {setNeedsDisplay()}}
private var axesDrawer = AxesDrawer()
override func draw(_ rect: CGRect) {
axesColor.setStroke()
axesDrawer.color = axesColor
axesDrawer.drawAxes(in: bounds, origin: origin, pointsPerUnit: scale)
//Draw the graph function in the view using the graphFunctionY
drawGraphFunction(in: bounds, origin: origin, pointsPerUnit: scale)
}
//Handles UI of drawing new function
private func drawGraphFunction(in rect: CGRect, origin: CGPoint, pointsPerUnit: CGFloat){
var graphX, graphY:CGFloat
var x,y: Double
UIGraphicsGetCurrentContext()?.saveGState()
graphColor.set()
let path = UIBezierPath()
path.lineWidth = 20.0
//For the graph view's width, calculate the function and show
for i in 0...Int(rect.size.width * scale) {
graphX = CGFloat(i)
x = Double((graphX - origin.x)/scale)
y = graphFunctionY?(x) ?? 0
graphY = (CGFloat(y) + origin.y) * scale
path.addLine(to: CGPoint(x: graphX, y: graphY))
}
path.stroke()
UIGraphicsGetCurrentContext()?.restoreGState()
}
}
| 8c387bfc70d6287af4e35ea476374ee3 | 30.873563 | 93 | 0.627119 | false | false | false | false |
mactive/rw-courses-note | refs/heads/master | ProgrammingInSwift/ControlFlow.playground/Pages/SwitchChallenge.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
let lifeStage: String
let age = 80
//switch age {
//case ..<0:
// lifeStage = "Not born yet"
//case 0...2:
// lifeStage = "Infant"
//case 3...12:
// lifeStage = "Child"
//case 13...19:
// lifeStage = "Teenager"
//case 20...39:
// lifeStage = "Adult"
//case 40...60:
// lifeStage = "Middle aged"
//case 61...99:
// lifeStage = "Eldery"
//case let age:
// fatalError("Unaccounted for age: \(age)")
//}
let name = "Jessy"
switch (name, age) {
case (name, ..<0):
lifeStage = "\(name) is Not born yet"
case (name, 0...2):
lifeStage = "\(name) is Infant"
case (name, 3...12):
lifeStage = "\(name) is Child"
case (name, 13...19):
lifeStage = "\(name) is Teenager"
case (name, 20...39):
lifeStage = "\(name) is Adult"
case (name, 40...60):
lifeStage = "\(name) is Middle aged"
case (name, 61...99):
lifeStage = "\(name) is Eldery"
case (_, let age):
fatalError("Unaccounted for age): \(age)")
}
//: [Next](@next)
| b3f93b59d9837d46d226fb7d8b67a6f5 | 19.653061 | 47 | 0.56917 | false | false | false | false |
manuelbl/WirekiteMac | refs/heads/master | Examples/Nunchuck/Nunchuck/Nunchuck.swift | mit | 1 | // Wirekite for MacOS
//
// Copyright (c) 2017 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
import Foundation
import WirekiteMac
class Nunchuck {
var device: WirekiteDevice?
var i2cPort: PortID = 0
var slaveAddress = 0x52
var joystickX = 0
var joystickY = 0
var accelerometerX = 0
var accelerometerY = 0
var accelerometerZ = 0
var cButton = false
var zButton = false
init(device: WirekiteDevice, i2cPort: PortID) {
self.device = device
self.i2cPort = i2cPort;
initController()
readData()
}
func readData() {
let senssorData = device!.requestData(onI2CPort: i2cPort, fromSlave: slaveAddress, length: 6)
if senssorData == nil || senssorData!.count != 6 {
let result = device!.lastResult(onI2CPort: i2cPort).rawValue
NSLog("nunchuck read failed - reason \(result)")
return
}
var sensorBytes = [UInt8](senssorData!)
joystickX = Int(sensorBytes[0])
joystickY = Int(sensorBytes[1])
accelerometerX = (Int(sensorBytes[2]) << 2) | Int((sensorBytes[5] >> 2) & 0x3)
accelerometerY = (Int(sensorBytes[3]) << 2) | Int((sensorBytes[5] >> 4) & 0x3)
accelerometerZ = (Int(sensorBytes[4]) << 2) | Int((sensorBytes[5] >> 6) & 0x3)
cButton = (sensorBytes[5] & 2) == 0
zButton = (sensorBytes[5] & 1) == 0
// prepare next data read (convert command)
let cmdBytes: [UInt8] = [ 0 ]
let cmdData = Data(bytes: cmdBytes)
device!.submit(onI2CPort: i2cPort, data: cmdData, toSlave: slaveAddress)
}
func initController() {
let initSequenceBytes: [[UInt8]] = [
[ 0xf0, 0x55 ],
[ 0xfb, 0x00 ]
]
for bytes in initSequenceBytes {
let data = Data(bytes: bytes)
let numBytes = device!.send(onI2CPort: i2cPort, data: data, toSlave: slaveAddress)
if numBytes != bytes.count {
let result = device!.lastResult(onI2CPort: i2cPort).rawValue
NSLog("nunchuck init seq failed - reason \(result)")
return
}
}
}
}
| 10e7c12894bd5a28470892d56c083af8 | 30.246575 | 101 | 0.572556 | false | false | false | false |
samburnstone/SwiftStudyGroup | refs/heads/master | Swift Language Guide Playgrounds/Homework Week 7.playground/Pages/Generics.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
//:## Generics
//: _________
//: Start with a simple function that swaps the values of the two parameters
func swapValues<T>(inout a: T, inout b: T)
{
let tempA = a
a = b
b = tempA
}
var value1 = 100
var value2 = 5
swapValues(&value1, b: &value2)
// Note how value1 now contains the value 5, whilst value2 stored 100
value1
value2
//:### Generic Types
struct Queue <Element>
{
var items = [Element]()
mutating func push(element: Element)
{
items.append(element)
}
mutating func pop() -> Element?
{
if items.isEmpty
{
return nil
}
return items.removeFirst()
}
func peek() -> Element?
{
return items.first
}
}
//: Let's try it out on some types
var integerQueue = Queue(items: [0, 1, 2, 4])
integerQueue.dynamicType // Note that compiler automatically infers the type of the Queue
integerQueue.pop()
integerQueue.peek()
integerQueue.pop()
var stringQueue = Queue<String>()
stringQueue.push("Sam")
stringQueue.push("Chris")
stringQueue.pop()
stringQueue.pop()
stringQueue.peek()
//:### Defining Constraints For Types
//: __________
//: A contrived example is a function taking two parameters where we check the type of the elements contained within each collection are equal AND the types conform to the `Equatable` protocol. NOTE: As C1 and C2 element types have already been checked to be equal, we can omit a check that C2's item type also conforms to Equatable
func collectionIsSubsetOfOtherCollection<C1: CollectionType, C2: CollectionType where C1.Generator.Element == C2.Generator.Element, C1.Generator.Element: Equatable>(possibleSubsetCollection: C1, collectionToCheckAgainst: C2) -> Bool
{
for itemA in possibleSubsetCollection
{
if !collectionToCheckAgainst.contains(itemA)
{
return false
}
}
// If we get to here then all items in collection A exist in collection B
return true
}
var queueOfStrings = Set<String>()
queueOfStrings.insert("Sam")
queueOfStrings.insert("Ryan")
queueOfStrings.insert("Rob")
//queueOfStrings.insert("Andy") // <- Would cause to return false
var arrayOfStrings = Array<String>()
arrayOfStrings.append("Sam")
arrayOfStrings.append("Ryan")
arrayOfStrings.append("Rob")
collectionIsSubsetOfOtherCollection(queueOfStrings, collectionToCheckAgainst:arrayOfStrings)
//: Tried to implement the above as an extension of CollectionType but had no luck :(´®
//extension CollectionType
//{
// func isSubsetOfCollection<T: CollectionType where T.Generator.Element == Self.Generator.Element, T.Generator.Element: Equatable>(otherCollection: T) -> Bool
// {
// for itemA in self
// {
// var found = false
// for itemB in otherCollection
// {
// if itemA == itemB
// {
// found = true
// }
// }
// if !found
// {
// return false
// }
// }
//
// // If we get to here then all items in collection A exist in collection B
// return true
// }
//}
//arrayOfStrings.isSubsetOfCollection(queueOfStrings)
//:### Associated types
//: Protocols cannot be defined generically using type parameters. Can instead define an **associated type** using `typealias` keyword
protocol FoodItemDigestingType
{
typealias Food: FoodItemType
func eat(food: Food)
func excrete(food: Food)
}
protocol FoodItemType {}
struct Bamboo: FoodItemType {}
struct Honey: FoodItemType {}
struct IronGirder {}
//: Note that if the types we pass in for `eat` and `excrete` don't match we get a compiler error
struct Panda: FoodItemDigestingType
{
func eat(food: Bamboo)
{
}
func excrete(food: Bamboo)
{
}
}
//: **Note:** The below does not compile as we're passing a type that does not conform to `FoodItemType`. This constraint is set by due to: `typealias Food: FoodItemType`
//struct Alien: FoodItemDigestingType {
// func eat(food: IronGirder) {}
//
// func excrete(food: IronGirder) {}
//}
//: [Next](@next)
| 6f6a88f4aafe081e665f2c150a4b2c6e | 25.77707 | 332 | 0.652236 | false | false | false | false |
oliverrussellwhite/JSON | refs/heads/master | JSONTests/JSONTests.swift | unlicense | 1 |
import JSON
import XCTest
class JSONTests: XCTestCase {
func testInit() {
func test(lhs: String, rhs: JSON, file: StaticString = #file, line: UInt = #line) {
do {
let lhs = try JSON(deserializing: Data(lhs.utf8))
XCTAssert(lhs == rhs, file: file, line: line)
}
catch {
XCTFail(file: file, line: line)
}
}
test(lhs: "{}", rhs: .dictionary([:]))
test(lhs: "{\"a\":1}", rhs: .dictionary(["a" : .integer(1)]))
test(lhs: "{\"a\":1,\"b\":2}", rhs: .dictionary(["a" : .integer(1), "b" : .integer(2)]))
test(lhs: "[]", rhs: .array([]))
test(lhs: "[1]", rhs: .array([.integer(1)]))
test(lhs: "[1,2]", rhs: .array([.integer(1), .integer(2)]))
test(lhs: "\"\"", rhs: .string(""))
test(lhs: "\"a\"", rhs: .string("a"))
test(lhs: "\"\\\"\"", rhs: .string("\""))
test(lhs: "\"\\\\\"", rhs: .string("\\"))
test(lhs: "\"\\/\"", rhs: .string("/"))
test(lhs: "\"\\b\"", rhs: .string("\u{8}"))
test(lhs: "\"\\f\"", rhs: .string("\u{c}"))
test(lhs: "\"\\n\"", rhs: .string("\n"))
test(lhs: "\"\\r\"", rhs: .string("\r"))
test(lhs: "\"\\t\"", rhs: .string("\t"))
test(lhs: "\"\\u203d\"", rhs: .string("‽"))
test(lhs: "\"\\ud83d\\ude00\"", rhs: .string("😀"))
test(lhs: "0", rhs: .integer(0))
test(lhs: "-0", rhs: .integer(-0))
test(lhs: "1", rhs: .integer(1))
test(lhs: "-1", rhs: .integer(-1))
test(lhs: "123", rhs: .integer(123))
test(lhs: "-123", rhs: .integer(-123))
test(lhs: "0e003", rhs: .double(0e003))
test(lhs: "-0e003", rhs: .double(-0e003))
test(lhs: "0e-0003", rhs: .double(0e-0003))
test(lhs: "-0e-0003", rhs: .double(-0e-0003))
test(lhs: "0e+003", rhs: .double(0e+003))
test(lhs: "-0e+003", rhs: .double(-0e+003))
test(lhs: "0E003", rhs: .double(0E003))
test(lhs: "-0E003", rhs: .double(-0E003))
test(lhs: "0E-0003", rhs: .double(0E-0003))
test(lhs: "-0E-0003", rhs: .double(-0E-0003))
test(lhs: "0E+003", rhs: .double(0E+003))
test(lhs: "-0E+003", rhs: .double(-0E+003))
test(lhs: "1e003", rhs: .double(1e003))
test(lhs: "-1e003", rhs: .double(-1e003))
test(lhs: "1e-0003", rhs: .double(1e-0003))
test(lhs: "-1e-0003", rhs: .double(-1e-0003))
test(lhs: "1e+003", rhs: .double(1e+003))
test(lhs: "-1e+003", rhs: .double(-1e+003))
test(lhs: "1E003", rhs: .double(1E003))
test(lhs: "-1E003", rhs: .double(-1E003))
test(lhs: "1E-0003", rhs: .double(1E-0003))
test(lhs: "-1E-0003", rhs: .double(-1E-0003))
test(lhs: "1E+003", rhs: .double(1E+003))
test(lhs: "-1E+003", rhs: .double(-1E+003))
test(lhs: "123e003", rhs: .double(123e003))
test(lhs: "-123e003", rhs: .double(-123e003))
test(lhs: "123e-0003", rhs: .double(123e-0003))
test(lhs: "-123e-0003", rhs: .double(-123e-0003))
test(lhs: "123e+003", rhs: .double(123e+003))
test(lhs: "-123e+003", rhs: .double(-123e+003))
test(lhs: "123E003", rhs: .double(123E003))
test(lhs: "-123E003", rhs: .double(-123E003))
test(lhs: "123E-0003", rhs: .double(123E-0003))
test(lhs: "-123E-0003", rhs: .double(-123E-0003))
test(lhs: "123E+003", rhs: .double(123E+003))
test(lhs: "-123E+003", rhs: .double(-123E+003))
test(lhs: "0.123", rhs: .double(0.123))
test(lhs: "-0.123", rhs: .double(-0.123))
test(lhs: "0.123e003", rhs: .double(0.123e003))
test(lhs: "-0.123e003", rhs: .double(-0.123e003))
test(lhs: "0.123e-0003", rhs: .double(0.123e-0003))
test(lhs: "-0.123e-0003", rhs: .double(-0.123e-0003))
test(lhs: "0.123e+003", rhs: .double(0.123e+003))
test(lhs: "-0.123e+003", rhs: .double(-0.123e+003))
test(lhs: "0.123E003", rhs: .double(0.123E003))
test(lhs: "-0.123E003", rhs: .double(-0.123E003))
test(lhs: "0.123E-0003", rhs: .double(0.123E-0003))
test(lhs: "-0.123E-0003", rhs: .double(-0.123E-0003))
test(lhs: "0.123E+003", rhs: .double(0.123E+003))
test(lhs: "-0.123E+003", rhs: .double(-0.123E+003))
test(lhs: "1.123", rhs: .double(1.123))
test(lhs: "-1.123", rhs: .double(-1.123))
test(lhs: "1.123e003", rhs: .double(1.123e003))
test(lhs: "-1.123e003", rhs: .double(-1.123e003))
test(lhs: "1.123e-0003", rhs: .double(1.123e-0003))
test(lhs: "-1.123e-0003", rhs: .double(-1.123e-0003))
test(lhs: "1.123e+003", rhs: .double(1.123e+003))
test(lhs: "-1.123e+003", rhs: .double(-1.123e+003))
test(lhs: "1.123E003", rhs: .double(1.123E003))
test(lhs: "-1.123E003", rhs: .double(-1.123E003))
test(lhs: "1.123E-0003", rhs: .double(1.123E-0003))
test(lhs: "-1.123E-0003", rhs: .double(-1.123E-0003))
test(lhs: "1.123E+003", rhs: .double(1.123E+003))
test(lhs: "-1.123E+003", rhs: .double(-1.123E+003))
test(lhs: "123.123", rhs: .double(123.123))
test(lhs: "-123.123", rhs: .double(-123.123))
test(lhs: "123.123e003", rhs: .double(123.123e003))
test(lhs: "-123.123e003", rhs: .double(-123.123e003))
test(lhs: "123.123e-0003", rhs: .double(123.123e-0003))
test(lhs: "-123.123e-0003", rhs: .double(-123.123e-0003))
test(lhs: "123.123e+003", rhs: .double(123.123e+003))
test(lhs: "-123.123e+003", rhs: .double(-123.123e+003))
test(lhs: "123.123E003", rhs: .double(123.123E003))
test(lhs: "-123.123E003", rhs: .double(-123.123E003))
test(lhs: "123.123E-0003", rhs: .double(123.123E-0003))
test(lhs: "-123.123E-0003", rhs: .double(-123.123E-0003))
test(lhs: "123.123E+003", rhs: .double(123.123E+003))
test(lhs: "-123.123E+003", rhs: .double(-123.123E+003))
test(lhs: "true", rhs: .boolean(true))
test(lhs: "false", rhs: .boolean(false))
test(lhs: "null", rhs: .null)
test(lhs: " \n\r\t{ \n\r\t\"a\" \n\r\t: \n\r\t[ \n\r\ttrue \n\r\t, \n\r\tfalse \n\r\t] \n\r\t, \n\r\t\"b\" \n\r\t: \n\r\tnull \n\r\t} \n\r\t", rhs: .dictionary(["a" : .array([.boolean(true), .boolean(false)]), "b" : .null]))
}
}
| 76dba2182cc890fc1284389aaf35649a | 47.492424 | 232 | 0.513201 | false | true | false | false |
ljshj/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleCell.swift | mit | 1 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
/**
Bubble types
*/
public enum BubbleType {
// Outcome text bubble
case TextOut
// Income text bubble
case TextIn
// Outcome media bubble
case MediaOut
// Income media bubble
case MediaIn
// Service bubble
case Service
// Sticker bubble
case Sticker
}
/**
Root class for bubble layouter. Used for preprocessing bubble layout in background.
*/
public protocol AABubbleLayouter {
func isSuitable(message: ACMessage) -> Bool
func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout
func cellClass() -> AnyClass
}
extension AABubbleLayouter {
func cellReuseId() -> String {
return "cell_\(cellClass())"
}
}
/**
Root class for bubble cells
*/
public class AABubbleCell: UICollectionViewCell {
public static let bubbleContentTop: CGFloat = 6
public static let bubbleContentBottom: CGFloat = 6
public static let bubbleTop: CGFloat = 3
public static let bubbleTopCompact: CGFloat = 1
public static let bubbleBottom: CGFloat = 3
public static let bubbleBottomCompact: CGFloat = 1
public static let avatarPadding: CGFloat = 39
public static let dateSize: CGFloat = 30
public static let newMessageSize: CGFloat = 30
//
// Cached text bubble images
//
private static var cachedOutTextBg = UIImage.tinted("BubbleOutgoingFull", color: ActorSDK.sharedActor().style.chatTextBubbleOutColor)
private static var cachedOutTextBgShadow = ActorSDK.sharedActor().style.bubbleShadowEnabled ? UIImage.tinted("BubbleOutgoingFull", color: ActorSDK.sharedActor().style.chatTextBubbleShadowColor) : UIImage()
private static var cachedOutTextBgBorder = UIImage.tinted("BubbleOutgoingFullBorder", color: ActorSDK.sharedActor().style.chatTextBubbleOutBorderColor)
private static var cachedOutTextCompactBg = UIImage.tinted("BubbleOutgoingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleOutColor)
private static var cachedOutTextCompactBgShadow = ActorSDK.sharedActor().style.bubbleShadowEnabled ? UIImage.tinted("BubbleOutgoingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleShadowColor) : UIImage()
private static var cachedOutTextCompactSelectedBg = UIImage.tinted("BubbleOutgoingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleOutSelectedColor)
private static var cachedOutTextCompactBgBorder = UIImage.tinted("BubbleOutgoingPartialBorder", color: ActorSDK.sharedActor().style.chatTextBubbleOutBorderColor)
private static var cachedInTextBg = UIImage.tinted("BubbleIncomingFull", color: ActorSDK.sharedActor().style.chatTextBubbleInColor)
private static var cachedInTextBgShadow = ActorSDK.sharedActor().style.bubbleShadowEnabled ? UIImage.tinted("BubbleIncomingFull", color: ActorSDK.sharedActor().style.chatTextBubbleShadowColor) : UIImage()
private static var cachedInTextBgBorder = UIImage.tinted("BubbleIncomingFullBorder", color: ActorSDK.sharedActor().style.chatTextBubbleInBorderColor)
private static var cachedInTextCompactBg = UIImage.tinted("BubbleIncomingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleInColor)
private static var cachedInTextCompactBgShadow = ActorSDK.sharedActor().style.bubbleShadowEnabled ?UIImage.tinted("BubbleIncomingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleShadowColor) : UIImage()
private static var cachedInTextCompactSelectedBg = UIImage.tinted("BubbleIncomingPartial", color: ActorSDK.sharedActor().style.chatTextBubbleInSelectedColor)
private static var cachedInTextCompactBgBorder = UIImage.tinted("BubbleIncomingPartialBorder", color: ActorSDK.sharedActor().style.chatTextBubbleInBorderColor)
//
// Cached media bubble images
//
private static let cachedMediaBg = UIImage.tinted("BubbleOutgoingPartial", color: ActorSDK.sharedActor().style.chatMediaBubbleColor)
private static var cachedMediaBgBorder = UIImage.tinted("BubbleOutgoingPartialBorder", color: ActorSDK.sharedActor().style.chatMediaBubbleBorderColor)
//
// Cached Service bubble images
//
private static var cachedServiceBg:UIImage = Imaging.roundedImage(ActorSDK.sharedActor().style.chatServiceBubbleColor, size: CGSizeMake(18, 18), radius: 9)
//
// Cached Date bubble images
//
// private static var dateBgImage = Imaging.roundedImage(ActorSDK.sharedActor().style.chatDateBubbleColor, size: CGSizeMake(18, 18), radius: 9)
private static var dateBgImage = ActorSDK.sharedActor().style.statusBackgroundImage
// MARK: -
// MARK: Public vars
// Views
public let avatarView = AAAvatarView()
public var avatarAdded: Bool = false
public let bubble = UIImageView()
public let bubbleShadow = UIImageView()
public let bubbleBorder = UIImageView()
private let dateText = UILabel()
private let dateBg = UIImageView()
private let newMessage = UILabel()
// Layout
public var contentInsets : UIEdgeInsets = UIEdgeInsets()
public var bubbleInsets : UIEdgeInsets = UIEdgeInsets()
public var fullContentInsets : UIEdgeInsets {
get {
return UIEdgeInsets(
top: contentInsets.top + bubbleInsets.top + (isShowDate ? AABubbleCell.dateSize : 0) + (isShowNewMessages ? AABubbleCell.newMessageSize : 0),
left: contentInsets.left + bubbleInsets.left + (isGroup && !isOut ? AABubbleCell.avatarPadding : 0),
bottom: contentInsets.bottom + bubbleInsets.bottom,
right: contentInsets.right + bubbleInsets.right)
}
}
public var needLayout: Bool = true
public let groupContentInsetY = 20.0
public let groupContentInsetX = 40.0
public var bubbleVerticalSpacing: CGFloat = 6.0
public let bubblePadding: CGFloat = 6;
public let bubbleMediaPadding: CGFloat = 10;
// Binded data
public var peer: ACPeer!
public weak var controller: AAConversationContentController!
public var isGroup: Bool = false
public var isFullSize: Bool!
public var bindedSetting: AACellSetting?
public var bindedMessage: ACMessage? = nil
public var bubbleType:BubbleType? = nil
public var isOut: Bool = false
public var isShowDate: Bool = false
public var isShowNewMessages: Bool = false
var appStyle: ActorStyle {
get {
return ActorSDK.sharedActor().style
}
}
// MARK: -
// MARK: Constructors
public init(frame: CGRect, isFullSize: Bool) {
super.init(frame: frame)
self.isFullSize = isFullSize
dateBg.image = AABubbleCell.dateBgImage
dateText.font = UIFont.mediumSystemFontOfSize(12)
dateText.textColor = appStyle.chatDateTextColor
dateText.contentMode = UIViewContentMode.Center
dateText.textAlignment = NSTextAlignment.Center
newMessage.font = UIFont.mediumSystemFontOfSize(14)
newMessage.textColor = appStyle.chatUnreadTextColor
newMessage.contentMode = UIViewContentMode.Center
newMessage.textAlignment = NSTextAlignment.Center
newMessage.backgroundColor = appStyle.chatUnreadBgColor
newMessage.text = AALocalized("ChatNewMessages")
//"New Messages"
contentView.transform = CGAffineTransformMake(1, 0, 0, -1, 0, 0)
ActorSDK.sharedActor().style.bubbleShadowEnabled ? contentView.addSubview(bubbleShadow) : print("go to light!")
contentView.addSubview(bubble)
contentView.addSubview(bubbleBorder)
contentView.addSubview(newMessage)
contentView.addSubview(dateBg)
contentView.addSubview(dateText)
avatarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleCell.avatarDidTap)))
avatarView.userInteractionEnabled = true
backgroundColor = UIColor.clearColor()
// Speed up animations
self.layer.speed = 1.5
//self.layer.shouldRasterize = true
//self.layer.rasterizationScale = UIScreen.mainScreen().scale
//self.layer.drawsAsynchronously = true
//self.contentView.layer.drawsAsynchronously = true
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setConfig(peer: ACPeer, controller: AAConversationContentController) {
self.peer = peer
self.controller = controller
if (peer.isGroup && !isFullSize) {
self.isGroup = true
}
}
public override func canBecomeFirstResponder() -> Bool {
return false
}
public override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == #selector(NSObject.delete(_:)) {
return true
}
return false
}
public override func delete(sender: AnyObject?) {
let rids = IOSLongArray(length: 1)
rids.replaceLongAtIndex(0, withLong: bindedMessage!.rid)
Actor.deleteMessagesWithPeer(self.peer, withRids: rids)
}
func avatarDidTap() {
if bindedMessage != nil {
controller.onBubbleAvatarTap(self.avatarView, uid: bindedMessage!.senderId)
}
}
public func performBind(message: ACMessage, receiveDate: jlong, readDate: jlong, setting: AACellSetting, isShowNewMessages: Bool, layout: AACellLayout) {
var reuse = false
if (bindedMessage != nil && bindedMessage?.rid == message.rid) {
reuse = true
}
isOut = message.senderId == Actor.myUid();
bindedMessage = message
self.isShowNewMessages = isShowNewMessages
if !reuse && !isFullSize {
if (!isOut && isGroup) {
let user = Actor.getUserWithUid(message.senderId)
// Small hack for replacing senter name and title
// with current group title
if user.isBot() && user.getNameModel().get() == "Bot" {
let group = Actor.getGroupWithGid(self.peer.peerId)
let avatar: ACAvatar? = group.getAvatarModel().get()
let name = group.getNameModel().get()
avatarView.bind(name, id: Int(user.getId()), avatar: avatar)
} else {
let avatar: ACAvatar? = user.getAvatarModel().get()
let name = user.getNameModel().get()
avatarView.bind(name, id: Int(user.getId()), avatar: avatar)
}
if !avatarAdded {
contentView.addSubview(avatarView)
avatarAdded = true
}
} else {
if avatarAdded {
avatarView.removeFromSuperview()
avatarAdded = false
}
}
}
self.isShowDate = setting.showDate
if (isShowDate) {
self.dateText.text = layout.anchorDate
}
self.bindedSetting = setting
bind(message, receiveDate: receiveDate, readDate: readDate, reuse: reuse, cellLayout: layout, setting: setting)
if (!reuse) {
needLayout = true
super.setNeedsLayout()
}
}
public func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) {
fatalError("bind(message:) has not been implemented")
}
public func bindBubbleType(type: BubbleType, isCompact: Bool) {
self.bubbleType = type
// Update Bubble background images
switch(type) {
case BubbleType.TextIn:
if (isCompact) {
bubbleShadow.image = AABubbleCell.cachedInTextCompactBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedInTextCompactBgShadow
bubble.image = AABubbleCell.cachedInTextCompactBg
bubbleBorder.image = AABubbleCell.cachedInTextCompactBgBorder
bubble.highlightedImage = AABubbleCell.cachedInTextCompactSelectedBg
bubbleBorder.highlightedImage = AABubbleCell.cachedInTextCompactBgBorder
} else {
bubbleShadow.image = AABubbleCell.cachedInTextBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedInTextBgShadow
bubble.image = AABubbleCell.cachedInTextBg
bubbleBorder.image = AABubbleCell.cachedInTextBgBorder
bubble.highlightedImage = AABubbleCell.cachedInTextBg
bubbleBorder.highlightedImage = AABubbleCell.cachedInTextBgBorder
}
break
case BubbleType.TextOut:
if (isCompact) {
bubbleShadow.image = AABubbleCell.cachedOutTextCompactBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedOutTextCompactBgShadow
bubble.image = AABubbleCell.cachedOutTextCompactBg
bubbleBorder.image = AABubbleCell.cachedOutTextCompactBgBorder
bubble.highlightedImage = AABubbleCell.cachedOutTextCompactSelectedBg
bubbleBorder.highlightedImage = AABubbleCell.cachedOutTextCompactBgBorder
} else {
bubbleShadow.image = AABubbleCell.cachedOutTextBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedOutTextBgShadow
bubble.image = AABubbleCell.cachedOutTextBg
bubbleBorder.image = AABubbleCell.cachedOutTextBgBorder
bubble.highlightedImage = AABubbleCell.cachedOutTextBg
bubbleBorder.highlightedImage = AABubbleCell.cachedOutTextBgBorder
}
break
case BubbleType.MediaIn:
bubble.image = AABubbleCell.cachedMediaBg
bubbleBorder.image = AABubbleCell.cachedMediaBgBorder
bubble.highlightedImage = AABubbleCell.cachedMediaBg
bubbleBorder.highlightedImage = AABubbleCell.cachedMediaBgBorder
break
case BubbleType.MediaOut:
bubble.image = AABubbleCell.cachedMediaBg
bubbleBorder.image = AABubbleCell.cachedMediaBgBorder
bubble.highlightedImage = AABubbleCell.cachedMediaBg
bubbleBorder.highlightedImage = AABubbleCell.cachedMediaBgBorder
break
case BubbleType.Service:
bubble.image = AABubbleCell.cachedServiceBg
bubbleBorder.image = nil
bubble.highlightedImage = AABubbleCell.cachedServiceBg
bubbleBorder.highlightedImage = nil
break
case BubbleType.Sticker:
bubble.image = nil;
bubbleBorder.image = nil
bubble.highlightedImage = nil;
bubbleBorder.highlightedImage = nil
break
}
}
func updateView() {
let type = self.bubbleType! as BubbleType
switch (type) {
case BubbleType.TextIn:
if (!isFullSize!) {
bubbleShadow.image = AABubbleCell.cachedInTextCompactBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedInTextCompactBgShadow
bubble.image = AABubbleCell.cachedInTextCompactBg
bubbleBorder.image = AABubbleCell.cachedInTextCompactBgBorder
bubble.highlightedImage = AABubbleCell.cachedInTextCompactSelectedBg
bubbleBorder.highlightedImage = AABubbleCell.cachedInTextCompactBgBorder
} else {
bubbleShadow.image = AABubbleCell.cachedInTextBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedInTextBgShadow
bubble.image = AABubbleCell.cachedInTextBg
bubbleBorder.image = AABubbleCell.cachedInTextBgBorder
bubble.highlightedImage = AABubbleCell.cachedInTextBg
bubbleBorder.highlightedImage = AABubbleCell.cachedInTextBgBorder
}
break
case BubbleType.TextOut:
if (!isFullSize!) {
bubbleShadow.image = AABubbleCell.cachedOutTextCompactBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedOutTextCompactBgShadow
bubble.image = AABubbleCell.cachedOutTextCompactBg
bubbleBorder.image = AABubbleCell.cachedOutTextCompactBgBorder
bubble.highlightedImage = AABubbleCell.cachedOutTextCompactSelectedBg
bubbleBorder.highlightedImage = AABubbleCell.cachedOutTextCompactBgBorder
} else {
bubbleShadow.image = AABubbleCell.cachedOutTextBgShadow
bubbleShadow.highlightedImage = AABubbleCell.cachedOutTextBgShadow
bubble.image = AABubbleCell.cachedOutTextBg
bubbleBorder.image = AABubbleCell.cachedOutTextBgBorder
bubble.highlightedImage = AABubbleCell.cachedOutTextBg
bubbleBorder.highlightedImage = AABubbleCell.cachedOutTextBgBorder
}
break
case BubbleType.MediaIn:
bubble.image = AABubbleCell.cachedMediaBg
bubbleBorder.image = AABubbleCell.cachedMediaBgBorder
bubble.highlightedImage = AABubbleCell.cachedMediaBg
bubbleBorder.highlightedImage = AABubbleCell.cachedMediaBgBorder
break
case BubbleType.MediaOut:
bubble.image = AABubbleCell.cachedMediaBg
bubbleBorder.image = AABubbleCell.cachedMediaBgBorder
bubble.highlightedImage = AABubbleCell.cachedMediaBg
bubbleBorder.highlightedImage = AABubbleCell.cachedMediaBgBorder
break
case BubbleType.Service:
bubble.image = AABubbleCell.cachedServiceBg
bubbleBorder.image = nil
bubble.highlightedImage = AABubbleCell.cachedServiceBg
bubbleBorder.highlightedImage = nil
break
case BubbleType.Sticker:
bubble.image = nil;
bubbleBorder.image = nil
bubble.highlightedImage = nil;
bubbleBorder.highlightedImage = nil
break
}
}
// MARK: -
// MARK: Layout
public override func layoutSubviews() {
super.layoutSubviews()
UIView.performWithoutAnimation { () -> Void in
let endPadding: CGFloat = 32
let startPadding: CGFloat = (!self.isOut && self.isGroup) ? AABubbleCell.avatarPadding : 0
let cellMaxWidth = self.contentView.frame.size.width - endPadding - startPadding
self.layoutContent(cellMaxWidth, offsetX: startPadding)
self.layoutAnchor()
if (!self.isOut && self.isGroup && !self.isFullSize) {
self.layoutAvatar()
}
}
}
func layoutAnchor() {
if (isShowDate) {
dateText.frame = CGRectMake(0, 0, 1000, 1000)
dateText.sizeToFit()
dateText.frame = CGRectMake(
(self.contentView.frame.size.width-dateText.frame.width)/2, 8, dateText.frame.width, 18)
dateBg.frame = CGRectMake(dateText.frame.minX - 8, dateText.frame.minY, dateText.frame.width + 16, 18)
dateText.hidden = false
dateBg.hidden = false
} else {
dateText.hidden = true
dateBg.hidden = true
}
if (isShowNewMessages) {
var top = CGFloat(0)
if (isShowDate) {
top += AABubbleCell.dateSize
}
newMessage.hidden = false
newMessage.frame = CGRectMake(0, top + CGFloat(2), self.contentView.frame.width, AABubbleCell.newMessageSize - CGFloat(4))
} else {
newMessage.hidden = true
}
}
public func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) {
}
func layoutAvatar() {
let avatarSize = CGFloat(42)
avatarView.frame = CGRect(x: 5 + (AADevice.isiPad ? 16 : 0), y: self.contentView.frame.size.height - avatarSize - 2 - bubbleInsets.bottom, width: avatarSize, height: avatarSize)
}
// Need to be called in child cells
public func layoutBubble(contentWidth: CGFloat, contentHeight: CGFloat) {
let fullWidth = contentView.bounds.width
let bubbleW = contentWidth + contentInsets.left + contentInsets.right
let bubbleH = contentHeight + contentInsets.top + contentInsets.bottom
var topOffset = CGFloat(0)
if (isShowDate) {
topOffset += AABubbleCell.dateSize
}
if (isShowNewMessages) {
topOffset += AABubbleCell.newMessageSize
}
var bubbleFrame : CGRect!
if (!isFullSize) {
if (isOut) {
bubbleFrame = CGRect(
x: fullWidth - contentWidth - contentInsets.left - contentInsets.right - bubbleInsets.right,
y: bubbleInsets.top + topOffset,
width: bubbleW,
height: bubbleH)
} else {
let padding : CGFloat = isGroup ? AABubbleCell.avatarPadding : 0
bubbleFrame = CGRect(
x: bubbleInsets.left + padding,
y: bubbleInsets.top + topOffset,
width: bubbleW,
height: bubbleH)
}
} else {
bubbleFrame = CGRect(
x: (fullWidth - contentWidth - contentInsets.left - contentInsets.right)/2,
y: bubbleInsets.top + topOffset,
width: bubbleW,
height: bubbleH)
}
bubble.frame = bubbleFrame
bubbleBorder.frame = bubbleFrame
bubbleShadow.frame = CGRect(
x: bubbleFrame.minX + 1,
y: bubbleFrame.minY + 1,
width: bubbleW,
height: bubbleH)
}
public func layoutBubble(frame: CGRect) {
bubble.frame = frame
bubbleBorder.frame = frame
bubbleShadow.frame = frame
}
public override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
return layoutAttributes
}
}
| 593159ef53e5858391f2938bf6fe11f1 | 41.745318 | 219 | 0.639972 | false | false | false | false |
efremidze/Cluster | refs/heads/master | Example/Extensions.swift | mit | 1 | //
// Extensions.swift
// Cluster
//
// Created by Lasha Efremidze on 7/8/17.
// Copyright © 2017 efremidze. All rights reserved.
//
import UIKit
import MapKit
extension UIImage {
func filled(with color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let mask = self.cgImage else { return self }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
static let pin = UIImage(named: "pin")?.filled(with: .green)
static let pin2 = UIImage(named: "pin2")?.filled(with: .green)
static let me = UIImage(named: "me")?.filled(with: .blue)
}
extension UIColor {
class var green: UIColor { return UIColor(red: 76 / 255, green: 217 / 255, blue: 100 / 255, alpha: 1) }
class var blue: UIColor { return UIColor(red: 0, green: 122 / 255, blue: 1, alpha: 1) }
}
extension MKMapView {
func annotationView<T: MKAnnotationView>(of type: T.Type, annotation: MKAnnotation?, reuseIdentifier: String) -> T {
guard let annotationView = dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? T else {
return type.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
annotationView.annotation = annotation
return annotationView
}
}
| 67ebfaef6b6270eedc35523b0d68f362 | 34.897959 | 120 | 0.66174 | false | false | false | false |
coderLL/DYTV | refs/heads/master | DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// DYTV
//
// Created by CodeLL on 2016/10/15.
// Copyright © 2016年 coderLL. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
// MARK:- 定义属性
var baseContentView : UIView?
// MARK:- 懒加载属性
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "home_header_normal"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "home_header_normal")!, UIImage(named: "home_header_hot")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
}
// MARK:- 添加UI界面
extension BaseViewController {
// MARK:- 设置UI界面
func setupUI() {
// 1.先隐藏内容的view
self.baseContentView?.isHidden = true
// 2.添加执行动画的UIImageView
self.view.addSubview(animImageView)
// 3.给UIImageView执行动画
self.animImageView.startAnimating()
// 4.设置背景颜色
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
// MARK:- 数据请求完成
func loadDataFinished() {
// 1.停止动画
self.animImageView.stopAnimating()
// 2.隐藏animImageView
self.animImageView.isHidden = true
// 3.显示内容的view
self.baseContentView?.isHidden = false
}
}
| 628aa9d29376017932dc4a9f03c32fd2 | 23.939394 | 111 | 0.602673 | false | false | false | false |
lucaswoj/sugar.swift | refs/heads/master | SugarEventStream.swift | mit | 1 | //
// SugarEventStream.swift
// Sugar
//
// Created by Lucas Wojciechowski on 10/20/14.
// Copyright (c) 2014 Scree Apps. All rights reserved.
//
import Foundation
class SugarEventStream<T> {
init() {}
var handlers:[(handler:Handler, once:Bool, queue:NSOperationQueue?)] = []
typealias Handler = T -> Void
func addHandler(handler:Handler, once:Bool = false, queue:NSOperationQueue? = nil) {
handlers.append((handler: handler, once: once, queue:queue))
}
func trigger(value:T) {
for (index, (handler, once, queue)) in enumerate(handlers) {
if queue == nil {
handler(value)
} else {
queue!.addOperation(NSBlockOperation({
handler(value)
}))
}
if once {
handlers.removeAtIndex(index)
}
}
}
} | 45251ff5d742fbb39abf4bcaf848fc09 | 22.025641 | 88 | 0.548495 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/SimpleRedux/State.swift | mit | 1 | //
// State.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-24.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
struct State {
let isLoginRequired: Bool
let rootModal: RootModal
let showFiatAmounts: Bool
let alert: AlertType
let defaultCurrencyCode: String
let isPushNotificationsEnabled: Bool
let isPromptingBiometrics: Bool
let pinLength: Int
let walletID: String?
let wallets: [CurrencyId: WalletState]
var experiments: [Experiment]?
let creationRequired: [CurrencyId]
subscript(currency: Currency) -> WalletState? {
guard let walletState = wallets[currency.uid] else {
return nil
}
return walletState
}
var orderedWallets: [WalletState] {
return wallets.values.sorted(by: { $0.displayOrder < $1.displayOrder })
}
var currencies: [Currency] {
return orderedWallets.map { $0.currency }
}
var shouldShowBuyNotificationForDefaultCurrency: Bool {
switch defaultCurrencyCode {
// Currencies eligible for Coinify.
case C.euroCurrencyCode,
C.britishPoundCurrencyCode,
C.danishKroneCurrencyCode:
return true
default:
return false
}
}
}
extension State {
static var initial: State {
return State( isLoginRequired: true,
rootModal: .none,
showFiatAmounts: UserDefaults.showFiatAmounts,
alert: .none,
defaultCurrencyCode: UserDefaults.defaultCurrencyCode,
isPushNotificationsEnabled: UserDefaults.pushToken != nil,
isPromptingBiometrics: false,
pinLength: 6,
walletID: nil,
wallets: [:],
experiments: nil,
creationRequired: []
)
}
func mutate( isOnboardingEnabled: Bool? = nil,
isLoginRequired: Bool? = nil,
rootModal: RootModal? = nil,
showFiatAmounts: Bool? = nil,
alert: AlertType? = nil,
defaultCurrencyCode: String? = nil,
isPushNotificationsEnabled: Bool? = nil,
isPromptingBiometrics: Bool? = nil,
pinLength: Int? = nil,
walletID: String? = nil,
wallets: [CurrencyId: WalletState]? = nil,
experiments: [Experiment]? = nil,
creationRequired: [CurrencyId]? = nil) -> State {
return State(isLoginRequired: isLoginRequired ?? self.isLoginRequired,
rootModal: rootModal ?? self.rootModal,
showFiatAmounts: showFiatAmounts ?? self.showFiatAmounts,
alert: alert ?? self.alert,
defaultCurrencyCode: defaultCurrencyCode ?? self.defaultCurrencyCode,
isPushNotificationsEnabled: isPushNotificationsEnabled ?? self.isPushNotificationsEnabled,
isPromptingBiometrics: isPromptingBiometrics ?? self.isPromptingBiometrics,
pinLength: pinLength ?? self.pinLength,
walletID: walletID ?? self.walletID,
wallets: wallets ?? self.wallets,
experiments: experiments ?? self.experiments,
creationRequired: creationRequired ?? self.creationRequired)
}
func mutate(walletState: WalletState) -> State {
var wallets = self.wallets
wallets[walletState.currency.uid] = walletState
return mutate(wallets: wallets)
}
}
// MARK: - Experiments
extension State {
public func experimentWithName(_ experimentName: ExperimentName) -> Experiment? {
guard let set = experiments, let exp = set.first(where: { $0.name == experimentName.rawValue }) else { return nil }
return exp
}
public func requiresCreation(_ currency: Currency) -> Bool {
return creationRequired.contains(currency.uid)
}
}
// MARK: -
enum RootModal {
case none
case send(currency: Currency)
case receive(currency: Currency)
case loginScan
case requestAmount(currency: Currency, address: String)
case buy(currency: Currency?)
case sell(currency: Currency?)
case trade
case receiveLegacy
case stake(currency: Currency)
case gift
}
enum SyncState {
case syncing
case connecting
case success
case failed
}
// MARK: -
struct WalletState {
let currency: Currency
weak var wallet: Wallet?
let displayOrder: Int // -1 for hidden
let syncProgress: Float
let syncState: SyncState
let balance: Amount?
let lastBlockTimestamp: UInt32
let isRescanning: Bool
var receiveAddress: String? {
return wallet?.receiveAddress
}
let currentRate: Rate?
let fiatPriceInfo: FiatPriceInfo?
static func initial(_ currency: Currency, wallet: Wallet? = nil, displayOrder: Int) -> WalletState {
return WalletState(currency: currency,
wallet: wallet,
displayOrder: displayOrder,
syncProgress: 0.0,
syncState: .success,
balance: UserDefaults.balance(forCurrency: currency),
lastBlockTimestamp: 0,
isRescanning: false,
currentRate: UserDefaults.currentRate(forCode: currency.code),
fiatPriceInfo: nil)
}
func mutate( wallet: Wallet? = nil,
displayOrder: Int? = nil,
syncProgress: Float? = nil,
syncState: SyncState? = nil,
balance: Amount? = nil,
lastBlockTimestamp: UInt32? = nil,
isRescanning: Bool? = nil,
receiveAddress: String? = nil,
legacyReceiveAddress: String? = nil,
currentRate: Rate? = nil,
fiatPriceInfo: FiatPriceInfo? = nil) -> WalletState {
return WalletState(currency: self.currency,
wallet: wallet ?? self.wallet,
displayOrder: displayOrder ?? self.displayOrder,
syncProgress: syncProgress ?? self.syncProgress,
syncState: syncState ?? self.syncState,
balance: balance ?? self.balance,
lastBlockTimestamp: lastBlockTimestamp ?? self.lastBlockTimestamp,
isRescanning: isRescanning ?? self.isRescanning,
currentRate: currentRate ?? self.currentRate,
fiatPriceInfo: fiatPriceInfo ?? self.fiatPriceInfo)
}
}
extension WalletState: Equatable {}
func == (lhs: WalletState, rhs: WalletState) -> Bool {
return lhs.currency == rhs.currency &&
lhs.wallet?.currency == rhs.wallet?.currency &&
lhs.syncProgress == rhs.syncProgress &&
lhs.syncState == rhs.syncState &&
lhs.balance == rhs.balance &&
lhs.lastBlockTimestamp == rhs.lastBlockTimestamp &&
lhs.isRescanning == rhs.isRescanning &&
lhs.currentRate == rhs.currentRate
}
extension RootModal: Equatable {}
func == (lhs: RootModal, rhs: RootModal) -> Bool {
switch(lhs, rhs) {
case (.none, .none):
return true
case (.send(let lhsCurrency), .send(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.receive(let lhsCurrency), .receive(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.loginScan, .loginScan):
return true
case (.requestAmount(let lhsCurrency, let lhsAddress), .requestAmount(let rhsCurrency, let rhsAddress)):
return lhsCurrency == rhsCurrency && lhsAddress == rhsAddress
case (.buy(let lhsCurrency?), .buy(let rhsCurrency?)):
return lhsCurrency == rhsCurrency
case (.buy(nil), .buy(nil)):
return true
case (.sell(let lhsCurrency?), .sell(let rhsCurrency?)):
return lhsCurrency == rhsCurrency
case (.sell(nil), .sell(nil)):
return true
case (.trade, .trade):
return true
case (.receiveLegacy, .receiveLegacy):
return true
case (.stake(let lhsCurrency), .stake(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.gift, .gift):
return true
default:
return false
}
}
extension Currency {
var state: WalletState? {
return Store.state[self]
}
var wallet: Wallet? {
return Store.state[self]?.wallet
}
}
| 269ad77193bdb3801bdd50438df5deec | 34.090909 | 123 | 0.577382 | false | false | false | false |
GreenCom-Networks/ios-charts | refs/heads/master | Advanced/Pods/Charts/Charts/Classes/Charts/BubbleChartView.swift | apache-2.0 | 7 | //
// BubbleChartView.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BubbleChartView: BarLineChartViewBase, BubbleChartDataProvider
{
public override func initialize()
{
super.initialize()
renderer = BubbleChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
public override func calcMinMax()
{
super.calcMinMax()
guard let data = _data else { return }
if _xAxis.axisRange == 0.0 && data.yValCount > 0
{
_xAxis.axisRange = 1.0
}
_xAxis._axisMinimum = -0.5
_xAxis._axisMaximum = Double(data.xVals.count) - 0.5
if renderer as? BubbleChartRenderer !== nil,
let sets = data.dataSets as? [IBubbleChartDataSet]
{
for set in sets {
let xmin = set.xMin
let xmax = set.xMax
if (xmin < _xAxis._axisMinimum)
{
_xAxis._axisMinimum = xmin
}
if (xmax > _xAxis._axisMaximum)
{
_xAxis._axisMaximum = xmax
}
}
}
_xAxis.axisRange = abs(_xAxis._axisMaximum - _xAxis._axisMinimum)
}
// MARK: - BubbleChartDataProbider
public var bubbleData: BubbleChartData? { return _data as? BubbleChartData }
} | 35c09d08acfcf81c625266e79aea0a49 | 25.539683 | 114 | 0.530221 | false | false | false | false |
ArthurKK/Bond | refs/heads/master | Bond/Extensions/OSX/NSTableView+Bond.swift | apache-2.0 | 10 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Michail Pishchagin (@mblsha)
//
// 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
public protocol BNDTableViewDelegate {
typealias Element
func createCell(row: Int, array: ObservableArray<Element>, tableView: NSTableView) -> NSTableCellView
}
class BNDTableViewDataSource<DelegateType: BNDTableViewDelegate>: NSObject, NSTableViewDataSource, NSTableViewDelegate {
private let array: ObservableArray<DelegateType.Element>
private weak var tableView: NSTableView!
private var delegate: DelegateType?
private init(array: ObservableArray<DelegateType.Element>, tableView: NSTableView, delegate: DelegateType) {
self.tableView = tableView
self.delegate = delegate
self.array = array
super.init()
tableView.setDataSource(self)
tableView.setDelegate(self)
tableView.reloadData()
array.observeNew { [weak self] arrayEvent in
guard let unwrappedSelf = self,
tableView = unwrappedSelf.tableView else { return }
switch arrayEvent.operation {
case .Batch(let operations):
tableView.beginUpdates()
for diff in changeSetsFromBatchOperations(operations) {
BNDTableViewDataSource.applyRowUnitChangeSet(diff, tableView: tableView)
}
tableView.endUpdates()
case .Reset:
tableView.reloadData()
default:
tableView.beginUpdates()
BNDTableViewDataSource.applyRowUnitChangeSet(arrayEvent.operation.changeSet(), tableView: tableView)
tableView.endUpdates()
}
}.disposeIn(bnd_bag)
}
private class func applyRowUnitChangeSet(changeSet: ObservableArrayEventChangeSet, tableView: NSTableView) {
switch changeSet {
case .Inserts(let indices):
// FIXME: How to use .Automatic effect a-la UIKit?
tableView.insertRowsAtIndexes(NSIndexSet(set: indices), withAnimation: .EffectNone)
case .Updates(let indices):
tableView.reloadDataForRowIndexes(NSIndexSet(set: indices), columnIndexes: NSIndexSet())
case .Deletes(let indices):
tableView.removeRowsAtIndexes(NSIndexSet(set: indices), withAnimation: .EffectNone)
}
}
/// MARK - NSTableViewDataSource
@objc func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return array.count
}
/// MARK - NSTableViewDelegate
@objc func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
return delegate?.createCell(row, array: array, tableView: tableView)
}
override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? {
guard let delegate = delegate as? AnyObject
where delegate.respondsToSelector(aSelector) else {
return self
}
return delegate
}
override func respondsToSelector(aSelector: Selector) -> Bool {
guard let delegate = delegate as? AnyObject
where delegate.respondsToSelector(aSelector) else {
return super.respondsToSelector(aSelector)
}
return true
}
}
extension NSTableView {
private struct AssociatedKeys {
static var BondDataSourceKey = "bnd_BondDataSourceKey"
}
}
public extension EventProducerType where EventType: ObservableArrayEventType {
private typealias ElementType = EventType.ObservableArrayEventSequenceType.Generator.Element
public func bindTo<DelegateType: BNDTableViewDelegate where DelegateType.Element == ElementType>(tableView: NSTableView, delegate: DelegateType) -> DisposableType {
let array: ObservableArray<ElementType>
if let downcastedarray = self as? ObservableArray<ElementType> {
array = downcastedarray
} else {
array = self.crystallize()
}
let dataSource = BNDTableViewDataSource<DelegateType>(array: array, tableView: tableView, delegate: delegate)
objc_setAssociatedObject(tableView, NSTableView.AssociatedKeys.BondDataSourceKey, dataSource, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return BlockDisposable { [weak tableView] in
if let tableView = tableView {
objc_setAssociatedObject(tableView, NSTableView.AssociatedKeys.BondDataSourceKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
| 5bb726482985db616ce2f6e90010d4d2 | 36.877698 | 166 | 0.74245 | false | false | false | false |
sarunw/NavigationBarManager | refs/heads/master | Example/NavigationBarManager/ViewController.swift | mit | 1 | //
// ViewController.swift
// NavigationBarManager
//
// Created by Sarun Wongpatcharapakorn on 12/01/2016.
// Copyright (c) 2016 Sarun Wongpatcharapakorn. All rights reserved.
//
import UIKit
import NavigationBarManager
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var refreshControl: UIRefreshControl!
var navBarManager: NavigationBarManager!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navBarManager = NavigationBarManager(viewController: self, scrollView: collectionView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(didPullToRefresh(sender:)), for: .valueChanged)
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
// Fallback on earlier versions
collectionView.addSubview(refreshControl)
}
let rect = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 100)
let redView = UIView(frame: rect)
redView.backgroundColor = UIColor.red
navBarManager.extensionView = redView
}
func didPullToRefresh(sender: AnyObject) {
longRunningProcess()
}
private func longRunningProcess() {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2, execute: {
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Collection View
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
clear()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
private var numberOfItems = 10
@IBAction func didTapLoad(_ sender: Any) {
load()
}
private func clear() {
numberOfItems = 0
collectionView.reloadData()
}
private func load() {
numberOfItems = 10
collectionView.reloadData()
}
// MARK: - Scroll View
func scrollViewDidScroll(_ scrollView: UIScrollView) {
navBarManager.handleScrollViewDidScroll(scrollView: scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == true {
// have inertia, handle in scrollViewDidEndDecelerating
return
}
navBarManager.handleScrollViewDidEnd(scrollView: scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// stop
navBarManager.handleScrollViewDidEnd(scrollView: scrollView)
}
}
| 45d8e8d7b7f19f51dfb0d5e3f9ce4b6e | 29.348214 | 121 | 0.652545 | false | false | false | false |
wnagrodzki/DragGestureRecognizer | refs/heads/master | DragGestureRecognizer/DragGestureRecognizer.swift | mit | 1 | //
// DragGestureRecognizer.swift
// DragGestureRecognizer
//
// Created by Wojciech Nagrodzki on 01/09/16.
// Copyright © 2016 Wojciech Nagrodzki. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
/// `DragGestureRecognizer` is a subclass of `UILongPressGestureRecognizer` that allows for tracking translation similarly to `UIPanGestureRecognizer`.
class DragGestureRecognizer: UILongPressGestureRecognizer {
private var initialTouchLocationInScreenFixedCoordinateSpace: CGPoint?
private var initialTouchLocationsInViews = [UIView: CGPoint]()
/// The total translation of the drag gesture in the coordinate system of the specified view.
/// - parameters:
/// - view: The view in whose coordinate system the translation of the drag gesture should be computed. Pass `nil` to indicate window.
func translation(in view: UIView?) -> CGPoint {
// not attached to a view or outside window
guard let window = self.view?.window else { return CGPoint() }
// gesture not in progress
guard let initialTouchLocationInScreenFixedCoordinateSpace = initialTouchLocationInScreenFixedCoordinateSpace else { return CGPoint() }
let initialLocation: CGPoint
let currentLocation: CGPoint
if let view = view {
initialLocation = initialTouchLocationsInViews[view] ?? window.screen.fixedCoordinateSpace.convert(initialTouchLocationInScreenFixedCoordinateSpace, to: view)
currentLocation = location(in: view)
}
else {
initialLocation = initialTouchLocationInScreenFixedCoordinateSpace
currentLocation = location(in: nil)
}
return CGPoint(x: currentLocation.x - initialLocation.x, y: currentLocation.y - initialLocation.y)
}
/// Sets the translation value in the coordinate system of the specified view.
/// - parameters:
/// - translation: A point that identifies the new translation value.
/// - view: A view in whose coordinate system the translation is to occur. Pass `nil` to indicate window.
func setTranslation(_ translation: CGPoint, in view: UIView?) {
// not attached to a view or outside window
guard let window = self.view?.window else { return }
// gesture not in progress
guard let _ = initialTouchLocationInScreenFixedCoordinateSpace else { return }
let inView = view ?? window
let currentLocation = location(in: inView)
let initialLocation = CGPoint(x: currentLocation.x - translation.x, y: currentLocation.y - translation.y)
initialTouchLocationsInViews[inView] = initialLocation
}
override var state: UIGestureRecognizer.State {
didSet {
switch state {
case .began:
initialTouchLocationInScreenFixedCoordinateSpace = location(in: nil)
case .ended, .cancelled, .failed:
initialTouchLocationInScreenFixedCoordinateSpace = nil
initialTouchLocationsInViews = [:]
case .possible, .changed:
break
}
}
}
}
| 3c9405e5baf4b815187b8731f1080272 | 40.948718 | 170 | 0.662286 | false | false | false | false |
nuclearace/SwiftDiscord | refs/heads/master | Sources/SwiftDiscord/Guild/DiscordWebhook.swift | mit | 1 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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
/// Represents a webhook.
public struct DiscordWebhook {
// MARK: Properties
/// The avatar of this webhook.
public let avatar: String?
/// The snowflake for the channel this webhook is for.
public let channelId: ChannelID
/// The snowflake for of the guild this webhook is for, if for a guild.
public let guildId: GuildID?
/// The id of this webhook.
public let id: WebhookID
/// The default name of this webhook.
public let name: String?
/// The secure token for this webhook.
public let token: String
/// The user this webhook was created by (not present when the webhook was gotten by its token).
public let user: DiscordUser?
init(webhookObject: [String: Any]) {
avatar = webhookObject["avatar"] as? String
channelId = webhookObject.getSnowflake(key: "channel_id")
guildId = Snowflake(webhookObject["guild_id"] as? String)
id = webhookObject.getSnowflake()
name = webhookObject["name"] as? String
token = webhookObject.get("token", or: "")
if let userObject = webhookObject["user"] as? [String: Any] {
user = DiscordUser(userObject: userObject)
} else {
user = nil
}
}
static func webhooksFromArray(_ webhookArray: [[String: Any]]) -> [DiscordWebhook] {
return webhookArray.map(DiscordWebhook.init)
}
}
| 5973fc04dd6f0a21169abab43db49b7b | 39.222222 | 119 | 0.701657 | false | false | false | false |
watson-developer-cloud/speech-ios-sdk | refs/heads/master | watsonsdktest-swift/SwiftTTSViewController.swift | apache-2.0 | 1 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class SwiftTTSViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIGestureRecognizerDelegate {
var ttsVoices: NSArray?
var ttsInstance: TextToSpeech?
@IBOutlet var voiceSelectorButton: UIButton!
@IBOutlet weak var pickerViewContainer: UIView!
@IBOutlet var ttsField: UITextView!
var pickerView: UIPickerView!
let pickerViewHeight:CGFloat = 250.0
let pickerViewAnimationDuration: NSTimeInterval = 0.5
let pickerViewAnimationDelay: NSTimeInterval = 0.1
let pickerViewPositionOffset: CGFloat = 33.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let credentialFilePath = NSBundle.mainBundle().pathForResource("Credentials", ofType: "plist")
let credentials = NSDictionary(contentsOfFile: credentialFilePath!)
let confTTS: TTSConfiguration = TTSConfiguration()
confTTS.basicAuthUsername = credentials?["TTSUsername"] as! String
confTTS.basicAuthPassword = credentials?["TTSPassword"] as! String
confTTS.audioCodec = WATSONSDK_TTS_AUDIO_CODEC_TYPE_OPUS
confTTS.voiceName = WATSONSDK_DEFAULT_TTS_VOICE
confTTS.xWatsonLearningOptOut = false // Change to true to opt-out
self.ttsInstance = TextToSpeech(config: confTTS)
self.ttsInstance?.listVoices({ (jsonDict, error) -> Void in
if error == nil{
self.voiceHandler(jsonDict)
}
else{
self.ttsField.text = error.description
}
})
}
// dismiss keyboard when the background is touched
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.ttsField.endEditing(true)
}
// start recording
@IBAction func onStartSynthesizing(sender: AnyObject) {
self.ttsInstance?.synthesize({ (data: NSData!, reqError: NSError!) -> Void in
if reqError == nil {
self.ttsInstance?.playAudio({ (error: NSError!) -> Void in
if error == nil{
print("Audio finished playing")
}
else{
print("Error playing audio %@", error.localizedDescription)
}
}, withData: data)
}
else{
print("Error requesting data: %@", reqError.description)
}
}, theText: self.ttsField.text)
}
// show picker view when the button is clicked
@IBAction func onSelectingModel(sender: AnyObject) {
self.hidePickerView(false, withAnimation: true)
}
// hide picker view
func onHidingPickerView(){
self.hidePickerView(true, withAnimation: true)
}
// set voice name when the picker view data is changed
func onSelectedModel(row: Int){
guard let voices = self.ttsVoices else{
return
}
let voice = voices.objectAtIndex(row) as! NSDictionary
let voiceName:String = voice.objectForKey("name") as! String
let voiceGender:String = voice.objectForKey("gender") as! String
self.voiceSelectorButton.setTitle(String(format: "%@: %@", voiceGender, voiceName), forState: .Normal)
self.ttsInstance?.config.voiceName = voiceName
}
// setup picker view after the response is back
func voiceHandler(dict: NSDictionary){
self.ttsVoices = dict.objectForKey("voices") as? NSArray
self.getUIPickerViewInstance().backgroundColor = UIColor.whiteColor()
self.hidePickerView(true, withAnimation: false)
let gestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SwiftTTSViewController.pickerViewTapGestureRecognized))
gestureRecognizer.delegate = self
self.getUIPickerViewInstance().addGestureRecognizer(gestureRecognizer);
self.view.addSubview(self.getUIPickerViewInstance())
var row = 0
if let list = self.ttsVoices{
for i in 0 ..< list.count{
if list.objectAtIndex(i).objectForKey("name") as? String == self.ttsInstance?.config.voiceName{
row = i
}
}
}
else{
row = (self.ttsVoices?.count)! - 1
}
self.getUIPickerViewInstance().selectRow(row, inComponent: 0, animated: false)
self.onSelectedModel(row)
}
// get picker view initialized
func getUIPickerViewInstance() -> UIPickerView{
guard let _ = self.pickerView else{
let pickerViewframe = CGRectMake(0, UIScreen.mainScreen().bounds.height - self.pickerViewHeight + self.pickerViewPositionOffset, UIScreen.mainScreen().bounds.width, self.pickerViewHeight)
self.pickerView = UIPickerView(frame: pickerViewframe)
self.pickerView.dataSource = self
self.pickerView.delegate = self
self.pickerView.opaque = true
self.pickerView.showsSelectionIndicator = true
self.pickerView.userInteractionEnabled = true
return self.pickerView
}
return self.pickerView
}
// display/show picker view with animations
func hidePickerView(hide: Bool, withAnimation: Bool){
if withAnimation{
UIView.animateWithDuration(self.pickerViewAnimationDuration, delay: self.pickerViewAnimationDelay, options: .CurveEaseInOut, animations: { () -> Void in
var frame = self.getUIPickerViewInstance().frame
if hide{
frame.origin.y = (UIScreen.mainScreen().bounds.height)
}
else{
self.getUIPickerViewInstance().hidden = hide
frame.origin.y = UIScreen.mainScreen().bounds.height - self.pickerViewHeight + self.pickerViewPositionOffset
}
self.getUIPickerViewInstance().frame = frame
}) { (Bool) -> Void in
self.getUIPickerViewInstance().hidden = hide
}
}
else{
self.getUIPickerViewInstance().hidden = hide
}
}
func pickerViewTapGestureRecognized(sender: UIGestureRecognizer){
self.onSelectedModel(self.getUIPickerViewInstance().selectedRowInComponent(0))
}
// UIGestureRecognizerDelegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// UIGestureRecognizerDelegate
// UIPickerView delegate methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
guard let voices = self.ttsVoices else {
return 0
}
return voices.count
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 50
}
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return self.pickerViewHeight
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
var tView: UILabel? = view as? UILabel
if tView == nil {
tView = UILabel()
tView?.font = UIFont(name: "Helvetica", size: 12)
tView?.numberOfLines = 1
}
let model = self.ttsVoices?.objectAtIndex(row) as? NSDictionary
tView?.text = String(format: "%@: %@", (model?.objectForKey("gender") as? String)!, (model?.objectForKey("name") as? String)!)
return tView!
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.onSelectedModel(row)
self.hidePickerView(true, withAnimation: true)
}
// UIPickerView delegate methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 2337945fd8335cf359cc48a807e0876d | 40.24186 | 199 | 0.647344 | false | false | false | false |
nua-schroers/mvvm-frp | refs/heads/master | 10_Commandline-App/Matchgame/Matchgame/View/MatchGameUI.swift | mit | 1 | //
// PlayerMove.swift
// Matchgame
//
// Created by Dr. Wolfram Schroers on 5/9/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import Foundation
/// The text-based main UI of the app.
class MatchGameUI {
/// Print the welcome message at the beginning of the game.
class func welcome() {
print("Welcome to the match game\n")
print("The player removing the last match loses the game")
}
/// Query configuration parameters.
///
/// - returns: A tuple of the desired starting number of matches, the maximum number of matches to remove and the desired strategy (1: Dumb, 2: Wild, 3: Smart). Invalid values are returned as 0.
class func queryConfiguration() -> (Int, Int, Int) {
print("Starting number of matches: ", terminator:"")
let initialCount = queryIntNumber()
print("Maximum number of matches to remove: ", terminator:"")
let removeMax = queryIntNumber()
print("Strategy to use (1: Dumb, 2: Wild, 3: Smart): ", terminator:"")
let strategy = queryIntNumber()
return (initialCount, removeMax, strategy)
}
/// Display the current game state.
///
/// - Parameter count: The current number of matches.
class func showState(_ count: Int) {
print("There are \(count) matches")
}
/// Query a single user move. The user is queried for input until a valid move is entered.
///
/// - returns: The player move.
/// - Parameter limit: The maximum number of matches the player may remove.
class func userMove(_ limit:Int) -> Int {
var userMove = 0
var isMoveValid = false
repeat {
// Query the user move.
print("Please enter your move (1..\(limit))", terminator:"")
userMove = queryIntNumber()
if (userMove >= 1) && (userMove <= limit) {
// The move is valid, return it.
isMoveValid = true
} else {
// The move is invalid, inform the user.
print("This is not a valid move!")
}
} while !isMoveValid
return userMove
}
/// Show the number of matches the Mac has taken.
///
/// - Parameter move: The computer's move.
class func showComputerMove(_ move:Int) {
print("I have taken \(move) matches")
}
/// Print the final message at the end of a run.
class func byebye() {
print("I hope to see you soon again")
}
// MARK: Private implementation
/// Query user for an integer number.
///
/// - returns: The number the user has entered or 0 for an invalid input.
fileprivate class func queryIntNumber() -> Int {
// Query user input (may return arbitrary data), convert input to a string.
let userEntry = FileHandle.standardInput.availableData
let userString = String(data: userEntry,
encoding: String.Encoding.utf8) ?? "0"
// Attempt to convert to a number.
let userNumber = Int(userString.trimmingCharacters(in: .newlines)) ?? 0
return userNumber;
}
}
| eebb71bbc2141f3cafa78b084f12f95c | 32.924731 | 198 | 0.601268 | false | false | false | false |
JuanjoArreola/Apic | refs/heads/master | Sources/URLRequest+ParameterEncoding.swift | mit | 1 | import Foundation
enum EncodeError: Error {
case invalidMethod
}
public extension URLRequest {
mutating func encode(parameters: [String: Any], with encoding: ParameterEncoding) throws {
guard let method = httpMethod else { throw EncodeError.invalidMethod }
switch encoding {
case .url:
if ["GET", "HEAD", "DELETE"].contains(method) {
self.url = try self.url?.appending(parameters: parameters)
} else if let queryString = parameters.urlQueryString {
setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
self.httpBody = queryString.data(using: .utf8, allowLossyConversion: false)
} else {
throw RepositoryError.encodingError
}
case .json:
self.setValue("application/json", forHTTPHeaderField: "Content-Type")
self.httpBody = try JSONSerialization.data(withJSONObject: parameters.jsonValid, options: [])
}
}
}
public extension Dictionary where Key: ExpressibleByStringLiteral {
var urlQueryString: String? {
let string = self.map({ "\($0)=\(String(describing: $1))" }).joined(separator: "&")
return string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}
var jsonValid: [Key: Any] {
var result = [Key: Any]()
self.forEach({ result[$0] = JSONSerialization.isValidJSONObject(["_": $1]) ? $1 : String(describing: $1) })
return result
}
}
public extension URL {
func appending(parameters: [String: Any]) throws -> URL {
guard let queryString = parameters.urlQueryString,
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)else {
throw RepositoryError.encodingError
}
let percentEncodedQuery = (components.percentEncodedQuery.map { $0 + "&" } ?? "") + queryString
components.percentEncodedQuery = percentEncodedQuery
if let url = components.url {
return url
}
throw RepositoryError.encodingError
}
}
| 8cf9c433c45b687cb241ca6d27b7409c | 37.618182 | 115 | 0.632768 | false | false | false | false |
ycaihua/codecombat-ios | refs/heads/master | CodeCombat/TomeInventoryItemPropertyView.swift | mit | 1 | //
// TomeInventoryItemPropertyView.swift
// CodeCombat
//
// Created by Nick Winter on 8/7/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import Foundation
class TomeInventoryItemPropertyView: UIButton {
var item: TomeInventoryItem!
var property: TomeInventoryItemProperty!
func baseInit(item: TomeInventoryItem, property: TomeInventoryItemProperty) {
self.item = item
self.property = property
buildSubviews()
addTarget(self, action: Selector("onTapped:"), forControlEvents: .TouchUpInside)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(item: TomeInventoryItem,
property: TomeInventoryItemProperty, coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
baseInit(item, property: property)
}
init(item: TomeInventoryItem,
property: TomeInventoryItemProperty, frame: CGRect) {
super.init(frame: frame)
baseInit(item, property: property)
}
func buildSubviews() {
let padding = CGFloat(5.0)
if let name = property?.propertyData["name"].asString {
var dotLabel = UILabel(
frame: CGRect(
x: padding,
y: padding,
width: 25,
height: frame.height))
dotLabel.font = UIFont(name: "Menlo", size: 12)
dotLabel.text = " ● "
dotLabel.textColor = UIColor(red: 117.0 / 255.0, green: 110.0 / 255.0, blue: 90.0 / 255.0, alpha: 1.0)
dotLabel.sizeToFit()
var label = UILabel(
frame: CGRect(
x: padding + dotLabel.frame.width,
y: padding,
width: frame.width - 2 * padding - dotLabel.frame.width,
height: frame.height))
label.font = dotLabel.font
label.text = name
label.textColor = UIColor(red: 26.0 / 255.0, green: 20.0 / 255.0, blue: 12.0 / 255.0, alpha: 1.0)
addSubview(dotLabel)
addSubview(label)
label.sizeToFit()
frame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width,
height: label.frame.height + 2 * padding)
backgroundColor = UIColor(red: 225.0 / 255.0, green: 219.0 / 255.0, blue: 198.0 / 255.0, alpha: 1.0)
}
}
func onTapped(sender: TomeInventoryItemView) {
var docView = TomeInventoryItemPropertyDocumentationView(item: item, property: property, frame: CGRect(x: 0, y: 0, width: 320, height: 480))
var docViewController = UIViewController()
docViewController.view = docView
var popover = UIPopoverController(contentViewController: docViewController)
popover.presentPopoverFromRect(frame, inView: superview!.superview!, permittedArrowDirections: .Down | .Up, animated: true)
println("tapped \(self.item.name) \(self.property.name)")
}
}
| 11d5d73b893ae549f367252a93120eb7 | 32.82716 | 144 | 0.657299 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI | refs/heads/master | TestProject-GitHubAPI/TestProject-GitHubAPI/User.swift | mit | 1 | //
// User.swift
// TestProject-GitHubAPI
//
// Created by Yura Chukhlib on 05.07.16.
// Copyright © 2016 Yuri Chukhlib. All rights reserved.
//
import UIKit
import RealmSwift
class User: Object {
dynamic var id = ""
dynamic var userAvatarImageView = ""
dynamic var userBioLabel = ""
dynamic var followersCountLabel = 0
dynamic var followingCountLabel = 0
dynamic var publicGistsLabel = 0
dynamic var publicReposLabel = 0
var repositories = List<Project>()
override static func primaryKey() -> String? {
return "id"
}
}
| 0ed176e78ab083def0f9a7eb8b354b87 | 21.307692 | 56 | 0.667241 | false | false | false | false |
xu6148152/binea_project_for_ios | refs/heads/master | Dropit/Dropit/DropitBehavior.swift | mit | 1 | //
// DropitBehavior.swift
// Dropit
//
// Created by Binea Xu on 6/27/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import UIKit
class DropitBehavior: UIDynamicBehavior {
let gravity = UIGravityBehavior()
lazy var collider : UICollisionBehavior = {
let lazilyCreatedCollider = UICollisionBehavior()
lazilyCreatedCollider.translatesReferenceBoundsIntoBoundary = true
return lazilyCreatedCollider
}()
lazy var dropBehavior : UIDynamicItemBehavior = {
let lazilyCreatedDropBehavior = UIDynamicItemBehavior()
lazilyCreatedDropBehavior.allowsRotation = false
lazilyCreatedDropBehavior.elasticity = 0.75
return lazilyCreatedDropBehavior
}()
override init(){
super.init()
addChildBehavior(gravity)
addChildBehavior(collider)
addChildBehavior(dropBehavior)
}
func addDrop(view : UIView){
dynamicAnimator?.referenceView?.addSubview(view)
gravity.addItem(view)
collider.addItem(view)
dropBehavior.addItem(view)
}
func removeDrop(view : UIView){
gravity.removeItem(view)
collider.removeItem(view)
dropBehavior.removeItem(view)
}
func addBarrier(path: UIBezierPath, named name: String){
collider.removeBoundaryWithIdentifier(name)
collider.addBoundaryWithIdentifier(name, forPath: path)
}
}
| b2ba63cfdb754a8e42341ed65dfbd3f2 | 26.037037 | 74 | 0.666438 | false | false | false | false |
tianbinbin/DouYuShow | refs/heads/master | DouYuShow/DouYuShow/Classes/Main/ViewModel/BaseViewModel.swift | mit | 1 | //
// BaseViewModel.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/16.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class BaseViewModel {
// 共同的信息
lazy var anchorGroups:[AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel{
// 这里 [String:Any]? 是一个可选类型可传可不传 [String:Any]? = nil 直接给一个默认值为nil
// @escaping 当前闭包可能在其他地方使用到 作为逃逸的
// post 请求
func loadAnchorData(urlStr:String,parameters:[String:Any]? = nil,finishedCallBack:@escaping()->()){
NetWorkTools.RequestData(type: .GET, URLString: urlStr, parameters: parameters, SuccessCallBack: { (reslust) in
// 1.对结果进行处理
guard let reslutDict = reslust as? [String:Any] else{return}
guard let dataArr = reslutDict["data"] as? [[String:Any]] else {return}
// 2. 便利数组 将字典转换成模型
for dict in dataArr {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
// 3. 完成回调
finishedCallBack()
}) { (flaseresult) in
}
}
}
| 1be8b95105e24ba268505e72cf552f38 | 23.652174 | 119 | 0.557319 | false | false | false | false |
CosmicMind/Samples | refs/heads/development | Projects/Programmatic/TransitionsWithIdentifier/TransitionsWithIdentifier/PurpleViewController.swift | bsd-3-clause | 1 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import Motion
class PurpleViewController: UIViewController {
fileprivate var v1 = View()
fileprivate var v2 = View()
open override func viewDidLoad() {
super.viewDidLoad()
prepareView()
prepareTransitionViews()
prepareAnimation()
Motion.delay(2) { [weak self] in
self?.dismiss(animated: true)
}
}
}
extension PurpleViewController {
fileprivate func prepareView() {
isMotionEnabled = true
view.backgroundColor = .white
}
fileprivate func prepareTransitionViews() {
v1.backgroundColor = Color.deepOrange.base
v2.backgroundColor = Color.blueGrey.lighten3
}
fileprivate func prepareAnimation() {
animationMatch()
// animationScale()
// animationTranslate()
// animationRotate()
// animationArc()
}
}
extension PurpleViewController {
fileprivate func animationMatch() {
v1.motionIdentifier = "v1"
view.layout(v1).top().left().right().height(200)
v2.motionIdentifier = "v2"
view.layout(v2).bottom().left().right().height(70)
}
fileprivate func animationScale() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.scale(0.3), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationTranslate() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.translate(x: -200), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationRotate() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.translate(x: -200, y: 100), .rotate(270), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationArc() {
v2.motionIdentifier = "v2"
v2.shapePreset = .circle
v2.transition(.arc())
view.layout(v2).center(offsetX: -100, offsetY: -100).width(100).height(100)
}
}
| 1308e576fbb3366648d7c4ca7213d5ce | 32.810345 | 88 | 0.707292 | false | false | false | false |
kayoslab/CaffeineStatsview | refs/heads/master | CaffeineStatsview/CaffeineStatsview/View/StatsView.swift | mit | 1 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 cr0ss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import UIKit
class StatsView: UIView {
internal var objects:Array<Double>?
private var intersectDistance:Int = 2
private var catmullAlpha:CGFloat = 0.3
private var useCatmullRom:Bool = true
// MARK: - Constants
private let margin:CGFloat = 20.0
private let topBorder:CGFloat = 10
private let bottomBorder:CGFloat = 40
private let graphBorder:CGFloat = 30
private let statsColor:UIColor = .redColor()
// MARK: - Init
override init (frame : CGRect) {
super.init(frame : frame)
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
if var objects = self.objects {
let graphHeight = rect.height - self.topBorder - self.bottomBorder - self.graphBorder
let spacer = (rect.width - self.margin * 2) / CGFloat((objects.count-1))
// Is there any maxValue?
let maxValue:Int = Int(objects.maxElement() != nil ? objects.maxElement()! : 0.0)
let columnXPoint = { (column:Int) -> CGFloat in
var x:CGFloat = CGFloat(column) * spacer
x += self.margin
return x
}
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
// Flip the graph
y = graphHeight + self.topBorder + self.graphBorder - y
return y
}
let intersectHeight = (bounds.height - bottomBorder - topBorder)
let numberOfIntersections = Int(ceil(Double(objects.count) / Double(intersectDistance)))
for index in 0 ..< numberOfIntersections {
let intersectPath = UIBezierPath()
let intersectStartPoint = CGPoint(x: columnXPoint(index * self.intersectDistance), y: bounds.height-bottomBorder)
let intersectEndPoint = CGPoint(x: intersectStartPoint.x, y: intersectStartPoint.y - intersectHeight)
intersectPath.moveToPoint(intersectStartPoint)
intersectPath.addLineToPoint(intersectEndPoint)
UIColor.clearColor().setStroke()
intersectPath.lineWidth = 1.0
intersectPath.stroke()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [UIColor.lightGrayColor().CGColor, UIColor.lightGrayColor().CGColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 0.95]
//5 - create the gradient
let gradient = CGGradientCreateWithColors(colorSpace, colors, colorLocations)
//save the state of the context
CGContextSaveGState(context)
CGContextSetLineWidth(context, intersectPath.lineWidth)
CGContextAddPath(context, intersectPath.CGPath)
CGContextReplacePathWithStrokedPath(context)
CGContextClip(context)
CGContextDrawLinearGradient(context, gradient, intersectStartPoint, intersectEndPoint, .DrawsAfterEndLocation)
CGContextRestoreGState(context)
}
// Graph Color
self.statsColor.setFill()
self.statsColor.setStroke()
let graphPath = UIBezierPath()
var notZero:Bool = false
for object in objects {
if (object != 0.0) {
notZero = true
}
}
if(notZero) {
if (self.useCatmullRom == false || objects.count < 4) {
// Draw Graph without Catmull Rom
graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:columnYPoint(Int(objects[0]))))
for i in 1..<objects.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
graphPath.addLineToPoint(nextPoint)
}
} else {
// Implementation of Catmull Rom
let startIndex = 1
let endIndex = objects.count - 2
for i in startIndex ..< endIndex {
let p0 = CGPoint(x:columnXPoint(i-1 < 0 ? objects.count - 1 : i - 1), y:columnYPoint(Int(objects[i-1 < 0 ? objects.count - 1 : i - 1])))
let p1 = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
let p2 = CGPoint(x:columnXPoint((i+1) % objects.count), y:columnYPoint(Int(objects[(i+1)%objects.count])))
let p3 = CGPoint(x:columnXPoint((i+1) % objects.count + 1), y:columnYPoint(Int(objects[(i+1)%objects.count + 1])))
let d1 = p1.deltaTo(p0).length()
let d2 = p2.deltaTo(p1).length()
let d3 = p3.deltaTo(p2).length()
var b1 = p2.multiplyBy(pow(d1, 2 * self.catmullAlpha))
b1 = b1.deltaTo(p0.multiplyBy(pow(d2, 2 * self.catmullAlpha)))
b1 = b1.addTo(p1.multiplyBy(2 * pow(d1, 2 * self.catmullAlpha) + 3 * pow(d1, self.catmullAlpha) * pow(d2, self.catmullAlpha) + pow(d2, 2 * self.catmullAlpha)))
b1 = b1.multiplyBy(1.0 / (3 * pow(d1, self.catmullAlpha) * (pow(d1, self.catmullAlpha) + pow(d2, self.catmullAlpha))))
var b2 = p1.multiplyBy(pow(d3, 2 * self.catmullAlpha))
b2 = b2.deltaTo(p3.multiplyBy(pow(d2, 2 * self.catmullAlpha)))
b2 = b2.addTo(p2.multiplyBy(2 * pow(d3, 2 * self.catmullAlpha) + 3 * pow(d3, self.catmullAlpha) * pow(d2, self.catmullAlpha) + pow(d2, 2 * self.catmullAlpha)))
b2 = b2.multiplyBy(1.0 / (3 * pow(d3, self.catmullAlpha) * (pow(d3, self.catmullAlpha) + pow(d2, self.catmullAlpha))))
if i == startIndex {
graphPath.moveToPoint(p0)
}
graphPath.addCurveToPoint(p2, controlPoint1: b1, controlPoint2: b2)
}
let nextPoint = CGPoint(x:columnXPoint(objects.count - 1), y:columnYPoint(Int(objects[objects.count - 1])))
graphPath.addLineToPoint(nextPoint)
}
} else {
// Draw a Line, when there are no Objects in the Array
let zero = graphHeight + topBorder + graphBorder
graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:zero))
for i in 1..<objects.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:zero)
graphPath.addLineToPoint(nextPoint)
}
}
graphPath.lineWidth = 2.0
graphPath.stroke()
for i in 0..<objects.count {
if (i % self.intersectDistance == 0) {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
}
}
}
internal func setUpGraphView(statisticsItems:Array<Double>, intersectDistance:Int, catmullRom:Bool, catmullAlpha:CGFloat = 0.30) {
if statisticsItems.count <= 1 {
self.objects = [0.0, 0.0]
self.intersectDistance = 1
} else if intersectDistance == 0 {
self.intersectDistance = 1
self.intersectDistance += statisticsItems.count % 2
self.objects = statisticsItems
} else {
self.intersectDistance = intersectDistance
self.objects = statisticsItems
}
self.useCatmullRom = catmullRom
self.catmullAlpha = catmullAlpha
self.setNeedsDisplay()
}
}
// MARK: - CGPoint Extension
extension CGPoint{
func addTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x + a.x, self.y + a.y)
}
func deltaTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x - a.x, self.y - a.y)
}
func length() -> CGFloat {
return CGFloat(sqrt(CDouble(self.x*self.x + self.y*self.y)))
}
func multiplyBy(value:CGFloat) -> CGPoint{
return CGPointMake(self.x * value, self.y * value)
}
} | c05902d96a32d7f29113250cd8cee294 | 44.086364 | 183 | 0.575116 | false | false | false | false |
wess/overlook | refs/heads/master | Sources/overlook/commands/help.swift | mit | 1 | //
// help.swift
// overlook
//
// Created by Wesley Cope on 9/30/16.
//
//
import Foundation
import SwiftCLI
import Rainbow
public class HelpCommand : SwiftCLI.HelpCommand, Command {
public let name = "help"
public let signature = "[<opt>] ..."
public let shortDescription = "Prints help information"
public var printCLIDescription: Bool = true
public var allCommands: [Command] = []
public var availableCommands:[Command] = []
public func setupOptions(options: OptionRegistry) {}
public func execute(arguments: CommandArguments) throws {
print("Usage: overlook [OPTIONS]\n")
print("Available commands: ")
for command in allCommands {
var name = command.name
if !command.signature.isEmpty && !(command is HelpCommand) {
name += " \(command.signature)"
}
printLine(name: name, description: command.shortDescription)
}
}
private func printLine(name: String, description: String) {
let spacing = String(repeating: " ", count: 20 - name.characters.count)
print(" " + Overlook.name.lowercased() + " " + name.bold + "\(spacing)\(description)")
}
}
| 1c72df1e2a359df6b74640563e3e5ad2 | 24.510638 | 90 | 0.634696 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.